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