1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "clang/CodeGen/CodeGenAction.h"
10 #include "CodeGenModule.h"
11 #include "CoverageMappingGen.h"
12 #include "MacroPPCallbacks.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclGroup.h"
17 #include "clang/Basic/DiagnosticFrontend.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/LangStandard.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/CodeGen/BackendUtil.h"
23 #include "clang/CodeGen/ModuleBuilder.h"
24 #include "clang/Driver/DriverDiagnostic.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Lex/Preprocessor.h"
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"
42 #include "llvm/Pass.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"
53 using namespace clang
;
56 #define DEBUG_TYPE "codegenaction"
59 class BackendConsumer
;
60 class ClangDiagnosticHandler final
: public DiagnosticHandler
{
62 ClangDiagnosticHandler(const CodeGenOptions
&CGOpts
, BackendConsumer
*BCon
)
63 : CodeGenOpts(CGOpts
), BackendCon(BCon
) {}
65 bool handleDiagnostics(const DiagnosticInfo
&DI
) override
;
67 bool isAnalysisRemarkEnabled(StringRef PassName
) const override
{
68 return CodeGenOpts
.OptimizationRemarkAnalysis
.patternMatches(PassName
);
70 bool isMissedOptRemarkEnabled(StringRef PassName
) const override
{
71 return CodeGenOpts
.OptimizationRemarkMissed
.patternMatches(PassName
);
73 bool isPassedOptRemarkEnabled(StringRef PassName
) const override
{
74 return CodeGenOpts
.OptimizationRemark
.patternMatches(PassName
);
77 bool isAnyRemarkEnabled() const override
{
78 return CodeGenOpts
.OptimizationRemarkAnalysis
.hasValidPattern() ||
79 CodeGenOpts
.OptimizationRemarkMissed
.hasValidPattern() ||
80 CodeGenOpts
.OptimizationRemark
.hasValidPattern();
84 const CodeGenOptions
&CodeGenOpts
;
85 BackendConsumer
*BackendCon
;
88 static void reportOptRecordError(Error E
, DiagnosticsEngine
&Diags
,
89 const CodeGenOptions
&CodeGenOpts
) {
92 [&](const LLVMRemarkSetupFileError
&E
) {
93 Diags
.Report(diag::err_cannot_open_file
)
94 << CodeGenOpts
.OptRecordFile
<< E
.message();
96 [&](const LLVMRemarkSetupPatternError
&E
) {
97 Diags
.Report(diag::err_drv_optimization_remark_pattern
)
98 << E
.message() << CodeGenOpts
.OptRecordPasses
;
100 [&](const LLVMRemarkSetupFormatError
&E
) {
101 Diags
.Report(diag::err_drv_optimization_remark_format
)
102 << CodeGenOpts
.OptRecordFormat
;
106 class BackendConsumer
: public ASTConsumer
{
107 using LinkModule
= CodeGenAction::LinkModule
;
109 virtual void anchor();
110 DiagnosticsEngine
&Diags
;
111 BackendAction Action
;
112 const HeaderSearchOptions
&HeaderSearchOpts
;
113 const CodeGenOptions
&CodeGenOpts
;
114 const TargetOptions
&TargetOpts
;
115 const LangOptions
&LangOpts
;
116 std::unique_ptr
<raw_pwrite_stream
> AsmOutStream
;
118 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> FS
;
120 Timer LLVMIRGeneration
;
121 unsigned LLVMIRGenerationRefCount
;
123 /// True if we've finished generating IR. This prevents us from generating
124 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
125 /// can happen when Clang plugins trigger additional AST deserialization.
126 bool IRGenFinished
= false;
128 bool TimerIsEnabled
= false;
130 std::unique_ptr
<CodeGenerator
> Gen
;
132 SmallVector
<LinkModule
, 4> LinkModules
;
134 // A map from mangled names to their function's source location, used for
135 // backend diagnostics as the Clang AST may be unavailable. We actually use
136 // the mangled name's hash as the key because mangled names can be very
137 // long and take up lots of space. Using a hash can cause name collision,
138 // but that is rare and the consequences are pointing to a wrong source
139 // location which is not severe. This is a vector instead of an actual map
140 // because we optimize for time building this map rather than time
141 // retrieving an entry, as backend diagnostics are uncommon.
142 std::vector
<std::pair
<llvm::hash_code
, FullSourceLoc
>>
143 ManglingFullSourceLocs
;
145 // This is here so that the diagnostic printer knows the module a diagnostic
147 llvm::Module
*CurLinkModule
= nullptr;
150 BackendConsumer(BackendAction Action
, DiagnosticsEngine
&Diags
,
151 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
,
152 const HeaderSearchOptions
&HeaderSearchOpts
,
153 const PreprocessorOptions
&PPOpts
,
154 const CodeGenOptions
&CodeGenOpts
,
155 const TargetOptions
&TargetOpts
,
156 const LangOptions
&LangOpts
, const std::string
&InFile
,
157 SmallVector
<LinkModule
, 4> LinkModules
,
158 std::unique_ptr
<raw_pwrite_stream
> OS
, LLVMContext
&C
,
159 CoverageSourceInfo
*CoverageInfo
= nullptr)
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),
165 Gen(CreateLLVMCodeGen(Diags
, InFile
, std::move(VFS
), HeaderSearchOpts
,
166 PPOpts
, CodeGenOpts
, C
, CoverageInfo
)),
167 LinkModules(std::move(LinkModules
)) {
168 TimerIsEnabled
= CodeGenOpts
.TimePasses
;
169 llvm::TimePassesIsEnabled
= CodeGenOpts
.TimePasses
;
170 llvm::TimePassesPerRun
= CodeGenOpts
.TimePassesPerRun
;
173 // This constructor is used in installing an empty BackendConsumer
174 // to use the clang diagnostic handler for IR input files. It avoids
175 // initializing the OS field.
176 BackendConsumer(BackendAction Action
, DiagnosticsEngine
&Diags
,
177 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
,
178 const HeaderSearchOptions
&HeaderSearchOpts
,
179 const PreprocessorOptions
&PPOpts
,
180 const CodeGenOptions
&CodeGenOpts
,
181 const TargetOptions
&TargetOpts
,
182 const LangOptions
&LangOpts
, llvm::Module
*Module
,
183 SmallVector
<LinkModule
, 4> LinkModules
, LLVMContext
&C
,
184 CoverageSourceInfo
*CoverageInfo
= nullptr)
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),
190 Gen(CreateLLVMCodeGen(Diags
, "", std::move(VFS
), HeaderSearchOpts
,
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(); }
198 std::unique_ptr
<llvm::Module
> takeModule() {
199 return std::unique_ptr
<llvm::Module
>(Gen
->ReleaseModule());
202 CodeGenerator
*getCodeGenerator() { return Gen
.get(); }
204 void HandleCXXStaticMemberVarInstantiation(VarDecl
*VD
) override
{
205 Gen
->HandleCXXStaticMemberVarInstantiation(VD
);
208 void Initialize(ASTContext
&Ctx
) override
{
209 assert(!Context
&& "initialized multiple times");
214 LLVMIRGeneration
.startTimer();
216 Gen
->Initialize(Ctx
);
219 LLVMIRGeneration
.stopTimer();
222 bool HandleTopLevelDecl(DeclGroupRef D
) override
{
223 PrettyStackTraceDecl
CrashInfo(*D
.begin(), SourceLocation(),
224 Context
->getSourceManager(),
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();
245 void HandleInlineFunctionDefinition(FunctionDecl
*D
) override
{
246 PrettyStackTraceDecl
CrashInfo(D
, SourceLocation(),
247 Context
->getSourceManager(),
248 "LLVM IR generation of inline function");
250 LLVMIRGeneration
.startTimer();
252 Gen
->HandleInlineFunctionDefinition(D
);
255 LLVMIRGeneration
.stopTimer();
258 void HandleInterestingDecl(DeclGroupRef D
) override
{
259 // Ignore interesting decls from the AST reader after IRGen is finished.
261 HandleTopLevelDecl(D
);
264 // Links each entry in LinkModules into our module. Returns true on error.
265 bool LinkInModules() {
266 for (auto &LM
: LinkModules
) {
267 assert(LM
.Module
&& "LinkModule does not actually have a module");
268 if (LM
.PropagateAttrs
)
269 for (Function
&F
: *LM
.Module
) {
270 // Skip intrinsics. Keep consistent with how intrinsics are created
274 Gen
->CGM().mergeDefaultFunctionDefinitionAttributes(F
,
278 CurLinkModule
= LM
.Module
.get();
281 if (LM
.Internalize
) {
282 Err
= Linker::linkModules(
283 *getModule(), std::move(LM
.Module
), LM
.LinkFlags
,
284 [](llvm::Module
&M
, const llvm::StringSet
<> &GVS
) {
285 internalizeModule(M
, [&GVS
](const llvm::GlobalValue
&GV
) {
286 return !GV
.hasName() || (GVS
.count(GV
.getName()) == 0);
290 Err
= Linker::linkModules(*getModule(), std::move(LM
.Module
),
298 return false; // success
301 void HandleTranslationUnit(ASTContext
&C
) override
{
303 llvm::TimeTraceScope
TimeScope("Frontend");
304 PrettyStackTraceString
CrashInfo("Per-file LLVM IR generation");
305 if (TimerIsEnabled
) {
306 LLVMIRGenerationRefCount
+= 1;
307 if (LLVMIRGenerationRefCount
== 1)
308 LLVMIRGeneration
.startTimer();
311 Gen
->HandleTranslationUnit(C
);
313 if (TimerIsEnabled
) {
314 LLVMIRGenerationRefCount
-= 1;
315 if (LLVMIRGenerationRefCount
== 0)
316 LLVMIRGeneration
.stopTimer();
319 IRGenFinished
= true;
322 // Silently ignore if we weren't initialized for some reason.
326 LLVMContext
&Ctx
= getModule()->getContext();
327 std::unique_ptr
<DiagnosticHandler
> OldDiagnosticHandler
=
328 Ctx
.getDiagnosticHandler();
329 Ctx
.setDiagnosticHandler(std::make_unique
<ClangDiagnosticHandler
>(
332 Expected
<std::unique_ptr
<llvm::ToolOutputFile
>> OptRecordFileOrErr
=
333 setupLLVMOptimizationRemarks(
334 Ctx
, CodeGenOpts
.OptRecordFile
, CodeGenOpts
.OptRecordPasses
,
335 CodeGenOpts
.OptRecordFormat
, CodeGenOpts
.DiagnosticsWithHotness
,
336 CodeGenOpts
.DiagnosticsHotnessThreshold
);
338 if (Error E
= OptRecordFileOrErr
.takeError()) {
339 reportOptRecordError(std::move(E
), Diags
, CodeGenOpts
);
343 std::unique_ptr
<llvm::ToolOutputFile
> OptRecordFile
=
344 std::move(*OptRecordFileOrErr
);
347 CodeGenOpts
.getProfileUse() != CodeGenOptions::ProfileNone
)
348 Ctx
.setDiagnosticsHotnessRequested(true);
350 if (CodeGenOpts
.MisExpect
) {
351 Ctx
.setMisExpectWarningRequested(true);
354 if (CodeGenOpts
.DiagnosticsMisExpectTolerance
) {
355 Ctx
.setDiagnosticsMisExpectTolerance(
356 CodeGenOpts
.DiagnosticsMisExpectTolerance
);
359 // Link each LinkModule into our module.
363 for (auto &F
: getModule()->functions()) {
364 if (const Decl
*FD
= Gen
->GetDeclForMangledName(F
.getName())) {
365 auto Loc
= FD
->getASTContext().getFullLoc(FD
->getLocation());
366 // TODO: use a fast content hash when available.
367 auto NameHash
= llvm::hash_value(F
.getName());
368 ManglingFullSourceLocs
.push_back(std::make_pair(NameHash
, Loc
));
372 if (CodeGenOpts
.ClearASTBeforeBackend
) {
373 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
374 // Access to the AST is no longer available after this.
375 // Other things that the ASTContext manages are still available, e.g.
376 // the SourceManager. It'd be nice if we could separate out all the
377 // things in ASTContext used after this point and null out the
378 // ASTContext, but too many various parts of the ASTContext are still
379 // used in various parts.
381 C
.getAllocator().Reset();
384 EmbedBitcode(getModule(), CodeGenOpts
, llvm::MemoryBufferRef());
386 EmitBackendOutput(Diags
, HeaderSearchOpts
, CodeGenOpts
, TargetOpts
,
387 LangOpts
, C
.getTargetInfo().getDataLayoutString(),
388 getModule(), Action
, FS
, std::move(AsmOutStream
));
390 Ctx
.setDiagnosticHandler(std::move(OldDiagnosticHandler
));
393 OptRecordFile
->keep();
396 void HandleTagDeclDefinition(TagDecl
*D
) override
{
397 PrettyStackTraceDecl
CrashInfo(D
, SourceLocation(),
398 Context
->getSourceManager(),
399 "LLVM IR generation of declaration");
400 Gen
->HandleTagDeclDefinition(D
);
403 void HandleTagDeclRequiredDefinition(const TagDecl
*D
) override
{
404 Gen
->HandleTagDeclRequiredDefinition(D
);
407 void CompleteTentativeDefinition(VarDecl
*D
) override
{
408 Gen
->CompleteTentativeDefinition(D
);
411 void CompleteExternalDeclaration(VarDecl
*D
) override
{
412 Gen
->CompleteExternalDeclaration(D
);
415 void AssignInheritanceModel(CXXRecordDecl
*RD
) override
{
416 Gen
->AssignInheritanceModel(RD
);
419 void HandleVTable(CXXRecordDecl
*RD
) override
{
420 Gen
->HandleVTable(RD
);
423 /// Get the best possible source location to represent a diagnostic that
424 /// may have associated debug info.
426 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase
&D
,
427 bool &BadDebugInfo
, StringRef
&Filename
,
428 unsigned &Line
, unsigned &Column
) const;
430 std::optional
<FullSourceLoc
>
431 getFunctionSourceLocation(const Function
&F
) const;
433 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo
&DI
);
434 /// Specialized handler for InlineAsm diagnostic.
435 /// \return True if the diagnostic has been successfully reported, false
437 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm
&D
);
438 /// Specialized handler for diagnostics reported using SMDiagnostic.
439 void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr
&D
);
440 /// Specialized handler for StackSize diagnostic.
441 /// \return True if the diagnostic has been successfully reported, false
443 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize
&D
);
444 /// Specialized handler for ResourceLimit diagnostic.
445 /// \return True if the diagnostic has been successfully reported, false
447 bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit
&D
);
449 /// Specialized handler for unsupported backend feature diagnostic.
450 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported
&D
);
451 /// Specialized handlers for optimization remarks.
452 /// Note that these handlers only accept remarks and they always handle
454 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase
&D
,
457 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase
&D
);
458 void OptimizationRemarkHandler(
459 const llvm::OptimizationRemarkAnalysisFPCommute
&D
);
460 void OptimizationRemarkHandler(
461 const llvm::OptimizationRemarkAnalysisAliasing
&D
);
462 void OptimizationFailureHandler(
463 const llvm::DiagnosticInfoOptimizationFailure
&D
);
464 void DontCallDiagHandler(const DiagnosticInfoDontCall
&D
);
465 /// Specialized handler for misexpect warnings.
466 /// Note that misexpect remarks are emitted through ORE
467 void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect
&D
);
470 void BackendConsumer::anchor() {}
473 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo
&DI
) {
474 BackendCon
->DiagnosticHandlerImpl(DI
);
478 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
479 /// buffer to be a valid FullSourceLoc.
480 static FullSourceLoc
ConvertBackendLocation(const llvm::SMDiagnostic
&D
,
481 SourceManager
&CSM
) {
482 // Get both the clang and llvm source managers. The location is relative to
483 // a memory buffer that the LLVM Source Manager is handling, we need to add
484 // a copy to the Clang source manager.
485 const llvm::SourceMgr
&LSM
= *D
.getSourceMgr();
487 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
488 // already owns its one and clang::SourceManager wants to own its one.
489 const MemoryBuffer
*LBuf
=
490 LSM
.getMemoryBuffer(LSM
.FindBufferContainingLoc(D
.getLoc()));
492 // Create the copy and transfer ownership to clang::SourceManager.
493 // TODO: Avoid copying files into memory.
494 std::unique_ptr
<llvm::MemoryBuffer
> CBuf
=
495 llvm::MemoryBuffer::getMemBufferCopy(LBuf
->getBuffer(),
496 LBuf
->getBufferIdentifier());
497 // FIXME: Keep a file ID map instead of creating new IDs for each location.
498 FileID FID
= CSM
.createFileID(std::move(CBuf
));
500 // Translate the offset into the file.
501 unsigned Offset
= D
.getLoc().getPointer() - LBuf
->getBufferStart();
502 SourceLocation NewLoc
=
503 CSM
.getLocForStartOfFile(FID
).getLocWithOffset(Offset
);
504 return FullSourceLoc(NewLoc
, CSM
);
507 #define ComputeDiagID(Severity, GroupName, DiagID) \
509 switch (Severity) { \
510 case llvm::DS_Error: \
511 DiagID = diag::err_fe_##GroupName; \
513 case llvm::DS_Warning: \
514 DiagID = diag::warn_fe_##GroupName; \
516 case llvm::DS_Remark: \
517 llvm_unreachable("'remark' severity not expected"); \
519 case llvm::DS_Note: \
520 DiagID = diag::note_fe_##GroupName; \
525 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
527 switch (Severity) { \
528 case llvm::DS_Error: \
529 DiagID = diag::err_fe_##GroupName; \
531 case llvm::DS_Warning: \
532 DiagID = diag::warn_fe_##GroupName; \
534 case llvm::DS_Remark: \
535 DiagID = diag::remark_fe_##GroupName; \
537 case llvm::DS_Note: \
538 DiagID = diag::note_fe_##GroupName; \
543 void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr
&DI
) {
544 const llvm::SMDiagnostic
&D
= DI
.getSMDiag();
547 if (DI
.isInlineAsmDiag())
548 ComputeDiagID(DI
.getSeverity(), inline_asm
, DiagID
);
550 ComputeDiagID(DI
.getSeverity(), source_mgr
, DiagID
);
552 // This is for the empty BackendConsumer that uses the clang diagnostic
553 // handler for IR input files.
555 D
.print(nullptr, llvm::errs());
556 Diags
.Report(DiagID
).AddString("cannot compile inline asm");
560 // There are a couple of different kinds of errors we could get here.
561 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
563 // Strip "error: " off the start of the message string.
564 StringRef Message
= D
.getMessage();
565 (void)Message
.consume_front("error: ");
567 // If the SMDiagnostic has an inline asm source location, translate it.
569 if (D
.getLoc() != SMLoc())
570 Loc
= ConvertBackendLocation(D
, Context
->getSourceManager());
572 // If this problem has clang-level source location information, report the
573 // issue in the source with a note showing the instantiated
575 if (DI
.isInlineAsmDiag()) {
576 SourceLocation LocCookie
=
577 SourceLocation::getFromRawEncoding(DI
.getLocCookie());
578 if (LocCookie
.isValid()) {
579 Diags
.Report(LocCookie
, DiagID
).AddString(Message
);
581 if (D
.getLoc().isValid()) {
582 DiagnosticBuilder B
= Diags
.Report(Loc
, diag::note_fe_inline_asm_here
);
583 // Convert the SMDiagnostic ranges into SourceRange and attach them
584 // to the diagnostic.
585 for (const std::pair
<unsigned, unsigned> &Range
: D
.getRanges()) {
586 unsigned Column
= D
.getColumnNo();
587 B
<< SourceRange(Loc
.getLocWithOffset(Range
.first
- Column
),
588 Loc
.getLocWithOffset(Range
.second
- Column
));
595 // Otherwise, report the backend issue as occurring in the generated .s file.
596 // If Loc is invalid, we still need to report the issue, it just gets no
598 Diags
.Report(Loc
, DiagID
).AddString(Message
);
602 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm
&D
) {
604 ComputeDiagID(D
.getSeverity(), inline_asm
, DiagID
);
605 std::string Message
= D
.getMsgStr().str();
607 // If this problem has clang-level source location information, report the
608 // issue as being a problem in the source with a note showing the instantiated
610 SourceLocation LocCookie
=
611 SourceLocation::getFromRawEncoding(D
.getLocCookie());
612 if (LocCookie
.isValid())
613 Diags
.Report(LocCookie
, DiagID
).AddString(Message
);
615 // Otherwise, report the backend diagnostic as occurring in the generated
617 // If Loc is invalid, we still need to report the diagnostic, it just gets
620 Diags
.Report(Loc
, DiagID
).AddString(Message
);
622 // We handled all the possible severities.
627 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize
&D
) {
628 if (D
.getSeverity() != llvm::DS_Warning
)
629 // For now, the only support we have for StackSize diagnostic is warning.
630 // We do not know how to format other severities.
633 auto Loc
= getFunctionSourceLocation(D
.getFunction());
637 Diags
.Report(*Loc
, diag::warn_fe_frame_larger_than
)
638 << D
.getStackSize() << D
.getStackLimit()
639 << llvm::demangle(D
.getFunction().getName());
643 bool BackendConsumer::ResourceLimitDiagHandler(
644 const llvm::DiagnosticInfoResourceLimit
&D
) {
645 auto Loc
= getFunctionSourceLocation(D
.getFunction());
648 unsigned DiagID
= diag::err_fe_backend_resource_limit
;
649 ComputeDiagID(D
.getSeverity(), backend_resource_limit
, DiagID
);
651 Diags
.Report(*Loc
, DiagID
)
652 << D
.getResourceName() << D
.getResourceSize() << D
.getResourceLimit()
653 << llvm::demangle(D
.getFunction().getName());
657 const FullSourceLoc
BackendConsumer::getBestLocationFromDebugLoc(
658 const llvm::DiagnosticInfoWithLocationBase
&D
, bool &BadDebugInfo
,
659 StringRef
&Filename
, unsigned &Line
, unsigned &Column
) const {
660 SourceManager
&SourceMgr
= Context
->getSourceManager();
661 FileManager
&FileMgr
= SourceMgr
.getFileManager();
662 SourceLocation DILoc
;
664 if (D
.isLocationAvailable()) {
665 D
.getLocation(Filename
, Line
, Column
);
667 auto FE
= FileMgr
.getFile(Filename
);
669 FE
= FileMgr
.getFile(D
.getAbsolutePath());
671 // If -gcolumn-info was not used, Column will be 0. This upsets the
672 // source manager, so pass 1 if Column is not set.
673 DILoc
= SourceMgr
.translateFileLineCol(*FE
, Line
, Column
? Column
: 1);
676 BadDebugInfo
= DILoc
.isInvalid();
679 // If a location isn't available, try to approximate it using the associated
680 // function definition. We use the definition's right brace to differentiate
681 // from diagnostics that genuinely relate to the function itself.
682 FullSourceLoc
Loc(DILoc
, SourceMgr
);
683 if (Loc
.isInvalid()) {
684 if (auto MaybeLoc
= getFunctionSourceLocation(D
.getFunction()))
688 if (DILoc
.isInvalid() && D
.isLocationAvailable())
689 // If we were not able to translate the file:line:col information
690 // back to a SourceLocation, at least emit a note stating that
691 // we could not translate this location. This can happen in the
692 // case of #line directives.
693 Diags
.Report(Loc
, diag::note_fe_backend_invalid_loc
)
694 << Filename
<< Line
<< Column
;
699 std::optional
<FullSourceLoc
>
700 BackendConsumer::getFunctionSourceLocation(const Function
&F
) const {
701 auto Hash
= llvm::hash_value(F
.getName());
702 for (const auto &Pair
: ManglingFullSourceLocs
) {
703 if (Pair
.first
== Hash
)
709 void BackendConsumer::UnsupportedDiagHandler(
710 const llvm::DiagnosticInfoUnsupported
&D
) {
711 // We only support warnings or errors.
712 assert(D
.getSeverity() == llvm::DS_Error
||
713 D
.getSeverity() == llvm::DS_Warning
);
716 unsigned Line
, Column
;
717 bool BadDebugInfo
= false;
720 raw_string_ostream
MsgStream(Msg
);
722 // Context will be nullptr for IR input files, we will construct the diag
723 // message from llvm::DiagnosticInfoUnsupported.
724 if (Context
!= nullptr) {
725 Loc
= getBestLocationFromDebugLoc(D
, BadDebugInfo
, Filename
, Line
, Column
);
726 MsgStream
<< D
.getMessage();
728 DiagnosticPrinterRawOStream
DP(MsgStream
);
732 auto DiagType
= D
.getSeverity() == llvm::DS_Error
733 ? diag::err_fe_backend_unsupported
734 : diag::warn_fe_backend_unsupported
;
735 Diags
.Report(Loc
, DiagType
) << MsgStream
.str();
738 // If we were not able to translate the file:line:col information
739 // back to a SourceLocation, at least emit a note stating that
740 // we could not translate this location. This can happen in the
741 // case of #line directives.
742 Diags
.Report(Loc
, diag::note_fe_backend_invalid_loc
)
743 << Filename
<< Line
<< Column
;
746 void BackendConsumer::EmitOptimizationMessage(
747 const llvm::DiagnosticInfoOptimizationBase
&D
, unsigned DiagID
) {
748 // We only support warnings and remarks.
749 assert(D
.getSeverity() == llvm::DS_Remark
||
750 D
.getSeverity() == llvm::DS_Warning
);
753 unsigned Line
, Column
;
754 bool BadDebugInfo
= false;
757 raw_string_ostream
MsgStream(Msg
);
759 // Context will be nullptr for IR input files, we will construct the remark
760 // message from llvm::DiagnosticInfoOptimizationBase.
761 if (Context
!= nullptr) {
762 Loc
= getBestLocationFromDebugLoc(D
, BadDebugInfo
, Filename
, Line
, Column
);
763 MsgStream
<< D
.getMsg();
765 DiagnosticPrinterRawOStream
DP(MsgStream
);
770 MsgStream
<< " (hotness: " << *D
.getHotness() << ")";
772 Diags
.Report(Loc
, DiagID
)
773 << AddFlagValue(D
.getPassName())
777 // If we were not able to translate the file:line:col information
778 // back to a SourceLocation, at least emit a note stating that
779 // we could not translate this location. This can happen in the
780 // case of #line directives.
781 Diags
.Report(Loc
, diag::note_fe_backend_invalid_loc
)
782 << Filename
<< Line
<< Column
;
785 void BackendConsumer::OptimizationRemarkHandler(
786 const llvm::DiagnosticInfoOptimizationBase
&D
) {
787 // Without hotness information, don't show noisy remarks.
788 if (D
.isVerbose() && !D
.getHotness())
792 // Optimization remarks are active only if the -Rpass flag has a regular
793 // expression that matches the name of the pass name in \p D.
794 if (CodeGenOpts
.OptimizationRemark
.patternMatches(D
.getPassName()))
795 EmitOptimizationMessage(D
, diag::remark_fe_backend_optimization_remark
);
796 } else if (D
.isMissed()) {
797 // Missed optimization remarks are active only if the -Rpass-missed
798 // flag has a regular expression that matches the name of the pass
800 if (CodeGenOpts
.OptimizationRemarkMissed
.patternMatches(D
.getPassName()))
801 EmitOptimizationMessage(
802 D
, diag::remark_fe_backend_optimization_remark_missed
);
804 assert(D
.isAnalysis() && "Unknown remark type");
806 bool ShouldAlwaysPrint
= false;
807 if (auto *ORA
= dyn_cast
<llvm::OptimizationRemarkAnalysis
>(&D
))
808 ShouldAlwaysPrint
= ORA
->shouldAlwaysPrint();
810 if (ShouldAlwaysPrint
||
811 CodeGenOpts
.OptimizationRemarkAnalysis
.patternMatches(D
.getPassName()))
812 EmitOptimizationMessage(
813 D
, diag::remark_fe_backend_optimization_remark_analysis
);
817 void BackendConsumer::OptimizationRemarkHandler(
818 const llvm::OptimizationRemarkAnalysisFPCommute
&D
) {
819 // Optimization analysis remarks are active if the pass name is set to
820 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
821 // regular expression that matches the name of the pass name in \p D.
823 if (D
.shouldAlwaysPrint() ||
824 CodeGenOpts
.OptimizationRemarkAnalysis
.patternMatches(D
.getPassName()))
825 EmitOptimizationMessage(
826 D
, diag::remark_fe_backend_optimization_remark_analysis_fpcommute
);
829 void BackendConsumer::OptimizationRemarkHandler(
830 const llvm::OptimizationRemarkAnalysisAliasing
&D
) {
831 // Optimization analysis remarks are active if the pass name is set to
832 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
833 // regular expression that matches the name of the pass name in \p D.
835 if (D
.shouldAlwaysPrint() ||
836 CodeGenOpts
.OptimizationRemarkAnalysis
.patternMatches(D
.getPassName()))
837 EmitOptimizationMessage(
838 D
, diag::remark_fe_backend_optimization_remark_analysis_aliasing
);
841 void BackendConsumer::OptimizationFailureHandler(
842 const llvm::DiagnosticInfoOptimizationFailure
&D
) {
843 EmitOptimizationMessage(D
, diag::warn_fe_backend_optimization_failure
);
846 void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall
&D
) {
847 SourceLocation LocCookie
=
848 SourceLocation::getFromRawEncoding(D
.getLocCookie());
850 // FIXME: we can't yet diagnose indirect calls. When/if we can, we
851 // should instead assert that LocCookie.isValid().
852 if (!LocCookie
.isValid())
855 Diags
.Report(LocCookie
, D
.getSeverity() == DiagnosticSeverity::DS_Error
856 ? diag::err_fe_backend_error_attr
857 : diag::warn_fe_backend_warning_attr
)
858 << llvm::demangle(D
.getFunctionName()) << D
.getNote();
861 void BackendConsumer::MisExpectDiagHandler(
862 const llvm::DiagnosticInfoMisExpect
&D
) {
864 unsigned Line
, Column
;
865 bool BadDebugInfo
= false;
867 getBestLocationFromDebugLoc(D
, BadDebugInfo
, Filename
, Line
, Column
);
869 Diags
.Report(Loc
, diag::warn_profile_data_misexpect
) << D
.getMsg().str();
872 // If we were not able to translate the file:line:col information
873 // back to a SourceLocation, at least emit a note stating that
874 // we could not translate this location. This can happen in the
875 // case of #line directives.
876 Diags
.Report(Loc
, diag::note_fe_backend_invalid_loc
)
877 << Filename
<< Line
<< Column
;
880 /// This function is invoked when the backend needs
881 /// to report something to the user.
882 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo
&DI
) {
883 unsigned DiagID
= diag::err_fe_inline_asm
;
884 llvm::DiagnosticSeverity Severity
= DI
.getSeverity();
885 // Get the diagnostic ID based.
886 switch (DI
.getKind()) {
887 case llvm::DK_InlineAsm
:
888 if (InlineAsmDiagHandler(cast
<DiagnosticInfoInlineAsm
>(DI
)))
890 ComputeDiagID(Severity
, inline_asm
, DiagID
);
892 case llvm::DK_SrcMgr
:
893 SrcMgrDiagHandler(cast
<DiagnosticInfoSrcMgr
>(DI
));
895 case llvm::DK_StackSize
:
896 if (StackSizeDiagHandler(cast
<DiagnosticInfoStackSize
>(DI
)))
898 ComputeDiagID(Severity
, backend_frame_larger_than
, DiagID
);
900 case llvm::DK_ResourceLimit
:
901 if (ResourceLimitDiagHandler(cast
<DiagnosticInfoResourceLimit
>(DI
)))
903 ComputeDiagID(Severity
, backend_resource_limit
, DiagID
);
906 ComputeDiagID(Severity
, linking_module
, DiagID
);
908 case llvm::DK_OptimizationRemark
:
909 // Optimization remarks are always handled completely by this
910 // handler. There is no generic way of emitting them.
911 OptimizationRemarkHandler(cast
<OptimizationRemark
>(DI
));
913 case llvm::DK_OptimizationRemarkMissed
:
914 // Optimization remarks are always handled completely by this
915 // handler. There is no generic way of emitting them.
916 OptimizationRemarkHandler(cast
<OptimizationRemarkMissed
>(DI
));
918 case llvm::DK_OptimizationRemarkAnalysis
:
919 // Optimization remarks are always handled completely by this
920 // handler. There is no generic way of emitting them.
921 OptimizationRemarkHandler(cast
<OptimizationRemarkAnalysis
>(DI
));
923 case llvm::DK_OptimizationRemarkAnalysisFPCommute
:
924 // Optimization remarks are always handled completely by this
925 // handler. There is no generic way of emitting them.
926 OptimizationRemarkHandler(cast
<OptimizationRemarkAnalysisFPCommute
>(DI
));
928 case llvm::DK_OptimizationRemarkAnalysisAliasing
:
929 // Optimization remarks are always handled completely by this
930 // handler. There is no generic way of emitting them.
931 OptimizationRemarkHandler(cast
<OptimizationRemarkAnalysisAliasing
>(DI
));
933 case llvm::DK_MachineOptimizationRemark
:
934 // Optimization remarks are always handled completely by this
935 // handler. There is no generic way of emitting them.
936 OptimizationRemarkHandler(cast
<MachineOptimizationRemark
>(DI
));
938 case llvm::DK_MachineOptimizationRemarkMissed
:
939 // Optimization remarks are always handled completely by this
940 // handler. There is no generic way of emitting them.
941 OptimizationRemarkHandler(cast
<MachineOptimizationRemarkMissed
>(DI
));
943 case llvm::DK_MachineOptimizationRemarkAnalysis
:
944 // Optimization remarks are always handled completely by this
945 // handler. There is no generic way of emitting them.
946 OptimizationRemarkHandler(cast
<MachineOptimizationRemarkAnalysis
>(DI
));
948 case llvm::DK_OptimizationFailure
:
949 // Optimization failures are always handled completely by this
951 OptimizationFailureHandler(cast
<DiagnosticInfoOptimizationFailure
>(DI
));
953 case llvm::DK_Unsupported
:
954 UnsupportedDiagHandler(cast
<DiagnosticInfoUnsupported
>(DI
));
956 case llvm::DK_DontCall
:
957 DontCallDiagHandler(cast
<DiagnosticInfoDontCall
>(DI
));
959 case llvm::DK_MisExpect
:
960 MisExpectDiagHandler(cast
<DiagnosticInfoMisExpect
>(DI
));
963 // Plugin IDs are not bound to any value as they are set dynamically.
964 ComputeDiagRemarkID(Severity
, backend_plugin
, DiagID
);
967 std::string MsgStorage
;
969 raw_string_ostream
Stream(MsgStorage
);
970 DiagnosticPrinterRawOStream
DP(Stream
);
974 if (DI
.getKind() == DK_Linker
) {
975 assert(CurLinkModule
&& "CurLinkModule must be set for linker diagnostics");
976 Diags
.Report(DiagID
) << CurLinkModule
->getModuleIdentifier() << MsgStorage
;
980 // Report the backend message using the usual diagnostic mechanism.
982 Diags
.Report(Loc
, DiagID
).AddString(MsgStorage
);
986 CodeGenAction::CodeGenAction(unsigned _Act
, LLVMContext
*_VMContext
)
987 : Act(_Act
), VMContext(_VMContext
? _VMContext
: new LLVMContext
),
988 OwnsVMContext(!_VMContext
) {}
990 CodeGenAction::~CodeGenAction() {
996 bool CodeGenAction::hasIRSupport() const { return true; }
998 void CodeGenAction::EndSourceFileAction() {
999 // If the consumer creation failed, do nothing.
1000 if (!getCompilerInstance().hasASTConsumer())
1003 // Steal the module from the consumer.
1004 TheModule
= BEConsumer
->takeModule();
1007 std::unique_ptr
<llvm::Module
> CodeGenAction::takeModule() {
1008 return std::move(TheModule
);
1011 llvm::LLVMContext
*CodeGenAction::takeLLVMContext() {
1012 OwnsVMContext
= false;
1016 CodeGenerator
*CodeGenAction::getCodeGenerator() const {
1017 return BEConsumer
->getCodeGenerator();
1020 static std::unique_ptr
<raw_pwrite_stream
>
1021 GetOutputStream(CompilerInstance
&CI
, StringRef InFile
, BackendAction Action
) {
1023 case Backend_EmitAssembly
:
1024 return CI
.createDefaultOutputFile(false, InFile
, "s");
1025 case Backend_EmitLL
:
1026 return CI
.createDefaultOutputFile(false, InFile
, "ll");
1027 case Backend_EmitBC
:
1028 return CI
.createDefaultOutputFile(true, InFile
, "bc");
1029 case Backend_EmitNothing
:
1031 case Backend_EmitMCNull
:
1032 return CI
.createNullOutputFile();
1033 case Backend_EmitObj
:
1034 return CI
.createDefaultOutputFile(true, InFile
, "o");
1037 llvm_unreachable("Invalid action!");
1040 std::unique_ptr
<ASTConsumer
>
1041 CodeGenAction::CreateASTConsumer(CompilerInstance
&CI
, StringRef InFile
) {
1042 BackendAction BA
= static_cast<BackendAction
>(Act
);
1043 std::unique_ptr
<raw_pwrite_stream
> OS
= CI
.takeOutputStream();
1045 OS
= GetOutputStream(CI
, InFile
, BA
);
1047 if (BA
!= Backend_EmitNothing
&& !OS
)
1050 // Load bitcode modules to link with, if we need to.
1051 if (LinkModules
.empty())
1052 for (const CodeGenOptions::BitcodeFileToLink
&F
:
1053 CI
.getCodeGenOpts().LinkBitcodeFiles
) {
1054 auto BCBuf
= CI
.getFileManager().getBufferForFile(F
.Filename
);
1056 CI
.getDiagnostics().Report(diag::err_cannot_open_file
)
1057 << F
.Filename
<< BCBuf
.getError().message();
1058 LinkModules
.clear();
1062 Expected
<std::unique_ptr
<llvm::Module
>> ModuleOrErr
=
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
});
1076 CoverageSourceInfo
*CoverageInfo
= nullptr;
1077 // Add the preprocessor callback only when the coverage mapping is generated.
1078 if (CI
.getCodeGenOpts().CoverageMapping
)
1079 CoverageInfo
= CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
1080 CI
.getPreprocessor());
1082 std::unique_ptr
<BackendConsumer
> Result(new BackendConsumer(
1083 BA
, CI
.getDiagnostics(), &CI
.getVirtualFileSystem(),
1084 CI
.getHeaderSearchOpts(), CI
.getPreprocessorOpts(), CI
.getCodeGenOpts(),
1085 CI
.getTargetOpts(), CI
.getLangOpts(), std::string(InFile
),
1086 std::move(LinkModules
), std::move(OS
), *VMContext
, CoverageInfo
));
1087 BEConsumer
= Result
.get();
1089 // Enable generating macro debug info only when debug info is not disabled and
1090 // also macro debug info is enabled.
1091 if (CI
.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo
&&
1092 CI
.getCodeGenOpts().MacroDebugInfo
) {
1093 std::unique_ptr
<PPCallbacks
> Callbacks
=
1094 std::make_unique
<MacroPPCallbacks
>(BEConsumer
->getCodeGenerator(),
1095 CI
.getPreprocessor());
1096 CI
.getPreprocessor().addPPCallbacks(std::move(Callbacks
));
1099 return std::move(Result
);
1102 std::unique_ptr
<llvm::Module
>
1103 CodeGenAction::loadModule(MemoryBufferRef MBRef
) {
1104 CompilerInstance
&CI
= getCompilerInstance();
1105 SourceManager
&SM
= CI
.getSourceManager();
1107 // For ThinLTO backend invocations, ensure that the context
1108 // merges types based on ODR identifiers. We also need to read
1109 // the correct module out of a multi-module bitcode file.
1110 if (!CI
.getCodeGenOpts().ThinLTOIndexFile
.empty()) {
1111 VMContext
->enableDebugTypeODRUniquing();
1113 auto DiagErrors
= [&](Error E
) -> std::unique_ptr
<llvm::Module
> {
1115 CI
.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error
, "%0");
1116 handleAllErrors(std::move(E
), [&](ErrorInfoBase
&EIB
) {
1117 CI
.getDiagnostics().Report(DiagID
) << EIB
.message();
1122 Expected
<std::vector
<BitcodeModule
>> BMsOrErr
= getBitcodeModuleList(MBRef
);
1124 return DiagErrors(BMsOrErr
.takeError());
1125 BitcodeModule
*Bm
= llvm::lto::findThinLTOModule(*BMsOrErr
);
1126 // We have nothing to do if the file contains no ThinLTO module. This is
1127 // possible if ThinLTO compilation was not able to split module. Content of
1128 // the file was already processed by indexing and will be passed to the
1129 // linker using merged object file.
1131 auto M
= std::make_unique
<llvm::Module
>("empty", *VMContext
);
1132 M
->setTargetTriple(CI
.getTargetOpts().Triple
);
1135 Expected
<std::unique_ptr
<llvm::Module
>> MOrErr
=
1136 Bm
->parseModule(*VMContext
);
1138 return DiagErrors(MOrErr
.takeError());
1139 return std::move(*MOrErr
);
1142 llvm::SMDiagnostic Err
;
1143 if (std::unique_ptr
<llvm::Module
> M
= parseIR(MBRef
, Err
, *VMContext
))
1146 // Translate from the diagnostic info to the SourceManager location if
1148 // TODO: Unify this with ConvertBackendLocation()
1150 if (Err
.getLineNo() > 0) {
1151 assert(Err
.getColumnNo() >= 0);
1152 Loc
= SM
.translateFileLineCol(SM
.getFileEntryForID(SM
.getMainFileID()),
1153 Err
.getLineNo(), Err
.getColumnNo() + 1);
1156 // Strip off a leading diagnostic code if there is one.
1157 StringRef Msg
= Err
.getMessage();
1158 if (Msg
.startswith("error: "))
1159 Msg
= Msg
.substr(7);
1162 CI
.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error
, "%0");
1164 CI
.getDiagnostics().Report(Loc
, DiagID
) << Msg
;
1168 void CodeGenAction::ExecuteAction() {
1169 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR
) {
1170 this->ASTFrontendAction::ExecuteAction();
1174 // If this is an IR file, we have to treat it specially.
1175 BackendAction BA
= static_cast<BackendAction
>(Act
);
1176 CompilerInstance
&CI
= getCompilerInstance();
1177 auto &CodeGenOpts
= CI
.getCodeGenOpts();
1178 auto &Diagnostics
= CI
.getDiagnostics();
1179 std::unique_ptr
<raw_pwrite_stream
> OS
=
1180 GetOutputStream(CI
, getCurrentFileOrBufferName(), BA
);
1181 if (BA
!= Backend_EmitNothing
&& !OS
)
1184 SourceManager
&SM
= CI
.getSourceManager();
1185 FileID FID
= SM
.getMainFileID();
1186 std::optional
<MemoryBufferRef
> MainFile
= SM
.getBufferOrNone(FID
);
1190 TheModule
= loadModule(*MainFile
);
1194 const TargetOptions
&TargetOpts
= CI
.getTargetOpts();
1195 if (TheModule
->getTargetTriple() != TargetOpts
.Triple
) {
1196 Diagnostics
.Report(SourceLocation(), diag::warn_fe_override_module
)
1197 << TargetOpts
.Triple
;
1198 TheModule
->setTargetTriple(TargetOpts
.Triple
);
1201 EmbedObject(TheModule
.get(), CodeGenOpts
, Diagnostics
);
1202 EmbedBitcode(TheModule
.get(), CodeGenOpts
, *MainFile
);
1204 LLVMContext
&Ctx
= TheModule
->getContext();
1206 // Restore any diagnostic handler previously set before returning from this
1210 std::unique_ptr
<DiagnosticHandler
> PrevHandler
= Ctx
.getDiagnosticHandler();
1211 ~RAII() { Ctx
.setDiagnosticHandler(std::move(PrevHandler
)); }
1214 // Set clang diagnostic handler. To do this we need to create a fake
1216 BackendConsumer
Result(BA
, CI
.getDiagnostics(), &CI
.getVirtualFileSystem(),
1217 CI
.getHeaderSearchOpts(), CI
.getPreprocessorOpts(),
1218 CI
.getCodeGenOpts(), CI
.getTargetOpts(),
1219 CI
.getLangOpts(), TheModule
.get(),
1220 std::move(LinkModules
), *VMContext
, nullptr);
1221 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1222 // true here because the valued names are needed for reading textual IR.
1223 Ctx
.setDiscardValueNames(false);
1224 Ctx
.setDiagnosticHandler(
1225 std::make_unique
<ClangDiagnosticHandler
>(CodeGenOpts
, &Result
));
1227 Expected
<std::unique_ptr
<llvm::ToolOutputFile
>> OptRecordFileOrErr
=
1228 setupLLVMOptimizationRemarks(
1229 Ctx
, CodeGenOpts
.OptRecordFile
, CodeGenOpts
.OptRecordPasses
,
1230 CodeGenOpts
.OptRecordFormat
, CodeGenOpts
.DiagnosticsWithHotness
,
1231 CodeGenOpts
.DiagnosticsHotnessThreshold
);
1233 if (Error E
= OptRecordFileOrErr
.takeError()) {
1234 reportOptRecordError(std::move(E
), Diagnostics
, CodeGenOpts
);
1237 std::unique_ptr
<llvm::ToolOutputFile
> OptRecordFile
=
1238 std::move(*OptRecordFileOrErr
);
1241 Diagnostics
, CI
.getHeaderSearchOpts(), CodeGenOpts
, TargetOpts
,
1242 CI
.getLangOpts(), CI
.getTarget().getDataLayoutString(), TheModule
.get(),
1243 BA
, CI
.getFileManager().getVirtualFileSystemPtr(), std::move(OS
));
1245 OptRecordFile
->keep();
1250 void EmitAssemblyAction::anchor() { }
1251 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext
*_VMContext
)
1252 : CodeGenAction(Backend_EmitAssembly
, _VMContext
) {}
1254 void EmitBCAction::anchor() { }
1255 EmitBCAction::EmitBCAction(llvm::LLVMContext
*_VMContext
)
1256 : CodeGenAction(Backend_EmitBC
, _VMContext
) {}
1258 void EmitLLVMAction::anchor() { }
1259 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext
*_VMContext
)
1260 : CodeGenAction(Backend_EmitLL
, _VMContext
) {}
1262 void EmitLLVMOnlyAction::anchor() { }
1263 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext
*_VMContext
)
1264 : CodeGenAction(Backend_EmitNothing
, _VMContext
) {}
1266 void EmitCodeGenOnlyAction::anchor() { }
1267 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext
*_VMContext
)
1268 : CodeGenAction(Backend_EmitMCNull
, _VMContext
) {}
1270 void EmitObjAction::anchor() { }
1271 EmitObjAction::EmitObjAction(llvm::LLVMContext
*_VMContext
)
1272 : CodeGenAction(Backend_EmitObj
, _VMContext
) {}