CodeGenAction.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. #include "clang/CodeGen/CodeGenAction.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/DeclGroup.h"
  13. #include "clang/Basic/FileManager.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/CodeGen/BackendUtil.h"
  17. #include "clang/CodeGen/ModuleBuilder.h"
  18. #include "clang/Frontend/CompilerInstance.h"
  19. #include "clang/Frontend/FrontendDiagnostic.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/Bitcode/ReaderWriter.h"
  22. #include "llvm/IR/DebugInfo.h"
  23. #include "llvm/IR/DiagnosticInfo.h"
  24. #include "llvm/IR/DiagnosticPrinter.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IRReader/IRReader.h"
  28. #include "llvm/Linker/Linker.h"
  29. #include "llvm/Pass.h"
  30. #include "llvm/Support/MemoryBuffer.h"
  31. #include "llvm/Support/SourceMgr.h"
  32. #include "llvm/Support/Timer.h"
  33. #include <memory>
  34. using namespace clang;
  35. using namespace llvm;
  36. namespace clang {
  37. class BackendConsumer : public ASTConsumer {
  38. virtual void anchor();
  39. DiagnosticsEngine &Diags;
  40. BackendAction Action;
  41. const CodeGenOptions &CodeGenOpts;
  42. const TargetOptions &TargetOpts;
  43. const LangOptions &LangOpts;
  44. raw_ostream *AsmOutStream;
  45. ASTContext *Context;
  46. Timer LLVMIRGeneration;
  47. std::unique_ptr<CodeGenerator> Gen;
  48. std::unique_ptr<llvm::Module> TheModule, LinkModule;
  49. public:
  50. BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
  51. const CodeGenOptions &compopts,
  52. const TargetOptions &targetopts,
  53. const LangOptions &langopts, bool TimePasses,
  54. const std::string &infile, llvm::Module *LinkModule,
  55. raw_ostream *OS, LLVMContext &C)
  56. : Diags(_Diags), Action(action), CodeGenOpts(compopts),
  57. TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
  58. Context(), LLVMIRGeneration("LLVM IR Generation Time"),
  59. Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
  60. LinkModule(LinkModule) {
  61. llvm::TimePassesIsEnabled = TimePasses;
  62. }
  63. llvm::Module *takeModule() { return TheModule.release(); }
  64. llvm::Module *takeLinkModule() { return LinkModule.release(); }
  65. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  66. Gen->HandleCXXStaticMemberVarInstantiation(VD);
  67. }
  68. void Initialize(ASTContext &Ctx) override {
  69. Context = &Ctx;
  70. if (llvm::TimePassesIsEnabled)
  71. LLVMIRGeneration.startTimer();
  72. Gen->Initialize(Ctx);
  73. TheModule.reset(Gen->GetModule());
  74. if (llvm::TimePassesIsEnabled)
  75. LLVMIRGeneration.stopTimer();
  76. }
  77. bool HandleTopLevelDecl(DeclGroupRef D) override {
  78. PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
  79. Context->getSourceManager(),
  80. "LLVM IR generation of declaration");
  81. if (llvm::TimePassesIsEnabled)
  82. LLVMIRGeneration.startTimer();
  83. Gen->HandleTopLevelDecl(D);
  84. if (llvm::TimePassesIsEnabled)
  85. LLVMIRGeneration.stopTimer();
  86. return true;
  87. }
  88. void HandleTranslationUnit(ASTContext &C) override {
  89. {
  90. PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
  91. if (llvm::TimePassesIsEnabled)
  92. LLVMIRGeneration.startTimer();
  93. Gen->HandleTranslationUnit(C);
  94. if (llvm::TimePassesIsEnabled)
  95. LLVMIRGeneration.stopTimer();
  96. }
  97. // Silently ignore if we weren't initialized for some reason.
  98. if (!TheModule)
  99. return;
  100. // Make sure IR generation is happy with the module. This is released by
  101. // the module provider.
  102. llvm::Module *M = Gen->ReleaseModule();
  103. if (!M) {
  104. // The module has been released by IR gen on failures, do not double
  105. // free.
  106. TheModule.release();
  107. return;
  108. }
  109. assert(TheModule.get() == M &&
  110. "Unexpected module change during IR generation");
  111. // Link LinkModule into this module if present, preserving its validity.
  112. if (LinkModule) {
  113. std::string ErrorMsg;
  114. if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
  115. &ErrorMsg)) {
  116. Diags.Report(diag::err_fe_cannot_link_module)
  117. << LinkModule->getModuleIdentifier() << ErrorMsg;
  118. return;
  119. }
  120. }
  121. // Install an inline asm handler so that diagnostics get printed through
  122. // our diagnostics hooks.
  123. LLVMContext &Ctx = TheModule->getContext();
  124. LLVMContext::InlineAsmDiagHandlerTy OldHandler =
  125. Ctx.getInlineAsmDiagnosticHandler();
  126. void *OldContext = Ctx.getInlineAsmDiagnosticContext();
  127. Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
  128. LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
  129. Ctx.getDiagnosticHandler();
  130. void *OldDiagnosticContext = Ctx.getDiagnosticContext();
  131. Ctx.setDiagnosticHandler(DiagnosticHandler, this);
  132. EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  133. C.getTargetInfo().getTargetDescription(),
  134. TheModule.get(), Action, AsmOutStream);
  135. Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
  136. Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
  137. }
  138. void HandleTagDeclDefinition(TagDecl *D) override {
  139. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  140. Context->getSourceManager(),
  141. "LLVM IR generation of declaration");
  142. Gen->HandleTagDeclDefinition(D);
  143. }
  144. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  145. Gen->HandleTagDeclRequiredDefinition(D);
  146. }
  147. void CompleteTentativeDefinition(VarDecl *D) override {
  148. Gen->CompleteTentativeDefinition(D);
  149. }
  150. void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
  151. Gen->HandleVTable(RD, DefinitionRequired);
  152. }
  153. void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
  154. Gen->HandleLinkerOptionPragma(Opts);
  155. }
  156. void HandleDetectMismatch(llvm::StringRef Name,
  157. llvm::StringRef Value) override {
  158. Gen->HandleDetectMismatch(Name, Value);
  159. }
  160. void HandleDependentLibrary(llvm::StringRef Opts) override {
  161. Gen->HandleDependentLibrary(Opts);
  162. }
  163. static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
  164. unsigned LocCookie) {
  165. SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
  166. ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
  167. }
  168. static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
  169. void *Context) {
  170. ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
  171. }
  172. void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
  173. SourceLocation LocCookie);
  174. void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
  175. /// \brief Specialized handler for InlineAsm diagnostic.
  176. /// \return True if the diagnostic has been successfully reported, false
  177. /// otherwise.
  178. bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
  179. /// \brief Specialized handler for StackSize diagnostic.
  180. /// \return True if the diagnostic has been successfully reported, false
  181. /// otherwise.
  182. bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
  183. /// \brief Specialized handler for the optimization diagnostic.
  184. /// Note that this handler only accepts remarks and it always handles
  185. /// them.
  186. void
  187. OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
  188. };
  189. void BackendConsumer::anchor() {}
  190. }
  191. /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
  192. /// buffer to be a valid FullSourceLoc.
  193. static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
  194. SourceManager &CSM) {
  195. // Get both the clang and llvm source managers. The location is relative to
  196. // a memory buffer that the LLVM Source Manager is handling, we need to add
  197. // a copy to the Clang source manager.
  198. const llvm::SourceMgr &LSM = *D.getSourceMgr();
  199. // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
  200. // already owns its one and clang::SourceManager wants to own its one.
  201. const MemoryBuffer *LBuf =
  202. LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
  203. // Create the copy and transfer ownership to clang::SourceManager.
  204. llvm::MemoryBuffer *CBuf =
  205. llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
  206. LBuf->getBufferIdentifier());
  207. FileID FID = CSM.createFileIDForMemBuffer(CBuf);
  208. // Translate the offset into the file.
  209. unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
  210. SourceLocation NewLoc =
  211. CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
  212. return FullSourceLoc(NewLoc, CSM);
  213. }
  214. /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
  215. /// error parsing inline asm. The SMDiagnostic indicates the error relative to
  216. /// the temporary memory buffer that the inline asm parser has set up.
  217. void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
  218. SourceLocation LocCookie) {
  219. // There are a couple of different kinds of errors we could get here. First,
  220. // we re-format the SMDiagnostic in terms of a clang diagnostic.
  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. // If the SMDiagnostic has an inline asm source location, translate it.
  226. FullSourceLoc Loc;
  227. if (D.getLoc() != SMLoc())
  228. Loc = ConvertBackendLocation(D, Context->getSourceManager());
  229. // If this problem has clang-level source location information, report the
  230. // issue as being an error in the source with a note showing the instantiated
  231. // code.
  232. if (LocCookie.isValid()) {
  233. Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
  234. if (D.getLoc().isValid()) {
  235. DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
  236. // Convert the SMDiagnostic ranges into SourceRange and attach them
  237. // to the diagnostic.
  238. for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
  239. std::pair<unsigned, unsigned> Range = D.getRanges()[i];
  240. unsigned Column = D.getColumnNo();
  241. B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
  242. Loc.getLocWithOffset(Range.second - Column));
  243. }
  244. }
  245. return;
  246. }
  247. // Otherwise, report the backend error as occurring in the generated .s file.
  248. // If Loc is invalid, we still need to report the error, it just gets no
  249. // location info.
  250. Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
  251. }
  252. #define ComputeDiagID(Severity, GroupName, DiagID) \
  253. do { \
  254. switch (Severity) { \
  255. case llvm::DS_Error: \
  256. DiagID = diag::err_fe_##GroupName; \
  257. break; \
  258. case llvm::DS_Warning: \
  259. DiagID = diag::warn_fe_##GroupName; \
  260. break; \
  261. case llvm::DS_Remark: \
  262. llvm_unreachable("'remark' severity not expected"); \
  263. break; \
  264. case llvm::DS_Note: \
  265. DiagID = diag::note_fe_##GroupName; \
  266. break; \
  267. } \
  268. } while (false)
  269. #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
  270. do { \
  271. switch (Severity) { \
  272. case llvm::DS_Error: \
  273. DiagID = diag::err_fe_##GroupName; \
  274. break; \
  275. case llvm::DS_Warning: \
  276. DiagID = diag::warn_fe_##GroupName; \
  277. break; \
  278. case llvm::DS_Remark: \
  279. DiagID = diag::remark_fe_##GroupName; \
  280. break; \
  281. case llvm::DS_Note: \
  282. DiagID = diag::note_fe_##GroupName; \
  283. break; \
  284. } \
  285. } while (false)
  286. bool
  287. BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
  288. unsigned DiagID;
  289. ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
  290. std::string Message = D.getMsgStr().str();
  291. // If this problem has clang-level source location information, report the
  292. // issue as being a problem in the source with a note showing the instantiated
  293. // code.
  294. SourceLocation LocCookie =
  295. SourceLocation::getFromRawEncoding(D.getLocCookie());
  296. if (LocCookie.isValid())
  297. Diags.Report(LocCookie, DiagID).AddString(Message);
  298. else {
  299. // Otherwise, report the backend diagnostic as occurring in the generated
  300. // .s file.
  301. // If Loc is invalid, we still need to report the diagnostic, it just gets
  302. // no location info.
  303. FullSourceLoc Loc;
  304. Diags.Report(Loc, DiagID).AddString(Message);
  305. }
  306. // We handled all the possible severities.
  307. return true;
  308. }
  309. bool
  310. BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
  311. if (D.getSeverity() != llvm::DS_Warning)
  312. // For now, the only support we have for StackSize diagnostic is warning.
  313. // We do not know how to format other severities.
  314. return false;
  315. // FIXME: We should demangle the function name.
  316. // FIXME: Is there a way to get a location for that function?
  317. FullSourceLoc Loc;
  318. Diags.Report(Loc, diag::warn_fe_backend_frame_larger_than)
  319. << D.getStackSize() << D.getFunction().getName();
  320. return true;
  321. }
  322. void BackendConsumer::OptimizationRemarkHandler(
  323. const llvm::DiagnosticInfoOptimizationRemark &D) {
  324. // We only support remarks.
  325. assert(D.getSeverity() == llvm::DS_Remark);
  326. // Optimization remarks are active only if -Rpass=regexp is given and the
  327. // regular expression pattern in 'regexp' matches the name of the pass
  328. // name in \p D.
  329. if (CodeGenOpts.OptimizationRemarkPattern &&
  330. CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) {
  331. SourceManager &SourceMgr = Context->getSourceManager();
  332. FileManager &FileMgr = SourceMgr.getFileManager();
  333. StringRef Filename;
  334. unsigned Line, Column;
  335. D.getLocation(&Filename, &Line, &Column);
  336. SourceLocation Loc;
  337. const FileEntry *FE = FileMgr.getFile(Filename);
  338. if (FE && Line > 0) {
  339. // If -gcolumn-info was not used, Column will be 0. This upsets the
  340. // source manager, so if Column is not set, set it to 1.
  341. if (Column == 0)
  342. Column = 1;
  343. Loc = SourceMgr.translateFileLineCol(FE, Line, Column);
  344. }
  345. Diags.Report(Loc, diag::remark_fe_backend_optimization_remark)
  346. << AddFlagValue(D.getPassName()) << D.getMsg().str();
  347. if (Line == 0)
  348. // If we could not extract a source location for the diagnostic,
  349. // inform the user how they can get source locations back.
  350. //
  351. // FIXME: We should really be generating !srcloc annotations when
  352. // -Rpass is used. !srcloc annotations need to be emitted in
  353. // approximately the same spots as !dbg nodes.
  354. Diags.Report(diag::note_fe_backend_optimization_remark_missing_loc);
  355. else if (Loc.isInvalid())
  356. // If we were not able to translate the file:line:col information
  357. // back to a SourceLocation, at least emit a note stating that
  358. // we could not translate this location. This can happen in the
  359. // case of #line directives.
  360. Diags.Report(diag::note_fe_backend_optimization_remark_invalid_loc)
  361. << Filename << Line << Column;
  362. }
  363. }
  364. /// \brief This function is invoked when the backend needs
  365. /// to report something to the user.
  366. void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
  367. unsigned DiagID = diag::err_fe_inline_asm;
  368. llvm::DiagnosticSeverity Severity = DI.getSeverity();
  369. // Get the diagnostic ID based.
  370. switch (DI.getKind()) {
  371. case llvm::DK_InlineAsm:
  372. if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
  373. return;
  374. ComputeDiagID(Severity, inline_asm, DiagID);
  375. break;
  376. case llvm::DK_StackSize:
  377. if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
  378. return;
  379. ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
  380. break;
  381. case llvm::DK_OptimizationRemark:
  382. // Optimization remarks are always handled completely by this
  383. // handler. There is no generic way of emitting them.
  384. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
  385. return;
  386. default:
  387. // Plugin IDs are not bound to any value as they are set dynamically.
  388. ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
  389. break;
  390. }
  391. std::string MsgStorage;
  392. {
  393. raw_string_ostream Stream(MsgStorage);
  394. DiagnosticPrinterRawOStream DP(Stream);
  395. DI.print(DP);
  396. }
  397. // Report the backend message using the usual diagnostic mechanism.
  398. FullSourceLoc Loc;
  399. Diags.Report(Loc, DiagID).AddString(MsgStorage);
  400. }
  401. #undef ComputeDiagID
  402. CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
  403. : Act(_Act), LinkModule(0),
  404. VMContext(_VMContext ? _VMContext : new LLVMContext),
  405. OwnsVMContext(!_VMContext) {}
  406. CodeGenAction::~CodeGenAction() {
  407. TheModule.reset();
  408. if (OwnsVMContext)
  409. delete VMContext;
  410. }
  411. bool CodeGenAction::hasIRSupport() const { return true; }
  412. void CodeGenAction::EndSourceFileAction() {
  413. // If the consumer creation failed, do nothing.
  414. if (!getCompilerInstance().hasASTConsumer())
  415. return;
  416. // If we were given a link module, release consumer's ownership of it.
  417. if (LinkModule)
  418. BEConsumer->takeLinkModule();
  419. // Steal the module from the consumer.
  420. TheModule.reset(BEConsumer->takeModule());
  421. }
  422. llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
  423. llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
  424. OwnsVMContext = false;
  425. return VMContext;
  426. }
  427. static raw_ostream *GetOutputStream(CompilerInstance &CI,
  428. StringRef InFile,
  429. BackendAction Action) {
  430. switch (Action) {
  431. case Backend_EmitAssembly:
  432. return CI.createDefaultOutputFile(false, InFile, "s");
  433. case Backend_EmitLL:
  434. return CI.createDefaultOutputFile(false, InFile, "ll");
  435. case Backend_EmitBC:
  436. return CI.createDefaultOutputFile(true, InFile, "bc");
  437. case Backend_EmitNothing:
  438. return 0;
  439. case Backend_EmitMCNull:
  440. case Backend_EmitObj:
  441. return CI.createDefaultOutputFile(true, InFile, "o");
  442. }
  443. llvm_unreachable("Invalid action!");
  444. }
  445. ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
  446. StringRef InFile) {
  447. BackendAction BA = static_cast<BackendAction>(Act);
  448. std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
  449. if (BA != Backend_EmitNothing && !OS)
  450. return 0;
  451. llvm::Module *LinkModuleToUse = LinkModule;
  452. // If we were not given a link module, and the user requested that one be
  453. // loaded from bitcode, do so now.
  454. const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
  455. if (!LinkModuleToUse && !LinkBCFile.empty()) {
  456. std::string ErrorStr;
  457. llvm::MemoryBuffer *BCBuf =
  458. CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
  459. if (!BCBuf) {
  460. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  461. << LinkBCFile << ErrorStr;
  462. return 0;
  463. }
  464. ErrorOr<llvm::Module *> ModuleOrErr =
  465. getLazyBitcodeModule(BCBuf, *VMContext);
  466. if (error_code EC = ModuleOrErr.getError()) {
  467. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  468. << LinkBCFile << EC.message();
  469. return 0;
  470. }
  471. LinkModuleToUse = ModuleOrErr.get();
  472. }
  473. BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
  474. CI.getTargetOpts(), CI.getLangOpts(),
  475. CI.getFrontendOpts().ShowTimers, InFile,
  476. LinkModuleToUse, OS.release(), *VMContext);
  477. return BEConsumer;
  478. }
  479. void CodeGenAction::ExecuteAction() {
  480. // If this is an IR file, we have to treat it specially.
  481. if (getCurrentFileKind() == IK_LLVM_IR) {
  482. BackendAction BA = static_cast<BackendAction>(Act);
  483. CompilerInstance &CI = getCompilerInstance();
  484. raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
  485. if (BA != Backend_EmitNothing && !OS)
  486. return;
  487. bool Invalid;
  488. SourceManager &SM = CI.getSourceManager();
  489. const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
  490. &Invalid);
  491. if (Invalid)
  492. return;
  493. // FIXME: This is stupid, IRReader shouldn't take ownership.
  494. llvm::MemoryBuffer *MainFileCopy =
  495. llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
  496. getCurrentFile());
  497. llvm::SMDiagnostic Err;
  498. TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
  499. if (!TheModule) {
  500. // Translate from the diagnostic info to the SourceManager location.
  501. SourceLocation Loc = SM.translateFileLineCol(
  502. SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
  503. Err.getColumnNo() + 1);
  504. // Strip off a leading diagnostic code if there is one.
  505. StringRef Msg = Err.getMessage();
  506. if (Msg.startswith("error: "))
  507. Msg = Msg.substr(7);
  508. unsigned DiagID =
  509. CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  510. CI.getDiagnostics().Report(Loc, DiagID) << Msg;
  511. return;
  512. }
  513. const TargetOptions &TargetOpts = CI.getTargetOpts();
  514. if (TheModule->getTargetTriple() != TargetOpts.Triple) {
  515. unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
  516. DiagnosticsEngine::Warning,
  517. "overriding the module target triple with %0");
  518. CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
  519. TheModule->setTargetTriple(TargetOpts.Triple);
  520. }
  521. EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
  522. CI.getLangOpts(), CI.getTarget().getTargetDescription(),
  523. TheModule.get(), BA, OS);
  524. return;
  525. }
  526. // Otherwise follow the normal AST path.
  527. this->ASTFrontendAction::ExecuteAction();
  528. }
  529. //
  530. void EmitAssemblyAction::anchor() { }
  531. EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
  532. : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
  533. void EmitBCAction::anchor() { }
  534. EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
  535. : CodeGenAction(Backend_EmitBC, _VMContext) {}
  536. void EmitLLVMAction::anchor() { }
  537. EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
  538. : CodeGenAction(Backend_EmitLL, _VMContext) {}
  539. void EmitLLVMOnlyAction::anchor() { }
  540. EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
  541. : CodeGenAction(Backend_EmitNothing, _VMContext) {}
  542. void EmitCodeGenOnlyAction::anchor() { }
  543. EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
  544. : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
  545. void EmitObjAction::anchor() { }
  546. EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
  547. : CodeGenAction(Backend_EmitObj, _VMContext) {}