clang 19.0.0git
CodeGenAction.cpp
Go to the documentation of this file.
1//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "BackendConsumer.h"
11#include "CGCall.h"
12#include "CodeGenModule.h"
13#include "CoverageMappingGen.h"
14#include "MacroPPCallbacks.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclGroup.h"
33#include "llvm/ADT/Hashing.h"
34#include "llvm/Bitcode/BitcodeReader.h"
35#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
36#include "llvm/Demangle/Demangle.h"
37#include "llvm/IR/DebugInfo.h"
38#include "llvm/IR/DiagnosticInfo.h"
39#include "llvm/IR/DiagnosticPrinter.h"
40#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/LLVMRemarkStreamer.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IRReader/IRReader.h"
45#include "llvm/LTO/LTOBackend.h"
46#include "llvm/Linker/Linker.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/SourceMgr.h"
50#include "llvm/Support/TimeProfiler.h"
51#include "llvm/Support/Timer.h"
52#include "llvm/Support/ToolOutputFile.h"
53#include "llvm/Support/YAMLTraits.h"
54#include "llvm/Transforms/IPO/Internalize.h"
55#include "llvm/Transforms/Utils/Cloning.h"
56
57#include <optional>
58using namespace clang;
59using namespace llvm;
60
61#define DEBUG_TYPE "codegenaction"
62
63namespace llvm {
64extern cl::opt<bool> ClRelinkBuiltinBitcodePostop;
65}
66
67namespace clang {
68class BackendConsumer;
70public:
72 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
73
74 bool handleDiagnostics(const DiagnosticInfo &DI) override;
75
76 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
77 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
78 }
79 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
80 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
81 }
82 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
83 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
84 }
85
86 bool isAnyRemarkEnabled() const override {
87 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
90 }
91
92private:
93 const CodeGenOptions &CodeGenOpts;
94 BackendConsumer *BackendCon;
95};
96
97static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
98 const CodeGenOptions &CodeGenOpts) {
99 handleAllErrors(
100 std::move(E),
101 [&](const LLVMRemarkSetupFileError &E) {
102 Diags.Report(diag::err_cannot_open_file)
103 << CodeGenOpts.OptRecordFile << E.message();
104 },
105 [&](const LLVMRemarkSetupPatternError &E) {
106 Diags.Report(diag::err_drv_optimization_remark_pattern)
107 << E.message() << CodeGenOpts.OptRecordPasses;
108 },
109 [&](const LLVMRemarkSetupFormatError &E) {
110 Diags.Report(diag::err_drv_optimization_remark_format)
111 << CodeGenOpts.OptRecordFormat;
112 });
113}
114
116 BackendAction Action, DiagnosticsEngine &Diags,
118 const HeaderSearchOptions &HeaderSearchOpts,
119 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
120 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
121 const FileManager &FileMgr, const std::string &InFile,
122 SmallVector<LinkModule, 4> LinkModules,
123 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
124 CoverageSourceInfo *CoverageInfo)
125 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
126 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
127 FileMgr(FileMgr), AsmOutStream(std::move(OS)), Context(nullptr), FS(VFS),
128 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
129 LLVMIRGenerationRefCount(0),
130 Gen(CreateLLVMCodeGen(Diags, InFile, std::move(VFS), HeaderSearchOpts,
131 PPOpts, CodeGenOpts, C, CoverageInfo)),
132 LinkModules(std::move(LinkModules)) {
133 TimerIsEnabled = CodeGenOpts.TimePasses;
134 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
135 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
136}
137
138// This constructor is used in installing an empty BackendConsumer
139// to use the clang diagnostic handler for IR input files. It avoids
140// initializing the OS field.
142 BackendAction Action, DiagnosticsEngine &Diags,
144 const HeaderSearchOptions &HeaderSearchOpts,
145 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
146 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
147 const FileManager &FileMgr, llvm::Module *Module,
148 SmallVector<LinkModule, 4> LinkModules, LLVMContext &C,
149 CoverageSourceInfo *CoverageInfo)
150 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
151 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
152 FileMgr(FileMgr), Context(nullptr), FS(VFS),
153 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
154 LLVMIRGenerationRefCount(0),
155 Gen(CreateLLVMCodeGen(Diags, "", std::move(VFS), HeaderSearchOpts, PPOpts,
156 CodeGenOpts, C, CoverageInfo)),
157 LinkModules(std::move(LinkModules)), CurLinkModule(Module) {
158 TimerIsEnabled = CodeGenOpts.TimePasses;
159 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
160 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
161}
162
163llvm::Module* BackendConsumer::getModule() const {
164 return Gen->GetModule();
165}
166
167std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
168 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
169}
170
172 return Gen.get();
173}
174
176 Gen->HandleCXXStaticMemberVarInstantiation(VD);
177}
178
180 assert(!Context && "initialized multiple times");
181
182 Context = &Ctx;
183
184 if (TimerIsEnabled)
185 LLVMIRGeneration.startTimer();
186
187 Gen->Initialize(Ctx);
188
189 if (TimerIsEnabled)
190 LLVMIRGeneration.stopTimer();
191}
192
194 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
195 Context->getSourceManager(),
196 "LLVM IR generation of declaration");
197
198 // Recurse.
199 if (TimerIsEnabled) {
200 LLVMIRGenerationRefCount += 1;
201 if (LLVMIRGenerationRefCount == 1)
202 LLVMIRGeneration.startTimer();
203 }
204
205 Gen->HandleTopLevelDecl(D);
206
207 if (TimerIsEnabled) {
208 LLVMIRGenerationRefCount -= 1;
209 if (LLVMIRGenerationRefCount == 0)
210 LLVMIRGeneration.stopTimer();
211 }
212
213 return true;
214}
215
218 Context->getSourceManager(),
219 "LLVM IR generation of inline function");
220 if (TimerIsEnabled)
221 LLVMIRGeneration.startTimer();
222
223 Gen->HandleInlineFunctionDefinition(D);
224
225 if (TimerIsEnabled)
226 LLVMIRGeneration.stopTimer();
227}
228
230 // Ignore interesting decls from the AST reader after IRGen is finished.
231 if (!IRGenFinished)
233}
234
235bool BackendConsumer::ReloadModules(llvm::Module *M) {
237 CodeGenOpts.LinkBitcodeFiles) {
238 auto BCBuf = FileMgr.getBufferForFile(F.Filename);
239 if (!BCBuf) {
240 Diags.Report(diag::err_cannot_open_file)
241 << F.Filename << BCBuf.getError().message();
242 LinkModules.clear();
243 return true;
244 }
245
246 LLVMContext &Ctx = getModule()->getContext();
248 getOwningLazyBitcodeModule(std::move(*BCBuf), Ctx);
249
250 if (!ModuleOrErr) {
251 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
252 Diags.Report(diag::err_cannot_open_file) << F.Filename << EIB.message();
253 });
254 LinkModules.clear();
255 return true;
256 }
257 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
258 F.Internalize, F.LinkFlags});
259 }
260
261 return false; // success
262}
263
264// Links each entry in LinkModules into our module. Returns true on error.
265bool BackendConsumer::LinkInModules(llvm::Module *M, bool ShouldLinkFiles) {
266 for (auto &LM : LinkModules) {
267 assert(LM.Module && "LinkModule does not actually have a module");
268
269 // If ShouldLinkFiles is not set, skip files added via the
270 // -mlink-bitcode-files, only linking -mlink-builtin-bitcode
271 if (!LM.Internalize && !ShouldLinkFiles)
272 continue;
273
274 if (LM.PropagateAttrs)
275 for (Function &F : *LM.Module) {
276 // Skip intrinsics. Keep consistent with how intrinsics are created
277 // in LLVM IR.
278 if (F.isIntrinsic())
279 continue;
281 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
282 }
283
284 CurLinkModule = LM.Module.get();
285 bool Err;
286
287 if (LM.Internalize) {
288 Err = Linker::linkModules(
289 *M, std::move(LM.Module), LM.LinkFlags,
290 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
291 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
292 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
293 });
294 });
295 } else
296 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
297
298 if (Err)
299 return true;
300 }
301
302 LinkModules.clear();
303 return false; // success
304}
305
307 {
308 llvm::TimeTraceScope TimeScope("Frontend");
309 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
310 if (TimerIsEnabled) {
311 LLVMIRGenerationRefCount += 1;
312 if (LLVMIRGenerationRefCount == 1)
313 LLVMIRGeneration.startTimer();
314 }
315
316 Gen->HandleTranslationUnit(C);
317
318 if (TimerIsEnabled) {
319 LLVMIRGenerationRefCount -= 1;
320 if (LLVMIRGenerationRefCount == 0)
321 LLVMIRGeneration.stopTimer();
322 }
323
324 IRGenFinished = true;
325 }
326
327 // Silently ignore if we weren't initialized for some reason.
328 if (!getModule())
329 return;
330
331 LLVMContext &Ctx = getModule()->getContext();
332 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
333 Ctx.getDiagnosticHandler();
334 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
335 CodeGenOpts, this));
336
338 setupLLVMOptimizationRemarks(
339 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
340 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
341 CodeGenOpts.DiagnosticsHotnessThreshold);
342
343 if (Error E = OptRecordFileOrErr.takeError()) {
344 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
345 return;
346 }
347
348 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
349 std::move(*OptRecordFileOrErr);
350
351 if (OptRecordFile &&
352 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
353 Ctx.setDiagnosticsHotnessRequested(true);
354
355 if (CodeGenOpts.MisExpect) {
356 Ctx.setMisExpectWarningRequested(true);
357 }
358
359 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
360 Ctx.setDiagnosticsMisExpectTolerance(
362 }
363
364 // Link each LinkModule into our module.
366 return;
367
368 for (auto &F : getModule()->functions()) {
369 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
370 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
371 // TODO: use a fast content hash when available.
372 auto NameHash = llvm::hash_value(F.getName());
373 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
374 }
375 }
376
377 if (CodeGenOpts.ClearASTBeforeBackend) {
378 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
379 // Access to the AST is no longer available after this.
380 // Other things that the ASTContext manages are still available, e.g.
381 // the SourceManager. It'd be nice if we could separate out all the
382 // things in ASTContext used after this point and null out the
383 // ASTContext, but too many various parts of the ASTContext are still
384 // used in various parts.
385 C.cleanup();
386 C.getAllocator().Reset();
387 }
388
389 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
390
391 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
392 C.getTargetInfo().getDataLayoutString(), getModule(),
393 Action, FS, std::move(AsmOutStream), this);
394
395 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
396
397 if (OptRecordFile)
398 OptRecordFile->keep();
399}
400
403 Context->getSourceManager(),
404 "LLVM IR generation of declaration");
405 Gen->HandleTagDeclDefinition(D);
406}
407
409 Gen->HandleTagDeclRequiredDefinition(D);
410}
411
413 Gen->CompleteTentativeDefinition(D);
414}
415
417 Gen->CompleteExternalDeclaration(D);
418}
419
421 Gen->AssignInheritanceModel(RD);
422}
423
425 Gen->HandleVTable(RD);
426}
427
428void BackendConsumer::anchor() { }
429
430} // namespace clang
431
432bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
433 BackendCon->DiagnosticHandlerImpl(DI);
434 return true;
435}
436
437/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
438/// buffer to be a valid FullSourceLoc.
439static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
440 SourceManager &CSM) {
441 // Get both the clang and llvm source managers. The location is relative to
442 // a memory buffer that the LLVM Source Manager is handling, we need to add
443 // a copy to the Clang source manager.
444 const llvm::SourceMgr &LSM = *D.getSourceMgr();
445
446 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
447 // already owns its one and clang::SourceManager wants to own its one.
448 const MemoryBuffer *LBuf =
449 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
450
451 // Create the copy and transfer ownership to clang::SourceManager.
452 // TODO: Avoid copying files into memory.
453 std::unique_ptr<llvm::MemoryBuffer> CBuf =
454 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
455 LBuf->getBufferIdentifier());
456 // FIXME: Keep a file ID map instead of creating new IDs for each location.
457 FileID FID = CSM.createFileID(std::move(CBuf));
458
459 // Translate the offset into the file.
460 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
461 SourceLocation NewLoc =
462 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
463 return FullSourceLoc(NewLoc, CSM);
464}
465
466#define ComputeDiagID(Severity, GroupName, DiagID) \
467 do { \
468 switch (Severity) { \
469 case llvm::DS_Error: \
470 DiagID = diag::err_fe_##GroupName; \
471 break; \
472 case llvm::DS_Warning: \
473 DiagID = diag::warn_fe_##GroupName; \
474 break; \
475 case llvm::DS_Remark: \
476 llvm_unreachable("'remark' severity not expected"); \
477 break; \
478 case llvm::DS_Note: \
479 DiagID = diag::note_fe_##GroupName; \
480 break; \
481 } \
482 } while (false)
483
484#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
485 do { \
486 switch (Severity) { \
487 case llvm::DS_Error: \
488 DiagID = diag::err_fe_##GroupName; \
489 break; \
490 case llvm::DS_Warning: \
491 DiagID = diag::warn_fe_##GroupName; \
492 break; \
493 case llvm::DS_Remark: \
494 DiagID = diag::remark_fe_##GroupName; \
495 break; \
496 case llvm::DS_Note: \
497 DiagID = diag::note_fe_##GroupName; \
498 break; \
499 } \
500 } while (false)
501
502void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
503 const llvm::SMDiagnostic &D = DI.getSMDiag();
504
505 unsigned DiagID;
506 if (DI.isInlineAsmDiag())
507 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
508 else
509 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
510
511 // This is for the empty BackendConsumer that uses the clang diagnostic
512 // handler for IR input files.
513 if (!Context) {
514 D.print(nullptr, llvm::errs());
515 Diags.Report(DiagID).AddString("cannot compile inline asm");
516 return;
517 }
518
519 // There are a couple of different kinds of errors we could get here.
520 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
521
522 // Strip "error: " off the start of the message string.
523 StringRef Message = D.getMessage();
524 (void)Message.consume_front("error: ");
525
526 // If the SMDiagnostic has an inline asm source location, translate it.
527 FullSourceLoc Loc;
528 if (D.getLoc() != SMLoc())
529 Loc = ConvertBackendLocation(D, Context->getSourceManager());
530
531 // If this problem has clang-level source location information, report the
532 // issue in the source with a note showing the instantiated
533 // code.
534 if (DI.isInlineAsmDiag()) {
535 SourceLocation LocCookie =
536 SourceLocation::getFromRawEncoding(DI.getLocCookie());
537 if (LocCookie.isValid()) {
538 Diags.Report(LocCookie, DiagID).AddString(Message);
539
540 if (D.getLoc().isValid()) {
541 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
542 // Convert the SMDiagnostic ranges into SourceRange and attach them
543 // to the diagnostic.
544 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
545 unsigned Column = D.getColumnNo();
546 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
547 Loc.getLocWithOffset(Range.second - Column));
548 }
549 }
550 return;
551 }
552 }
553
554 // Otherwise, report the backend issue as occurring in the generated .s file.
555 // If Loc is invalid, we still need to report the issue, it just gets no
556 // location info.
557 Diags.Report(Loc, DiagID).AddString(Message);
558}
559
560bool
561BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
562 unsigned DiagID;
563 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
564 std::string Message = D.getMsgStr().str();
565
566 // If this problem has clang-level source location information, report the
567 // issue as being a problem in the source with a note showing the instantiated
568 // code.
569 SourceLocation LocCookie =
570 SourceLocation::getFromRawEncoding(D.getLocCookie());
571 if (LocCookie.isValid())
572 Diags.Report(LocCookie, DiagID).AddString(Message);
573 else {
574 // Otherwise, report the backend diagnostic as occurring in the generated
575 // .s file.
576 // If Loc is invalid, we still need to report the diagnostic, it just gets
577 // no location info.
578 FullSourceLoc Loc;
579 Diags.Report(Loc, DiagID).AddString(Message);
580 }
581 // We handled all the possible severities.
582 return true;
583}
584
585bool
586BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
587 if (D.getSeverity() != llvm::DS_Warning)
588 // For now, the only support we have for StackSize diagnostic is warning.
589 // We do not know how to format other severities.
590 return false;
591
592 auto Loc = getFunctionSourceLocation(D.getFunction());
593 if (!Loc)
594 return false;
595
596 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
597 << D.getStackSize() << D.getStackLimit()
598 << llvm::demangle(D.getFunction().getName());
599 return true;
600}
601
603 const llvm::DiagnosticInfoResourceLimit &D) {
604 auto Loc = getFunctionSourceLocation(D.getFunction());
605 if (!Loc)
606 return false;
607 unsigned DiagID = diag::err_fe_backend_resource_limit;
608 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
609
610 Diags.Report(*Loc, DiagID)
611 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
612 << llvm::demangle(D.getFunction().getName());
613 return true;
614}
615
617 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
618 StringRef &Filename, unsigned &Line, unsigned &Column) const {
619 SourceManager &SourceMgr = Context->getSourceManager();
620 FileManager &FileMgr = SourceMgr.getFileManager();
621 SourceLocation DILoc;
622
623 if (D.isLocationAvailable()) {
624 D.getLocation(Filename, Line, Column);
625 if (Line > 0) {
626 auto FE = FileMgr.getFile(Filename);
627 if (!FE)
628 FE = FileMgr.getFile(D.getAbsolutePath());
629 if (FE) {
630 // If -gcolumn-info was not used, Column will be 0. This upsets the
631 // source manager, so pass 1 if Column is not set.
632 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
633 }
634 }
635 BadDebugInfo = DILoc.isInvalid();
636 }
637
638 // If a location isn't available, try to approximate it using the associated
639 // function definition. We use the definition's right brace to differentiate
640 // from diagnostics that genuinely relate to the function itself.
641 FullSourceLoc Loc(DILoc, SourceMgr);
642 if (Loc.isInvalid()) {
643 if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
644 Loc = *MaybeLoc;
645 }
646
647 if (DILoc.isInvalid() && D.isLocationAvailable())
648 // If we were not able to translate the file:line:col information
649 // back to a SourceLocation, at least emit a note stating that
650 // we could not translate this location. This can happen in the
651 // case of #line directives.
652 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
653 << Filename << Line << Column;
654
655 return Loc;
656}
657
658std::optional<FullSourceLoc>
660 auto Hash = llvm::hash_value(F.getName());
661 for (const auto &Pair : ManglingFullSourceLocs) {
662 if (Pair.first == Hash)
663 return Pair.second;
664 }
665 return std::nullopt;
666}
667
669 const llvm::DiagnosticInfoUnsupported &D) {
670 // We only support warnings or errors.
671 assert(D.getSeverity() == llvm::DS_Error ||
672 D.getSeverity() == llvm::DS_Warning);
673
674 StringRef Filename;
675 unsigned Line, Column;
676 bool BadDebugInfo = false;
677 FullSourceLoc Loc;
678 std::string Msg;
679 raw_string_ostream MsgStream(Msg);
680
681 // Context will be nullptr for IR input files, we will construct the diag
682 // message from llvm::DiagnosticInfoUnsupported.
683 if (Context != nullptr) {
684 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
685 MsgStream << D.getMessage();
686 } else {
687 DiagnosticPrinterRawOStream DP(MsgStream);
688 D.print(DP);
689 }
690
691 auto DiagType = D.getSeverity() == llvm::DS_Error
692 ? diag::err_fe_backend_unsupported
693 : diag::warn_fe_backend_unsupported;
694 Diags.Report(Loc, DiagType) << MsgStream.str();
695
696 if (BadDebugInfo)
697 // If we were not able to translate the file:line:col information
698 // back to a SourceLocation, at least emit a note stating that
699 // we could not translate this location. This can happen in the
700 // case of #line directives.
701 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
702 << Filename << Line << Column;
703}
704
706 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
707 // We only support warnings and remarks.
708 assert(D.getSeverity() == llvm::DS_Remark ||
709 D.getSeverity() == llvm::DS_Warning);
710
711 StringRef Filename;
712 unsigned Line, Column;
713 bool BadDebugInfo = false;
714 FullSourceLoc Loc;
715 std::string Msg;
716 raw_string_ostream MsgStream(Msg);
717
718 // Context will be nullptr for IR input files, we will construct the remark
719 // message from llvm::DiagnosticInfoOptimizationBase.
720 if (Context != nullptr) {
721 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
722 MsgStream << D.getMsg();
723 } else {
724 DiagnosticPrinterRawOStream DP(MsgStream);
725 D.print(DP);
726 }
727
728 if (D.getHotness())
729 MsgStream << " (hotness: " << *D.getHotness() << ")";
730
731 Diags.Report(Loc, DiagID)
732 << AddFlagValue(D.getPassName())
733 << MsgStream.str();
734
735 if (BadDebugInfo)
736 // If we were not able to translate the file:line:col information
737 // back to a SourceLocation, at least emit a note stating that
738 // we could not translate this location. This can happen in the
739 // case of #line directives.
740 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
741 << Filename << Line << Column;
742}
743
745 const llvm::DiagnosticInfoOptimizationBase &D) {
746 // Without hotness information, don't show noisy remarks.
747 if (D.isVerbose() && !D.getHotness())
748 return;
749
750 if (D.isPassed()) {
751 // Optimization remarks are active only if the -Rpass flag has a regular
752 // expression that matches the name of the pass name in \p D.
753 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
754 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
755 } else if (D.isMissed()) {
756 // Missed optimization remarks are active only if the -Rpass-missed
757 // flag has a regular expression that matches the name of the pass
758 // name in \p D.
759 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
761 D, diag::remark_fe_backend_optimization_remark_missed);
762 } else {
763 assert(D.isAnalysis() && "Unknown remark type");
764
765 bool ShouldAlwaysPrint = false;
766 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
767 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
768
769 if (ShouldAlwaysPrint ||
770 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
772 D, diag::remark_fe_backend_optimization_remark_analysis);
773 }
774}
775
777 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
778 // Optimization analysis remarks are active if the pass name is set to
779 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
780 // regular expression that matches the name of the pass name in \p D.
781
782 if (D.shouldAlwaysPrint() ||
783 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
785 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
786}
787
789 const llvm::OptimizationRemarkAnalysisAliasing &D) {
790 // Optimization analysis remarks are active if the pass name is set to
791 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
792 // regular expression that matches the name of the pass name in \p D.
793
794 if (D.shouldAlwaysPrint() ||
795 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
797 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
798}
799
801 const llvm::DiagnosticInfoOptimizationFailure &D) {
802 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
803}
804
805void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
806 SourceLocation LocCookie =
807 SourceLocation::getFromRawEncoding(D.getLocCookie());
808
809 // FIXME: we can't yet diagnose indirect calls. When/if we can, we
810 // should instead assert that LocCookie.isValid().
811 if (!LocCookie.isValid())
812 return;
813
814 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
815 ? diag::err_fe_backend_error_attr
816 : diag::warn_fe_backend_warning_attr)
817 << llvm::demangle(D.getFunctionName()) << D.getNote();
818}
819
821 const llvm::DiagnosticInfoMisExpect &D) {
822 StringRef Filename;
823 unsigned Line, Column;
824 bool BadDebugInfo = false;
825 FullSourceLoc Loc =
827
828 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
829
830 if (BadDebugInfo)
831 // If we were not able to translate the file:line:col information
832 // back to a SourceLocation, at least emit a note stating that
833 // we could not translate this location. This can happen in the
834 // case of #line directives.
835 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
836 << Filename << Line << Column;
837}
838
839/// This function is invoked when the backend needs
840/// to report something to the user.
841void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
842 unsigned DiagID = diag::err_fe_inline_asm;
843 llvm::DiagnosticSeverity Severity = DI.getSeverity();
844 // Get the diagnostic ID based.
845 switch (DI.getKind()) {
846 case llvm::DK_InlineAsm:
847 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
848 return;
849 ComputeDiagID(Severity, inline_asm, DiagID);
850 break;
851 case llvm::DK_SrcMgr:
852 SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));
853 return;
854 case llvm::DK_StackSize:
855 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
856 return;
857 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
858 break;
859 case llvm::DK_ResourceLimit:
860 if (ResourceLimitDiagHandler(cast<DiagnosticInfoResourceLimit>(DI)))
861 return;
862 ComputeDiagID(Severity, backend_resource_limit, DiagID);
863 break;
864 case DK_Linker:
865 ComputeDiagID(Severity, linking_module, DiagID);
866 break;
867 case llvm::DK_OptimizationRemark:
868 // Optimization remarks are always handled completely by this
869 // handler. There is no generic way of emitting them.
870 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
871 return;
872 case llvm::DK_OptimizationRemarkMissed:
873 // Optimization remarks are always handled completely by this
874 // handler. There is no generic way of emitting them.
875 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
876 return;
877 case llvm::DK_OptimizationRemarkAnalysis:
878 // Optimization remarks are always handled completely by this
879 // handler. There is no generic way of emitting them.
880 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
881 return;
882 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
883 // Optimization remarks are always handled completely by this
884 // handler. There is no generic way of emitting them.
885 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
886 return;
887 case llvm::DK_OptimizationRemarkAnalysisAliasing:
888 // Optimization remarks are always handled completely by this
889 // handler. There is no generic way of emitting them.
890 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
891 return;
892 case llvm::DK_MachineOptimizationRemark:
893 // Optimization remarks are always handled completely by this
894 // handler. There is no generic way of emitting them.
895 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
896 return;
897 case llvm::DK_MachineOptimizationRemarkMissed:
898 // Optimization remarks are always handled completely by this
899 // handler. There is no generic way of emitting them.
900 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
901 return;
902 case llvm::DK_MachineOptimizationRemarkAnalysis:
903 // Optimization remarks are always handled completely by this
904 // handler. There is no generic way of emitting them.
905 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
906 return;
907 case llvm::DK_OptimizationFailure:
908 // Optimization failures are always handled completely by this
909 // handler.
910 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
911 return;
912 case llvm::DK_Unsupported:
913 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
914 return;
915 case llvm::DK_DontCall:
916 DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));
917 return;
918 case llvm::DK_MisExpect:
919 MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
920 return;
921 default:
922 // Plugin IDs are not bound to any value as they are set dynamically.
923 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
924 break;
925 }
926 std::string MsgStorage;
927 {
928 raw_string_ostream Stream(MsgStorage);
929 DiagnosticPrinterRawOStream DP(Stream);
930 DI.print(DP);
931 }
932
933 if (DI.getKind() == DK_Linker) {
934 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
935 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
936 return;
937 }
938
939 // Report the backend message using the usual diagnostic mechanism.
940 FullSourceLoc Loc;
941 Diags.Report(Loc, DiagID).AddString(MsgStorage);
942}
943#undef ComputeDiagID
944
945CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
946 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
947 OwnsVMContext(!_VMContext) {}
948
950 TheModule.reset();
951 if (OwnsVMContext)
952 delete VMContext;
953}
954
955bool CodeGenAction::loadLinkModules(CompilerInstance &CI) {
956 if (!LinkModules.empty())
957 return false;
958
961 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
962 if (!BCBuf) {
963 CI.getDiagnostics().Report(diag::err_cannot_open_file)
964 << F.Filename << BCBuf.getError().message();
965 LinkModules.clear();
966 return true;
967 }
968
970 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
971 if (!ModuleOrErr) {
972 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
973 CI.getDiagnostics().Report(diag::err_cannot_open_file)
974 << F.Filename << EIB.message();
975 });
976 LinkModules.clear();
977 return true;
978 }
979 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
980 F.Internalize, F.LinkFlags});
981 }
982 return false;
983}
984
985bool CodeGenAction::hasIRSupport() const { return true; }
986
988 // If the consumer creation failed, do nothing.
989 if (!getCompilerInstance().hasASTConsumer())
990 return;
991
992 // Steal the module from the consumer.
993 TheModule = BEConsumer->takeModule();
994}
995
996std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
997 return std::move(TheModule);
998}
999
1001 OwnsVMContext = false;
1002 return VMContext;
1003}
1004
1006 return BEConsumer->getCodeGenerator();
1007}
1008
1011 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
1012 return true;
1013}
1014
1015static std::unique_ptr<raw_pwrite_stream>
1016GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
1017 switch (Action) {
1019 return CI.createDefaultOutputFile(false, InFile, "s");
1020 case Backend_EmitLL:
1021 return CI.createDefaultOutputFile(false, InFile, "ll");
1022 case Backend_EmitBC:
1023 return CI.createDefaultOutputFile(true, InFile, "bc");
1025 return nullptr;
1026 case Backend_EmitMCNull:
1027 return CI.createNullOutputFile();
1028 case Backend_EmitObj:
1029 return CI.createDefaultOutputFile(true, InFile, "o");
1030 }
1031
1032 llvm_unreachable("Invalid action!");
1033}
1034
1035std::unique_ptr<ASTConsumer>
1037 BackendAction BA = static_cast<BackendAction>(Act);
1038 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
1039 if (!OS)
1040 OS = GetOutputStream(CI, InFile, BA);
1041
1042 if (BA != Backend_EmitNothing && !OS)
1043 return nullptr;
1044
1045 // Load bitcode modules to link with, if we need to.
1046 if (loadLinkModules(CI))
1047 return nullptr;
1048
1049 CoverageSourceInfo *CoverageInfo = nullptr;
1050 // Add the preprocessor callback only when the coverage mapping is generated.
1051 if (CI.getCodeGenOpts().CoverageMapping)
1053 CI.getPreprocessor());
1054
1055 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
1056 BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
1058 CI.getTargetOpts(), CI.getLangOpts(), CI.getFileManager(),
1059 std::string(InFile), std::move(LinkModules), std::move(OS), *VMContext,
1060 CoverageInfo));
1061 BEConsumer = Result.get();
1062
1063 // Enable generating macro debug info only when debug info is not disabled and
1064 // also macro debug info is enabled.
1065 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1066 CI.getCodeGenOpts().MacroDebugInfo) {
1067 std::unique_ptr<PPCallbacks> Callbacks =
1068 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
1069 CI.getPreprocessor());
1070 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
1071 }
1072
1073 if (CI.getFrontendOpts().GenReducedBMI &&
1074 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
1075 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1076 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1079 Consumers[1] = std::move(Result);
1080 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1081 }
1082
1083 return std::move(Result);
1084}
1085
1086std::unique_ptr<llvm::Module>
1087CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1090
1091 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1092 unsigned DiagID =
1094 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1095 CI.getDiagnostics().Report(DiagID) << EIB.message();
1096 });
1097 return {};
1098 };
1099
1100 // For ThinLTO backend invocations, ensure that the context
1101 // merges types based on ODR identifiers. We also need to read
1102 // the correct module out of a multi-module bitcode file.
1103 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1104 VMContext->enableDebugTypeODRUniquing();
1105
1106 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1107 if (!BMsOrErr)
1108 return DiagErrors(BMsOrErr.takeError());
1109 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1110 // We have nothing to do if the file contains no ThinLTO module. This is
1111 // possible if ThinLTO compilation was not able to split module. Content of
1112 // the file was already processed by indexing and will be passed to the
1113 // linker using merged object file.
1114 if (!Bm) {
1115 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1116 M->setTargetTriple(CI.getTargetOpts().Triple);
1117 return M;
1118 }
1120 Bm->parseModule(*VMContext);
1121 if (!MOrErr)
1122 return DiagErrors(MOrErr.takeError());
1123 return std::move(*MOrErr);
1124 }
1125
1126 // Load bitcode modules to link with, if we need to.
1127 if (loadLinkModules(CI))
1128 return nullptr;
1129
1130 // Handle textual IR and bitcode file with one single module.
1131 llvm::SMDiagnostic Err;
1132 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1133 return M;
1134
1135 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1136 // output), place the extra modules (actually only one, a regular LTO module)
1137 // into LinkModules as if we are using -mlink-bitcode-file.
1138 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1139 if (BMsOrErr && BMsOrErr->size()) {
1140 std::unique_ptr<llvm::Module> FirstM;
1141 for (auto &BM : *BMsOrErr) {
1143 BM.parseModule(*VMContext);
1144 if (!MOrErr)
1145 return DiagErrors(MOrErr.takeError());
1146 if (FirstM)
1147 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
1148 /*Internalize=*/false, /*LinkFlags=*/{}});
1149 else
1150 FirstM = std::move(*MOrErr);
1151 }
1152 if (FirstM)
1153 return FirstM;
1154 }
1155 // If BMsOrErr fails, consume the error and use the error message from
1156 // parseIR.
1157 consumeError(BMsOrErr.takeError());
1158
1159 // Translate from the diagnostic info to the SourceManager location if
1160 // available.
1161 // TODO: Unify this with ConvertBackendLocation()
1162 SourceLocation Loc;
1163 if (Err.getLineNo() > 0) {
1164 assert(Err.getColumnNo() >= 0);
1165 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1166 Err.getLineNo(), Err.getColumnNo() + 1);
1167 }
1168
1169 // Strip off a leading diagnostic code if there is one.
1170 StringRef Msg = Err.getMessage();
1171 Msg.consume_front("error: ");
1172
1173 unsigned DiagID =
1175
1176 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1177 return {};
1178}
1179
1181 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1183 return;
1184 }
1185
1186 // If this is an IR file, we have to treat it specially.
1187 BackendAction BA = static_cast<BackendAction>(Act);
1189 auto &CodeGenOpts = CI.getCodeGenOpts();
1190 auto &Diagnostics = CI.getDiagnostics();
1191 std::unique_ptr<raw_pwrite_stream> OS =
1193 if (BA != Backend_EmitNothing && !OS)
1194 return;
1195
1197 FileID FID = SM.getMainFileID();
1198 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1199 if (!MainFile)
1200 return;
1201
1202 TheModule = loadModule(*MainFile);
1203 if (!TheModule)
1204 return;
1205
1206 const TargetOptions &TargetOpts = CI.getTargetOpts();
1207 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1208 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1209 << TargetOpts.Triple;
1210 TheModule->setTargetTriple(TargetOpts.Triple);
1211 }
1212
1213 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1214 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1215
1216 LLVMContext &Ctx = TheModule->getContext();
1217
1218 // Restore any diagnostic handler previously set before returning from this
1219 // function.
1220 struct RAII {
1221 LLVMContext &Ctx;
1222 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1223 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1224 } _{Ctx};
1225
1226 // Set clang diagnostic handler. To do this we need to create a fake
1227 // BackendConsumer.
1230 CI.getCodeGenOpts(), CI.getTargetOpts(),
1231 CI.getLangOpts(), CI.getFileManager(), TheModule.get(),
1232 std::move(LinkModules), *VMContext, nullptr);
1233
1234 // Link in each pending link module.
1235 if (Result.LinkInModules(&*TheModule))
1236 return;
1237
1238 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1239 // true here because the valued names are needed for reading textual IR.
1240 Ctx.setDiscardValueNames(false);
1241 Ctx.setDiagnosticHandler(
1242 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1243
1245 setupLLVMOptimizationRemarks(
1246 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1247 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1248 CodeGenOpts.DiagnosticsHotnessThreshold);
1249
1250 if (Error E = OptRecordFileOrErr.takeError()) {
1251 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1252 return;
1253 }
1254 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1255 std::move(*OptRecordFileOrErr);
1256
1258 Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts, TargetOpts,
1259 CI.getLangOpts(), CI.getTarget().getDataLayoutString(), TheModule.get(),
1260 BA, CI.getFileManager().getVirtualFileSystemPtr(), std::move(OS));
1261 if (OptRecordFile)
1262 OptRecordFile->keep();
1263}
1264
1265//
1266
1267void EmitAssemblyAction::anchor() { }
1268EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1269 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1270
1271void EmitBCAction::anchor() { }
1272EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1273 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1274
1275void EmitLLVMAction::anchor() { }
1276EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1277 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1278
1279void EmitLLVMOnlyAction::anchor() { }
1280EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1281 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1282
1283void EmitCodeGenOnlyAction::anchor() { }
1285 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1286
1287void EmitObjAction::anchor() { }
1288EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1289 : CodeGenAction(Backend_EmitObj, _VMContext) {}
Defines the clang::ASTContext interface.
#define SM(sm)
Definition: Cuda.cpp:82
#define ComputeDiagID(Severity, GroupName, DiagID)
static std::unique_ptr< raw_pwrite_stream > GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action)
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM)
ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr buffer to be a valid FullS...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::FileManager interface and associated types.
StringRef Filename
Definition: Format.cpp:2971
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
SourceManager & getSourceManager()
Definition: ASTContext.h:705
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
llvm::Module * getModule() const
void OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D)
bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D)
Specialized handler for StackSize diagnostic.
void HandleVTable(CXXRecordDecl *RD) override
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
void HandleTagDeclDefinition(TagDecl *D) override
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
bool HandleTopLevelDecl(DeclGroupRef D) override
HandleTopLevelDecl - Handle the specified top-level declaration.
void Initialize(ASTContext &Ctx) override
Initialize - This is called to initialize the consumer, providing the ASTContext.
void HandleInlineFunctionDefinition(FunctionDecl *D) override
This callback is invoked each time an inline (method or friend) function definition in a class is com...
void OptimizationFailureHandler(const llvm::DiagnosticInfoOptimizationFailure &D)
void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI)
This function is invoked when the backend needs to report something to the user.
void HandleTagDeclRequiredDefinition(const TagDecl *D) override
This callback is invoked the first time each TagDecl is required to be complete.
void HandleInterestingDecl(DeclGroupRef D) override
HandleInterestingDecl - Handle the specified interesting declaration.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
std::optional< FullSourceLoc > getFunctionSourceLocation(const llvm::Function &F) const
bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D)
Specialized handler for ResourceLimit diagnostic.
std::unique_ptr< llvm::Module > takeModule()
void AssignInheritanceModel(CXXRecordDecl *RD) override
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
bool LinkInModules(llvm::Module *M, bool ShouldLinkFiles=true)
bool ReloadModules(llvm::Module *M)
void HandleTranslationUnit(ASTContext &C) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
void CompleteTentativeDefinition(VarDecl *D) override
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
void CompleteExternalDeclaration(VarDecl *D) override
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D)
Specialized handler for unsupported backend feature diagnostic.
bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D)
Specialized handler for InlineAsm diagnostic.
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, const FileManager &FileMgr, const std::string &InFile, SmallVector< LinkModule, 4 > LinkModules, std::unique_ptr< raw_pwrite_stream > OS, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
const FullSourceLoc getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const
Get the best possible source location to represent a diagnostic that may have associated debug info.
void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID)
Specialized handlers for optimization remarks.
void DontCallDiagHandler(const llvm::DiagnosticInfoDontCall &D)
void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D)
Specialized handler for misexpect warnings.
CodeGenerator * getCodeGenerator()
void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D)
Specialized handler for diagnostics reported using SMDiagnostic.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isMissedOptRemarkEnabled(StringRef PassName) const override
bool handleDiagnostics(const DiagnosticInfo &DI) override
ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
bool isPassedOptRemarkEnabled(StringRef PassName) const override
bool isAnyRemarkEnabled() const override
bool isAnalysisRemarkEnabled(StringRef PassName) const override
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
CodeGenerator * getCodeGenerator() const
friend class BackendConsumer
Definition: CodeGenAction.h:27
void EndSourceFileAction() override
Callback at the end of processing a single input.
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
CodeGenAction(unsigned _Act, llvm::LLVMContext *_VMContext=nullptr)
Create a new code generation action.
llvm::LLVMContext * takeLLVMContext()
Take the LLVM context used by this action.
BackendConsumer * BEConsumer
Definition: CodeGenAction.h:88
bool hasIRSupport() const override
Does this action support use with IR files?
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
std::unique_ptr< llvm::Module > takeModule()
Take the generated LLVM module, for use after the action has been run.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
std::optional< uint64_t > DiagnosticsHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
std::optional< uint32_t > DiagnosticsMisExpectTolerance
The maximum percentage profiling weights can deviate from the expected values in order to be included...
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
OptRemark OptimizationRemark
Selected optimizations for which we should enable optimization remarks.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
OptRemark OptimizationRemarkAnalysis
Selected optimizations for which we should enable optimization analyses.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
OptRemark OptimizationRemarkMissed
Selected optimizations for which we should enable missed optimization remarks.
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
The primary public interface to the Clang code generator.
Definition: ModuleBuilder.h:48
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
FileManager & getFileManager() const
Return the current file manager to the caller.
InMemoryModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
HeaderSearchOptions & getHeaderSearchOpts()
PreprocessorOptions & getPreprocessorOpts()
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
Stores additional source code information like skipped ranges which is required by the coverage mappi...
iterator begin()
Definition: DeclGroup.h:99
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
EmitAssemblyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitBCAction(llvm::LLVMContext *_VMContext=nullptr)
EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitLLVMAction(llvm::LLVMContext *_VMContext=nullptr)
EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitObjAction(llvm::LLVMContext *_VMContext=nullptr)
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
Definition: FileManager.h:253
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
InputKind getCurrentFileKind() const
CompilerInstance & getCompilerInstance() const
StringRef getCurrentFileOrBufferName() const
unsigned GenReducedBMI
Whether to generate reduced BMI for C++20 named modules.
std::string ModuleOutputPath
Output Path for module output file.
A SourceLocation and its associated SourceManager.
Represents a function declaration or definition.
Definition: Decl.h:1971
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
Definition: LangOptions.h:108
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
Describes a module or submodule.
Definition: Module.h:105
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition: DeclBase.h:1287
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
FileManager & getFileManager() const
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
A trivial tuple used to represent a source range.
void AddString(StringRef V) const
Definition: Diagnostic.h:1199
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
const char * getDataLayoutString() const
Definition: TargetInfo.h:1245
Options for controlling the target.
Definition: TargetOptions.h:26
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
Represents a variable declaration or definition.
Definition: Decl.h:918
Defines the clang::TargetInfo interface.
void mergeDefaultFunctionDefinitionAttributes(llvm::Function &F, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, bool WillInternalize)
Adds attributes to F according to our CodeGenOpts and LangOpts, as though we had emitted it ourselves...
Definition: CGCall.cpp:2071
@ VFS
Remove unused -ivfsoverlay arguments.
The JSON file list parser is used to communicate input to InstallAPI.
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
@ Result
The result type of a method or function.
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
BackendAction
Definition: BackendUtil.h:35
@ Backend_EmitAssembly
Emit native assembly files.
Definition: BackendUtil.h:36
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:38
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition: BackendUtil.h:37
@ Backend_EmitObj
Emit native object files.
Definition: BackendUtil.h:41
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition: BackendUtil.h:40
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition: BackendUtil.h:39
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
cl::opt< bool > ClRelinkBuiltinBitcodePostop
Definition: Format.h:5394
bool patternMatches(StringRef String) const
Matches the given string against the regex, if there is some.
bool hasValidPattern() const
Returns true iff the optimization remark holds a valid regular expression.