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