BackendUtil.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
  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/BackendUtil.h"
  9. #include "clang/Basic/CodeGenOptions.h"
  10. #include "clang/Basic/Diagnostic.h"
  11. #include "clang/Basic/LangOptions.h"
  12. #include "clang/Basic/TargetOptions.h"
  13. #include "clang/Frontend/FrontendDiagnostic.h"
  14. #include "clang/Frontend/Utils.h"
  15. #include "clang/Lex/HeaderSearchOptions.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/StringSwitch.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Analysis/GlobalsModRef.h"
  22. #include "llvm/Analysis/StackSafetyAnalysis.h"
  23. #include "llvm/Analysis/TargetLibraryInfo.h"
  24. #include "llvm/Analysis/TargetTransformInfo.h"
  25. #include "llvm/Bitcode/BitcodeReader.h"
  26. #include "llvm/Bitcode/BitcodeWriter.h"
  27. #include "llvm/Bitcode/BitcodeWriterPass.h"
  28. #include "llvm/CodeGen/RegAllocRegistry.h"
  29. #include "llvm/CodeGen/SchedulerRegistry.h"
  30. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/DebugInfo.h"
  33. #include "llvm/IR/LegacyPassManager.h"
  34. #include "llvm/IR/Module.h"
  35. #include "llvm/IR/ModuleSummaryIndex.h"
  36. #include "llvm/IR/PassManager.h"
  37. #include "llvm/IR/Verifier.h"
  38. #include "llvm/IRPrinter/IRPrintingPasses.h"
  39. #include "llvm/LTO/LTOBackend.h"
  40. #include "llvm/MC/MCAsmInfo.h"
  41. #include "llvm/MC/SubtargetFeature.h"
  42. #include "llvm/MC/TargetRegistry.h"
  43. #include "llvm/Object/OffloadBinary.h"
  44. #include "llvm/Passes/PassBuilder.h"
  45. #include "llvm/Passes/PassPlugin.h"
  46. #include "llvm/Passes/StandardInstrumentations.h"
  47. #include "llvm/Support/BuryPointer.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Support/MemoryBuffer.h"
  50. #include "llvm/Support/PrettyStackTrace.h"
  51. #include "llvm/Support/TimeProfiler.h"
  52. #include "llvm/Support/Timer.h"
  53. #include "llvm/Support/ToolOutputFile.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include "llvm/Target/TargetMachine.h"
  56. #include "llvm/Target/TargetOptions.h"
  57. #include "llvm/Transforms/Coroutines/CoroCleanup.h"
  58. #include "llvm/Transforms/Coroutines/CoroEarly.h"
  59. #include "llvm/Transforms/Coroutines/CoroElide.h"
  60. #include "llvm/Transforms/Coroutines/CoroSplit.h"
  61. #include "llvm/Transforms/IPO.h"
  62. #include "llvm/Transforms/IPO/AlwaysInliner.h"
  63. #include "llvm/Transforms/IPO/LowerTypeTests.h"
  64. #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
  65. #include "llvm/Transforms/InstCombine/InstCombine.h"
  66. #include "llvm/Transforms/Instrumentation.h"
  67. #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
  68. #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
  69. #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
  70. #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
  71. #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
  72. #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
  73. #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
  74. #include "llvm/Transforms/Instrumentation/KCFI.h"
  75. #include "llvm/Transforms/Instrumentation/MemProfiler.h"
  76. #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
  77. #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
  78. #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
  79. #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
  80. #include "llvm/Transforms/ObjCARC.h"
  81. #include "llvm/Transforms/Scalar.h"
  82. #include "llvm/Transforms/Scalar/EarlyCSE.h"
  83. #include "llvm/Transforms/Scalar/GVN.h"
  84. #include "llvm/Transforms/Scalar/JumpThreading.h"
  85. #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
  86. #include "llvm/Transforms/Utils.h"
  87. #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
  88. #include "llvm/Transforms/Utils/Debugify.h"
  89. #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
  90. #include "llvm/Transforms/Utils/ModuleUtils.h"
  91. #include "llvm/Transforms/Utils/NameAnonGlobals.h"
  92. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  93. #include <memory>
  94. #include <optional>
  95. using namespace clang;
  96. using namespace llvm;
  97. #define HANDLE_EXTENSION(Ext) \
  98. llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
  99. #include "llvm/Support/Extension.def"
  100. namespace llvm {
  101. extern cl::opt<bool> DebugInfoCorrelate;
  102. // Experiment to move sanitizers earlier.
  103. static cl::opt<bool> ClSanitizeOnOptimizerEarlyEP(
  104. "sanitizer-early-opt-ep", cl::Optional,
  105. cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false));
  106. }
  107. namespace {
  108. // Default filename used for profile generation.
  109. std::string getDefaultProfileGenName() {
  110. return DebugInfoCorrelate ? "default_%p.proflite" : "default_%m.profraw";
  111. }
  112. class EmitAssemblyHelper {
  113. DiagnosticsEngine &Diags;
  114. const HeaderSearchOptions &HSOpts;
  115. const CodeGenOptions &CodeGenOpts;
  116. const clang::TargetOptions &TargetOpts;
  117. const LangOptions &LangOpts;
  118. Module *TheModule;
  119. Timer CodeGenerationTime;
  120. std::unique_ptr<raw_pwrite_stream> OS;
  121. Triple TargetTriple;
  122. TargetIRAnalysis getTargetIRAnalysis() const {
  123. if (TM)
  124. return TM->getTargetIRAnalysis();
  125. return TargetIRAnalysis();
  126. }
  127. /// Generates the TargetMachine.
  128. /// Leaves TM unchanged if it is unable to create the target machine.
  129. /// Some of our clang tests specify triples which are not built
  130. /// into clang. This is okay because these tests check the generated
  131. /// IR, and they require DataLayout which depends on the triple.
  132. /// In this case, we allow this method to fail and not report an error.
  133. /// When MustCreateTM is used, we print an error if we are unable to load
  134. /// the requested target.
  135. void CreateTargetMachine(bool MustCreateTM);
  136. /// Add passes necessary to emit assembly or LLVM IR.
  137. ///
  138. /// \return True on success.
  139. bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
  140. raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
  141. std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
  142. std::error_code EC;
  143. auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
  144. llvm::sys::fs::OF_None);
  145. if (EC) {
  146. Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
  147. F.reset();
  148. }
  149. return F;
  150. }
  151. void
  152. RunOptimizationPipeline(BackendAction Action,
  153. std::unique_ptr<raw_pwrite_stream> &OS,
  154. std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS);
  155. void RunCodegenPipeline(BackendAction Action,
  156. std::unique_ptr<raw_pwrite_stream> &OS,
  157. std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
  158. /// Check whether we should emit a module summary for regular LTO.
  159. /// The module summary should be emitted by default for regular LTO
  160. /// except for ld64 targets.
  161. ///
  162. /// \return True if the module summary should be emitted.
  163. bool shouldEmitRegularLTOSummary() const {
  164. return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
  165. TargetTriple.getVendor() != llvm::Triple::Apple;
  166. }
  167. public:
  168. EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  169. const HeaderSearchOptions &HeaderSearchOpts,
  170. const CodeGenOptions &CGOpts,
  171. const clang::TargetOptions &TOpts,
  172. const LangOptions &LOpts, Module *M)
  173. : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
  174. TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
  175. CodeGenerationTime("codegen", "Code Generation Time"),
  176. TargetTriple(TheModule->getTargetTriple()) {}
  177. ~EmitAssemblyHelper() {
  178. if (CodeGenOpts.DisableFree)
  179. BuryPointer(std::move(TM));
  180. }
  181. std::unique_ptr<TargetMachine> TM;
  182. // Emit output using the new pass manager for the optimization pipeline.
  183. void EmitAssembly(BackendAction Action,
  184. std::unique_ptr<raw_pwrite_stream> OS);
  185. };
  186. }
  187. static SanitizerCoverageOptions
  188. getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
  189. SanitizerCoverageOptions Opts;
  190. Opts.CoverageType =
  191. static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
  192. Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
  193. Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
  194. Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
  195. Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
  196. Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
  197. Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
  198. Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
  199. Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
  200. Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
  201. Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
  202. Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
  203. Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
  204. Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
  205. Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
  206. Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
  207. Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
  208. return Opts;
  209. }
  210. static SanitizerBinaryMetadataOptions
  211. getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts) {
  212. SanitizerBinaryMetadataOptions Opts;
  213. Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
  214. Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
  215. Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
  216. return Opts;
  217. }
  218. // Check if ASan should use GC-friendly instrumentation for globals.
  219. // First of all, there is no point if -fdata-sections is off (expect for MachO,
  220. // where this is not a factor). Also, on ELF this feature requires an assembler
  221. // extension that only works with -integrated-as at the moment.
  222. static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
  223. if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
  224. return false;
  225. switch (T.getObjectFormat()) {
  226. case Triple::MachO:
  227. case Triple::COFF:
  228. return true;
  229. case Triple::ELF:
  230. return !CGOpts.DisableIntegratedAS;
  231. case Triple::GOFF:
  232. llvm::report_fatal_error("ASan not implemented for GOFF");
  233. case Triple::XCOFF:
  234. llvm::report_fatal_error("ASan not implemented for XCOFF.");
  235. case Triple::Wasm:
  236. case Triple::DXContainer:
  237. case Triple::SPIRV:
  238. case Triple::UnknownObjectFormat:
  239. break;
  240. }
  241. return false;
  242. }
  243. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  244. const CodeGenOptions &CodeGenOpts) {
  245. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  246. switch (CodeGenOpts.getVecLib()) {
  247. case CodeGenOptions::Accelerate:
  248. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate,
  249. TargetTriple);
  250. break;
  251. case CodeGenOptions::LIBMVEC:
  252. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::LIBMVEC_X86,
  253. TargetTriple);
  254. break;
  255. case CodeGenOptions::MASSV:
  256. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV,
  257. TargetTriple);
  258. break;
  259. case CodeGenOptions::SVML:
  260. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML,
  261. TargetTriple);
  262. break;
  263. case CodeGenOptions::SLEEF:
  264. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SLEEFGNUABI,
  265. TargetTriple);
  266. break;
  267. case CodeGenOptions::Darwin_libsystem_m:
  268. TLII->addVectorizableFunctionsFromVecLib(
  269. TargetLibraryInfoImpl::DarwinLibSystemM, TargetTriple);
  270. break;
  271. default:
  272. break;
  273. }
  274. return TLII;
  275. }
  276. static std::optional<llvm::CodeModel::Model>
  277. getCodeModel(const CodeGenOptions &CodeGenOpts) {
  278. unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  279. .Case("tiny", llvm::CodeModel::Tiny)
  280. .Case("small", llvm::CodeModel::Small)
  281. .Case("kernel", llvm::CodeModel::Kernel)
  282. .Case("medium", llvm::CodeModel::Medium)
  283. .Case("large", llvm::CodeModel::Large)
  284. .Case("default", ~1u)
  285. .Default(~0u);
  286. assert(CodeModel != ~0u && "invalid code model!");
  287. if (CodeModel == ~1u)
  288. return std::nullopt;
  289. return static_cast<llvm::CodeModel::Model>(CodeModel);
  290. }
  291. static CodeGenFileType getCodeGenFileType(BackendAction Action) {
  292. if (Action == Backend_EmitObj)
  293. return CGFT_ObjectFile;
  294. else if (Action == Backend_EmitMCNull)
  295. return CGFT_Null;
  296. else {
  297. assert(Action == Backend_EmitAssembly && "Invalid action!");
  298. return CGFT_AssemblyFile;
  299. }
  300. }
  301. static bool actionRequiresCodeGen(BackendAction Action) {
  302. return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
  303. Action != Backend_EmitLL;
  304. }
  305. static bool initTargetOptions(DiagnosticsEngine &Diags,
  306. llvm::TargetOptions &Options,
  307. const CodeGenOptions &CodeGenOpts,
  308. const clang::TargetOptions &TargetOpts,
  309. const LangOptions &LangOpts,
  310. const HeaderSearchOptions &HSOpts) {
  311. switch (LangOpts.getThreadModel()) {
  312. case LangOptions::ThreadModelKind::POSIX:
  313. Options.ThreadModel = llvm::ThreadModel::POSIX;
  314. break;
  315. case LangOptions::ThreadModelKind::Single:
  316. Options.ThreadModel = llvm::ThreadModel::Single;
  317. break;
  318. }
  319. // Set float ABI type.
  320. assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
  321. CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
  322. "Invalid Floating Point ABI!");
  323. Options.FloatABIType =
  324. llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
  325. .Case("soft", llvm::FloatABI::Soft)
  326. .Case("softfp", llvm::FloatABI::Soft)
  327. .Case("hard", llvm::FloatABI::Hard)
  328. .Default(llvm::FloatABI::Default);
  329. // Set FP fusion mode.
  330. switch (LangOpts.getDefaultFPContractMode()) {
  331. case LangOptions::FPM_Off:
  332. // Preserve any contraction performed by the front-end. (Strict performs
  333. // splitting of the muladd intrinsic in the backend.)
  334. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  335. break;
  336. case LangOptions::FPM_On:
  337. case LangOptions::FPM_FastHonorPragmas:
  338. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  339. break;
  340. case LangOptions::FPM_Fast:
  341. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  342. break;
  343. }
  344. Options.BinutilsVersion =
  345. llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
  346. Options.UseInitArray = CodeGenOpts.UseInitArray;
  347. Options.LowerGlobalDtorsViaCxaAtExit =
  348. CodeGenOpts.RegisterGlobalDtorsWithAtExit;
  349. Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
  350. Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
  351. Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
  352. // Set EABI version.
  353. Options.EABIVersion = TargetOpts.EABIVersion;
  354. if (LangOpts.hasSjLjExceptions())
  355. Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
  356. if (LangOpts.hasSEHExceptions())
  357. Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
  358. if (LangOpts.hasDWARFExceptions())
  359. Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
  360. if (LangOpts.hasWasmExceptions())
  361. Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
  362. Options.NoInfsFPMath = LangOpts.NoHonorInfs;
  363. Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
  364. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  365. Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
  366. LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
  367. (LangOpts.getDefaultFPContractMode() ==
  368. LangOptions::FPModeKind::FPM_Fast ||
  369. LangOpts.getDefaultFPContractMode() ==
  370. LangOptions::FPModeKind::FPM_FastHonorPragmas);
  371. Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
  372. Options.BBSections =
  373. llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
  374. .Case("all", llvm::BasicBlockSection::All)
  375. .Case("labels", llvm::BasicBlockSection::Labels)
  376. .StartsWith("list=", llvm::BasicBlockSection::List)
  377. .Case("none", llvm::BasicBlockSection::None)
  378. .Default(llvm::BasicBlockSection::None);
  379. if (Options.BBSections == llvm::BasicBlockSection::List) {
  380. ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
  381. MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
  382. if (!MBOrErr) {
  383. Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
  384. << MBOrErr.getError().message();
  385. return false;
  386. }
  387. Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
  388. }
  389. Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
  390. Options.FunctionSections = CodeGenOpts.FunctionSections;
  391. Options.DataSections = CodeGenOpts.DataSections;
  392. Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
  393. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  394. Options.UniqueBasicBlockSectionNames =
  395. CodeGenOpts.UniqueBasicBlockSectionNames;
  396. Options.TLSSize = CodeGenOpts.TLSSize;
  397. Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
  398. Options.ExplicitEmulatedTLS = true;
  399. Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
  400. Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
  401. Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
  402. Options.EmitAddrsig = CodeGenOpts.Addrsig;
  403. Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
  404. Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
  405. Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
  406. Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
  407. Options.LoopAlignment = CodeGenOpts.LoopAlignment;
  408. Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
  409. Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
  410. Options.Hotpatch = CodeGenOpts.HotPatch;
  411. Options.JMCInstrument = CodeGenOpts.JMCInstrument;
  412. switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
  413. case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
  414. Options.SwiftAsyncFramePointer =
  415. SwiftAsyncFramePointerMode::DeploymentBased;
  416. break;
  417. case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
  418. Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
  419. break;
  420. case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
  421. Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
  422. break;
  423. }
  424. Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
  425. Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
  426. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  427. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  428. Options.MCOptions.MCUseDwarfDirectory =
  429. CodeGenOpts.NoDwarfDirectoryAsm
  430. ? llvm::MCTargetOptions::DisableDwarfDirectory
  431. : llvm::MCTargetOptions::EnableDwarfDirectory;
  432. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  433. Options.MCOptions.MCIncrementalLinkerCompatible =
  434. CodeGenOpts.IncrementalLinkerCompatible;
  435. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  436. Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
  437. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  438. Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
  439. Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
  440. Options.MCOptions.ABIName = TargetOpts.ABI;
  441. for (const auto &Entry : HSOpts.UserEntries)
  442. if (!Entry.IsFramework &&
  443. (Entry.Group == frontend::IncludeDirGroup::Quoted ||
  444. Entry.Group == frontend::IncludeDirGroup::Angled ||
  445. Entry.Group == frontend::IncludeDirGroup::System))
  446. Options.MCOptions.IASSearchPaths.push_back(
  447. Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
  448. Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
  449. Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
  450. Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile;
  451. Options.MisExpect = CodeGenOpts.MisExpect;
  452. return true;
  453. }
  454. static std::optional<GCOVOptions>
  455. getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) {
  456. if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
  457. return std::nullopt;
  458. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  459. // LLVM's -default-gcov-version flag is set to something invalid.
  460. GCOVOptions Options;
  461. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  462. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  463. llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
  464. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  465. Options.Filter = CodeGenOpts.ProfileFilterFiles;
  466. Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
  467. Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
  468. return Options;
  469. }
  470. static std::optional<InstrProfOptions>
  471. getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
  472. const LangOptions &LangOpts) {
  473. if (!CodeGenOpts.hasProfileClangInstr())
  474. return std::nullopt;
  475. InstrProfOptions Options;
  476. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  477. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  478. Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
  479. return Options;
  480. }
  481. static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
  482. SmallVector<const char *, 16> BackendArgs;
  483. BackendArgs.push_back("clang"); // Fake program name.
  484. if (!CodeGenOpts.DebugPass.empty()) {
  485. BackendArgs.push_back("-debug-pass");
  486. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  487. }
  488. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  489. BackendArgs.push_back("-limit-float-precision");
  490. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  491. }
  492. // Check for the default "clang" invocation that won't set any cl::opt values.
  493. // Skip trying to parse the command line invocation to avoid the issues
  494. // described below.
  495. if (BackendArgs.size() == 1)
  496. return;
  497. BackendArgs.push_back(nullptr);
  498. // FIXME: The command line parser below is not thread-safe and shares a global
  499. // state, so this call might crash or overwrite the options of another Clang
  500. // instance in the same process.
  501. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  502. BackendArgs.data());
  503. }
  504. void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  505. // Create the TargetMachine for generating code.
  506. std::string Error;
  507. std::string Triple = TheModule->getTargetTriple();
  508. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  509. if (!TheTarget) {
  510. if (MustCreateTM)
  511. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  512. return;
  513. }
  514. std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
  515. std::string FeaturesStr =
  516. llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
  517. llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
  518. std::optional<CodeGenOpt::Level> OptLevelOrNone =
  519. CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
  520. assert(OptLevelOrNone && "Invalid optimization level!");
  521. CodeGenOpt::Level OptLevel = *OptLevelOrNone;
  522. llvm::TargetOptions Options;
  523. if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
  524. HSOpts))
  525. return;
  526. TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
  527. Options, RM, CM, OptLevel));
  528. }
  529. bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
  530. BackendAction Action,
  531. raw_pwrite_stream &OS,
  532. raw_pwrite_stream *DwoOS) {
  533. // Add LibraryInfo.
  534. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  535. createTLII(TargetTriple, CodeGenOpts));
  536. CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
  537. // Normal mode, emit a .s or .o file by running the code generator. Note,
  538. // this also adds codegenerator level optimization passes.
  539. CodeGenFileType CGFT = getCodeGenFileType(Action);
  540. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  541. // "codegen" passes so that it isn't run multiple times when there is
  542. // inlining happening.
  543. if (CodeGenOpts.OptimizationLevel > 0)
  544. CodeGenPasses.add(createObjCARCContractPass());
  545. if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
  546. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  547. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  548. return false;
  549. }
  550. return true;
  551. }
  552. static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
  553. switch (Opts.OptimizationLevel) {
  554. default:
  555. llvm_unreachable("Invalid optimization level!");
  556. case 0:
  557. return OptimizationLevel::O0;
  558. case 1:
  559. return OptimizationLevel::O1;
  560. case 2:
  561. switch (Opts.OptimizeSize) {
  562. default:
  563. llvm_unreachable("Invalid optimization level for size!");
  564. case 0:
  565. return OptimizationLevel::O2;
  566. case 1:
  567. return OptimizationLevel::Os;
  568. case 2:
  569. return OptimizationLevel::Oz;
  570. }
  571. case 3:
  572. return OptimizationLevel::O3;
  573. }
  574. }
  575. static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts,
  576. PassBuilder &PB) {
  577. // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
  578. if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
  579. TargetTriple.isAArch64(64))
  580. return;
  581. // Ensure we lower KCFI operand bundles with -O0.
  582. PB.registerOptimizerLastEPCallback(
  583. [&](ModulePassManager &MPM, OptimizationLevel Level) {
  584. if (Level == OptimizationLevel::O0 &&
  585. LangOpts.Sanitize.has(SanitizerKind::KCFI))
  586. MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
  587. });
  588. // When optimizations are requested, run KCIFPass after InstCombine to
  589. // avoid unnecessary checks.
  590. PB.registerPeepholeEPCallback(
  591. [&](FunctionPassManager &FPM, OptimizationLevel Level) {
  592. if (Level != OptimizationLevel::O0 &&
  593. LangOpts.Sanitize.has(SanitizerKind::KCFI))
  594. FPM.addPass(KCFIPass());
  595. });
  596. }
  597. static void addSanitizers(const Triple &TargetTriple,
  598. const CodeGenOptions &CodeGenOpts,
  599. const LangOptions &LangOpts, PassBuilder &PB) {
  600. auto SanitizersCallback = [&](ModulePassManager &MPM,
  601. OptimizationLevel Level) {
  602. if (CodeGenOpts.hasSanitizeCoverage()) {
  603. auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
  604. MPM.addPass(SanitizerCoveragePass(
  605. SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
  606. CodeGenOpts.SanitizeCoverageIgnorelistFiles));
  607. }
  608. if (CodeGenOpts.hasSanitizeBinaryMetadata()) {
  609. MPM.addPass(SanitizerBinaryMetadataPass(
  610. getSanitizerBinaryMetadataOptions(CodeGenOpts)));
  611. }
  612. auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
  613. if (LangOpts.Sanitize.has(Mask)) {
  614. int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
  615. bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
  616. MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
  617. CodeGenOpts.SanitizeMemoryParamRetval);
  618. MPM.addPass(MemorySanitizerPass(options));
  619. if (Level != OptimizationLevel::O0) {
  620. // MemorySanitizer inserts complex instrumentation that mostly follows
  621. // the logic of the original code, but operates on "shadow" values. It
  622. // can benefit from re-running some general purpose optimization
  623. // passes.
  624. MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
  625. FunctionPassManager FPM;
  626. FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
  627. FPM.addPass(InstCombinePass());
  628. FPM.addPass(JumpThreadingPass());
  629. FPM.addPass(GVNPass());
  630. FPM.addPass(InstCombinePass());
  631. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  632. }
  633. }
  634. };
  635. MSanPass(SanitizerKind::Memory, false);
  636. MSanPass(SanitizerKind::KernelMemory, true);
  637. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  638. MPM.addPass(ModuleThreadSanitizerPass());
  639. MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
  640. }
  641. auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
  642. if (LangOpts.Sanitize.has(Mask)) {
  643. bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
  644. bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
  645. llvm::AsanDtorKind DestructorKind =
  646. CodeGenOpts.getSanitizeAddressDtor();
  647. AddressSanitizerOptions Opts;
  648. Opts.CompileKernel = CompileKernel;
  649. Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
  650. Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
  651. Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
  652. MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
  653. DestructorKind));
  654. }
  655. };
  656. ASanPass(SanitizerKind::Address, false);
  657. ASanPass(SanitizerKind::KernelAddress, true);
  658. auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
  659. if (LangOpts.Sanitize.has(Mask)) {
  660. bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
  661. MPM.addPass(HWAddressSanitizerPass(
  662. {CompileKernel, Recover,
  663. /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
  664. }
  665. };
  666. HWASanPass(SanitizerKind::HWAddress, false);
  667. HWASanPass(SanitizerKind::KernelHWAddress, true);
  668. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  669. MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
  670. }
  671. };
  672. if (ClSanitizeOnOptimizerEarlyEP) {
  673. PB.registerOptimizerEarlyEPCallback(
  674. [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level) {
  675. ModulePassManager NewMPM;
  676. SanitizersCallback(NewMPM, Level);
  677. if (!NewMPM.isEmpty()) {
  678. // Sanitizers can abandon<GlobalsAA>.
  679. NewMPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
  680. MPM.addPass(std::move(NewMPM));
  681. }
  682. });
  683. } else {
  684. // LastEP does not need GlobalsAA.
  685. PB.registerOptimizerLastEPCallback(SanitizersCallback);
  686. }
  687. }
  688. void EmitAssemblyHelper::RunOptimizationPipeline(
  689. BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
  690. std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) {
  691. std::optional<PGOOptions> PGOOpt;
  692. if (CodeGenOpts.hasProfileIRInstr())
  693. // -fprofile-generate.
  694. PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
  695. ? getDefaultProfileGenName()
  696. : CodeGenOpts.InstrProfileOutput,
  697. "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
  698. CodeGenOpts.DebugInfoForProfiling);
  699. else if (CodeGenOpts.hasProfileIRUse()) {
  700. // -fprofile-use.
  701. auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
  702. : PGOOptions::NoCSAction;
  703. PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
  704. CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
  705. CSAction, CodeGenOpts.DebugInfoForProfiling);
  706. } else if (!CodeGenOpts.SampleProfileFile.empty())
  707. // -fprofile-sample-use
  708. PGOOpt = PGOOptions(
  709. CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
  710. PGOOptions::SampleUse, PGOOptions::NoCSAction,
  711. CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
  712. else if (CodeGenOpts.PseudoProbeForProfiling)
  713. // -fpseudo-probe-for-profiling
  714. PGOOpt =
  715. PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
  716. CodeGenOpts.DebugInfoForProfiling, true);
  717. else if (CodeGenOpts.DebugInfoForProfiling)
  718. // -fdebug-info-for-profiling
  719. PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
  720. PGOOptions::NoCSAction, true);
  721. // Check to see if we want to generate a CS profile.
  722. if (CodeGenOpts.hasProfileCSIRInstr()) {
  723. assert(!CodeGenOpts.hasProfileCSIRUse() &&
  724. "Cannot have both CSProfileUse pass and CSProfileGen pass at "
  725. "the same time");
  726. if (PGOOpt) {
  727. assert(PGOOpt->Action != PGOOptions::IRInstr &&
  728. PGOOpt->Action != PGOOptions::SampleUse &&
  729. "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
  730. " pass");
  731. PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
  732. ? getDefaultProfileGenName()
  733. : CodeGenOpts.InstrProfileOutput;
  734. PGOOpt->CSAction = PGOOptions::CSIRInstr;
  735. } else
  736. PGOOpt = PGOOptions("",
  737. CodeGenOpts.InstrProfileOutput.empty()
  738. ? getDefaultProfileGenName()
  739. : CodeGenOpts.InstrProfileOutput,
  740. "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
  741. CodeGenOpts.DebugInfoForProfiling);
  742. }
  743. if (TM)
  744. TM->setPGOOption(PGOOpt);
  745. PipelineTuningOptions PTO;
  746. PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
  747. // For historical reasons, loop interleaving is set to mirror setting for loop
  748. // unrolling.
  749. PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
  750. PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
  751. PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
  752. PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
  753. // Only enable CGProfilePass when using integrated assembler, since
  754. // non-integrated assemblers don't recognize .cgprofile section.
  755. PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
  756. LoopAnalysisManager LAM;
  757. FunctionAnalysisManager FAM;
  758. CGSCCAnalysisManager CGAM;
  759. ModuleAnalysisManager MAM;
  760. bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
  761. PassInstrumentationCallbacks PIC;
  762. PrintPassOptions PrintPassOpts;
  763. PrintPassOpts.Indent = DebugPassStructure;
  764. PrintPassOpts.SkipAnalyses = DebugPassStructure;
  765. StandardInstrumentations SI(
  766. TheModule->getContext(),
  767. (CodeGenOpts.DebugPassManager || DebugPassStructure),
  768. /*VerifyEach*/ false, PrintPassOpts);
  769. SI.registerCallbacks(PIC, &FAM);
  770. PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
  771. if (CodeGenOpts.EnableAssignmentTracking) {
  772. PB.registerPipelineStartEPCallback(
  773. [&](ModulePassManager &MPM, OptimizationLevel Level) {
  774. MPM.addPass(AssignmentTrackingPass());
  775. });
  776. }
  777. // Enable verify-debuginfo-preserve-each for new PM.
  778. DebugifyEachInstrumentation Debugify;
  779. DebugInfoPerPass DebugInfoBeforePass;
  780. if (CodeGenOpts.EnableDIPreservationVerify) {
  781. Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
  782. Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
  783. if (!CodeGenOpts.DIBugsReportFilePath.empty())
  784. Debugify.setOrigDIVerifyBugsReportFilePath(
  785. CodeGenOpts.DIBugsReportFilePath);
  786. Debugify.registerCallbacks(PIC);
  787. }
  788. // Attempt to load pass plugins and register their callbacks with PB.
  789. for (auto &PluginFN : CodeGenOpts.PassPlugins) {
  790. auto PassPlugin = PassPlugin::Load(PluginFN);
  791. if (PassPlugin) {
  792. PassPlugin->registerPassBuilderCallbacks(PB);
  793. } else {
  794. Diags.Report(diag::err_fe_unable_to_load_plugin)
  795. << PluginFN << toString(PassPlugin.takeError());
  796. }
  797. }
  798. #define HANDLE_EXTENSION(Ext) \
  799. get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
  800. #include "llvm/Support/Extension.def"
  801. // Register the target library analysis directly and give it a customized
  802. // preset TLI.
  803. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  804. createTLII(TargetTriple, CodeGenOpts));
  805. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  806. // Register all the basic analyses with the managers.
  807. PB.registerModuleAnalyses(MAM);
  808. PB.registerCGSCCAnalyses(CGAM);
  809. PB.registerFunctionAnalyses(FAM);
  810. PB.registerLoopAnalyses(LAM);
  811. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  812. ModulePassManager MPM;
  813. if (!CodeGenOpts.DisableLLVMPasses) {
  814. // Map our optimization levels into one of the distinct levels used to
  815. // configure the pipeline.
  816. OptimizationLevel Level = mapToLevel(CodeGenOpts);
  817. bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
  818. bool IsLTO = CodeGenOpts.PrepareForLTO;
  819. if (LangOpts.ObjCAutoRefCount) {
  820. PB.registerPipelineStartEPCallback(
  821. [](ModulePassManager &MPM, OptimizationLevel Level) {
  822. if (Level != OptimizationLevel::O0)
  823. MPM.addPass(
  824. createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
  825. });
  826. PB.registerPipelineEarlySimplificationEPCallback(
  827. [](ModulePassManager &MPM, OptimizationLevel Level) {
  828. if (Level != OptimizationLevel::O0)
  829. MPM.addPass(ObjCARCAPElimPass());
  830. });
  831. PB.registerScalarOptimizerLateEPCallback(
  832. [](FunctionPassManager &FPM, OptimizationLevel Level) {
  833. if (Level != OptimizationLevel::O0)
  834. FPM.addPass(ObjCARCOptPass());
  835. });
  836. }
  837. // If we reached here with a non-empty index file name, then the index
  838. // file was empty and we are not performing ThinLTO backend compilation
  839. // (used in testing in a distributed build environment).
  840. bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
  841. // If so drop any the type test assume sequences inserted for whole program
  842. // vtables so that codegen doesn't complain.
  843. if (IsThinLTOPostLink)
  844. PB.registerPipelineStartEPCallback(
  845. [](ModulePassManager &MPM, OptimizationLevel Level) {
  846. MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
  847. /*ImportSummary=*/nullptr,
  848. /*DropTypeTests=*/true));
  849. });
  850. if (CodeGenOpts.InstrumentFunctions ||
  851. CodeGenOpts.InstrumentFunctionEntryBare ||
  852. CodeGenOpts.InstrumentFunctionsAfterInlining ||
  853. CodeGenOpts.InstrumentForProfiling) {
  854. PB.registerPipelineStartEPCallback(
  855. [](ModulePassManager &MPM, OptimizationLevel Level) {
  856. MPM.addPass(createModuleToFunctionPassAdaptor(
  857. EntryExitInstrumenterPass(/*PostInlining=*/false)));
  858. });
  859. PB.registerOptimizerLastEPCallback(
  860. [](ModulePassManager &MPM, OptimizationLevel Level) {
  861. MPM.addPass(createModuleToFunctionPassAdaptor(
  862. EntryExitInstrumenterPass(/*PostInlining=*/true)));
  863. });
  864. }
  865. // Register callbacks to schedule sanitizer passes at the appropriate part
  866. // of the pipeline.
  867. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  868. PB.registerScalarOptimizerLateEPCallback(
  869. [](FunctionPassManager &FPM, OptimizationLevel Level) {
  870. FPM.addPass(BoundsCheckingPass());
  871. });
  872. // Don't add sanitizers if we are here from ThinLTO PostLink. That already
  873. // done on PreLink stage.
  874. if (!IsThinLTOPostLink) {
  875. addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
  876. addKCFIPass(TargetTriple, LangOpts, PB);
  877. }
  878. if (std::optional<GCOVOptions> Options =
  879. getGCOVOptions(CodeGenOpts, LangOpts))
  880. PB.registerPipelineStartEPCallback(
  881. [Options](ModulePassManager &MPM, OptimizationLevel Level) {
  882. MPM.addPass(GCOVProfilerPass(*Options));
  883. });
  884. if (std::optional<InstrProfOptions> Options =
  885. getInstrProfOptions(CodeGenOpts, LangOpts))
  886. PB.registerPipelineStartEPCallback(
  887. [Options](ModulePassManager &MPM, OptimizationLevel Level) {
  888. MPM.addPass(InstrProfiling(*Options, false));
  889. });
  890. if (CodeGenOpts.OptimizationLevel == 0) {
  891. MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
  892. } else if (IsThinLTO) {
  893. MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
  894. } else if (IsLTO) {
  895. MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
  896. } else {
  897. MPM = PB.buildPerModuleDefaultPipeline(Level);
  898. }
  899. if (!CodeGenOpts.MemoryProfileOutput.empty()) {
  900. MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
  901. MPM.addPass(ModuleMemProfilerPass());
  902. }
  903. }
  904. // Add a verifier pass if requested. We don't have to do this if the action
  905. // requires code generation because there will already be a verifier pass in
  906. // the code-generation pipeline.
  907. if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
  908. MPM.addPass(VerifierPass());
  909. if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
  910. if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
  911. if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
  912. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  913. CodeGenOpts.EnableSplitLTOUnit);
  914. if (Action == Backend_EmitBC) {
  915. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  916. ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
  917. if (!ThinLinkOS)
  918. return;
  919. }
  920. MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
  921. : nullptr));
  922. } else {
  923. MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
  924. /*EmitLTOSummary=*/true));
  925. }
  926. } else {
  927. // Emit a module summary by default for Regular LTO except for ld64
  928. // targets
  929. bool EmitLTOSummary = shouldEmitRegularLTOSummary();
  930. if (EmitLTOSummary) {
  931. if (!TheModule->getModuleFlag("ThinLTO"))
  932. TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
  933. if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
  934. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  935. uint32_t(1));
  936. }
  937. if (Action == Backend_EmitBC)
  938. MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
  939. EmitLTOSummary));
  940. else
  941. MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
  942. EmitLTOSummary));
  943. }
  944. }
  945. // Now that we have all of the passes ready, run them.
  946. {
  947. PrettyStackTraceString CrashInfo("Optimizer");
  948. llvm::TimeTraceScope TimeScope("Optimizer");
  949. MPM.run(*TheModule, MAM);
  950. }
  951. }
  952. void EmitAssemblyHelper::RunCodegenPipeline(
  953. BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
  954. std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
  955. // We still use the legacy PM to run the codegen pipeline since the new PM
  956. // does not work with the codegen pipeline.
  957. // FIXME: make the new PM work with the codegen pipeline.
  958. legacy::PassManager CodeGenPasses;
  959. // Append any output we need to the pass manager.
  960. switch (Action) {
  961. case Backend_EmitAssembly:
  962. case Backend_EmitMCNull:
  963. case Backend_EmitObj:
  964. CodeGenPasses.add(
  965. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  966. if (!CodeGenOpts.SplitDwarfOutput.empty()) {
  967. DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
  968. if (!DwoOS)
  969. return;
  970. }
  971. if (!AddEmitPasses(CodeGenPasses, Action, *OS,
  972. DwoOS ? &DwoOS->os() : nullptr))
  973. // FIXME: Should we handle this error differently?
  974. return;
  975. break;
  976. default:
  977. return;
  978. }
  979. {
  980. PrettyStackTraceString CrashInfo("Code generation");
  981. llvm::TimeTraceScope TimeScope("CodeGenPasses");
  982. CodeGenPasses.run(*TheModule);
  983. }
  984. }
  985. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  986. std::unique_ptr<raw_pwrite_stream> OS) {
  987. TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
  988. setCommandLineOpts(CodeGenOpts);
  989. bool RequiresCodeGen = actionRequiresCodeGen(Action);
  990. CreateTargetMachine(RequiresCodeGen);
  991. if (RequiresCodeGen && !TM)
  992. return;
  993. if (TM)
  994. TheModule->setDataLayout(TM->createDataLayout());
  995. // Before executing passes, print the final values of the LLVM options.
  996. cl::PrintOptionValues();
  997. std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
  998. RunOptimizationPipeline(Action, OS, ThinLinkOS);
  999. RunCodegenPipeline(Action, OS, DwoOS);
  1000. if (ThinLinkOS)
  1001. ThinLinkOS->keep();
  1002. if (DwoOS)
  1003. DwoOS->keep();
  1004. }
  1005. static void runThinLTOBackend(
  1006. DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
  1007. const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
  1008. const clang::TargetOptions &TOpts, const LangOptions &LOpts,
  1009. std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
  1010. std::string ProfileRemapping, BackendAction Action) {
  1011. StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
  1012. ModuleToDefinedGVSummaries;
  1013. CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
  1014. setCommandLineOpts(CGOpts);
  1015. // We can simply import the values mentioned in the combined index, since
  1016. // we should only invoke this using the individual indexes written out
  1017. // via a WriteIndexesThinBackend.
  1018. FunctionImporter::ImportMapTy ImportList;
  1019. if (!lto::initImportList(*M, *CombinedIndex, ImportList))
  1020. return;
  1021. auto AddStream = [&](size_t Task, const Twine &ModuleName) {
  1022. return std::make_unique<CachedFileStream>(std::move(OS),
  1023. CGOpts.ObjectFilenameForDebug);
  1024. };
  1025. lto::Config Conf;
  1026. if (CGOpts.SaveTempsFilePrefix != "") {
  1027. if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
  1028. /* UseInputModulePath */ false)) {
  1029. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1030. errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
  1031. << '\n';
  1032. });
  1033. }
  1034. }
  1035. Conf.CPU = TOpts.CPU;
  1036. Conf.CodeModel = getCodeModel(CGOpts);
  1037. Conf.MAttrs = TOpts.Features;
  1038. Conf.RelocModel = CGOpts.RelocationModel;
  1039. std::optional<CodeGenOpt::Level> OptLevelOrNone =
  1040. CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
  1041. assert(OptLevelOrNone && "Invalid optimization level!");
  1042. Conf.CGOptLevel = *OptLevelOrNone;
  1043. Conf.OptLevel = CGOpts.OptimizationLevel;
  1044. initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
  1045. Conf.SampleProfile = std::move(SampleProfile);
  1046. Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
  1047. // For historical reasons, loop interleaving is set to mirror setting for loop
  1048. // unrolling.
  1049. Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
  1050. Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
  1051. Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
  1052. // Only enable CGProfilePass when using integrated assembler, since
  1053. // non-integrated assemblers don't recognize .cgprofile section.
  1054. Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
  1055. // Context sensitive profile.
  1056. if (CGOpts.hasProfileCSIRInstr()) {
  1057. Conf.RunCSIRInstr = true;
  1058. Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
  1059. } else if (CGOpts.hasProfileCSIRUse()) {
  1060. Conf.RunCSIRInstr = false;
  1061. Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
  1062. }
  1063. Conf.ProfileRemapping = std::move(ProfileRemapping);
  1064. Conf.DebugPassManager = CGOpts.DebugPassManager;
  1065. Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
  1066. Conf.RemarksFilename = CGOpts.OptRecordFile;
  1067. Conf.RemarksPasses = CGOpts.OptRecordPasses;
  1068. Conf.RemarksFormat = CGOpts.OptRecordFormat;
  1069. Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
  1070. Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
  1071. switch (Action) {
  1072. case Backend_EmitNothing:
  1073. Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
  1074. return false;
  1075. };
  1076. break;
  1077. case Backend_EmitLL:
  1078. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1079. M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
  1080. return false;
  1081. };
  1082. break;
  1083. case Backend_EmitBC:
  1084. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1085. WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
  1086. return false;
  1087. };
  1088. break;
  1089. default:
  1090. Conf.CGFileType = getCodeGenFileType(Action);
  1091. break;
  1092. }
  1093. if (Error E =
  1094. thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
  1095. ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
  1096. /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
  1097. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1098. errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
  1099. });
  1100. }
  1101. }
  1102. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  1103. const HeaderSearchOptions &HeaderOpts,
  1104. const CodeGenOptions &CGOpts,
  1105. const clang::TargetOptions &TOpts,
  1106. const LangOptions &LOpts,
  1107. StringRef TDesc, Module *M,
  1108. BackendAction Action,
  1109. std::unique_ptr<raw_pwrite_stream> OS) {
  1110. llvm::TimeTraceScope TimeScope("Backend");
  1111. std::unique_ptr<llvm::Module> EmptyModule;
  1112. if (!CGOpts.ThinLTOIndexFile.empty()) {
  1113. // If we are performing a ThinLTO importing compile, load the function index
  1114. // into memory and pass it into runThinLTOBackend, which will run the
  1115. // function importer and invoke LTO passes.
  1116. std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
  1117. if (Error E = llvm::getModuleSummaryIndexForFile(
  1118. CGOpts.ThinLTOIndexFile,
  1119. /*IgnoreEmptyThinLTOIndexFile*/ true)
  1120. .moveInto(CombinedIndex)) {
  1121. logAllUnhandledErrors(std::move(E), errs(),
  1122. "Error loading index file '" +
  1123. CGOpts.ThinLTOIndexFile + "': ");
  1124. return;
  1125. }
  1126. // A null CombinedIndex means we should skip ThinLTO compilation
  1127. // (LLVM will optionally ignore empty index files, returning null instead
  1128. // of an error).
  1129. if (CombinedIndex) {
  1130. if (!CombinedIndex->skipModuleByDistributedBackend()) {
  1131. runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
  1132. TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
  1133. CGOpts.ProfileRemappingFile, Action);
  1134. return;
  1135. }
  1136. // Distributed indexing detected that nothing from the module is needed
  1137. // for the final linking. So we can skip the compilation. We sill need to
  1138. // output an empty object file to make sure that a linker does not fail
  1139. // trying to read it. Also for some features, like CFI, we must skip
  1140. // the compilation as CombinedIndex does not contain all required
  1141. // information.
  1142. EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
  1143. EmptyModule->setTargetTriple(M->getTargetTriple());
  1144. M = EmptyModule.get();
  1145. }
  1146. }
  1147. EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
  1148. AsmHelper.EmitAssembly(Action, std::move(OS));
  1149. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  1150. // DataLayout.
  1151. if (AsmHelper.TM) {
  1152. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  1153. if (DLDesc != TDesc) {
  1154. unsigned DiagID = Diags.getCustomDiagID(
  1155. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  1156. "expected target description '%1'");
  1157. Diags.Report(DiagID) << DLDesc << TDesc;
  1158. }
  1159. }
  1160. }
  1161. // With -fembed-bitcode, save a copy of the llvm IR as data in the
  1162. // __LLVM,__bitcode section.
  1163. void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
  1164. llvm::MemoryBufferRef Buf) {
  1165. if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
  1166. return;
  1167. llvm::embedBitcodeInModule(
  1168. *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
  1169. CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
  1170. CGOpts.CmdArgs);
  1171. }
  1172. void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
  1173. DiagnosticsEngine &Diags) {
  1174. if (CGOpts.OffloadObjects.empty())
  1175. return;
  1176. for (StringRef OffloadObject : CGOpts.OffloadObjects) {
  1177. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
  1178. llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
  1179. if (std::error_code EC = ObjectOrErr.getError()) {
  1180. auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1181. "could not open '%0' for embedding");
  1182. Diags.Report(DiagID) << OffloadObject;
  1183. return;
  1184. }
  1185. llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
  1186. Align(object::OffloadBinary::getAlignment()));
  1187. }
  1188. }