CodeGenAction.cpp 29 KB

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