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