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