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