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