CodeGenAction.cpp revision 263508
1//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
2//
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
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"
32using namespace clang;
33using namespace llvm;
34
35namespace clang {
36  class BackendConsumer : public ASTConsumer {
37    virtual void anchor();
38    DiagnosticsEngine &Diags;
39    BackendAction Action;
40    const CodeGenOptions &CodeGenOpts;
41    const TargetOptions &TargetOpts;
42    const LangOptions &LangOpts;
43    raw_ostream *AsmOutStream;
44    ASTContext *Context;
45
46    Timer LLVMIRGeneration;
47
48    OwningPtr<CodeGenerator> Gen;
49
50    OwningPtr<llvm::Module> TheModule, LinkModule;
51
52  public:
53    BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
54                    const CodeGenOptions &compopts,
55                    const TargetOptions &targetopts,
56                    const LangOptions &langopts,
57                    bool TimePasses,
58                    const std::string &infile,
59                    llvm::Module *LinkModule,
60                    raw_ostream *OS,
61                    LLVMContext &C) :
62      Diags(_Diags),
63      Action(action),
64      CodeGenOpts(compopts),
65      TargetOpts(targetopts),
66      LangOpts(langopts),
67      AsmOutStream(OS),
68      Context(),
69      LLVMIRGeneration("LLVM IR Generation Time"),
70      Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
71      LinkModule(LinkModule)
72    {
73      llvm::TimePassesIsEnabled = TimePasses;
74    }
75
76    llvm::Module *takeModule() { return TheModule.take(); }
77    llvm::Module *takeLinkModule() { return LinkModule.take(); }
78
79    virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
80      Gen->HandleCXXStaticMemberVarInstantiation(VD);
81    }
82
83    virtual void Initialize(ASTContext &Ctx) {
84      Context = &Ctx;
85
86      if (llvm::TimePassesIsEnabled)
87        LLVMIRGeneration.startTimer();
88
89      Gen->Initialize(Ctx);
90
91      TheModule.reset(Gen->GetModule());
92
93      if (llvm::TimePassesIsEnabled)
94        LLVMIRGeneration.stopTimer();
95    }
96
97    virtual bool HandleTopLevelDecl(DeclGroupRef D) {
98      PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
99                                     Context->getSourceManager(),
100                                     "LLVM IR generation of declaration");
101
102      if (llvm::TimePassesIsEnabled)
103        LLVMIRGeneration.startTimer();
104
105      Gen->HandleTopLevelDecl(D);
106
107      if (llvm::TimePassesIsEnabled)
108        LLVMIRGeneration.stopTimer();
109
110      return true;
111    }
112
113    virtual void HandleTranslationUnit(ASTContext &C) {
114      {
115        PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
116        if (llvm::TimePassesIsEnabled)
117          LLVMIRGeneration.startTimer();
118
119        Gen->HandleTranslationUnit(C);
120
121        if (llvm::TimePassesIsEnabled)
122          LLVMIRGeneration.stopTimer();
123      }
124
125      // Silently ignore if we weren't initialized for some reason.
126      if (!TheModule)
127        return;
128
129      // Make sure IR generation is happy with the module. This is released by
130      // the module provider.
131      llvm::Module *M = Gen->ReleaseModule();
132      if (!M) {
133        // The module has been released by IR gen on failures, do not double
134        // free.
135        TheModule.take();
136        return;
137      }
138
139      assert(TheModule.get() == M &&
140             "Unexpected module change during IR generation");
141
142      // Link LinkModule into this module if present, preserving its validity.
143      if (LinkModule) {
144        std::string ErrorMsg;
145        if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
146                                &ErrorMsg)) {
147          Diags.Report(diag::err_fe_cannot_link_module)
148            << LinkModule->getModuleIdentifier() << ErrorMsg;
149          return;
150        }
151      }
152
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);
160
161      EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
162                        TheModule.get(), Action, AsmOutStream);
163
164      Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
165    }
166
167    virtual void HandleTagDeclDefinition(TagDecl *D) {
168      PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
169                                     Context->getSourceManager(),
170                                     "LLVM IR generation of declaration");
171      Gen->HandleTagDeclDefinition(D);
172    }
173
174    virtual void HandleTagDeclRequiredDefinition(const TagDecl *D) {
175      Gen->HandleTagDeclRequiredDefinition(D);
176    }
177
178    virtual void CompleteTentativeDefinition(VarDecl *D) {
179      Gen->CompleteTentativeDefinition(D);
180    }
181
182    virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
183      Gen->HandleVTable(RD, DefinitionRequired);
184    }
185
186    virtual void HandleLinkerOptionPragma(llvm::StringRef Opts) {
187      Gen->HandleLinkerOptionPragma(Opts);
188    }
189
190    virtual void HandleDetectMismatch(llvm::StringRef Name,
191                                      llvm::StringRef Value) {
192      Gen->HandleDetectMismatch(Name, Value);
193    }
194
195    virtual void HandleDependentLibrary(llvm::StringRef Opts) {
196      Gen->HandleDependentLibrary(Opts);
197    }
198
199    static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
200                                     unsigned LocCookie) {
201      SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
202      ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
203    }
204
205    void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
206                               SourceLocation LocCookie);
207  };
208
209  void BackendConsumer::anchor() {}
210}
211
212/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
213/// buffer to be a valid FullSourceLoc.
214static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
215                                            SourceManager &CSM) {
216  // Get both the clang and llvm source managers.  The location is relative to
217  // a memory buffer that the LLVM Source Manager is handling, we need to add
218  // a copy to the Clang source manager.
219  const llvm::SourceMgr &LSM = *D.getSourceMgr();
220
221  // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
222  // already owns its one and clang::SourceManager wants to own its one.
223  const MemoryBuffer *LBuf =
224  LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
225
226  // Create the copy and transfer ownership to clang::SourceManager.
227  llvm::MemoryBuffer *CBuf =
228  llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
229                                       LBuf->getBufferIdentifier());
230  FileID FID = CSM.createFileIDForMemBuffer(CBuf);
231
232  // Translate the offset into the file.
233  unsigned Offset = D.getLoc().getPointer()  - LBuf->getBufferStart();
234  SourceLocation NewLoc =
235  CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
236  return FullSourceLoc(NewLoc, CSM);
237}
238
239
240/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
241/// error parsing inline asm.  The SMDiagnostic indicates the error relative to
242/// the temporary memory buffer that the inline asm parser has set up.
243void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
244                                            SourceLocation LocCookie) {
245  // There are a couple of different kinds of errors we could get here.  First,
246  // we re-format the SMDiagnostic in terms of a clang diagnostic.
247
248  // Strip "error: " off the start of the message string.
249  StringRef Message = D.getMessage();
250  if (Message.startswith("error: "))
251    Message = Message.substr(7);
252
253  // If the SMDiagnostic has an inline asm source location, translate it.
254  FullSourceLoc Loc;
255  if (D.getLoc() != SMLoc())
256    Loc = ConvertBackendLocation(D, Context->getSourceManager());
257
258
259  // If this problem has clang-level source location information, report the
260  // issue as being an error in the source with a note showing the instantiated
261  // code.
262  if (LocCookie.isValid()) {
263    Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
264
265    if (D.getLoc().isValid()) {
266      DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
267      // Convert the SMDiagnostic ranges into SourceRange and attach them
268      // to the diagnostic.
269      for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
270        std::pair<unsigned, unsigned> Range = D.getRanges()[i];
271        unsigned Column = D.getColumnNo();
272        B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
273                         Loc.getLocWithOffset(Range.second - Column));
274      }
275    }
276    return;
277  }
278
279  // Otherwise, report the backend error as occurring in the generated .s file.
280  // If Loc is invalid, we still need to report the error, it just gets no
281  // location info.
282  Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
283}
284
285//
286
287CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
288  : Act(_Act), LinkModule(0),
289    VMContext(_VMContext ? _VMContext : new LLVMContext),
290    OwnsVMContext(!_VMContext) {}
291
292CodeGenAction::~CodeGenAction() {
293  TheModule.reset();
294  if (OwnsVMContext)
295    delete VMContext;
296}
297
298bool CodeGenAction::hasIRSupport() const { return true; }
299
300void CodeGenAction::EndSourceFileAction() {
301  // If the consumer creation failed, do nothing.
302  if (!getCompilerInstance().hasASTConsumer())
303    return;
304
305  // If we were given a link module, release consumer's ownership of it.
306  if (LinkModule)
307    BEConsumer->takeLinkModule();
308
309  // Steal the module from the consumer.
310  TheModule.reset(BEConsumer->takeModule());
311}
312
313llvm::Module *CodeGenAction::takeModule() {
314  return TheModule.take();
315}
316
317llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
318  OwnsVMContext = false;
319  return VMContext;
320}
321
322static raw_ostream *GetOutputStream(CompilerInstance &CI,
323                                    StringRef InFile,
324                                    BackendAction Action) {
325  switch (Action) {
326  case Backend_EmitAssembly:
327    return CI.createDefaultOutputFile(false, InFile, "s");
328  case Backend_EmitLL:
329    return CI.createDefaultOutputFile(false, InFile, "ll");
330  case Backend_EmitBC:
331    return CI.createDefaultOutputFile(true, InFile, "bc");
332  case Backend_EmitNothing:
333    return 0;
334  case Backend_EmitMCNull:
335  case Backend_EmitObj:
336    return CI.createDefaultOutputFile(true, InFile, "o");
337  }
338
339  llvm_unreachable("Invalid action!");
340}
341
342ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
343                                              StringRef InFile) {
344  BackendAction BA = static_cast<BackendAction>(Act);
345  OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
346  if (BA != Backend_EmitNothing && !OS)
347    return 0;
348
349  llvm::Module *LinkModuleToUse = LinkModule;
350
351  // If we were not given a link module, and the user requested that one be
352  // loaded from bitcode, do so now.
353  const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
354  if (!LinkModuleToUse && !LinkBCFile.empty()) {
355    std::string ErrorStr;
356
357    llvm::MemoryBuffer *BCBuf =
358      CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
359    if (!BCBuf) {
360      CI.getDiagnostics().Report(diag::err_cannot_open_file)
361        << LinkBCFile << ErrorStr;
362      return 0;
363    }
364
365    LinkModuleToUse = getLazyBitcodeModule(BCBuf, *VMContext, &ErrorStr);
366    if (!LinkModuleToUse) {
367      CI.getDiagnostics().Report(diag::err_cannot_open_file)
368        << LinkBCFile << ErrorStr;
369      return 0;
370    }
371  }
372
373  BEConsumer =
374      new BackendConsumer(BA, CI.getDiagnostics(),
375                          CI.getCodeGenOpts(), CI.getTargetOpts(),
376                          CI.getLangOpts(),
377                          CI.getFrontendOpts().ShowTimers, InFile,
378                          LinkModuleToUse, OS.take(), *VMContext);
379  return BEConsumer;
380}
381
382void CodeGenAction::ExecuteAction() {
383  // If this is an IR file, we have to treat it specially.
384  if (getCurrentFileKind() == IK_LLVM_IR) {
385    BackendAction BA = static_cast<BackendAction>(Act);
386    CompilerInstance &CI = getCompilerInstance();
387    raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
388    if (BA != Backend_EmitNothing && !OS)
389      return;
390
391    bool Invalid;
392    SourceManager &SM = CI.getSourceManager();
393    const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
394                                                      &Invalid);
395    if (Invalid)
396      return;
397
398    // FIXME: This is stupid, IRReader shouldn't take ownership.
399    llvm::MemoryBuffer *MainFileCopy =
400      llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
401                                           getCurrentFile());
402
403    llvm::SMDiagnostic Err;
404    TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
405    if (!TheModule) {
406      // Translate from the diagnostic info to the SourceManager location.
407      SourceLocation Loc = SM.translateFileLineCol(
408        SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
409        Err.getColumnNo() + 1);
410
411      // Get a custom diagnostic for the error. We strip off a leading
412      // diagnostic code if there is one.
413      StringRef Msg = Err.getMessage();
414      if (Msg.startswith("error: "))
415        Msg = Msg.substr(7);
416
417      // Escape '%', which is interpreted as a format character.
418      SmallString<128> EscapedMessage;
419      for (unsigned i = 0, e = Msg.size(); i != e; ++i) {
420        if (Msg[i] == '%')
421          EscapedMessage += '%';
422        EscapedMessage += Msg[i];
423      }
424
425      unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
426          DiagnosticsEngine::Error, EscapedMessage);
427
428      CI.getDiagnostics().Report(Loc, DiagID);
429      return;
430    }
431
432    EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
433                      CI.getTargetOpts(), CI.getLangOpts(),
434                      TheModule.get(),
435                      BA, OS);
436    return;
437  }
438
439  // Otherwise follow the normal AST path.
440  this->ASTFrontendAction::ExecuteAction();
441}
442
443//
444
445void EmitAssemblyAction::anchor() { }
446EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
447  : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
448
449void EmitBCAction::anchor() { }
450EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
451  : CodeGenAction(Backend_EmitBC, _VMContext) {}
452
453void EmitLLVMAction::anchor() { }
454EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
455  : CodeGenAction(Backend_EmitLL, _VMContext) {}
456
457void EmitLLVMOnlyAction::anchor() { }
458EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
459  : CodeGenAction(Backend_EmitNothing, _VMContext) {}
460
461void EmitCodeGenOnlyAction::anchor() { }
462EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
463  : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
464
465void EmitObjAction::anchor() { }
466EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
467  : CodeGenAction(Backend_EmitObj, _VMContext) {}
468