CodeGenAction.cpp 30 KB

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