CodeGenAction.cpp 36 KB

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