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