1//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "clang/CodeGen/CodeGenAction.h"
10#include "BackendConsumer.h"
11#include "CGCall.h"
12#include "CodeGenModule.h"
13#include "CoverageMappingGen.h"
14#include "MacroPPCallbacks.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclGroup.h"
19#include "clang/Basic/DiagnosticFrontend.h"
20#include "clang/Basic/FileManager.h"
21#include "clang/Basic/LangStandard.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/CodeGen/BackendUtil.h"
25#include "clang/CodeGen/ModuleBuilder.h"
26#include "clang/Driver/DriverDiagnostic.h"
27#include "clang/Frontend/CompilerInstance.h"
28#include "clang/Frontend/MultiplexConsumer.h"
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Serialization/ASTWriter.h"
31#include "llvm/ADT/Hashing.h"
32#include "llvm/ADT/ScopeExit.h"
33#include "llvm/Bitcode/BitcodeReader.h"
34#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
35#include "llvm/Demangle/Demangle.h"
36#include "llvm/IR/DebugInfo.h"
37#include "llvm/IR/DiagnosticInfo.h"
38#include "llvm/IR/DiagnosticPrinter.h"
39#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/LLVMRemarkStreamer.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/PassTimingInfo.h"
44#include "llvm/IR/Verifier.h"
45#include "llvm/IRReader/IRReader.h"
46#include "llvm/LTO/LTOBackend.h"
47#include "llvm/Linker/Linker.h"
48#include "llvm/Pass.h"
49#include "llvm/Support/ManagedStatic.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Mutex.h"
52#include "llvm/Support/SourceMgr.h"
53#include "llvm/Support/TimeProfiler.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/ToolOutputFile.h"
56#include "llvm/Transforms/IPO/Internalize.h"
57#include "llvm/Transforms/Utils/Cloning.h"
58
59#include <optional>
60using namespace clang;
61using namespace llvm;
62
63#define DEBUG_TYPE "codegenaction"
64
65namespace {
66llvm::ManagedStatic<llvm::sys::SmartMutex<true>> TimePassesMutex;
67}
68
69namespace clang {
70class BackendConsumer;
71class ClangDiagnosticHandler final : public DiagnosticHandler {
72public:
73 ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
74 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
75
76 bool handleDiagnostics(const DiagnosticInfo &DI) override;
77
78 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
79 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(String: PassName);
80 }
81 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
82 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(String: PassName);
83 }
84 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
85 return CodeGenOpts.OptimizationRemark.patternMatches(String: PassName);
86 }
87
88 bool isAnyRemarkEnabled() const override {
89 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
90 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
91 CodeGenOpts.OptimizationRemark.hasValidPattern();
92 }
93
94private:
95 const CodeGenOptions &CodeGenOpts;
96 BackendConsumer *BackendCon;
97};
98
99static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
100 const CodeGenOptions &CodeGenOpts) {
101 handleAllErrors(
102 E: std::move(E),
103 Handlers: [&](const LLVMRemarkSetupFileError &E) {
104 Diags.Report(DiagID: diag::err_cannot_open_file)
105 << CodeGenOpts.OptRecordFile << E.message();
106 },
107 Handlers: [&](const LLVMRemarkSetupPatternError &E) {
108 Diags.Report(DiagID: diag::err_drv_optimization_remark_pattern)
109 << E.message() << CodeGenOpts.OptRecordPasses;
110 },
111 Handlers: [&](const LLVMRemarkSetupFormatError &E) {
112 Diags.Report(DiagID: diag::err_drv_optimization_remark_format)
113 << CodeGenOpts.OptRecordFormat;
114 });
115}
116
117BackendConsumer::BackendConsumer(CompilerInstance &CI, BackendAction Action,
118 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
119 LLVMContext &C,
120 SmallVector<LinkModule, 4> LinkModules,
121 StringRef InFile,
122 std::unique_ptr<raw_pwrite_stream> OS,
123 CoverageSourceInfo *CoverageInfo,
124 llvm::Module *CurLinkModule)
125 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
126 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
127 AsmOutStream(std::move(OS)), FS(VFS), Action(Action),
128 Gen(CreateLLVMCodeGen(CI, ModuleName: InFile, C, CoverageInfo)),
129 LinkModules(std::move(LinkModules)), CurLinkModule(CurLinkModule) {
130 TimerIsEnabled = CodeGenOpts.TimePasses;
131 {
132 llvm::sys::SmartScopedLock<true> Lock(*TimePassesMutex);
133 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
134 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
135 }
136 if (CodeGenOpts.TimePasses)
137 LLVMIRGeneration.init(TimerName: "irgen", TimerDescription: "LLVM IR generation", tg&: CI.getTimerGroup());
138}
139
140llvm::Module* BackendConsumer::getModule() const {
141 return Gen->GetModule();
142}
143
144std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
145 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
146}
147
148CodeGenerator* BackendConsumer::getCodeGenerator() {
149 return Gen.get();
150}
151
152void BackendConsumer::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
153 Gen->HandleCXXStaticMemberVarInstantiation(D: VD);
154}
155
156void BackendConsumer::Initialize(ASTContext &Ctx) {
157 assert(!Context && "initialized multiple times");
158
159 Context = &Ctx;
160
161 if (TimerIsEnabled)
162 LLVMIRGeneration.startTimer();
163
164 Gen->Initialize(Context&: Ctx);
165
166 if (TimerIsEnabled)
167 LLVMIRGeneration.stopTimer();
168}
169
170bool BackendConsumer::HandleTopLevelDecl(DeclGroupRef D) {
171 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
172 Context->getSourceManager(),
173 "LLVM IR generation of declaration");
174
175 // Recurse.
176 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
177 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
178
179 Gen->HandleTopLevelDecl(D);
180
181 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
182 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
183
184 return true;
185}
186
187void BackendConsumer::HandleInlineFunctionDefinition(FunctionDecl *D) {
188 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
189 Context->getSourceManager(),
190 "LLVM IR generation of inline function");
191 if (TimerIsEnabled)
192 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
193
194 Gen->HandleInlineFunctionDefinition(D);
195
196 if (TimerIsEnabled)
197 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
198}
199
200void BackendConsumer::HandleInterestingDecl(DeclGroupRef D) {
201 HandleTopLevelDecl(D);
202}
203
204// Links each entry in LinkModules into our module. Returns true on error.
205bool BackendConsumer::LinkInModules(llvm::Module *M) {
206 for (auto &LM : LinkModules) {
207 assert(LM.Module && "LinkModule does not actually have a module");
208
209 if (LM.PropagateAttrs)
210 for (Function &F : *LM.Module) {
211 // Skip intrinsics. Keep consistent with how intrinsics are created
212 // in LLVM IR.
213 if (F.isIntrinsic())
214 continue;
215 CodeGen::mergeDefaultFunctionDefinitionAttributes(
216 F, CodeGenOpts, LangOpts, TargetOpts, WillInternalize: LM.Internalize);
217 }
218
219 CurLinkModule = LM.Module.get();
220 bool Err;
221
222 if (LM.Internalize) {
223 Err = Linker::linkModules(
224 Dest&: *M, Src: std::move(LM.Module), Flags: LM.LinkFlags,
225 InternalizeCallback: [](llvm::Module &M, const llvm::StringSet<> &GVS) {
226 internalizeModule(TheModule&: M, MustPreserveGV: [&GVS](const llvm::GlobalValue &GV) {
227 return !GV.hasName() || (GVS.count(Key: GV.getName()) == 0);
228 });
229 });
230 } else
231 Err = Linker::linkModules(Dest&: *M, Src: std::move(LM.Module), Flags: LM.LinkFlags);
232
233 if (Err)
234 return true;
235 }
236
237 LinkModules.clear();
238 return false; // success
239}
240
241void BackendConsumer::HandleTranslationUnit(ASTContext &C) {
242 {
243 llvm::TimeTraceScope TimeScope("Frontend");
244 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
245 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
246 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
247
248 Gen->HandleTranslationUnit(Ctx&: C);
249
250 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
251 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
252 }
253
254 // Silently ignore if we weren't initialized for some reason.
255 if (!getModule())
256 return;
257
258 LLVMContext &Ctx = getModule()->getContext();
259 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
260 Ctx.getDiagnosticHandler();
261 llvm::scope_exit RestoreDiagnosticHandler(
262 [&]() { Ctx.setDiagnosticHandler(DH: std::move(OldDiagnosticHandler)); });
263 Ctx.setDiagnosticHandler(DH: std::make_unique<ClangDiagnosticHandler>(
264 args: CodeGenOpts, args: this));
265
266 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
267 Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: ","));
268
269 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
270 setupLLVMOptimizationRemarks(
271 Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses,
272 RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness,
273 RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold);
274
275 if (Error E = OptRecordFileOrErr.takeError()) {
276 reportOptRecordError(E: std::move(E), Diags, CodeGenOpts);
277 return;
278 }
279
280 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
281
282 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
283 llvm::driver::ProfileInstrKind::ProfileNone)
284 Ctx.setDiagnosticsHotnessRequested(true);
285
286 if (CodeGenOpts.MisExpect) {
287 Ctx.setMisExpectWarningRequested(true);
288 }
289
290 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
291 Ctx.setDiagnosticsMisExpectTolerance(
292 CodeGenOpts.DiagnosticsMisExpectTolerance);
293 }
294
295 // Link each LinkModule into our module.
296 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(M: getModule()))
297 return;
298
299 for (auto &F : getModule()->functions()) {
300 if (const Decl *FD = Gen->GetDeclForMangledName(MangledName: F.getName())) {
301 auto Loc = FD->getASTContext().getFullLoc(Loc: FD->getLocation());
302 // TODO: use a fast content hash when available.
303 auto NameHash = llvm::hash_value(S: F.getName());
304 ManglingFullSourceLocs.push_back(x: std::make_pair(x&: NameHash, y&: Loc));
305 }
306 }
307
308 if (CodeGenOpts.ClearASTBeforeBackend) {
309 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
310 // Access to the AST is no longer available after this.
311 // Other things that the ASTContext manages are still available, e.g.
312 // the SourceManager. It'd be nice if we could separate out all the
313 // things in ASTContext used after this point and null out the
314 // ASTContext, but too many various parts of the ASTContext are still
315 // used in various parts.
316 C.cleanup();
317 C.getAllocator().Reset();
318 }
319
320 EmbedBitcode(M: getModule(), CGOpts: CodeGenOpts, Buf: llvm::MemoryBufferRef());
321
322 emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(),
323 TDesc: C.getTargetInfo().getDataLayoutString(), M: getModule(),
324 Action, VFS: FS, OS: std::move(AsmOutStream), BC: this);
325
326 if (OptRecordFile)
327 OptRecordFile->keep();
328}
329
330void BackendConsumer::HandleTagDeclDefinition(TagDecl *D) {
331 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
332 Context->getSourceManager(),
333 "LLVM IR generation of declaration");
334 Gen->HandleTagDeclDefinition(D);
335}
336
337void BackendConsumer::HandleTagDeclRequiredDefinition(const TagDecl *D) {
338 Gen->HandleTagDeclRequiredDefinition(D);
339}
340
341void BackendConsumer::CompleteTentativeDefinition(VarDecl *D) {
342 Gen->CompleteTentativeDefinition(D);
343}
344
345void BackendConsumer::CompleteExternalDeclaration(DeclaratorDecl *D) {
346 Gen->CompleteExternalDeclaration(D);
347}
348
349void BackendConsumer::AssignInheritanceModel(CXXRecordDecl *RD) {
350 Gen->AssignInheritanceModel(RD);
351}
352
353void BackendConsumer::HandleVTable(CXXRecordDecl *RD) {
354 Gen->HandleVTable(RD);
355}
356
357void BackendConsumer::anchor() { }
358
359} // namespace clang
360
361bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
362 BackendCon->DiagnosticHandlerImpl(DI);
363 return true;
364}
365
366/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
367/// buffer to be a valid FullSourceLoc.
368static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
369 SourceManager &CSM) {
370 // Get both the clang and llvm source managers. The location is relative to
371 // a memory buffer that the LLVM Source Manager is handling, we need to add
372 // a copy to the Clang source manager.
373 const llvm::SourceMgr &LSM = *D.getSourceMgr();
374
375 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
376 // already owns its one and clang::SourceManager wants to own its one.
377 const MemoryBuffer *LBuf =
378 LSM.getMemoryBuffer(i: LSM.FindBufferContainingLoc(Loc: D.getLoc()));
379
380 // Create the copy and transfer ownership to clang::SourceManager.
381 // TODO: Avoid copying files into memory.
382 std::unique_ptr<llvm::MemoryBuffer> CBuf =
383 llvm::MemoryBuffer::getMemBufferCopy(InputData: LBuf->getBuffer(),
384 BufferName: LBuf->getBufferIdentifier());
385 // FIXME: Keep a file ID map instead of creating new IDs for each location.
386 FileID FID = CSM.createFileID(Buffer: std::move(CBuf));
387
388 // Translate the offset into the file.
389 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
390 SourceLocation NewLoc =
391 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
392 return FullSourceLoc(NewLoc, CSM);
393}
394
395#define ComputeDiagID(Severity, GroupName, DiagID) \
396 do { \
397 switch (Severity) { \
398 case llvm::DS_Error: \
399 DiagID = diag::err_fe_##GroupName; \
400 break; \
401 case llvm::DS_Warning: \
402 DiagID = diag::warn_fe_##GroupName; \
403 break; \
404 case llvm::DS_Remark: \
405 llvm_unreachable("'remark' severity not expected"); \
406 break; \
407 case llvm::DS_Note: \
408 DiagID = diag::note_fe_##GroupName; \
409 break; \
410 } \
411 } while (false)
412
413#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
414 do { \
415 switch (Severity) { \
416 case llvm::DS_Error: \
417 DiagID = diag::err_fe_##GroupName; \
418 break; \
419 case llvm::DS_Warning: \
420 DiagID = diag::warn_fe_##GroupName; \
421 break; \
422 case llvm::DS_Remark: \
423 DiagID = diag::remark_fe_##GroupName; \
424 break; \
425 case llvm::DS_Note: \
426 DiagID = diag::note_fe_##GroupName; \
427 break; \
428 } \
429 } while (false)
430
431void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
432 const llvm::SMDiagnostic &D = DI.getSMDiag();
433
434 unsigned DiagID;
435 if (DI.isInlineAsmDiag())
436 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
437 else
438 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
439
440 // This is for the empty BackendConsumer that uses the clang diagnostic
441 // handler for IR input files.
442 if (!Context) {
443 D.print(ProgName: nullptr, S&: llvm::errs());
444 Diags.Report(DiagID).AddString(V: "cannot compile inline asm");
445 return;
446 }
447
448 // There are a couple of different kinds of errors we could get here.
449 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
450
451 // Strip "error: " off the start of the message string.
452 StringRef Message = D.getMessage();
453 (void)Message.consume_front(Prefix: "error: ");
454
455 // If the SMDiagnostic has an inline asm source location, translate it.
456 FullSourceLoc Loc;
457 if (D.getLoc() != SMLoc())
458 Loc = ConvertBackendLocation(D, CSM&: Context->getSourceManager());
459
460 // If this problem has clang-level source location information, report the
461 // issue in the source with a note showing the instantiated
462 // code.
463 if (DI.isInlineAsmDiag()) {
464 SourceLocation LocCookie =
465 SourceLocation::getFromRawEncoding(Encoding: DI.getLocCookie());
466 if (LocCookie.isValid()) {
467 Diags.Report(Loc: LocCookie, DiagID).AddString(V: Message);
468
469 if (D.getLoc().isValid()) {
470 DiagnosticBuilder B = Diags.Report(Loc, DiagID: diag::note_fe_inline_asm_here);
471 // Convert the SMDiagnostic ranges into SourceRange and attach them
472 // to the diagnostic.
473 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
474 unsigned Column = D.getColumnNo();
475 B << SourceRange(Loc.getLocWithOffset(Offset: Range.first - Column),
476 Loc.getLocWithOffset(Offset: Range.second - Column));
477 }
478 }
479 return;
480 }
481 }
482
483 // Otherwise, report the backend issue as occurring in the generated .s file.
484 // If Loc is invalid, we still need to report the issue, it just gets no
485 // location info.
486 Diags.Report(Loc, DiagID).AddString(V: Message);
487}
488
489bool
490BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
491 unsigned DiagID;
492 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
493 std::string Message = D.getMsgStr().str();
494
495 // If this problem has clang-level source location information, report the
496 // issue as being a problem in the source with a note showing the instantiated
497 // code.
498 SourceLocation LocCookie =
499 SourceLocation::getFromRawEncoding(Encoding: D.getLocCookie());
500 if (LocCookie.isValid())
501 Diags.Report(Loc: LocCookie, DiagID).AddString(V: Message);
502 else {
503 // Otherwise, report the backend diagnostic as occurring in the generated
504 // .s file.
505 // If Loc is invalid, we still need to report the diagnostic, it just gets
506 // no location info.
507 FullSourceLoc Loc;
508 Diags.Report(Loc, DiagID).AddString(V: Message);
509 }
510 // We handled all the possible severities.
511 return true;
512}
513
514bool
515BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
516 if (D.getSeverity() != llvm::DS_Warning)
517 // For now, the only support we have for StackSize diagnostic is warning.
518 // We do not know how to format other severities.
519 return false;
520
521 auto Loc = getFunctionSourceLocation(F: D.getFunction());
522 if (!Loc)
523 return false;
524
525 Diags.Report(Loc: *Loc, DiagID: diag::warn_fe_frame_larger_than)
526 << D.getStackSize() << D.getStackLimit()
527 << llvm::demangle(MangledName: D.getFunction().getName());
528 return true;
529}
530
531bool BackendConsumer::ResourceLimitDiagHandler(
532 const llvm::DiagnosticInfoResourceLimit &D) {
533 auto Loc = getFunctionSourceLocation(F: D.getFunction());
534 if (!Loc)
535 return false;
536 unsigned DiagID = diag::err_fe_backend_resource_limit;
537 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
538
539 Diags.Report(Loc: *Loc, DiagID)
540 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
541 << llvm::demangle(MangledName: D.getFunction().getName());
542 return true;
543}
544
545const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
546 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
547 StringRef &Filename, unsigned &Line, unsigned &Column) const {
548 SourceManager &SourceMgr = Context->getSourceManager();
549 FileManager &FileMgr = SourceMgr.getFileManager();
550 SourceLocation DILoc;
551
552 if (D.isLocationAvailable()) {
553 D.getLocation(RelativePath&: Filename, Line, Column);
554 if (Line > 0) {
555 auto FE = FileMgr.getOptionalFileRef(Filename);
556 if (!FE)
557 FE = FileMgr.getOptionalFileRef(Filename: D.getAbsolutePath());
558 if (FE) {
559 // If -gcolumn-info was not used, Column will be 0. This upsets the
560 // source manager, so pass 1 if Column is not set.
561 DILoc = SourceMgr.translateFileLineCol(SourceFile: *FE, Line, Col: Column ? Column : 1);
562 }
563 }
564 BadDebugInfo = DILoc.isInvalid();
565 }
566
567 // If a location isn't available, try to approximate it using the associated
568 // function definition. We use the definition's right brace to differentiate
569 // from diagnostics that genuinely relate to the function itself.
570 FullSourceLoc Loc(DILoc, SourceMgr);
571 if (Loc.isInvalid()) {
572 if (auto MaybeLoc = getFunctionSourceLocation(F: D.getFunction()))
573 Loc = *MaybeLoc;
574 }
575
576 if (DILoc.isInvalid() && D.isLocationAvailable())
577 // If we were not able to translate the file:line:col information
578 // back to a SourceLocation, at least emit a note stating that
579 // we could not translate this location. This can happen in the
580 // case of #line directives.
581 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
582 << Filename << Line << Column;
583
584 return Loc;
585}
586
587std::optional<FullSourceLoc>
588BackendConsumer::getFunctionSourceLocation(const Function &F) const {
589 auto Hash = llvm::hash_value(S: F.getName());
590 for (const auto &Pair : ManglingFullSourceLocs) {
591 if (Pair.first == Hash)
592 return Pair.second;
593 }
594 return std::nullopt;
595}
596
597void BackendConsumer::UnsupportedDiagHandler(
598 const llvm::DiagnosticInfoUnsupported &D) {
599 // We only support warnings or errors.
600 assert(D.getSeverity() == llvm::DS_Error ||
601 D.getSeverity() == llvm::DS_Warning);
602
603 StringRef Filename;
604 unsigned Line, Column;
605 bool BadDebugInfo = false;
606 FullSourceLoc Loc;
607 std::string Msg;
608 raw_string_ostream MsgStream(Msg);
609
610 // Context will be nullptr for IR input files, we will construct the diag
611 // message from llvm::DiagnosticInfoUnsupported.
612 if (Context != nullptr) {
613 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
614 MsgStream << D.getMessage();
615 } else {
616 DiagnosticPrinterRawOStream DP(MsgStream);
617 D.print(DP);
618 }
619
620 auto DiagType = D.getSeverity() == llvm::DS_Error
621 ? diag::err_fe_backend_unsupported
622 : diag::warn_fe_backend_unsupported;
623 Diags.Report(Loc, DiagID: DiagType) << Msg;
624
625 if (BadDebugInfo)
626 // If we were not able to translate the file:line:col information
627 // back to a SourceLocation, at least emit a note stating that
628 // we could not translate this location. This can happen in the
629 // case of #line directives.
630 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
631 << Filename << Line << Column;
632}
633
634void BackendConsumer::EmitOptimizationMessage(
635 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
636 // We only support warnings and remarks.
637 assert(D.getSeverity() == llvm::DS_Remark ||
638 D.getSeverity() == llvm::DS_Warning);
639
640 StringRef Filename;
641 unsigned Line, Column;
642 bool BadDebugInfo = false;
643 FullSourceLoc Loc;
644 std::string Msg;
645 raw_string_ostream MsgStream(Msg);
646
647 // Context will be nullptr for IR input files, we will construct the remark
648 // message from llvm::DiagnosticInfoOptimizationBase.
649 if (Context != nullptr) {
650 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
651 MsgStream << D.getMsg();
652 } else {
653 DiagnosticPrinterRawOStream DP(MsgStream);
654 D.print(DP);
655 }
656
657 if (D.getHotness())
658 MsgStream << " (hotness: " << *D.getHotness() << ")";
659
660 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;
661
662 if (BadDebugInfo)
663 // If we were not able to translate the file:line:col information
664 // back to a SourceLocation, at least emit a note stating that
665 // we could not translate this location. This can happen in the
666 // case of #line directives.
667 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
668 << Filename << Line << Column;
669}
670
671void BackendConsumer::OptimizationRemarkHandler(
672 const llvm::DiagnosticInfoOptimizationBase &D) {
673 // Without hotness information, don't show noisy remarks.
674 if (D.isVerbose() && !D.getHotness())
675 return;
676
677 if (D.isPassed()) {
678 // Optimization remarks are active only if the -Rpass flag has a regular
679 // expression that matches the name of the pass name in \p D.
680 if (CodeGenOpts.OptimizationRemark.patternMatches(String: D.getPassName()))
681 EmitOptimizationMessage(D, DiagID: diag::remark_fe_backend_optimization_remark);
682 } else if (D.isMissed()) {
683 // Missed optimization remarks are active only if the -Rpass-missed
684 // flag has a regular expression that matches the name of the pass
685 // name in \p D.
686 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(String: D.getPassName()))
687 EmitOptimizationMessage(
688 D, DiagID: diag::remark_fe_backend_optimization_remark_missed);
689 } else {
690 assert(D.isAnalysis() && "Unknown remark type");
691
692 bool ShouldAlwaysPrint = false;
693 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(Val: &D))
694 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
695
696 if (ShouldAlwaysPrint ||
697 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(String: D.getPassName()))
698 EmitOptimizationMessage(
699 D, DiagID: diag::remark_fe_backend_optimization_remark_analysis);
700 }
701}
702
703void BackendConsumer::OptimizationRemarkHandler(
704 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
705 // Optimization analysis remarks are active if the pass name is set to
706 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
707 // regular expression that matches the name of the pass name in \p D.
708
709 if (D.shouldAlwaysPrint() ||
710 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(String: D.getPassName()))
711 EmitOptimizationMessage(
712 D, DiagID: diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
713}
714
715void BackendConsumer::OptimizationRemarkHandler(
716 const llvm::OptimizationRemarkAnalysisAliasing &D) {
717 // Optimization analysis remarks are active if the pass name is set to
718 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
719 // regular expression that matches the name of the pass name in \p D.
720
721 if (D.shouldAlwaysPrint() ||
722 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(String: D.getPassName()))
723 EmitOptimizationMessage(
724 D, DiagID: diag::remark_fe_backend_optimization_remark_analysis_aliasing);
725}
726
727void BackendConsumer::OptimizationFailureHandler(
728 const llvm::DiagnosticInfoOptimizationFailure &D) {
729 EmitOptimizationMessage(D, DiagID: diag::warn_fe_backend_optimization_failure);
730}
731
732void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
733 SourceLocation LocCookie =
734 SourceLocation::getFromRawEncoding(Encoding: D.getLocCookie());
735
736 // FIXME: we can't yet diagnose indirect calls. When/if we can, we
737 // should instead assert that LocCookie.isValid().
738 if (!LocCookie.isValid())
739 return;
740
741 Diags.Report(Loc: LocCookie, DiagID: D.getSeverity() == DiagnosticSeverity::DS_Error
742 ? diag::err_fe_backend_error_attr
743 : diag::warn_fe_backend_warning_attr)
744 << llvm::demangle(MangledName: D.getFunctionName()) << D.getNote();
745
746 if (!CodeGenOpts.ShowInliningChain)
747 return;
748
749 auto EmitNote = [&](SourceLocation Loc, StringRef FuncName, bool IsFirst) {
750 if (!Loc.isValid())
751 Loc = LocCookie;
752 unsigned DiagID =
753 IsFirst ? diag::note_fe_backend_in : diag::note_fe_backend_inlined;
754 Diags.Report(Loc, DiagID) << llvm::demangle(MangledName: FuncName.str());
755 };
756
757 // Try debug info first for accurate source locations.
758 if (!D.getDebugInlineChain().empty()) {
759 SourceManager &SM = Context->getSourceManager();
760 FileManager &FM = SM.getFileManager();
761 for (const auto &[I, Info] : llvm::enumerate(First: D.getDebugInlineChain())) {
762 SourceLocation Loc;
763 if (Info.Line > 0)
764 if (auto FE = FM.getOptionalFileRef(Filename: Info.Filename))
765 Loc = SM.translateFileLineCol(SourceFile: *FE, Line: Info.Line,
766 Col: Info.Column ? Info.Column : 1);
767 EmitNote(Loc, Info.FuncName, I == 0);
768 }
769 return;
770 }
771
772 // Fall back to heuristic (srcloc metadata) when debug info is unavailable.
773 auto InliningDecisions = D.getInliningDecisions();
774 if (InliningDecisions.empty())
775 return;
776
777 for (const auto &[I, Entry] : llvm::enumerate(First&: InliningDecisions)) {
778 SourceLocation Loc =
779 I == 0 ? LocCookie : SourceLocation::getFromRawEncoding(Encoding: Entry.second);
780 EmitNote(Loc, Entry.first, I == 0);
781 }
782
783 // Suggest enabling debug info (at least -gline-directives-only) for more
784 // accurate locations.
785 Diags.Report(Loc: LocCookie, DiagID: diag::note_fe_backend_inlining_debug_info);
786}
787
788void BackendConsumer::MisExpectDiagHandler(
789 const llvm::DiagnosticInfoMisExpect &D) {
790 StringRef Filename;
791 unsigned Line, Column;
792 bool BadDebugInfo = false;
793 FullSourceLoc Loc =
794 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
795
796 Diags.Report(Loc, DiagID: diag::warn_profile_data_misexpect) << D.getMsg().str();
797
798 if (BadDebugInfo)
799 // If we were not able to translate the file:line:col information
800 // back to a SourceLocation, at least emit a note stating that
801 // we could not translate this location. This can happen in the
802 // case of #line directives.
803 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
804 << Filename << Line << Column;
805}
806
807/// This function is invoked when the backend needs
808/// to report something to the user.
809void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
810 unsigned DiagID = diag::err_fe_inline_asm;
811 llvm::DiagnosticSeverity Severity = DI.getSeverity();
812 // Get the diagnostic ID based.
813 switch (DI.getKind()) {
814 case llvm::DK_InlineAsm:
815 if (InlineAsmDiagHandler(D: cast<DiagnosticInfoInlineAsm>(Val: DI)))
816 return;
817 ComputeDiagID(Severity, inline_asm, DiagID);
818 break;
819 case llvm::DK_SrcMgr:
820 SrcMgrDiagHandler(DI: cast<DiagnosticInfoSrcMgr>(Val: DI));
821 return;
822 case llvm::DK_StackSize:
823 if (StackSizeDiagHandler(D: cast<DiagnosticInfoStackSize>(Val: DI)))
824 return;
825 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
826 break;
827 case llvm::DK_ResourceLimit:
828 if (ResourceLimitDiagHandler(D: cast<DiagnosticInfoResourceLimit>(Val: DI)))
829 return;
830 ComputeDiagID(Severity, backend_resource_limit, DiagID);
831 break;
832 case DK_Linker:
833 ComputeDiagID(Severity, linking_module, DiagID);
834 break;
835 case llvm::DK_OptimizationRemark:
836 // Optimization remarks are always handled completely by this
837 // handler. There is no generic way of emitting them.
838 OptimizationRemarkHandler(D: cast<OptimizationRemark>(Val: DI));
839 return;
840 case llvm::DK_OptimizationRemarkMissed:
841 // Optimization remarks are always handled completely by this
842 // handler. There is no generic way of emitting them.
843 OptimizationRemarkHandler(D: cast<OptimizationRemarkMissed>(Val: DI));
844 return;
845 case llvm::DK_OptimizationRemarkAnalysis:
846 // Optimization remarks are always handled completely by this
847 // handler. There is no generic way of emitting them.
848 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysis>(Val: DI));
849 return;
850 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
851 // Optimization remarks are always handled completely by this
852 // handler. There is no generic way of emitting them.
853 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysisFPCommute>(Val: DI));
854 return;
855 case llvm::DK_OptimizationRemarkAnalysisAliasing:
856 // Optimization remarks are always handled completely by this
857 // handler. There is no generic way of emitting them.
858 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysisAliasing>(Val: DI));
859 return;
860 case llvm::DK_MachineOptimizationRemark:
861 // Optimization remarks are always handled completely by this
862 // handler. There is no generic way of emitting them.
863 OptimizationRemarkHandler(D: cast<MachineOptimizationRemark>(Val: DI));
864 return;
865 case llvm::DK_MachineOptimizationRemarkMissed:
866 // Optimization remarks are always handled completely by this
867 // handler. There is no generic way of emitting them.
868 OptimizationRemarkHandler(D: cast<MachineOptimizationRemarkMissed>(Val: DI));
869 return;
870 case llvm::DK_MachineOptimizationRemarkAnalysis:
871 // Optimization remarks are always handled completely by this
872 // handler. There is no generic way of emitting them.
873 OptimizationRemarkHandler(D: cast<MachineOptimizationRemarkAnalysis>(Val: DI));
874 return;
875 case llvm::DK_OptimizationFailure:
876 // Optimization failures are always handled completely by this
877 // handler.
878 OptimizationFailureHandler(D: cast<DiagnosticInfoOptimizationFailure>(Val: DI));
879 return;
880 case llvm::DK_Unsupported:
881 UnsupportedDiagHandler(D: cast<DiagnosticInfoUnsupported>(Val: DI));
882 return;
883 case llvm::DK_DontCall:
884 DontCallDiagHandler(D: cast<DiagnosticInfoDontCall>(Val: DI));
885 return;
886 case llvm::DK_MisExpect:
887 MisExpectDiagHandler(D: cast<DiagnosticInfoMisExpect>(Val: DI));
888 return;
889 default:
890 // Plugin IDs are not bound to any value as they are set dynamically.
891 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
892 break;
893 }
894 std::string MsgStorage;
895 {
896 raw_string_ostream Stream(MsgStorage);
897 DiagnosticPrinterRawOStream DP(Stream);
898 DI.print(DP);
899 }
900
901 if (DI.getKind() == DK_Linker) {
902 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
903 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
904 return;
905 }
906
907 // Report the backend message using the usual diagnostic mechanism.
908 FullSourceLoc Loc;
909 Diags.Report(Loc, DiagID).AddString(V: MsgStorage);
910}
911#undef ComputeDiagID
912
913CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
914 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
915 OwnsVMContext(!_VMContext) {}
916
917CodeGenAction::~CodeGenAction() {
918 TheModule.reset();
919 if (OwnsVMContext)
920 delete VMContext;
921}
922
923bool CodeGenAction::hasIRSupport() const { return true; }
924
925void CodeGenAction::EndSourceFileAction() {
926 ASTFrontendAction::EndSourceFileAction();
927
928 // If the consumer creation failed, do nothing.
929 if (!getCompilerInstance().hasASTConsumer())
930 return;
931
932 // Steal the module from the consumer.
933 TheModule = BEConsumer->takeModule();
934}
935
936std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
937 return std::move(TheModule);
938}
939
940llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
941 OwnsVMContext = false;
942 return VMContext;
943}
944
945CodeGenerator *CodeGenAction::getCodeGenerator() const {
946 return BEConsumer->getCodeGenerator();
947}
948
949bool CodeGenAction::BeginSourceFileAction(CompilerInstance &CI) {
950 if (CI.getFrontendOpts().GenReducedBMI)
951 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
952 return ASTFrontendAction::BeginSourceFileAction(CI);
953}
954
955static std::unique_ptr<raw_pwrite_stream>
956GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
957 switch (Action) {
958 case Backend_EmitAssembly:
959 return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "s");
960 case Backend_EmitLL:
961 return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "ll");
962 case Backend_EmitBC:
963 return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "bc");
964 case Backend_EmitNothing:
965 return nullptr;
966 case Backend_EmitMCNull:
967 return CI.createNullOutputFile();
968 case Backend_EmitObj:
969 return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "o");
970 }
971
972 llvm_unreachable("Invalid action!");
973}
974
975std::unique_ptr<ASTConsumer>
976CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
977 BackendAction BA = static_cast<BackendAction>(Act);
978 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
979 if (!OS)
980 OS = GetOutputStream(CI, InFile, Action: BA);
981
982 if (BA != Backend_EmitNothing && !OS)
983 return nullptr;
984
985 // Load bitcode modules to link with, if we need to.
986 if (clang::loadLinkModules(CI, Ctx&: *VMContext, LinkModules))
987 return nullptr;
988
989 CoverageSourceInfo *CoverageInfo = nullptr;
990 // Add the preprocessor callback only when the coverage mapping is generated.
991 if (CI.getCodeGenOpts().CoverageMapping)
992 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
993 CI.getPreprocessor());
994
995 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
996 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
997 InFile, std::move(OS), CoverageInfo));
998 BEConsumer = Result.get();
999
1000 // Enable generating macro debug info only when debug info is not disabled and
1001 // also macro debug info is enabled.
1002 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1003 CI.getCodeGenOpts().MacroDebugInfo) {
1004 std::unique_ptr<PPCallbacks> Callbacks =
1005 std::make_unique<MacroPPCallbacks>(args: BEConsumer->getCodeGenerator(),
1006 args&: CI.getPreprocessor());
1007 CI.getPreprocessor().addPPCallbacks(C: std::move(Callbacks));
1008 }
1009
1010 if (CI.getFrontendOpts().GenReducedBMI &&
1011 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
1012 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1013 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1014 args&: CI.getPreprocessor(), args&: CI.getModuleCache(),
1015 args&: CI.getFrontendOpts().ModuleOutputPath, args&: CI.getCodeGenOpts());
1016 Consumers[1] = std::move(Result);
1017 return std::make_unique<MultiplexConsumer>(args: std::move(Consumers));
1018 }
1019
1020 return std::move(Result);
1021}
1022
1023std::unique_ptr<llvm::Module>
1024CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1025 CompilerInstance &CI = getCompilerInstance();
1026 SourceManager &SM = CI.getSourceManager();
1027
1028 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1029 unsigned DiagID =
1030 CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0");
1031 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
1032 CI.getDiagnostics().Report(DiagID) << EIB.message();
1033 });
1034 return {};
1035 };
1036
1037 // For ThinLTO backend invocations, ensure that the context
1038 // merges types based on ODR identifiers. We also need to read
1039 // the correct module out of a multi-module bitcode file.
1040 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1041 VMContext->enableDebugTypeODRUniquing();
1042
1043 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
1044 if (!BMsOrErr)
1045 return DiagErrors(BMsOrErr.takeError());
1046 BitcodeModule *Bm = llvm::lto::findThinLTOModule(BMs: *BMsOrErr);
1047 // We have nothing to do if the file contains no ThinLTO module. This is
1048 // possible if ThinLTO compilation was not able to split module. Content of
1049 // the file was already processed by indexing and will be passed to the
1050 // linker using merged object file.
1051 if (!Bm) {
1052 auto M = std::make_unique<llvm::Module>(args: "empty", args&: *VMContext);
1053 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
1054 return M;
1055 }
1056 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1057 Bm->parseModule(Context&: *VMContext);
1058 if (!MOrErr)
1059 return DiagErrors(MOrErr.takeError());
1060 return std::move(*MOrErr);
1061 }
1062
1063 // Load bitcode modules to link with, if we need to.
1064 if (clang::loadLinkModules(CI, Ctx&: *VMContext, LinkModules))
1065 return nullptr;
1066
1067 // Handle textual IR and bitcode file with one single module.
1068 llvm::SMDiagnostic Err;
1069 if (std::unique_ptr<llvm::Module> M = parseIR(Buffer: MBRef, Err, Context&: *VMContext)) {
1070 // For LLVM IR files, always verify the input and report the error in a way
1071 // that does not ask people to report an issue for it.
1072 std::string VerifierErr;
1073 raw_string_ostream VerifierErrStream(VerifierErr);
1074 if (llvm::verifyModule(M: *M, OS: &VerifierErrStream)) {
1075 CI.getDiagnostics().Report(DiagID: diag::err_invalid_llvm_ir) << VerifierErr;
1076 return {};
1077 }
1078 return M;
1079 }
1080
1081 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1082 // output), place the extra modules (actually only one, a regular LTO module)
1083 // into LinkModules as if we are using -mlink-bitcode-file.
1084 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
1085 if (BMsOrErr && BMsOrErr->size()) {
1086 std::unique_ptr<llvm::Module> FirstM;
1087 for (auto &BM : *BMsOrErr) {
1088 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1089 BM.parseModule(Context&: *VMContext);
1090 if (!MOrErr)
1091 return DiagErrors(MOrErr.takeError());
1092 if (FirstM)
1093 LinkModules.push_back(Elt: {.Module: std::move(*MOrErr), /*PropagateAttrs=*/false,
1094 /*Internalize=*/false, /*LinkFlags=*/{}});
1095 else
1096 FirstM = std::move(*MOrErr);
1097 }
1098 if (FirstM)
1099 return FirstM;
1100 }
1101 // If BMsOrErr fails, consume the error and use the error message from
1102 // parseIR.
1103 consumeError(Err: BMsOrErr.takeError());
1104
1105 // Translate from the diagnostic info to the SourceManager location if
1106 // available.
1107 // TODO: Unify this with ConvertBackendLocation()
1108 SourceLocation Loc;
1109 if (Err.getLineNo() > 0) {
1110 assert(Err.getColumnNo() >= 0);
1111 Loc = SM.translateFileLineCol(SourceFile: SM.getFileEntryForID(FID: SM.getMainFileID()),
1112 Line: Err.getLineNo(), Col: Err.getColumnNo() + 1);
1113 }
1114
1115 // Strip off a leading diagnostic code if there is one.
1116 StringRef Msg = Err.getMessage();
1117 Msg.consume_front(Prefix: "error: ");
1118
1119 unsigned DiagID =
1120 CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0");
1121
1122 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1123 return {};
1124}
1125
1126void CodeGenAction::ExecuteAction() {
1127 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1128 this->ASTFrontendAction::ExecuteAction();
1129 return;
1130 }
1131
1132 // If this is an IR file, we have to treat it specially.
1133 BackendAction BA = static_cast<BackendAction>(Act);
1134 CompilerInstance &CI = getCompilerInstance();
1135 auto &CodeGenOpts = CI.getCodeGenOpts();
1136 auto &Diagnostics = CI.getDiagnostics();
1137 std::unique_ptr<raw_pwrite_stream> OS =
1138 GetOutputStream(CI, InFile: getCurrentFileOrBufferName(), Action: BA);
1139 if (BA != Backend_EmitNothing && !OS)
1140 return;
1141
1142 SourceManager &SM = CI.getSourceManager();
1143 FileID FID = SM.getMainFileID();
1144 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1145 if (!MainFile)
1146 return;
1147
1148 TheModule = loadModule(MBRef: *MainFile);
1149 if (!TheModule)
1150 return;
1151
1152 const TargetOptions &TargetOpts = CI.getTargetOpts();
1153 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
1154 Diagnostics.Report(Loc: SourceLocation(), DiagID: diag::warn_fe_override_module)
1155 << TargetOpts.Triple;
1156 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
1157 }
1158
1159 EmbedObject(M: TheModule.get(), CGOpts: CodeGenOpts, VFS&: CI.getVirtualFileSystem(),
1160 Diags&: Diagnostics);
1161 EmbedBitcode(M: TheModule.get(), CGOpts: CodeGenOpts, Buf: *MainFile);
1162
1163 LLVMContext &Ctx = TheModule->getContext();
1164
1165 // Restore any diagnostic handler previously set before returning from this
1166 // function.
1167 struct RAII {
1168 LLVMContext &Ctx;
1169 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1170 ~RAII() { Ctx.setDiagnosticHandler(DH: std::move(PrevHandler)); }
1171 } _{.Ctx: Ctx};
1172
1173 // Set clang diagnostic handler. To do this we need to create a fake
1174 // BackendConsumer.
1175 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
1176 std::move(LinkModules), "", nullptr, nullptr,
1177 TheModule.get());
1178
1179 // Link in each pending link module.
1180 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(M: &*TheModule))
1181 return;
1182
1183 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1184 // true here because the valued names are needed for reading textual IR.
1185 Ctx.setDiscardValueNames(false);
1186 Ctx.setDiagnosticHandler(
1187 DH: std::make_unique<ClangDiagnosticHandler>(args&: CodeGenOpts, args: &Result));
1188
1189 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1190 Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: ","));
1191
1192 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
1193 setupLLVMOptimizationRemarks(
1194 Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses,
1195 RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness,
1196 RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold);
1197
1198 if (Error E = OptRecordFileOrErr.takeError()) {
1199 reportOptRecordError(E: std::move(E), Diags&: Diagnostics, CodeGenOpts);
1200 return;
1201 }
1202 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1203
1204 emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(),
1205 TDesc: CI.getTarget().getDataLayoutString(), M: TheModule.get(), Action: BA,
1206 VFS: CI.getFileManager().getVirtualFileSystemPtr(),
1207 OS: std::move(OS));
1208 if (OptRecordFile)
1209 OptRecordFile->keep();
1210}
1211
1212//
1213
1214void EmitAssemblyAction::anchor() { }
1215EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1216 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1217
1218void EmitBCAction::anchor() { }
1219EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1220 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1221
1222void EmitLLVMAction::anchor() { }
1223EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1224 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1225
1226void EmitLLVMOnlyAction::anchor() { }
1227EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1228 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1229
1230void EmitCodeGenOnlyAction::anchor() { }
1231EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1232 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1233
1234void EmitObjAction::anchor() { }
1235EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1236 : CodeGenAction(Backend_EmitObj, _VMContext) {}
1237