xref: /llvm-project/clang/lib/CodeGen/CodeGenAction.cpp (revision 6622029d5ee15bfddacbda4825804ee89f8c30e6)
1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "CoverageMappingGen.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclGroup.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/CodeGen/BackendUtil.h"
19 #include "clang/CodeGen/CodeGenAction.h"
20 #include "clang/CodeGen/ModuleBuilder.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Frontend/FrontendDiagnostic.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/Timer.h"
37 #include <memory>
38 using namespace clang;
39 using namespace llvm;
40 
41 namespace clang {
42   class BackendConsumer : public ASTConsumer {
43     virtual void anchor();
44     DiagnosticsEngine &Diags;
45     BackendAction Action;
46     const CodeGenOptions &CodeGenOpts;
47     const TargetOptions &TargetOpts;
48     const LangOptions &LangOpts;
49     raw_pwrite_stream *AsmOutStream;
50     ASTContext *Context;
51 
52     Timer LLVMIRGeneration;
53 
54     std::unique_ptr<CodeGenerator> Gen;
55 
56     SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
57         LinkModules;
58 
59     // This is here so that the diagnostic printer knows the module a diagnostic
60     // refers to.
61     llvm::Module *CurLinkModule = nullptr;
62 
63   public:
64     BackendConsumer(
65         BackendAction Action, DiagnosticsEngine &Diags,
66         const HeaderSearchOptions &HeaderSearchOpts,
67         const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
68         const TargetOptions &TargetOpts, const LangOptions &LangOpts,
69         bool TimePasses, const std::string &InFile,
70         const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
71         raw_pwrite_stream *OS, LLVMContext &C,
72         CoverageSourceInfo *CoverageInfo = nullptr)
73         : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
74           TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
75           Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
76           Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
77                                 CodeGenOpts, C, CoverageInfo)) {
78       llvm::TimePassesIsEnabled = TimePasses;
79       for (auto &I : LinkModules)
80         this->LinkModules.push_back(
81             std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
82     }
83     llvm::Module *getModule() const { return Gen->GetModule(); }
84     std::unique_ptr<llvm::Module> takeModule() {
85       return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
86     }
87     void releaseLinkModules() {
88       for (auto &I : LinkModules)
89         I.second.release();
90     }
91 
92     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
93       Gen->HandleCXXStaticMemberVarInstantiation(VD);
94     }
95 
96     void Initialize(ASTContext &Ctx) override {
97       assert(!Context && "initialized multiple times");
98 
99       Context = &Ctx;
100 
101       if (llvm::TimePassesIsEnabled)
102         LLVMIRGeneration.startTimer();
103 
104       Gen->Initialize(Ctx);
105 
106       if (llvm::TimePassesIsEnabled)
107         LLVMIRGeneration.stopTimer();
108     }
109 
110     bool HandleTopLevelDecl(DeclGroupRef D) override {
111       PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
112                                      Context->getSourceManager(),
113                                      "LLVM IR generation of declaration");
114 
115       if (llvm::TimePassesIsEnabled)
116         LLVMIRGeneration.startTimer();
117 
118       Gen->HandleTopLevelDecl(D);
119 
120       if (llvm::TimePassesIsEnabled)
121         LLVMIRGeneration.stopTimer();
122 
123       return true;
124     }
125 
126     void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
127       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
128                                      Context->getSourceManager(),
129                                      "LLVM IR generation of inline method");
130       if (llvm::TimePassesIsEnabled)
131         LLVMIRGeneration.startTimer();
132 
133       Gen->HandleInlineMethodDefinition(D);
134 
135       if (llvm::TimePassesIsEnabled)
136         LLVMIRGeneration.stopTimer();
137     }
138 
139     void HandleTranslationUnit(ASTContext &C) override {
140       {
141         PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
142         if (llvm::TimePassesIsEnabled)
143           LLVMIRGeneration.startTimer();
144 
145         Gen->HandleTranslationUnit(C);
146 
147         if (llvm::TimePassesIsEnabled)
148           LLVMIRGeneration.stopTimer();
149       }
150 
151       // Silently ignore if we weren't initialized for some reason.
152       if (!getModule())
153         return;
154 
155       // Install an inline asm handler so that diagnostics get printed through
156       // our diagnostics hooks.
157       LLVMContext &Ctx = getModule()->getContext();
158       LLVMContext::InlineAsmDiagHandlerTy OldHandler =
159         Ctx.getInlineAsmDiagnosticHandler();
160       void *OldContext = Ctx.getInlineAsmDiagnosticContext();
161       Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
162 
163       LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
164           Ctx.getDiagnosticHandler();
165       void *OldDiagnosticContext = Ctx.getDiagnosticContext();
166       Ctx.setDiagnosticHandler(DiagnosticHandler, this);
167 
168       // Link LinkModule into this module if present, preserving its validity.
169       for (auto &I : LinkModules) {
170         unsigned LinkFlags = I.first;
171         CurLinkModule = I.second.get();
172         if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
173           return;
174       }
175 
176       EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
177                         C.getTargetInfo().getDataLayoutString(),
178                         getModule(), Action, AsmOutStream);
179 
180       Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
181 
182       Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
183     }
184 
185     void HandleTagDeclDefinition(TagDecl *D) override {
186       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
187                                      Context->getSourceManager(),
188                                      "LLVM IR generation of declaration");
189       Gen->HandleTagDeclDefinition(D);
190     }
191 
192     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
193       Gen->HandleTagDeclRequiredDefinition(D);
194     }
195 
196     void CompleteTentativeDefinition(VarDecl *D) override {
197       Gen->CompleteTentativeDefinition(D);
198     }
199 
200     void AssignInheritanceModel(CXXRecordDecl *RD) override {
201       Gen->AssignInheritanceModel(RD);
202     }
203 
204     void HandleVTable(CXXRecordDecl *RD) override {
205       Gen->HandleVTable(RD);
206     }
207 
208     void HandleDetectMismatch(llvm::StringRef Name,
209                                       llvm::StringRef Value) override {
210       Gen->HandleDetectMismatch(Name, Value);
211     }
212 
213     static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
214                                      unsigned LocCookie) {
215       SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
216       ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
217     }
218 
219     static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
220                                   void *Context) {
221       ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
222     }
223 
224     /// Get the best possible source location to represent a diagnostic that
225     /// may have associated debug info.
226     const FullSourceLoc
227     getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
228                                 bool &BadDebugInfo, StringRef &Filename,
229                                 unsigned &Line, unsigned &Column) const;
230 
231     void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
232                                SourceLocation LocCookie);
233 
234     void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
235     /// \brief Specialized handler for InlineAsm diagnostic.
236     /// \return True if the diagnostic has been successfully reported, false
237     /// otherwise.
238     bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
239     /// \brief Specialized handler for StackSize diagnostic.
240     /// \return True if the diagnostic has been successfully reported, false
241     /// otherwise.
242     bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
243     /// \brief Specialized handler for unsupported backend feature diagnostic.
244     void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
245     /// \brief Specialized handlers for optimization remarks.
246     /// Note that these handlers only accept remarks and they always handle
247     /// them.
248     void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
249                                  unsigned DiagID);
250     void
251     OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
252     void OptimizationRemarkHandler(
253         const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
254     void OptimizationRemarkHandler(
255         const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
256     void OptimizationRemarkHandler(
257         const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
258     void OptimizationRemarkHandler(
259         const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
260     void OptimizationFailureHandler(
261         const llvm::DiagnosticInfoOptimizationFailure &D);
262   };
263 
264   void BackendConsumer::anchor() {}
265 }
266 
267 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
268 /// buffer to be a valid FullSourceLoc.
269 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
270                                             SourceManager &CSM) {
271   // Get both the clang and llvm source managers.  The location is relative to
272   // a memory buffer that the LLVM Source Manager is handling, we need to add
273   // a copy to the Clang source manager.
274   const llvm::SourceMgr &LSM = *D.getSourceMgr();
275 
276   // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
277   // already owns its one and clang::SourceManager wants to own its one.
278   const MemoryBuffer *LBuf =
279   LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
280 
281   // Create the copy and transfer ownership to clang::SourceManager.
282   // TODO: Avoid copying files into memory.
283   std::unique_ptr<llvm::MemoryBuffer> CBuf =
284       llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
285                                            LBuf->getBufferIdentifier());
286   // FIXME: Keep a file ID map instead of creating new IDs for each location.
287   FileID FID = CSM.createFileID(std::move(CBuf));
288 
289   // Translate the offset into the file.
290   unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
291   SourceLocation NewLoc =
292   CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
293   return FullSourceLoc(NewLoc, CSM);
294 }
295 
296 
297 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
298 /// error parsing inline asm.  The SMDiagnostic indicates the error relative to
299 /// the temporary memory buffer that the inline asm parser has set up.
300 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
301                                             SourceLocation LocCookie) {
302   // There are a couple of different kinds of errors we could get here.  First,
303   // we re-format the SMDiagnostic in terms of a clang diagnostic.
304 
305   // Strip "error: " off the start of the message string.
306   StringRef Message = D.getMessage();
307   if (Message.startswith("error: "))
308     Message = Message.substr(7);
309 
310   // If the SMDiagnostic has an inline asm source location, translate it.
311   FullSourceLoc Loc;
312   if (D.getLoc() != SMLoc())
313     Loc = ConvertBackendLocation(D, Context->getSourceManager());
314 
315   unsigned DiagID;
316   switch (D.getKind()) {
317   case llvm::SourceMgr::DK_Error:
318     DiagID = diag::err_fe_inline_asm;
319     break;
320   case llvm::SourceMgr::DK_Warning:
321     DiagID = diag::warn_fe_inline_asm;
322     break;
323   case llvm::SourceMgr::DK_Note:
324     DiagID = diag::note_fe_inline_asm;
325     break;
326   }
327   // If this problem has clang-level source location information, report the
328   // issue in the source with a note showing the instantiated
329   // code.
330   if (LocCookie.isValid()) {
331     Diags.Report(LocCookie, DiagID).AddString(Message);
332 
333     if (D.getLoc().isValid()) {
334       DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
335       // Convert the SMDiagnostic ranges into SourceRange and attach them
336       // to the diagnostic.
337       for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
338         unsigned Column = D.getColumnNo();
339         B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
340                          Loc.getLocWithOffset(Range.second - Column));
341       }
342     }
343     return;
344   }
345 
346   // Otherwise, report the backend issue as occurring in the generated .s file.
347   // If Loc is invalid, we still need to report the issue, it just gets no
348   // location info.
349   Diags.Report(Loc, DiagID).AddString(Message);
350 }
351 
352 #define ComputeDiagID(Severity, GroupName, DiagID)                             \
353   do {                                                                         \
354     switch (Severity) {                                                        \
355     case llvm::DS_Error:                                                       \
356       DiagID = diag::err_fe_##GroupName;                                       \
357       break;                                                                   \
358     case llvm::DS_Warning:                                                     \
359       DiagID = diag::warn_fe_##GroupName;                                      \
360       break;                                                                   \
361     case llvm::DS_Remark:                                                      \
362       llvm_unreachable("'remark' severity not expected");                      \
363       break;                                                                   \
364     case llvm::DS_Note:                                                        \
365       DiagID = diag::note_fe_##GroupName;                                      \
366       break;                                                                   \
367     }                                                                          \
368   } while (false)
369 
370 #define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
371   do {                                                                         \
372     switch (Severity) {                                                        \
373     case llvm::DS_Error:                                                       \
374       DiagID = diag::err_fe_##GroupName;                                       \
375       break;                                                                   \
376     case llvm::DS_Warning:                                                     \
377       DiagID = diag::warn_fe_##GroupName;                                      \
378       break;                                                                   \
379     case llvm::DS_Remark:                                                      \
380       DiagID = diag::remark_fe_##GroupName;                                    \
381       break;                                                                   \
382     case llvm::DS_Note:                                                        \
383       DiagID = diag::note_fe_##GroupName;                                      \
384       break;                                                                   \
385     }                                                                          \
386   } while (false)
387 
388 bool
389 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
390   unsigned DiagID;
391   ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
392   std::string Message = D.getMsgStr().str();
393 
394   // If this problem has clang-level source location information, report the
395   // issue as being a problem in the source with a note showing the instantiated
396   // code.
397   SourceLocation LocCookie =
398       SourceLocation::getFromRawEncoding(D.getLocCookie());
399   if (LocCookie.isValid())
400     Diags.Report(LocCookie, DiagID).AddString(Message);
401   else {
402     // Otherwise, report the backend diagnostic as occurring in the generated
403     // .s file.
404     // If Loc is invalid, we still need to report the diagnostic, it just gets
405     // no location info.
406     FullSourceLoc Loc;
407     Diags.Report(Loc, DiagID).AddString(Message);
408   }
409   // We handled all the possible severities.
410   return true;
411 }
412 
413 bool
414 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
415   if (D.getSeverity() != llvm::DS_Warning)
416     // For now, the only support we have for StackSize diagnostic is warning.
417     // We do not know how to format other severities.
418     return false;
419 
420   if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
421     Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
422                  diag::warn_fe_frame_larger_than)
423         << D.getStackSize() << Decl::castToDeclContext(ND);
424     return true;
425   }
426 
427   return false;
428 }
429 
430 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
431     const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
432                                 unsigned &Line, unsigned &Column) const {
433   SourceManager &SourceMgr = Context->getSourceManager();
434   FileManager &FileMgr = SourceMgr.getFileManager();
435   SourceLocation DILoc;
436 
437   if (D.isLocationAvailable()) {
438     D.getLocation(&Filename, &Line, &Column);
439     const FileEntry *FE = FileMgr.getFile(Filename);
440     if (FE && Line > 0) {
441       // If -gcolumn-info was not used, Column will be 0. This upsets the
442       // source manager, so pass 1 if Column is not set.
443       DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
444     }
445     BadDebugInfo = DILoc.isInvalid();
446   }
447 
448   // If a location isn't available, try to approximate it using the associated
449   // function definition. We use the definition's right brace to differentiate
450   // from diagnostics that genuinely relate to the function itself.
451   FullSourceLoc Loc(DILoc, SourceMgr);
452   if (Loc.isInvalid())
453     if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
454       Loc = FD->getASTContext().getFullLoc(FD->getLocation());
455 
456   if (DILoc.isInvalid() && D.isLocationAvailable())
457     // If we were not able to translate the file:line:col information
458     // back to a SourceLocation, at least emit a note stating that
459     // we could not translate this location. This can happen in the
460     // case of #line directives.
461     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
462         << Filename << Line;
463 
464   return Loc;
465 }
466 
467 void BackendConsumer::UnsupportedDiagHandler(
468     const llvm::DiagnosticInfoUnsupported &D) {
469   // We only support errors.
470   assert(D.getSeverity() == llvm::DS_Error);
471 
472   StringRef Filename;
473   unsigned Line, Column;
474   bool BadDebugInfo;
475   FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
476       Line, Column);
477 
478   Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
479 
480   if (BadDebugInfo)
481     // If we were not able to translate the file:line:col information
482     // back to a SourceLocation, at least emit a note stating that
483     // we could not translate this location. This can happen in the
484     // case of #line directives.
485     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
486         << Filename << Line << Column;
487 }
488 
489 void BackendConsumer::EmitOptimizationMessage(
490     const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
491   // We only support warnings and remarks.
492   assert(D.getSeverity() == llvm::DS_Remark ||
493          D.getSeverity() == llvm::DS_Warning);
494 
495   StringRef Filename;
496   unsigned Line, Column;
497   bool BadDebugInfo = false;
498   FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
499       Line, Column);
500 
501   Diags.Report(Loc, DiagID)
502       << AddFlagValue(D.getPassName() ? D.getPassName() : "")
503       << D.getMsg().str();
504 
505   if (BadDebugInfo)
506     // If we were not able to translate the file:line:col information
507     // back to a SourceLocation, at least emit a note stating that
508     // we could not translate this location. This can happen in the
509     // case of #line directives.
510     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
511         << Filename << Line << Column;
512 }
513 
514 void BackendConsumer::OptimizationRemarkHandler(
515     const llvm::DiagnosticInfoOptimizationRemark &D) {
516   // Optimization remarks are active only if the -Rpass flag has a regular
517   // expression that matches the name of the pass name in \p D.
518   if (CodeGenOpts.OptimizationRemarkPattern &&
519       CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
520     EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
521 }
522 
523 void BackendConsumer::OptimizationRemarkHandler(
524     const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
525   // Missed optimization remarks are active only if the -Rpass-missed
526   // flag has a regular expression that matches the name of the pass
527   // name in \p D.
528   if (CodeGenOpts.OptimizationRemarkMissedPattern &&
529       CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
530     EmitOptimizationMessage(D,
531                             diag::remark_fe_backend_optimization_remark_missed);
532 }
533 
534 void BackendConsumer::OptimizationRemarkHandler(
535     const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
536   // Optimization analysis remarks are active if the pass name is set to
537   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
538   // regular expression that matches the name of the pass name in \p D.
539 
540   if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
541       (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
542        CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
543     EmitOptimizationMessage(
544         D, diag::remark_fe_backend_optimization_remark_analysis);
545 }
546 
547 void BackendConsumer::OptimizationRemarkHandler(
548     const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
549   // Optimization analysis remarks are active if the pass name is set to
550   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
551   // regular expression that matches the name of the pass name in \p D.
552 
553   if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
554       (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
555        CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
556     EmitOptimizationMessage(
557         D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
558 }
559 
560 void BackendConsumer::OptimizationRemarkHandler(
561     const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
562   // Optimization analysis remarks are active if the pass name is set to
563   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
564   // regular expression that matches the name of the pass name in \p D.
565 
566   if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
567       (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
568        CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
569     EmitOptimizationMessage(
570         D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
571 }
572 
573 void BackendConsumer::OptimizationFailureHandler(
574     const llvm::DiagnosticInfoOptimizationFailure &D) {
575   EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
576 }
577 
578 /// \brief This function is invoked when the backend needs
579 /// to report something to the user.
580 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
581   unsigned DiagID = diag::err_fe_inline_asm;
582   llvm::DiagnosticSeverity Severity = DI.getSeverity();
583   // Get the diagnostic ID based.
584   switch (DI.getKind()) {
585   case llvm::DK_InlineAsm:
586     if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
587       return;
588     ComputeDiagID(Severity, inline_asm, DiagID);
589     break;
590   case llvm::DK_StackSize:
591     if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
592       return;
593     ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
594     break;
595   case DK_Linker:
596     assert(CurLinkModule);
597     // FIXME: stop eating the warnings and notes.
598     if (Severity != DS_Error)
599       return;
600     DiagID = diag::err_fe_cannot_link_module;
601     break;
602   case llvm::DK_OptimizationRemark:
603     // Optimization remarks are always handled completely by this
604     // handler. There is no generic way of emitting them.
605     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
606     return;
607   case llvm::DK_OptimizationRemarkMissed:
608     // Optimization remarks are always handled completely by this
609     // handler. There is no generic way of emitting them.
610     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
611     return;
612   case llvm::DK_OptimizationRemarkAnalysis:
613     // Optimization remarks are always handled completely by this
614     // handler. There is no generic way of emitting them.
615     OptimizationRemarkHandler(
616         cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
617     return;
618   case llvm::DK_OptimizationRemarkAnalysisFPCommute:
619     // Optimization remarks are always handled completely by this
620     // handler. There is no generic way of emitting them.
621     OptimizationRemarkHandler(
622         cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
623     return;
624   case llvm::DK_OptimizationRemarkAnalysisAliasing:
625     // Optimization remarks are always handled completely by this
626     // handler. There is no generic way of emitting them.
627     OptimizationRemarkHandler(
628         cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
629     return;
630   case llvm::DK_OptimizationFailure:
631     // Optimization failures are always handled completely by this
632     // handler.
633     OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
634     return;
635   case llvm::DK_Unsupported:
636     UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
637     return;
638   default:
639     // Plugin IDs are not bound to any value as they are set dynamically.
640     ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
641     break;
642   }
643   std::string MsgStorage;
644   {
645     raw_string_ostream Stream(MsgStorage);
646     DiagnosticPrinterRawOStream DP(Stream);
647     DI.print(DP);
648   }
649 
650   if (DiagID == diag::err_fe_cannot_link_module) {
651     Diags.Report(diag::err_fe_cannot_link_module)
652         << CurLinkModule->getModuleIdentifier() << MsgStorage;
653     return;
654   }
655 
656   // Report the backend message using the usual diagnostic mechanism.
657   FullSourceLoc Loc;
658   Diags.Report(Loc, DiagID).AddString(MsgStorage);
659 }
660 #undef ComputeDiagID
661 
662 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
663     : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
664       OwnsVMContext(!_VMContext) {}
665 
666 CodeGenAction::~CodeGenAction() {
667   TheModule.reset();
668   if (OwnsVMContext)
669     delete VMContext;
670 }
671 
672 bool CodeGenAction::hasIRSupport() const { return true; }
673 
674 void CodeGenAction::EndSourceFileAction() {
675   // If the consumer creation failed, do nothing.
676   if (!getCompilerInstance().hasASTConsumer())
677     return;
678 
679   // Take back ownership of link modules we passed to consumer.
680   if (!LinkModules.empty())
681     BEConsumer->releaseLinkModules();
682 
683   // Steal the module from the consumer.
684   TheModule = BEConsumer->takeModule();
685 }
686 
687 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
688   return std::move(TheModule);
689 }
690 
691 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
692   OwnsVMContext = false;
693   return VMContext;
694 }
695 
696 static raw_pwrite_stream *
697 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
698   switch (Action) {
699   case Backend_EmitAssembly:
700     return CI.createDefaultOutputFile(false, InFile, "s");
701   case Backend_EmitLL:
702     return CI.createDefaultOutputFile(false, InFile, "ll");
703   case Backend_EmitBC:
704     return CI.createDefaultOutputFile(true, InFile, "bc");
705   case Backend_EmitNothing:
706     return nullptr;
707   case Backend_EmitMCNull:
708     return CI.createNullOutputFile();
709   case Backend_EmitObj:
710     return CI.createDefaultOutputFile(true, InFile, "o");
711   }
712 
713   llvm_unreachable("Invalid action!");
714 }
715 
716 std::unique_ptr<ASTConsumer>
717 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
718   BackendAction BA = static_cast<BackendAction>(Act);
719   raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
720   if (BA != Backend_EmitNothing && !OS)
721     return nullptr;
722 
723   // Load bitcode modules to link with, if we need to.
724   if (LinkModules.empty())
725     for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
726       const std::string &LinkBCFile = I.second;
727 
728       auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
729       if (!BCBuf) {
730         CI.getDiagnostics().Report(diag::err_cannot_open_file)
731             << LinkBCFile << BCBuf.getError().message();
732         LinkModules.clear();
733         return nullptr;
734       }
735 
736       ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
737           getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
738       if (std::error_code EC = ModuleOrErr.getError()) {
739         CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
740                                                                << EC.message();
741         LinkModules.clear();
742         return nullptr;
743       }
744       addLinkModule(ModuleOrErr.get().release(), I.first);
745     }
746 
747   CoverageSourceInfo *CoverageInfo = nullptr;
748   // Add the preprocessor callback only when the coverage mapping is generated.
749   if (CI.getCodeGenOpts().CoverageMapping) {
750     CoverageInfo = new CoverageSourceInfo;
751     CI.getPreprocessor().addPPCallbacks(
752                                     std::unique_ptr<PPCallbacks>(CoverageInfo));
753   }
754 
755   std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
756       BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
757       CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
758       CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
759       OS, *VMContext, CoverageInfo));
760   BEConsumer = Result.get();
761   return std::move(Result);
762 }
763 
764 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
765                                          void *Context,
766                                          unsigned LocCookie) {
767   SM.print(nullptr, llvm::errs());
768 }
769 
770 void CodeGenAction::ExecuteAction() {
771   // If this is an IR file, we have to treat it specially.
772   if (getCurrentFileKind() == IK_LLVM_IR) {
773     BackendAction BA = static_cast<BackendAction>(Act);
774     CompilerInstance &CI = getCompilerInstance();
775     raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
776     if (BA != Backend_EmitNothing && !OS)
777       return;
778 
779     bool Invalid;
780     SourceManager &SM = CI.getSourceManager();
781     FileID FID = SM.getMainFileID();
782     llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
783     if (Invalid)
784       return;
785 
786     llvm::SMDiagnostic Err;
787     TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
788     if (!TheModule) {
789       // Translate from the diagnostic info to the SourceManager location if
790       // available.
791       // TODO: Unify this with ConvertBackendLocation()
792       SourceLocation Loc;
793       if (Err.getLineNo() > 0) {
794         assert(Err.getColumnNo() >= 0);
795         Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
796                                       Err.getLineNo(), Err.getColumnNo() + 1);
797       }
798 
799       // Strip off a leading diagnostic code if there is one.
800       StringRef Msg = Err.getMessage();
801       if (Msg.startswith("error: "))
802         Msg = Msg.substr(7);
803 
804       unsigned DiagID =
805           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
806 
807       CI.getDiagnostics().Report(Loc, DiagID) << Msg;
808       return;
809     }
810     const TargetOptions &TargetOpts = CI.getTargetOpts();
811     if (TheModule->getTargetTriple() != TargetOpts.Triple) {
812       CI.getDiagnostics().Report(SourceLocation(),
813                                  diag::warn_fe_override_module)
814           << TargetOpts.Triple;
815       TheModule->setTargetTriple(TargetOpts.Triple);
816     }
817 
818     LLVMContext &Ctx = TheModule->getContext();
819     Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
820     EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
821                       CI.getLangOpts(), CI.getTarget().getDataLayoutString(),
822                       TheModule.get(), BA, OS);
823     return;
824   }
825 
826   // Otherwise follow the normal AST path.
827   this->ASTFrontendAction::ExecuteAction();
828 }
829 
830 //
831 
832 void EmitAssemblyAction::anchor() { }
833 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
834   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
835 
836 void EmitBCAction::anchor() { }
837 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
838   : CodeGenAction(Backend_EmitBC, _VMContext) {}
839 
840 void EmitLLVMAction::anchor() { }
841 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
842   : CodeGenAction(Backend_EmitLL, _VMContext) {}
843 
844 void EmitLLVMOnlyAction::anchor() { }
845 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
846   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
847 
848 void EmitCodeGenOnlyAction::anchor() { }
849 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
850   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
851 
852 void EmitObjAction::anchor() { }
853 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
854   : CodeGenAction(Backend_EmitObj, _VMContext) {}
855