blob: 89a7c7c727b0bc4769913eed4c20b25706653299 [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
Justin Lebarb080b632017-01-25 21:29:48 +000010#include "clang/CodeGen/CodeGenAction.h"
11#include "CodeGenModule.h"
Alex Lorenzee024992014-08-04 18:41:51 +000012#include "CoverageMappingGen.h"
Amjad Aboud546bc112017-02-09 22:07:24 +000013#include "MacroPPCallbacks.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000014#include "clang/AST/ASTConsumer.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000015#include "clang/AST/ASTContext.h"
Hans Wennborga926d842014-05-23 20:37:38 +000016#include "clang/AST/DeclCXX.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "clang/AST/DeclGroup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/FileManager.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/TargetInfo.h"
Daniel Dunbarc1b17292010-06-15 17:48:49 +000021#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000022#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000023#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "clang/Lex/Preprocessor.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000026#include "llvm/Bitcode/BitcodeReader.h"
Adam Nemet7b796f82017-01-26 04:07:11 +000027#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000028#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000029#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000033#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000034#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000035#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000036#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000038#include "llvm/Support/Timer.h"
Hal Finkel8f96e822016-10-11 00:26:09 +000039#include "llvm/Support/ToolOutputFile.h"
40#include "llvm/Support/YAMLTraits.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000041#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000042using namespace clang;
43using namespace llvm;
44
Nico Weber2992efa2011-01-25 20:34:14 +000045namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000046 class BackendConsumer : public ASTConsumer {
Justin Lebarb080b632017-01-25 21:29:48 +000047 using LinkModule = CodeGenAction::LinkModule;
48
David Blaikie68e081d2011-12-20 02:48:34 +000049 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000050 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000051 BackendAction Action;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000052 const HeaderSearchOptions &HeaderSearchOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000053 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000054 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000055 const LangOptions &LangOpts;
Peter Collingbourne03f89072016-07-15 00:55:40 +000056 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000057 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000058
Chris Lattner263d64c2009-02-18 01:37:30 +000059 Timer LLVMIRGeneration;
Davide Italianob99fabd2016-07-21 06:28:48 +000060 unsigned LLVMIRGenerationRefCount;
Mike Stump11289f42009-09-09 15:08:12 +000061
Reid Kleckner15241ba2016-11-30 00:25:36 +000062 /// True if we've finished generating IR. This prevents us from generating
63 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
64 /// can happen when Clang plugins trigger additional AST deserialization.
65 bool IRGenFinished = false;
66
Ahmed Charlesb8984322014-03-07 20:03:18 +000067 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000068
Justin Lebarb080b632017-01-25 21:29:48 +000069 SmallVector<LinkModule, 4> LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000070
Rafael Espindola8ce88a52015-12-14 23:17:07 +000071 // This is here so that the diagnostic printer knows the module a diagnostic
72 // refers to.
73 llvm::Module *CurLinkModule = nullptr;
74
Mike Stump11289f42009-09-09 15:08:12 +000075 public:
Justin Lebarb080b632017-01-25 21:29:48 +000076 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
77 const HeaderSearchOptions &HeaderSearchOpts,
78 const PreprocessorOptions &PPOpts,
79 const CodeGenOptions &CodeGenOpts,
80 const TargetOptions &TargetOpts,
81 const LangOptions &LangOpts, bool TimePasses,
82 const std::string &InFile,
83 SmallVector<LinkModule, 4> LinkModules,
84 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
85 CoverageSourceInfo *CoverageInfo = nullptr)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000086 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
87 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
Peter Collingbourne03f89072016-07-15 00:55:40 +000088 AsmOutStream(std::move(OS)), Context(nullptr),
Matthias Braunae032b62016-11-18 19:43:25 +000089 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
Davide Italianob99fabd2016-07-21 06:28:48 +000090 LLVMIRGenerationRefCount(0),
Adrian Prantle74f5252015-06-30 02:26:03 +000091 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Justin Lebarb080b632017-01-25 21:29:48 +000092 CodeGenOpts, C, CoverageInfo)),
93 LinkModules(std::move(LinkModules)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000094 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattnerdeffa132009-02-18 01:23:44 +000095 }
Serge Pavlov41c1f792016-02-18 16:42:09 +000096 llvm::Module *getModule() const { return Gen->GetModule(); }
97 std::unique_ptr<llvm::Module> takeModule() {
98 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
99 }
Daniel Dunbar400a6932010-02-25 04:37:50 +0000100
Amjad Aboud546bc112017-02-09 22:07:24 +0000101 CodeGenerator *getCodeGenerator() { return Gen.get(); }
102
Craig Topper4f12f102014-03-12 06:41:41 +0000103 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +0000104 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +0000105 }
106
Craig Topper4f12f102014-03-12 06:41:41 +0000107 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +0000108 assert(!Context && "initialized multiple times");
109
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000110 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000111
Daniel Dunbar8e705052009-11-30 08:39:52 +0000112 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000113 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000114
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000115 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000116
Daniel Dunbar8e705052009-11-30 08:39:52 +0000117 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000118 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Craig Topper4f12f102014-03-12 06:41:41 +0000121 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000122 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000123 Context->getSourceManager(),
124 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000125
Davide Italianob99fabd2016-07-21 06:28:48 +0000126 // Recurse.
127 if (llvm::TimePassesIsEnabled) {
128 LLVMIRGenerationRefCount += 1;
129 if (LLVMIRGenerationRefCount == 1)
130 LLVMIRGeneration.startTimer();
131 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000132
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000133 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000134
Davide Italianob99fabd2016-07-21 06:28:48 +0000135 if (llvm::TimePassesIsEnabled) {
136 LLVMIRGenerationRefCount -= 1;
137 if (LLVMIRGenerationRefCount == 0)
138 LLVMIRGeneration.stopTimer();
139 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000140
141 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000144 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000145 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
146 Context->getSourceManager(),
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000147 "LLVM IR generation of inline function");
Hans Wennborga926d842014-05-23 20:37:38 +0000148 if (llvm::TimePassesIsEnabled)
149 LLVMIRGeneration.startTimer();
150
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000151 Gen->HandleInlineFunctionDefinition(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000152
153 if (llvm::TimePassesIsEnabled)
154 LLVMIRGeneration.stopTimer();
155 }
156
Reid Kleckner68c4bb52016-11-30 01:32:53 +0000157 void HandleInterestingDecl(DeclGroupRef D) override {
Reid Kleckner15241ba2016-11-30 00:25:36 +0000158 // Ignore interesting decls from the AST reader after IRGen is finished.
159 if (!IRGenFinished)
160 HandleTopLevelDecl(D);
161 }
162
Justin Lebarb080b632017-01-25 21:29:48 +0000163 // Links each entry in LinkModules into our module. Returns true on error.
164 bool LinkInModules() {
165 for (auto &LM : LinkModules) {
166 if (LM.PropagateAttrs)
167 for (Function &F : *LM.Module)
168 Gen->CGM().AddDefaultFnAttrs(F);
169
170 CurLinkModule = LM.Module.get();
171 if (Linker::linkModules(*getModule(), std::move(LM.Module),
172 LM.LinkFlags))
173 return true;
174 }
175 return false; // success
176 }
177
Craig Topper4f12f102014-03-12 06:41:41 +0000178 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000179 {
Chris Lattnere46de752009-03-06 06:46:31 +0000180 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Davide Italianob99fabd2016-07-21 06:28:48 +0000181 if (llvm::TimePassesIsEnabled) {
182 LLVMIRGenerationRefCount += 1;
183 if (LLVMIRGenerationRefCount == 1)
184 LLVMIRGeneration.startTimer();
185 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000186
Chris Lattnercf169832009-03-28 04:11:33 +0000187 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000188
Davide Italianob99fabd2016-07-21 06:28:48 +0000189 if (llvm::TimePassesIsEnabled) {
190 LLVMIRGenerationRefCount -= 1;
191 if (LLVMIRGenerationRefCount == 0)
192 LLVMIRGeneration.stopTimer();
193 }
Reid Kleckner15241ba2016-11-30 00:25:36 +0000194
195 IRGenFinished = true;
Chris Lattnereae6cb62009-03-05 08:00:35 +0000196 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000197
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000198 // Silently ignore if we weren't initialized for some reason.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000199 if (!getModule())
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000200 return;
Mike Stump11289f42009-09-09 15:08:12 +0000201
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000202 // Install an inline asm handler so that diagnostics get printed through
203 // our diagnostics hooks.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000204 LLVMContext &Ctx = getModule()->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000205 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
206 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000207 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000208 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000209
Quentin Colombet728c5542014-02-06 18:30:43 +0000210 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
211 Ctx.getDiagnosticHandler();
212 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
213 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
Adam Nemet1eea3e52016-09-13 04:32:40 +0000214 Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
Quentin Colombet728c5542014-02-06 18:30:43 +0000215
Hal Finkel8f96e822016-10-11 00:26:09 +0000216 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
217 if (!CodeGenOpts.OptRecordFile.empty()) {
218 std::error_code EC;
219 OptRecordFile =
220 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
221 EC, sys::fs::F_None);
222 if (EC) {
223 Diags.Report(diag::err_cannot_open_file) <<
224 CodeGenOpts.OptRecordFile << EC.message();
225 return;
226 }
227
Mehdi Amini6f408362016-11-19 18:19:41 +0000228 Ctx.setDiagnosticsOutputFile(
229 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
Hal Finkel8f96e822016-10-11 00:26:09 +0000230
231 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
232 Ctx.setDiagnosticHotnessRequested(true);
233 }
234
Justin Lebarb080b632017-01-25 21:29:48 +0000235 // Link each LinkModule into our module.
236 if (LinkInModules())
237 return;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000238
Steven Wu27fb5222016-05-11 16:26:03 +0000239 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
240
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000241 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
242 LangOpts, C.getTargetInfo().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000243 getModule(), Action, std::move(AsmOutStream));
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000244
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000245 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000246
247 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Hal Finkel8f96e822016-10-11 00:26:09 +0000248
249 if (OptRecordFile)
250 OptRecordFile->keep();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000251 }
Mike Stump11289f42009-09-09 15:08:12 +0000252
Craig Topper4f12f102014-03-12 06:41:41 +0000253 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000254 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
255 Context->getSourceManager(),
256 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000257 Gen->HandleTagDeclDefinition(D);
258 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000259
Craig Topper4f12f102014-03-12 06:41:41 +0000260 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000261 Gen->HandleTagDeclRequiredDefinition(D);
262 }
263
Craig Topper4f12f102014-03-12 06:41:41 +0000264 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000265 Gen->CompleteTentativeDefinition(D);
266 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000267
David Majnemer929025d2016-01-26 19:30:26 +0000268 void AssignInheritanceModel(CXXRecordDecl *RD) override {
269 Gen->AssignInheritanceModel(RD);
270 }
271
Nico Weberb6a5d052015-01-15 04:07:35 +0000272 void HandleVTable(CXXRecordDecl *RD) override {
273 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000274 }
275
Chris Lattner5ec32e72010-04-06 18:38:50 +0000276 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
277 unsigned LocCookie) {
278 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
279 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
280 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000281
Quentin Colombet728c5542014-02-06 18:30:43 +0000282 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
283 void *Context) {
284 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
285 }
286
Oliver Stannard91817852016-02-02 13:52:52 +0000287 /// Get the best possible source location to represent a diagnostic that
288 /// may have associated debug info.
289 const FullSourceLoc
290 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
291 bool &BadDebugInfo, StringRef &Filename,
292 unsigned &Line, unsigned &Column) const;
293
Chris Lattner5ec32e72010-04-06 18:38:50 +0000294 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
295 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000296
297 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
298 /// \brief Specialized handler for InlineAsm diagnostic.
299 /// \return True if the diagnostic has been successfully reported, false
300 /// otherwise.
301 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
302 /// \brief Specialized handler for StackSize diagnostic.
303 /// \return True if the diagnostic has been successfully reported, false
304 /// otherwise.
305 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Oliver Stannard91817852016-02-02 13:52:52 +0000306 /// \brief Specialized handler for unsupported backend feature diagnostic.
307 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000308 /// \brief Specialized handlers for optimization remarks.
309 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000310 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000311 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
312 unsigned DiagID);
Adam Nemet7b796f82017-01-26 04:07:11 +0000313 void
314 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000315 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000316 const llvm::OptimizationRemarkAnalysisFPCommute &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000317 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000318 const llvm::OptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000319 void OptimizationFailureHandler(
320 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000321 };
David Blaikie68e081d2011-12-20 02:48:34 +0000322
323 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000324}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000325
Chris Lattner79f67a72010-04-08 00:23:06 +0000326/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
327/// buffer to be a valid FullSourceLoc.
328static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
329 SourceManager &CSM) {
330 // Get both the clang and llvm source managers. The location is relative to
331 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000332 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000333 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000334
Chris Lattner79f67a72010-04-08 00:23:06 +0000335 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
336 // already owns its one and clang::SourceManager wants to own its one.
337 const MemoryBuffer *LBuf =
338 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000339
Chris Lattner79f67a72010-04-08 00:23:06 +0000340 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000341 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000342 std::unique_ptr<llvm::MemoryBuffer> CBuf =
343 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
344 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000345 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000346 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000347
Chris Lattner79f67a72010-04-08 00:23:06 +0000348 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000349 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000350 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000351 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000352 return FullSourceLoc(NewLoc, CSM);
353}
354
Chris Lattner6d672132010-04-06 17:52:14 +0000355
Chris Lattner5ec32e72010-04-06 18:38:50 +0000356/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
357/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000358/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000359void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
360 SourceLocation LocCookie) {
361 // There are a couple of different kinds of errors we could get here. First,
362 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000363
364 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000365 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000366 if (Message.startswith("error: "))
367 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000368
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000369 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000370 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000371 if (D.getLoc() != SMLoc())
372 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000373
Joey Gouly5798b262014-06-05 21:23:42 +0000374 unsigned DiagID;
375 switch (D.getKind()) {
376 case llvm::SourceMgr::DK_Error:
377 DiagID = diag::err_fe_inline_asm;
378 break;
379 case llvm::SourceMgr::DK_Warning:
380 DiagID = diag::warn_fe_inline_asm;
381 break;
382 case llvm::SourceMgr::DK_Note:
383 DiagID = diag::note_fe_inline_asm;
384 break;
385 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000386 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000387 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000388 // code.
389 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000390 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000391
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000392 if (D.getLoc().isValid()) {
393 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
394 // Convert the SMDiagnostic ranges into SourceRange and attach them
395 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000396 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000397 unsigned Column = D.getColumnNo();
398 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
399 Loc.getLocWithOffset(Range.second - Column));
400 }
401 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000402 return;
403 }
404
Joey Gouly5798b262014-06-05 21:23:42 +0000405 // Otherwise, report the backend issue as occurring in the generated .s file.
406 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000407 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000408 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000409}
410
Quentin Colombet728c5542014-02-06 18:30:43 +0000411#define ComputeDiagID(Severity, GroupName, DiagID) \
412 do { \
413 switch (Severity) { \
414 case llvm::DS_Error: \
415 DiagID = diag::err_fe_##GroupName; \
416 break; \
417 case llvm::DS_Warning: \
418 DiagID = diag::warn_fe_##GroupName; \
419 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000420 case llvm::DS_Remark: \
421 llvm_unreachable("'remark' severity not expected"); \
422 break; \
423 case llvm::DS_Note: \
424 DiagID = diag::note_fe_##GroupName; \
425 break; \
426 } \
427 } while (false)
428
429#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
430 do { \
431 switch (Severity) { \
432 case llvm::DS_Error: \
433 DiagID = diag::err_fe_##GroupName; \
434 break; \
435 case llvm::DS_Warning: \
436 DiagID = diag::warn_fe_##GroupName; \
437 break; \
438 case llvm::DS_Remark: \
439 DiagID = diag::remark_fe_##GroupName; \
440 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000441 case llvm::DS_Note: \
442 DiagID = diag::note_fe_##GroupName; \
443 break; \
444 } \
445 } while (false)
446
447bool
448BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
449 unsigned DiagID;
450 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
451 std::string Message = D.getMsgStr().str();
452
453 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000454 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000455 // code.
456 SourceLocation LocCookie =
457 SourceLocation::getFromRawEncoding(D.getLocCookie());
458 if (LocCookie.isValid())
459 Diags.Report(LocCookie, DiagID).AddString(Message);
460 else {
461 // Otherwise, report the backend diagnostic as occurring in the generated
462 // .s file.
463 // If Loc is invalid, we still need to report the diagnostic, it just gets
464 // no location info.
465 FullSourceLoc Loc;
466 Diags.Report(Loc, DiagID).AddString(Message);
467 }
468 // We handled all the possible severities.
469 return true;
470}
471
472bool
473BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
474 if (D.getSeverity() != llvm::DS_Warning)
475 // For now, the only support we have for StackSize diagnostic is warning.
476 // We do not know how to format other severities.
477 return false;
478
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000479 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000480 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000481 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
482 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000483 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000484 return true;
485 }
486
487 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000488}
489
Oliver Stannard91817852016-02-02 13:52:52 +0000490const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
491 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
492 unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000493 SourceManager &SourceMgr = Context->getSourceManager();
494 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000495 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000496
497 if (D.isLocationAvailable()) {
498 D.getLocation(&Filename, &Line, &Column);
499 const FileEntry *FE = FileMgr.getFile(Filename);
500 if (FE && Line > 0) {
501 // If -gcolumn-info was not used, Column will be 0. This upsets the
502 // source manager, so pass 1 if Column is not set.
503 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
504 }
Oliver Stannard91817852016-02-02 13:52:52 +0000505 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000506 }
Alp Toker27506272014-06-05 22:11:12 +0000507
508 // If a location isn't available, try to approximate it using the associated
509 // function definition. We use the definition's right brace to differentiate
510 // from diagnostics that genuinely relate to the function itself.
511 FullSourceLoc Loc(DILoc, SourceMgr);
512 if (Loc.isInvalid())
513 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000514 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000515
Diego Novillo86f884e2015-05-08 20:59:56 +0000516 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000517 // If we were not able to translate the file:line:col information
518 // back to a SourceLocation, at least emit a note stating that
519 // we could not translate this location. This can happen in the
520 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000521 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000522 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000523
524 return Loc;
525}
526
527void BackendConsumer::UnsupportedDiagHandler(
528 const llvm::DiagnosticInfoUnsupported &D) {
529 // We only support errors.
530 assert(D.getSeverity() == llvm::DS_Error);
531
532 StringRef Filename;
533 unsigned Line, Column;
534 bool BadDebugInfo;
535 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
536 Line, Column);
537
538 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
539
540 if (BadDebugInfo)
541 // If we were not able to translate the file:line:col information
542 // back to a SourceLocation, at least emit a note stating that
543 // we could not translate this location. This can happen in the
544 // case of #line directives.
545 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
546 << Filename << Line << Column;
547}
548
549void BackendConsumer::EmitOptimizationMessage(
550 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
551 // We only support warnings and remarks.
552 assert(D.getSeverity() == llvm::DS_Remark ||
553 D.getSeverity() == llvm::DS_Warning);
554
555 StringRef Filename;
556 unsigned Line, Column;
557 bool BadDebugInfo = false;
558 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
559 Line, Column);
560
Adam Nemet1eea3e52016-09-13 04:32:40 +0000561 std::string Msg;
562 raw_string_ostream MsgStream(Msg);
Adam Nemet699fc5b2016-09-27 20:55:12 +0000563 MsgStream << D.getMsg();
Adam Nemet1eea3e52016-09-13 04:32:40 +0000564
565 if (D.getHotness())
566 MsgStream << " (hotness: " << *D.getHotness() << ")";
567
Oliver Stannard91817852016-02-02 13:52:52 +0000568 Diags.Report(Loc, DiagID)
Mehdi Amini117296c2016-10-01 02:56:57 +0000569 << AddFlagValue(D.getPassName())
Adam Nemet1eea3e52016-09-13 04:32:40 +0000570 << MsgStream.str();
Oliver Stannard91817852016-02-02 13:52:52 +0000571
572 if (BadDebugInfo)
573 // If we were not able to translate the file:line:col information
574 // back to a SourceLocation, at least emit a note stating that
575 // we could not translate this location. This can happen in the
576 // case of #line directives.
577 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000578 << Filename << Line << Column;
579}
580
581void BackendConsumer::OptimizationRemarkHandler(
Adam Nemet7b796f82017-01-26 04:07:11 +0000582 const llvm::DiagnosticInfoOptimizationBase &D) {
583 if (D.isPassed()) {
584 // Optimization remarks are active only if the -Rpass flag has a regular
585 // expression that matches the name of the pass name in \p D.
586 if (CodeGenOpts.OptimizationRemarkPattern &&
587 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
588 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
589 } else if (D.isMissed()) {
590 // Missed optimization remarks are active only if the -Rpass-missed
591 // flag has a regular expression that matches the name of the pass
592 // name in \p D.
593 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
594 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
595 EmitOptimizationMessage(
596 D, diag::remark_fe_backend_optimization_remark_missed);
597 } else {
598 assert(D.isAnalysis() && "Unknown remark type");
Diego Novillod23ec942014-05-29 19:55:06 +0000599
Adam Nemet7b796f82017-01-26 04:07:11 +0000600 bool ShouldAlwaysPrint = false;
601 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
602 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
Diego Novillod23ec942014-05-29 19:55:06 +0000603
Adam Nemet7b796f82017-01-26 04:07:11 +0000604 if (ShouldAlwaysPrint ||
605 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
606 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
607 EmitOptimizationMessage(
608 D, diag::remark_fe_backend_optimization_remark_analysis);
609 }
Diego Novillo829b1702014-04-16 16:54:24 +0000610}
611
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000612void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000613 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000614 // Optimization analysis remarks are active if the pass name is set to
615 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
616 // regular expression that matches the name of the pass name in \p D.
617
Adam Nemetb5beb972016-06-29 04:55:31 +0000618 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000619 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
620 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000621 EmitOptimizationMessage(
622 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
623}
624
Tyler Nowicki034baf62015-08-10 23:05:16 +0000625void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000626 const llvm::OptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000627 // Optimization analysis remarks are active if the pass name is set to
628 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
629 // regular expression that matches the name of the pass name in \p D.
630
Adam Nemetb5beb972016-06-29 04:55:31 +0000631 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000632 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
633 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000634 EmitOptimizationMessage(
635 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
636}
637
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000638void BackendConsumer::OptimizationFailureHandler(
639 const llvm::DiagnosticInfoOptimizationFailure &D) {
640 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
641}
642
Quentin Colombet728c5542014-02-06 18:30:43 +0000643/// \brief This function is invoked when the backend needs
644/// to report something to the user.
645void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
646 unsigned DiagID = diag::err_fe_inline_asm;
647 llvm::DiagnosticSeverity Severity = DI.getSeverity();
648 // Get the diagnostic ID based.
649 switch (DI.getKind()) {
650 case llvm::DK_InlineAsm:
651 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
652 return;
653 ComputeDiagID(Severity, inline_asm, DiagID);
654 break;
655 case llvm::DK_StackSize:
656 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
657 return;
658 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
659 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000660 case DK_Linker:
661 assert(CurLinkModule);
662 // FIXME: stop eating the warnings and notes.
663 if (Severity != DS_Error)
664 return;
665 DiagID = diag::err_fe_cannot_link_module;
666 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000667 case llvm::DK_OptimizationRemark:
668 // Optimization remarks are always handled completely by this
669 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000670 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
Diego Novillo829b1702014-04-16 16:54:24 +0000671 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000672 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000673 // Optimization remarks are always handled completely by this
674 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000675 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
Diego Novillod23ec942014-05-29 19:55:06 +0000676 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000677 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000678 // Optimization remarks are always handled completely by this
679 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000680 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000681 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000682 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
683 // Optimization remarks are always handled completely by this
684 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000685 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000686 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000687 case llvm::DK_OptimizationRemarkAnalysisAliasing:
688 // Optimization remarks are always handled completely by this
689 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000690 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
Tyler Nowicki034baf62015-08-10 23:05:16 +0000691 return;
Adam Nemet7b796f82017-01-26 04:07:11 +0000692 case llvm::DK_MachineOptimizationRemark:
693 // Optimization remarks are always handled completely by this
694 // handler. There is no generic way of emitting them.
695 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
696 return;
697 case llvm::DK_MachineOptimizationRemarkMissed:
698 // Optimization remarks are always handled completely by this
699 // handler. There is no generic way of emitting them.
700 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
701 return;
702 case llvm::DK_MachineOptimizationRemarkAnalysis:
703 // Optimization remarks are always handled completely by this
704 // handler. There is no generic way of emitting them.
705 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
706 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000707 case llvm::DK_OptimizationFailure:
708 // Optimization failures are always handled completely by this
709 // handler.
710 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
711 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000712 case llvm::DK_Unsupported:
713 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
714 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000715 default:
716 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000717 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000718 break;
719 }
720 std::string MsgStorage;
721 {
722 raw_string_ostream Stream(MsgStorage);
723 DiagnosticPrinterRawOStream DP(Stream);
724 DI.print(DP);
725 }
726
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000727 if (DiagID == diag::err_fe_cannot_link_module) {
728 Diags.Report(diag::err_fe_cannot_link_module)
729 << CurLinkModule->getModuleIdentifier() << MsgStorage;
730 return;
731 }
732
Quentin Colombet728c5542014-02-06 18:30:43 +0000733 // Report the backend message using the usual diagnostic mechanism.
734 FullSourceLoc Loc;
735 Diags.Report(Loc, DiagID).AddString(MsgStorage);
736}
737#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000738
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000739CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000740 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000741 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000742
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000743CodeGenAction::~CodeGenAction() {
744 TheModule.reset();
745 if (OwnsVMContext)
746 delete VMContext;
747}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000748
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000749bool CodeGenAction::hasIRSupport() const { return true; }
750
Daniel Dunbar400a6932010-02-25 04:37:50 +0000751void CodeGenAction::EndSourceFileAction() {
752 // If the consumer creation failed, do nothing.
753 if (!getCompilerInstance().hasASTConsumer())
754 return;
755
756 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000757 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000758}
759
Rafael Espindolae8337302014-08-19 14:36:35 +0000760std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
761 return std::move(TheModule);
762}
763
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000764llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
765 OwnsVMContext = false;
766 return VMContext;
767}
768
Peter Collingbourne03f89072016-07-15 00:55:40 +0000769static std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000770GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000771 switch (Action) {
772 case Backend_EmitAssembly:
773 return CI.createDefaultOutputFile(false, InFile, "s");
774 case Backend_EmitLL:
775 return CI.createDefaultOutputFile(false, InFile, "ll");
776 case Backend_EmitBC:
777 return CI.createDefaultOutputFile(true, InFile, "bc");
778 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000779 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000780 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000781 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000782 case Backend_EmitObj:
783 return CI.createDefaultOutputFile(true, InFile, "o");
784 }
785
David Blaikie83d382b2011-09-23 05:06:16 +0000786 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000787}
788
David Blaikie6beb6aa2014-08-10 19:56:51 +0000789std::unique_ptr<ASTConsumer>
790CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000791 BackendAction BA = static_cast<BackendAction>(Act);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000792 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000793 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000794 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000795
Artem Belevich5d40ae32015-10-27 17:56:59 +0000796 // Load bitcode modules to link with, if we need to.
797 if (LinkModules.empty())
Justin Lebarb080b632017-01-25 21:29:48 +0000798 for (const CodeGenOptions::BitcodeFileToLink &F :
799 CI.getCodeGenOpts().LinkBitcodeFiles) {
800 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000801 if (!BCBuf) {
802 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000803 << F.Filename << BCBuf.getError().message();
Artem Belevich5d40ae32015-10-27 17:56:59 +0000804 LinkModules.clear();
805 return nullptr;
806 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000807
Peter Collingbourned9445c42016-11-13 07:00:17 +0000808 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000809 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000810 if (!ModuleOrErr) {
811 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
812 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000813 << F.Filename << EIB.message();
Peter Collingbourned9445c42016-11-13 07:00:17 +0000814 });
Artem Belevich5d40ae32015-10-27 17:56:59 +0000815 LinkModules.clear();
816 return nullptr;
817 }
Justin Lebarb080b632017-01-25 21:29:48 +0000818 LinkModules.push_back(
819 {std::move(ModuleOrErr.get()), F.PropagateAttrs, F.LinkFlags});
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000820 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000821
Alex Lorenzee024992014-08-04 18:41:51 +0000822 CoverageSourceInfo *CoverageInfo = nullptr;
823 // Add the preprocessor callback only when the coverage mapping is generated.
824 if (CI.getCodeGenOpts().CoverageMapping) {
825 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000826 CI.getPreprocessor().addPPCallbacks(
827 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000828 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000829
David Blaikie037e75b2014-08-10 21:06:17 +0000830 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000831 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
832 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Justin Lebarb080b632017-01-25 21:29:48 +0000833 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
834 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000835 BEConsumer = Result.get();
Amjad Aboud546bc112017-02-09 22:07:24 +0000836
837 // Enable generating macro debug info only when debug info is not disabled and
838 // also macro debug info is enabled.
839 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
840 CI.getCodeGenOpts().MacroDebugInfo) {
841 std::unique_ptr<PPCallbacks> Callbacks =
842 llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
843 CI.getPreprocessor());
844 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
845 }
846
David Blaikie6beb6aa2014-08-10 19:56:51 +0000847 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000848}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000849
Tim Northover1390b442016-04-06 19:58:07 +0000850static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
851 void *Context,
852 unsigned LocCookie) {
853 SM.print(nullptr, llvm::errs());
854
855 auto Diags = static_cast<DiagnosticsEngine *>(Context);
856 unsigned DiagID;
857 switch (SM.getKind()) {
858 case llvm::SourceMgr::DK_Error:
859 DiagID = diag::err_fe_inline_asm;
860 break;
861 case llvm::SourceMgr::DK_Warning:
862 DiagID = diag::warn_fe_inline_asm;
863 break;
864 case llvm::SourceMgr::DK_Note:
865 DiagID = diag::note_fe_inline_asm;
866 break;
867 }
868
869 Diags->Report(DiagID).AddString("cannot compile inline asm");
870}
871
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000872std::unique_ptr<llvm::Module> CodeGenAction::loadModule(MemoryBufferRef MBRef) {
873 CompilerInstance &CI = getCompilerInstance();
874 SourceManager &SM = CI.getSourceManager();
875
876 // For ThinLTO backend invocations, ensure that the context
Peter Collingbournef5d17122017-01-26 21:09:48 +0000877 // merges types based on ODR identifiers. We also need to read
878 // the correct module out of a multi-module bitcode file.
879 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000880 VMContext->enableDebugTypeODRUniquing();
881
Peter Collingbournef5d17122017-01-26 21:09:48 +0000882 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
883 unsigned DiagID =
884 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
885 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
886 CI.getDiagnostics().Report(DiagID) << EIB.message();
887 });
888 return {};
889 };
890
891 Expected<llvm::BitcodeModule> BMOrErr = FindThinLTOModule(MBRef);
892 if (!BMOrErr)
893 return DiagErrors(BMOrErr.takeError());
894
895 Expected<std::unique_ptr<llvm::Module>> MOrErr =
896 BMOrErr->parseModule(*VMContext);
897 if (!MOrErr)
898 return DiagErrors(MOrErr.takeError());
899 return std::move(*MOrErr);
900 }
901
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000902 llvm::SMDiagnostic Err;
903 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
904 return M;
905
906 // Translate from the diagnostic info to the SourceManager location if
907 // available.
908 // TODO: Unify this with ConvertBackendLocation()
909 SourceLocation Loc;
910 if (Err.getLineNo() > 0) {
911 assert(Err.getColumnNo() >= 0);
912 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
913 Err.getLineNo(), Err.getColumnNo() + 1);
914 }
915
916 // Strip off a leading diagnostic code if there is one.
917 StringRef Msg = Err.getMessage();
918 if (Msg.startswith("error: "))
919 Msg = Msg.substr(7);
920
921 unsigned DiagID =
922 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
923
924 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
925 return {};
926}
927
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000928void CodeGenAction::ExecuteAction() {
929 // If this is an IR file, we have to treat it specially.
930 if (getCurrentFileKind() == IK_LLVM_IR) {
931 BackendAction BA = static_cast<BackendAction>(Act);
932 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000933 std::unique_ptr<raw_pwrite_stream> OS =
934 GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000935 if (BA != Backend_EmitNothing && !OS)
936 return;
937
938 bool Invalid;
939 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000940 FileID FID = SM.getMainFileID();
941 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000942 if (Invalid)
943 return;
944
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000945 TheModule = loadModule(*MainFile);
946 if (!TheModule)
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000947 return;
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000948
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000949 const TargetOptions &TargetOpts = CI.getTargetOpts();
950 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000951 CI.getDiagnostics().Report(SourceLocation(),
952 diag::warn_fe_override_module)
953 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000954 TheModule->setTargetTriple(TargetOpts.Triple);
955 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000956
Steven Wu27fb5222016-05-11 16:26:03 +0000957 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
958 MainFile->getMemBufferRef());
959
Tim Northover1390b442016-04-06 19:58:07 +0000960 LLVMContext &Ctx = TheModule->getContext();
961 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
962 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +0000963
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000964 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
965 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
966 CI.getTarget().getDataLayout(), TheModule.get(), BA,
967 std::move(OS));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000968 return;
969 }
970
971 // Otherwise follow the normal AST path.
972 this->ASTFrontendAction::ExecuteAction();
973}
974
975//
976
David Blaikie68e081d2011-12-20 02:48:34 +0000977void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000978EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
979 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000980
David Blaikie68e081d2011-12-20 02:48:34 +0000981void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000982EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
983 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000984
David Blaikie68e081d2011-12-20 02:48:34 +0000985void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000986EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
987 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000988
David Blaikie68e081d2011-12-20 02:48:34 +0000989void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000990EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
991 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000992
David Blaikie68e081d2011-12-20 02:48:34 +0000993void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000994EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
995 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000996
David Blaikie68e081d2011-12-20 02:48:34 +0000997void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000998EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
999 : CodeGenAction(Backend_EmitObj, _VMContext) {}