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