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