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