blob: a197faece1f543eae8aa2614e59fb2c1e65d639d [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
Daniel Dunbarc1b17292010-06-15 17:48:49 +000010#include "clang/CodeGen/CodeGenAction.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"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000013#include "clang/AST/DeclGroup.h"
Hans Wennborga926d842014-05-23 20:37:38 +000014#include "clang/AST/DeclCXX.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"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000019#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000020#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000021#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/ADT/SmallString.h"
23#include "llvm/Bitcode/ReaderWriter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000024#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000025#include "llvm/IR/DiagnosticInfo.h"
26#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000029#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000030#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000031#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000032#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000034#include "llvm/Support/Timer.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000035#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000036using namespace clang;
37using namespace llvm;
38
Nico Weber2992efa2011-01-25 20:34:14 +000039namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000040 class BackendConsumer : public ASTConsumer {
David Blaikie68e081d2011-12-20 02:48:34 +000041 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000042 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000043 BackendAction Action;
Daniel Dunbarde182242009-11-30 08:39:32 +000044 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000045 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000046 const LangOptions &LangOpts;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000047 raw_ostream *AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000048 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000049
Chris Lattner263d64c2009-02-18 01:37:30 +000050 Timer LLVMIRGeneration;
Mike Stump11289f42009-09-09 15:08:12 +000051
Ahmed Charlesb8984322014-03-07 20:03:18 +000052 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000053
Ahmed Charlesb8984322014-03-07 20:03:18 +000054 std::unique_ptr<llvm::Module> TheModule, LinkModule;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000055
Mike Stump11289f42009-09-09 15:08:12 +000056 public:
David Blaikie9c902b52011-09-25 23:23:43 +000057 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
Daniel Dunbar6d5824f2010-06-07 23:19:17 +000058 const CodeGenOptions &compopts,
Dan Gohmanfec0ff82011-07-05 22:02:36 +000059 const TargetOptions &targetopts,
Rafael Espindola666a2ab2013-12-18 16:38:48 +000060 const LangOptions &langopts, bool TimePasses,
61 const std::string &infile, llvm::Module *LinkModule,
62 raw_ostream *OS, LLVMContext &C)
63 : Diags(_Diags), Action(action), CodeGenOpts(compopts),
64 TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
65 Context(), LLVMIRGeneration("LLVM IR Generation Time"),
66 Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
67 LinkModule(LinkModule) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000068 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattnerdeffa132009-02-18 01:23:44 +000069 }
Daniel Dunbarc13935e2008-10-21 23:49:24 +000070
Ahmed Charles9a16beb2014-03-07 19:33:25 +000071 llvm::Module *takeModule() { return TheModule.release(); }
72 llvm::Module *takeLinkModule() { return LinkModule.release(); }
Daniel Dunbar400a6932010-02-25 04:37:50 +000073
Craig Topper4f12f102014-03-12 06:41:41 +000074 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +000075 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +000076 }
77
Craig Topper4f12f102014-03-12 06:41:41 +000078 void Initialize(ASTContext &Ctx) override {
Chris Lattner5cf49fe2009-03-28 02:18:25 +000079 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +000080
Daniel Dunbar8e705052009-11-30 08:39:52 +000081 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000082 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +000083
Chris Lattner5cf49fe2009-03-28 02:18:25 +000084 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +000085
Daniel Dunbar400a6932010-02-25 04:37:50 +000086 TheModule.reset(Gen->GetModule());
Mike Stump11289f42009-09-09 15:08:12 +000087
Daniel Dunbar8e705052009-11-30 08:39:52 +000088 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000089 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +000090 }
Mike Stump11289f42009-09-09 15:08:12 +000091
Craig Topper4f12f102014-03-12 06:41:41 +000092 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000093 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +000094 Context->getSourceManager(),
95 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +000096
Daniel Dunbar8e705052009-11-30 08:39:52 +000097 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000098 LLVMIRGeneration.startTimer();
Chris Lattner5bbb3c82009-03-29 16:50:03 +000099
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000100 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000101
Daniel Dunbar8e705052009-11-30 08:39:52 +0000102 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000103 LLVMIRGeneration.stopTimer();
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000104
105 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Hans Wennborga926d842014-05-23 20:37:38 +0000108 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
109 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
110 Context->getSourceManager(),
111 "LLVM IR generation of inline method");
112 if (llvm::TimePassesIsEnabled)
113 LLVMIRGeneration.startTimer();
114
115 Gen->HandleInlineMethodDefinition(D);
116
117 if (llvm::TimePassesIsEnabled)
118 LLVMIRGeneration.stopTimer();
119 }
120
Craig Topper4f12f102014-03-12 06:41:41 +0000121 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000122 {
Chris Lattnere46de752009-03-06 06:46:31 +0000123 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbar8e705052009-11-30 08:39:52 +0000124 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000125 LLVMIRGeneration.startTimer();
Chris Lattner263d64c2009-02-18 01:37:30 +0000126
Chris Lattnercf169832009-03-28 04:11:33 +0000127 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000128
Daniel Dunbar8e705052009-11-30 08:39:52 +0000129 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000130 LLVMIRGeneration.stopTimer();
131 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000132
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000133 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar3e111522010-06-07 23:21:04 +0000134 if (!TheModule)
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000135 return;
Mike Stump11289f42009-09-09 15:08:12 +0000136
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000137 // Make sure IR generation is happy with the module. This is released by
138 // the module provider.
Douglas Gregorde3ef502011-11-30 23:21:26 +0000139 llvm::Module *M = Gen->ReleaseModule();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000140 if (!M) {
141 // The module has been released by IR gen on failures, do not double
142 // free.
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000143 TheModule.release();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000144 return;
145 }
146
147 assert(TheModule.get() == M &&
148 "Unexpected module change during IR generation");
149
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000150 // Link LinkModule into this module if present, preserving its validity.
151 if (LinkModule) {
152 std::string ErrorMsg;
153 if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
154 &ErrorMsg)) {
155 Diags.Report(diag::err_fe_cannot_link_module)
156 << LinkModule->getModuleIdentifier() << ErrorMsg;
157 return;
158 }
159 }
160
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000161 // Install an inline asm handler so that diagnostics get printed through
162 // our diagnostics hooks.
163 LLVMContext &Ctx = TheModule->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000164 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
165 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000166 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000167 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000168
Quentin Colombet728c5542014-02-06 18:30:43 +0000169 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
170 Ctx.getDiagnosticHandler();
171 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
172 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
173
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000174 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
Alp Tokere83b9062014-01-02 15:08:04 +0000175 C.getTargetInfo().getTargetDescription(),
Daniel Dunbar3e111522010-06-07 23:21:04 +0000176 TheModule.get(), Action, AsmOutStream);
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000177
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000178 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000179
180 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000181 }
Mike Stump11289f42009-09-09 15:08:12 +0000182
Craig Topper4f12f102014-03-12 06:41:41 +0000183 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000184 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
185 Context->getSourceManager(),
186 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000187 Gen->HandleTagDeclDefinition(D);
188 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000189
Craig Topper4f12f102014-03-12 06:41:41 +0000190 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000191 Gen->HandleTagDeclRequiredDefinition(D);
192 }
193
Craig Topper4f12f102014-03-12 06:41:41 +0000194 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000195 Gen->CompleteTentativeDefinition(D);
196 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000197
Craig Topper4f12f102014-03-12 06:41:41 +0000198 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
Douglas Gregor88d292c2010-05-13 16:44:06 +0000199 Gen->HandleVTable(RD, DefinitionRequired);
200 }
201
Craig Topper4f12f102014-03-12 06:41:41 +0000202 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000203 Gen->HandleLinkerOptionPragma(Opts);
204 }
205
Craig Topper4f12f102014-03-12 06:41:41 +0000206 void HandleDetectMismatch(llvm::StringRef Name,
207 llvm::StringRef Value) override {
Aaron Ballman5d041be2013-06-04 02:07:14 +0000208 Gen->HandleDetectMismatch(Name, Value);
209 }
210
Craig Topper4f12f102014-03-12 06:41:41 +0000211 void HandleDependentLibrary(llvm::StringRef Opts) override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000212 Gen->HandleDependentLibrary(Opts);
213 }
214
Chris Lattner5ec32e72010-04-06 18:38:50 +0000215 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
216 unsigned LocCookie) {
217 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
218 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
219 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000220
Quentin Colombet728c5542014-02-06 18:30:43 +0000221 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
222 void *Context) {
223 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
224 }
225
Chris Lattner5ec32e72010-04-06 18:38:50 +0000226 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
227 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000228
229 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
230 /// \brief Specialized handler for InlineAsm diagnostic.
231 /// \return True if the diagnostic has been successfully reported, false
232 /// otherwise.
233 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
234 /// \brief Specialized handler for StackSize diagnostic.
235 /// \return True if the diagnostic has been successfully reported, false
236 /// otherwise.
237 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000238 /// \brief Specialized handlers for optimization remarks.
239 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000240 /// them.
241 void
Diego Novillod23ec942014-05-29 19:55:06 +0000242 EmitOptimizationRemark(const llvm::DiagnosticInfoOptimizationRemarkBase &D,
243 unsigned DiagID);
244 void
Diego Novillo829b1702014-04-16 16:54:24 +0000245 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000246 void OptimizationRemarkHandler(
247 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
248 void OptimizationRemarkHandler(
249 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
Mike Stump11289f42009-09-09 15:08:12 +0000250 };
David Blaikie68e081d2011-12-20 02:48:34 +0000251
252 void BackendConsumer::anchor() {}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000253}
254
Chris Lattner79f67a72010-04-08 00:23:06 +0000255/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
256/// buffer to be a valid FullSourceLoc.
257static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
258 SourceManager &CSM) {
259 // Get both the clang and llvm source managers. The location is relative to
260 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000261 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000262 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000263
Chris Lattner79f67a72010-04-08 00:23:06 +0000264 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
265 // already owns its one and clang::SourceManager wants to own its one.
266 const MemoryBuffer *LBuf =
267 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000268
Chris Lattner79f67a72010-04-08 00:23:06 +0000269 // Create the copy and transfer ownership to clang::SourceManager.
270 llvm::MemoryBuffer *CBuf =
271 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
272 LBuf->getBufferIdentifier());
Alp Toker6ac2cd02014-05-16 17:23:01 +0000273 FileID FID = CSM.createFileID(CBuf);
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000274
Chris Lattner79f67a72010-04-08 00:23:06 +0000275 // Translate the offset into the file.
276 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000277 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000278 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000279 return FullSourceLoc(NewLoc, CSM);
280}
281
Chris Lattner6d672132010-04-06 17:52:14 +0000282
Chris Lattner5ec32e72010-04-06 18:38:50 +0000283/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
284/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000285/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000286void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
287 SourceLocation LocCookie) {
288 // There are a couple of different kinds of errors we could get here. First,
289 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000290
291 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000292 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000293 if (Message.startswith("error: "))
294 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000295
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000296 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000297 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000298 if (D.getLoc() != SMLoc())
299 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Chris Lattnerf4a4bec2012-01-31 06:13:55 +0000300
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000301
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000302 // If this problem has clang-level source location information, report the
303 // issue as being an error in the source with a note showing the instantiated
304 // code.
305 if (LocCookie.isValid()) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000306 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000307
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000308 if (D.getLoc().isValid()) {
309 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
310 // Convert the SMDiagnostic ranges into SourceRange and attach them
311 // to the diagnostic.
312 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
313 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
314 unsigned Column = D.getColumnNo();
315 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
316 Loc.getLocWithOffset(Range.second - Column));
317 }
318 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000319 return;
320 }
321
Chris Lattner57540c52011-04-15 05:22:18 +0000322 // Otherwise, report the backend error as occurring in the generated .s file.
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000323 // If Loc is invalid, we still need to report the error, it just gets no
324 // location info.
325 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000326}
327
Quentin Colombet728c5542014-02-06 18:30:43 +0000328#define ComputeDiagID(Severity, GroupName, DiagID) \
329 do { \
330 switch (Severity) { \
331 case llvm::DS_Error: \
332 DiagID = diag::err_fe_##GroupName; \
333 break; \
334 case llvm::DS_Warning: \
335 DiagID = diag::warn_fe_##GroupName; \
336 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000337 case llvm::DS_Remark: \
338 llvm_unreachable("'remark' severity not expected"); \
339 break; \
340 case llvm::DS_Note: \
341 DiagID = diag::note_fe_##GroupName; \
342 break; \
343 } \
344 } while (false)
345
346#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
347 do { \
348 switch (Severity) { \
349 case llvm::DS_Error: \
350 DiagID = diag::err_fe_##GroupName; \
351 break; \
352 case llvm::DS_Warning: \
353 DiagID = diag::warn_fe_##GroupName; \
354 break; \
355 case llvm::DS_Remark: \
356 DiagID = diag::remark_fe_##GroupName; \
357 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000358 case llvm::DS_Note: \
359 DiagID = diag::note_fe_##GroupName; \
360 break; \
361 } \
362 } while (false)
363
364bool
365BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
366 unsigned DiagID;
367 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
368 std::string Message = D.getMsgStr().str();
369
370 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000371 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000372 // code.
373 SourceLocation LocCookie =
374 SourceLocation::getFromRawEncoding(D.getLocCookie());
375 if (LocCookie.isValid())
376 Diags.Report(LocCookie, DiagID).AddString(Message);
377 else {
378 // Otherwise, report the backend diagnostic as occurring in the generated
379 // .s file.
380 // If Loc is invalid, we still need to report the diagnostic, it just gets
381 // no location info.
382 FullSourceLoc Loc;
383 Diags.Report(Loc, DiagID).AddString(Message);
384 }
385 // We handled all the possible severities.
386 return true;
387}
388
389bool
390BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
391 if (D.getSeverity() != llvm::DS_Warning)
392 // For now, the only support we have for StackSize diagnostic is warning.
393 // We do not know how to format other severities.
394 return false;
395
396 // FIXME: We should demangle the function name.
397 // FIXME: Is there a way to get a location for that function?
398 FullSourceLoc Loc;
399 Diags.Report(Loc, diag::warn_fe_backend_frame_larger_than)
400 << D.getStackSize() << D.getFunction().getName();
401 return true;
402}
403
Diego Novillod23ec942014-05-29 19:55:06 +0000404void BackendConsumer::EmitOptimizationRemark(
405 const llvm::DiagnosticInfoOptimizationRemarkBase &D, unsigned DiagID) {
Diego Novillo829b1702014-04-16 16:54:24 +0000406 // We only support remarks.
Eric Christopher25c4e672014-05-02 17:52:19 +0000407 assert(D.getSeverity() == llvm::DS_Remark);
Diego Novillo829b1702014-04-16 16:54:24 +0000408
Diego Novillod23ec942014-05-29 19:55:06 +0000409 SourceManager &SourceMgr = Context->getSourceManager();
410 FileManager &FileMgr = SourceMgr.getFileManager();
411 StringRef Filename;
412 unsigned Line, Column;
413 D.getLocation(&Filename, &Line, &Column);
414 SourceLocation Loc;
415 const FileEntry *FE = FileMgr.getFile(Filename);
416 if (FE && Line > 0) {
417 // If -gcolumn-info was not used, Column will be 0. This upsets the
418 // source manager, so if Column is not set, set it to 1.
419 if (Column == 0)
420 Column = 1;
421 Loc = SourceMgr.translateFileLineCol(FE, Line, Column);
Diego Novillo829b1702014-04-16 16:54:24 +0000422 }
Diego Novillod23ec942014-05-29 19:55:06 +0000423 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName())
424 << D.getMsg().str();
425
426 if (Line == 0)
427 // If we could not extract a source location for the diagnostic,
428 // inform the user how they can get source locations back.
429 //
430 // FIXME: We should really be generating !srcloc annotations when
431 // -Rpass is used. !srcloc annotations need to be emitted in
432 // approximately the same spots as !dbg nodes.
433 Diags.Report(diag::note_fe_backend_optimization_remark_missing_loc);
434 else if (Loc.isInvalid())
435 // If we were not able to translate the file:line:col information
436 // back to a SourceLocation, at least emit a note stating that
437 // we could not translate this location. This can happen in the
438 // case of #line directives.
439 Diags.Report(diag::note_fe_backend_optimization_remark_invalid_loc)
440 << Filename << Line << Column;
441}
442
443void BackendConsumer::OptimizationRemarkHandler(
444 const llvm::DiagnosticInfoOptimizationRemark &D) {
445 // Optimization remarks are active only if the -Rpass flag has a regular
446 // expression that matches the name of the pass name in \p D.
447 if (CodeGenOpts.OptimizationRemarkPattern &&
448 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
449 EmitOptimizationRemark(D, diag::remark_fe_backend_optimization_remark);
450}
451
452void BackendConsumer::OptimizationRemarkHandler(
453 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
454 // Missed optimization remarks are active only if the -Rpass-missed
455 // flag has a regular expression that matches the name of the pass
456 // name in \p D.
457 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
458 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
459 EmitOptimizationRemark(D,
460 diag::remark_fe_backend_optimization_remark_missed);
461}
462
463void BackendConsumer::OptimizationRemarkHandler(
464 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
465 // Optimization analysis remarks are active only if the -Rpass-analysis
466 // flag has a regular expression that matches the name of the pass
467 // name in \p D.
468 if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
469 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
470 EmitOptimizationRemark(
471 D, diag::remark_fe_backend_optimization_remark_analysis);
Diego Novillo829b1702014-04-16 16:54:24 +0000472}
473
Quentin Colombet728c5542014-02-06 18:30:43 +0000474/// \brief This function is invoked when the backend needs
475/// to report something to the user.
476void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
477 unsigned DiagID = diag::err_fe_inline_asm;
478 llvm::DiagnosticSeverity Severity = DI.getSeverity();
479 // Get the diagnostic ID based.
480 switch (DI.getKind()) {
481 case llvm::DK_InlineAsm:
482 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
483 return;
484 ComputeDiagID(Severity, inline_asm, DiagID);
485 break;
486 case llvm::DK_StackSize:
487 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
488 return;
489 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
490 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000491 case llvm::DK_OptimizationRemark:
492 // Optimization remarks are always handled completely by this
493 // handler. There is no generic way of emitting them.
494 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
495 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000496 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000497 // Optimization remarks are always handled completely by this
498 // handler. There is no generic way of emitting them.
499 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
500 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000501 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000502 // Optimization remarks are always handled completely by this
503 // handler. There is no generic way of emitting them.
504 OptimizationRemarkHandler(
505 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000506 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000507 default:
508 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000509 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000510 break;
511 }
512 std::string MsgStorage;
513 {
514 raw_string_ostream Stream(MsgStorage);
515 DiagnosticPrinterRawOStream DP(Stream);
516 DI.print(DP);
517 }
518
519 // Report the backend message using the usual diagnostic mechanism.
520 FullSourceLoc Loc;
521 Diags.Report(Loc, DiagID).AddString(MsgStorage);
522}
523#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000524
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000525CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Craig Topper8a13c412014-05-21 05:09:00 +0000526 : Act(_Act), LinkModule(nullptr),
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000527 VMContext(_VMContext ? _VMContext : new LLVMContext),
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000528 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000529
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000530CodeGenAction::~CodeGenAction() {
531 TheModule.reset();
532 if (OwnsVMContext)
533 delete VMContext;
534}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000535
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000536bool CodeGenAction::hasIRSupport() const { return true; }
537
Daniel Dunbar400a6932010-02-25 04:37:50 +0000538void CodeGenAction::EndSourceFileAction() {
539 // If the consumer creation failed, do nothing.
540 if (!getCompilerInstance().hasASTConsumer())
541 return;
542
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000543 // If we were given a link module, release consumer's ownership of it.
544 if (LinkModule)
545 BEConsumer->takeLinkModule();
546
Daniel Dunbar400a6932010-02-25 04:37:50 +0000547 // Steal the module from the consumer.
Nico Weber2992efa2011-01-25 20:34:14 +0000548 TheModule.reset(BEConsumer->takeModule());
Daniel Dunbar400a6932010-02-25 04:37:50 +0000549}
550
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000551llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
Daniel Dunbar400a6932010-02-25 04:37:50 +0000552
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000553llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
554 OwnsVMContext = false;
555 return VMContext;
556}
557
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000558static raw_ostream *GetOutputStream(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000559 StringRef InFile,
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000560 BackendAction Action) {
561 switch (Action) {
562 case Backend_EmitAssembly:
563 return CI.createDefaultOutputFile(false, InFile, "s");
564 case Backend_EmitLL:
565 return CI.createDefaultOutputFile(false, InFile, "ll");
566 case Backend_EmitBC:
567 return CI.createDefaultOutputFile(true, InFile, "bc");
568 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000569 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000570 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000571 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000572 case Backend_EmitObj:
573 return CI.createDefaultOutputFile(true, InFile, "o");
574 }
575
David Blaikie83d382b2011-09-23 05:06:16 +0000576 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000577}
578
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000579ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000580 StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000581 BackendAction BA = static_cast<BackendAction>(Act);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000582 std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000583 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000584 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000585
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000586 llvm::Module *LinkModuleToUse = LinkModule;
587
588 // If we were not given a link module, and the user requested that one be
589 // loaded from bitcode, do so now.
590 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
591 if (!LinkModuleToUse && !LinkBCFile.empty()) {
592 std::string ErrorStr;
593
594 llvm::MemoryBuffer *BCBuf =
595 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
596 if (!BCBuf) {
597 CI.getDiagnostics().Report(diag::err_cannot_open_file)
598 << LinkBCFile << ErrorStr;
Craig Topper8a13c412014-05-21 05:09:00 +0000599 return nullptr;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000600 }
601
Rafael Espindola6b6004a2014-01-13 18:31:09 +0000602 ErrorOr<llvm::Module *> ModuleOrErr =
603 getLazyBitcodeModule(BCBuf, *VMContext);
604 if (error_code EC = ModuleOrErr.getError()) {
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000605 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Rafael Espindola6b6004a2014-01-13 18:31:09 +0000606 << LinkBCFile << EC.message();
Craig Topper8a13c412014-05-21 05:09:00 +0000607 return nullptr;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000608 }
Rafael Espindola6b6004a2014-01-13 18:31:09 +0000609 LinkModuleToUse = ModuleOrErr.get();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000610 }
611
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000612 BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
613 CI.getTargetOpts(), CI.getLangOpts(),
Warren Hunt583db192014-05-28 19:17:45 +0000614 CI.getFrontendOpts().ShowTimers, InFile,
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000615 LinkModuleToUse, OS.release(), *VMContext);
Nico Weber2992efa2011-01-25 20:34:14 +0000616 return BEConsumer;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000617}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000618
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000619void CodeGenAction::ExecuteAction() {
620 // If this is an IR file, we have to treat it specially.
621 if (getCurrentFileKind() == IK_LLVM_IR) {
622 BackendAction BA = static_cast<BackendAction>(Act);
623 CompilerInstance &CI = getCompilerInstance();
624 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
625 if (BA != Backend_EmitNothing && !OS)
626 return;
627
628 bool Invalid;
629 SourceManager &SM = CI.getSourceManager();
630 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
631 &Invalid);
632 if (Invalid)
633 return;
634
635 // FIXME: This is stupid, IRReader shouldn't take ownership.
636 llvm::MemoryBuffer *MainFileCopy =
637 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000638 getCurrentFile());
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000639
640 llvm::SMDiagnostic Err;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000641 TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000642 if (!TheModule) {
643 // Translate from the diagnostic info to the SourceManager location.
Argyrios Kyrtzidis27bf76d2011-09-19 20:40:38 +0000644 SourceLocation Loc = SM.translateFileLineCol(
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000645 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
646 Err.getColumnNo() + 1);
647
Alp Tokerbc043f22013-12-21 05:20:03 +0000648 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000649 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000650 if (Msg.startswith("error: "))
651 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000652
Alp Tokerbc043f22013-12-21 05:20:03 +0000653 unsigned DiagID =
654 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000655
Alp Tokerbc043f22013-12-21 05:20:03 +0000656 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000657 return;
658 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000659 const TargetOptions &TargetOpts = CI.getTargetOpts();
660 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
661 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
662 DiagnosticsEngine::Warning,
663 "overriding the module target triple with %0");
664
665 CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
666 TheModule->setTargetTriple(TargetOpts.Triple);
667 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000668
Alp Tokere83b9062014-01-02 15:08:04 +0000669 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
670 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
671 TheModule.get(), BA, OS);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000672 return;
673 }
674
675 // Otherwise follow the normal AST path.
676 this->ASTFrontendAction::ExecuteAction();
677}
678
679//
680
David Blaikie68e081d2011-12-20 02:48:34 +0000681void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000682EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
683 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000684
David Blaikie68e081d2011-12-20 02:48:34 +0000685void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000686EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
687 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000688
David Blaikie68e081d2011-12-20 02:48:34 +0000689void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000690EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
691 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000692
David Blaikie68e081d2011-12-20 02:48:34 +0000693void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000694EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
695 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000696
David Blaikie68e081d2011-12-20 02:48:34 +0000697void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000698EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
699 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000700
David Blaikie68e081d2011-12-20 02:48:34 +0000701void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000702EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
703 : CodeGenAction(Backend_EmitObj, _VMContext) {}