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