CodeGenAction.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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. unsigned DiagID;
  248. switch (D.getKind()) {
  249. case llvm::SourceMgr::DK_Error:
  250. DiagID = diag::err_fe_inline_asm;
  251. break;
  252. case llvm::SourceMgr::DK_Warning:
  253. DiagID = diag::warn_fe_inline_asm;
  254. break;
  255. case llvm::SourceMgr::DK_Note:
  256. DiagID = diag::note_fe_inline_asm;
  257. break;
  258. }
  259. // If this problem has clang-level source location information, report the
  260. // issue in the source with a note showing the instantiated
  261. // code.
  262. if (LocCookie.isValid()) {
  263. Diags.Report(LocCookie, DiagID).AddString(Message);
  264. if (D.getLoc().isValid()) {
  265. DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
  266. // Convert the SMDiagnostic ranges into SourceRange and attach them
  267. // to the diagnostic.
  268. for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
  269. std::pair<unsigned, unsigned> Range = D.getRanges()[i];
  270. unsigned Column = D.getColumnNo();
  271. B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
  272. Loc.getLocWithOffset(Range.second - Column));
  273. }
  274. }
  275. return;
  276. }
  277. // Otherwise, report the backend issue as occurring in the generated .s file.
  278. // If Loc is invalid, we still need to report the issue, it just gets no
  279. // location info.
  280. Diags.Report(Loc, DiagID).AddString(Message);
  281. }
  282. #define ComputeDiagID(Severity, GroupName, DiagID) \
  283. do { \
  284. switch (Severity) { \
  285. case llvm::DS_Error: \
  286. DiagID = diag::err_fe_##GroupName; \
  287. break; \
  288. case llvm::DS_Warning: \
  289. DiagID = diag::warn_fe_##GroupName; \
  290. break; \
  291. case llvm::DS_Remark: \
  292. llvm_unreachable("'remark' severity not expected"); \
  293. break; \
  294. case llvm::DS_Note: \
  295. DiagID = diag::note_fe_##GroupName; \
  296. break; \
  297. } \
  298. } while (false)
  299. #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
  300. do { \
  301. switch (Severity) { \
  302. case llvm::DS_Error: \
  303. DiagID = diag::err_fe_##GroupName; \
  304. break; \
  305. case llvm::DS_Warning: \
  306. DiagID = diag::warn_fe_##GroupName; \
  307. break; \
  308. case llvm::DS_Remark: \
  309. DiagID = diag::remark_fe_##GroupName; \
  310. break; \
  311. case llvm::DS_Note: \
  312. DiagID = diag::note_fe_##GroupName; \
  313. break; \
  314. } \
  315. } while (false)
  316. bool
  317. BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
  318. unsigned DiagID;
  319. ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
  320. std::string Message = D.getMsgStr().str();
  321. // If this problem has clang-level source location information, report the
  322. // issue as being a problem in the source with a note showing the instantiated
  323. // code.
  324. SourceLocation LocCookie =
  325. SourceLocation::getFromRawEncoding(D.getLocCookie());
  326. if (LocCookie.isValid())
  327. Diags.Report(LocCookie, DiagID).AddString(Message);
  328. else {
  329. // Otherwise, report the backend diagnostic as occurring in the generated
  330. // .s file.
  331. // If Loc is invalid, we still need to report the diagnostic, it just gets
  332. // no location info.
  333. FullSourceLoc Loc;
  334. Diags.Report(Loc, DiagID).AddString(Message);
  335. }
  336. // We handled all the possible severities.
  337. return true;
  338. }
  339. bool
  340. BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
  341. if (D.getSeverity() != llvm::DS_Warning)
  342. // For now, the only support we have for StackSize diagnostic is warning.
  343. // We do not know how to format other severities.
  344. return false;
  345. if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
  346. Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
  347. diag::warn_fe_frame_larger_than)
  348. << D.getStackSize() << Decl::castToDeclContext(ND);
  349. return true;
  350. }
  351. return false;
  352. }
  353. void BackendConsumer::EmitOptimizationRemark(
  354. const llvm::DiagnosticInfoOptimizationRemarkBase &D, unsigned DiagID) {
  355. // We only support remarks.
  356. assert(D.getSeverity() == llvm::DS_Remark);
  357. SourceManager &SourceMgr = Context->getSourceManager();
  358. FileManager &FileMgr = SourceMgr.getFileManager();
  359. StringRef Filename;
  360. unsigned Line, Column;
  361. D.getLocation(&Filename, &Line, &Column);
  362. SourceLocation Loc;
  363. const FileEntry *FE = FileMgr.getFile(Filename);
  364. if (FE && Line > 0) {
  365. // If -gcolumn-info was not used, Column will be 0. This upsets the
  366. // source manager, so if Column is not set, set it to 1.
  367. if (Column == 0)
  368. Column = 1;
  369. Loc = SourceMgr.translateFileLineCol(FE, Line, Column);
  370. }
  371. Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName())
  372. << D.getMsg().str();
  373. if (Line == 0)
  374. // If we could not extract a source location for the diagnostic,
  375. // inform the user how they can get source locations back.
  376. //
  377. // FIXME: We should really be generating !srcloc annotations when
  378. // -Rpass is used. !srcloc annotations need to be emitted in
  379. // approximately the same spots as !dbg nodes.
  380. Diags.Report(diag::note_fe_backend_optimization_remark_missing_loc);
  381. else if (Loc.isInvalid())
  382. // If we were not able to translate the file:line:col information
  383. // back to a SourceLocation, at least emit a note stating that
  384. // we could not translate this location. This can happen in the
  385. // case of #line directives.
  386. Diags.Report(diag::note_fe_backend_optimization_remark_invalid_loc)
  387. << Filename << Line << Column;
  388. }
  389. void BackendConsumer::OptimizationRemarkHandler(
  390. const llvm::DiagnosticInfoOptimizationRemark &D) {
  391. // Optimization remarks are active only if the -Rpass flag has a regular
  392. // expression that matches the name of the pass name in \p D.
  393. if (CodeGenOpts.OptimizationRemarkPattern &&
  394. CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
  395. EmitOptimizationRemark(D, diag::remark_fe_backend_optimization_remark);
  396. }
  397. void BackendConsumer::OptimizationRemarkHandler(
  398. const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
  399. // Missed optimization remarks are active only if the -Rpass-missed
  400. // flag has a regular expression that matches the name of the pass
  401. // name in \p D.
  402. if (CodeGenOpts.OptimizationRemarkMissedPattern &&
  403. CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
  404. EmitOptimizationRemark(D,
  405. diag::remark_fe_backend_optimization_remark_missed);
  406. }
  407. void BackendConsumer::OptimizationRemarkHandler(
  408. const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
  409. // Optimization analysis remarks are active only if the -Rpass-analysis
  410. // flag has a regular expression that matches the name of the pass
  411. // name in \p D.
  412. if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
  413. CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
  414. EmitOptimizationRemark(
  415. D, diag::remark_fe_backend_optimization_remark_analysis);
  416. }
  417. /// \brief This function is invoked when the backend needs
  418. /// to report something to the user.
  419. void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
  420. unsigned DiagID = diag::err_fe_inline_asm;
  421. llvm::DiagnosticSeverity Severity = DI.getSeverity();
  422. // Get the diagnostic ID based.
  423. switch (DI.getKind()) {
  424. case llvm::DK_InlineAsm:
  425. if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
  426. return;
  427. ComputeDiagID(Severity, inline_asm, DiagID);
  428. break;
  429. case llvm::DK_StackSize:
  430. if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
  431. return;
  432. ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
  433. break;
  434. case llvm::DK_OptimizationRemark:
  435. // Optimization remarks are always handled completely by this
  436. // handler. There is no generic way of emitting them.
  437. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
  438. return;
  439. case llvm::DK_OptimizationRemarkMissed:
  440. // Optimization remarks are always handled completely by this
  441. // handler. There is no generic way of emitting them.
  442. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
  443. return;
  444. case llvm::DK_OptimizationRemarkAnalysis:
  445. // Optimization remarks are always handled completely by this
  446. // handler. There is no generic way of emitting them.
  447. OptimizationRemarkHandler(
  448. cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
  449. return;
  450. default:
  451. // Plugin IDs are not bound to any value as they are set dynamically.
  452. ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
  453. break;
  454. }
  455. std::string MsgStorage;
  456. {
  457. raw_string_ostream Stream(MsgStorage);
  458. DiagnosticPrinterRawOStream DP(Stream);
  459. DI.print(DP);
  460. }
  461. // Report the backend message using the usual diagnostic mechanism.
  462. FullSourceLoc Loc;
  463. Diags.Report(Loc, DiagID).AddString(MsgStorage);
  464. }
  465. #undef ComputeDiagID
  466. CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
  467. : Act(_Act), LinkModule(nullptr),
  468. VMContext(_VMContext ? _VMContext : new LLVMContext),
  469. OwnsVMContext(!_VMContext) {}
  470. CodeGenAction::~CodeGenAction() {
  471. TheModule.reset();
  472. if (OwnsVMContext)
  473. delete VMContext;
  474. }
  475. bool CodeGenAction::hasIRSupport() const { return true; }
  476. void CodeGenAction::EndSourceFileAction() {
  477. // If the consumer creation failed, do nothing.
  478. if (!getCompilerInstance().hasASTConsumer())
  479. return;
  480. // If we were given a link module, release consumer's ownership of it.
  481. if (LinkModule)
  482. BEConsumer->takeLinkModule();
  483. // Steal the module from the consumer.
  484. TheModule.reset(BEConsumer->takeModule());
  485. }
  486. llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
  487. llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
  488. OwnsVMContext = false;
  489. return VMContext;
  490. }
  491. static raw_ostream *GetOutputStream(CompilerInstance &CI,
  492. StringRef InFile,
  493. BackendAction Action) {
  494. switch (Action) {
  495. case Backend_EmitAssembly:
  496. return CI.createDefaultOutputFile(false, InFile, "s");
  497. case Backend_EmitLL:
  498. return CI.createDefaultOutputFile(false, InFile, "ll");
  499. case Backend_EmitBC:
  500. return CI.createDefaultOutputFile(true, InFile, "bc");
  501. case Backend_EmitNothing:
  502. return nullptr;
  503. case Backend_EmitMCNull:
  504. return CI.createNullOutputFile();
  505. case Backend_EmitObj:
  506. return CI.createDefaultOutputFile(true, InFile, "o");
  507. }
  508. llvm_unreachable("Invalid action!");
  509. }
  510. ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
  511. StringRef InFile) {
  512. BackendAction BA = static_cast<BackendAction>(Act);
  513. std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
  514. if (BA != Backend_EmitNothing && !OS)
  515. return nullptr;
  516. llvm::Module *LinkModuleToUse = LinkModule;
  517. // If we were not given a link module, and the user requested that one be
  518. // loaded from bitcode, do so now.
  519. const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
  520. if (!LinkModuleToUse && !LinkBCFile.empty()) {
  521. std::string ErrorStr;
  522. llvm::MemoryBuffer *BCBuf =
  523. CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
  524. if (!BCBuf) {
  525. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  526. << LinkBCFile << ErrorStr;
  527. return nullptr;
  528. }
  529. ErrorOr<llvm::Module *> ModuleOrErr =
  530. getLazyBitcodeModule(BCBuf, *VMContext);
  531. if (error_code EC = ModuleOrErr.getError()) {
  532. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  533. << LinkBCFile << EC.message();
  534. return nullptr;
  535. }
  536. LinkModuleToUse = ModuleOrErr.get();
  537. }
  538. BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
  539. CI.getTargetOpts(), CI.getLangOpts(),
  540. CI.getFrontendOpts().ShowTimers, InFile,
  541. LinkModuleToUse, OS.release(), *VMContext);
  542. return BEConsumer;
  543. }
  544. void CodeGenAction::ExecuteAction() {
  545. // If this is an IR file, we have to treat it specially.
  546. if (getCurrentFileKind() == IK_LLVM_IR) {
  547. BackendAction BA = static_cast<BackendAction>(Act);
  548. CompilerInstance &CI = getCompilerInstance();
  549. raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
  550. if (BA != Backend_EmitNothing && !OS)
  551. return;
  552. bool Invalid;
  553. SourceManager &SM = CI.getSourceManager();
  554. const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
  555. &Invalid);
  556. if (Invalid)
  557. return;
  558. // FIXME: This is stupid, IRReader shouldn't take ownership.
  559. llvm::MemoryBuffer *MainFileCopy =
  560. llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
  561. getCurrentFile());
  562. llvm::SMDiagnostic Err;
  563. TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
  564. if (!TheModule) {
  565. // Translate from the diagnostic info to the SourceManager location.
  566. SourceLocation Loc = SM.translateFileLineCol(
  567. SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
  568. Err.getColumnNo() + 1);
  569. // Strip off a leading diagnostic code if there is one.
  570. StringRef Msg = Err.getMessage();
  571. if (Msg.startswith("error: "))
  572. Msg = Msg.substr(7);
  573. unsigned DiagID =
  574. CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  575. CI.getDiagnostics().Report(Loc, DiagID) << Msg;
  576. return;
  577. }
  578. const TargetOptions &TargetOpts = CI.getTargetOpts();
  579. if (TheModule->getTargetTriple() != TargetOpts.Triple) {
  580. unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
  581. DiagnosticsEngine::Warning,
  582. "overriding the module target triple with %0");
  583. CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
  584. TheModule->setTargetTriple(TargetOpts.Triple);
  585. }
  586. EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
  587. CI.getLangOpts(), CI.getTarget().getTargetDescription(),
  588. TheModule.get(), BA, OS);
  589. return;
  590. }
  591. // Otherwise follow the normal AST path.
  592. this->ASTFrontendAction::ExecuteAction();
  593. }
  594. //
  595. void EmitAssemblyAction::anchor() { }
  596. EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
  597. : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
  598. void EmitBCAction::anchor() { }
  599. EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
  600. : CodeGenAction(Backend_EmitBC, _VMContext) {}
  601. void EmitLLVMAction::anchor() { }
  602. EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
  603. : CodeGenAction(Backend_EmitLL, _VMContext) {}
  604. void EmitLLVMOnlyAction::anchor() { }
  605. EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
  606. : CodeGenAction(Backend_EmitNothing, _VMContext) {}
  607. void EmitCodeGenOnlyAction::anchor() { }
  608. EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
  609. : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
  610. void EmitObjAction::anchor() { }
  611. EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
  612. : CodeGenAction(Backend_EmitObj, _VMContext) {}