blob: 5f74141d75b371d3d9dba9e555a35df28db8473c [file] [log] [blame]
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
Daniel Dunbarc13935e2008-10-21 23:49:24 +00002//
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
Alex Lorenzee024992014-08-04 18:41:51 +000010#include "CoverageMappingGen.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000012#include "clang/AST/ASTContext.h"
Hans Wennborga926d842014-05-23 20:37:38 +000013#include "clang/AST/DeclCXX.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000014#include "clang/AST/DeclGroup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/Basic/TargetInfo.h"
Daniel Dunbarc1b17292010-06-15 17:48:49 +000018#include "clang/CodeGen/BackendUtil.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/CodeGen/CodeGenAction.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000020#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000021#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000023#include "clang/Lex/Preprocessor.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Diego Novillo829b1702014-04-16 16:54:24 +000025#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000026#include "llvm/IR/DiagnosticInfo.h"
27#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000030#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000031#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000032#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000033#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000035#include "llvm/Support/Timer.h"
Hal Finkel8f96e822016-10-11 00:26:09 +000036#include "llvm/Support/ToolOutputFile.h"
37#include "llvm/Support/YAMLTraits.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000038#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000039using namespace clang;
40using namespace llvm;
41
Nico Weber2992efa2011-01-25 20:34:14 +000042namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000043 class BackendConsumer : public ASTConsumer {
David Blaikie68e081d2011-12-20 02:48:34 +000044 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000045 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000046 BackendAction Action;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000047 const HeaderSearchOptions &HeaderSearchOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000048 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000049 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000050 const LangOptions &LangOpts;
Peter Collingbourne03f89072016-07-15 00:55:40 +000051 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000052 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000053
Chris Lattner263d64c2009-02-18 01:37:30 +000054 Timer LLVMIRGeneration;
Davide Italianob99fabd2016-07-21 06:28:48 +000055 unsigned LLVMIRGenerationRefCount;
Mike Stump11289f42009-09-09 15:08:12 +000056
Reid Kleckner15241ba2016-11-30 00:25:36 +000057 /// True if we've finished generating IR. This prevents us from generating
58 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
59 /// can happen when Clang plugins trigger additional AST deserialization.
60 bool IRGenFinished = false;
61
Ahmed Charlesb8984322014-03-07 20:03:18 +000062 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000063
Artem Belevich5d40ae32015-10-27 17:56:59 +000064 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
65 LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000066
Rafael Espindola8ce88a52015-12-14 23:17:07 +000067 // This is here so that the diagnostic printer knows the module a diagnostic
68 // refers to.
69 llvm::Module *CurLinkModule = nullptr;
70
Mike Stump11289f42009-09-09 15:08:12 +000071 public:
Artem Belevich5d40ae32015-10-27 17:56:59 +000072 BackendConsumer(
73 BackendAction Action, DiagnosticsEngine &Diags,
74 const HeaderSearchOptions &HeaderSearchOpts,
75 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
76 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
77 bool TimePasses, const std::string &InFile,
78 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
Peter Collingbourne03f89072016-07-15 00:55:40 +000079 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
Artem Belevich5d40ae32015-10-27 17:56:59 +000080 CoverageSourceInfo *CoverageInfo = nullptr)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000081 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
82 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
Peter Collingbourne03f89072016-07-15 00:55:40 +000083 AsmOutStream(std::move(OS)), Context(nullptr),
Matthias Braunae032b62016-11-18 19:43:25 +000084 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
Davide Italianob99fabd2016-07-21 06:28:48 +000085 LLVMIRGenerationRefCount(0),
Adrian Prantle74f5252015-06-30 02:26:03 +000086 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Artem Belevich5d40ae32015-10-27 17:56:59 +000087 CodeGenOpts, C, CoverageInfo)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000088 llvm::TimePassesIsEnabled = TimePasses;
Artem Belevich5d40ae32015-10-27 17:56:59 +000089 for (auto &I : LinkModules)
90 this->LinkModules.push_back(
91 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
Chris Lattnerdeffa132009-02-18 01:23:44 +000092 }
Serge Pavlov41c1f792016-02-18 16:42:09 +000093 llvm::Module *getModule() const { return Gen->GetModule(); }
94 std::unique_ptr<llvm::Module> takeModule() {
95 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
96 }
Artem Belevich5d40ae32015-10-27 17:56:59 +000097 void releaseLinkModules() {
98 for (auto &I : LinkModules)
99 I.second.release();
100 }
Daniel Dunbar400a6932010-02-25 04:37:50 +0000101
Craig Topper4f12f102014-03-12 06:41:41 +0000102 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +0000103 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +0000104 }
105
Craig Topper4f12f102014-03-12 06:41:41 +0000106 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +0000107 assert(!Context && "initialized multiple times");
108
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000109 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000110
Daniel Dunbar8e705052009-11-30 08:39:52 +0000111 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000112 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000114 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000115
Daniel Dunbar8e705052009-11-30 08:39:52 +0000116 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000117 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Craig Topper4f12f102014-03-12 06:41:41 +0000120 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000121 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000122 Context->getSourceManager(),
123 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000124
Davide Italianob99fabd2016-07-21 06:28:48 +0000125 // Recurse.
126 if (llvm::TimePassesIsEnabled) {
127 LLVMIRGenerationRefCount += 1;
128 if (LLVMIRGenerationRefCount == 1)
129 LLVMIRGeneration.startTimer();
130 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000131
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000132 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000133
Davide Italianob99fabd2016-07-21 06:28:48 +0000134 if (llvm::TimePassesIsEnabled) {
135 LLVMIRGenerationRefCount -= 1;
136 if (LLVMIRGenerationRefCount == 0)
137 LLVMIRGeneration.stopTimer();
138 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000139
140 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000141 }
Mike Stump11289f42009-09-09 15:08:12 +0000142
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000143 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000144 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
145 Context->getSourceManager(),
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000146 "LLVM IR generation of inline function");
Hans Wennborga926d842014-05-23 20:37:38 +0000147 if (llvm::TimePassesIsEnabled)
148 LLVMIRGeneration.startTimer();
149
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000150 Gen->HandleInlineFunctionDefinition(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000151
152 if (llvm::TimePassesIsEnabled)
153 LLVMIRGeneration.stopTimer();
154 }
155
Reid Kleckner68c4bb52016-11-30 01:32:53 +0000156 void HandleInterestingDecl(DeclGroupRef D) override {
Reid Kleckner15241ba2016-11-30 00:25:36 +0000157 // Ignore interesting decls from the AST reader after IRGen is finished.
158 if (!IRGenFinished)
159 HandleTopLevelDecl(D);
160 }
161
Craig Topper4f12f102014-03-12 06:41:41 +0000162 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000163 {
Chris Lattnere46de752009-03-06 06:46:31 +0000164 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Davide Italianob99fabd2016-07-21 06:28:48 +0000165 if (llvm::TimePassesIsEnabled) {
166 LLVMIRGenerationRefCount += 1;
167 if (LLVMIRGenerationRefCount == 1)
168 LLVMIRGeneration.startTimer();
169 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000170
Chris Lattnercf169832009-03-28 04:11:33 +0000171 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000172
Davide Italianob99fabd2016-07-21 06:28:48 +0000173 if (llvm::TimePassesIsEnabled) {
174 LLVMIRGenerationRefCount -= 1;
175 if (LLVMIRGenerationRefCount == 0)
176 LLVMIRGeneration.stopTimer();
177 }
Reid Kleckner15241ba2016-11-30 00:25:36 +0000178
179 IRGenFinished = true;
Chris Lattnereae6cb62009-03-05 08:00:35 +0000180 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000181
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000182 // Silently ignore if we weren't initialized for some reason.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000183 if (!getModule())
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000184 return;
Mike Stump11289f42009-09-09 15:08:12 +0000185
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000186 // Install an inline asm handler so that diagnostics get printed through
187 // our diagnostics hooks.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000188 LLVMContext &Ctx = getModule()->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000189 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
190 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000191 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000192 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000193
Quentin Colombet728c5542014-02-06 18:30:43 +0000194 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
195 Ctx.getDiagnosticHandler();
196 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
197 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
Adam Nemet1eea3e52016-09-13 04:32:40 +0000198 Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
Quentin Colombet728c5542014-02-06 18:30:43 +0000199
Hal Finkel8f96e822016-10-11 00:26:09 +0000200 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
201 if (!CodeGenOpts.OptRecordFile.empty()) {
202 std::error_code EC;
203 OptRecordFile =
204 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
205 EC, sys::fs::F_None);
206 if (EC) {
207 Diags.Report(diag::err_cannot_open_file) <<
208 CodeGenOpts.OptRecordFile << EC.message();
209 return;
210 }
211
Mehdi Amini6f408362016-11-19 18:19:41 +0000212 Ctx.setDiagnosticsOutputFile(
213 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
Hal Finkel8f96e822016-10-11 00:26:09 +0000214
215 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
216 Ctx.setDiagnosticHotnessRequested(true);
217 }
218
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000219 // Link LinkModule into this module if present, preserving its validity.
220 for (auto &I : LinkModules) {
221 unsigned LinkFlags = I.first;
222 CurLinkModule = I.second.get();
Serge Pavlov41c1f792016-02-18 16:42:09 +0000223 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000224 return;
225 }
226
Steven Wu27fb5222016-05-11 16:26:03 +0000227 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
228
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000229 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
230 LangOpts, C.getTargetInfo().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000231 getModule(), Action, std::move(AsmOutStream));
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000232
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000233 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000234
235 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Hal Finkel8f96e822016-10-11 00:26:09 +0000236
237 if (OptRecordFile)
238 OptRecordFile->keep();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000239 }
Mike Stump11289f42009-09-09 15:08:12 +0000240
Craig Topper4f12f102014-03-12 06:41:41 +0000241 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000242 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
243 Context->getSourceManager(),
244 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000245 Gen->HandleTagDeclDefinition(D);
246 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000247
Craig Topper4f12f102014-03-12 06:41:41 +0000248 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000249 Gen->HandleTagDeclRequiredDefinition(D);
250 }
251
Craig Topper4f12f102014-03-12 06:41:41 +0000252 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000253 Gen->CompleteTentativeDefinition(D);
254 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000255
David Majnemer929025d2016-01-26 19:30:26 +0000256 void AssignInheritanceModel(CXXRecordDecl *RD) override {
257 Gen->AssignInheritanceModel(RD);
258 }
259
Nico Weberb6a5d052015-01-15 04:07:35 +0000260 void HandleVTable(CXXRecordDecl *RD) override {
261 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000262 }
263
Chris Lattner5ec32e72010-04-06 18:38:50 +0000264 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
265 unsigned LocCookie) {
266 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
267 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
268 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000269
Quentin Colombet728c5542014-02-06 18:30:43 +0000270 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
271 void *Context) {
272 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
273 }
274
Oliver Stannard91817852016-02-02 13:52:52 +0000275 /// Get the best possible source location to represent a diagnostic that
276 /// may have associated debug info.
277 const FullSourceLoc
278 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
279 bool &BadDebugInfo, StringRef &Filename,
280 unsigned &Line, unsigned &Column) const;
281
Chris Lattner5ec32e72010-04-06 18:38:50 +0000282 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
283 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000284
285 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
286 /// \brief Specialized handler for InlineAsm diagnostic.
287 /// \return True if the diagnostic has been successfully reported, false
288 /// otherwise.
289 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
290 /// \brief Specialized handler for StackSize diagnostic.
291 /// \return True if the diagnostic has been successfully reported, false
292 /// otherwise.
293 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Oliver Stannard91817852016-02-02 13:52:52 +0000294 /// \brief Specialized handler for unsupported backend feature diagnostic.
295 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000296 /// \brief Specialized handlers for optimization remarks.
297 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000298 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000299 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
300 unsigned DiagID);
Adam Nemetb4e64a72016-09-27 22:19:29 +0000301 void OptimizationRemarkHandler(const llvm::OptimizationRemark &D);
302 void OptimizationRemarkHandler(const llvm::OptimizationRemarkMissed &D);
303 void OptimizationRemarkHandler(const llvm::OptimizationRemarkAnalysis &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000304 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000305 const llvm::OptimizationRemarkAnalysisFPCommute &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000306 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000307 const llvm::OptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000308 void OptimizationFailureHandler(
309 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000310 };
David Blaikie68e081d2011-12-20 02:48:34 +0000311
312 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000313}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000314
Chris Lattner79f67a72010-04-08 00:23:06 +0000315/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
316/// buffer to be a valid FullSourceLoc.
317static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
318 SourceManager &CSM) {
319 // Get both the clang and llvm source managers. The location is relative to
320 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000321 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000322 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000323
Chris Lattner79f67a72010-04-08 00:23:06 +0000324 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
325 // already owns its one and clang::SourceManager wants to own its one.
326 const MemoryBuffer *LBuf =
327 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000328
Chris Lattner79f67a72010-04-08 00:23:06 +0000329 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000330 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000331 std::unique_ptr<llvm::MemoryBuffer> CBuf =
332 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
333 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000334 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000335 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000336
Chris Lattner79f67a72010-04-08 00:23:06 +0000337 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000338 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000339 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000340 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000341 return FullSourceLoc(NewLoc, CSM);
342}
343
Chris Lattner6d672132010-04-06 17:52:14 +0000344
Chris Lattner5ec32e72010-04-06 18:38:50 +0000345/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
346/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000347/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000348void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
349 SourceLocation LocCookie) {
350 // There are a couple of different kinds of errors we could get here. First,
351 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000352
353 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000354 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000355 if (Message.startswith("error: "))
356 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000357
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000358 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000359 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000360 if (D.getLoc() != SMLoc())
361 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000362
Joey Gouly5798b262014-06-05 21:23:42 +0000363 unsigned DiagID;
364 switch (D.getKind()) {
365 case llvm::SourceMgr::DK_Error:
366 DiagID = diag::err_fe_inline_asm;
367 break;
368 case llvm::SourceMgr::DK_Warning:
369 DiagID = diag::warn_fe_inline_asm;
370 break;
371 case llvm::SourceMgr::DK_Note:
372 DiagID = diag::note_fe_inline_asm;
373 break;
374 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000375 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000376 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000377 // code.
378 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000379 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000380
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000381 if (D.getLoc().isValid()) {
382 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
383 // Convert the SMDiagnostic ranges into SourceRange and attach them
384 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000385 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000386 unsigned Column = D.getColumnNo();
387 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
388 Loc.getLocWithOffset(Range.second - Column));
389 }
390 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000391 return;
392 }
393
Joey Gouly5798b262014-06-05 21:23:42 +0000394 // Otherwise, report the backend issue as occurring in the generated .s file.
395 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000396 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000397 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000398}
399
Quentin Colombet728c5542014-02-06 18:30:43 +0000400#define ComputeDiagID(Severity, GroupName, DiagID) \
401 do { \
402 switch (Severity) { \
403 case llvm::DS_Error: \
404 DiagID = diag::err_fe_##GroupName; \
405 break; \
406 case llvm::DS_Warning: \
407 DiagID = diag::warn_fe_##GroupName; \
408 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000409 case llvm::DS_Remark: \
410 llvm_unreachable("'remark' severity not expected"); \
411 break; \
412 case llvm::DS_Note: \
413 DiagID = diag::note_fe_##GroupName; \
414 break; \
415 } \
416 } while (false)
417
418#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
419 do { \
420 switch (Severity) { \
421 case llvm::DS_Error: \
422 DiagID = diag::err_fe_##GroupName; \
423 break; \
424 case llvm::DS_Warning: \
425 DiagID = diag::warn_fe_##GroupName; \
426 break; \
427 case llvm::DS_Remark: \
428 DiagID = diag::remark_fe_##GroupName; \
429 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000430 case llvm::DS_Note: \
431 DiagID = diag::note_fe_##GroupName; \
432 break; \
433 } \
434 } while (false)
435
436bool
437BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
438 unsigned DiagID;
439 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
440 std::string Message = D.getMsgStr().str();
441
442 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000443 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000444 // code.
445 SourceLocation LocCookie =
446 SourceLocation::getFromRawEncoding(D.getLocCookie());
447 if (LocCookie.isValid())
448 Diags.Report(LocCookie, DiagID).AddString(Message);
449 else {
450 // Otherwise, report the backend diagnostic as occurring in the generated
451 // .s file.
452 // If Loc is invalid, we still need to report the diagnostic, it just gets
453 // no location info.
454 FullSourceLoc Loc;
455 Diags.Report(Loc, DiagID).AddString(Message);
456 }
457 // We handled all the possible severities.
458 return true;
459}
460
461bool
462BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
463 if (D.getSeverity() != llvm::DS_Warning)
464 // For now, the only support we have for StackSize diagnostic is warning.
465 // We do not know how to format other severities.
466 return false;
467
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000468 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000469 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000470 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
471 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000472 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000473 return true;
474 }
475
476 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000477}
478
Oliver Stannard91817852016-02-02 13:52:52 +0000479const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
480 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
481 unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000482 SourceManager &SourceMgr = Context->getSourceManager();
483 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000484 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000485
486 if (D.isLocationAvailable()) {
487 D.getLocation(&Filename, &Line, &Column);
488 const FileEntry *FE = FileMgr.getFile(Filename);
489 if (FE && Line > 0) {
490 // If -gcolumn-info was not used, Column will be 0. This upsets the
491 // source manager, so pass 1 if Column is not set.
492 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
493 }
Oliver Stannard91817852016-02-02 13:52:52 +0000494 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000495 }
Alp Toker27506272014-06-05 22:11:12 +0000496
497 // If a location isn't available, try to approximate it using the associated
498 // function definition. We use the definition's right brace to differentiate
499 // from diagnostics that genuinely relate to the function itself.
500 FullSourceLoc Loc(DILoc, SourceMgr);
501 if (Loc.isInvalid())
502 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000503 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000504
Diego Novillo86f884e2015-05-08 20:59:56 +0000505 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000506 // If we were not able to translate the file:line:col information
507 // back to a SourceLocation, at least emit a note stating that
508 // we could not translate this location. This can happen in the
509 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000510 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000511 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000512
513 return Loc;
514}
515
516void BackendConsumer::UnsupportedDiagHandler(
517 const llvm::DiagnosticInfoUnsupported &D) {
518 // We only support errors.
519 assert(D.getSeverity() == llvm::DS_Error);
520
521 StringRef Filename;
522 unsigned Line, Column;
523 bool BadDebugInfo;
524 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
525 Line, Column);
526
527 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
528
529 if (BadDebugInfo)
530 // If we were not able to translate the file:line:col information
531 // back to a SourceLocation, at least emit a note stating that
532 // we could not translate this location. This can happen in the
533 // case of #line directives.
534 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
535 << Filename << Line << Column;
536}
537
538void BackendConsumer::EmitOptimizationMessage(
539 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
540 // We only support warnings and remarks.
541 assert(D.getSeverity() == llvm::DS_Remark ||
542 D.getSeverity() == llvm::DS_Warning);
543
544 StringRef Filename;
545 unsigned Line, Column;
546 bool BadDebugInfo = false;
547 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
548 Line, Column);
549
Adam Nemet1eea3e52016-09-13 04:32:40 +0000550 std::string Msg;
551 raw_string_ostream MsgStream(Msg);
Adam Nemet699fc5b2016-09-27 20:55:12 +0000552 MsgStream << D.getMsg();
Adam Nemet1eea3e52016-09-13 04:32:40 +0000553
554 if (D.getHotness())
555 MsgStream << " (hotness: " << *D.getHotness() << ")";
556
Oliver Stannard91817852016-02-02 13:52:52 +0000557 Diags.Report(Loc, DiagID)
Mehdi Amini117296c2016-10-01 02:56:57 +0000558 << AddFlagValue(D.getPassName())
Adam Nemet1eea3e52016-09-13 04:32:40 +0000559 << MsgStream.str();
Oliver Stannard91817852016-02-02 13:52:52 +0000560
561 if (BadDebugInfo)
562 // If we were not able to translate the file:line:col information
563 // back to a SourceLocation, at least emit a note stating that
564 // we could not translate this location. This can happen in the
565 // case of #line directives.
566 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000567 << Filename << Line << Column;
568}
569
570void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000571 const llvm::OptimizationRemark &D) {
Diego Novillod23ec942014-05-29 19:55:06 +0000572 // Optimization remarks are active only if the -Rpass flag has a regular
573 // expression that matches the name of the pass name in \p D.
574 if (CodeGenOpts.OptimizationRemarkPattern &&
575 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000576 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
Diego Novillod23ec942014-05-29 19:55:06 +0000577}
578
579void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000580 const llvm::OptimizationRemarkMissed &D) {
Diego Novillod23ec942014-05-29 19:55:06 +0000581 // Missed optimization remarks are active only if the -Rpass-missed
582 // flag has a regular expression that matches the name of the pass
583 // name in \p D.
584 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
585 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000586 EmitOptimizationMessage(D,
587 diag::remark_fe_backend_optimization_remark_missed);
Diego Novillod23ec942014-05-29 19:55:06 +0000588}
589
590void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000591 const llvm::OptimizationRemarkAnalysis &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000592 // Optimization analysis remarks are active if the pass name is set to
593 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
594 // regular expression that matches the name of the pass name in \p D.
595
Adam Nemetb5beb972016-06-29 04:55:31 +0000596 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000597 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
598 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000599 EmitOptimizationMessage(
Diego Novillod23ec942014-05-29 19:55:06 +0000600 D, diag::remark_fe_backend_optimization_remark_analysis);
Diego Novillo829b1702014-04-16 16:54:24 +0000601}
602
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000603void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000604 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000605 // Optimization analysis remarks are active if the pass name is set to
606 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
607 // regular expression that matches the name of the pass name in \p D.
608
Adam Nemetb5beb972016-06-29 04:55:31 +0000609 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000610 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
611 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000612 EmitOptimizationMessage(
613 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
614}
615
Tyler Nowicki034baf62015-08-10 23:05:16 +0000616void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000617 const llvm::OptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000618 // Optimization analysis remarks are active if the pass name is set to
619 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
620 // regular expression that matches the name of the pass name in \p D.
621
Adam Nemetb5beb972016-06-29 04:55:31 +0000622 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000623 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
624 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000625 EmitOptimizationMessage(
626 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
627}
628
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000629void BackendConsumer::OptimizationFailureHandler(
630 const llvm::DiagnosticInfoOptimizationFailure &D) {
631 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
632}
633
Quentin Colombet728c5542014-02-06 18:30:43 +0000634/// \brief This function is invoked when the backend needs
635/// to report something to the user.
636void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
637 unsigned DiagID = diag::err_fe_inline_asm;
638 llvm::DiagnosticSeverity Severity = DI.getSeverity();
639 // Get the diagnostic ID based.
640 switch (DI.getKind()) {
641 case llvm::DK_InlineAsm:
642 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
643 return;
644 ComputeDiagID(Severity, inline_asm, DiagID);
645 break;
646 case llvm::DK_StackSize:
647 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
648 return;
649 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
650 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000651 case DK_Linker:
652 assert(CurLinkModule);
653 // FIXME: stop eating the warnings and notes.
654 if (Severity != DS_Error)
655 return;
656 DiagID = diag::err_fe_cannot_link_module;
657 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000658 case llvm::DK_OptimizationRemark:
659 // Optimization remarks are always handled completely by this
660 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000661 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
Diego Novillo829b1702014-04-16 16:54:24 +0000662 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000663 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000664 // Optimization remarks are always handled completely by this
665 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000666 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
Diego Novillod23ec942014-05-29 19:55:06 +0000667 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000668 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000669 // Optimization remarks are always handled completely by this
670 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000671 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000672 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000673 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
674 // Optimization remarks are always handled completely by this
675 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000676 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000677 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000678 case llvm::DK_OptimizationRemarkAnalysisAliasing:
679 // Optimization remarks are always handled completely by this
680 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000681 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
Tyler Nowicki034baf62015-08-10 23:05:16 +0000682 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000683 case llvm::DK_OptimizationFailure:
684 // Optimization failures are always handled completely by this
685 // handler.
686 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
687 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000688 case llvm::DK_Unsupported:
689 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
690 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000691 default:
692 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000693 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000694 break;
695 }
696 std::string MsgStorage;
697 {
698 raw_string_ostream Stream(MsgStorage);
699 DiagnosticPrinterRawOStream DP(Stream);
700 DI.print(DP);
701 }
702
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000703 if (DiagID == diag::err_fe_cannot_link_module) {
704 Diags.Report(diag::err_fe_cannot_link_module)
705 << CurLinkModule->getModuleIdentifier() << MsgStorage;
706 return;
707 }
708
Quentin Colombet728c5542014-02-06 18:30:43 +0000709 // Report the backend message using the usual diagnostic mechanism.
710 FullSourceLoc Loc;
711 Diags.Report(Loc, DiagID).AddString(MsgStorage);
712}
713#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000714
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000715CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000716 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000717 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000718
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000719CodeGenAction::~CodeGenAction() {
720 TheModule.reset();
721 if (OwnsVMContext)
722 delete VMContext;
723}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000724
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000725bool CodeGenAction::hasIRSupport() const { return true; }
726
Daniel Dunbar400a6932010-02-25 04:37:50 +0000727void CodeGenAction::EndSourceFileAction() {
728 // If the consumer creation failed, do nothing.
729 if (!getCompilerInstance().hasASTConsumer())
730 return;
731
Artem Belevich5d40ae32015-10-27 17:56:59 +0000732 // Take back ownership of link modules we passed to consumer.
733 if (!LinkModules.empty())
734 BEConsumer->releaseLinkModules();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000735
Daniel Dunbar400a6932010-02-25 04:37:50 +0000736 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000737 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000738}
739
Rafael Espindolae8337302014-08-19 14:36:35 +0000740std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
741 return std::move(TheModule);
742}
743
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000744llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
745 OwnsVMContext = false;
746 return VMContext;
747}
748
Peter Collingbourne03f89072016-07-15 00:55:40 +0000749static std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000750GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000751 switch (Action) {
752 case Backend_EmitAssembly:
753 return CI.createDefaultOutputFile(false, InFile, "s");
754 case Backend_EmitLL:
755 return CI.createDefaultOutputFile(false, InFile, "ll");
756 case Backend_EmitBC:
757 return CI.createDefaultOutputFile(true, InFile, "bc");
758 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000759 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000760 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000761 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000762 case Backend_EmitObj:
763 return CI.createDefaultOutputFile(true, InFile, "o");
764 }
765
David Blaikie83d382b2011-09-23 05:06:16 +0000766 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000767}
768
David Blaikie6beb6aa2014-08-10 19:56:51 +0000769std::unique_ptr<ASTConsumer>
770CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000771 BackendAction BA = static_cast<BackendAction>(Act);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000772 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000773 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000774 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000775
Artem Belevich5d40ae32015-10-27 17:56:59 +0000776 // Load bitcode modules to link with, if we need to.
777 if (LinkModules.empty())
778 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
779 const std::string &LinkBCFile = I.second;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000780
Artem Belevich5d40ae32015-10-27 17:56:59 +0000781 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
782 if (!BCBuf) {
783 CI.getDiagnostics().Report(diag::err_cannot_open_file)
784 << LinkBCFile << BCBuf.getError().message();
785 LinkModules.clear();
786 return nullptr;
787 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000788
Peter Collingbourned9445c42016-11-13 07:00:17 +0000789 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000790 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000791 if (!ModuleOrErr) {
792 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
793 CI.getDiagnostics().Report(diag::err_cannot_open_file)
794 << LinkBCFile << EIB.message();
795 });
Artem Belevich5d40ae32015-10-27 17:56:59 +0000796 LinkModules.clear();
797 return nullptr;
798 }
799 addLinkModule(ModuleOrErr.get().release(), I.first);
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000800 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000801
Alex Lorenzee024992014-08-04 18:41:51 +0000802 CoverageSourceInfo *CoverageInfo = nullptr;
803 // Add the preprocessor callback only when the coverage mapping is generated.
804 if (CI.getCodeGenOpts().CoverageMapping) {
805 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000806 CI.getPreprocessor().addPPCallbacks(
807 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000808 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000809
David Blaikie037e75b2014-08-10 21:06:17 +0000810 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000811 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
812 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Artem Belevich5d40ae32015-10-27 17:56:59 +0000813 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000814 std::move(OS), *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000815 BEConsumer = Result.get();
816 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000817}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000818
Tim Northover1390b442016-04-06 19:58:07 +0000819static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
820 void *Context,
821 unsigned LocCookie) {
822 SM.print(nullptr, llvm::errs());
823
824 auto Diags = static_cast<DiagnosticsEngine *>(Context);
825 unsigned DiagID;
826 switch (SM.getKind()) {
827 case llvm::SourceMgr::DK_Error:
828 DiagID = diag::err_fe_inline_asm;
829 break;
830 case llvm::SourceMgr::DK_Warning:
831 DiagID = diag::warn_fe_inline_asm;
832 break;
833 case llvm::SourceMgr::DK_Note:
834 DiagID = diag::note_fe_inline_asm;
835 break;
836 }
837
838 Diags->Report(DiagID).AddString("cannot compile inline asm");
839}
840
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000841void CodeGenAction::ExecuteAction() {
842 // If this is an IR file, we have to treat it specially.
843 if (getCurrentFileKind() == IK_LLVM_IR) {
844 BackendAction BA = static_cast<BackendAction>(Act);
845 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000846 std::unique_ptr<raw_pwrite_stream> OS =
847 GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000848 if (BA != Backend_EmitNothing && !OS)
849 return;
850
851 bool Invalid;
852 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000853 FileID FID = SM.getMainFileID();
854 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000855 if (Invalid)
856 return;
857
Teresa Johnsonb1047492016-04-20 02:23:52 +0000858 // For ThinLTO backend invocations, ensure that the context
859 // merges types based on ODR identifiers.
860 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
861 VMContext->enableDebugTypeODRUniquing();
862
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000863 llvm::SMDiagnostic Err;
Rafael Espindola32327732014-08-26 21:49:29 +0000864 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000865 if (!TheModule) {
Alp Toker7b463d52014-06-30 01:33:59 +0000866 // Translate from the diagnostic info to the SourceManager location if
867 // available.
868 // TODO: Unify this with ConvertBackendLocation()
869 SourceLocation Loc;
870 if (Err.getLineNo() > 0) {
871 assert(Err.getColumnNo() >= 0);
872 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
873 Err.getLineNo(), Err.getColumnNo() + 1);
874 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000875
Alp Tokerbc043f22013-12-21 05:20:03 +0000876 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000877 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000878 if (Msg.startswith("error: "))
879 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000880
Alp Tokerbc043f22013-12-21 05:20:03 +0000881 unsigned DiagID =
882 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000883
Alp Tokerbc043f22013-12-21 05:20:03 +0000884 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000885 return;
886 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000887 const TargetOptions &TargetOpts = CI.getTargetOpts();
888 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000889 CI.getDiagnostics().Report(SourceLocation(),
890 diag::warn_fe_override_module)
891 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000892 TheModule->setTargetTriple(TargetOpts.Triple);
893 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000894
Steven Wu27fb5222016-05-11 16:26:03 +0000895 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
896 MainFile->getMemBufferRef());
897
Tim Northover1390b442016-04-06 19:58:07 +0000898 LLVMContext &Ctx = TheModule->getContext();
899 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
900 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +0000901
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000902 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
903 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
904 CI.getTarget().getDataLayout(), TheModule.get(), BA,
905 std::move(OS));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000906 return;
907 }
908
909 // Otherwise follow the normal AST path.
910 this->ASTFrontendAction::ExecuteAction();
911}
912
913//
914
David Blaikie68e081d2011-12-20 02:48:34 +0000915void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000916EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
917 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000918
David Blaikie68e081d2011-12-20 02:48:34 +0000919void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000920EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
921 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000922
David Blaikie68e081d2011-12-20 02:48:34 +0000923void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000924EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
925 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000926
David Blaikie68e081d2011-12-20 02:48:34 +0000927void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000928EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
929 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000930
David Blaikie68e081d2011-12-20 02:48:34 +0000931void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000932EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
933 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000934
David Blaikie68e081d2011-12-20 02:48:34 +0000935void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000936EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
937 : CodeGenAction(Backend_EmitObj, _VMContext) {}