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