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/AST/DeclCXX.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/CodeGen/BackendUtil.h"
19 #include "clang/CodeGen/ModuleBuilder.h"
20 #include "clang/Frontend/CompilerInstance.h"
21 #include "clang/Frontend/FrontendDiagnostic.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/DiagnosticPrinter.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IRReader/IRReader.h"
30 #include "llvm/Linker/Linker.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/Timer.h"
35 #include <memory>
36 using namespace clang;
37 using namespace llvm;
38 
39 namespace clang {
40   class BackendConsumer : public ASTConsumer {
41     virtual void anchor();
42     DiagnosticsEngine &Diags;
43     BackendAction Action;
44     const CodeGenOptions &CodeGenOpts;
45     const TargetOptions &TargetOpts;
46     const LangOptions &LangOpts;
47     raw_ostream *AsmOutStream;
48     ASTContext *Context;
49 
50     Timer LLVMIRGeneration;
51 
52     std::unique_ptr<CodeGenerator> Gen;
53 
54     std::unique_ptr<llvm::Module> TheModule, LinkModule;
55 
56   public:
57     BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
58                     const CodeGenOptions &compopts,
59                     const TargetOptions &targetopts,
60                     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) {
68       llvm::TimePassesIsEnabled = TimePasses;
69     }
70 
71     llvm::Module *takeModule() { return TheModule.release(); }
72     llvm::Module *takeLinkModule() { return LinkModule.release(); }
73 
74     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
75       Gen->HandleCXXStaticMemberVarInstantiation(VD);
76     }
77 
78     void Initialize(ASTContext &Ctx) override {
79       Context = &Ctx;
80 
81       if (llvm::TimePassesIsEnabled)
82         LLVMIRGeneration.startTimer();
83 
84       Gen->Initialize(Ctx);
85 
86       TheModule.reset(Gen->GetModule());
87 
88       if (llvm::TimePassesIsEnabled)
89         LLVMIRGeneration.stopTimer();
90     }
91 
92     bool HandleTopLevelDecl(DeclGroupRef D) override {
93       PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
94                                      Context->getSourceManager(),
95                                      "LLVM IR generation of declaration");
96 
97       if (llvm::TimePassesIsEnabled)
98         LLVMIRGeneration.startTimer();
99 
100       Gen->HandleTopLevelDecl(D);
101 
102       if (llvm::TimePassesIsEnabled)
103         LLVMIRGeneration.stopTimer();
104 
105       return true;
106     }
107 
108     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 
121     void HandleTranslationUnit(ASTContext &C) override {
122       {
123         PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
124         if (llvm::TimePassesIsEnabled)
125           LLVMIRGeneration.startTimer();
126 
127         Gen->HandleTranslationUnit(C);
128 
129         if (llvm::TimePassesIsEnabled)
130           LLVMIRGeneration.stopTimer();
131       }
132 
133       // Silently ignore if we weren't initialized for some reason.
134       if (!TheModule)
135         return;
136 
137       // Make sure IR generation is happy with the module. This is released by
138       // the module provider.
139       llvm::Module *M = Gen->ReleaseModule();
140       if (!M) {
141         // The module has been released by IR gen on failures, do not double
142         // free.
143         TheModule.release();
144         return;
145       }
146 
147       assert(TheModule.get() == M &&
148              "Unexpected module change during IR generation");
149 
150       // 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 
161       // Install an inline asm handler so that diagnostics get printed through
162       // our diagnostics hooks.
163       LLVMContext &Ctx = TheModule->getContext();
164       LLVMContext::InlineAsmDiagHandlerTy OldHandler =
165         Ctx.getInlineAsmDiagnosticHandler();
166       void *OldContext = Ctx.getInlineAsmDiagnosticContext();
167       Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
168 
169       LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
170           Ctx.getDiagnosticHandler();
171       void *OldDiagnosticContext = Ctx.getDiagnosticContext();
172       Ctx.setDiagnosticHandler(DiagnosticHandler, this);
173 
174       EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
175                         C.getTargetInfo().getTargetDescription(),
176                         TheModule.get(), Action, AsmOutStream);
177 
178       Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
179 
180       Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
181     }
182 
183     void HandleTagDeclDefinition(TagDecl *D) override {
184       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
185                                      Context->getSourceManager(),
186                                      "LLVM IR generation of declaration");
187       Gen->HandleTagDeclDefinition(D);
188     }
189 
190     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
191       Gen->HandleTagDeclRequiredDefinition(D);
192     }
193 
194     void CompleteTentativeDefinition(VarDecl *D) override {
195       Gen->CompleteTentativeDefinition(D);
196     }
197 
198     void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
199       Gen->HandleVTable(RD, DefinitionRequired);
200     }
201 
202     void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
203       Gen->HandleLinkerOptionPragma(Opts);
204     }
205 
206     void HandleDetectMismatch(llvm::StringRef Name,
207                                       llvm::StringRef Value) override {
208       Gen->HandleDetectMismatch(Name, Value);
209     }
210 
211     void HandleDependentLibrary(llvm::StringRef Opts) override {
212       Gen->HandleDependentLibrary(Opts);
213     }
214 
215     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     }
220 
221     static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
222                                   void *Context) {
223       ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
224     }
225 
226     void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
227                                SourceLocation LocCookie);
228 
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);
238     /// \brief Specialized handlers for optimization remarks.
239     /// Note that these handlers only accept remarks and they always handle
240     /// them.
241     void
242     EmitOptimizationRemark(const llvm::DiagnosticInfoOptimizationRemarkBase &D,
243                            unsigned DiagID);
244     void
245     OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
246     void OptimizationRemarkHandler(
247         const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
248     void OptimizationRemarkHandler(
249         const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
250   };
251 
252   void BackendConsumer::anchor() {}
253 }
254 
255 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
256 /// buffer to be a valid FullSourceLoc.
257 static 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
261   // a copy to the Clang source manager.
262   const llvm::SourceMgr &LSM = *D.getSourceMgr();
263 
264   // 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()));
268 
269   // Create the copy and transfer ownership to clang::SourceManager.
270   llvm::MemoryBuffer *CBuf =
271   llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
272                                        LBuf->getBufferIdentifier());
273   FileID FID = CSM.createFileID(CBuf);
274 
275   // Translate the offset into the file.
276   unsigned Offset = D.getLoc().getPointer()  - LBuf->getBufferStart();
277   SourceLocation NewLoc =
278   CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
279   return FullSourceLoc(NewLoc, CSM);
280 }
281 
282 
283 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
284 /// error parsing inline asm.  The SMDiagnostic indicates the error relative to
285 /// the temporary memory buffer that the inline asm parser has set up.
286 void 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.
290 
291   // Strip "error: " off the start of the message string.
292   StringRef Message = D.getMessage();
293   if (Message.startswith("error: "))
294     Message = Message.substr(7);
295 
296   // If the SMDiagnostic has an inline asm source location, translate it.
297   FullSourceLoc Loc;
298   if (D.getLoc() != SMLoc())
299     Loc = ConvertBackendLocation(D, Context->getSourceManager());
300 
301 
302   // 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()) {
306     Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
307 
308     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     }
319     return;
320   }
321 
322   // Otherwise, report the backend error as occurring in the generated .s file.
323   // 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);
326 }
327 
328 #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;                                                                   \
337     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;                                                                   \
358     case llvm::DS_Note:                                                        \
359       DiagID = diag::note_fe_##GroupName;                                      \
360       break;                                                                   \
361     }                                                                          \
362   } while (false)
363 
364 bool
365 BackendConsumer::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
371   // issue as being a problem in the source with a note showing the instantiated
372   // 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 
389 bool
390 BackendConsumer::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 
404 void BackendConsumer::EmitOptimizationRemark(
405     const llvm::DiagnosticInfoOptimizationRemarkBase &D, unsigned DiagID) {
406   // We only support remarks.
407   assert(D.getSeverity() == llvm::DS_Remark);
408 
409   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);
422   }
423   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 
443 void 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 
452 void 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 
463 void 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);
472 }
473 
474 /// \brief This function is invoked when the backend needs
475 /// to report something to the user.
476 void 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;
491   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;
496   case llvm::DK_OptimizationRemarkMissed:
497     // 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;
501   case llvm::DK_OptimizationRemarkAnalysis:
502     // Optimization remarks are always handled completely by this
503     // handler. There is no generic way of emitting them.
504     OptimizationRemarkHandler(
505         cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
506     return;
507   default:
508     // Plugin IDs are not bound to any value as they are set dynamically.
509     ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
510     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
524 
525 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
526   : Act(_Act), LinkModule(nullptr),
527     VMContext(_VMContext ? _VMContext : new LLVMContext),
528     OwnsVMContext(!_VMContext) {}
529 
530 CodeGenAction::~CodeGenAction() {
531   TheModule.reset();
532   if (OwnsVMContext)
533     delete VMContext;
534 }
535 
536 bool CodeGenAction::hasIRSupport() const { return true; }
537 
538 void CodeGenAction::EndSourceFileAction() {
539   // If the consumer creation failed, do nothing.
540   if (!getCompilerInstance().hasASTConsumer())
541     return;
542 
543   // If we were given a link module, release consumer's ownership of it.
544   if (LinkModule)
545     BEConsumer->takeLinkModule();
546 
547   // Steal the module from the consumer.
548   TheModule.reset(BEConsumer->takeModule());
549 }
550 
551 llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
552 
553 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
554   OwnsVMContext = false;
555   return VMContext;
556 }
557 
558 static raw_ostream *GetOutputStream(CompilerInstance &CI,
559                                     StringRef InFile,
560                                     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:
569     return nullptr;
570   case Backend_EmitMCNull:
571   case Backend_EmitObj:
572     return CI.createDefaultOutputFile(true, InFile, "o");
573   }
574 
575   llvm_unreachable("Invalid action!");
576 }
577 
578 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
579                                               StringRef InFile) {
580   BackendAction BA = static_cast<BackendAction>(Act);
581   std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
582   if (BA != Backend_EmitNothing && !OS)
583     return nullptr;
584 
585   llvm::Module *LinkModuleToUse = LinkModule;
586 
587   // If we were not given a link module, and the user requested that one be
588   // loaded from bitcode, do so now.
589   const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
590   if (!LinkModuleToUse && !LinkBCFile.empty()) {
591     std::string ErrorStr;
592 
593     llvm::MemoryBuffer *BCBuf =
594       CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
595     if (!BCBuf) {
596       CI.getDiagnostics().Report(diag::err_cannot_open_file)
597         << LinkBCFile << ErrorStr;
598       return nullptr;
599     }
600 
601     ErrorOr<llvm::Module *> ModuleOrErr =
602         getLazyBitcodeModule(BCBuf, *VMContext);
603     if (error_code EC = ModuleOrErr.getError()) {
604       CI.getDiagnostics().Report(diag::err_cannot_open_file)
605         << LinkBCFile << EC.message();
606       return nullptr;
607     }
608     LinkModuleToUse = ModuleOrErr.get();
609   }
610 
611   BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
612                                    CI.getTargetOpts(), CI.getLangOpts(),
613                                    CI.getFrontendOpts().ShowTimers, InFile,
614                                    LinkModuleToUse, OS.release(), *VMContext);
615   return BEConsumer;
616 }
617 
618 void CodeGenAction::ExecuteAction() {
619   // If this is an IR file, we have to treat it specially.
620   if (getCurrentFileKind() == IK_LLVM_IR) {
621     BackendAction BA = static_cast<BackendAction>(Act);
622     CompilerInstance &CI = getCompilerInstance();
623     raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
624     if (BA != Backend_EmitNothing && !OS)
625       return;
626 
627     bool Invalid;
628     SourceManager &SM = CI.getSourceManager();
629     const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
630                                                       &Invalid);
631     if (Invalid)
632       return;
633 
634     // FIXME: This is stupid, IRReader shouldn't take ownership.
635     llvm::MemoryBuffer *MainFileCopy =
636       llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
637                                            getCurrentFile());
638 
639     llvm::SMDiagnostic Err;
640     TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
641     if (!TheModule) {
642       // Translate from the diagnostic info to the SourceManager location.
643       SourceLocation Loc = SM.translateFileLineCol(
644         SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
645         Err.getColumnNo() + 1);
646 
647       // Strip off a leading diagnostic code if there is one.
648       StringRef Msg = Err.getMessage();
649       if (Msg.startswith("error: "))
650         Msg = Msg.substr(7);
651 
652       unsigned DiagID =
653           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
654 
655       CI.getDiagnostics().Report(Loc, DiagID) << Msg;
656       return;
657     }
658     const TargetOptions &TargetOpts = CI.getTargetOpts();
659     if (TheModule->getTargetTriple() != TargetOpts.Triple) {
660       unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
661           DiagnosticsEngine::Warning,
662           "overriding the module target triple with %0");
663 
664       CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
665       TheModule->setTargetTriple(TargetOpts.Triple);
666     }
667 
668     EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
669                       CI.getLangOpts(), CI.getTarget().getTargetDescription(),
670                       TheModule.get(), BA, OS);
671     return;
672   }
673 
674   // Otherwise follow the normal AST path.
675   this->ASTFrontendAction::ExecuteAction();
676 }
677 
678 //
679 
680 void EmitAssemblyAction::anchor() { }
681 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
682   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
683 
684 void EmitBCAction::anchor() { }
685 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
686   : CodeGenAction(Backend_EmitBC, _VMContext) {}
687 
688 void EmitLLVMAction::anchor() { }
689 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
690   : CodeGenAction(Backend_EmitLL, _VMContext) {}
691 
692 void EmitLLVMOnlyAction::anchor() { }
693 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
694   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
695 
696 void EmitCodeGenOnlyAction::anchor() { }
697 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
698   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
699 
700 void EmitObjAction::anchor() { }
701 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
702   : CodeGenAction(Backend_EmitObj, _VMContext) {}
703