14ba67500SRoman Divacky //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
24ba67500SRoman Divacky //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64ba67500SRoman Divacky //
74ba67500SRoman Divacky //===----------------------------------------------------------------------===//
84ba67500SRoman Divacky
97442d6faSDimitry Andric #include "clang/CodeGen/CodeGenAction.h"
10b1c73532SDimitry Andric #include "BackendConsumer.h"
117fa27ce4SDimitry Andric #include "CGCall.h"
127442d6faSDimitry Andric #include "CodeGenModule.h"
1306d4ba38SDimitry Andric #include "CoverageMappingGen.h"
147442d6faSDimitry Andric #include "MacroPPCallbacks.h"
154ba67500SRoman Divacky #include "clang/AST/ASTConsumer.h"
164ba67500SRoman Divacky #include "clang/AST/ASTContext.h"
179f4dbff6SDimitry Andric #include "clang/AST/DeclCXX.h"
1806d4ba38SDimitry Andric #include "clang/AST/DeclGroup.h"
19519fc96cSDimitry Andric #include "clang/Basic/DiagnosticFrontend.h"
20809500fcSDimitry Andric #include "clang/Basic/FileManager.h"
21519fc96cSDimitry Andric #include "clang/Basic/LangStandard.h"
22809500fcSDimitry Andric #include "clang/Basic/SourceManager.h"
23809500fcSDimitry Andric #include "clang/Basic/TargetInfo.h"
244ba67500SRoman Divacky #include "clang/CodeGen/BackendUtil.h"
254ba67500SRoman Divacky #include "clang/CodeGen/ModuleBuilder.h"
2622989816SDimitry Andric #include "clang/Driver/DriverDiagnostic.h"
274ba67500SRoman Divacky #include "clang/Frontend/CompilerInstance.h"
28ac9a064cSDimitry Andric #include "clang/Frontend/FrontendActions.h"
294ba67500SRoman Divacky #include "clang/Frontend/FrontendDiagnostic.h"
30ac9a064cSDimitry Andric #include "clang/Frontend/MultiplexConsumer.h"
3106d4ba38SDimitry Andric #include "clang/Lex/Preprocessor.h"
32ac9a064cSDimitry Andric #include "clang/Serialization/ASTWriter.h"
33c0981da4SDimitry Andric #include "llvm/ADT/Hashing.h"
34bab175ecSDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
357442d6faSDimitry Andric #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
36c0981da4SDimitry Andric #include "llvm/Demangle/Demangle.h"
379f4dbff6SDimitry Andric #include "llvm/IR/DebugInfo.h"
389f4dbff6SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
399f4dbff6SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
407442d6faSDimitry Andric #include "llvm/IR/GlobalValue.h"
41809500fcSDimitry Andric #include "llvm/IR/LLVMContext.h"
42cfca06d7SDimitry Andric #include "llvm/IR/LLVMRemarkStreamer.h"
43809500fcSDimitry Andric #include "llvm/IR/Module.h"
44809500fcSDimitry Andric #include "llvm/IRReader/IRReader.h"
45b60736ecSDimitry Andric #include "llvm/LTO/LTOBackend.h"
469f4dbff6SDimitry Andric #include "llvm/Linker/Linker.h"
47809500fcSDimitry Andric #include "llvm/Pass.h"
484ba67500SRoman Divacky #include "llvm/Support/MemoryBuffer.h"
494ba67500SRoman Divacky #include "llvm/Support/SourceMgr.h"
50519fc96cSDimitry Andric #include "llvm/Support/TimeProfiler.h"
514ba67500SRoman Divacky #include "llvm/Support/Timer.h"
52bab175ecSDimitry Andric #include "llvm/Support/ToolOutputFile.h"
53bab175ecSDimitry Andric #include "llvm/Support/YAMLTraits.h"
547442d6faSDimitry Andric #include "llvm/Transforms/IPO/Internalize.h"
55b1c73532SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
567442d6faSDimitry Andric
57e3b55780SDimitry Andric #include <optional>
584ba67500SRoman Divacky using namespace clang;
594ba67500SRoman Divacky using namespace llvm;
604ba67500SRoman Divacky
61c0981da4SDimitry Andric #define DEBUG_TYPE "codegenaction"
62c0981da4SDimitry Andric
63bca07a45SDimitry Andric namespace clang {
64461a67faSDimitry Andric class BackendConsumer;
65461a67faSDimitry Andric class ClangDiagnosticHandler final : public DiagnosticHandler {
66461a67faSDimitry Andric public:
ClangDiagnosticHandler(const CodeGenOptions & CGOpts,BackendConsumer * BCon)67461a67faSDimitry Andric ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
68461a67faSDimitry Andric : CodeGenOpts(CGOpts), BackendCon(BCon) {}
69461a67faSDimitry Andric
70461a67faSDimitry Andric bool handleDiagnostics(const DiagnosticInfo &DI) override;
71461a67faSDimitry Andric
isAnalysisRemarkEnabled(StringRef PassName) const72461a67faSDimitry Andric bool isAnalysisRemarkEnabled(StringRef PassName) const override {
73344a3780SDimitry Andric return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
74461a67faSDimitry Andric }
isMissedOptRemarkEnabled(StringRef PassName) const75461a67faSDimitry Andric bool isMissedOptRemarkEnabled(StringRef PassName) const override {
76344a3780SDimitry Andric return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
77461a67faSDimitry Andric }
isPassedOptRemarkEnabled(StringRef PassName) const78461a67faSDimitry Andric bool isPassedOptRemarkEnabled(StringRef PassName) const override {
79344a3780SDimitry Andric return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
80461a67faSDimitry Andric }
81461a67faSDimitry Andric
isAnyRemarkEnabled() const82461a67faSDimitry Andric bool isAnyRemarkEnabled() const override {
83344a3780SDimitry Andric return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
84344a3780SDimitry Andric CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
85344a3780SDimitry Andric CodeGenOpts.OptimizationRemark.hasValidPattern();
86461a67faSDimitry Andric }
87461a67faSDimitry Andric
88461a67faSDimitry Andric private:
89461a67faSDimitry Andric const CodeGenOptions &CodeGenOpts;
90461a67faSDimitry Andric BackendConsumer *BackendCon;
91461a67faSDimitry Andric };
92461a67faSDimitry Andric
reportOptRecordError(Error E,DiagnosticsEngine & Diags,const CodeGenOptions & CodeGenOpts)93706b4fc4SDimitry Andric static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
947fa27ce4SDimitry Andric const CodeGenOptions &CodeGenOpts) {
95706b4fc4SDimitry Andric handleAllErrors(
96706b4fc4SDimitry Andric std::move(E),
97cfca06d7SDimitry Andric [&](const LLVMRemarkSetupFileError &E) {
98706b4fc4SDimitry Andric Diags.Report(diag::err_cannot_open_file)
99706b4fc4SDimitry Andric << CodeGenOpts.OptRecordFile << E.message();
100706b4fc4SDimitry Andric },
101cfca06d7SDimitry Andric [&](const LLVMRemarkSetupPatternError &E) {
102706b4fc4SDimitry Andric Diags.Report(diag::err_drv_optimization_remark_pattern)
103706b4fc4SDimitry Andric << E.message() << CodeGenOpts.OptRecordPasses;
104706b4fc4SDimitry Andric },
105cfca06d7SDimitry Andric [&](const LLVMRemarkSetupFormatError &E) {
106706b4fc4SDimitry Andric Diags.Report(diag::err_drv_optimization_remark_format)
107706b4fc4SDimitry Andric << CodeGenOpts.OptRecordFormat;
108706b4fc4SDimitry Andric });
109706b4fc4SDimitry Andric }
110706b4fc4SDimitry Andric
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)111ac9a064cSDimitry Andric BackendConsumer::BackendConsumer(
112ac9a064cSDimitry Andric BackendAction Action, DiagnosticsEngine &Diags,
1137fa27ce4SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
114c192b3dcSDimitry Andric const HeaderSearchOptions &HeaderSearchOpts,
115ac9a064cSDimitry Andric const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
116ac9a064cSDimitry Andric const TargetOptions &TargetOpts, const LangOptions &LangOpts,
117ac9a064cSDimitry Andric const std::string &InFile, SmallVector<LinkModule, 4> LinkModules,
118ac9a064cSDimitry Andric std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
119b1c73532SDimitry Andric CoverageSourceInfo *CoverageInfo)
1206694ed09SDimitry Andric : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
1216694ed09SDimitry Andric CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
1227fa27ce4SDimitry Andric AsmOutStream(std::move(OS)), Context(nullptr), FS(VFS),
123bab175ecSDimitry Andric LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
124bab175ecSDimitry Andric LLVMIRGenerationRefCount(0),
1257fa27ce4SDimitry Andric Gen(CreateLLVMCodeGen(Diags, InFile, std::move(VFS), HeaderSearchOpts,
12608e8dd7bSDimitry Andric PPOpts, CodeGenOpts, C, CoverageInfo)),
1277442d6faSDimitry Andric LinkModules(std::move(LinkModules)) {
128b60736ecSDimitry Andric TimerIsEnabled = CodeGenOpts.TimePasses;
129b60736ecSDimitry Andric llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
130b60736ecSDimitry Andric llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
1314ba67500SRoman Divacky }
132706b4fc4SDimitry Andric
133706b4fc4SDimitry Andric // This constructor is used in installing an empty BackendConsumer
134706b4fc4SDimitry Andric // to use the clang diagnostic handler for IR input files. It avoids
135706b4fc4SDimitry Andric // initializing the OS field.
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)136ac9a064cSDimitry Andric BackendConsumer::BackendConsumer(
137ac9a064cSDimitry Andric BackendAction Action, DiagnosticsEngine &Diags,
1387fa27ce4SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
139706b4fc4SDimitry Andric const HeaderSearchOptions &HeaderSearchOpts,
140ac9a064cSDimitry Andric const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
141ac9a064cSDimitry Andric const TargetOptions &TargetOpts, const LangOptions &LangOpts,
142ac9a064cSDimitry Andric llvm::Module *Module, SmallVector<LinkModule, 4> LinkModules,
143ac9a064cSDimitry Andric LLVMContext &C, CoverageSourceInfo *CoverageInfo)
144706b4fc4SDimitry Andric : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
145706b4fc4SDimitry Andric CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
1467fa27ce4SDimitry Andric Context(nullptr), FS(VFS),
147706b4fc4SDimitry Andric LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
148706b4fc4SDimitry Andric LLVMIRGenerationRefCount(0),
149ac9a064cSDimitry Andric Gen(CreateLLVMCodeGen(Diags, "", std::move(VFS), HeaderSearchOpts, PPOpts,
150ac9a064cSDimitry Andric CodeGenOpts, C, CoverageInfo)),
151c0981da4SDimitry Andric LinkModules(std::move(LinkModules)), CurLinkModule(Module) {
152b60736ecSDimitry Andric TimerIsEnabled = CodeGenOpts.TimePasses;
153b60736ecSDimitry Andric llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
154b60736ecSDimitry Andric llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
155706b4fc4SDimitry Andric }
156b1c73532SDimitry Andric
getModule() const157b1c73532SDimitry Andric llvm::Module* BackendConsumer::getModule() const {
158b1c73532SDimitry Andric return Gen->GetModule();
159b1c73532SDimitry Andric }
160b1c73532SDimitry Andric
takeModule()161b1c73532SDimitry Andric std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
1622b6b257fSDimitry Andric return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
1632b6b257fSDimitry Andric }
1647442d6faSDimitry Andric
getCodeGenerator()165b1c73532SDimitry Andric CodeGenerator* BackendConsumer::getCodeGenerator() {
166b1c73532SDimitry Andric return Gen.get();
167b1c73532SDimitry Andric }
168dbe13110SDimitry Andric
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)169b1c73532SDimitry Andric void BackendConsumer::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
170dbe13110SDimitry Andric Gen->HandleCXXStaticMemberVarInstantiation(VD);
171dbe13110SDimitry Andric }
1724ba67500SRoman Divacky
Initialize(ASTContext & Ctx)173b1c73532SDimitry Andric void BackendConsumer::Initialize(ASTContext &Ctx) {
17445b53394SDimitry Andric assert(!Context && "initialized multiple times");
1755e20cdd8SDimitry Andric
1764ba67500SRoman Divacky Context = &Ctx;
1774ba67500SRoman Divacky
178b60736ecSDimitry Andric if (TimerIsEnabled)
1794ba67500SRoman Divacky LLVMIRGeneration.startTimer();
1804ba67500SRoman Divacky
1814ba67500SRoman Divacky Gen->Initialize(Ctx);
1824ba67500SRoman Divacky
183b60736ecSDimitry Andric if (TimerIsEnabled)
1844ba67500SRoman Divacky LLVMIRGeneration.stopTimer();
1854ba67500SRoman Divacky }
1864ba67500SRoman Divacky
HandleTopLevelDecl(DeclGroupRef D)187b1c73532SDimitry Andric bool BackendConsumer::HandleTopLevelDecl(DeclGroupRef D) {
1884ba67500SRoman Divacky PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
1894ba67500SRoman Divacky Context->getSourceManager(),
1904ba67500SRoman Divacky "LLVM IR generation of declaration");
1914ba67500SRoman Divacky
192bab175ecSDimitry Andric // Recurse.
193b60736ecSDimitry Andric if (TimerIsEnabled) {
194bab175ecSDimitry Andric LLVMIRGenerationRefCount += 1;
195bab175ecSDimitry Andric if (LLVMIRGenerationRefCount == 1)
1964ba67500SRoman Divacky LLVMIRGeneration.startTimer();
197bab175ecSDimitry Andric }
1984ba67500SRoman Divacky
1994ba67500SRoman Divacky Gen->HandleTopLevelDecl(D);
2004ba67500SRoman Divacky
201b60736ecSDimitry Andric if (TimerIsEnabled) {
202bab175ecSDimitry Andric LLVMIRGenerationRefCount -= 1;
203bab175ecSDimitry Andric if (LLVMIRGenerationRefCount == 0)
2044ba67500SRoman Divacky LLVMIRGeneration.stopTimer();
205bab175ecSDimitry Andric }
206dbe13110SDimitry Andric
207dbe13110SDimitry Andric return true;
2084ba67500SRoman Divacky }
2094ba67500SRoman Divacky
HandleInlineFunctionDefinition(FunctionDecl * D)210b1c73532SDimitry Andric void BackendConsumer::HandleInlineFunctionDefinition(FunctionDecl *D) {
2119f4dbff6SDimitry Andric PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2129f4dbff6SDimitry Andric Context->getSourceManager(),
2132b6b257fSDimitry Andric "LLVM IR generation of inline function");
214b60736ecSDimitry Andric if (TimerIsEnabled)
2159f4dbff6SDimitry Andric LLVMIRGeneration.startTimer();
2169f4dbff6SDimitry Andric
2172b6b257fSDimitry Andric Gen->HandleInlineFunctionDefinition(D);
2189f4dbff6SDimitry Andric
219b60736ecSDimitry Andric if (TimerIsEnabled)
2209f4dbff6SDimitry Andric LLVMIRGeneration.stopTimer();
2219f4dbff6SDimitry Andric }
2229f4dbff6SDimitry Andric
HandleInterestingDecl(DeclGroupRef D)223b1c73532SDimitry Andric void BackendConsumer::HandleInterestingDecl(DeclGroupRef D) {
224bab175ecSDimitry Andric // Ignore interesting decls from the AST reader after IRGen is finished.
225bab175ecSDimitry Andric if (!IRGenFinished)
226bab175ecSDimitry Andric HandleTopLevelDecl(D);
227bab175ecSDimitry Andric }
228bab175ecSDimitry Andric
2297442d6faSDimitry Andric // Links each entry in LinkModules into our module. Returns true on error.
LinkInModules(llvm::Module * M)230ac9a064cSDimitry Andric bool BackendConsumer::LinkInModules(llvm::Module *M) {
2317442d6faSDimitry Andric for (auto &LM : LinkModules) {
2327fa27ce4SDimitry Andric assert(LM.Module && "LinkModule does not actually have a module");
233b1c73532SDimitry Andric
2347442d6faSDimitry Andric if (LM.PropagateAttrs)
235b60736ecSDimitry Andric for (Function &F : *LM.Module) {
236b60736ecSDimitry Andric // Skip intrinsics. Keep consistent with how intrinsics are created
237b60736ecSDimitry Andric // in LLVM IR.
238b60736ecSDimitry Andric if (F.isIntrinsic())
239b60736ecSDimitry Andric continue;
2407fa27ce4SDimitry Andric CodeGen::mergeDefaultFunctionDefinitionAttributes(
2417fa27ce4SDimitry Andric F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
242b60736ecSDimitry Andric }
2437442d6faSDimitry Andric
2447442d6faSDimitry Andric CurLinkModule = LM.Module.get();
2457442d6faSDimitry Andric bool Err;
246b1c73532SDimitry Andric
2477442d6faSDimitry Andric if (LM.Internalize) {
2487442d6faSDimitry Andric Err = Linker::linkModules(
249ac9a064cSDimitry Andric *M, std::move(LM.Module), LM.LinkFlags,
2507442d6faSDimitry Andric [](llvm::Module &M, const llvm::StringSet<> &GVS) {
2517442d6faSDimitry Andric internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
2527442d6faSDimitry Andric return !GV.hasName() || (GVS.count(GV.getName()) == 0);
2537442d6faSDimitry Andric });
2547442d6faSDimitry Andric });
255b1c73532SDimitry Andric } else
256ac9a064cSDimitry Andric Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
257b1c73532SDimitry Andric
258ac9a064cSDimitry Andric if (Err)
259ac9a064cSDimitry Andric return true;
2607442d6faSDimitry Andric }
2617442d6faSDimitry Andric
262ac9a064cSDimitry Andric LinkModules.clear();
2637442d6faSDimitry Andric return false; // success
2647442d6faSDimitry Andric }
2657442d6faSDimitry Andric
HandleTranslationUnit(ASTContext & C)266b1c73532SDimitry Andric void BackendConsumer::HandleTranslationUnit(ASTContext &C) {
2674ba67500SRoman Divacky {
268706b4fc4SDimitry Andric llvm::TimeTraceScope TimeScope("Frontend");
2694ba67500SRoman Divacky PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
270b60736ecSDimitry Andric if (TimerIsEnabled) {
271bab175ecSDimitry Andric LLVMIRGenerationRefCount += 1;
272bab175ecSDimitry Andric if (LLVMIRGenerationRefCount == 1)
2734ba67500SRoman Divacky LLVMIRGeneration.startTimer();
274bab175ecSDimitry Andric }
2754ba67500SRoman Divacky
2764ba67500SRoman Divacky Gen->HandleTranslationUnit(C);
2774ba67500SRoman Divacky
278b60736ecSDimitry Andric if (TimerIsEnabled) {
279bab175ecSDimitry Andric LLVMIRGenerationRefCount -= 1;
280bab175ecSDimitry Andric if (LLVMIRGenerationRefCount == 0)
2814ba67500SRoman Divacky LLVMIRGeneration.stopTimer();
2824ba67500SRoman Divacky }
2834ba67500SRoman Divacky
284bab175ecSDimitry Andric IRGenFinished = true;
285bab175ecSDimitry Andric }
286bab175ecSDimitry Andric
2874ba67500SRoman Divacky // Silently ignore if we weren't initialized for some reason.
2882b6b257fSDimitry Andric if (!getModule())
2894ba67500SRoman Divacky return;
2904ba67500SRoman Divacky
2912b6b257fSDimitry Andric LLVMContext &Ctx = getModule()->getContext();
292461a67faSDimitry Andric std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
2939f4dbff6SDimitry Andric Ctx.getDiagnosticHandler();
294519fc96cSDimitry Andric Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
295461a67faSDimitry Andric CodeGenOpts, this));
29622989816SDimitry Andric
297ac9a064cSDimitry Andric Ctx.setDefaultTargetCPU(TargetOpts.CPU);
298ac9a064cSDimitry Andric Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
299ac9a064cSDimitry Andric
30022989816SDimitry Andric Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
301cfca06d7SDimitry Andric setupLLVMOptimizationRemarks(
302706b4fc4SDimitry Andric Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
303706b4fc4SDimitry Andric CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
304cf1b4019SDimitry Andric CodeGenOpts.DiagnosticsHotnessThreshold);
305bab175ecSDimitry Andric
30622989816SDimitry Andric if (Error E = OptRecordFileOrErr.takeError()) {
307706b4fc4SDimitry Andric reportOptRecordError(std::move(E), Diags, CodeGenOpts);
308bab175ecSDimitry Andric return;
309bab175ecSDimitry Andric }
310706b4fc4SDimitry Andric
31122989816SDimitry Andric std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
31222989816SDimitry Andric std::move(*OptRecordFileOrErr);
313bab175ecSDimitry Andric
31422989816SDimitry Andric if (OptRecordFile &&
31522989816SDimitry Andric CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
316cf1b4019SDimitry Andric Ctx.setDiagnosticsHotnessRequested(true);
3179f4dbff6SDimitry Andric
318145449b1SDimitry Andric if (CodeGenOpts.MisExpect) {
319145449b1SDimitry Andric Ctx.setMisExpectWarningRequested(true);
320145449b1SDimitry Andric }
321145449b1SDimitry Andric
322145449b1SDimitry Andric if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
323145449b1SDimitry Andric Ctx.setDiagnosticsMisExpectTolerance(
324145449b1SDimitry Andric CodeGenOpts.DiagnosticsMisExpectTolerance);
325145449b1SDimitry Andric }
326145449b1SDimitry Andric
3277442d6faSDimitry Andric // Link each LinkModule into our module.
328ac9a064cSDimitry Andric if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))
32945b53394SDimitry Andric return;
33045b53394SDimitry Andric
331c0981da4SDimitry Andric for (auto &F : getModule()->functions()) {
332c0981da4SDimitry Andric if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
333c0981da4SDimitry Andric auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
334c0981da4SDimitry Andric // TODO: use a fast content hash when available.
335c0981da4SDimitry Andric auto NameHash = llvm::hash_value(F.getName());
336c0981da4SDimitry Andric ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
337c0981da4SDimitry Andric }
338c0981da4SDimitry Andric }
339c0981da4SDimitry Andric
340c0981da4SDimitry Andric if (CodeGenOpts.ClearASTBeforeBackend) {
341c0981da4SDimitry Andric LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
342c0981da4SDimitry Andric // Access to the AST is no longer available after this.
343c0981da4SDimitry Andric // Other things that the ASTContext manages are still available, e.g.
344c0981da4SDimitry Andric // the SourceManager. It'd be nice if we could separate out all the
345c0981da4SDimitry Andric // things in ASTContext used after this point and null out the
346c0981da4SDimitry Andric // ASTContext, but too many various parts of the ASTContext are still
347c0981da4SDimitry Andric // used in various parts.
348c0981da4SDimitry Andric C.cleanup();
349c0981da4SDimitry Andric C.getAllocator().Reset();
350c0981da4SDimitry Andric }
351c0981da4SDimitry Andric
3522b6b257fSDimitry Andric EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
3532b6b257fSDimitry Andric
354b1c73532SDimitry Andric EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
355b1c73532SDimitry Andric C.getTargetInfo().getDataLayoutString(), getModule(),
356b1c73532SDimitry Andric Action, FS, std::move(AsmOutStream), this);
3574ba67500SRoman Divacky
358461a67faSDimitry Andric Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
359bab175ecSDimitry Andric
360bab175ecSDimitry Andric if (OptRecordFile)
361bab175ecSDimitry Andric OptRecordFile->keep();
3624ba67500SRoman Divacky }
3634ba67500SRoman Divacky
HandleTagDeclDefinition(TagDecl * D)364b1c73532SDimitry Andric void BackendConsumer::HandleTagDeclDefinition(TagDecl *D) {
3654ba67500SRoman Divacky PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3664ba67500SRoman Divacky Context->getSourceManager(),
3674ba67500SRoman Divacky "LLVM IR generation of declaration");
3684ba67500SRoman Divacky Gen->HandleTagDeclDefinition(D);
3694ba67500SRoman Divacky }
3704ba67500SRoman Divacky
HandleTagDeclRequiredDefinition(const TagDecl * D)371b1c73532SDimitry Andric void BackendConsumer::HandleTagDeclRequiredDefinition(const TagDecl *D) {
372bfef3995SDimitry Andric Gen->HandleTagDeclRequiredDefinition(D);
373bfef3995SDimitry Andric }
374bfef3995SDimitry Andric
CompleteTentativeDefinition(VarDecl * D)375b1c73532SDimitry Andric void BackendConsumer::CompleteTentativeDefinition(VarDecl *D) {
3764ba67500SRoman Divacky Gen->CompleteTentativeDefinition(D);
3774ba67500SRoman Divacky }
3784ba67500SRoman Divacky
CompleteExternalDeclaration(DeclaratorDecl * D)379ac9a064cSDimitry Andric void BackendConsumer::CompleteExternalDeclaration(DeclaratorDecl *D) {
380706b4fc4SDimitry Andric Gen->CompleteExternalDeclaration(D);
381706b4fc4SDimitry Andric }
382706b4fc4SDimitry Andric
AssignInheritanceModel(CXXRecordDecl * RD)383b1c73532SDimitry Andric void BackendConsumer::AssignInheritanceModel(CXXRecordDecl *RD) {
3842b6b257fSDimitry Andric Gen->AssignInheritanceModel(RD);
3852b6b257fSDimitry Andric }
3862b6b257fSDimitry Andric
HandleVTable(CXXRecordDecl * RD)387b1c73532SDimitry Andric void BackendConsumer::HandleVTable(CXXRecordDecl *RD) {
3885e20cdd8SDimitry Andric Gen->HandleVTable(RD);
3894ba67500SRoman Divacky }
3904ba67500SRoman Divacky
anchor()391dbe13110SDimitry Andric void BackendConsumer::anchor() { }
392b1c73532SDimitry Andric
393b1c73532SDimitry Andric } // namespace clang
3944ba67500SRoman Divacky
handleDiagnostics(const DiagnosticInfo & DI)395461a67faSDimitry Andric bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
396461a67faSDimitry Andric BackendCon->DiagnosticHandlerImpl(DI);
397461a67faSDimitry Andric return true;
398461a67faSDimitry Andric }
399461a67faSDimitry Andric
4004ba67500SRoman Divacky /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
4014ba67500SRoman Divacky /// buffer to be a valid FullSourceLoc.
ConvertBackendLocation(const llvm::SMDiagnostic & D,SourceManager & CSM)4024ba67500SRoman Divacky static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
4034ba67500SRoman Divacky SourceManager &CSM) {
4044ba67500SRoman Divacky // Get both the clang and llvm source managers. The location is relative to
4054ba67500SRoman Divacky // a memory buffer that the LLVM Source Manager is handling, we need to add
4064ba67500SRoman Divacky // a copy to the Clang source manager.
4074ba67500SRoman Divacky const llvm::SourceMgr &LSM = *D.getSourceMgr();
4084ba67500SRoman Divacky
4094ba67500SRoman Divacky // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
4104ba67500SRoman Divacky // already owns its one and clang::SourceManager wants to own its one.
4114ba67500SRoman Divacky const MemoryBuffer *LBuf =
4124ba67500SRoman Divacky LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
4134ba67500SRoman Divacky
4144ba67500SRoman Divacky // Create the copy and transfer ownership to clang::SourceManager.
4159f4dbff6SDimitry Andric // TODO: Avoid copying files into memory.
41606d4ba38SDimitry Andric std::unique_ptr<llvm::MemoryBuffer> CBuf =
4174ba67500SRoman Divacky llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
4184ba67500SRoman Divacky LBuf->getBufferIdentifier());
4199f4dbff6SDimitry Andric // FIXME: Keep a file ID map instead of creating new IDs for each location.
42006d4ba38SDimitry Andric FileID FID = CSM.createFileID(std::move(CBuf));
4214ba67500SRoman Divacky
4224ba67500SRoman Divacky // Translate the offset into the file.
4234ba67500SRoman Divacky unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
4244ba67500SRoman Divacky SourceLocation NewLoc =
42536981b17SDimitry Andric CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
4264ba67500SRoman Divacky return FullSourceLoc(NewLoc, CSM);
4274ba67500SRoman Divacky }
4284ba67500SRoman Divacky
4299f4dbff6SDimitry Andric #define ComputeDiagID(Severity, GroupName, DiagID) \
4309f4dbff6SDimitry Andric do { \
4319f4dbff6SDimitry Andric switch (Severity) { \
4329f4dbff6SDimitry Andric case llvm::DS_Error: \
4339f4dbff6SDimitry Andric DiagID = diag::err_fe_##GroupName; \
4349f4dbff6SDimitry Andric break; \
4359f4dbff6SDimitry Andric case llvm::DS_Warning: \
4369f4dbff6SDimitry Andric DiagID = diag::warn_fe_##GroupName; \
4379f4dbff6SDimitry Andric break; \
4389f4dbff6SDimitry Andric case llvm::DS_Remark: \
4399f4dbff6SDimitry Andric llvm_unreachable("'remark' severity not expected"); \
4409f4dbff6SDimitry Andric break; \
4419f4dbff6SDimitry Andric case llvm::DS_Note: \
4429f4dbff6SDimitry Andric DiagID = diag::note_fe_##GroupName; \
4439f4dbff6SDimitry Andric break; \
4449f4dbff6SDimitry Andric } \
4459f4dbff6SDimitry Andric } while (false)
4469f4dbff6SDimitry Andric
4479f4dbff6SDimitry Andric #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
4489f4dbff6SDimitry Andric do { \
4499f4dbff6SDimitry Andric switch (Severity) { \
4509f4dbff6SDimitry Andric case llvm::DS_Error: \
4519f4dbff6SDimitry Andric DiagID = diag::err_fe_##GroupName; \
4529f4dbff6SDimitry Andric break; \
4539f4dbff6SDimitry Andric case llvm::DS_Warning: \
4549f4dbff6SDimitry Andric DiagID = diag::warn_fe_##GroupName; \
4559f4dbff6SDimitry Andric break; \
4569f4dbff6SDimitry Andric case llvm::DS_Remark: \
4579f4dbff6SDimitry Andric DiagID = diag::remark_fe_##GroupName; \
4589f4dbff6SDimitry Andric break; \
4599f4dbff6SDimitry Andric case llvm::DS_Note: \
4609f4dbff6SDimitry Andric DiagID = diag::note_fe_##GroupName; \
4619f4dbff6SDimitry Andric break; \
4629f4dbff6SDimitry Andric } \
4639f4dbff6SDimitry Andric } while (false)
4649f4dbff6SDimitry Andric
SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr & DI)465344a3780SDimitry Andric void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
466344a3780SDimitry Andric const llvm::SMDiagnostic &D = DI.getSMDiag();
467344a3780SDimitry Andric
468344a3780SDimitry Andric unsigned DiagID;
469344a3780SDimitry Andric if (DI.isInlineAsmDiag())
470344a3780SDimitry Andric ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
471344a3780SDimitry Andric else
472344a3780SDimitry Andric ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
473344a3780SDimitry Andric
474344a3780SDimitry Andric // This is for the empty BackendConsumer that uses the clang diagnostic
475344a3780SDimitry Andric // handler for IR input files.
476344a3780SDimitry Andric if (!Context) {
477344a3780SDimitry Andric D.print(nullptr, llvm::errs());
478344a3780SDimitry Andric Diags.Report(DiagID).AddString("cannot compile inline asm");
479344a3780SDimitry Andric return;
480344a3780SDimitry Andric }
481344a3780SDimitry Andric
482344a3780SDimitry Andric // There are a couple of different kinds of errors we could get here.
483344a3780SDimitry Andric // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
484344a3780SDimitry Andric
485344a3780SDimitry Andric // Strip "error: " off the start of the message string.
486344a3780SDimitry Andric StringRef Message = D.getMessage();
487344a3780SDimitry Andric (void)Message.consume_front("error: ");
488344a3780SDimitry Andric
489344a3780SDimitry Andric // If the SMDiagnostic has an inline asm source location, translate it.
490344a3780SDimitry Andric FullSourceLoc Loc;
491344a3780SDimitry Andric if (D.getLoc() != SMLoc())
492344a3780SDimitry Andric Loc = ConvertBackendLocation(D, Context->getSourceManager());
493344a3780SDimitry Andric
494344a3780SDimitry Andric // If this problem has clang-level source location information, report the
495344a3780SDimitry Andric // issue in the source with a note showing the instantiated
496344a3780SDimitry Andric // code.
497344a3780SDimitry Andric if (DI.isInlineAsmDiag()) {
498344a3780SDimitry Andric SourceLocation LocCookie =
499344a3780SDimitry Andric SourceLocation::getFromRawEncoding(DI.getLocCookie());
500344a3780SDimitry Andric if (LocCookie.isValid()) {
501344a3780SDimitry Andric Diags.Report(LocCookie, DiagID).AddString(Message);
502344a3780SDimitry Andric
503344a3780SDimitry Andric if (D.getLoc().isValid()) {
504344a3780SDimitry Andric DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
505344a3780SDimitry Andric // Convert the SMDiagnostic ranges into SourceRange and attach them
506344a3780SDimitry Andric // to the diagnostic.
507344a3780SDimitry Andric for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
508344a3780SDimitry Andric unsigned Column = D.getColumnNo();
509344a3780SDimitry Andric B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
510344a3780SDimitry Andric Loc.getLocWithOffset(Range.second - Column));
511344a3780SDimitry Andric }
512344a3780SDimitry Andric }
513344a3780SDimitry Andric return;
514344a3780SDimitry Andric }
515344a3780SDimitry Andric }
516344a3780SDimitry Andric
517344a3780SDimitry Andric // Otherwise, report the backend issue as occurring in the generated .s file.
518344a3780SDimitry Andric // If Loc is invalid, we still need to report the issue, it just gets no
519344a3780SDimitry Andric // location info.
520344a3780SDimitry Andric Diags.Report(Loc, DiagID).AddString(Message);
521344a3780SDimitry Andric }
522344a3780SDimitry Andric
5239f4dbff6SDimitry Andric bool
InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm & D)5249f4dbff6SDimitry Andric BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
5259f4dbff6SDimitry Andric unsigned DiagID;
5269f4dbff6SDimitry Andric ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
5279f4dbff6SDimitry Andric std::string Message = D.getMsgStr().str();
5289f4dbff6SDimitry Andric
5299f4dbff6SDimitry Andric // If this problem has clang-level source location information, report the
5309f4dbff6SDimitry Andric // issue as being a problem in the source with a note showing the instantiated
5319f4dbff6SDimitry Andric // code.
5329f4dbff6SDimitry Andric SourceLocation LocCookie =
5339f4dbff6SDimitry Andric SourceLocation::getFromRawEncoding(D.getLocCookie());
5349f4dbff6SDimitry Andric if (LocCookie.isValid())
5359f4dbff6SDimitry Andric Diags.Report(LocCookie, DiagID).AddString(Message);
5369f4dbff6SDimitry Andric else {
5379f4dbff6SDimitry Andric // Otherwise, report the backend diagnostic as occurring in the generated
5389f4dbff6SDimitry Andric // .s file.
5399f4dbff6SDimitry Andric // If Loc is invalid, we still need to report the diagnostic, it just gets
5409f4dbff6SDimitry Andric // no location info.
5419f4dbff6SDimitry Andric FullSourceLoc Loc;
5429f4dbff6SDimitry Andric Diags.Report(Loc, DiagID).AddString(Message);
5439f4dbff6SDimitry Andric }
5449f4dbff6SDimitry Andric // We handled all the possible severities.
5459f4dbff6SDimitry Andric return true;
5469f4dbff6SDimitry Andric }
5479f4dbff6SDimitry Andric
5489f4dbff6SDimitry Andric bool
StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize & D)5499f4dbff6SDimitry Andric BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
5509f4dbff6SDimitry Andric if (D.getSeverity() != llvm::DS_Warning)
5519f4dbff6SDimitry Andric // For now, the only support we have for StackSize diagnostic is warning.
5529f4dbff6SDimitry Andric // We do not know how to format other severities.
5539f4dbff6SDimitry Andric return false;
5549f4dbff6SDimitry Andric
555c0981da4SDimitry Andric auto Loc = getFunctionSourceLocation(D.getFunction());
556c0981da4SDimitry Andric if (!Loc)
557c0981da4SDimitry Andric return false;
558c0981da4SDimitry Andric
559c0981da4SDimitry Andric Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
5607fa27ce4SDimitry Andric << D.getStackSize() << D.getStackLimit()
5617fa27ce4SDimitry Andric << llvm::demangle(D.getFunction().getName());
562e3b55780SDimitry Andric return true;
563e3b55780SDimitry Andric }
564e3b55780SDimitry Andric
ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit & D)565e3b55780SDimitry Andric bool BackendConsumer::ResourceLimitDiagHandler(
566e3b55780SDimitry Andric const llvm::DiagnosticInfoResourceLimit &D) {
567e3b55780SDimitry Andric auto Loc = getFunctionSourceLocation(D.getFunction());
568e3b55780SDimitry Andric if (!Loc)
569e3b55780SDimitry Andric return false;
570e3b55780SDimitry Andric unsigned DiagID = diag::err_fe_backend_resource_limit;
571e3b55780SDimitry Andric ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
572e3b55780SDimitry Andric
573e3b55780SDimitry Andric Diags.Report(*Loc, DiagID)
574e3b55780SDimitry Andric << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
5757fa27ce4SDimitry Andric << llvm::demangle(D.getFunction().getName());
5769f4dbff6SDimitry Andric return true;
5779f4dbff6SDimitry Andric }
5789f4dbff6SDimitry Andric
getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase & D,bool & BadDebugInfo,StringRef & Filename,unsigned & Line,unsigned & Column) const5792b6b257fSDimitry Andric const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
5807442d6faSDimitry Andric const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
5817442d6faSDimitry Andric StringRef &Filename, unsigned &Line, unsigned &Column) const {
5829f4dbff6SDimitry Andric SourceManager &SourceMgr = Context->getSourceManager();
5839f4dbff6SDimitry Andric FileManager &FileMgr = SourceMgr.getFileManager();
5849f4dbff6SDimitry Andric SourceLocation DILoc;
5855e20cdd8SDimitry Andric
5865e20cdd8SDimitry Andric if (D.isLocationAvailable()) {
587676fbe81SDimitry Andric D.getLocation(Filename, Line, Column);
588676fbe81SDimitry Andric if (Line > 0) {
589519fc96cSDimitry Andric auto FE = FileMgr.getFile(Filename);
590676fbe81SDimitry Andric if (!FE)
591676fbe81SDimitry Andric FE = FileMgr.getFile(D.getAbsolutePath());
592676fbe81SDimitry Andric if (FE) {
5939f4dbff6SDimitry Andric // If -gcolumn-info was not used, Column will be 0. This upsets the
5949f4dbff6SDimitry Andric // source manager, so pass 1 if Column is not set.
595519fc96cSDimitry Andric DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
5969f4dbff6SDimitry Andric }
597676fbe81SDimitry Andric }
5982b6b257fSDimitry Andric BadDebugInfo = DILoc.isInvalid();
5995e20cdd8SDimitry Andric }
6009f4dbff6SDimitry Andric
6019f4dbff6SDimitry Andric // If a location isn't available, try to approximate it using the associated
6029f4dbff6SDimitry Andric // function definition. We use the definition's right brace to differentiate
6039f4dbff6SDimitry Andric // from diagnostics that genuinely relate to the function itself.
6049f4dbff6SDimitry Andric FullSourceLoc Loc(DILoc, SourceMgr);
605c0981da4SDimitry Andric if (Loc.isInvalid()) {
606c0981da4SDimitry Andric if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
607c0981da4SDimitry Andric Loc = *MaybeLoc;
608c0981da4SDimitry Andric }
6099f4dbff6SDimitry Andric
6105e20cdd8SDimitry Andric if (DILoc.isInvalid() && D.isLocationAvailable())
6119f4dbff6SDimitry Andric // If we were not able to translate the file:line:col information
6129f4dbff6SDimitry Andric // back to a SourceLocation, at least emit a note stating that
6139f4dbff6SDimitry Andric // we could not translate this location. This can happen in the
6149f4dbff6SDimitry Andric // case of #line directives.
6152b6b257fSDimitry Andric Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
6162b6b257fSDimitry Andric << Filename << Line << Column;
6172b6b257fSDimitry Andric
6182b6b257fSDimitry Andric return Loc;
6192b6b257fSDimitry Andric }
6202b6b257fSDimitry Andric
621e3b55780SDimitry Andric std::optional<FullSourceLoc>
getFunctionSourceLocation(const Function & F) const622c0981da4SDimitry Andric BackendConsumer::getFunctionSourceLocation(const Function &F) const {
623c0981da4SDimitry Andric auto Hash = llvm::hash_value(F.getName());
624c0981da4SDimitry Andric for (const auto &Pair : ManglingFullSourceLocs) {
625c0981da4SDimitry Andric if (Pair.first == Hash)
626c0981da4SDimitry Andric return Pair.second;
627c0981da4SDimitry Andric }
628e3b55780SDimitry Andric return std::nullopt;
629c0981da4SDimitry Andric }
630c0981da4SDimitry Andric
UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported & D)6312b6b257fSDimitry Andric void BackendConsumer::UnsupportedDiagHandler(
6322b6b257fSDimitry Andric const llvm::DiagnosticInfoUnsupported &D) {
633cfca06d7SDimitry Andric // We only support warnings or errors.
634cfca06d7SDimitry Andric assert(D.getSeverity() == llvm::DS_Error ||
635cfca06d7SDimitry Andric D.getSeverity() == llvm::DS_Warning);
6362b6b257fSDimitry Andric
6372b6b257fSDimitry Andric StringRef Filename;
6382b6b257fSDimitry Andric unsigned Line, Column;
6392410013dSDimitry Andric bool BadDebugInfo = false;
640706b4fc4SDimitry Andric FullSourceLoc Loc;
641706b4fc4SDimitry Andric std::string Msg;
642706b4fc4SDimitry Andric raw_string_ostream MsgStream(Msg);
6432b6b257fSDimitry Andric
644706b4fc4SDimitry Andric // Context will be nullptr for IR input files, we will construct the diag
645706b4fc4SDimitry Andric // message from llvm::DiagnosticInfoUnsupported.
646706b4fc4SDimitry Andric if (Context != nullptr) {
647706b4fc4SDimitry Andric Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
648706b4fc4SDimitry Andric MsgStream << D.getMessage();
649706b4fc4SDimitry Andric } else {
650706b4fc4SDimitry Andric DiagnosticPrinterRawOStream DP(MsgStream);
651706b4fc4SDimitry Andric D.print(DP);
652706b4fc4SDimitry Andric }
653cfca06d7SDimitry Andric
654cfca06d7SDimitry Andric auto DiagType = D.getSeverity() == llvm::DS_Error
655cfca06d7SDimitry Andric ? diag::err_fe_backend_unsupported
656cfca06d7SDimitry Andric : diag::warn_fe_backend_unsupported;
657cfca06d7SDimitry Andric Diags.Report(Loc, DiagType) << MsgStream.str();
6582b6b257fSDimitry Andric
6592b6b257fSDimitry Andric if (BadDebugInfo)
6602b6b257fSDimitry Andric // If we were not able to translate the file:line:col information
6612b6b257fSDimitry Andric // back to a SourceLocation, at least emit a note stating that
6622b6b257fSDimitry Andric // we could not translate this location. This can happen in the
6632b6b257fSDimitry Andric // case of #line directives.
6642b6b257fSDimitry Andric Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
6652b6b257fSDimitry Andric << Filename << Line << Column;
6662b6b257fSDimitry Andric }
6672b6b257fSDimitry Andric
EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase & D,unsigned DiagID)6682b6b257fSDimitry Andric void BackendConsumer::EmitOptimizationMessage(
6692b6b257fSDimitry Andric const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
6702b6b257fSDimitry Andric // We only support warnings and remarks.
6712b6b257fSDimitry Andric assert(D.getSeverity() == llvm::DS_Remark ||
6722b6b257fSDimitry Andric D.getSeverity() == llvm::DS_Warning);
6732b6b257fSDimitry Andric
6742b6b257fSDimitry Andric StringRef Filename;
6752b6b257fSDimitry Andric unsigned Line, Column;
6762b6b257fSDimitry Andric bool BadDebugInfo = false;
677706b4fc4SDimitry Andric FullSourceLoc Loc;
678bab175ecSDimitry Andric std::string Msg;
679bab175ecSDimitry Andric raw_string_ostream MsgStream(Msg);
680706b4fc4SDimitry Andric
681706b4fc4SDimitry Andric // Context will be nullptr for IR input files, we will construct the remark
682706b4fc4SDimitry Andric // message from llvm::DiagnosticInfoOptimizationBase.
683706b4fc4SDimitry Andric if (Context != nullptr) {
684706b4fc4SDimitry Andric Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
685bab175ecSDimitry Andric MsgStream << D.getMsg();
686706b4fc4SDimitry Andric } else {
687706b4fc4SDimitry Andric DiagnosticPrinterRawOStream DP(MsgStream);
688706b4fc4SDimitry Andric D.print(DP);
689706b4fc4SDimitry Andric }
690bab175ecSDimitry Andric
691bab175ecSDimitry Andric if (D.getHotness())
692bab175ecSDimitry Andric MsgStream << " (hotness: " << *D.getHotness() << ")";
693bab175ecSDimitry Andric
6942b6b257fSDimitry Andric Diags.Report(Loc, DiagID)
695bab175ecSDimitry Andric << AddFlagValue(D.getPassName())
696bab175ecSDimitry Andric << MsgStream.str();
6972b6b257fSDimitry Andric
6982b6b257fSDimitry Andric if (BadDebugInfo)
6992b6b257fSDimitry Andric // If we were not able to translate the file:line:col information
7002b6b257fSDimitry Andric // back to a SourceLocation, at least emit a note stating that
7012b6b257fSDimitry Andric // we could not translate this location. This can happen in the
7022b6b257fSDimitry Andric // case of #line directives.
7032b6b257fSDimitry Andric Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
7049f4dbff6SDimitry Andric << Filename << Line << Column;
7059f4dbff6SDimitry Andric }
7069f4dbff6SDimitry Andric
OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase & D)7079f4dbff6SDimitry Andric void BackendConsumer::OptimizationRemarkHandler(
7087442d6faSDimitry Andric const llvm::DiagnosticInfoOptimizationBase &D) {
709461a67faSDimitry Andric // Without hotness information, don't show noisy remarks.
710461a67faSDimitry Andric if (D.isVerbose() && !D.getHotness())
711461a67faSDimitry Andric return;
712461a67faSDimitry Andric
7137442d6faSDimitry Andric if (D.isPassed()) {
7149f4dbff6SDimitry Andric // Optimization remarks are active only if the -Rpass flag has a regular
7159f4dbff6SDimitry Andric // expression that matches the name of the pass name in \p D.
716344a3780SDimitry Andric if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
7179f4dbff6SDimitry Andric EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
7187442d6faSDimitry Andric } else if (D.isMissed()) {
7199f4dbff6SDimitry Andric // Missed optimization remarks are active only if the -Rpass-missed
7209f4dbff6SDimitry Andric // flag has a regular expression that matches the name of the pass
7219f4dbff6SDimitry Andric // name in \p D.
722344a3780SDimitry Andric if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
7237442d6faSDimitry Andric EmitOptimizationMessage(
7247442d6faSDimitry Andric D, diag::remark_fe_backend_optimization_remark_missed);
7257442d6faSDimitry Andric } else {
7267442d6faSDimitry Andric assert(D.isAnalysis() && "Unknown remark type");
7279f4dbff6SDimitry Andric
7287442d6faSDimitry Andric bool ShouldAlwaysPrint = false;
7297442d6faSDimitry Andric if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
7307442d6faSDimitry Andric ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
73145b53394SDimitry Andric
7327442d6faSDimitry Andric if (ShouldAlwaysPrint ||
733344a3780SDimitry Andric CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
7349f4dbff6SDimitry Andric EmitOptimizationMessage(
7359f4dbff6SDimitry Andric D, diag::remark_fe_backend_optimization_remark_analysis);
7369f4dbff6SDimitry Andric }
7377442d6faSDimitry Andric }
7389f4dbff6SDimitry Andric
OptimizationRemarkHandler(const llvm::OptimizationRemarkAnalysisFPCommute & D)73945b53394SDimitry Andric void BackendConsumer::OptimizationRemarkHandler(
740bab175ecSDimitry Andric const llvm::OptimizationRemarkAnalysisFPCommute &D) {
74145b53394SDimitry Andric // Optimization analysis remarks are active if the pass name is set to
74245b53394SDimitry Andric // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
74345b53394SDimitry Andric // regular expression that matches the name of the pass name in \p D.
74445b53394SDimitry Andric
7452b6b257fSDimitry Andric if (D.shouldAlwaysPrint() ||
746344a3780SDimitry Andric CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
74745b53394SDimitry Andric EmitOptimizationMessage(
74845b53394SDimitry Andric D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
74945b53394SDimitry Andric }
75045b53394SDimitry Andric
OptimizationRemarkHandler(const llvm::OptimizationRemarkAnalysisAliasing & D)75145b53394SDimitry Andric void BackendConsumer::OptimizationRemarkHandler(
752bab175ecSDimitry Andric const llvm::OptimizationRemarkAnalysisAliasing &D) {
75345b53394SDimitry Andric // Optimization analysis remarks are active if the pass name is set to
75445b53394SDimitry Andric // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
75545b53394SDimitry Andric // regular expression that matches the name of the pass name in \p D.
75645b53394SDimitry Andric
7572b6b257fSDimitry Andric if (D.shouldAlwaysPrint() ||
758344a3780SDimitry Andric CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
75945b53394SDimitry Andric EmitOptimizationMessage(
76045b53394SDimitry Andric D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
76145b53394SDimitry Andric }
76245b53394SDimitry Andric
OptimizationFailureHandler(const llvm::DiagnosticInfoOptimizationFailure & D)7639f4dbff6SDimitry Andric void BackendConsumer::OptimizationFailureHandler(
7649f4dbff6SDimitry Andric const llvm::DiagnosticInfoOptimizationFailure &D) {
7659f4dbff6SDimitry Andric EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
7669f4dbff6SDimitry Andric }
7679f4dbff6SDimitry Andric
DontCallDiagHandler(const DiagnosticInfoDontCall & D)768c0981da4SDimitry Andric void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
769c0981da4SDimitry Andric SourceLocation LocCookie =
770c0981da4SDimitry Andric SourceLocation::getFromRawEncoding(D.getLocCookie());
771c0981da4SDimitry Andric
772c0981da4SDimitry Andric // FIXME: we can't yet diagnose indirect calls. When/if we can, we
773c0981da4SDimitry Andric // should instead assert that LocCookie.isValid().
774c0981da4SDimitry Andric if (!LocCookie.isValid())
775c0981da4SDimitry Andric return;
776c0981da4SDimitry Andric
777c0981da4SDimitry Andric Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
778c0981da4SDimitry Andric ? diag::err_fe_backend_error_attr
779c0981da4SDimitry Andric : diag::warn_fe_backend_warning_attr)
7807fa27ce4SDimitry Andric << llvm::demangle(D.getFunctionName()) << D.getNote();
781c0981da4SDimitry Andric }
782c0981da4SDimitry Andric
MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect & D)783145449b1SDimitry Andric void BackendConsumer::MisExpectDiagHandler(
784145449b1SDimitry Andric const llvm::DiagnosticInfoMisExpect &D) {
785145449b1SDimitry Andric StringRef Filename;
786145449b1SDimitry Andric unsigned Line, Column;
787145449b1SDimitry Andric bool BadDebugInfo = false;
788145449b1SDimitry Andric FullSourceLoc Loc =
789145449b1SDimitry Andric getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
790145449b1SDimitry Andric
791145449b1SDimitry Andric Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
792145449b1SDimitry Andric
793145449b1SDimitry Andric if (BadDebugInfo)
794145449b1SDimitry Andric // If we were not able to translate the file:line:col information
795145449b1SDimitry Andric // back to a SourceLocation, at least emit a note stating that
796145449b1SDimitry Andric // we could not translate this location. This can happen in the
797145449b1SDimitry Andric // case of #line directives.
798145449b1SDimitry Andric Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
799145449b1SDimitry Andric << Filename << Line << Column;
800145449b1SDimitry Andric }
801145449b1SDimitry Andric
80248675466SDimitry Andric /// This function is invoked when the backend needs
8039f4dbff6SDimitry Andric /// to report something to the user.
DiagnosticHandlerImpl(const DiagnosticInfo & DI)8049f4dbff6SDimitry Andric void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
8059f4dbff6SDimitry Andric unsigned DiagID = diag::err_fe_inline_asm;
8069f4dbff6SDimitry Andric llvm::DiagnosticSeverity Severity = DI.getSeverity();
8079f4dbff6SDimitry Andric // Get the diagnostic ID based.
8089f4dbff6SDimitry Andric switch (DI.getKind()) {
8099f4dbff6SDimitry Andric case llvm::DK_InlineAsm:
8109f4dbff6SDimitry Andric if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
8119f4dbff6SDimitry Andric return;
8129f4dbff6SDimitry Andric ComputeDiagID(Severity, inline_asm, DiagID);
8139f4dbff6SDimitry Andric break;
814344a3780SDimitry Andric case llvm::DK_SrcMgr:
815344a3780SDimitry Andric SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));
816344a3780SDimitry Andric return;
8179f4dbff6SDimitry Andric case llvm::DK_StackSize:
8189f4dbff6SDimitry Andric if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
8199f4dbff6SDimitry Andric return;
8209f4dbff6SDimitry Andric ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
8219f4dbff6SDimitry Andric break;
822e3b55780SDimitry Andric case llvm::DK_ResourceLimit:
823e3b55780SDimitry Andric if (ResourceLimitDiagHandler(cast<DiagnosticInfoResourceLimit>(DI)))
824e3b55780SDimitry Andric return;
825e3b55780SDimitry Andric ComputeDiagID(Severity, backend_resource_limit, DiagID);
826e3b55780SDimitry Andric break;
82745b53394SDimitry Andric case DK_Linker:
828c0981da4SDimitry Andric ComputeDiagID(Severity, linking_module, DiagID);
82945b53394SDimitry Andric break;
8309f4dbff6SDimitry Andric case llvm::DK_OptimizationRemark:
8319f4dbff6SDimitry Andric // Optimization remarks are always handled completely by this
8329f4dbff6SDimitry Andric // handler. There is no generic way of emitting them.
833bab175ecSDimitry Andric OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
8349f4dbff6SDimitry Andric return;
8359f4dbff6SDimitry Andric case llvm::DK_OptimizationRemarkMissed:
8369f4dbff6SDimitry Andric // Optimization remarks are always handled completely by this
8379f4dbff6SDimitry Andric // handler. There is no generic way of emitting them.
838bab175ecSDimitry Andric OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
8399f4dbff6SDimitry Andric return;
8409f4dbff6SDimitry Andric case llvm::DK_OptimizationRemarkAnalysis:
8419f4dbff6SDimitry Andric // Optimization remarks are always handled completely by this
8429f4dbff6SDimitry Andric // handler. There is no generic way of emitting them.
843bab175ecSDimitry Andric OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
8449f4dbff6SDimitry Andric return;
84545b53394SDimitry Andric case llvm::DK_OptimizationRemarkAnalysisFPCommute:
84645b53394SDimitry Andric // Optimization remarks are always handled completely by this
84745b53394SDimitry Andric // handler. There is no generic way of emitting them.
848bab175ecSDimitry Andric OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
84945b53394SDimitry Andric return;
85045b53394SDimitry Andric case llvm::DK_OptimizationRemarkAnalysisAliasing:
85145b53394SDimitry Andric // Optimization remarks are always handled completely by this
85245b53394SDimitry Andric // handler. There is no generic way of emitting them.
853bab175ecSDimitry Andric OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
85445b53394SDimitry Andric return;
8557442d6faSDimitry Andric case llvm::DK_MachineOptimizationRemark:
8567442d6faSDimitry Andric // Optimization remarks are always handled completely by this
8577442d6faSDimitry Andric // handler. There is no generic way of emitting them.
8587442d6faSDimitry Andric OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
8597442d6faSDimitry Andric return;
8607442d6faSDimitry Andric case llvm::DK_MachineOptimizationRemarkMissed:
8617442d6faSDimitry Andric // Optimization remarks are always handled completely by this
8627442d6faSDimitry Andric // handler. There is no generic way of emitting them.
8637442d6faSDimitry Andric OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
8647442d6faSDimitry Andric return;
8657442d6faSDimitry Andric case llvm::DK_MachineOptimizationRemarkAnalysis:
8667442d6faSDimitry Andric // Optimization remarks are always handled completely by this
8677442d6faSDimitry Andric // handler. There is no generic way of emitting them.
8687442d6faSDimitry Andric OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
8697442d6faSDimitry Andric return;
8709f4dbff6SDimitry Andric case llvm::DK_OptimizationFailure:
8719f4dbff6SDimitry Andric // Optimization failures are always handled completely by this
8729f4dbff6SDimitry Andric // handler.
8739f4dbff6SDimitry Andric OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
8749f4dbff6SDimitry Andric return;
8752b6b257fSDimitry Andric case llvm::DK_Unsupported:
8762b6b257fSDimitry Andric UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
8772b6b257fSDimitry Andric return;
878c0981da4SDimitry Andric case llvm::DK_DontCall:
879c0981da4SDimitry Andric DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));
880c0981da4SDimitry Andric return;
881145449b1SDimitry Andric case llvm::DK_MisExpect:
882145449b1SDimitry Andric MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
883145449b1SDimitry Andric return;
8849f4dbff6SDimitry Andric default:
8859f4dbff6SDimitry Andric // Plugin IDs are not bound to any value as they are set dynamically.
8869f4dbff6SDimitry Andric ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
8879f4dbff6SDimitry Andric break;
8889f4dbff6SDimitry Andric }
8899f4dbff6SDimitry Andric std::string MsgStorage;
8909f4dbff6SDimitry Andric {
8919f4dbff6SDimitry Andric raw_string_ostream Stream(MsgStorage);
8929f4dbff6SDimitry Andric DiagnosticPrinterRawOStream DP(Stream);
8939f4dbff6SDimitry Andric DI.print(DP);
8949f4dbff6SDimitry Andric }
8959f4dbff6SDimitry Andric
896c0981da4SDimitry Andric if (DI.getKind() == DK_Linker) {
897c0981da4SDimitry Andric assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
898c0981da4SDimitry Andric Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
89945b53394SDimitry Andric return;
90045b53394SDimitry Andric }
90145b53394SDimitry Andric
9029f4dbff6SDimitry Andric // Report the backend message using the usual diagnostic mechanism.
9039f4dbff6SDimitry Andric FullSourceLoc Loc;
9049f4dbff6SDimitry Andric Diags.Report(Loc, DiagID).AddString(MsgStorage);
9059f4dbff6SDimitry Andric }
9069f4dbff6SDimitry Andric #undef ComputeDiagID
9074ba67500SRoman Divacky
CodeGenAction(unsigned _Act,LLVMContext * _VMContext)908bca07a45SDimitry Andric CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
90945b53394SDimitry Andric : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
910bca07a45SDimitry Andric OwnsVMContext(!_VMContext) {}
9114ba67500SRoman Divacky
~CodeGenAction()912bca07a45SDimitry Andric CodeGenAction::~CodeGenAction() {
913bca07a45SDimitry Andric TheModule.reset();
914bca07a45SDimitry Andric if (OwnsVMContext)
915bca07a45SDimitry Andric delete VMContext;
916bca07a45SDimitry Andric }
9174ba67500SRoman Divacky
loadLinkModules(CompilerInstance & CI)9187fa27ce4SDimitry Andric bool CodeGenAction::loadLinkModules(CompilerInstance &CI) {
9197fa27ce4SDimitry Andric if (!LinkModules.empty())
9207fa27ce4SDimitry Andric return false;
9217fa27ce4SDimitry Andric
9227fa27ce4SDimitry Andric for (const CodeGenOptions::BitcodeFileToLink &F :
9237fa27ce4SDimitry Andric CI.getCodeGenOpts().LinkBitcodeFiles) {
9247fa27ce4SDimitry Andric auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
9257fa27ce4SDimitry Andric if (!BCBuf) {
9267fa27ce4SDimitry Andric CI.getDiagnostics().Report(diag::err_cannot_open_file)
9277fa27ce4SDimitry Andric << F.Filename << BCBuf.getError().message();
9287fa27ce4SDimitry Andric LinkModules.clear();
9297fa27ce4SDimitry Andric return true;
9307fa27ce4SDimitry Andric }
9317fa27ce4SDimitry Andric
9327fa27ce4SDimitry Andric Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
9337fa27ce4SDimitry Andric getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
9347fa27ce4SDimitry Andric if (!ModuleOrErr) {
9357fa27ce4SDimitry Andric handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
9367fa27ce4SDimitry Andric CI.getDiagnostics().Report(diag::err_cannot_open_file)
9377fa27ce4SDimitry Andric << F.Filename << EIB.message();
9387fa27ce4SDimitry Andric });
9397fa27ce4SDimitry Andric LinkModules.clear();
9407fa27ce4SDimitry Andric return true;
9417fa27ce4SDimitry Andric }
9427fa27ce4SDimitry Andric LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
9437fa27ce4SDimitry Andric F.Internalize, F.LinkFlags});
9447fa27ce4SDimitry Andric }
9457fa27ce4SDimitry Andric return false;
9467fa27ce4SDimitry Andric }
9477fa27ce4SDimitry Andric
hasIRSupport() const9484ba67500SRoman Divacky bool CodeGenAction::hasIRSupport() const { return true; }
9494ba67500SRoman Divacky
EndSourceFileAction()9504ba67500SRoman Divacky void CodeGenAction::EndSourceFileAction() {
9514ba67500SRoman Divacky // If the consumer creation failed, do nothing.
9524ba67500SRoman Divacky if (!getCompilerInstance().hasASTConsumer())
9534ba67500SRoman Divacky return;
9544ba67500SRoman Divacky
9554ba67500SRoman Divacky // Steal the module from the consumer.
95606d4ba38SDimitry Andric TheModule = BEConsumer->takeModule();
9574ba67500SRoman Divacky }
9584ba67500SRoman Divacky
takeModule()95906d4ba38SDimitry Andric std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
96006d4ba38SDimitry Andric return std::move(TheModule);
96106d4ba38SDimitry Andric }
9624ba67500SRoman Divacky
takeLLVMContext()963bca07a45SDimitry Andric llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
964bca07a45SDimitry Andric OwnsVMContext = false;
965bca07a45SDimitry Andric return VMContext;
966bca07a45SDimitry Andric }
967bca07a45SDimitry Andric
getCodeGenerator() const968344a3780SDimitry Andric CodeGenerator *CodeGenAction::getCodeGenerator() const {
969344a3780SDimitry Andric return BEConsumer->getCodeGenerator();
970344a3780SDimitry Andric }
971344a3780SDimitry Andric
BeginSourceFileAction(CompilerInstance & CI)972ac9a064cSDimitry Andric bool CodeGenAction::BeginSourceFileAction(CompilerInstance &CI) {
973ac9a064cSDimitry Andric if (CI.getFrontendOpts().GenReducedBMI)
974ac9a064cSDimitry Andric CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
975ac9a064cSDimitry Andric return true;
976ac9a064cSDimitry Andric }
977ac9a064cSDimitry Andric
9782b6b257fSDimitry Andric static std::unique_ptr<raw_pwrite_stream>
GetOutputStream(CompilerInstance & CI,StringRef InFile,BackendAction Action)9795e20cdd8SDimitry Andric GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
9804ba67500SRoman Divacky switch (Action) {
9814ba67500SRoman Divacky case Backend_EmitAssembly:
9824ba67500SRoman Divacky return CI.createDefaultOutputFile(false, InFile, "s");
9834ba67500SRoman Divacky case Backend_EmitLL:
9844ba67500SRoman Divacky return CI.createDefaultOutputFile(false, InFile, "ll");
9854ba67500SRoman Divacky case Backend_EmitBC:
9864ba67500SRoman Divacky return CI.createDefaultOutputFile(true, InFile, "bc");
9874ba67500SRoman Divacky case Backend_EmitNothing:
9889f4dbff6SDimitry Andric return nullptr;
9894ba67500SRoman Divacky case Backend_EmitMCNull:
9909f4dbff6SDimitry Andric return CI.createNullOutputFile();
9914ba67500SRoman Divacky case Backend_EmitObj:
9924ba67500SRoman Divacky return CI.createDefaultOutputFile(true, InFile, "o");
9934ba67500SRoman Divacky }
9944ba67500SRoman Divacky
99536981b17SDimitry Andric llvm_unreachable("Invalid action!");
9964ba67500SRoman Divacky }
9974ba67500SRoman Divacky
99806d4ba38SDimitry Andric std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)99906d4ba38SDimitry Andric CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
10004ba67500SRoman Divacky BackendAction BA = static_cast<BackendAction>(Act);
100148675466SDimitry Andric std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
100248675466SDimitry Andric if (!OS)
100348675466SDimitry Andric OS = GetOutputStream(CI, InFile, BA);
100448675466SDimitry Andric
10054ba67500SRoman Divacky if (BA != Backend_EmitNothing && !OS)
10069f4dbff6SDimitry Andric return nullptr;
10074ba67500SRoman Divacky
100845b53394SDimitry Andric // Load bitcode modules to link with, if we need to.
10097fa27ce4SDimitry Andric if (loadLinkModules(CI))
10109f4dbff6SDimitry Andric return nullptr;
1011dbe13110SDimitry Andric
101206d4ba38SDimitry Andric CoverageSourceInfo *CoverageInfo = nullptr;
101306d4ba38SDimitry Andric // Add the preprocessor callback only when the coverage mapping is generated.
1014b60736ecSDimitry Andric if (CI.getCodeGenOpts().CoverageMapping)
1015b60736ecSDimitry Andric CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
1016b60736ecSDimitry Andric CI.getPreprocessor());
101745b53394SDimitry Andric
101806d4ba38SDimitry Andric std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
101908e8dd7bSDimitry Andric BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
102008e8dd7bSDimitry Andric CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
102108e8dd7bSDimitry Andric CI.getTargetOpts(), CI.getLangOpts(), std::string(InFile),
102208e8dd7bSDimitry Andric std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
102306d4ba38SDimitry Andric BEConsumer = Result.get();
10247442d6faSDimitry Andric
10257442d6faSDimitry Andric // Enable generating macro debug info only when debug info is not disabled and
10267442d6faSDimitry Andric // also macro debug info is enabled.
10277442d6faSDimitry Andric if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
10287442d6faSDimitry Andric CI.getCodeGenOpts().MacroDebugInfo) {
10297442d6faSDimitry Andric std::unique_ptr<PPCallbacks> Callbacks =
1030519fc96cSDimitry Andric std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
10317442d6faSDimitry Andric CI.getPreprocessor());
10327442d6faSDimitry Andric CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
10337442d6faSDimitry Andric }
10347442d6faSDimitry Andric
1035ac9a064cSDimitry Andric if (CI.getFrontendOpts().GenReducedBMI &&
1036ac9a064cSDimitry Andric !CI.getFrontendOpts().ModuleOutputPath.empty()) {
1037ac9a064cSDimitry Andric std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1038ac9a064cSDimitry Andric Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1039ac9a064cSDimitry Andric CI.getPreprocessor(), CI.getModuleCache(),
1040ac9a064cSDimitry Andric CI.getFrontendOpts().ModuleOutputPath);
1041ac9a064cSDimitry Andric Consumers[1] = std::move(Result);
1042ac9a064cSDimitry Andric return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1043ac9a064cSDimitry Andric }
1044ac9a064cSDimitry Andric
104506d4ba38SDimitry Andric return std::move(Result);
10464ba67500SRoman Divacky }
10474ba67500SRoman Divacky
104822989816SDimitry Andric std::unique_ptr<llvm::Module>
loadModule(MemoryBufferRef MBRef)104922989816SDimitry Andric CodeGenAction::loadModule(MemoryBufferRef MBRef) {
10507442d6faSDimitry Andric CompilerInstance &CI = getCompilerInstance();
10517442d6faSDimitry Andric SourceManager &SM = CI.getSourceManager();
10527442d6faSDimitry Andric
10537442d6faSDimitry Andric auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
10547442d6faSDimitry Andric unsigned DiagID =
10557442d6faSDimitry Andric CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
10567442d6faSDimitry Andric handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
10577442d6faSDimitry Andric CI.getDiagnostics().Report(DiagID) << EIB.message();
10587442d6faSDimitry Andric });
10597442d6faSDimitry Andric return {};
10607442d6faSDimitry Andric };
10617442d6faSDimitry Andric
10627fa27ce4SDimitry Andric // For ThinLTO backend invocations, ensure that the context
10637fa27ce4SDimitry Andric // merges types based on ODR identifiers. We also need to read
10647fa27ce4SDimitry Andric // the correct module out of a multi-module bitcode file.
10657fa27ce4SDimitry Andric if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
10667fa27ce4SDimitry Andric VMContext->enableDebugTypeODRUniquing();
10677fa27ce4SDimitry Andric
106848675466SDimitry Andric Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
106948675466SDimitry Andric if (!BMsOrErr)
107048675466SDimitry Andric return DiagErrors(BMsOrErr.takeError());
1071b60736ecSDimitry Andric BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
107248675466SDimitry Andric // We have nothing to do if the file contains no ThinLTO module. This is
107348675466SDimitry Andric // possible if ThinLTO compilation was not able to split module. Content of
107448675466SDimitry Andric // the file was already processed by indexing and will be passed to the
107548675466SDimitry Andric // linker using merged object file.
107648675466SDimitry Andric if (!Bm) {
1077519fc96cSDimitry Andric auto M = std::make_unique<llvm::Module>("empty", *VMContext);
107848675466SDimitry Andric M->setTargetTriple(CI.getTargetOpts().Triple);
107948675466SDimitry Andric return M;
108048675466SDimitry Andric }
10817442d6faSDimitry Andric Expected<std::unique_ptr<llvm::Module>> MOrErr =
108248675466SDimitry Andric Bm->parseModule(*VMContext);
10837442d6faSDimitry Andric if (!MOrErr)
10847442d6faSDimitry Andric return DiagErrors(MOrErr.takeError());
10857442d6faSDimitry Andric return std::move(*MOrErr);
10867442d6faSDimitry Andric }
10877442d6faSDimitry Andric
10887fa27ce4SDimitry Andric // Load bitcode modules to link with, if we need to.
10897fa27ce4SDimitry Andric if (loadLinkModules(CI))
10907fa27ce4SDimitry Andric return nullptr;
10917fa27ce4SDimitry Andric
10927fa27ce4SDimitry Andric // Handle textual IR and bitcode file with one single module.
10937442d6faSDimitry Andric llvm::SMDiagnostic Err;
10947442d6faSDimitry Andric if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
10957442d6faSDimitry Andric return M;
10967442d6faSDimitry Andric
10977fa27ce4SDimitry Andric // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
10987fa27ce4SDimitry Andric // output), place the extra modules (actually only one, a regular LTO module)
10997fa27ce4SDimitry Andric // into LinkModules as if we are using -mlink-bitcode-file.
11007fa27ce4SDimitry Andric Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
11017fa27ce4SDimitry Andric if (BMsOrErr && BMsOrErr->size()) {
11027fa27ce4SDimitry Andric std::unique_ptr<llvm::Module> FirstM;
11037fa27ce4SDimitry Andric for (auto &BM : *BMsOrErr) {
11047fa27ce4SDimitry Andric Expected<std::unique_ptr<llvm::Module>> MOrErr =
11057fa27ce4SDimitry Andric BM.parseModule(*VMContext);
11067fa27ce4SDimitry Andric if (!MOrErr)
11077fa27ce4SDimitry Andric return DiagErrors(MOrErr.takeError());
11087fa27ce4SDimitry Andric if (FirstM)
11097fa27ce4SDimitry Andric LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
11107fa27ce4SDimitry Andric /*Internalize=*/false, /*LinkFlags=*/{}});
11117fa27ce4SDimitry Andric else
11127fa27ce4SDimitry Andric FirstM = std::move(*MOrErr);
11137fa27ce4SDimitry Andric }
11147fa27ce4SDimitry Andric if (FirstM)
11157fa27ce4SDimitry Andric return FirstM;
11167fa27ce4SDimitry Andric }
11177fa27ce4SDimitry Andric // If BMsOrErr fails, consume the error and use the error message from
11187fa27ce4SDimitry Andric // parseIR.
11197fa27ce4SDimitry Andric consumeError(BMsOrErr.takeError());
11207fa27ce4SDimitry Andric
11217442d6faSDimitry Andric // Translate from the diagnostic info to the SourceManager location if
11227442d6faSDimitry Andric // available.
11237442d6faSDimitry Andric // TODO: Unify this with ConvertBackendLocation()
11247442d6faSDimitry Andric SourceLocation Loc;
11257442d6faSDimitry Andric if (Err.getLineNo() > 0) {
11267442d6faSDimitry Andric assert(Err.getColumnNo() >= 0);
11277442d6faSDimitry Andric Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
11287442d6faSDimitry Andric Err.getLineNo(), Err.getColumnNo() + 1);
11297442d6faSDimitry Andric }
11307442d6faSDimitry Andric
11317442d6faSDimitry Andric // Strip off a leading diagnostic code if there is one.
11327442d6faSDimitry Andric StringRef Msg = Err.getMessage();
113377dbea07SDimitry Andric Msg.consume_front("error: ");
11347442d6faSDimitry Andric
11357442d6faSDimitry Andric unsigned DiagID =
11367442d6faSDimitry Andric CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
11377442d6faSDimitry Andric
11387442d6faSDimitry Andric CI.getDiagnostics().Report(Loc, DiagID) << Msg;
11397442d6faSDimitry Andric return {};
11407442d6faSDimitry Andric }
11417442d6faSDimitry Andric
ExecuteAction()11424ba67500SRoman Divacky void CodeGenAction::ExecuteAction() {
1143b60736ecSDimitry Andric if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1144b60736ecSDimitry Andric this->ASTFrontendAction::ExecuteAction();
1145b60736ecSDimitry Andric return;
1146b60736ecSDimitry Andric }
1147b60736ecSDimitry Andric
11484ba67500SRoman Divacky // If this is an IR file, we have to treat it specially.
11494ba67500SRoman Divacky BackendAction BA = static_cast<BackendAction>(Act);
11504ba67500SRoman Divacky CompilerInstance &CI = getCompilerInstance();
1151706b4fc4SDimitry Andric auto &CodeGenOpts = CI.getCodeGenOpts();
1152706b4fc4SDimitry Andric auto &Diagnostics = CI.getDiagnostics();
11532b6b257fSDimitry Andric std::unique_ptr<raw_pwrite_stream> OS =
1154145449b1SDimitry Andric GetOutputStream(CI, getCurrentFileOrBufferName(), BA);
11554ba67500SRoman Divacky if (BA != Backend_EmitNothing && !OS)
11564ba67500SRoman Divacky return;
11574ba67500SRoman Divacky
11584ba67500SRoman Divacky SourceManager &SM = CI.getSourceManager();
11599f4dbff6SDimitry Andric FileID FID = SM.getMainFileID();
1160e3b55780SDimitry Andric std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1161b60736ecSDimitry Andric if (!MainFile)
11624ba67500SRoman Divacky return;
11634ba67500SRoman Divacky
11647442d6faSDimitry Andric TheModule = loadModule(*MainFile);
11657442d6faSDimitry Andric if (!TheModule)
11664ba67500SRoman Divacky return;
11677442d6faSDimitry Andric
11689f4dbff6SDimitry Andric const TargetOptions &TargetOpts = CI.getTargetOpts();
11699f4dbff6SDimitry Andric if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1170b60736ecSDimitry Andric Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
11715e20cdd8SDimitry Andric << TargetOpts.Triple;
11729f4dbff6SDimitry Andric TheModule->setTargetTriple(TargetOpts.Triple);
11739f4dbff6SDimitry Andric }
11749f4dbff6SDimitry Andric
1175ecbca9f5SDimitry Andric EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1176b60736ecSDimitry Andric EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
11772b6b257fSDimitry Andric
11785e20cdd8SDimitry Andric LLVMContext &Ctx = TheModule->getContext();
1179344a3780SDimitry Andric
1180344a3780SDimitry Andric // Restore any diagnostic handler previously set before returning from this
1181344a3780SDimitry Andric // function.
1182344a3780SDimitry Andric struct RAII {
1183344a3780SDimitry Andric LLVMContext &Ctx;
1184344a3780SDimitry Andric std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1185344a3780SDimitry Andric ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1186344a3780SDimitry Andric } _{Ctx};
11872b6b257fSDimitry Andric
1188706b4fc4SDimitry Andric // Set clang diagnostic handler. To do this we need to create a fake
1189706b4fc4SDimitry Andric // BackendConsumer.
119008e8dd7bSDimitry Andric BackendConsumer Result(BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
119108e8dd7bSDimitry Andric CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),
119208e8dd7bSDimitry Andric CI.getCodeGenOpts(), CI.getTargetOpts(),
119308e8dd7bSDimitry Andric CI.getLangOpts(), TheModule.get(),
1194706b4fc4SDimitry Andric std::move(LinkModules), *VMContext, nullptr);
11957fa27ce4SDimitry Andric
11967fa27ce4SDimitry Andric // Link in each pending link module.
1197ac9a064cSDimitry Andric if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
11987fa27ce4SDimitry Andric return;
11997fa27ce4SDimitry Andric
1200cfca06d7SDimitry Andric // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1201cfca06d7SDimitry Andric // true here because the valued names are needed for reading textual IR.
1202cfca06d7SDimitry Andric Ctx.setDiscardValueNames(false);
1203706b4fc4SDimitry Andric Ctx.setDiagnosticHandler(
1204706b4fc4SDimitry Andric std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1205706b4fc4SDimitry Andric
1206ac9a064cSDimitry Andric Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1207ac9a064cSDimitry Andric Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
1208ac9a064cSDimitry Andric
1209706b4fc4SDimitry Andric Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
1210cfca06d7SDimitry Andric setupLLVMOptimizationRemarks(
1211706b4fc4SDimitry Andric Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1212706b4fc4SDimitry Andric CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1213706b4fc4SDimitry Andric CodeGenOpts.DiagnosticsHotnessThreshold);
1214706b4fc4SDimitry Andric
1215706b4fc4SDimitry Andric if (Error E = OptRecordFileOrErr.takeError()) {
1216706b4fc4SDimitry Andric reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1217706b4fc4SDimitry Andric return;
1218706b4fc4SDimitry Andric }
1219706b4fc4SDimitry Andric std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1220706b4fc4SDimitry Andric std::move(*OptRecordFileOrErr);
1221706b4fc4SDimitry Andric
12227fa27ce4SDimitry Andric EmitBackendOutput(
12237fa27ce4SDimitry Andric Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts, TargetOpts,
12247fa27ce4SDimitry Andric CI.getLangOpts(), CI.getTarget().getDataLayoutString(), TheModule.get(),
12257fa27ce4SDimitry Andric BA, CI.getFileManager().getVirtualFileSystemPtr(), std::move(OS));
1226706b4fc4SDimitry Andric if (OptRecordFile)
1227706b4fc4SDimitry Andric OptRecordFile->keep();
12284ba67500SRoman Divacky }
12294ba67500SRoman Divacky
12304ba67500SRoman Divacky //
12314ba67500SRoman Divacky
anchor()1232dbe13110SDimitry Andric void EmitAssemblyAction::anchor() { }
EmitAssemblyAction(llvm::LLVMContext * _VMContext)1233bca07a45SDimitry Andric EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1234bca07a45SDimitry Andric : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
12354ba67500SRoman Divacky
anchor()1236dbe13110SDimitry Andric void EmitBCAction::anchor() { }
EmitBCAction(llvm::LLVMContext * _VMContext)1237bca07a45SDimitry Andric EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1238bca07a45SDimitry Andric : CodeGenAction(Backend_EmitBC, _VMContext) {}
12394ba67500SRoman Divacky
anchor()1240dbe13110SDimitry Andric void EmitLLVMAction::anchor() { }
EmitLLVMAction(llvm::LLVMContext * _VMContext)1241bca07a45SDimitry Andric EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1242bca07a45SDimitry Andric : CodeGenAction(Backend_EmitLL, _VMContext) {}
12434ba67500SRoman Divacky
anchor()1244dbe13110SDimitry Andric void EmitLLVMOnlyAction::anchor() { }
EmitLLVMOnlyAction(llvm::LLVMContext * _VMContext)1245bca07a45SDimitry Andric EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1246bca07a45SDimitry Andric : CodeGenAction(Backend_EmitNothing, _VMContext) {}
12474ba67500SRoman Divacky
anchor()1248dbe13110SDimitry Andric void EmitCodeGenOnlyAction::anchor() { }
EmitCodeGenOnlyAction(llvm::LLVMContext * _VMContext)1249bca07a45SDimitry Andric EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1250bca07a45SDimitry Andric : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
12514ba67500SRoman Divacky
anchor()1252dbe13110SDimitry Andric void EmitObjAction::anchor() { }
EmitObjAction(llvm::LLVMContext * _VMContext)1253bca07a45SDimitry Andric EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1254bca07a45SDimitry Andric : CodeGenAction(Backend_EmitObj, _VMContext) {}
1255