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