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