1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/CodeGen/CodeGenAction.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclGroup.h"
14 #include "clang/Basic/FileManager.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/CodeGen/BackendUtil.h"
18 #include "clang/CodeGen/ModuleBuilder.h"
19 #include "clang/Frontend/CompilerInstance.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IRReader/IRReader.h"
27 #include "llvm/Linker.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Support/Timer.h"
32 using namespace clang;
36 class BackendConsumer : public ASTConsumer {
37 virtual void anchor();
38 DiagnosticsEngine &Diags;
40 const CodeGenOptions &CodeGenOpts;
41 const TargetOptions &TargetOpts;
42 const LangOptions &LangOpts;
43 raw_ostream *AsmOutStream;
46 Timer LLVMIRGeneration;
48 OwningPtr<CodeGenerator> Gen;
50 OwningPtr<llvm::Module> TheModule, LinkModule;
53 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
54 const CodeGenOptions &compopts,
55 const TargetOptions &targetopts,
56 const LangOptions &langopts,
58 const std::string &infile,
59 llvm::Module *LinkModule,
64 CodeGenOpts(compopts),
65 TargetOpts(targetopts),
69 LLVMIRGeneration("LLVM IR Generation Time"),
70 Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
71 LinkModule(LinkModule)
73 llvm::TimePassesIsEnabled = TimePasses;
76 llvm::Module *takeModule() { return TheModule.take(); }
77 llvm::Module *takeLinkModule() { return LinkModule.take(); }
79 virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
80 Gen->HandleCXXStaticMemberVarInstantiation(VD);
83 virtual void Initialize(ASTContext &Ctx) {
86 if (llvm::TimePassesIsEnabled)
87 LLVMIRGeneration.startTimer();
91 TheModule.reset(Gen->GetModule());
93 if (llvm::TimePassesIsEnabled)
94 LLVMIRGeneration.stopTimer();
97 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
98 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
99 Context->getSourceManager(),
100 "LLVM IR generation of declaration");
102 if (llvm::TimePassesIsEnabled)
103 LLVMIRGeneration.startTimer();
105 Gen->HandleTopLevelDecl(D);
107 if (llvm::TimePassesIsEnabled)
108 LLVMIRGeneration.stopTimer();
113 virtual void HandleTranslationUnit(ASTContext &C) {
115 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
116 if (llvm::TimePassesIsEnabled)
117 LLVMIRGeneration.startTimer();
119 Gen->HandleTranslationUnit(C);
121 if (llvm::TimePassesIsEnabled)
122 LLVMIRGeneration.stopTimer();
125 // Silently ignore if we weren't initialized for some reason.
129 // Make sure IR generation is happy with the module. This is released by
130 // the module provider.
131 llvm::Module *M = Gen->ReleaseModule();
133 // The module has been released by IR gen on failures, do not double
139 assert(TheModule.get() == M &&
140 "Unexpected module change during IR generation");
142 // Link LinkModule into this module if present, preserving its validity.
144 std::string ErrorMsg;
145 if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
147 Diags.Report(diag::err_fe_cannot_link_module)
148 << LinkModule->getModuleIdentifier() << ErrorMsg;
153 // Install an inline asm handler so that diagnostics get printed through
154 // our diagnostics hooks.
155 LLVMContext &Ctx = TheModule->getContext();
156 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
157 Ctx.getInlineAsmDiagnosticHandler();
158 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
159 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
161 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
162 TheModule.get(), Action, AsmOutStream);
164 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
167 virtual void HandleTagDeclDefinition(TagDecl *D) {
168 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
169 Context->getSourceManager(),
170 "LLVM IR generation of declaration");
171 Gen->HandleTagDeclDefinition(D);
174 virtual void CompleteTentativeDefinition(VarDecl *D) {
175 Gen->CompleteTentativeDefinition(D);
178 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
179 Gen->HandleVTable(RD, DefinitionRequired);
182 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
183 unsigned LocCookie) {
184 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
185 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
188 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
189 SourceLocation LocCookie);
192 void BackendConsumer::anchor() {}
195 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
196 /// buffer to be a valid FullSourceLoc.
197 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
198 SourceManager &CSM) {
199 // Get both the clang and llvm source managers. The location is relative to
200 // a memory buffer that the LLVM Source Manager is handling, we need to add
201 // a copy to the Clang source manager.
202 const llvm::SourceMgr &LSM = *D.getSourceMgr();
204 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
205 // already owns its one and clang::SourceManager wants to own its one.
206 const MemoryBuffer *LBuf =
207 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
209 // Create the copy and transfer ownership to clang::SourceManager.
210 llvm::MemoryBuffer *CBuf =
211 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
212 LBuf->getBufferIdentifier());
213 FileID FID = CSM.createFileIDForMemBuffer(CBuf);
215 // Translate the offset into the file.
216 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
217 SourceLocation NewLoc =
218 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
219 return FullSourceLoc(NewLoc, CSM);
223 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
224 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
225 /// the temporary memory buffer that the inline asm parser has set up.
226 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
227 SourceLocation LocCookie) {
228 // There are a couple of different kinds of errors we could get here. First,
229 // we re-format the SMDiagnostic in terms of a clang diagnostic.
231 // Strip "error: " off the start of the message string.
232 StringRef Message = D.getMessage();
233 if (Message.startswith("error: "))
234 Message = Message.substr(7);
236 // If the SMDiagnostic has an inline asm source location, translate it.
238 if (D.getLoc() != SMLoc())
239 Loc = ConvertBackendLocation(D, Context->getSourceManager());
242 // If this problem has clang-level source location information, report the
243 // issue as being an error in the source with a note showing the instantiated
245 if (LocCookie.isValid()) {
246 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
248 if (D.getLoc().isValid()) {
249 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
250 // Convert the SMDiagnostic ranges into SourceRange and attach them
251 // to the diagnostic.
252 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
253 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
254 unsigned Column = D.getColumnNo();
255 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
256 Loc.getLocWithOffset(Range.second - Column));
262 // Otherwise, report the backend error as occurring in the generated .s file.
263 // If Loc is invalid, we still need to report the error, it just gets no
265 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
270 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
271 : Act(_Act), LinkModule(0),
272 VMContext(_VMContext ? _VMContext : new LLVMContext),
273 OwnsVMContext(!_VMContext) {}
275 CodeGenAction::~CodeGenAction() {
281 bool CodeGenAction::hasIRSupport() const { return true; }
283 void CodeGenAction::EndSourceFileAction() {
284 // If the consumer creation failed, do nothing.
285 if (!getCompilerInstance().hasASTConsumer())
288 // If we were given a link module, release consumer's ownership of it.
290 BEConsumer->takeLinkModule();
292 // Steal the module from the consumer.
293 TheModule.reset(BEConsumer->takeModule());
296 llvm::Module *CodeGenAction::takeModule() {
297 return TheModule.take();
300 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
301 OwnsVMContext = false;
305 static raw_ostream *GetOutputStream(CompilerInstance &CI,
307 BackendAction Action) {
309 case Backend_EmitAssembly:
310 return CI.createDefaultOutputFile(false, InFile, "s");
312 return CI.createDefaultOutputFile(false, InFile, "ll");
314 return CI.createDefaultOutputFile(true, InFile, "bc");
315 case Backend_EmitNothing:
317 case Backend_EmitMCNull:
318 case Backend_EmitObj:
319 return CI.createDefaultOutputFile(true, InFile, "o");
322 llvm_unreachable("Invalid action!");
325 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
327 BackendAction BA = static_cast<BackendAction>(Act);
328 OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
329 if (BA != Backend_EmitNothing && !OS)
332 llvm::Module *LinkModuleToUse = LinkModule;
334 // If we were not given a link module, and the user requested that one be
335 // loaded from bitcode, do so now.
336 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
337 if (!LinkModuleToUse && !LinkBCFile.empty()) {
338 std::string ErrorStr;
340 llvm::MemoryBuffer *BCBuf =
341 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
343 CI.getDiagnostics().Report(diag::err_cannot_open_file)
344 << LinkBCFile << ErrorStr;
348 LinkModuleToUse = getLazyBitcodeModule(BCBuf, *VMContext, &ErrorStr);
349 if (!LinkModuleToUse) {
350 CI.getDiagnostics().Report(diag::err_cannot_open_file)
351 << LinkBCFile << ErrorStr;
357 new BackendConsumer(BA, CI.getDiagnostics(),
358 CI.getCodeGenOpts(), CI.getTargetOpts(),
360 CI.getFrontendOpts().ShowTimers, InFile,
361 LinkModuleToUse, OS.take(), *VMContext);
365 void CodeGenAction::ExecuteAction() {
366 // If this is an IR file, we have to treat it specially.
367 if (getCurrentFileKind() == IK_LLVM_IR) {
368 BackendAction BA = static_cast<BackendAction>(Act);
369 CompilerInstance &CI = getCompilerInstance();
370 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
371 if (BA != Backend_EmitNothing && !OS)
375 SourceManager &SM = CI.getSourceManager();
376 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
381 // FIXME: This is stupid, IRReader shouldn't take ownership.
382 llvm::MemoryBuffer *MainFileCopy =
383 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
386 llvm::SMDiagnostic Err;
387 TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
389 // Translate from the diagnostic info to the SourceManager location.
390 SourceLocation Loc = SM.translateFileLineCol(
391 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
392 Err.getColumnNo() + 1);
394 // Get a custom diagnostic for the error. We strip off a leading
395 // diagnostic code if there is one.
396 StringRef Msg = Err.getMessage();
397 if (Msg.startswith("error: "))
400 // Escape '%', which is interpreted as a format character.
401 SmallString<128> EscapedMessage;
402 for (unsigned i = 0, e = Msg.size(); i != e; ++i) {
404 EscapedMessage += '%';
405 EscapedMessage += Msg[i];
408 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
409 DiagnosticsEngine::Error, EscapedMessage);
411 CI.getDiagnostics().Report(Loc, DiagID);
415 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
416 CI.getTargetOpts(), CI.getLangOpts(),
422 // Otherwise follow the normal AST path.
423 this->ASTFrontendAction::ExecuteAction();
428 void EmitAssemblyAction::anchor() { }
429 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
430 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
432 void EmitBCAction::anchor() { }
433 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
434 : CodeGenAction(Backend_EmitBC, _VMContext) {}
436 void EmitLLVMAction::anchor() { }
437 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
438 : CodeGenAction(Backend_EmitLL, _VMContext) {}
440 void EmitLLVMOnlyAction::anchor() { }
441 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
442 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
444 void EmitCodeGenOnlyAction::anchor() { }
445 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
446 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
448 void EmitObjAction::anchor() { }
449 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
450 : CodeGenAction(Backend_EmitObj, _VMContext) {}