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