CodeGenAction.cpp 41 KB

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