blob: 657af24e739bb1e922e5d657a7479f22e75869fb [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/Bitcode/ReaderWriter.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;
Daniel Dunbarde182242009-11-30 08:39:32 +000047 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000048 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000049 const LangOptions &LangOpts;
Peter Collingbourne03f89072016-07-15 00:55:40 +000050 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000051 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000052
Chris Lattner263d64c2009-02-18 01:37:30 +000053 Timer LLVMIRGeneration;
Davide Italianob99fabd2016-07-21 06:28:48 +000054 unsigned LLVMIRGenerationRefCount;
Mike Stump11289f42009-09-09 15:08:12 +000055
Ahmed Charlesb8984322014-03-07 20:03:18 +000056 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000057
Artem Belevich5d40ae32015-10-27 17:56:59 +000058 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
59 LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000060
Rafael Espindola8ce88a52015-12-14 23:17:07 +000061 // This is here so that the diagnostic printer knows the module a diagnostic
62 // refers to.
63 llvm::Module *CurLinkModule = nullptr;
64
Mike Stump11289f42009-09-09 15:08:12 +000065 public:
Artem Belevich5d40ae32015-10-27 17:56:59 +000066 BackendConsumer(
67 BackendAction Action, DiagnosticsEngine &Diags,
68 const HeaderSearchOptions &HeaderSearchOpts,
69 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
70 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
71 bool TimePasses, const std::string &InFile,
72 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
Peter Collingbourne03f89072016-07-15 00:55:40 +000073 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
Artem Belevich5d40ae32015-10-27 17:56:59 +000074 CoverageSourceInfo *CoverageInfo = nullptr)
Justin Bognercb082992015-05-22 22:16:55 +000075 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
Peter Collingbourne03f89072016-07-15 00:55:40 +000076 TargetOpts(TargetOpts), LangOpts(LangOpts),
77 AsmOutStream(std::move(OS)), Context(nullptr),
78 LLVMIRGeneration("LLVM IR Generation Time"),
Davide Italianob99fabd2016-07-21 06:28:48 +000079 LLVMIRGenerationRefCount(0),
Adrian Prantle74f5252015-06-30 02:26:03 +000080 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Artem Belevich5d40ae32015-10-27 17:56:59 +000081 CodeGenOpts, C, CoverageInfo)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000082 llvm::TimePassesIsEnabled = TimePasses;
Artem Belevich5d40ae32015-10-27 17:56:59 +000083 for (auto &I : LinkModules)
84 this->LinkModules.push_back(
85 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
Chris Lattnerdeffa132009-02-18 01:23:44 +000086 }
Serge Pavlov41c1f792016-02-18 16:42:09 +000087 llvm::Module *getModule() const { return Gen->GetModule(); }
88 std::unique_ptr<llvm::Module> takeModule() {
89 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
90 }
Artem Belevich5d40ae32015-10-27 17:56:59 +000091 void releaseLinkModules() {
92 for (auto &I : LinkModules)
93 I.second.release();
94 }
Daniel Dunbar400a6932010-02-25 04:37:50 +000095
Craig Topper4f12f102014-03-12 06:41:41 +000096 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +000097 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +000098 }
99
Craig Topper4f12f102014-03-12 06:41:41 +0000100 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +0000101 assert(!Context && "initialized multiple times");
102
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000103 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000104
Daniel Dunbar8e705052009-11-30 08:39:52 +0000105 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000106 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000107
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000108 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000109
Daniel Dunbar8e705052009-11-30 08:39:52 +0000110 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000111 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000112 }
Mike Stump11289f42009-09-09 15:08:12 +0000113
Craig Topper4f12f102014-03-12 06:41:41 +0000114 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000115 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000116 Context->getSourceManager(),
117 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000118
Davide Italianob99fabd2016-07-21 06:28:48 +0000119 // Recurse.
120 if (llvm::TimePassesIsEnabled) {
121 LLVMIRGenerationRefCount += 1;
122 if (LLVMIRGenerationRefCount == 1)
123 LLVMIRGeneration.startTimer();
124 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000125
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000126 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000127
Davide Italianob99fabd2016-07-21 06:28:48 +0000128 if (llvm::TimePassesIsEnabled) {
129 LLVMIRGenerationRefCount -= 1;
130 if (LLVMIRGenerationRefCount == 0)
131 LLVMIRGeneration.stopTimer();
132 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000133
134 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000135 }
Mike Stump11289f42009-09-09 15:08:12 +0000136
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000137 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000138 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
139 Context->getSourceManager(),
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000140 "LLVM IR generation of inline function");
Hans Wennborga926d842014-05-23 20:37:38 +0000141 if (llvm::TimePassesIsEnabled)
142 LLVMIRGeneration.startTimer();
143
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000144 Gen->HandleInlineFunctionDefinition(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000145
146 if (llvm::TimePassesIsEnabled)
147 LLVMIRGeneration.stopTimer();
148 }
149
Craig Topper4f12f102014-03-12 06:41:41 +0000150 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000151 {
Chris Lattnere46de752009-03-06 06:46:31 +0000152 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Davide Italianob99fabd2016-07-21 06:28:48 +0000153 if (llvm::TimePassesIsEnabled) {
154 LLVMIRGenerationRefCount += 1;
155 if (LLVMIRGenerationRefCount == 1)
156 LLVMIRGeneration.startTimer();
157 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000158
Chris Lattnercf169832009-03-28 04:11:33 +0000159 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000160
Davide Italianob99fabd2016-07-21 06:28:48 +0000161 if (llvm::TimePassesIsEnabled) {
162 LLVMIRGenerationRefCount -= 1;
163 if (LLVMIRGenerationRefCount == 0)
164 LLVMIRGeneration.stopTimer();
165 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000166 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000167
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000168 // Silently ignore if we weren't initialized for some reason.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000169 if (!getModule())
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000170 return;
Mike Stump11289f42009-09-09 15:08:12 +0000171
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000172 // Install an inline asm handler so that diagnostics get printed through
173 // our diagnostics hooks.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000174 LLVMContext &Ctx = getModule()->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000175 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
176 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000177 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000178 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000179
Quentin Colombet728c5542014-02-06 18:30:43 +0000180 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
181 Ctx.getDiagnosticHandler();
182 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
183 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
Adam Nemet1eea3e52016-09-13 04:32:40 +0000184 Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
Quentin Colombet728c5542014-02-06 18:30:43 +0000185
Hal Finkel8f96e822016-10-11 00:26:09 +0000186 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
187 if (!CodeGenOpts.OptRecordFile.empty()) {
188 std::error_code EC;
189 OptRecordFile =
190 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
191 EC, sys::fs::F_None);
192 if (EC) {
193 Diags.Report(diag::err_cannot_open_file) <<
194 CodeGenOpts.OptRecordFile << EC.message();
195 return;
196 }
197
198 Ctx.setDiagnosticsOutputFile(new yaml::Output(OptRecordFile->os()));
199
200 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
201 Ctx.setDiagnosticHotnessRequested(true);
202 }
203
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000204 // Link LinkModule into this module if present, preserving its validity.
205 for (auto &I : LinkModules) {
206 unsigned LinkFlags = I.first;
207 CurLinkModule = I.second.get();
Serge Pavlov41c1f792016-02-18 16:42:09 +0000208 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000209 return;
210 }
211
Steven Wu27fb5222016-05-11 16:26:03 +0000212 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
213
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000214 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
James Y Knightb214cbc2016-03-04 19:00:41 +0000215 C.getTargetInfo().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000216 getModule(), Action, std::move(AsmOutStream));
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000217
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000218 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000219
220 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Hal Finkel8f96e822016-10-11 00:26:09 +0000221
222 if (OptRecordFile)
223 OptRecordFile->keep();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
Craig Topper4f12f102014-03-12 06:41:41 +0000226 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000227 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
228 Context->getSourceManager(),
229 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000230 Gen->HandleTagDeclDefinition(D);
231 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000232
Craig Topper4f12f102014-03-12 06:41:41 +0000233 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000234 Gen->HandleTagDeclRequiredDefinition(D);
235 }
236
Craig Topper4f12f102014-03-12 06:41:41 +0000237 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000238 Gen->CompleteTentativeDefinition(D);
239 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000240
David Majnemer929025d2016-01-26 19:30:26 +0000241 void AssignInheritanceModel(CXXRecordDecl *RD) override {
242 Gen->AssignInheritanceModel(RD);
243 }
244
Nico Weberb6a5d052015-01-15 04:07:35 +0000245 void HandleVTable(CXXRecordDecl *RD) override {
246 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000247 }
248
Chris Lattner5ec32e72010-04-06 18:38:50 +0000249 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
250 unsigned LocCookie) {
251 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
252 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
253 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000254
Quentin Colombet728c5542014-02-06 18:30:43 +0000255 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
256 void *Context) {
257 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
258 }
259
Oliver Stannard91817852016-02-02 13:52:52 +0000260 /// Get the best possible source location to represent a diagnostic that
261 /// may have associated debug info.
262 const FullSourceLoc
263 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
264 bool &BadDebugInfo, StringRef &Filename,
265 unsigned &Line, unsigned &Column) const;
266
Chris Lattner5ec32e72010-04-06 18:38:50 +0000267 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
268 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000269
270 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
271 /// \brief Specialized handler for InlineAsm diagnostic.
272 /// \return True if the diagnostic has been successfully reported, false
273 /// otherwise.
274 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
275 /// \brief Specialized handler for StackSize diagnostic.
276 /// \return True if the diagnostic has been successfully reported, false
277 /// otherwise.
278 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Oliver Stannard91817852016-02-02 13:52:52 +0000279 /// \brief Specialized handler for unsupported backend feature diagnostic.
280 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000281 /// \brief Specialized handlers for optimization remarks.
282 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000283 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000284 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
285 unsigned DiagID);
Adam Nemetb4e64a72016-09-27 22:19:29 +0000286 void OptimizationRemarkHandler(const llvm::OptimizationRemark &D);
287 void OptimizationRemarkHandler(const llvm::OptimizationRemarkMissed &D);
288 void OptimizationRemarkHandler(const llvm::OptimizationRemarkAnalysis &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000289 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000290 const llvm::OptimizationRemarkAnalysisFPCommute &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000291 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000292 const llvm::OptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000293 void OptimizationFailureHandler(
294 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000295 };
David Blaikie68e081d2011-12-20 02:48:34 +0000296
297 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000298}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000299
Chris Lattner79f67a72010-04-08 00:23:06 +0000300/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
301/// buffer to be a valid FullSourceLoc.
302static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
303 SourceManager &CSM) {
304 // Get both the clang and llvm source managers. The location is relative to
305 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000306 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000307 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000308
Chris Lattner79f67a72010-04-08 00:23:06 +0000309 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
310 // already owns its one and clang::SourceManager wants to own its one.
311 const MemoryBuffer *LBuf =
312 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000313
Chris Lattner79f67a72010-04-08 00:23:06 +0000314 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000315 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000316 std::unique_ptr<llvm::MemoryBuffer> CBuf =
317 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
318 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000319 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000320 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000321
Chris Lattner79f67a72010-04-08 00:23:06 +0000322 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000323 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000324 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000325 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000326 return FullSourceLoc(NewLoc, CSM);
327}
328
Chris Lattner6d672132010-04-06 17:52:14 +0000329
Chris Lattner5ec32e72010-04-06 18:38:50 +0000330/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
331/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000332/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000333void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
334 SourceLocation LocCookie) {
335 // There are a couple of different kinds of errors we could get here. First,
336 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000337
338 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000339 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000340 if (Message.startswith("error: "))
341 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000342
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000343 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000344 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000345 if (D.getLoc() != SMLoc())
346 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000347
Joey Gouly5798b262014-06-05 21:23:42 +0000348 unsigned DiagID;
349 switch (D.getKind()) {
350 case llvm::SourceMgr::DK_Error:
351 DiagID = diag::err_fe_inline_asm;
352 break;
353 case llvm::SourceMgr::DK_Warning:
354 DiagID = diag::warn_fe_inline_asm;
355 break;
356 case llvm::SourceMgr::DK_Note:
357 DiagID = diag::note_fe_inline_asm;
358 break;
359 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000360 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000361 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000362 // code.
363 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000364 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000365
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000366 if (D.getLoc().isValid()) {
367 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
368 // Convert the SMDiagnostic ranges into SourceRange and attach them
369 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000370 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000371 unsigned Column = D.getColumnNo();
372 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
373 Loc.getLocWithOffset(Range.second - Column));
374 }
375 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000376 return;
377 }
378
Joey Gouly5798b262014-06-05 21:23:42 +0000379 // Otherwise, report the backend issue as occurring in the generated .s file.
380 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000381 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000382 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000383}
384
Quentin Colombet728c5542014-02-06 18:30:43 +0000385#define ComputeDiagID(Severity, GroupName, DiagID) \
386 do { \
387 switch (Severity) { \
388 case llvm::DS_Error: \
389 DiagID = diag::err_fe_##GroupName; \
390 break; \
391 case llvm::DS_Warning: \
392 DiagID = diag::warn_fe_##GroupName; \
393 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000394 case llvm::DS_Remark: \
395 llvm_unreachable("'remark' severity not expected"); \
396 break; \
397 case llvm::DS_Note: \
398 DiagID = diag::note_fe_##GroupName; \
399 break; \
400 } \
401 } while (false)
402
403#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
404 do { \
405 switch (Severity) { \
406 case llvm::DS_Error: \
407 DiagID = diag::err_fe_##GroupName; \
408 break; \
409 case llvm::DS_Warning: \
410 DiagID = diag::warn_fe_##GroupName; \
411 break; \
412 case llvm::DS_Remark: \
413 DiagID = diag::remark_fe_##GroupName; \
414 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000415 case llvm::DS_Note: \
416 DiagID = diag::note_fe_##GroupName; \
417 break; \
418 } \
419 } while (false)
420
421bool
422BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
423 unsigned DiagID;
424 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
425 std::string Message = D.getMsgStr().str();
426
427 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000428 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000429 // code.
430 SourceLocation LocCookie =
431 SourceLocation::getFromRawEncoding(D.getLocCookie());
432 if (LocCookie.isValid())
433 Diags.Report(LocCookie, DiagID).AddString(Message);
434 else {
435 // Otherwise, report the backend diagnostic as occurring in the generated
436 // .s file.
437 // If Loc is invalid, we still need to report the diagnostic, it just gets
438 // no location info.
439 FullSourceLoc Loc;
440 Diags.Report(Loc, DiagID).AddString(Message);
441 }
442 // We handled all the possible severities.
443 return true;
444}
445
446bool
447BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
448 if (D.getSeverity() != llvm::DS_Warning)
449 // For now, the only support we have for StackSize diagnostic is warning.
450 // We do not know how to format other severities.
451 return false;
452
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000453 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000454 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000455 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
456 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000457 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000458 return true;
459 }
460
461 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000462}
463
Oliver Stannard91817852016-02-02 13:52:52 +0000464const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
465 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
466 unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000467 SourceManager &SourceMgr = Context->getSourceManager();
468 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000469 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000470
471 if (D.isLocationAvailable()) {
472 D.getLocation(&Filename, &Line, &Column);
473 const FileEntry *FE = FileMgr.getFile(Filename);
474 if (FE && Line > 0) {
475 // If -gcolumn-info was not used, Column will be 0. This upsets the
476 // source manager, so pass 1 if Column is not set.
477 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
478 }
Oliver Stannard91817852016-02-02 13:52:52 +0000479 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000480 }
Alp Toker27506272014-06-05 22:11:12 +0000481
482 // If a location isn't available, try to approximate it using the associated
483 // function definition. We use the definition's right brace to differentiate
484 // from diagnostics that genuinely relate to the function itself.
485 FullSourceLoc Loc(DILoc, SourceMgr);
486 if (Loc.isInvalid())
487 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000488 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000489
Diego Novillo86f884e2015-05-08 20:59:56 +0000490 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000491 // If we were not able to translate the file:line:col information
492 // back to a SourceLocation, at least emit a note stating that
493 // we could not translate this location. This can happen in the
494 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000495 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000496 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000497
498 return Loc;
499}
500
501void BackendConsumer::UnsupportedDiagHandler(
502 const llvm::DiagnosticInfoUnsupported &D) {
503 // We only support errors.
504 assert(D.getSeverity() == llvm::DS_Error);
505
506 StringRef Filename;
507 unsigned Line, Column;
508 bool BadDebugInfo;
509 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
510 Line, Column);
511
512 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
513
514 if (BadDebugInfo)
515 // If we were not able to translate the file:line:col information
516 // back to a SourceLocation, at least emit a note stating that
517 // we could not translate this location. This can happen in the
518 // case of #line directives.
519 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
520 << Filename << Line << Column;
521}
522
523void BackendConsumer::EmitOptimizationMessage(
524 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
525 // We only support warnings and remarks.
526 assert(D.getSeverity() == llvm::DS_Remark ||
527 D.getSeverity() == llvm::DS_Warning);
528
529 StringRef Filename;
530 unsigned Line, Column;
531 bool BadDebugInfo = false;
532 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
533 Line, Column);
534
Adam Nemet1eea3e52016-09-13 04:32:40 +0000535 std::string Msg;
536 raw_string_ostream MsgStream(Msg);
Adam Nemet699fc5b2016-09-27 20:55:12 +0000537 MsgStream << D.getMsg();
Adam Nemet1eea3e52016-09-13 04:32:40 +0000538
539 if (D.getHotness())
540 MsgStream << " (hotness: " << *D.getHotness() << ")";
541
Oliver Stannard91817852016-02-02 13:52:52 +0000542 Diags.Report(Loc, DiagID)
Mehdi Amini117296c2016-10-01 02:56:57 +0000543 << AddFlagValue(D.getPassName())
Adam Nemet1eea3e52016-09-13 04:32:40 +0000544 << MsgStream.str();
Oliver Stannard91817852016-02-02 13:52:52 +0000545
546 if (BadDebugInfo)
547 // If we were not able to translate the file:line:col information
548 // back to a SourceLocation, at least emit a note stating that
549 // we could not translate this location. This can happen in the
550 // case of #line directives.
551 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000552 << Filename << Line << Column;
553}
554
555void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000556 const llvm::OptimizationRemark &D) {
Diego Novillod23ec942014-05-29 19:55:06 +0000557 // Optimization remarks are active only if the -Rpass flag has a regular
558 // expression that matches the name of the pass name in \p D.
559 if (CodeGenOpts.OptimizationRemarkPattern &&
560 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000561 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
Diego Novillod23ec942014-05-29 19:55:06 +0000562}
563
564void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000565 const llvm::OptimizationRemarkMissed &D) {
Diego Novillod23ec942014-05-29 19:55:06 +0000566 // Missed optimization remarks are active only if the -Rpass-missed
567 // flag has a regular expression that matches the name of the pass
568 // name in \p D.
569 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
570 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000571 EmitOptimizationMessage(D,
572 diag::remark_fe_backend_optimization_remark_missed);
Diego Novillod23ec942014-05-29 19:55:06 +0000573}
574
575void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000576 const llvm::OptimizationRemarkAnalysis &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000577 // Optimization analysis remarks are active if the pass name is set to
578 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
579 // regular expression that matches the name of the pass name in \p D.
580
Adam Nemetb5beb972016-06-29 04:55:31 +0000581 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000582 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
583 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000584 EmitOptimizationMessage(
Diego Novillod23ec942014-05-29 19:55:06 +0000585 D, diag::remark_fe_backend_optimization_remark_analysis);
Diego Novillo829b1702014-04-16 16:54:24 +0000586}
587
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000588void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000589 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000590 // Optimization analysis remarks are active if the pass name is set to
591 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
592 // regular expression that matches the name of the pass name in \p D.
593
Adam Nemetb5beb972016-06-29 04:55:31 +0000594 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000595 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
596 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000597 EmitOptimizationMessage(
598 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
599}
600
Tyler Nowicki034baf62015-08-10 23:05:16 +0000601void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000602 const llvm::OptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000603 // Optimization analysis remarks are active if the pass name is set to
604 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
605 // regular expression that matches the name of the pass name in \p D.
606
Adam Nemetb5beb972016-06-29 04:55:31 +0000607 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000608 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
609 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000610 EmitOptimizationMessage(
611 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
612}
613
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000614void BackendConsumer::OptimizationFailureHandler(
615 const llvm::DiagnosticInfoOptimizationFailure &D) {
616 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
617}
618
Quentin Colombet728c5542014-02-06 18:30:43 +0000619/// \brief This function is invoked when the backend needs
620/// to report something to the user.
621void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
622 unsigned DiagID = diag::err_fe_inline_asm;
623 llvm::DiagnosticSeverity Severity = DI.getSeverity();
624 // Get the diagnostic ID based.
625 switch (DI.getKind()) {
626 case llvm::DK_InlineAsm:
627 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
628 return;
629 ComputeDiagID(Severity, inline_asm, DiagID);
630 break;
631 case llvm::DK_StackSize:
632 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
633 return;
634 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
635 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000636 case DK_Linker:
637 assert(CurLinkModule);
638 // FIXME: stop eating the warnings and notes.
639 if (Severity != DS_Error)
640 return;
641 DiagID = diag::err_fe_cannot_link_module;
642 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000643 case llvm::DK_OptimizationRemark:
644 // Optimization remarks are always handled completely by this
645 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000646 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
Diego Novillo829b1702014-04-16 16:54:24 +0000647 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000648 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000649 // Optimization remarks are always handled completely by this
650 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000651 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
Diego Novillod23ec942014-05-29 19:55:06 +0000652 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000653 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000654 // Optimization remarks are always handled completely by this
655 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000656 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000657 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000658 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
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<OptimizationRemarkAnalysisFPCommute>(DI));
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000662 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000663 case llvm::DK_OptimizationRemarkAnalysisAliasing:
664 // 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<OptimizationRemarkAnalysisAliasing>(DI));
Tyler Nowicki034baf62015-08-10 23:05:16 +0000667 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000668 case llvm::DK_OptimizationFailure:
669 // Optimization failures are always handled completely by this
670 // handler.
671 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
672 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000673 case llvm::DK_Unsupported:
674 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
675 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000676 default:
677 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000678 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000679 break;
680 }
681 std::string MsgStorage;
682 {
683 raw_string_ostream Stream(MsgStorage);
684 DiagnosticPrinterRawOStream DP(Stream);
685 DI.print(DP);
686 }
687
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000688 if (DiagID == diag::err_fe_cannot_link_module) {
689 Diags.Report(diag::err_fe_cannot_link_module)
690 << CurLinkModule->getModuleIdentifier() << MsgStorage;
691 return;
692 }
693
Quentin Colombet728c5542014-02-06 18:30:43 +0000694 // Report the backend message using the usual diagnostic mechanism.
695 FullSourceLoc Loc;
696 Diags.Report(Loc, DiagID).AddString(MsgStorage);
697}
698#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000699
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000700CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000701 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000702 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000703
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000704CodeGenAction::~CodeGenAction() {
705 TheModule.reset();
706 if (OwnsVMContext)
707 delete VMContext;
708}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000709
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000710bool CodeGenAction::hasIRSupport() const { return true; }
711
Daniel Dunbar400a6932010-02-25 04:37:50 +0000712void CodeGenAction::EndSourceFileAction() {
713 // If the consumer creation failed, do nothing.
714 if (!getCompilerInstance().hasASTConsumer())
715 return;
716
Artem Belevich5d40ae32015-10-27 17:56:59 +0000717 // Take back ownership of link modules we passed to consumer.
718 if (!LinkModules.empty())
719 BEConsumer->releaseLinkModules();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000720
Daniel Dunbar400a6932010-02-25 04:37:50 +0000721 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000722 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000723}
724
Rafael Espindolae8337302014-08-19 14:36:35 +0000725std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
726 return std::move(TheModule);
727}
728
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000729llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
730 OwnsVMContext = false;
731 return VMContext;
732}
733
Peter Collingbourne03f89072016-07-15 00:55:40 +0000734static std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000735GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000736 switch (Action) {
737 case Backend_EmitAssembly:
738 return CI.createDefaultOutputFile(false, InFile, "s");
739 case Backend_EmitLL:
740 return CI.createDefaultOutputFile(false, InFile, "ll");
741 case Backend_EmitBC:
742 return CI.createDefaultOutputFile(true, InFile, "bc");
743 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000744 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000745 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000746 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000747 case Backend_EmitObj:
748 return CI.createDefaultOutputFile(true, InFile, "o");
749 }
750
David Blaikie83d382b2011-09-23 05:06:16 +0000751 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000752}
753
David Blaikie6beb6aa2014-08-10 19:56:51 +0000754std::unique_ptr<ASTConsumer>
755CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000756 BackendAction BA = static_cast<BackendAction>(Act);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000757 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000758 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000759 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000760
Artem Belevich5d40ae32015-10-27 17:56:59 +0000761 // Load bitcode modules to link with, if we need to.
762 if (LinkModules.empty())
763 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
764 const std::string &LinkBCFile = I.second;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000765
Artem Belevich5d40ae32015-10-27 17:56:59 +0000766 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
767 if (!BCBuf) {
768 CI.getDiagnostics().Report(diag::err_cannot_open_file)
769 << LinkBCFile << BCBuf.getError().message();
770 LinkModules.clear();
771 return nullptr;
772 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000773
Artem Belevich5d40ae32015-10-27 17:56:59 +0000774 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
775 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
776 if (std::error_code EC = ModuleOrErr.getError()) {
777 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
778 << EC.message();
779 LinkModules.clear();
780 return nullptr;
781 }
782 addLinkModule(ModuleOrErr.get().release(), I.first);
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000783 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000784
Alex Lorenzee024992014-08-04 18:41:51 +0000785 CoverageSourceInfo *CoverageInfo = nullptr;
786 // Add the preprocessor callback only when the coverage mapping is generated.
787 if (CI.getCodeGenOpts().CoverageMapping) {
788 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000789 CI.getPreprocessor().addPPCallbacks(
790 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000791 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000792
David Blaikie037e75b2014-08-10 21:06:17 +0000793 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000794 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
795 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Artem Belevich5d40ae32015-10-27 17:56:59 +0000796 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000797 std::move(OS), *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000798 BEConsumer = Result.get();
799 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000800}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000801
Tim Northover1390b442016-04-06 19:58:07 +0000802static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
803 void *Context,
804 unsigned LocCookie) {
805 SM.print(nullptr, llvm::errs());
806
807 auto Diags = static_cast<DiagnosticsEngine *>(Context);
808 unsigned DiagID;
809 switch (SM.getKind()) {
810 case llvm::SourceMgr::DK_Error:
811 DiagID = diag::err_fe_inline_asm;
812 break;
813 case llvm::SourceMgr::DK_Warning:
814 DiagID = diag::warn_fe_inline_asm;
815 break;
816 case llvm::SourceMgr::DK_Note:
817 DiagID = diag::note_fe_inline_asm;
818 break;
819 }
820
821 Diags->Report(DiagID).AddString("cannot compile inline asm");
822}
823
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000824void CodeGenAction::ExecuteAction() {
825 // If this is an IR file, we have to treat it specially.
826 if (getCurrentFileKind() == IK_LLVM_IR) {
827 BackendAction BA = static_cast<BackendAction>(Act);
828 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000829 std::unique_ptr<raw_pwrite_stream> OS =
830 GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000831 if (BA != Backend_EmitNothing && !OS)
832 return;
833
834 bool Invalid;
835 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000836 FileID FID = SM.getMainFileID();
837 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000838 if (Invalid)
839 return;
840
Teresa Johnsonb1047492016-04-20 02:23:52 +0000841 // For ThinLTO backend invocations, ensure that the context
842 // merges types based on ODR identifiers.
843 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
844 VMContext->enableDebugTypeODRUniquing();
845
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000846 llvm::SMDiagnostic Err;
Rafael Espindola32327732014-08-26 21:49:29 +0000847 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000848 if (!TheModule) {
Alp Toker7b463d52014-06-30 01:33:59 +0000849 // Translate from the diagnostic info to the SourceManager location if
850 // available.
851 // TODO: Unify this with ConvertBackendLocation()
852 SourceLocation Loc;
853 if (Err.getLineNo() > 0) {
854 assert(Err.getColumnNo() >= 0);
855 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
856 Err.getLineNo(), Err.getColumnNo() + 1);
857 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000858
Alp Tokerbc043f22013-12-21 05:20:03 +0000859 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000860 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000861 if (Msg.startswith("error: "))
862 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000863
Alp Tokerbc043f22013-12-21 05:20:03 +0000864 unsigned DiagID =
865 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000866
Alp Tokerbc043f22013-12-21 05:20:03 +0000867 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000868 return;
869 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000870 const TargetOptions &TargetOpts = CI.getTargetOpts();
871 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000872 CI.getDiagnostics().Report(SourceLocation(),
873 diag::warn_fe_override_module)
874 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000875 TheModule->setTargetTriple(TargetOpts.Triple);
876 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000877
Steven Wu27fb5222016-05-11 16:26:03 +0000878 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
879 MainFile->getMemBufferRef());
880
Tim Northover1390b442016-04-06 19:58:07 +0000881 LLVMContext &Ctx = TheModule->getContext();
882 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
883 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +0000884
Alp Tokere83b9062014-01-02 15:08:04 +0000885 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
James Y Knightb214cbc2016-03-04 19:00:41 +0000886 CI.getLangOpts(), CI.getTarget().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000887 TheModule.get(), BA, std::move(OS));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000888 return;
889 }
890
891 // Otherwise follow the normal AST path.
892 this->ASTFrontendAction::ExecuteAction();
893}
894
895//
896
David Blaikie68e081d2011-12-20 02:48:34 +0000897void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000898EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
899 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000900
David Blaikie68e081d2011-12-20 02:48:34 +0000901void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000902EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
903 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000904
David Blaikie68e081d2011-12-20 02:48:34 +0000905void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000906EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
907 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000908
David Blaikie68e081d2011-12-20 02:48:34 +0000909void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000910EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
911 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000912
David Blaikie68e081d2011-12-20 02:48:34 +0000913void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000914EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
915 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000916
David Blaikie68e081d2011-12-20 02:48:34 +0000917void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000918EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
919 : CodeGenAction(Backend_EmitObj, _VMContext) {}