clang 23.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/ADT/ScopeExit.h"
33#include "llvm/Bitcode/BitcodeReader.h"
34#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
35#include "llvm/Demangle/Demangle.h"
36#include "llvm/IR/DebugInfo.h"
37#include "llvm/IR/DiagnosticInfo.h"
38#include "llvm/IR/DiagnosticPrinter.h"
39#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/LLVMRemarkStreamer.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Verifier.h"
44#include "llvm/IRReader/IRReader.h"
45#include "llvm/LTO/LTOBackend.h"
46#include "llvm/Linker/Linker.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/SourceMgr.h"
50#include "llvm/Support/TimeProfiler.h"
51#include "llvm/Support/Timer.h"
52#include "llvm/Support/ToolOutputFile.h"
53#include "llvm/Transforms/IPO/Internalize.h"
54#include "llvm/Transforms/Utils/Cloning.h"
55
56#include <optional>
57using namespace clang;
58using namespace llvm;
59
60#define DEBUG_TYPE "codegenaction"
61
62namespace clang {
63class BackendConsumer;
65public:
67 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
68
69 bool handleDiagnostics(const DiagnosticInfo &DI) override;
70
71 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
72 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
73 }
74 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
75 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
76 }
77 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
78 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
79 }
80
81 bool isAnyRemarkEnabled() const override {
82 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
83 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
84 CodeGenOpts.OptimizationRemark.hasValidPattern();
85 }
86
87private:
88 const CodeGenOptions &CodeGenOpts;
89 BackendConsumer *BackendCon;
90};
91
93 const CodeGenOptions &CodeGenOpts) {
94 handleAllErrors(
95 std::move(E),
96 [&](const LLVMRemarkSetupFileError &E) {
97 Diags.Report(diag::err_cannot_open_file)
98 << CodeGenOpts.OptRecordFile << E.message();
99 },
100 [&](const LLVMRemarkSetupPatternError &E) {
101 Diags.Report(diag::err_drv_optimization_remark_pattern)
102 << E.message() << CodeGenOpts.OptRecordPasses;
103 },
104 [&](const LLVMRemarkSetupFormatError &E) {
105 Diags.Report(diag::err_drv_optimization_remark_format)
106 << CodeGenOpts.OptRecordFormat;
107 });
108}
109
112 LLVMContext &C,
113 SmallVector<LinkModule, 4> LinkModules,
114 StringRef InFile,
115 std::unique_ptr<raw_pwrite_stream> OS,
116 CoverageSourceInfo *CoverageInfo,
117 llvm::Module *CurLinkModule)
118 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
119 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
120 AsmOutStream(std::move(OS)), FS(VFS), Action(Action),
121 Gen(CreateLLVMCodeGen(CI, InFile, C, CoverageInfo)),
122 LinkModules(std::move(LinkModules)), CurLinkModule(CurLinkModule) {
123 TimerIsEnabled = CodeGenOpts.TimePasses;
124 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
125 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
126 if (CodeGenOpts.TimePasses)
127 LLVMIRGeneration.init("irgen", "LLVM IR generation", CI.getTimerGroup());
128}
129
130llvm::Module* BackendConsumer::getModule() const {
131 return Gen->GetModule();
132}
133
134std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
135 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
136}
137
139 return Gen.get();
140}
141
145
147 assert(!Context && "initialized multiple times");
148
149 Context = &Ctx;
150
151 if (TimerIsEnabled)
152 LLVMIRGeneration.startTimer();
153
154 Gen->Initialize(Ctx);
155
156 if (TimerIsEnabled)
157 LLVMIRGeneration.stopTimer();
158}
159
161 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
162 Context->getSourceManager(),
163 "LLVM IR generation of declaration");
164
165 // Recurse.
166 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
167 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
168
169 Gen->HandleTopLevelDecl(D);
170
171 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
172 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
173
174 return true;
175}
176
179 Context->getSourceManager(),
180 "LLVM IR generation of inline function");
181 if (TimerIsEnabled)
182 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
183
184 Gen->HandleInlineFunctionDefinition(D);
185
186 if (TimerIsEnabled)
187 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
188}
189
193
194// Links each entry in LinkModules into our module. Returns true on error.
195bool BackendConsumer::LinkInModules(llvm::Module *M) {
196 for (auto &LM : LinkModules) {
197 assert(LM.Module && "LinkModule does not actually have a module");
198
199 if (LM.PropagateAttrs)
200 for (Function &F : *LM.Module) {
201 // Skip intrinsics. Keep consistent with how intrinsics are created
202 // in LLVM IR.
203 if (F.isIntrinsic())
204 continue;
206 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
207 }
208
209 CurLinkModule = LM.Module.get();
210 bool Err;
211
212 if (LM.Internalize) {
213 Err = Linker::linkModules(
214 *M, std::move(LM.Module), LM.LinkFlags,
215 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
216 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
217 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
218 });
219 });
220 } else
221 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
222
223 if (Err)
224 return true;
225 }
226
227 LinkModules.clear();
228 return false; // success
229}
230
232 {
233 llvm::TimeTraceScope TimeScope("Frontend");
234 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
235 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
236 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
237
238 Gen->HandleTranslationUnit(C);
239
240 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
241 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
242 }
243
244 // Silently ignore if we weren't initialized for some reason.
245 if (!getModule())
246 return;
247
248 LLVMContext &Ctx = getModule()->getContext();
249 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
250 Ctx.getDiagnosticHandler();
251 llvm::scope_exit RestoreDiagnosticHandler(
252 [&]() { Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); });
253 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
254 CodeGenOpts, this));
255
256 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
257 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
258
259 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
260 setupLLVMOptimizationRemarks(
261 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
262 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
263 CodeGenOpts.DiagnosticsHotnessThreshold);
264
265 if (Error E = OptRecordFileOrErr.takeError()) {
266 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
267 return;
268 }
269
270 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
271
272 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
273 llvm::driver::ProfileInstrKind::ProfileNone)
274 Ctx.setDiagnosticsHotnessRequested(true);
275
276 if (CodeGenOpts.MisExpect) {
277 Ctx.setMisExpectWarningRequested(true);
278 }
279
280 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
281 Ctx.setDiagnosticsMisExpectTolerance(
282 CodeGenOpts.DiagnosticsMisExpectTolerance);
283 }
284
285 // Link each LinkModule into our module.
286 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))
287 return;
288
289 for (auto &F : getModule()->functions()) {
290 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
291 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
292 // TODO: use a fast content hash when available.
293 auto NameHash = llvm::hash_value(F.getName());
294 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
295 }
296 }
297
298 if (CodeGenOpts.ClearASTBeforeBackend) {
299 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
300 // Access to the AST is no longer available after this.
301 // Other things that the ASTContext manages are still available, e.g.
302 // the SourceManager. It'd be nice if we could separate out all the
303 // things in ASTContext used after this point and null out the
304 // ASTContext, but too many various parts of the ASTContext are still
305 // used in various parts.
306 C.cleanup();
307 C.getAllocator().Reset();
308 }
309
310 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
311
312 emitBackendOutput(CI, CI.getCodeGenOpts(),
313 C.getTargetInfo().getDataLayoutString(), getModule(),
314 Action, FS, std::move(AsmOutStream), this);
315
316 if (OptRecordFile)
317 OptRecordFile->keep();
318}
319
322 Context->getSourceManager(),
323 "LLVM IR generation of declaration");
324 Gen->HandleTagDeclDefinition(D);
325}
326
328 Gen->HandleTagDeclRequiredDefinition(D);
329}
330
332 Gen->CompleteTentativeDefinition(D);
333}
334
336 Gen->CompleteExternalDeclaration(D);
337}
338
340 Gen->AssignInheritanceModel(RD);
341}
342
344 Gen->HandleVTable(RD);
345}
346
347void BackendConsumer::anchor() { }
348
349} // namespace clang
350
351bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
352 BackendCon->DiagnosticHandlerImpl(DI);
353 return true;
354}
355
356/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
357/// buffer to be a valid FullSourceLoc.
358static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
359 SourceManager &CSM) {
360 // Get both the clang and llvm source managers. The location is relative to
361 // a memory buffer that the LLVM Source Manager is handling, we need to add
362 // a copy to the Clang source manager.
363 const llvm::SourceMgr &LSM = *D.getSourceMgr();
364
365 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
366 // already owns its one and clang::SourceManager wants to own its one.
367 const MemoryBuffer *LBuf =
368 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
369
370 // Create the copy and transfer ownership to clang::SourceManager.
371 // TODO: Avoid copying files into memory.
372 std::unique_ptr<llvm::MemoryBuffer> CBuf =
373 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
374 LBuf->getBufferIdentifier());
375 // FIXME: Keep a file ID map instead of creating new IDs for each location.
376 FileID FID = CSM.createFileID(std::move(CBuf));
377
378 // Translate the offset into the file.
379 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
380 SourceLocation NewLoc =
381 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
382 return FullSourceLoc(NewLoc, CSM);
383}
384
385#define ComputeDiagID(Severity, GroupName, DiagID) \
386 do { \
387 switch (Severity) { \
388 case llvm::DS_Error: \
389 DiagID = diag::err_fe_##GroupName; \
390 break; \
391 case llvm::DS_Warning: \
392 DiagID = diag::warn_fe_##GroupName; \
393 break; \
394 case llvm::DS_Remark: \
395 llvm_unreachable("'remark' severity not expected"); \
396 break; \
397 case llvm::DS_Note: \
398 DiagID = diag::note_fe_##GroupName; \
399 break; \
400 } \
401 } while (false)
402
403#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
404 do { \
405 switch (Severity) { \
406 case llvm::DS_Error: \
407 DiagID = diag::err_fe_##GroupName; \
408 break; \
409 case llvm::DS_Warning: \
410 DiagID = diag::warn_fe_##GroupName; \
411 break; \
412 case llvm::DS_Remark: \
413 DiagID = diag::remark_fe_##GroupName; \
414 break; \
415 case llvm::DS_Note: \
416 DiagID = diag::note_fe_##GroupName; \
417 break; \
418 } \
419 } while (false)
420
421void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
422 const llvm::SMDiagnostic &D = DI.getSMDiag();
423
424 unsigned DiagID;
425 if (DI.isInlineAsmDiag())
426 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
427 else
428 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
429
430 // This is for the empty BackendConsumer that uses the clang diagnostic
431 // handler for IR input files.
432 if (!Context) {
433 D.print(nullptr, llvm::errs());
434 Diags.Report(DiagID).AddString("cannot compile inline asm");
435 return;
436 }
437
438 // There are a couple of different kinds of errors we could get here.
439 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
440
441 // Strip "error: " off the start of the message string.
442 StringRef Message = D.getMessage();
443 (void)Message.consume_front("error: ");
444
445 // If the SMDiagnostic has an inline asm source location, translate it.
446 FullSourceLoc Loc;
447 if (D.getLoc() != SMLoc())
448 Loc = ConvertBackendLocation(D, Context->getSourceManager());
449
450 // If this problem has clang-level source location information, report the
451 // issue in the source with a note showing the instantiated
452 // code.
453 if (DI.isInlineAsmDiag()) {
454 SourceLocation LocCookie =
455 SourceLocation::getFromRawEncoding(DI.getLocCookie());
456 if (LocCookie.isValid()) {
457 Diags.Report(LocCookie, DiagID).AddString(Message);
458
459 if (D.getLoc().isValid()) {
460 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
461 // Convert the SMDiagnostic ranges into SourceRange and attach them
462 // to the diagnostic.
463 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
464 unsigned Column = D.getColumnNo();
465 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
466 Loc.getLocWithOffset(Range.second - Column));
467 }
468 }
469 return;
470 }
471 }
472
473 // Otherwise, report the backend issue as occurring in the generated .s file.
474 // If Loc is invalid, we still need to report the issue, it just gets no
475 // location info.
476 Diags.Report(Loc, DiagID).AddString(Message);
477}
478
479bool
480BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
481 unsigned DiagID;
482 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
483 std::string Message = D.getMsgStr().str();
484
485 // If this problem has clang-level source location information, report the
486 // issue as being a problem in the source with a note showing the instantiated
487 // code.
488 SourceLocation LocCookie =
489 SourceLocation::getFromRawEncoding(D.getLocCookie());
490 if (LocCookie.isValid())
491 Diags.Report(LocCookie, DiagID).AddString(Message);
492 else {
493 // Otherwise, report the backend diagnostic as occurring in the generated
494 // .s file.
495 // If Loc is invalid, we still need to report the diagnostic, it just gets
496 // no location info.
497 FullSourceLoc Loc;
498 Diags.Report(Loc, DiagID).AddString(Message);
499 }
500 // We handled all the possible severities.
501 return true;
502}
503
504bool
505BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
506 if (D.getSeverity() != llvm::DS_Warning)
507 // For now, the only support we have for StackSize diagnostic is warning.
508 // We do not know how to format other severities.
509 return false;
510
511 auto Loc = getFunctionSourceLocation(D.getFunction());
512 if (!Loc)
513 return false;
514
515 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
516 << D.getStackSize() << D.getStackLimit()
517 << llvm::demangle(D.getFunction().getName());
518 return true;
519}
520
522 const llvm::DiagnosticInfoResourceLimit &D) {
523 auto Loc = getFunctionSourceLocation(D.getFunction());
524 if (!Loc)
525 return false;
526 unsigned DiagID = diag::err_fe_backend_resource_limit;
527 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
528
529 Diags.Report(*Loc, DiagID)
530 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
531 << llvm::demangle(D.getFunction().getName());
532 return true;
533}
534
536 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
537 StringRef &Filename, unsigned &Line, unsigned &Column) const {
538 SourceManager &SourceMgr = Context->getSourceManager();
539 FileManager &FileMgr = SourceMgr.getFileManager();
540 SourceLocation DILoc;
541
542 if (D.isLocationAvailable()) {
543 D.getLocation(Filename, Line, Column);
544 if (Line > 0) {
545 auto FE = FileMgr.getOptionalFileRef(Filename);
546 if (!FE)
547 FE = FileMgr.getOptionalFileRef(D.getAbsolutePath());
548 if (FE) {
549 // If -gcolumn-info was not used, Column will be 0. This upsets the
550 // source manager, so pass 1 if Column is not set.
551 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
552 }
553 }
554 BadDebugInfo = DILoc.isInvalid();
555 }
556
557 // If a location isn't available, try to approximate it using the associated
558 // function definition. We use the definition's right brace to differentiate
559 // from diagnostics that genuinely relate to the function itself.
560 FullSourceLoc Loc(DILoc, SourceMgr);
561 if (Loc.isInvalid()) {
562 if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
563 Loc = *MaybeLoc;
564 }
565
566 if (DILoc.isInvalid() && D.isLocationAvailable())
567 // If we were not able to translate the file:line:col information
568 // back to a SourceLocation, at least emit a note stating that
569 // we could not translate this location. This can happen in the
570 // case of #line directives.
571 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
572 << Filename << Line << Column;
573
574 return Loc;
575}
576
577std::optional<FullSourceLoc>
579 auto Hash = llvm::hash_value(F.getName());
580 for (const auto &Pair : ManglingFullSourceLocs) {
581 if (Pair.first == Hash)
582 return Pair.second;
583 }
584 return std::nullopt;
585}
586
588 const llvm::DiagnosticInfoUnsupported &D) {
589 // We only support warnings or errors.
590 assert(D.getSeverity() == llvm::DS_Error ||
591 D.getSeverity() == llvm::DS_Warning);
592
593 StringRef Filename;
594 unsigned Line, Column;
595 bool BadDebugInfo = false;
596 FullSourceLoc Loc;
597 std::string Msg;
598 raw_string_ostream MsgStream(Msg);
599
600 // Context will be nullptr for IR input files, we will construct the diag
601 // message from llvm::DiagnosticInfoUnsupported.
602 if (Context != nullptr) {
603 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
604 MsgStream << D.getMessage();
605 } else {
606 DiagnosticPrinterRawOStream DP(MsgStream);
607 D.print(DP);
608 }
609
610 auto DiagType = D.getSeverity() == llvm::DS_Error
611 ? diag::err_fe_backend_unsupported
612 : diag::warn_fe_backend_unsupported;
613 Diags.Report(Loc, DiagType) << Msg;
614
615 if (BadDebugInfo)
616 // If we were not able to translate the file:line:col information
617 // back to a SourceLocation, at least emit a note stating that
618 // we could not translate this location. This can happen in the
619 // case of #line directives.
620 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
621 << Filename << Line << Column;
622}
623
625 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
626 // We only support warnings and remarks.
627 assert(D.getSeverity() == llvm::DS_Remark ||
628 D.getSeverity() == llvm::DS_Warning);
629
630 StringRef Filename;
631 unsigned Line, Column;
632 bool BadDebugInfo = false;
633 FullSourceLoc Loc;
634 std::string Msg;
635 raw_string_ostream MsgStream(Msg);
636
637 // Context will be nullptr for IR input files, we will construct the remark
638 // message from llvm::DiagnosticInfoOptimizationBase.
639 if (Context != nullptr) {
640 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
641 MsgStream << D.getMsg();
642 } else {
643 DiagnosticPrinterRawOStream DP(MsgStream);
644 D.print(DP);
645 }
646
647 if (D.getHotness())
648 MsgStream << " (hotness: " << *D.getHotness() << ")";
649
650 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;
651
652 if (BadDebugInfo)
653 // If we were not able to translate the file:line:col information
654 // back to a SourceLocation, at least emit a note stating that
655 // we could not translate this location. This can happen in the
656 // case of #line directives.
657 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
658 << Filename << Line << Column;
659}
660
662 const llvm::DiagnosticInfoOptimizationBase &D) {
663 // Without hotness information, don't show noisy remarks.
664 if (D.isVerbose() && !D.getHotness())
665 return;
666
667 if (D.isPassed()) {
668 // Optimization remarks are active only if the -Rpass flag has a regular
669 // expression that matches the name of the pass name in \p D.
670 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
671 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
672 } else if (D.isMissed()) {
673 // Missed optimization remarks are active only if the -Rpass-missed
674 // flag has a regular expression that matches the name of the pass
675 // name in \p D.
676 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
678 D, diag::remark_fe_backend_optimization_remark_missed);
679 } else {
680 assert(D.isAnalysis() && "Unknown remark type");
681
682 bool ShouldAlwaysPrint = false;
683 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
684 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
685
686 if (ShouldAlwaysPrint ||
687 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
689 D, diag::remark_fe_backend_optimization_remark_analysis);
690 }
691}
692
694 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
695 // Optimization analysis remarks are active if the pass name is set to
696 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
697 // regular expression that matches the name of the pass name in \p D.
698
699 if (D.shouldAlwaysPrint() ||
700 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
702 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
703}
704
706 const llvm::OptimizationRemarkAnalysisAliasing &D) {
707 // Optimization analysis remarks are active if the pass name is set to
708 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
709 // regular expression that matches the name of the pass name in \p D.
710
711 if (D.shouldAlwaysPrint() ||
712 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
714 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
715}
716
718 const llvm::DiagnosticInfoOptimizationFailure &D) {
719 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
720}
721
722void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
723 SourceLocation LocCookie =
724 SourceLocation::getFromRawEncoding(D.getLocCookie());
725
726 // FIXME: we can't yet diagnose indirect calls. When/if we can, we
727 // should instead assert that LocCookie.isValid().
728 if (!LocCookie.isValid())
729 return;
730
731 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
732 ? diag::err_fe_backend_error_attr
733 : diag::warn_fe_backend_warning_attr)
734 << llvm::demangle(D.getFunctionName()) << D.getNote();
735
736 if (!CodeGenOpts.ShowInliningChain)
737 return;
738
739 auto EmitNote = [&](SourceLocation Loc, StringRef FuncName, bool IsFirst) {
740 if (!Loc.isValid())
741 Loc = LocCookie;
742 unsigned DiagID =
743 IsFirst ? diag::note_fe_backend_in : diag::note_fe_backend_inlined;
744 Diags.Report(Loc, DiagID) << llvm::demangle(FuncName.str());
745 };
746
747 // Try debug info first for accurate source locations.
748 if (!D.getDebugInlineChain().empty()) {
749 SourceManager &SM = Context->getSourceManager();
750 FileManager &FM = SM.getFileManager();
751 for (const auto &[I, Info] : llvm::enumerate(D.getDebugInlineChain())) {
752 SourceLocation Loc;
753 if (Info.Line > 0)
754 if (auto FE = FM.getOptionalFileRef(Info.Filename))
755 Loc = SM.translateFileLineCol(*FE, Info.Line,
756 Info.Column ? Info.Column : 1);
757 EmitNote(Loc, Info.FuncName, I == 0);
758 }
759 return;
760 }
761
762 // Fall back to heuristic (srcloc metadata) when debug info is unavailable.
763 auto InliningDecisions = D.getInliningDecisions();
764 if (InliningDecisions.empty())
765 return;
766
767 for (const auto &[I, Entry] : llvm::enumerate(InliningDecisions)) {
768 SourceLocation Loc =
769 I == 0 ? LocCookie : SourceLocation::getFromRawEncoding(Entry.second);
770 EmitNote(Loc, Entry.first, I == 0);
771 }
772
773 // Suggest enabling debug info (at least -gline-directives-only) for more
774 // accurate locations.
775 Diags.Report(LocCookie, diag::note_fe_backend_inlining_debug_info);
776}
777
779 const llvm::DiagnosticInfoMisExpect &D) {
780 StringRef Filename;
781 unsigned Line, Column;
782 bool BadDebugInfo = false;
783 FullSourceLoc Loc =
784 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
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:
806 return;
807 ComputeDiagID(Severity, inline_asm, DiagID);
808 break;
809 case llvm::DK_SrcMgr:
811 return;
812 case llvm::DK_StackSize:
814 return;
815 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
816 break;
817 case llvm::DK_ResourceLimit:
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.
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.
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.
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.
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.
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.
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.
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.
864 return;
865 case llvm::DK_OptimizationFailure:
866 // Optimization failures are always handled completely by this
867 // handler.
869 return;
870 case llvm::DK_Unsupported:
872 return;
873 case llvm::DK_DontCall:
875 return;
876 case llvm::DK_MisExpect:
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.
898 FullSourceLoc Loc;
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
947
948 // If the consumer creation failed, do nothing.
949 if (!getCompilerInstance().hasASTConsumer())
950 return;
951
952 // Steal the module from the consumer.
953 TheModule = BEConsumer->takeModule();
954}
955
956std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
957 return std::move(TheModule);
958}
959
960llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
961 OwnsVMContext = false;
962 return VMContext;
963}
964
966 return BEConsumer->getCodeGenerator();
967}
968
974
975static std::unique_ptr<raw_pwrite_stream>
976GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
977 switch (Action) {
979 return CI.createDefaultOutputFile(false, InFile, "s");
980 case Backend_EmitLL:
981 return CI.createDefaultOutputFile(false, InFile, "ll");
982 case Backend_EmitBC:
983 return CI.createDefaultOutputFile(true, InFile, "bc");
985 return nullptr;
987 return CI.createNullOutputFile();
988 case Backend_EmitObj:
989 return CI.createDefaultOutputFile(true, InFile, "o");
990 }
991
992 llvm_unreachable("Invalid action!");
993}
994
995std::unique_ptr<ASTConsumer>
997 BackendAction BA = static_cast<BackendAction>(Act);
998 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
999 if (!OS)
1000 OS = GetOutputStream(CI, InFile, BA);
1001
1002 if (BA != Backend_EmitNothing && !OS)
1003 return nullptr;
1004
1005 // Load bitcode modules to link with, if we need to.
1006 if (loadLinkModules(CI))
1007 return nullptr;
1008
1009 CoverageSourceInfo *CoverageInfo = nullptr;
1010 // Add the preprocessor callback only when the coverage mapping is generated.
1011 if (CI.getCodeGenOpts().CoverageMapping)
1013 CI.getPreprocessor());
1014
1015 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
1016 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
1017 InFile, std::move(OS), 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(Triple(CI.getTargetOpts().Triple));
1074 return M;
1075 }
1076 Expected<std::unique_ptr<llvm::Module>> MOrErr =
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 // For LLVM IR files, always verify the input and report the error in a way
1091 // that does not ask people to report an issue for it.
1092 std::string VerifierErr;
1093 raw_string_ostream VerifierErrStream(VerifierErr);
1094 if (llvm::verifyModule(*M, &VerifierErrStream)) {
1095 CI.getDiagnostics().Report(diag::err_invalid_llvm_ir) << VerifierErr;
1096 return {};
1097 }
1098 return M;
1099 }
1100
1101 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1102 // output), place the extra modules (actually only one, a regular LTO module)
1103 // into LinkModules as if we are using -mlink-bitcode-file.
1104 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1105 if (BMsOrErr && BMsOrErr->size()) {
1106 std::unique_ptr<llvm::Module> FirstM;
1107 for (auto &BM : *BMsOrErr) {
1108 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1109 BM.parseModule(*VMContext);
1110 if (!MOrErr)
1111 return DiagErrors(MOrErr.takeError());
1112 if (FirstM)
1113 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
1114 /*Internalize=*/false, /*LinkFlags=*/{}});
1115 else
1116 FirstM = std::move(*MOrErr);
1117 }
1118 if (FirstM)
1119 return FirstM;
1120 }
1121 // If BMsOrErr fails, consume the error and use the error message from
1122 // parseIR.
1123 consumeError(BMsOrErr.takeError());
1124
1125 // Translate from the diagnostic info to the SourceManager location if
1126 // available.
1127 // TODO: Unify this with ConvertBackendLocation()
1128 SourceLocation Loc;
1129 if (Err.getLineNo() > 0) {
1130 assert(Err.getColumnNo() >= 0);
1131 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1132 Err.getLineNo(), Err.getColumnNo() + 1);
1133 }
1134
1135 // Strip off a leading diagnostic code if there is one.
1136 StringRef Msg = Err.getMessage();
1137 Msg.consume_front("error: ");
1138
1139 unsigned DiagID =
1141
1142 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1143 return {};
1144}
1145
1147 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1149 return;
1150 }
1151
1152 // If this is an IR file, we have to treat it specially.
1153 BackendAction BA = static_cast<BackendAction>(Act);
1155 auto &CodeGenOpts = CI.getCodeGenOpts();
1156 auto &Diagnostics = CI.getDiagnostics();
1157 std::unique_ptr<raw_pwrite_stream> OS =
1159 if (BA != Backend_EmitNothing && !OS)
1160 return;
1161
1163 FileID FID = SM.getMainFileID();
1164 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1165 if (!MainFile)
1166 return;
1167
1168 TheModule = loadModule(*MainFile);
1169 if (!TheModule)
1170 return;
1171
1172 const TargetOptions &TargetOpts = CI.getTargetOpts();
1173 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
1174 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1175 << TargetOpts.Triple;
1176 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
1177 }
1178
1179 EmbedObject(TheModule.get(), CodeGenOpts, CI.getVirtualFileSystem(),
1180 Diagnostics);
1181 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1182
1183 LLVMContext &Ctx = TheModule->getContext();
1184
1185 // Restore any diagnostic handler previously set before returning from this
1186 // function.
1187 struct RAII {
1188 LLVMContext &Ctx;
1189 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1190 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1191 } _{Ctx};
1192
1193 // Set clang diagnostic handler. To do this we need to create a fake
1194 // BackendConsumer.
1195 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
1196 std::move(LinkModules), "", nullptr, nullptr,
1197 TheModule.get());
1198
1199 // Link in each pending link module.
1200 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
1201 return;
1202
1203 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1204 // true here because the valued names are needed for reading textual IR.
1205 Ctx.setDiscardValueNames(false);
1206 Ctx.setDiagnosticHandler(
1207 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1208
1209 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1210 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
1211
1212 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
1213 setupLLVMOptimizationRemarks(
1214 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1215 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1216 CodeGenOpts.DiagnosticsHotnessThreshold);
1217
1218 if (Error E = OptRecordFileOrErr.takeError()) {
1219 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1220 return;
1221 }
1222 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1223
1225 CI.getTarget().getDataLayoutString(), TheModule.get(), BA,
1227 std::move(OS));
1228 if (OptRecordFile)
1229 OptRecordFile->keep();
1230}
1231
1232//
1233
1234void EmitAssemblyAction::anchor() { }
1235EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1236 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1237
1238void EmitBCAction::anchor() { }
1239EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1240 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1241
1242void EmitLLVMAction::anchor() { }
1243EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1244 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1245
1246void EmitLLVMOnlyAction::anchor() { }
1247EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1248 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1249
1250void EmitCodeGenOnlyAction::anchor() { }
1252 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1253
1254void EmitObjAction::anchor() { }
1255EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1256 : CodeGenAction(Backend_EmitObj, _VMContext) {}
Defines the clang::ASTContext interface.
#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.
unsigned IsFirst
Indicates that this is the first token of the file.
#define SM(sm)
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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
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
bool hasIRSupport() const override
Does this action support use with IR files?
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
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::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
The primary public interface to the Clang code generator.
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.
ModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
Stores additional source code information like skipped ranges which is required by the coverage mappi...
iterator begin()
Definition DeclGroup.h:95
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:913
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.
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
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:2015
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
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...
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.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3732
const char * getDataLayoutString() const
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string CPU
If given, the name of the target CPU to generate code for.
Represents a variable declaration or definition.
Definition Decl.h:926
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:2235
The JSON file list parser is used to communicate input to InstallAPI.
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
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 EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
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
std::unique_ptr< CodeGenerator > CreateLLVMCodeGen(const CompilerInstance &CI, llvm::StringRef ModuleName, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
U cast(CodeGen::Address addr)
Definition Address.h:327
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)