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