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