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