blob: f8ae031f0f3bbc6dad6990de9296b764f07f69b4 [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/ADT/SmallString.h"
25#include "llvm/Bitcode/ReaderWriter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000026#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000027#include "llvm/IR/DiagnosticInfo.h"
28#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000031#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000032#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000033#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000034#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000036#include "llvm/Support/Timer.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000037#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000038using namespace clang;
39using namespace llvm;
40
Nico Weber2992efa2011-01-25 20:34:14 +000041namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000042 class BackendConsumer : public ASTConsumer {
David Blaikie68e081d2011-12-20 02:48:34 +000043 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000044 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000045 BackendAction Action;
Daniel Dunbarde182242009-11-30 08:39:32 +000046 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000047 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000048 const LangOptions &LangOpts;
Rafael Espindola2f16bc12015-04-14 15:15:49 +000049 raw_pwrite_stream *AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000050 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000051
Chris Lattner263d64c2009-02-18 01:37:30 +000052 Timer LLVMIRGeneration;
Mike Stump11289f42009-09-09 15:08:12 +000053
Ahmed Charlesb8984322014-03-07 20:03:18 +000054 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000055
Artem Belevich5d40ae32015-10-27 17:56:59 +000056 std::unique_ptr<llvm::Module> TheModule;
57 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
58 LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000059
Rafael Espindola8ce88a52015-12-14 23:17:07 +000060 // This is here so that the diagnostic printer knows the module a diagnostic
61 // refers to.
62 llvm::Module *CurLinkModule = nullptr;
63
Mike Stump11289f42009-09-09 15:08:12 +000064 public:
Artem Belevich5d40ae32015-10-27 17:56:59 +000065 BackendConsumer(
66 BackendAction Action, DiagnosticsEngine &Diags,
67 const HeaderSearchOptions &HeaderSearchOpts,
68 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
69 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
70 bool TimePasses, const std::string &InFile,
71 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
72 raw_pwrite_stream *OS, LLVMContext &C,
73 CoverageSourceInfo *CoverageInfo = nullptr)
Justin Bognercb082992015-05-22 22:16:55 +000074 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
75 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
Yaron Keren2f5ec2f2014-12-25 12:21:56 +000076 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
Adrian Prantle74f5252015-06-30 02:26:03 +000077 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Artem Belevich5d40ae32015-10-27 17:56:59 +000078 CodeGenOpts, C, CoverageInfo)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000079 llvm::TimePassesIsEnabled = TimePasses;
Artem Belevich5d40ae32015-10-27 17:56:59 +000080 for (auto &I : LinkModules)
81 this->LinkModules.push_back(
82 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
Chris Lattnerdeffa132009-02-18 01:23:44 +000083 }
David Blaikie780dd3b2014-08-29 05:08:19 +000084 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
Artem Belevich5d40ae32015-10-27 17:56:59 +000085 void releaseLinkModules() {
86 for (auto &I : LinkModules)
87 I.second.release();
88 }
Daniel Dunbar400a6932010-02-25 04:37:50 +000089
Craig Topper4f12f102014-03-12 06:41:41 +000090 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +000091 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +000092 }
93
Craig Topper4f12f102014-03-12 06:41:41 +000094 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +000095 assert(!Context && "initialized multiple times");
96
Chris Lattner5cf49fe2009-03-28 02:18:25 +000097 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +000098
Daniel Dunbar8e705052009-11-30 08:39:52 +000099 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000100 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000101
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000102 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000103
Daniel Dunbar400a6932010-02-25 04:37:50 +0000104 TheModule.reset(Gen->GetModule());
Mike Stump11289f42009-09-09 15:08:12 +0000105
Daniel Dunbar8e705052009-11-30 08:39:52 +0000106 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000107 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Craig Topper4f12f102014-03-12 06:41:41 +0000110 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000111 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000112 Context->getSourceManager(),
113 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000114
Daniel Dunbar8e705052009-11-30 08:39:52 +0000115 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000116 LLVMIRGeneration.startTimer();
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000117
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000118 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000119
Daniel Dunbar8e705052009-11-30 08:39:52 +0000120 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000121 LLVMIRGeneration.stopTimer();
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000122
123 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
Hans Wennborga926d842014-05-23 20:37:38 +0000126 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
127 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
128 Context->getSourceManager(),
129 "LLVM IR generation of inline method");
130 if (llvm::TimePassesIsEnabled)
131 LLVMIRGeneration.startTimer();
132
133 Gen->HandleInlineMethodDefinition(D);
134
135 if (llvm::TimePassesIsEnabled)
136 LLVMIRGeneration.stopTimer();
137 }
138
Craig Topper4f12f102014-03-12 06:41:41 +0000139 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000140 {
Chris Lattnere46de752009-03-06 06:46:31 +0000141 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbar8e705052009-11-30 08:39:52 +0000142 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000143 LLVMIRGeneration.startTimer();
Chris Lattner263d64c2009-02-18 01:37:30 +0000144
Chris Lattnercf169832009-03-28 04:11:33 +0000145 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000146
Daniel Dunbar8e705052009-11-30 08:39:52 +0000147 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000148 LLVMIRGeneration.stopTimer();
149 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000150
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000151 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar3e111522010-06-07 23:21:04 +0000152 if (!TheModule)
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000153 return;
Mike Stump11289f42009-09-09 15:08:12 +0000154
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000155 // Make sure IR generation is happy with the module. This is released by
156 // the module provider.
Douglas Gregorde3ef502011-11-30 23:21:26 +0000157 llvm::Module *M = Gen->ReleaseModule();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000158 if (!M) {
159 // The module has been released by IR gen on failures, do not double
160 // free.
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000161 TheModule.release();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000162 return;
163 }
164
165 assert(TheModule.get() == M &&
166 "Unexpected module change during IR generation");
167
168 // Install an inline asm handler so that diagnostics get printed through
169 // our diagnostics hooks.
170 LLVMContext &Ctx = TheModule->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000171 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
172 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000173 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000174 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000175
Quentin Colombet728c5542014-02-06 18:30:43 +0000176 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
177 Ctx.getDiagnosticHandler();
178 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
179 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
180
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000181 // Link LinkModule into this module if present, preserving its validity.
182 for (auto &I : LinkModules) {
183 unsigned LinkFlags = I.first;
184 CurLinkModule = I.second.get();
Rafael Espindola433049f2015-12-16 23:16:37 +0000185 if (Linker::linkModules(*M, std::move(I.second), LinkFlags))
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000186 return;
187 }
188
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000189 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
Eric Christopher964a5f32015-08-05 23:48:05 +0000190 C.getTargetInfo().getDataLayoutString(),
Daniel Dunbar3e111522010-06-07 23:21:04 +0000191 TheModule.get(), Action, AsmOutStream);
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000192
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000193 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000194
195 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000196 }
Mike Stump11289f42009-09-09 15:08:12 +0000197
Craig Topper4f12f102014-03-12 06:41:41 +0000198 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000199 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
200 Context->getSourceManager(),
201 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000202 Gen->HandleTagDeclDefinition(D);
203 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000204
Craig Topper4f12f102014-03-12 06:41:41 +0000205 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000206 Gen->HandleTagDeclRequiredDefinition(D);
207 }
208
Craig Topper4f12f102014-03-12 06:41:41 +0000209 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000210 Gen->CompleteTentativeDefinition(D);
211 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000212
David Majnemer929025d2016-01-26 19:30:26 +0000213 void AssignInheritanceModel(CXXRecordDecl *RD) override {
214 Gen->AssignInheritanceModel(RD);
215 }
216
Nico Weberb6a5d052015-01-15 04:07:35 +0000217 void HandleVTable(CXXRecordDecl *RD) override {
218 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000219 }
220
Peter Collingbournedc134532016-01-16 00:31:22 +0000221 void HandleLinkerOption(llvm::StringRef Opts) override {
222 Gen->HandleLinkerOption(Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000223 }
224
Craig Topper4f12f102014-03-12 06:41:41 +0000225 void HandleDetectMismatch(llvm::StringRef Name,
226 llvm::StringRef Value) override {
Aaron Ballman5d041be2013-06-04 02:07:14 +0000227 Gen->HandleDetectMismatch(Name, Value);
228 }
229
Craig Topper4f12f102014-03-12 06:41:41 +0000230 void HandleDependentLibrary(llvm::StringRef Opts) override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000231 Gen->HandleDependentLibrary(Opts);
232 }
233
Chris Lattner5ec32e72010-04-06 18:38:50 +0000234 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
235 unsigned LocCookie) {
236 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
237 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
238 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000239
Quentin Colombet728c5542014-02-06 18:30:43 +0000240 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
241 void *Context) {
242 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
243 }
244
Chris Lattner5ec32e72010-04-06 18:38:50 +0000245 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
246 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000247
248 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
249 /// \brief Specialized handler for InlineAsm diagnostic.
250 /// \return True if the diagnostic has been successfully reported, false
251 /// otherwise.
252 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
253 /// \brief Specialized handler for StackSize diagnostic.
254 /// \return True if the diagnostic has been successfully reported, false
255 /// otherwise.
256 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000257 /// \brief Specialized handlers for optimization remarks.
258 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000259 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000260 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
261 unsigned DiagID);
Diego Novillod23ec942014-05-29 19:55:06 +0000262 void
Diego Novillo829b1702014-04-16 16:54:24 +0000263 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000264 void OptimizationRemarkHandler(
265 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
266 void OptimizationRemarkHandler(
267 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000268 void OptimizationRemarkHandler(
269 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
Tyler Nowicki034baf62015-08-10 23:05:16 +0000270 void OptimizationRemarkHandler(
271 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000272 void OptimizationFailureHandler(
273 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000274 };
David Blaikie68e081d2011-12-20 02:48:34 +0000275
276 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000277}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000278
Chris Lattner79f67a72010-04-08 00:23:06 +0000279/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
280/// buffer to be a valid FullSourceLoc.
281static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
282 SourceManager &CSM) {
283 // Get both the clang and llvm source managers. The location is relative to
284 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000285 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000286 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000287
Chris Lattner79f67a72010-04-08 00:23:06 +0000288 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
289 // already owns its one and clang::SourceManager wants to own its one.
290 const MemoryBuffer *LBuf =
291 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000292
Chris Lattner79f67a72010-04-08 00:23:06 +0000293 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000294 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000295 std::unique_ptr<llvm::MemoryBuffer> CBuf =
296 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
297 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000298 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000299 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000300
Chris Lattner79f67a72010-04-08 00:23:06 +0000301 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000302 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000303 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000304 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000305 return FullSourceLoc(NewLoc, CSM);
306}
307
Chris Lattner6d672132010-04-06 17:52:14 +0000308
Chris Lattner5ec32e72010-04-06 18:38:50 +0000309/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
310/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000311/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000312void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
313 SourceLocation LocCookie) {
314 // There are a couple of different kinds of errors we could get here. First,
315 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000316
317 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000318 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000319 if (Message.startswith("error: "))
320 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000321
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000322 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000323 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000324 if (D.getLoc() != SMLoc())
325 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000326
Joey Gouly5798b262014-06-05 21:23:42 +0000327 unsigned DiagID;
328 switch (D.getKind()) {
329 case llvm::SourceMgr::DK_Error:
330 DiagID = diag::err_fe_inline_asm;
331 break;
332 case llvm::SourceMgr::DK_Warning:
333 DiagID = diag::warn_fe_inline_asm;
334 break;
335 case llvm::SourceMgr::DK_Note:
336 DiagID = diag::note_fe_inline_asm;
337 break;
338 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000339 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000340 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000341 // code.
342 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000343 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000344
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000345 if (D.getLoc().isValid()) {
346 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
347 // Convert the SMDiagnostic ranges into SourceRange and attach them
348 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000349 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000350 unsigned Column = D.getColumnNo();
351 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
352 Loc.getLocWithOffset(Range.second - Column));
353 }
354 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000355 return;
356 }
357
Joey Gouly5798b262014-06-05 21:23:42 +0000358 // Otherwise, report the backend issue as occurring in the generated .s file.
359 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000360 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000361 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000362}
363
Quentin Colombet728c5542014-02-06 18:30:43 +0000364#define ComputeDiagID(Severity, GroupName, DiagID) \
365 do { \
366 switch (Severity) { \
367 case llvm::DS_Error: \
368 DiagID = diag::err_fe_##GroupName; \
369 break; \
370 case llvm::DS_Warning: \
371 DiagID = diag::warn_fe_##GroupName; \
372 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000373 case llvm::DS_Remark: \
374 llvm_unreachable("'remark' severity not expected"); \
375 break; \
376 case llvm::DS_Note: \
377 DiagID = diag::note_fe_##GroupName; \
378 break; \
379 } \
380 } while (false)
381
382#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
383 do { \
384 switch (Severity) { \
385 case llvm::DS_Error: \
386 DiagID = diag::err_fe_##GroupName; \
387 break; \
388 case llvm::DS_Warning: \
389 DiagID = diag::warn_fe_##GroupName; \
390 break; \
391 case llvm::DS_Remark: \
392 DiagID = diag::remark_fe_##GroupName; \
393 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000394 case llvm::DS_Note: \
395 DiagID = diag::note_fe_##GroupName; \
396 break; \
397 } \
398 } while (false)
399
400bool
401BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
402 unsigned DiagID;
403 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
404 std::string Message = D.getMsgStr().str();
405
406 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000407 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000408 // code.
409 SourceLocation LocCookie =
410 SourceLocation::getFromRawEncoding(D.getLocCookie());
411 if (LocCookie.isValid())
412 Diags.Report(LocCookie, DiagID).AddString(Message);
413 else {
414 // Otherwise, report the backend diagnostic as occurring in the generated
415 // .s file.
416 // If Loc is invalid, we still need to report the diagnostic, it just gets
417 // no location info.
418 FullSourceLoc Loc;
419 Diags.Report(Loc, DiagID).AddString(Message);
420 }
421 // We handled all the possible severities.
422 return true;
423}
424
425bool
426BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
427 if (D.getSeverity() != llvm::DS_Warning)
428 // For now, the only support we have for StackSize diagnostic is warning.
429 // We do not know how to format other severities.
430 return false;
431
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000432 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
433 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
434 diag::warn_fe_frame_larger_than)
435 << D.getStackSize() << Decl::castToDeclContext(ND);
436 return true;
437 }
438
439 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000440}
441
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000442void BackendConsumer::EmitOptimizationMessage(
Tyler Nowickie4707712014-07-16 00:40:42 +0000443 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000444 // We only support warnings and remarks.
445 assert(D.getSeverity() == llvm::DS_Remark ||
446 D.getSeverity() == llvm::DS_Warning);
Diego Novillo829b1702014-04-16 16:54:24 +0000447
Diego Novillod23ec942014-05-29 19:55:06 +0000448 SourceManager &SourceMgr = Context->getSourceManager();
449 FileManager &FileMgr = SourceMgr.getFileManager();
450 StringRef Filename;
451 unsigned Line, Column;
Alp Toker27506272014-06-05 22:11:12 +0000452 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000453
454 if (D.isLocationAvailable()) {
455 D.getLocation(&Filename, &Line, &Column);
456 const FileEntry *FE = FileMgr.getFile(Filename);
457 if (FE && Line > 0) {
458 // If -gcolumn-info was not used, Column will be 0. This upsets the
459 // source manager, so pass 1 if Column is not set.
460 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
461 }
Diego Novillo829b1702014-04-16 16:54:24 +0000462 }
Alp Toker27506272014-06-05 22:11:12 +0000463
464 // If a location isn't available, try to approximate it using the associated
465 // function definition. We use the definition's right brace to differentiate
466 // from diagnostics that genuinely relate to the function itself.
467 FullSourceLoc Loc(DILoc, SourceMgr);
468 if (Loc.isInvalid())
469 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
470 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
471
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000472 Diags.Report(Loc, DiagID)
473 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
474 << D.getMsg().str();
Diego Novillod23ec942014-05-29 19:55:06 +0000475
Diego Novillo86f884e2015-05-08 20:59:56 +0000476 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000477 // If we were not able to translate the file:line:col information
478 // back to a SourceLocation, at least emit a note stating that
479 // we could not translate this location. This can happen in the
480 // case of #line directives.
Alp Toker27506272014-06-05 22:11:12 +0000481 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000482 << Filename << Line << Column;
483}
484
485void BackendConsumer::OptimizationRemarkHandler(
486 const llvm::DiagnosticInfoOptimizationRemark &D) {
487 // Optimization remarks are active only if the -Rpass flag has a regular
488 // expression that matches the name of the pass name in \p D.
489 if (CodeGenOpts.OptimizationRemarkPattern &&
490 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000491 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
Diego Novillod23ec942014-05-29 19:55:06 +0000492}
493
494void BackendConsumer::OptimizationRemarkHandler(
495 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
496 // Missed optimization remarks are active only if the -Rpass-missed
497 // flag has a regular expression that matches the name of the pass
498 // name in \p D.
499 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
500 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000501 EmitOptimizationMessage(D,
502 diag::remark_fe_backend_optimization_remark_missed);
Diego Novillod23ec942014-05-29 19:55:06 +0000503}
504
505void BackendConsumer::OptimizationRemarkHandler(
506 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000507 // Optimization analysis remarks are active if the pass name is set to
508 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
509 // regular expression that matches the name of the pass name in \p D.
510
511 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
512 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
513 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000514 EmitOptimizationMessage(
Diego Novillod23ec942014-05-29 19:55:06 +0000515 D, diag::remark_fe_backend_optimization_remark_analysis);
Diego Novillo829b1702014-04-16 16:54:24 +0000516}
517
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000518void BackendConsumer::OptimizationRemarkHandler(
519 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000520 // Optimization analysis remarks are active if the pass name is set to
521 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
522 // regular expression that matches the name of the pass name in \p D.
523
524 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
525 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
526 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000527 EmitOptimizationMessage(
528 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
529}
530
Tyler Nowicki034baf62015-08-10 23:05:16 +0000531void BackendConsumer::OptimizationRemarkHandler(
532 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000533 // Optimization analysis remarks are active if the pass name is set to
534 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
535 // regular expression that matches the name of the pass name in \p D.
536
537 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
538 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
539 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000540 EmitOptimizationMessage(
541 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
542}
543
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000544void BackendConsumer::OptimizationFailureHandler(
545 const llvm::DiagnosticInfoOptimizationFailure &D) {
546 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
547}
548
Quentin Colombet728c5542014-02-06 18:30:43 +0000549/// \brief This function is invoked when the backend needs
550/// to report something to the user.
551void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
552 unsigned DiagID = diag::err_fe_inline_asm;
553 llvm::DiagnosticSeverity Severity = DI.getSeverity();
554 // Get the diagnostic ID based.
555 switch (DI.getKind()) {
556 case llvm::DK_InlineAsm:
557 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
558 return;
559 ComputeDiagID(Severity, inline_asm, DiagID);
560 break;
561 case llvm::DK_StackSize:
562 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
563 return;
564 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
565 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000566 case DK_Linker:
567 assert(CurLinkModule);
568 // FIXME: stop eating the warnings and notes.
569 if (Severity != DS_Error)
570 return;
571 DiagID = diag::err_fe_cannot_link_module;
572 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000573 case llvm::DK_OptimizationRemark:
574 // Optimization remarks are always handled completely by this
575 // handler. There is no generic way of emitting them.
576 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
577 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000578 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000579 // Optimization remarks are always handled completely by this
580 // handler. There is no generic way of emitting them.
581 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
582 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000583 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000584 // Optimization remarks are always handled completely by this
585 // handler. There is no generic way of emitting them.
586 OptimizationRemarkHandler(
587 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000588 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000589 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
590 // Optimization remarks are always handled completely by this
591 // handler. There is no generic way of emitting them.
592 OptimizationRemarkHandler(
593 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
594 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000595 case llvm::DK_OptimizationRemarkAnalysisAliasing:
596 // Optimization remarks are always handled completely by this
597 // handler. There is no generic way of emitting them.
598 OptimizationRemarkHandler(
599 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
600 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000601 case llvm::DK_OptimizationFailure:
602 // Optimization failures are always handled completely by this
603 // handler.
604 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
605 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000606 default:
607 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000608 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000609 break;
610 }
611 std::string MsgStorage;
612 {
613 raw_string_ostream Stream(MsgStorage);
614 DiagnosticPrinterRawOStream DP(Stream);
615 DI.print(DP);
616 }
617
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000618 if (DiagID == diag::err_fe_cannot_link_module) {
619 Diags.Report(diag::err_fe_cannot_link_module)
620 << CurLinkModule->getModuleIdentifier() << MsgStorage;
621 return;
622 }
623
Quentin Colombet728c5542014-02-06 18:30:43 +0000624 // Report the backend message using the usual diagnostic mechanism.
625 FullSourceLoc Loc;
626 Diags.Report(Loc, DiagID).AddString(MsgStorage);
627}
628#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000629
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000630CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000631 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
632 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000633
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000634CodeGenAction::~CodeGenAction() {
635 TheModule.reset();
636 if (OwnsVMContext)
637 delete VMContext;
638}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000639
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000640bool CodeGenAction::hasIRSupport() const { return true; }
641
Daniel Dunbar400a6932010-02-25 04:37:50 +0000642void CodeGenAction::EndSourceFileAction() {
643 // If the consumer creation failed, do nothing.
644 if (!getCompilerInstance().hasASTConsumer())
645 return;
646
Artem Belevich5d40ae32015-10-27 17:56:59 +0000647 // Take back ownership of link modules we passed to consumer.
648 if (!LinkModules.empty())
649 BEConsumer->releaseLinkModules();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000650
Daniel Dunbar400a6932010-02-25 04:37:50 +0000651 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000652 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000653}
654
Rafael Espindolae8337302014-08-19 14:36:35 +0000655std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
656 return std::move(TheModule);
657}
658
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000659llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
660 OwnsVMContext = false;
661 return VMContext;
662}
663
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000664static raw_pwrite_stream *
665GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000666 switch (Action) {
667 case Backend_EmitAssembly:
668 return CI.createDefaultOutputFile(false, InFile, "s");
669 case Backend_EmitLL:
670 return CI.createDefaultOutputFile(false, InFile, "ll");
671 case Backend_EmitBC:
672 return CI.createDefaultOutputFile(true, InFile, "bc");
673 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000674 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000675 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000676 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000677 case Backend_EmitObj:
678 return CI.createDefaultOutputFile(true, InFile, "o");
679 }
680
David Blaikie83d382b2011-09-23 05:06:16 +0000681 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000682}
683
David Blaikie6beb6aa2014-08-10 19:56:51 +0000684std::unique_ptr<ASTConsumer>
685CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000686 BackendAction BA = static_cast<BackendAction>(Act);
Artem Beleviched0577c2015-05-12 17:44:15 +0000687 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000688 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000689 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000690
Artem Belevich5d40ae32015-10-27 17:56:59 +0000691 // Load bitcode modules to link with, if we need to.
692 if (LinkModules.empty())
693 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
694 const std::string &LinkBCFile = I.second;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000695
Artem Belevich5d40ae32015-10-27 17:56:59 +0000696 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
697 if (!BCBuf) {
698 CI.getDiagnostics().Report(diag::err_cannot_open_file)
699 << LinkBCFile << BCBuf.getError().message();
700 LinkModules.clear();
701 return nullptr;
702 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000703
Artem Belevich5d40ae32015-10-27 17:56:59 +0000704 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
705 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
706 if (std::error_code EC = ModuleOrErr.getError()) {
707 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
708 << EC.message();
709 LinkModules.clear();
710 return nullptr;
711 }
712 addLinkModule(ModuleOrErr.get().release(), I.first);
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000713 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000714
Alex Lorenzee024992014-08-04 18:41:51 +0000715 CoverageSourceInfo *CoverageInfo = nullptr;
716 // Add the preprocessor callback only when the coverage mapping is generated.
717 if (CI.getCodeGenOpts().CoverageMapping) {
718 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000719 CI.getPreprocessor().addPPCallbacks(
720 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000721 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000722
David Blaikie037e75b2014-08-10 21:06:17 +0000723 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000724 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
725 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Artem Belevich5d40ae32015-10-27 17:56:59 +0000726 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
727 OS, *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000728 BEConsumer = Result.get();
729 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000730}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000731
Steven Wu15b385f2015-02-12 02:06:55 +0000732static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
733 void *Context,
734 unsigned LocCookie) {
735 SM.print(nullptr, llvm::errs());
736}
737
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000738void CodeGenAction::ExecuteAction() {
739 // If this is an IR file, we have to treat it specially.
740 if (getCurrentFileKind() == IK_LLVM_IR) {
741 BackendAction BA = static_cast<BackendAction>(Act);
742 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000743 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000744 if (BA != Backend_EmitNothing && !OS)
745 return;
746
747 bool Invalid;
748 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000749 FileID FID = SM.getMainFileID();
750 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000751 if (Invalid)
752 return;
753
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000754 llvm::SMDiagnostic Err;
Rafael Espindola32327732014-08-26 21:49:29 +0000755 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000756 if (!TheModule) {
Alp Toker7b463d52014-06-30 01:33:59 +0000757 // Translate from the diagnostic info to the SourceManager location if
758 // available.
759 // TODO: Unify this with ConvertBackendLocation()
760 SourceLocation Loc;
761 if (Err.getLineNo() > 0) {
762 assert(Err.getColumnNo() >= 0);
763 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
764 Err.getLineNo(), Err.getColumnNo() + 1);
765 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000766
Alp Tokerbc043f22013-12-21 05:20:03 +0000767 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000768 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000769 if (Msg.startswith("error: "))
770 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000771
Alp Tokerbc043f22013-12-21 05:20:03 +0000772 unsigned DiagID =
773 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000774
Alp Tokerbc043f22013-12-21 05:20:03 +0000775 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000776 return;
777 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000778 const TargetOptions &TargetOpts = CI.getTargetOpts();
779 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000780 CI.getDiagnostics().Report(SourceLocation(),
781 diag::warn_fe_override_module)
782 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000783 TheModule->setTargetTriple(TargetOpts.Triple);
784 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000785
Steven Wu15b385f2015-02-12 02:06:55 +0000786 LLVMContext &Ctx = TheModule->getContext();
787 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
Alp Tokere83b9062014-01-02 15:08:04 +0000788 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
Eric Christopher964a5f32015-08-05 23:48:05 +0000789 CI.getLangOpts(), CI.getTarget().getDataLayoutString(),
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000790 TheModule.get(), BA, OS);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000791 return;
792 }
793
794 // Otherwise follow the normal AST path.
795 this->ASTFrontendAction::ExecuteAction();
796}
797
798//
799
David Blaikie68e081d2011-12-20 02:48:34 +0000800void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000801EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
802 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000803
David Blaikie68e081d2011-12-20 02:48:34 +0000804void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000805EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
806 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000807
David Blaikie68e081d2011-12-20 02:48:34 +0000808void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000809EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
810 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000811
David Blaikie68e081d2011-12-20 02:48:34 +0000812void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000813EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
814 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000815
David Blaikie68e081d2011-12-20 02:48:34 +0000816void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000817EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
818 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000819
David Blaikie68e081d2011-12-20 02:48:34 +0000820void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000821EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
822 : CodeGenAction(Backend_EmitObj, _VMContext) {}