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