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 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
252 CodeGenOpts, this));
253
254 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
255 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
256
257 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
258 setupLLVMOptimizationRemarks(
259 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
260 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
261 CodeGenOpts.DiagnosticsHotnessThreshold);
262
263 if (Error E = OptRecordFileOrErr.takeError()) {
264 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
265 return;
266 }
267
268 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
269
270 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
271 llvm::driver::ProfileInstrKind::ProfileNone)
272 Ctx.setDiagnosticsHotnessRequested(true);
273
274 if (CodeGenOpts.MisExpect) {
275 Ctx.setMisExpectWarningRequested(true);
276 }
277
278 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
279 Ctx.setDiagnosticsMisExpectTolerance(
280 CodeGenOpts.DiagnosticsMisExpectTolerance);
281 }
282
283 // Link each LinkModule into our module.
284 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))
285 return;
286
287 for (auto &F : getModule()->functions()) {
288 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
289 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
290 // TODO: use a fast content hash when available.
291 auto NameHash = llvm::hash_value(F.getName());
292 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
293 }
294 }
295
296 if (CodeGenOpts.ClearASTBeforeBackend) {
297 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
298 // Access to the AST is no longer available after this.
299 // Other things that the ASTContext manages are still available, e.g.
300 // the SourceManager. It'd be nice if we could separate out all the
301 // things in ASTContext used after this point and null out the
302 // ASTContext, but too many various parts of the ASTContext are still
303 // used in various parts.
304 C.cleanup();
305 C.getAllocator().Reset();
306 }
307
308 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
309
310 emitBackendOutput(CI, CI.getCodeGenOpts(),
311 C.getTargetInfo().getDataLayoutString(), getModule(),
312 Action, FS, std::move(AsmOutStream), this);
313
314 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
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
738 const llvm::DiagnosticInfoMisExpect &D) {
739 StringRef Filename;
740 unsigned Line, Column;
741 bool BadDebugInfo = false;
742 FullSourceLoc Loc =
743 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
744
745 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
746
747 if (BadDebugInfo)
748 // If we were not able to translate the file:line:col information
749 // back to a SourceLocation, at least emit a note stating that
750 // we could not translate this location. This can happen in the
751 // case of #line directives.
752 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
753 << Filename << Line << Column;
754}
755
756/// This function is invoked when the backend needs
757/// to report something to the user.
758void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
759 unsigned DiagID = diag::err_fe_inline_asm;
760 llvm::DiagnosticSeverity Severity = DI.getSeverity();
761 // Get the diagnostic ID based.
762 switch (DI.getKind()) {
763 case llvm::DK_InlineAsm:
765 return;
766 ComputeDiagID(Severity, inline_asm, DiagID);
767 break;
768 case llvm::DK_SrcMgr:
770 return;
771 case llvm::DK_StackSize:
773 return;
774 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
775 break;
776 case llvm::DK_ResourceLimit:
778 return;
779 ComputeDiagID(Severity, backend_resource_limit, DiagID);
780 break;
781 case DK_Linker:
782 ComputeDiagID(Severity, linking_module, DiagID);
783 break;
784 case llvm::DK_OptimizationRemark:
785 // Optimization remarks are always handled completely by this
786 // handler. There is no generic way of emitting them.
788 return;
789 case llvm::DK_OptimizationRemarkMissed:
790 // Optimization remarks are always handled completely by this
791 // handler. There is no generic way of emitting them.
793 return;
794 case llvm::DK_OptimizationRemarkAnalysis:
795 // Optimization remarks are always handled completely by this
796 // handler. There is no generic way of emitting them.
798 return;
799 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
800 // Optimization remarks are always handled completely by this
801 // handler. There is no generic way of emitting them.
803 return;
804 case llvm::DK_OptimizationRemarkAnalysisAliasing:
805 // Optimization remarks are always handled completely by this
806 // handler. There is no generic way of emitting them.
808 return;
809 case llvm::DK_MachineOptimizationRemark:
810 // Optimization remarks are always handled completely by this
811 // handler. There is no generic way of emitting them.
813 return;
814 case llvm::DK_MachineOptimizationRemarkMissed:
815 // Optimization remarks are always handled completely by this
816 // handler. There is no generic way of emitting them.
818 return;
819 case llvm::DK_MachineOptimizationRemarkAnalysis:
820 // Optimization remarks are always handled completely by this
821 // handler. There is no generic way of emitting them.
823 return;
824 case llvm::DK_OptimizationFailure:
825 // Optimization failures are always handled completely by this
826 // handler.
828 return;
829 case llvm::DK_Unsupported:
831 return;
832 case llvm::DK_DontCall:
834 return;
835 case llvm::DK_MisExpect:
837 return;
838 default:
839 // Plugin IDs are not bound to any value as they are set dynamically.
840 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
841 break;
842 }
843 std::string MsgStorage;
844 {
845 raw_string_ostream Stream(MsgStorage);
846 DiagnosticPrinterRawOStream DP(Stream);
847 DI.print(DP);
848 }
849
850 if (DI.getKind() == DK_Linker) {
851 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
852 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
853 return;
854 }
855
856 // Report the backend message using the usual diagnostic mechanism.
857 FullSourceLoc Loc;
858 Diags.Report(Loc, DiagID).AddString(MsgStorage);
859}
860#undef ComputeDiagID
861
862CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
863 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
864 OwnsVMContext(!_VMContext) {}
865
867 TheModule.reset();
868 if (OwnsVMContext)
869 delete VMContext;
870}
871
872bool CodeGenAction::loadLinkModules(CompilerInstance &CI) {
873 if (!LinkModules.empty())
874 return false;
875
878 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
879 if (!BCBuf) {
880 CI.getDiagnostics().Report(diag::err_cannot_open_file)
881 << F.Filename << BCBuf.getError().message();
882 LinkModules.clear();
883 return true;
884 }
885
887 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
888 if (!ModuleOrErr) {
889 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
890 CI.getDiagnostics().Report(diag::err_cannot_open_file)
891 << F.Filename << EIB.message();
892 });
893 LinkModules.clear();
894 return true;
895 }
896 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
897 F.Internalize, F.LinkFlags});
898 }
899 return false;
900}
901
902bool CodeGenAction::hasIRSupport() const { return true; }
903
906
907 // If the consumer creation failed, do nothing.
908 if (!getCompilerInstance().hasASTConsumer())
909 return;
910
911 // Steal the module from the consumer.
912 TheModule = BEConsumer->takeModule();
913}
914
915std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
916 return std::move(TheModule);
917}
918
919llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
920 OwnsVMContext = false;
921 return VMContext;
922}
923
925 return BEConsumer->getCodeGenerator();
926}
927
933
934static std::unique_ptr<raw_pwrite_stream>
935GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
936 switch (Action) {
938 return CI.createDefaultOutputFile(false, InFile, "s");
939 case Backend_EmitLL:
940 return CI.createDefaultOutputFile(false, InFile, "ll");
941 case Backend_EmitBC:
942 return CI.createDefaultOutputFile(true, InFile, "bc");
944 return nullptr;
946 return CI.createNullOutputFile();
947 case Backend_EmitObj:
948 return CI.createDefaultOutputFile(true, InFile, "o");
949 }
950
951 llvm_unreachable("Invalid action!");
952}
953
954std::unique_ptr<ASTConsumer>
956 BackendAction BA = static_cast<BackendAction>(Act);
957 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
958 if (!OS)
959 OS = GetOutputStream(CI, InFile, BA);
960
961 if (BA != Backend_EmitNothing && !OS)
962 return nullptr;
963
964 // Load bitcode modules to link with, if we need to.
965 if (loadLinkModules(CI))
966 return nullptr;
967
968 CoverageSourceInfo *CoverageInfo = nullptr;
969 // Add the preprocessor callback only when the coverage mapping is generated.
970 if (CI.getCodeGenOpts().CoverageMapping)
972 CI.getPreprocessor());
973
974 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
975 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
976 InFile, std::move(OS), CoverageInfo));
977 BEConsumer = Result.get();
978
979 // Enable generating macro debug info only when debug info is not disabled and
980 // also macro debug info is enabled.
981 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
982 CI.getCodeGenOpts().MacroDebugInfo) {
983 std::unique_ptr<PPCallbacks> Callbacks =
984 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
985 CI.getPreprocessor());
986 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
987 }
988
990 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
991 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
992 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
995 Consumers[1] = std::move(Result);
996 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
997 }
998
999 return std::move(Result);
1000}
1001
1002std::unique_ptr<llvm::Module>
1003CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1006
1007 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1008 unsigned DiagID =
1010 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1011 CI.getDiagnostics().Report(DiagID) << EIB.message();
1012 });
1013 return {};
1014 };
1015
1016 // For ThinLTO backend invocations, ensure that the context
1017 // merges types based on ODR identifiers. We also need to read
1018 // the correct module out of a multi-module bitcode file.
1019 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1020 VMContext->enableDebugTypeODRUniquing();
1021
1022 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1023 if (!BMsOrErr)
1024 return DiagErrors(BMsOrErr.takeError());
1025 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1026 // We have nothing to do if the file contains no ThinLTO module. This is
1027 // possible if ThinLTO compilation was not able to split module. Content of
1028 // the file was already processed by indexing and will be passed to the
1029 // linker using merged object file.
1030 if (!Bm) {
1031 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1032 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
1033 return M;
1034 }
1035 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1036 Bm->parseModule(*VMContext);
1037 if (!MOrErr)
1038 return DiagErrors(MOrErr.takeError());
1039 return std::move(*MOrErr);
1040 }
1041
1042 // Load bitcode modules to link with, if we need to.
1043 if (loadLinkModules(CI))
1044 return nullptr;
1045
1046 // Handle textual IR and bitcode file with one single module.
1047 llvm::SMDiagnostic Err;
1048 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
1049 // For LLVM IR files, always verify the input and report the error in a way
1050 // that does not ask people to report an issue for it.
1051 std::string VerifierErr;
1052 raw_string_ostream VerifierErrStream(VerifierErr);
1053 if (llvm::verifyModule(*M, &VerifierErrStream)) {
1054 CI.getDiagnostics().Report(diag::err_invalid_llvm_ir) << VerifierErr;
1055 return {};
1056 }
1057 return M;
1058 }
1059
1060 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1061 // output), place the extra modules (actually only one, a regular LTO module)
1062 // into LinkModules as if we are using -mlink-bitcode-file.
1063 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1064 if (BMsOrErr && BMsOrErr->size()) {
1065 std::unique_ptr<llvm::Module> FirstM;
1066 for (auto &BM : *BMsOrErr) {
1067 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1068 BM.parseModule(*VMContext);
1069 if (!MOrErr)
1070 return DiagErrors(MOrErr.takeError());
1071 if (FirstM)
1072 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
1073 /*Internalize=*/false, /*LinkFlags=*/{}});
1074 else
1075 FirstM = std::move(*MOrErr);
1076 }
1077 if (FirstM)
1078 return FirstM;
1079 }
1080 // If BMsOrErr fails, consume the error and use the error message from
1081 // parseIR.
1082 consumeError(BMsOrErr.takeError());
1083
1084 // Translate from the diagnostic info to the SourceManager location if
1085 // available.
1086 // TODO: Unify this with ConvertBackendLocation()
1087 SourceLocation Loc;
1088 if (Err.getLineNo() > 0) {
1089 assert(Err.getColumnNo() >= 0);
1090 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1091 Err.getLineNo(), Err.getColumnNo() + 1);
1092 }
1093
1094 // Strip off a leading diagnostic code if there is one.
1095 StringRef Msg = Err.getMessage();
1096 Msg.consume_front("error: ");
1097
1098 unsigned DiagID =
1100
1101 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1102 return {};
1103}
1104
1106 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1108 return;
1109 }
1110
1111 // If this is an IR file, we have to treat it specially.
1112 BackendAction BA = static_cast<BackendAction>(Act);
1114 auto &CodeGenOpts = CI.getCodeGenOpts();
1115 auto &Diagnostics = CI.getDiagnostics();
1116 std::unique_ptr<raw_pwrite_stream> OS =
1118 if (BA != Backend_EmitNothing && !OS)
1119 return;
1120
1122 FileID FID = SM.getMainFileID();
1123 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1124 if (!MainFile)
1125 return;
1126
1127 TheModule = loadModule(*MainFile);
1128 if (!TheModule)
1129 return;
1130
1131 const TargetOptions &TargetOpts = CI.getTargetOpts();
1132 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
1133 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1134 << TargetOpts.Triple;
1135 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
1136 }
1137
1138 EmbedObject(TheModule.get(), CodeGenOpts, CI.getVirtualFileSystem(),
1139 Diagnostics);
1140 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1141
1142 LLVMContext &Ctx = TheModule->getContext();
1143
1144 // Restore any diagnostic handler previously set before returning from this
1145 // function.
1146 struct RAII {
1147 LLVMContext &Ctx;
1148 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1149 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1150 } _{Ctx};
1151
1152 // Set clang diagnostic handler. To do this we need to create a fake
1153 // BackendConsumer.
1154 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
1155 std::move(LinkModules), "", nullptr, nullptr,
1156 TheModule.get());
1157
1158 // Link in each pending link module.
1159 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
1160 return;
1161
1162 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1163 // true here because the valued names are needed for reading textual IR.
1164 Ctx.setDiscardValueNames(false);
1165 Ctx.setDiagnosticHandler(
1166 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1167
1168 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1169 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
1170
1171 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
1172 setupLLVMOptimizationRemarks(
1173 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1174 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1175 CodeGenOpts.DiagnosticsHotnessThreshold);
1176
1177 if (Error E = OptRecordFileOrErr.takeError()) {
1178 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1179 return;
1180 }
1181 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1182
1184 CI.getTarget().getDataLayoutString(), TheModule.get(), BA,
1186 std::move(OS));
1187 if (OptRecordFile)
1188 OptRecordFile->keep();
1189}
1190
1191//
1192
1193void EmitAssemblyAction::anchor() { }
1194EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1195 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1196
1197void EmitBCAction::anchor() { }
1198EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1199 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1200
1201void EmitLLVMAction::anchor() { }
1202EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1203 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1204
1205void EmitLLVMOnlyAction::anchor() { }
1206EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1207 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1208
1209void EmitCodeGenOnlyAction::anchor() { }
1211 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1212
1213void EmitObjAction::anchor() { }
1214EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1215 : 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.
#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:220
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:905
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,...
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:2000
@ 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:3717
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:2143
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)