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