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