CodeGenAction.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
  52. LinkModules;
  53. // This is here so that the diagnostic printer knows the module a diagnostic
  54. // refers to.
  55. llvm::Module *CurLinkModule = nullptr;
  56. public:
  57. BackendConsumer(
  58. BackendAction Action, DiagnosticsEngine &Diags,
  59. const HeaderSearchOptions &HeaderSearchOpts,
  60. const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
  61. const TargetOptions &TargetOpts, const LangOptions &LangOpts,
  62. bool TimePasses, const std::string &InFile,
  63. const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
  64. raw_pwrite_stream *OS, LLVMContext &C,
  65. CoverageSourceInfo *CoverageInfo = nullptr)
  66. : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
  67. TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
  68. Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
  69. Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
  70. CodeGenOpts, C, CoverageInfo)) {
  71. llvm::TimePassesIsEnabled = TimePasses;
  72. for (auto &I : LinkModules)
  73. this->LinkModules.push_back(
  74. std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
  75. }
  76. llvm::Module *getModule() const { return Gen->GetModule(); }
  77. std::unique_ptr<llvm::Module> takeModule() {
  78. return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
  79. }
  80. void releaseLinkModules() {
  81. for (auto &I : LinkModules)
  82. I.second.release();
  83. }
  84. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  85. Gen->HandleCXXStaticMemberVarInstantiation(VD);
  86. }
  87. void Initialize(ASTContext &Ctx) override {
  88. assert(!Context && "initialized multiple times");
  89. Context = &Ctx;
  90. if (llvm::TimePassesIsEnabled)
  91. LLVMIRGeneration.startTimer();
  92. Gen->Initialize(Ctx);
  93. if (llvm::TimePassesIsEnabled)
  94. LLVMIRGeneration.stopTimer();
  95. }
  96. bool HandleTopLevelDecl(DeclGroupRef D) override {
  97. PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
  98. Context->getSourceManager(),
  99. "LLVM IR generation of declaration");
  100. if (llvm::TimePassesIsEnabled)
  101. LLVMIRGeneration.startTimer();
  102. Gen->HandleTopLevelDecl(D);
  103. if (llvm::TimePassesIsEnabled)
  104. LLVMIRGeneration.stopTimer();
  105. return true;
  106. }
  107. void HandleInlineFunctionDefinition(FunctionDecl *D) override {
  108. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  109. Context->getSourceManager(),
  110. "LLVM IR generation of inline function");
  111. if (llvm::TimePassesIsEnabled)
  112. LLVMIRGeneration.startTimer();
  113. Gen->HandleInlineFunctionDefinition(D);
  114. if (llvm::TimePassesIsEnabled)
  115. LLVMIRGeneration.stopTimer();
  116. }
  117. void HandleTranslationUnit(ASTContext &C) override {
  118. {
  119. PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
  120. if (llvm::TimePassesIsEnabled)
  121. LLVMIRGeneration.startTimer();
  122. Gen->HandleTranslationUnit(C);
  123. if (llvm::TimePassesIsEnabled)
  124. LLVMIRGeneration.stopTimer();
  125. }
  126. // Silently ignore if we weren't initialized for some reason.
  127. if (!getModule())
  128. return;
  129. // Install an inline asm handler so that diagnostics get printed through
  130. // our diagnostics hooks.
  131. LLVMContext &Ctx = getModule()->getContext();
  132. LLVMContext::InlineAsmDiagHandlerTy OldHandler =
  133. Ctx.getInlineAsmDiagnosticHandler();
  134. void *OldContext = Ctx.getInlineAsmDiagnosticContext();
  135. Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
  136. LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
  137. Ctx.getDiagnosticHandler();
  138. void *OldDiagnosticContext = Ctx.getDiagnosticContext();
  139. Ctx.setDiagnosticHandler(DiagnosticHandler, this);
  140. // Link LinkModule into this module if present, preserving its validity.
  141. for (auto &I : LinkModules) {
  142. unsigned LinkFlags = I.first;
  143. CurLinkModule = I.second.get();
  144. if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
  145. return;
  146. }
  147. EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
  148. EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  149. C.getTargetInfo().getDataLayout(),
  150. getModule(), Action, AsmOutStream);
  151. Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
  152. Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
  153. }
  154. void HandleTagDeclDefinition(TagDecl *D) override {
  155. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  156. Context->getSourceManager(),
  157. "LLVM IR generation of declaration");
  158. Gen->HandleTagDeclDefinition(D);
  159. }
  160. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  161. Gen->HandleTagDeclRequiredDefinition(D);
  162. }
  163. void CompleteTentativeDefinition(VarDecl *D) override {
  164. Gen->CompleteTentativeDefinition(D);
  165. }
  166. void AssignInheritanceModel(CXXRecordDecl *RD) override {
  167. Gen->AssignInheritanceModel(RD);
  168. }
  169. void HandleVTable(CXXRecordDecl *RD) override {
  170. Gen->HandleVTable(RD);
  171. }
  172. static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
  173. unsigned LocCookie) {
  174. SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
  175. ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
  176. }
  177. static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
  178. void *Context) {
  179. ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
  180. }
  181. /// Get the best possible source location to represent a diagnostic that
  182. /// may have associated debug info.
  183. const FullSourceLoc
  184. getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
  185. bool &BadDebugInfo, StringRef &Filename,
  186. unsigned &Line, unsigned &Column) const;
  187. void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
  188. SourceLocation LocCookie);
  189. void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
  190. /// \brief Specialized handler for InlineAsm diagnostic.
  191. /// \return True if the diagnostic has been successfully reported, false
  192. /// otherwise.
  193. bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
  194. /// \brief Specialized handler for StackSize diagnostic.
  195. /// \return True if the diagnostic has been successfully reported, false
  196. /// otherwise.
  197. bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
  198. /// \brief Specialized handler for unsupported backend feature diagnostic.
  199. void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
  200. /// \brief Specialized handlers for optimization remarks.
  201. /// Note that these handlers only accept remarks and they always handle
  202. /// them.
  203. void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
  204. unsigned DiagID);
  205. void
  206. OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
  207. void OptimizationRemarkHandler(
  208. const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
  209. void OptimizationRemarkHandler(
  210. const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
  211. void OptimizationRemarkHandler(
  212. const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
  213. void OptimizationRemarkHandler(
  214. const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
  215. void OptimizationFailureHandler(
  216. const llvm::DiagnosticInfoOptimizationFailure &D);
  217. };
  218. void BackendConsumer::anchor() {}
  219. }
  220. /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
  221. /// buffer to be a valid FullSourceLoc.
  222. static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
  223. SourceManager &CSM) {
  224. // Get both the clang and llvm source managers. The location is relative to
  225. // a memory buffer that the LLVM Source Manager is handling, we need to add
  226. // a copy to the Clang source manager.
  227. const llvm::SourceMgr &LSM = *D.getSourceMgr();
  228. // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
  229. // already owns its one and clang::SourceManager wants to own its one.
  230. const MemoryBuffer *LBuf =
  231. LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
  232. // Create the copy and transfer ownership to clang::SourceManager.
  233. // TODO: Avoid copying files into memory.
  234. std::unique_ptr<llvm::MemoryBuffer> CBuf =
  235. llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
  236. LBuf->getBufferIdentifier());
  237. // FIXME: Keep a file ID map instead of creating new IDs for each location.
  238. FileID FID = CSM.createFileID(std::move(CBuf));
  239. // Translate the offset into the file.
  240. unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
  241. SourceLocation NewLoc =
  242. CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
  243. return FullSourceLoc(NewLoc, CSM);
  244. }
  245. /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
  246. /// error parsing inline asm. The SMDiagnostic indicates the error relative to
  247. /// the temporary memory buffer that the inline asm parser has set up.
  248. void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
  249. SourceLocation LocCookie) {
  250. // There are a couple of different kinds of errors we could get here. First,
  251. // we re-format the SMDiagnostic in terms of a clang diagnostic.
  252. // Strip "error: " off the start of the message string.
  253. StringRef Message = D.getMessage();
  254. if (Message.startswith("error: "))
  255. Message = Message.substr(7);
  256. // If the SMDiagnostic has an inline asm source location, translate it.
  257. FullSourceLoc Loc;
  258. if (D.getLoc() != SMLoc())
  259. Loc = ConvertBackendLocation(D, Context->getSourceManager());
  260. unsigned DiagID;
  261. switch (D.getKind()) {
  262. case llvm::SourceMgr::DK_Error:
  263. DiagID = diag::err_fe_inline_asm;
  264. break;
  265. case llvm::SourceMgr::DK_Warning:
  266. DiagID = diag::warn_fe_inline_asm;
  267. break;
  268. case llvm::SourceMgr::DK_Note:
  269. DiagID = diag::note_fe_inline_asm;
  270. break;
  271. }
  272. // If this problem has clang-level source location information, report the
  273. // issue in the source with a note showing the instantiated
  274. // code.
  275. if (LocCookie.isValid()) {
  276. Diags.Report(LocCookie, DiagID).AddString(Message);
  277. if (D.getLoc().isValid()) {
  278. DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
  279. // Convert the SMDiagnostic ranges into SourceRange and attach them
  280. // to the diagnostic.
  281. for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
  282. unsigned Column = D.getColumnNo();
  283. B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
  284. Loc.getLocWithOffset(Range.second - Column));
  285. }
  286. }
  287. return;
  288. }
  289. // Otherwise, report the backend issue as occurring in the generated .s file.
  290. // If Loc is invalid, we still need to report the issue, it just gets no
  291. // location info.
  292. Diags.Report(Loc, DiagID).AddString(Message);
  293. }
  294. #define ComputeDiagID(Severity, GroupName, DiagID) \
  295. do { \
  296. switch (Severity) { \
  297. case llvm::DS_Error: \
  298. DiagID = diag::err_fe_##GroupName; \
  299. break; \
  300. case llvm::DS_Warning: \
  301. DiagID = diag::warn_fe_##GroupName; \
  302. break; \
  303. case llvm::DS_Remark: \
  304. llvm_unreachable("'remark' severity not expected"); \
  305. break; \
  306. case llvm::DS_Note: \
  307. DiagID = diag::note_fe_##GroupName; \
  308. break; \
  309. } \
  310. } while (false)
  311. #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
  312. do { \
  313. switch (Severity) { \
  314. case llvm::DS_Error: \
  315. DiagID = diag::err_fe_##GroupName; \
  316. break; \
  317. case llvm::DS_Warning: \
  318. DiagID = diag::warn_fe_##GroupName; \
  319. break; \
  320. case llvm::DS_Remark: \
  321. DiagID = diag::remark_fe_##GroupName; \
  322. break; \
  323. case llvm::DS_Note: \
  324. DiagID = diag::note_fe_##GroupName; \
  325. break; \
  326. } \
  327. } while (false)
  328. bool
  329. BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
  330. unsigned DiagID;
  331. ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
  332. std::string Message = D.getMsgStr().str();
  333. // If this problem has clang-level source location information, report the
  334. // issue as being a problem in the source with a note showing the instantiated
  335. // code.
  336. SourceLocation LocCookie =
  337. SourceLocation::getFromRawEncoding(D.getLocCookie());
  338. if (LocCookie.isValid())
  339. Diags.Report(LocCookie, DiagID).AddString(Message);
  340. else {
  341. // Otherwise, report the backend diagnostic as occurring in the generated
  342. // .s file.
  343. // If Loc is invalid, we still need to report the diagnostic, it just gets
  344. // no location info.
  345. FullSourceLoc Loc;
  346. Diags.Report(Loc, DiagID).AddString(Message);
  347. }
  348. // We handled all the possible severities.
  349. return true;
  350. }
  351. bool
  352. BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
  353. if (D.getSeverity() != llvm::DS_Warning)
  354. // For now, the only support we have for StackSize diagnostic is warning.
  355. // We do not know how to format other severities.
  356. return false;
  357. if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
  358. Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
  359. diag::warn_fe_frame_larger_than)
  360. << D.getStackSize() << Decl::castToDeclContext(ND);
  361. return true;
  362. }
  363. return false;
  364. }
  365. const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
  366. const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
  367. unsigned &Line, unsigned &Column) const {
  368. SourceManager &SourceMgr = Context->getSourceManager();
  369. FileManager &FileMgr = SourceMgr.getFileManager();
  370. SourceLocation DILoc;
  371. if (D.isLocationAvailable()) {
  372. D.getLocation(&Filename, &Line, &Column);
  373. const FileEntry *FE = FileMgr.getFile(Filename);
  374. if (FE && Line > 0) {
  375. // If -gcolumn-info was not used, Column will be 0. This upsets the
  376. // source manager, so pass 1 if Column is not set.
  377. DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
  378. }
  379. BadDebugInfo = DILoc.isInvalid();
  380. }
  381. // If a location isn't available, try to approximate it using the associated
  382. // function definition. We use the definition's right brace to differentiate
  383. // from diagnostics that genuinely relate to the function itself.
  384. FullSourceLoc Loc(DILoc, SourceMgr);
  385. if (Loc.isInvalid())
  386. if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
  387. Loc = FD->getASTContext().getFullLoc(FD->getLocation());
  388. if (DILoc.isInvalid() && D.isLocationAvailable())
  389. // If we were not able to translate the file:line:col information
  390. // back to a SourceLocation, at least emit a note stating that
  391. // we could not translate this location. This can happen in the
  392. // case of #line directives.
  393. Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
  394. << Filename << Line << Column;
  395. return Loc;
  396. }
  397. void BackendConsumer::UnsupportedDiagHandler(
  398. const llvm::DiagnosticInfoUnsupported &D) {
  399. // We only support errors.
  400. assert(D.getSeverity() == llvm::DS_Error);
  401. StringRef Filename;
  402. unsigned Line, Column;
  403. bool BadDebugInfo;
  404. FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
  405. Line, Column);
  406. Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
  407. if (BadDebugInfo)
  408. // If we were not able to translate the file:line:col information
  409. // back to a SourceLocation, at least emit a note stating that
  410. // we could not translate this location. This can happen in the
  411. // case of #line directives.
  412. Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
  413. << Filename << Line << Column;
  414. }
  415. void BackendConsumer::EmitOptimizationMessage(
  416. const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
  417. // We only support warnings and remarks.
  418. assert(D.getSeverity() == llvm::DS_Remark ||
  419. D.getSeverity() == llvm::DS_Warning);
  420. StringRef Filename;
  421. unsigned Line, Column;
  422. bool BadDebugInfo = false;
  423. FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
  424. Line, Column);
  425. Diags.Report(Loc, DiagID)
  426. << AddFlagValue(D.getPassName() ? D.getPassName() : "")
  427. << D.getMsg().str();
  428. if (BadDebugInfo)
  429. // If we were not able to translate the file:line:col information
  430. // back to a SourceLocation, at least emit a note stating that
  431. // we could not translate this location. This can happen in the
  432. // case of #line directives.
  433. Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
  434. << Filename << Line << Column;
  435. }
  436. void BackendConsumer::OptimizationRemarkHandler(
  437. const llvm::DiagnosticInfoOptimizationRemark &D) {
  438. // Optimization remarks are active only if the -Rpass flag has a regular
  439. // expression that matches the name of the pass name in \p D.
  440. if (CodeGenOpts.OptimizationRemarkPattern &&
  441. CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
  442. EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
  443. }
  444. void BackendConsumer::OptimizationRemarkHandler(
  445. const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
  446. // Missed optimization remarks are active only if the -Rpass-missed
  447. // flag has a regular expression that matches the name of the pass
  448. // name in \p D.
  449. if (CodeGenOpts.OptimizationRemarkMissedPattern &&
  450. CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
  451. EmitOptimizationMessage(D,
  452. diag::remark_fe_backend_optimization_remark_missed);
  453. }
  454. void BackendConsumer::OptimizationRemarkHandler(
  455. const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
  456. // Optimization analysis remarks are active if the pass name is set to
  457. // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
  458. // regular expression that matches the name of the pass name in \p D.
  459. if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
  460. (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
  461. CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
  462. EmitOptimizationMessage(
  463. D, diag::remark_fe_backend_optimization_remark_analysis);
  464. }
  465. void BackendConsumer::OptimizationRemarkHandler(
  466. const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
  467. // Optimization analysis remarks are active if the pass name is set to
  468. // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
  469. // regular expression that matches the name of the pass name in \p D.
  470. if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
  471. (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
  472. CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
  473. EmitOptimizationMessage(
  474. D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
  475. }
  476. void BackendConsumer::OptimizationRemarkHandler(
  477. const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
  478. // Optimization analysis remarks are active if the pass name is set to
  479. // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
  480. // regular expression that matches the name of the pass name in \p D.
  481. if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
  482. (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
  483. CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
  484. EmitOptimizationMessage(
  485. D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
  486. }
  487. void BackendConsumer::OptimizationFailureHandler(
  488. const llvm::DiagnosticInfoOptimizationFailure &D) {
  489. EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
  490. }
  491. /// \brief This function is invoked when the backend needs
  492. /// to report something to the user.
  493. void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
  494. unsigned DiagID = diag::err_fe_inline_asm;
  495. llvm::DiagnosticSeverity Severity = DI.getSeverity();
  496. // Get the diagnostic ID based.
  497. switch (DI.getKind()) {
  498. case llvm::DK_InlineAsm:
  499. if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
  500. return;
  501. ComputeDiagID(Severity, inline_asm, DiagID);
  502. break;
  503. case llvm::DK_StackSize:
  504. if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
  505. return;
  506. ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
  507. break;
  508. case DK_Linker:
  509. assert(CurLinkModule);
  510. // FIXME: stop eating the warnings and notes.
  511. if (Severity != DS_Error)
  512. return;
  513. DiagID = diag::err_fe_cannot_link_module;
  514. break;
  515. case llvm::DK_OptimizationRemark:
  516. // Optimization remarks are always handled completely by this
  517. // handler. There is no generic way of emitting them.
  518. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
  519. return;
  520. case llvm::DK_OptimizationRemarkMissed:
  521. // Optimization remarks are always handled completely by this
  522. // handler. There is no generic way of emitting them.
  523. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
  524. return;
  525. case llvm::DK_OptimizationRemarkAnalysis:
  526. // Optimization remarks are always handled completely by this
  527. // handler. There is no generic way of emitting them.
  528. OptimizationRemarkHandler(
  529. cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
  530. return;
  531. case llvm::DK_OptimizationRemarkAnalysisFPCommute:
  532. // Optimization remarks are always handled completely by this
  533. // handler. There is no generic way of emitting them.
  534. OptimizationRemarkHandler(
  535. cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
  536. return;
  537. case llvm::DK_OptimizationRemarkAnalysisAliasing:
  538. // Optimization remarks are always handled completely by this
  539. // handler. There is no generic way of emitting them.
  540. OptimizationRemarkHandler(
  541. cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
  542. return;
  543. case llvm::DK_OptimizationFailure:
  544. // Optimization failures are always handled completely by this
  545. // handler.
  546. OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
  547. return;
  548. case llvm::DK_Unsupported:
  549. UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
  550. return;
  551. default:
  552. // Plugin IDs are not bound to any value as they are set dynamically.
  553. ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
  554. break;
  555. }
  556. std::string MsgStorage;
  557. {
  558. raw_string_ostream Stream(MsgStorage);
  559. DiagnosticPrinterRawOStream DP(Stream);
  560. DI.print(DP);
  561. }
  562. if (DiagID == diag::err_fe_cannot_link_module) {
  563. Diags.Report(diag::err_fe_cannot_link_module)
  564. << CurLinkModule->getModuleIdentifier() << MsgStorage;
  565. return;
  566. }
  567. // Report the backend message using the usual diagnostic mechanism.
  568. FullSourceLoc Loc;
  569. Diags.Report(Loc, DiagID).AddString(MsgStorage);
  570. }
  571. #undef ComputeDiagID
  572. CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
  573. : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
  574. OwnsVMContext(!_VMContext) {}
  575. CodeGenAction::~CodeGenAction() {
  576. TheModule.reset();
  577. if (OwnsVMContext)
  578. delete VMContext;
  579. }
  580. bool CodeGenAction::hasIRSupport() const { return true; }
  581. void CodeGenAction::EndSourceFileAction() {
  582. // If the consumer creation failed, do nothing.
  583. if (!getCompilerInstance().hasASTConsumer())
  584. return;
  585. // Take back ownership of link modules we passed to consumer.
  586. if (!LinkModules.empty())
  587. BEConsumer->releaseLinkModules();
  588. // Steal the module from the consumer.
  589. TheModule = BEConsumer->takeModule();
  590. }
  591. std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
  592. return std::move(TheModule);
  593. }
  594. llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
  595. OwnsVMContext = false;
  596. return VMContext;
  597. }
  598. static raw_pwrite_stream *
  599. GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
  600. switch (Action) {
  601. case Backend_EmitAssembly:
  602. return CI.createDefaultOutputFile(false, InFile, "s");
  603. case Backend_EmitLL:
  604. return CI.createDefaultOutputFile(false, InFile, "ll");
  605. case Backend_EmitBC:
  606. return CI.createDefaultOutputFile(true, InFile, "bc");
  607. case Backend_EmitNothing:
  608. return nullptr;
  609. case Backend_EmitMCNull:
  610. return CI.createNullOutputFile();
  611. case Backend_EmitObj:
  612. return CI.createDefaultOutputFile(true, InFile, "o");
  613. }
  614. llvm_unreachable("Invalid action!");
  615. }
  616. std::unique_ptr<ASTConsumer>
  617. CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  618. BackendAction BA = static_cast<BackendAction>(Act);
  619. raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
  620. if (BA != Backend_EmitNothing && !OS)
  621. return nullptr;
  622. // Load bitcode modules to link with, if we need to.
  623. if (LinkModules.empty())
  624. for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
  625. const std::string &LinkBCFile = I.second;
  626. auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
  627. if (!BCBuf) {
  628. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  629. << LinkBCFile << BCBuf.getError().message();
  630. LinkModules.clear();
  631. return nullptr;
  632. }
  633. ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
  634. getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
  635. if (std::error_code EC = ModuleOrErr.getError()) {
  636. CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
  637. << EC.message();
  638. LinkModules.clear();
  639. return nullptr;
  640. }
  641. addLinkModule(ModuleOrErr.get().release(), I.first);
  642. }
  643. CoverageSourceInfo *CoverageInfo = nullptr;
  644. // Add the preprocessor callback only when the coverage mapping is generated.
  645. if (CI.getCodeGenOpts().CoverageMapping) {
  646. CoverageInfo = new CoverageSourceInfo;
  647. CI.getPreprocessor().addPPCallbacks(
  648. std::unique_ptr<PPCallbacks>(CoverageInfo));
  649. }
  650. std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
  651. BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
  652. CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
  653. CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
  654. OS, *VMContext, CoverageInfo));
  655. BEConsumer = Result.get();
  656. return std::move(Result);
  657. }
  658. static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
  659. void *Context,
  660. unsigned LocCookie) {
  661. SM.print(nullptr, llvm::errs());
  662. auto Diags = static_cast<DiagnosticsEngine *>(Context);
  663. unsigned DiagID;
  664. switch (SM.getKind()) {
  665. case llvm::SourceMgr::DK_Error:
  666. DiagID = diag::err_fe_inline_asm;
  667. break;
  668. case llvm::SourceMgr::DK_Warning:
  669. DiagID = diag::warn_fe_inline_asm;
  670. break;
  671. case llvm::SourceMgr::DK_Note:
  672. DiagID = diag::note_fe_inline_asm;
  673. break;
  674. }
  675. Diags->Report(DiagID).AddString("cannot compile inline asm");
  676. }
  677. void CodeGenAction::ExecuteAction() {
  678. // If this is an IR file, we have to treat it specially.
  679. if (getCurrentFileKind() == IK_LLVM_IR) {
  680. BackendAction BA = static_cast<BackendAction>(Act);
  681. CompilerInstance &CI = getCompilerInstance();
  682. raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
  683. if (BA != Backend_EmitNothing && !OS)
  684. return;
  685. bool Invalid;
  686. SourceManager &SM = CI.getSourceManager();
  687. FileID FID = SM.getMainFileID();
  688. llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
  689. if (Invalid)
  690. return;
  691. // For ThinLTO backend invocations, ensure that the context
  692. // merges types based on ODR identifiers.
  693. if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
  694. VMContext->enableDebugTypeODRUniquing();
  695. llvm::SMDiagnostic Err;
  696. TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
  697. if (!TheModule) {
  698. // Translate from the diagnostic info to the SourceManager location if
  699. // available.
  700. // TODO: Unify this with ConvertBackendLocation()
  701. SourceLocation Loc;
  702. if (Err.getLineNo() > 0) {
  703. assert(Err.getColumnNo() >= 0);
  704. Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
  705. Err.getLineNo(), Err.getColumnNo() + 1);
  706. }
  707. // Strip off a leading diagnostic code if there is one.
  708. StringRef Msg = Err.getMessage();
  709. if (Msg.startswith("error: "))
  710. Msg = Msg.substr(7);
  711. unsigned DiagID =
  712. CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  713. CI.getDiagnostics().Report(Loc, DiagID) << Msg;
  714. return;
  715. }
  716. const TargetOptions &TargetOpts = CI.getTargetOpts();
  717. if (TheModule->getTargetTriple() != TargetOpts.Triple) {
  718. CI.getDiagnostics().Report(SourceLocation(),
  719. diag::warn_fe_override_module)
  720. << TargetOpts.Triple;
  721. TheModule->setTargetTriple(TargetOpts.Triple);
  722. }
  723. EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
  724. MainFile->getMemBufferRef());
  725. LLVMContext &Ctx = TheModule->getContext();
  726. Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
  727. &CI.getDiagnostics());
  728. EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
  729. CI.getLangOpts(), CI.getTarget().getDataLayout(),
  730. TheModule.get(), BA, OS);
  731. return;
  732. }
  733. // Otherwise follow the normal AST path.
  734. this->ASTFrontendAction::ExecuteAction();
  735. }
  736. //
  737. void EmitAssemblyAction::anchor() { }
  738. EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
  739. : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
  740. void EmitBCAction::anchor() { }
  741. EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
  742. : CodeGenAction(Backend_EmitBC, _VMContext) {}
  743. void EmitLLVMAction::anchor() { }
  744. EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
  745. : CodeGenAction(Backend_EmitLL, _VMContext) {}
  746. void EmitLLVMOnlyAction::anchor() { }
  747. EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
  748. : CodeGenAction(Backend_EmitNothing, _VMContext) {}
  749. void EmitCodeGenOnlyAction::anchor() { }
  750. EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
  751. : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
  752. void EmitObjAction::anchor() { }
  753. EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
  754. : CodeGenAction(Backend_EmitObj, _VMContext) {}