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