CodeGenAction.cpp 27 KB

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