CodeGenAction.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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/DiagnosticFrontend.h"
  17. #include "clang/Basic/FileManager.h"
  18. #include "clang/Basic/LangStandard.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/CodeGen/BackendUtil.h"
  22. #include "clang/CodeGen/ModuleBuilder.h"
  23. #include "clang/Driver/DriverDiagnostic.h"
  24. #include "clang/Frontend/CompilerInstance.h"
  25. #include "clang/Frontend/FrontendDiagnostic.h"
  26. #include "clang/Lex/Preprocessor.h"
  27. #include "llvm/ADT/Hashing.h"
  28. #include "llvm/Bitcode/BitcodeReader.h"
  29. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  30. #include "llvm/Demangle/Demangle.h"
  31. #include "llvm/IR/DebugInfo.h"
  32. #include "llvm/IR/DiagnosticInfo.h"
  33. #include "llvm/IR/DiagnosticPrinter.h"
  34. #include "llvm/IR/GlobalValue.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/IR/LLVMRemarkStreamer.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/IRReader/IRReader.h"
  39. #include "llvm/LTO/LTOBackend.h"
  40. #include "llvm/Linker/Linker.h"
  41. #include "llvm/Pass.h"
  42. #include "llvm/Support/MemoryBuffer.h"
  43. #include "llvm/Support/SourceMgr.h"
  44. #include "llvm/Support/TimeProfiler.h"
  45. #include "llvm/Support/Timer.h"
  46. #include "llvm/Support/ToolOutputFile.h"
  47. #include "llvm/Support/YAMLTraits.h"
  48. #include "llvm/Transforms/IPO/Internalize.h"
  49. #include <memory>
  50. #include <optional>
  51. using namespace clang;
  52. using namespace llvm;
  53. #define DEBUG_TYPE "codegenaction"
  54. namespace clang {
  55. class BackendConsumer;
  56. class ClangDiagnosticHandler final : public DiagnosticHandler {
  57. public:
  58. ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
  59. : CodeGenOpts(CGOpts), BackendCon(BCon) {}
  60. bool handleDiagnostics(const DiagnosticInfo &DI) override;
  61. bool isAnalysisRemarkEnabled(StringRef PassName) const override {
  62. return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
  63. }
  64. bool isMissedOptRemarkEnabled(StringRef PassName) const override {
  65. return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
  66. }
  67. bool isPassedOptRemarkEnabled(StringRef PassName) const override {
  68. return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
  69. }
  70. bool isAnyRemarkEnabled() const override {
  71. return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
  72. CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
  73. CodeGenOpts.OptimizationRemark.hasValidPattern();
  74. }
  75. private:
  76. const CodeGenOptions &CodeGenOpts;
  77. BackendConsumer *BackendCon;
  78. };
  79. static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
  80. const CodeGenOptions CodeGenOpts) {
  81. handleAllErrors(
  82. std::move(E),
  83. [&](const LLVMRemarkSetupFileError &E) {
  84. Diags.Report(diag::err_cannot_open_file)
  85. << CodeGenOpts.OptRecordFile << E.message();
  86. },
  87. [&](const LLVMRemarkSetupPatternError &E) {
  88. Diags.Report(diag::err_drv_optimization_remark_pattern)
  89. << E.message() << CodeGenOpts.OptRecordPasses;
  90. },
  91. [&](const LLVMRemarkSetupFormatError &E) {
  92. Diags.Report(diag::err_drv_optimization_remark_format)
  93. << CodeGenOpts.OptRecordFormat;
  94. });
  95. }
  96. class BackendConsumer : public ASTConsumer {
  97. using LinkModule = CodeGenAction::LinkModule;
  98. virtual void anchor();
  99. DiagnosticsEngine &Diags;
  100. BackendAction Action;
  101. const HeaderSearchOptions &HeaderSearchOpts;
  102. const CodeGenOptions &CodeGenOpts;
  103. const TargetOptions &TargetOpts;
  104. const LangOptions &LangOpts;
  105. std::unique_ptr<raw_pwrite_stream> AsmOutStream;
  106. ASTContext *Context;
  107. Timer LLVMIRGeneration;
  108. unsigned LLVMIRGenerationRefCount;
  109. /// True if we've finished generating IR. This prevents us from generating
  110. /// additional LLVM IR after emitting output in HandleTranslationUnit. This
  111. /// can happen when Clang plugins trigger additional AST deserialization.
  112. bool IRGenFinished = false;
  113. bool TimerIsEnabled = false;
  114. std::unique_ptr<CodeGenerator> Gen;
  115. SmallVector<LinkModule, 4> LinkModules;
  116. // A map from mangled names to their function's source location, used for
  117. // backend diagnostics as the Clang AST may be unavailable. We actually use
  118. // the mangled name's hash as the key because mangled names can be very
  119. // long and take up lots of space. Using a hash can cause name collision,
  120. // but that is rare and the consequences are pointing to a wrong source
  121. // location which is not severe. This is a vector instead of an actual map
  122. // because we optimize for time building this map rather than time
  123. // retrieving an entry, as backend diagnostics are uncommon.
  124. std::vector<std::pair<llvm::hash_code, FullSourceLoc>>
  125. ManglingFullSourceLocs;
  126. // This is here so that the diagnostic printer knows the module a diagnostic
  127. // refers to.
  128. llvm::Module *CurLinkModule = nullptr;
  129. public:
  130. BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
  131. IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
  132. const HeaderSearchOptions &HeaderSearchOpts,
  133. const PreprocessorOptions &PPOpts,
  134. const CodeGenOptions &CodeGenOpts,
  135. const TargetOptions &TargetOpts,
  136. const LangOptions &LangOpts, const std::string &InFile,
  137. SmallVector<LinkModule, 4> LinkModules,
  138. std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
  139. CoverageSourceInfo *CoverageInfo = nullptr)
  140. : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
  141. CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
  142. AsmOutStream(std::move(OS)), Context(nullptr),
  143. LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
  144. LLVMIRGenerationRefCount(0),
  145. Gen(CreateLLVMCodeGen(Diags, InFile, std::move(FS), HeaderSearchOpts,
  146. PPOpts, CodeGenOpts, C, CoverageInfo)),
  147. LinkModules(std::move(LinkModules)) {
  148. TimerIsEnabled = CodeGenOpts.TimePasses;
  149. llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
  150. llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
  151. }
  152. // This constructor is used in installing an empty BackendConsumer
  153. // to use the clang diagnostic handler for IR input files. It avoids
  154. // initializing the OS field.
  155. BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
  156. IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
  157. const HeaderSearchOptions &HeaderSearchOpts,
  158. const PreprocessorOptions &PPOpts,
  159. const CodeGenOptions &CodeGenOpts,
  160. const TargetOptions &TargetOpts,
  161. const LangOptions &LangOpts, llvm::Module *Module,
  162. SmallVector<LinkModule, 4> LinkModules, LLVMContext &C,
  163. CoverageSourceInfo *CoverageInfo = nullptr)
  164. : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
  165. CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
  166. Context(nullptr),
  167. LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
  168. LLVMIRGenerationRefCount(0),
  169. Gen(CreateLLVMCodeGen(Diags, "", std::move(FS), HeaderSearchOpts,
  170. PPOpts, CodeGenOpts, C, CoverageInfo)),
  171. LinkModules(std::move(LinkModules)), CurLinkModule(Module) {
  172. TimerIsEnabled = CodeGenOpts.TimePasses;
  173. llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
  174. llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
  175. }
  176. llvm::Module *getModule() const { return Gen->GetModule(); }
  177. std::unique_ptr<llvm::Module> takeModule() {
  178. return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
  179. }
  180. CodeGenerator *getCodeGenerator() { return Gen.get(); }
  181. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  182. Gen->HandleCXXStaticMemberVarInstantiation(VD);
  183. }
  184. void Initialize(ASTContext &Ctx) override {
  185. assert(!Context && "initialized multiple times");
  186. Context = &Ctx;
  187. if (TimerIsEnabled)
  188. LLVMIRGeneration.startTimer();
  189. Gen->Initialize(Ctx);
  190. if (TimerIsEnabled)
  191. LLVMIRGeneration.stopTimer();
  192. }
  193. bool HandleTopLevelDecl(DeclGroupRef D) override {
  194. PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
  195. Context->getSourceManager(),
  196. "LLVM IR generation of declaration");
  197. // Recurse.
  198. if (TimerIsEnabled) {
  199. LLVMIRGenerationRefCount += 1;
  200. if (LLVMIRGenerationRefCount == 1)
  201. LLVMIRGeneration.startTimer();
  202. }
  203. Gen->HandleTopLevelDecl(D);
  204. if (TimerIsEnabled) {
  205. LLVMIRGenerationRefCount -= 1;
  206. if (LLVMIRGenerationRefCount == 0)
  207. LLVMIRGeneration.stopTimer();
  208. }
  209. return true;
  210. }
  211. void HandleInlineFunctionDefinition(FunctionDecl *D) override {
  212. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  213. Context->getSourceManager(),
  214. "LLVM IR generation of inline function");
  215. if (TimerIsEnabled)
  216. LLVMIRGeneration.startTimer();
  217. Gen->HandleInlineFunctionDefinition(D);
  218. if (TimerIsEnabled)
  219. LLVMIRGeneration.stopTimer();
  220. }
  221. void HandleInterestingDecl(DeclGroupRef D) override {
  222. // Ignore interesting decls from the AST reader after IRGen is finished.
  223. if (!IRGenFinished)
  224. HandleTopLevelDecl(D);
  225. }
  226. // Links each entry in LinkModules into our module. Returns true on error.
  227. bool LinkInModules() {
  228. for (auto &LM : LinkModules) {
  229. if (LM.PropagateAttrs)
  230. for (Function &F : *LM.Module) {
  231. // Skip intrinsics. Keep consistent with how intrinsics are created
  232. // in LLVM IR.
  233. if (F.isIntrinsic())
  234. continue;
  235. Gen->CGM().addDefaultFunctionDefinitionAttributes(F);
  236. }
  237. CurLinkModule = LM.Module.get();
  238. bool Err;
  239. if (LM.Internalize) {
  240. Err = Linker::linkModules(
  241. *getModule(), std::move(LM.Module), LM.LinkFlags,
  242. [](llvm::Module &M, const llvm::StringSet<> &GVS) {
  243. internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
  244. return !GV.hasName() || (GVS.count(GV.getName()) == 0);
  245. });
  246. });
  247. } else {
  248. Err = Linker::linkModules(*getModule(), std::move(LM.Module),
  249. LM.LinkFlags);
  250. }
  251. if (Err)
  252. return true;
  253. }
  254. return false; // success
  255. }
  256. void HandleTranslationUnit(ASTContext &C) override {
  257. {
  258. llvm::TimeTraceScope TimeScope("Frontend");
  259. PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
  260. if (TimerIsEnabled) {
  261. LLVMIRGenerationRefCount += 1;
  262. if (LLVMIRGenerationRefCount == 1)
  263. LLVMIRGeneration.startTimer();
  264. }
  265. Gen->HandleTranslationUnit(C);
  266. if (TimerIsEnabled) {
  267. LLVMIRGenerationRefCount -= 1;
  268. if (LLVMIRGenerationRefCount == 0)
  269. LLVMIRGeneration.stopTimer();
  270. }
  271. IRGenFinished = true;
  272. }
  273. // Silently ignore if we weren't initialized for some reason.
  274. if (!getModule())
  275. return;
  276. LLVMContext &Ctx = getModule()->getContext();
  277. std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
  278. Ctx.getDiagnosticHandler();
  279. Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
  280. CodeGenOpts, this));
  281. Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
  282. setupLLVMOptimizationRemarks(
  283. Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
  284. CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
  285. CodeGenOpts.DiagnosticsHotnessThreshold);
  286. if (Error E = OptRecordFileOrErr.takeError()) {
  287. reportOptRecordError(std::move(E), Diags, CodeGenOpts);
  288. return;
  289. }
  290. std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
  291. std::move(*OptRecordFileOrErr);
  292. if (OptRecordFile &&
  293. CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
  294. Ctx.setDiagnosticsHotnessRequested(true);
  295. if (CodeGenOpts.MisExpect) {
  296. Ctx.setMisExpectWarningRequested(true);
  297. }
  298. if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
  299. Ctx.setDiagnosticsMisExpectTolerance(
  300. CodeGenOpts.DiagnosticsMisExpectTolerance);
  301. }
  302. // Link each LinkModule into our module.
  303. if (LinkInModules())
  304. return;
  305. for (auto &F : getModule()->functions()) {
  306. if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
  307. auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
  308. // TODO: use a fast content hash when available.
  309. auto NameHash = llvm::hash_value(F.getName());
  310. ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
  311. }
  312. }
  313. if (CodeGenOpts.ClearASTBeforeBackend) {
  314. LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
  315. // Access to the AST is no longer available after this.
  316. // Other things that the ASTContext manages are still available, e.g.
  317. // the SourceManager. It'd be nice if we could separate out all the
  318. // things in ASTContext used after this point and null out the
  319. // ASTContext, but too many various parts of the ASTContext are still
  320. // used in various parts.
  321. C.cleanup();
  322. C.getAllocator().Reset();
  323. }
  324. EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
  325. EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
  326. LangOpts, C.getTargetInfo().getDataLayoutString(),
  327. getModule(), Action, std::move(AsmOutStream));
  328. Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
  329. if (OptRecordFile)
  330. OptRecordFile->keep();
  331. }
  332. void HandleTagDeclDefinition(TagDecl *D) override {
  333. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  334. Context->getSourceManager(),
  335. "LLVM IR generation of declaration");
  336. Gen->HandleTagDeclDefinition(D);
  337. }
  338. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  339. Gen->HandleTagDeclRequiredDefinition(D);
  340. }
  341. void CompleteTentativeDefinition(VarDecl *D) override {
  342. Gen->CompleteTentativeDefinition(D);
  343. }
  344. void CompleteExternalDeclaration(VarDecl *D) override {
  345. Gen->CompleteExternalDeclaration(D);
  346. }
  347. void AssignInheritanceModel(CXXRecordDecl *RD) override {
  348. Gen->AssignInheritanceModel(RD);
  349. }
  350. void HandleVTable(CXXRecordDecl *RD) override {
  351. Gen->HandleVTable(RD);
  352. }
  353. /// Get the best possible source location to represent a diagnostic that
  354. /// may have associated debug info.
  355. const FullSourceLoc
  356. getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
  357. bool &BadDebugInfo, StringRef &Filename,
  358. unsigned &Line, unsigned &Column) const;
  359. std::optional<FullSourceLoc>
  360. getFunctionSourceLocation(const Function &F) const;
  361. void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
  362. /// Specialized handler for InlineAsm diagnostic.
  363. /// \return True if the diagnostic has been successfully reported, false
  364. /// otherwise.
  365. bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
  366. /// Specialized handler for diagnostics reported using SMDiagnostic.
  367. void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D);
  368. /// Specialized handler for StackSize diagnostic.
  369. /// \return True if the diagnostic has been successfully reported, false
  370. /// otherwise.
  371. bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
  372. /// Specialized handler for ResourceLimit diagnostic.
  373. /// \return True if the diagnostic has been successfully reported, false
  374. /// otherwise.
  375. bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D);
  376. /// Specialized handler for unsupported backend feature diagnostic.
  377. void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
  378. /// Specialized handlers for optimization remarks.
  379. /// Note that these handlers only accept remarks and they always handle
  380. /// them.
  381. void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
  382. unsigned DiagID);
  383. void
  384. OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
  385. void OptimizationRemarkHandler(
  386. const llvm::OptimizationRemarkAnalysisFPCommute &D);
  387. void OptimizationRemarkHandler(
  388. const llvm::OptimizationRemarkAnalysisAliasing &D);
  389. void OptimizationFailureHandler(
  390. const llvm::DiagnosticInfoOptimizationFailure &D);
  391. void DontCallDiagHandler(const DiagnosticInfoDontCall &D);
  392. /// Specialized handler for misexpect warnings.
  393. /// Note that misexpect remarks are emitted through ORE
  394. void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D);
  395. };
  396. void BackendConsumer::anchor() {}
  397. }
  398. bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
  399. BackendCon->DiagnosticHandlerImpl(DI);
  400. return true;
  401. }
  402. /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
  403. /// buffer to be a valid FullSourceLoc.
  404. static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
  405. SourceManager &CSM) {
  406. // Get both the clang and llvm source managers. The location is relative to
  407. // a memory buffer that the LLVM Source Manager is handling, we need to add
  408. // a copy to the Clang source manager.
  409. const llvm::SourceMgr &LSM = *D.getSourceMgr();
  410. // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
  411. // already owns its one and clang::SourceManager wants to own its one.
  412. const MemoryBuffer *LBuf =
  413. LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
  414. // Create the copy and transfer ownership to clang::SourceManager.
  415. // TODO: Avoid copying files into memory.
  416. std::unique_ptr<llvm::MemoryBuffer> CBuf =
  417. llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
  418. LBuf->getBufferIdentifier());
  419. // FIXME: Keep a file ID map instead of creating new IDs for each location.
  420. FileID FID = CSM.createFileID(std::move(CBuf));
  421. // Translate the offset into the file.
  422. unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
  423. SourceLocation NewLoc =
  424. CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
  425. return FullSourceLoc(NewLoc, CSM);
  426. }
  427. #define ComputeDiagID(Severity, GroupName, DiagID) \
  428. do { \
  429. switch (Severity) { \
  430. case llvm::DS_Error: \
  431. DiagID = diag::err_fe_##GroupName; \
  432. break; \
  433. case llvm::DS_Warning: \
  434. DiagID = diag::warn_fe_##GroupName; \
  435. break; \
  436. case llvm::DS_Remark: \
  437. llvm_unreachable("'remark' severity not expected"); \
  438. break; \
  439. case llvm::DS_Note: \
  440. DiagID = diag::note_fe_##GroupName; \
  441. break; \
  442. } \
  443. } while (false)
  444. #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
  445. do { \
  446. switch (Severity) { \
  447. case llvm::DS_Error: \
  448. DiagID = diag::err_fe_##GroupName; \
  449. break; \
  450. case llvm::DS_Warning: \
  451. DiagID = diag::warn_fe_##GroupName; \
  452. break; \
  453. case llvm::DS_Remark: \
  454. DiagID = diag::remark_fe_##GroupName; \
  455. break; \
  456. case llvm::DS_Note: \
  457. DiagID = diag::note_fe_##GroupName; \
  458. break; \
  459. } \
  460. } while (false)
  461. void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
  462. const llvm::SMDiagnostic &D = DI.getSMDiag();
  463. unsigned DiagID;
  464. if (DI.isInlineAsmDiag())
  465. ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
  466. else
  467. ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
  468. // This is for the empty BackendConsumer that uses the clang diagnostic
  469. // handler for IR input files.
  470. if (!Context) {
  471. D.print(nullptr, llvm::errs());
  472. Diags.Report(DiagID).AddString("cannot compile inline asm");
  473. return;
  474. }
  475. // There are a couple of different kinds of errors we could get here.
  476. // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
  477. // Strip "error: " off the start of the message string.
  478. StringRef Message = D.getMessage();
  479. (void)Message.consume_front("error: ");
  480. // If the SMDiagnostic has an inline asm source location, translate it.
  481. FullSourceLoc Loc;
  482. if (D.getLoc() != SMLoc())
  483. Loc = ConvertBackendLocation(D, Context->getSourceManager());
  484. // If this problem has clang-level source location information, report the
  485. // issue in the source with a note showing the instantiated
  486. // code.
  487. if (DI.isInlineAsmDiag()) {
  488. SourceLocation LocCookie =
  489. SourceLocation::getFromRawEncoding(DI.getLocCookie());
  490. if (LocCookie.isValid()) {
  491. Diags.Report(LocCookie, DiagID).AddString(Message);
  492. if (D.getLoc().isValid()) {
  493. DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
  494. // Convert the SMDiagnostic ranges into SourceRange and attach them
  495. // to the diagnostic.
  496. for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
  497. unsigned Column = D.getColumnNo();
  498. B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
  499. Loc.getLocWithOffset(Range.second - Column));
  500. }
  501. }
  502. return;
  503. }
  504. }
  505. // Otherwise, report the backend issue as occurring in the generated .s file.
  506. // If Loc is invalid, we still need to report the issue, it just gets no
  507. // location info.
  508. Diags.Report(Loc, DiagID).AddString(Message);
  509. }
  510. bool
  511. BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
  512. unsigned DiagID;
  513. ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
  514. std::string Message = D.getMsgStr().str();
  515. // If this problem has clang-level source location information, report the
  516. // issue as being a problem in the source with a note showing the instantiated
  517. // code.
  518. SourceLocation LocCookie =
  519. SourceLocation::getFromRawEncoding(D.getLocCookie());
  520. if (LocCookie.isValid())
  521. Diags.Report(LocCookie, DiagID).AddString(Message);
  522. else {
  523. // Otherwise, report the backend diagnostic as occurring in the generated
  524. // .s file.
  525. // If Loc is invalid, we still need to report the diagnostic, it just gets
  526. // no location info.
  527. FullSourceLoc Loc;
  528. Diags.Report(Loc, DiagID).AddString(Message);
  529. }
  530. // We handled all the possible severities.
  531. return true;
  532. }
  533. bool
  534. BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
  535. if (D.getSeverity() != llvm::DS_Warning)
  536. // For now, the only support we have for StackSize diagnostic is warning.
  537. // We do not know how to format other severities.
  538. return false;
  539. auto Loc = getFunctionSourceLocation(D.getFunction());
  540. if (!Loc)
  541. return false;
  542. Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
  543. << D.getStackSize()
  544. << D.getStackLimit()
  545. << llvm::demangle(D.getFunction().getName().str());
  546. return true;
  547. }
  548. bool BackendConsumer::ResourceLimitDiagHandler(
  549. const llvm::DiagnosticInfoResourceLimit &D) {
  550. auto Loc = getFunctionSourceLocation(D.getFunction());
  551. if (!Loc)
  552. return false;
  553. unsigned DiagID = diag::err_fe_backend_resource_limit;
  554. ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
  555. Diags.Report(*Loc, DiagID)
  556. << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
  557. << llvm::demangle(D.getFunction().getName().str());
  558. return true;
  559. }
  560. const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
  561. const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
  562. StringRef &Filename, unsigned &Line, unsigned &Column) const {
  563. SourceManager &SourceMgr = Context->getSourceManager();
  564. FileManager &FileMgr = SourceMgr.getFileManager();
  565. SourceLocation DILoc;
  566. if (D.isLocationAvailable()) {
  567. D.getLocation(Filename, Line, Column);
  568. if (Line > 0) {
  569. auto FE = FileMgr.getFile(Filename);
  570. if (!FE)
  571. FE = FileMgr.getFile(D.getAbsolutePath());
  572. if (FE) {
  573. // If -gcolumn-info was not used, Column will be 0. This upsets the
  574. // source manager, so pass 1 if Column is not set.
  575. DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
  576. }
  577. }
  578. BadDebugInfo = DILoc.isInvalid();
  579. }
  580. // If a location isn't available, try to approximate it using the associated
  581. // function definition. We use the definition's right brace to differentiate
  582. // from diagnostics that genuinely relate to the function itself.
  583. FullSourceLoc Loc(DILoc, SourceMgr);
  584. if (Loc.isInvalid()) {
  585. if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
  586. Loc = *MaybeLoc;
  587. }
  588. if (DILoc.isInvalid() && D.isLocationAvailable())
  589. // If we were not able to translate the file:line:col information
  590. // back to a SourceLocation, at least emit a note stating that
  591. // we could not translate this location. This can happen in the
  592. // case of #line directives.
  593. Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
  594. << Filename << Line << Column;
  595. return Loc;
  596. }
  597. std::optional<FullSourceLoc>
  598. BackendConsumer::getFunctionSourceLocation(const Function &F) const {
  599. auto Hash = llvm::hash_value(F.getName());
  600. for (const auto &Pair : ManglingFullSourceLocs) {
  601. if (Pair.first == Hash)
  602. return Pair.second;
  603. }
  604. return std::nullopt;
  605. }
  606. void BackendConsumer::UnsupportedDiagHandler(
  607. const llvm::DiagnosticInfoUnsupported &D) {
  608. // We only support warnings or errors.
  609. assert(D.getSeverity() == llvm::DS_Error ||
  610. D.getSeverity() == llvm::DS_Warning);
  611. StringRef Filename;
  612. unsigned Line, Column;
  613. bool BadDebugInfo = false;
  614. FullSourceLoc Loc;
  615. std::string Msg;
  616. raw_string_ostream MsgStream(Msg);
  617. // Context will be nullptr for IR input files, we will construct the diag
  618. // message from llvm::DiagnosticInfoUnsupported.
  619. if (Context != nullptr) {
  620. Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
  621. MsgStream << D.getMessage();
  622. } else {
  623. DiagnosticPrinterRawOStream DP(MsgStream);
  624. D.print(DP);
  625. }
  626. auto DiagType = D.getSeverity() == llvm::DS_Error
  627. ? diag::err_fe_backend_unsupported
  628. : diag::warn_fe_backend_unsupported;
  629. Diags.Report(Loc, DiagType) << MsgStream.str();
  630. if (BadDebugInfo)
  631. // If we were not able to translate the file:line:col information
  632. // back to a SourceLocation, at least emit a note stating that
  633. // we could not translate this location. This can happen in the
  634. // case of #line directives.
  635. Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
  636. << Filename << Line << Column;
  637. }
  638. void BackendConsumer::EmitOptimizationMessage(
  639. const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
  640. // We only support warnings and remarks.
  641. assert(D.getSeverity() == llvm::DS_Remark ||
  642. D.getSeverity() == llvm::DS_Warning);
  643. StringRef Filename;
  644. unsigned Line, Column;
  645. bool BadDebugInfo = false;
  646. FullSourceLoc Loc;
  647. std::string Msg;
  648. raw_string_ostream MsgStream(Msg);
  649. // Context will be nullptr for IR input files, we will construct the remark
  650. // message from llvm::DiagnosticInfoOptimizationBase.
  651. if (Context != nullptr) {
  652. Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
  653. MsgStream << D.getMsg();
  654. } else {
  655. DiagnosticPrinterRawOStream DP(MsgStream);
  656. D.print(DP);
  657. }
  658. if (D.getHotness())
  659. MsgStream << " (hotness: " << *D.getHotness() << ")";
  660. Diags.Report(Loc, DiagID)
  661. << AddFlagValue(D.getPassName())
  662. << MsgStream.str();
  663. if (BadDebugInfo)
  664. // If we were not able to translate the file:line:col information
  665. // back to a SourceLocation, at least emit a note stating that
  666. // we could not translate this location. This can happen in the
  667. // case of #line directives.
  668. Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
  669. << Filename << Line << Column;
  670. }
  671. void BackendConsumer::OptimizationRemarkHandler(
  672. const llvm::DiagnosticInfoOptimizationBase &D) {
  673. // Without hotness information, don't show noisy remarks.
  674. if (D.isVerbose() && !D.getHotness())
  675. return;
  676. if (D.isPassed()) {
  677. // Optimization remarks are active only if the -Rpass flag has a regular
  678. // expression that matches the name of the pass name in \p D.
  679. if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
  680. EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
  681. } else if (D.isMissed()) {
  682. // Missed optimization remarks are active only if the -Rpass-missed
  683. // flag has a regular expression that matches the name of the pass
  684. // name in \p D.
  685. if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
  686. EmitOptimizationMessage(
  687. D, diag::remark_fe_backend_optimization_remark_missed);
  688. } else {
  689. assert(D.isAnalysis() && "Unknown remark type");
  690. bool ShouldAlwaysPrint = false;
  691. if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
  692. ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
  693. if (ShouldAlwaysPrint ||
  694. CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
  695. EmitOptimizationMessage(
  696. D, diag::remark_fe_backend_optimization_remark_analysis);
  697. }
  698. }
  699. void BackendConsumer::OptimizationRemarkHandler(
  700. const llvm::OptimizationRemarkAnalysisFPCommute &D) {
  701. // Optimization analysis remarks are active if the pass name is set to
  702. // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
  703. // regular expression that matches the name of the pass name in \p D.
  704. if (D.shouldAlwaysPrint() ||
  705. CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
  706. EmitOptimizationMessage(
  707. D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
  708. }
  709. void BackendConsumer::OptimizationRemarkHandler(
  710. const llvm::OptimizationRemarkAnalysisAliasing &D) {
  711. // Optimization analysis remarks are active if the pass name is set to
  712. // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
  713. // regular expression that matches the name of the pass name in \p D.
  714. if (D.shouldAlwaysPrint() ||
  715. CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
  716. EmitOptimizationMessage(
  717. D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
  718. }
  719. void BackendConsumer::OptimizationFailureHandler(
  720. const llvm::DiagnosticInfoOptimizationFailure &D) {
  721. EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
  722. }
  723. void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
  724. SourceLocation LocCookie =
  725. SourceLocation::getFromRawEncoding(D.getLocCookie());
  726. // FIXME: we can't yet diagnose indirect calls. When/if we can, we
  727. // should instead assert that LocCookie.isValid().
  728. if (!LocCookie.isValid())
  729. return;
  730. Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
  731. ? diag::err_fe_backend_error_attr
  732. : diag::warn_fe_backend_warning_attr)
  733. << llvm::demangle(D.getFunctionName().str()) << D.getNote();
  734. }
  735. void BackendConsumer::MisExpectDiagHandler(
  736. const llvm::DiagnosticInfoMisExpect &D) {
  737. StringRef Filename;
  738. unsigned Line, Column;
  739. bool BadDebugInfo = false;
  740. FullSourceLoc Loc =
  741. getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
  742. Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
  743. if (BadDebugInfo)
  744. // If we were not able to translate the file:line:col information
  745. // back to a SourceLocation, at least emit a note stating that
  746. // we could not translate this location. This can happen in the
  747. // case of #line directives.
  748. Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
  749. << Filename << Line << Column;
  750. }
  751. /// This function is invoked when the backend needs
  752. /// to report something to the user.
  753. void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
  754. unsigned DiagID = diag::err_fe_inline_asm;
  755. llvm::DiagnosticSeverity Severity = DI.getSeverity();
  756. // Get the diagnostic ID based.
  757. switch (DI.getKind()) {
  758. case llvm::DK_InlineAsm:
  759. if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
  760. return;
  761. ComputeDiagID(Severity, inline_asm, DiagID);
  762. break;
  763. case llvm::DK_SrcMgr:
  764. SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));
  765. return;
  766. case llvm::DK_StackSize:
  767. if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
  768. return;
  769. ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
  770. break;
  771. case llvm::DK_ResourceLimit:
  772. if (ResourceLimitDiagHandler(cast<DiagnosticInfoResourceLimit>(DI)))
  773. return;
  774. ComputeDiagID(Severity, backend_resource_limit, DiagID);
  775. break;
  776. case DK_Linker:
  777. ComputeDiagID(Severity, linking_module, DiagID);
  778. break;
  779. case llvm::DK_OptimizationRemark:
  780. // Optimization remarks are always handled completely by this
  781. // handler. There is no generic way of emitting them.
  782. OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
  783. return;
  784. case llvm::DK_OptimizationRemarkMissed:
  785. // Optimization remarks are always handled completely by this
  786. // handler. There is no generic way of emitting them.
  787. OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
  788. return;
  789. case llvm::DK_OptimizationRemarkAnalysis:
  790. // Optimization remarks are always handled completely by this
  791. // handler. There is no generic way of emitting them.
  792. OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
  793. return;
  794. case llvm::DK_OptimizationRemarkAnalysisFPCommute:
  795. // Optimization remarks are always handled completely by this
  796. // handler. There is no generic way of emitting them.
  797. OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
  798. return;
  799. case llvm::DK_OptimizationRemarkAnalysisAliasing:
  800. // Optimization remarks are always handled completely by this
  801. // handler. There is no generic way of emitting them.
  802. OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
  803. return;
  804. case llvm::DK_MachineOptimizationRemark:
  805. // Optimization remarks are always handled completely by this
  806. // handler. There is no generic way of emitting them.
  807. OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
  808. return;
  809. case llvm::DK_MachineOptimizationRemarkMissed:
  810. // Optimization remarks are always handled completely by this
  811. // handler. There is no generic way of emitting them.
  812. OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
  813. return;
  814. case llvm::DK_MachineOptimizationRemarkAnalysis:
  815. // Optimization remarks are always handled completely by this
  816. // handler. There is no generic way of emitting them.
  817. OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
  818. return;
  819. case llvm::DK_OptimizationFailure:
  820. // Optimization failures are always handled completely by this
  821. // handler.
  822. OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
  823. return;
  824. case llvm::DK_Unsupported:
  825. UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
  826. return;
  827. case llvm::DK_DontCall:
  828. DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));
  829. return;
  830. case llvm::DK_MisExpect:
  831. MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
  832. return;
  833. default:
  834. // Plugin IDs are not bound to any value as they are set dynamically.
  835. ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
  836. break;
  837. }
  838. std::string MsgStorage;
  839. {
  840. raw_string_ostream Stream(MsgStorage);
  841. DiagnosticPrinterRawOStream DP(Stream);
  842. DI.print(DP);
  843. }
  844. if (DI.getKind() == DK_Linker) {
  845. assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
  846. Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
  847. return;
  848. }
  849. // Report the backend message using the usual diagnostic mechanism.
  850. FullSourceLoc Loc;
  851. Diags.Report(Loc, DiagID).AddString(MsgStorage);
  852. }
  853. #undef ComputeDiagID
  854. CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
  855. : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
  856. OwnsVMContext(!_VMContext) {}
  857. CodeGenAction::~CodeGenAction() {
  858. TheModule.reset();
  859. if (OwnsVMContext)
  860. delete VMContext;
  861. }
  862. bool CodeGenAction::hasIRSupport() const { return true; }
  863. void CodeGenAction::EndSourceFileAction() {
  864. // If the consumer creation failed, do nothing.
  865. if (!getCompilerInstance().hasASTConsumer())
  866. return;
  867. // Steal the module from the consumer.
  868. TheModule = BEConsumer->takeModule();
  869. }
  870. std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
  871. return std::move(TheModule);
  872. }
  873. llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
  874. OwnsVMContext = false;
  875. return VMContext;
  876. }
  877. CodeGenerator *CodeGenAction::getCodeGenerator() const {
  878. return BEConsumer->getCodeGenerator();
  879. }
  880. static std::unique_ptr<raw_pwrite_stream>
  881. GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
  882. switch (Action) {
  883. case Backend_EmitAssembly:
  884. return CI.createDefaultOutputFile(false, InFile, "s");
  885. case Backend_EmitLL:
  886. return CI.createDefaultOutputFile(false, InFile, "ll");
  887. case Backend_EmitBC:
  888. return CI.createDefaultOutputFile(true, InFile, "bc");
  889. case Backend_EmitNothing:
  890. return nullptr;
  891. case Backend_EmitMCNull:
  892. return CI.createNullOutputFile();
  893. case Backend_EmitObj:
  894. return CI.createDefaultOutputFile(true, InFile, "o");
  895. }
  896. llvm_unreachable("Invalid action!");
  897. }
  898. std::unique_ptr<ASTConsumer>
  899. CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  900. BackendAction BA = static_cast<BackendAction>(Act);
  901. std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
  902. if (!OS)
  903. OS = GetOutputStream(CI, InFile, BA);
  904. if (BA != Backend_EmitNothing && !OS)
  905. return nullptr;
  906. VMContext->setOpaquePointers(CI.getCodeGenOpts().OpaquePointers);
  907. // Load bitcode modules to link with, if we need to.
  908. if (LinkModules.empty())
  909. for (const CodeGenOptions::BitcodeFileToLink &F :
  910. CI.getCodeGenOpts().LinkBitcodeFiles) {
  911. auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
  912. if (!BCBuf) {
  913. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  914. << F.Filename << BCBuf.getError().message();
  915. LinkModules.clear();
  916. return nullptr;
  917. }
  918. Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
  919. getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
  920. if (!ModuleOrErr) {
  921. handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  922. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  923. << F.Filename << EIB.message();
  924. });
  925. LinkModules.clear();
  926. return nullptr;
  927. }
  928. LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
  929. F.Internalize, F.LinkFlags});
  930. }
  931. CoverageSourceInfo *CoverageInfo = nullptr;
  932. // Add the preprocessor callback only when the coverage mapping is generated.
  933. if (CI.getCodeGenOpts().CoverageMapping)
  934. CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
  935. CI.getPreprocessor());
  936. std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
  937. BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
  938. CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
  939. CI.getTargetOpts(), CI.getLangOpts(), std::string(InFile),
  940. std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
  941. BEConsumer = Result.get();
  942. // Enable generating macro debug info only when debug info is not disabled and
  943. // also macro debug info is enabled.
  944. if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
  945. CI.getCodeGenOpts().MacroDebugInfo) {
  946. std::unique_ptr<PPCallbacks> Callbacks =
  947. std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
  948. CI.getPreprocessor());
  949. CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
  950. }
  951. return std::move(Result);
  952. }
  953. std::unique_ptr<llvm::Module>
  954. CodeGenAction::loadModule(MemoryBufferRef MBRef) {
  955. CompilerInstance &CI = getCompilerInstance();
  956. SourceManager &SM = CI.getSourceManager();
  957. VMContext->setOpaquePointers(CI.getCodeGenOpts().OpaquePointers);
  958. // For ThinLTO backend invocations, ensure that the context
  959. // merges types based on ODR identifiers. We also need to read
  960. // the correct module out of a multi-module bitcode file.
  961. if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
  962. VMContext->enableDebugTypeODRUniquing();
  963. auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
  964. unsigned DiagID =
  965. CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  966. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  967. CI.getDiagnostics().Report(DiagID) << EIB.message();
  968. });
  969. return {};
  970. };
  971. Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
  972. if (!BMsOrErr)
  973. return DiagErrors(BMsOrErr.takeError());
  974. BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
  975. // We have nothing to do if the file contains no ThinLTO module. This is
  976. // possible if ThinLTO compilation was not able to split module. Content of
  977. // the file was already processed by indexing and will be passed to the
  978. // linker using merged object file.
  979. if (!Bm) {
  980. auto M = std::make_unique<llvm::Module>("empty", *VMContext);
  981. M->setTargetTriple(CI.getTargetOpts().Triple);
  982. return M;
  983. }
  984. Expected<std::unique_ptr<llvm::Module>> MOrErr =
  985. Bm->parseModule(*VMContext);
  986. if (!MOrErr)
  987. return DiagErrors(MOrErr.takeError());
  988. return std::move(*MOrErr);
  989. }
  990. llvm::SMDiagnostic Err;
  991. if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
  992. return M;
  993. // Translate from the diagnostic info to the SourceManager location if
  994. // available.
  995. // TODO: Unify this with ConvertBackendLocation()
  996. SourceLocation Loc;
  997. if (Err.getLineNo() > 0) {
  998. assert(Err.getColumnNo() >= 0);
  999. Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
  1000. Err.getLineNo(), Err.getColumnNo() + 1);
  1001. }
  1002. // Strip off a leading diagnostic code if there is one.
  1003. StringRef Msg = Err.getMessage();
  1004. if (Msg.startswith("error: "))
  1005. Msg = Msg.substr(7);
  1006. unsigned DiagID =
  1007. CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  1008. CI.getDiagnostics().Report(Loc, DiagID) << Msg;
  1009. return {};
  1010. }
  1011. void CodeGenAction::ExecuteAction() {
  1012. if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
  1013. this->ASTFrontendAction::ExecuteAction();
  1014. return;
  1015. }
  1016. // If this is an IR file, we have to treat it specially.
  1017. BackendAction BA = static_cast<BackendAction>(Act);
  1018. CompilerInstance &CI = getCompilerInstance();
  1019. auto &CodeGenOpts = CI.getCodeGenOpts();
  1020. auto &Diagnostics = CI.getDiagnostics();
  1021. std::unique_ptr<raw_pwrite_stream> OS =
  1022. GetOutputStream(CI, getCurrentFileOrBufferName(), BA);
  1023. if (BA != Backend_EmitNothing && !OS)
  1024. return;
  1025. SourceManager &SM = CI.getSourceManager();
  1026. FileID FID = SM.getMainFileID();
  1027. std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
  1028. if (!MainFile)
  1029. return;
  1030. TheModule = loadModule(*MainFile);
  1031. if (!TheModule)
  1032. return;
  1033. const TargetOptions &TargetOpts = CI.getTargetOpts();
  1034. if (TheModule->getTargetTriple() != TargetOpts.Triple) {
  1035. Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
  1036. << TargetOpts.Triple;
  1037. TheModule->setTargetTriple(TargetOpts.Triple);
  1038. }
  1039. EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
  1040. EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
  1041. LLVMContext &Ctx = TheModule->getContext();
  1042. // Restore any diagnostic handler previously set before returning from this
  1043. // function.
  1044. struct RAII {
  1045. LLVMContext &Ctx;
  1046. std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
  1047. ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
  1048. } _{Ctx};
  1049. // Set clang diagnostic handler. To do this we need to create a fake
  1050. // BackendConsumer.
  1051. BackendConsumer Result(BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
  1052. CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),
  1053. CI.getCodeGenOpts(), CI.getTargetOpts(),
  1054. CI.getLangOpts(), TheModule.get(),
  1055. std::move(LinkModules), *VMContext, nullptr);
  1056. // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
  1057. // true here because the valued names are needed for reading textual IR.
  1058. Ctx.setDiscardValueNames(false);
  1059. Ctx.setDiagnosticHandler(
  1060. std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
  1061. Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
  1062. setupLLVMOptimizationRemarks(
  1063. Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
  1064. CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
  1065. CodeGenOpts.DiagnosticsHotnessThreshold);
  1066. if (Error E = OptRecordFileOrErr.takeError()) {
  1067. reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
  1068. return;
  1069. }
  1070. std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
  1071. std::move(*OptRecordFileOrErr);
  1072. EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts,
  1073. TargetOpts, CI.getLangOpts(),
  1074. CI.getTarget().getDataLayoutString(), TheModule.get(), BA,
  1075. std::move(OS));
  1076. if (OptRecordFile)
  1077. OptRecordFile->keep();
  1078. }
  1079. //
  1080. void EmitAssemblyAction::anchor() { }
  1081. EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
  1082. : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
  1083. void EmitBCAction::anchor() { }
  1084. EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
  1085. : CodeGenAction(Backend_EmitBC, _VMContext) {}
  1086. void EmitLLVMAction::anchor() { }
  1087. EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
  1088. : CodeGenAction(Backend_EmitLL, _VMContext) {}
  1089. void EmitLLVMOnlyAction::anchor() { }
  1090. EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
  1091. : CodeGenAction(Backend_EmitNothing, _VMContext) {}
  1092. void EmitCodeGenOnlyAction::anchor() { }
  1093. EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
  1094. : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
  1095. void EmitObjAction::anchor() { }
  1096. EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
  1097. : CodeGenAction(Backend_EmitObj, _VMContext) {}