BackendUtil.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  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/TargetLibraryInfo.h"
  21. #include "llvm/Analysis/TargetTransformInfo.h"
  22. #include "llvm/Bitcode/BitcodeReader.h"
  23. #include "llvm/Bitcode/BitcodeWriter.h"
  24. #include "llvm/Bitcode/BitcodeWriterPass.h"
  25. #include "llvm/CodeGen/RegAllocRegistry.h"
  26. #include "llvm/CodeGen/SchedulerRegistry.h"
  27. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/IRPrintingPasses.h"
  30. #include "llvm/IR/LegacyPassManager.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/ModuleSummaryIndex.h"
  33. #include "llvm/IR/Verifier.h"
  34. #include "llvm/LTO/LTOBackend.h"
  35. #include "llvm/MC/MCAsmInfo.h"
  36. #include "llvm/MC/SubtargetFeature.h"
  37. #include "llvm/Passes/PassBuilder.h"
  38. #include "llvm/Passes/PassPlugin.h"
  39. #include "llvm/Passes/StandardInstrumentations.h"
  40. #include "llvm/Support/BuryPointer.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/MemoryBuffer.h"
  43. #include "llvm/Support/PrettyStackTrace.h"
  44. #include "llvm/Support/TargetRegistry.h"
  45. #include "llvm/Support/TimeProfiler.h"
  46. #include "llvm/Support/Timer.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Target/TargetMachine.h"
  49. #include "llvm/Target/TargetOptions.h"
  50. #include "llvm/Transforms/Coroutines.h"
  51. #include "llvm/Transforms/IPO.h"
  52. #include "llvm/Transforms/IPO/AlwaysInliner.h"
  53. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  54. #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
  55. #include "llvm/Transforms/InstCombine/InstCombine.h"
  56. #include "llvm/Transforms/Instrumentation.h"
  57. #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
  58. #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
  59. #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
  60. #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
  61. #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
  62. #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
  63. #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
  64. #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
  65. #include "llvm/Transforms/ObjCARC.h"
  66. #include "llvm/Transforms/Scalar.h"
  67. #include "llvm/Transforms/Scalar/GVN.h"
  68. #include "llvm/Transforms/Utils.h"
  69. #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
  70. #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
  71. #include "llvm/Transforms/Utils/NameAnonGlobals.h"
  72. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  73. #include <memory>
  74. using namespace clang;
  75. using namespace llvm;
  76. namespace {
  77. // Default filename used for profile generation.
  78. static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
  79. class EmitAssemblyHelper {
  80. DiagnosticsEngine &Diags;
  81. const HeaderSearchOptions &HSOpts;
  82. const CodeGenOptions &CodeGenOpts;
  83. const clang::TargetOptions &TargetOpts;
  84. const LangOptions &LangOpts;
  85. Module *TheModule;
  86. Timer CodeGenerationTime;
  87. std::unique_ptr<raw_pwrite_stream> OS;
  88. TargetIRAnalysis getTargetIRAnalysis() const {
  89. if (TM)
  90. return TM->getTargetIRAnalysis();
  91. return TargetIRAnalysis();
  92. }
  93. void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
  94. /// Generates the TargetMachine.
  95. /// Leaves TM unchanged if it is unable to create the target machine.
  96. /// Some of our clang tests specify triples which are not built
  97. /// into clang. This is okay because these tests check the generated
  98. /// IR, and they require DataLayout which depends on the triple.
  99. /// In this case, we allow this method to fail and not report an error.
  100. /// When MustCreateTM is used, we print an error if we are unable to load
  101. /// the requested target.
  102. void CreateTargetMachine(bool MustCreateTM);
  103. /// Add passes necessary to emit assembly or LLVM IR.
  104. ///
  105. /// \return True on success.
  106. bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
  107. raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
  108. std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
  109. std::error_code EC;
  110. auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
  111. llvm::sys::fs::OF_None);
  112. if (EC) {
  113. Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
  114. F.reset();
  115. }
  116. return F;
  117. }
  118. public:
  119. EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  120. const HeaderSearchOptions &HeaderSearchOpts,
  121. const CodeGenOptions &CGOpts,
  122. const clang::TargetOptions &TOpts,
  123. const LangOptions &LOpts, Module *M)
  124. : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
  125. TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
  126. CodeGenerationTime("codegen", "Code Generation Time") {}
  127. ~EmitAssemblyHelper() {
  128. if (CodeGenOpts.DisableFree)
  129. BuryPointer(std::move(TM));
  130. }
  131. std::unique_ptr<TargetMachine> TM;
  132. void EmitAssembly(BackendAction Action,
  133. std::unique_ptr<raw_pwrite_stream> OS);
  134. void EmitAssemblyWithNewPassManager(BackendAction Action,
  135. std::unique_ptr<raw_pwrite_stream> OS);
  136. };
  137. // We need this wrapper to access LangOpts and CGOpts from extension functions
  138. // that we add to the PassManagerBuilder.
  139. class PassManagerBuilderWrapper : public PassManagerBuilder {
  140. public:
  141. PassManagerBuilderWrapper(const Triple &TargetTriple,
  142. const CodeGenOptions &CGOpts,
  143. const LangOptions &LangOpts)
  144. : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
  145. LangOpts(LangOpts) {}
  146. const Triple &getTargetTriple() const { return TargetTriple; }
  147. const CodeGenOptions &getCGOpts() const { return CGOpts; }
  148. const LangOptions &getLangOpts() const { return LangOpts; }
  149. private:
  150. const Triple &TargetTriple;
  151. const CodeGenOptions &CGOpts;
  152. const LangOptions &LangOpts;
  153. };
  154. }
  155. static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  156. if (Builder.OptLevel > 0)
  157. PM.add(createObjCARCAPElimPass());
  158. }
  159. static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  160. if (Builder.OptLevel > 0)
  161. PM.add(createObjCARCExpandPass());
  162. }
  163. static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  164. if (Builder.OptLevel > 0)
  165. PM.add(createObjCARCOptPass());
  166. }
  167. static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
  168. legacy::PassManagerBase &PM) {
  169. PM.add(createAddDiscriminatorsPass());
  170. }
  171. static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
  172. legacy::PassManagerBase &PM) {
  173. PM.add(createBoundsCheckingLegacyPass());
  174. }
  175. static SanitizerCoverageOptions
  176. getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
  177. SanitizerCoverageOptions Opts;
  178. Opts.CoverageType =
  179. static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
  180. Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
  181. Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
  182. Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
  183. Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
  184. Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
  185. Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
  186. Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
  187. Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
  188. Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
  189. Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
  190. Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
  191. Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
  192. return Opts;
  193. }
  194. static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
  195. legacy::PassManagerBase &PM) {
  196. const PassManagerBuilderWrapper &BuilderWrapper =
  197. static_cast<const PassManagerBuilderWrapper &>(Builder);
  198. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  199. auto Opts = getSancovOptsFromCGOpts(CGOpts);
  200. PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts));
  201. }
  202. // Check if ASan should use GC-friendly instrumentation for globals.
  203. // First of all, there is no point if -fdata-sections is off (expect for MachO,
  204. // where this is not a factor). Also, on ELF this feature requires an assembler
  205. // extension that only works with -integrated-as at the moment.
  206. static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
  207. if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
  208. return false;
  209. switch (T.getObjectFormat()) {
  210. case Triple::MachO:
  211. case Triple::COFF:
  212. return true;
  213. case Triple::ELF:
  214. return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
  215. case Triple::XCOFF:
  216. llvm::report_fatal_error("ASan not implemented for XCOFF.");
  217. case Triple::Wasm:
  218. case Triple::UnknownObjectFormat:
  219. break;
  220. }
  221. return false;
  222. }
  223. static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
  224. legacy::PassManagerBase &PM) {
  225. const PassManagerBuilderWrapper &BuilderWrapper =
  226. static_cast<const PassManagerBuilderWrapper&>(Builder);
  227. const Triple &T = BuilderWrapper.getTargetTriple();
  228. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  229. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
  230. bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
  231. bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
  232. bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
  233. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
  234. UseAfterScope));
  235. PM.add(createModuleAddressSanitizerLegacyPassPass(
  236. /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
  237. }
  238. static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
  239. legacy::PassManagerBase &PM) {
  240. PM.add(createAddressSanitizerFunctionPass(
  241. /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
  242. PM.add(createModuleAddressSanitizerLegacyPassPass(
  243. /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
  244. /*UseOdrIndicator*/ false));
  245. }
  246. static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
  247. legacy::PassManagerBase &PM) {
  248. const PassManagerBuilderWrapper &BuilderWrapper =
  249. static_cast<const PassManagerBuilderWrapper &>(Builder);
  250. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  251. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
  252. PM.add(
  253. createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
  254. }
  255. static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
  256. legacy::PassManagerBase &PM) {
  257. PM.add(createHWAddressSanitizerLegacyPassPass(
  258. /*CompileKernel*/ true, /*Recover*/ true));
  259. }
  260. static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
  261. legacy::PassManagerBase &PM,
  262. bool CompileKernel) {
  263. const PassManagerBuilderWrapper &BuilderWrapper =
  264. static_cast<const PassManagerBuilderWrapper&>(Builder);
  265. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  266. int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
  267. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
  268. PM.add(createMemorySanitizerLegacyPassPass(
  269. MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
  270. // MemorySanitizer inserts complex instrumentation that mostly follows
  271. // the logic of the original code, but operates on "shadow" values.
  272. // It can benefit from re-running some general purpose optimization passes.
  273. if (Builder.OptLevel > 0) {
  274. PM.add(createEarlyCSEPass());
  275. PM.add(createReassociatePass());
  276. PM.add(createLICMPass());
  277. PM.add(createGVNPass());
  278. PM.add(createInstructionCombiningPass());
  279. PM.add(createDeadStoreEliminationPass());
  280. }
  281. }
  282. static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
  283. legacy::PassManagerBase &PM) {
  284. addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
  285. }
  286. static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
  287. legacy::PassManagerBase &PM) {
  288. addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
  289. }
  290. static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
  291. legacy::PassManagerBase &PM) {
  292. PM.add(createThreadSanitizerLegacyPassPass());
  293. }
  294. static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
  295. legacy::PassManagerBase &PM) {
  296. const PassManagerBuilderWrapper &BuilderWrapper =
  297. static_cast<const PassManagerBuilderWrapper&>(Builder);
  298. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  299. PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
  300. }
  301. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  302. const CodeGenOptions &CodeGenOpts) {
  303. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  304. if (!CodeGenOpts.SimplifyLibCalls)
  305. TLII->disableAllFunctions();
  306. else {
  307. // Disable individual libc/libm calls in TargetLibraryInfo.
  308. LibFunc F;
  309. for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
  310. if (TLII->getLibFunc(FuncName, F))
  311. TLII->setUnavailable(F);
  312. }
  313. switch (CodeGenOpts.getVecLib()) {
  314. case CodeGenOptions::Accelerate:
  315. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
  316. break;
  317. case CodeGenOptions::MASSV:
  318. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
  319. break;
  320. case CodeGenOptions::SVML:
  321. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
  322. break;
  323. default:
  324. break;
  325. }
  326. return TLII;
  327. }
  328. static void addSymbolRewriterPass(const CodeGenOptions &Opts,
  329. legacy::PassManager *MPM) {
  330. llvm::SymbolRewriter::RewriteDescriptorList DL;
  331. llvm::SymbolRewriter::RewriteMapParser MapParser;
  332. for (const auto &MapFile : Opts.RewriteMapFiles)
  333. MapParser.parse(MapFile, &DL);
  334. MPM->add(createRewriteSymbolsPass(DL));
  335. }
  336. static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
  337. switch (CodeGenOpts.OptimizationLevel) {
  338. default:
  339. llvm_unreachable("Invalid optimization level!");
  340. case 0:
  341. return CodeGenOpt::None;
  342. case 1:
  343. return CodeGenOpt::Less;
  344. case 2:
  345. return CodeGenOpt::Default; // O2/Os/Oz
  346. case 3:
  347. return CodeGenOpt::Aggressive;
  348. }
  349. }
  350. static Optional<llvm::CodeModel::Model>
  351. getCodeModel(const CodeGenOptions &CodeGenOpts) {
  352. unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  353. .Case("tiny", llvm::CodeModel::Tiny)
  354. .Case("small", llvm::CodeModel::Small)
  355. .Case("kernel", llvm::CodeModel::Kernel)
  356. .Case("medium", llvm::CodeModel::Medium)
  357. .Case("large", llvm::CodeModel::Large)
  358. .Case("default", ~1u)
  359. .Default(~0u);
  360. assert(CodeModel != ~0u && "invalid code model!");
  361. if (CodeModel == ~1u)
  362. return None;
  363. return static_cast<llvm::CodeModel::Model>(CodeModel);
  364. }
  365. static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
  366. if (Action == Backend_EmitObj)
  367. return TargetMachine::CGFT_ObjectFile;
  368. else if (Action == Backend_EmitMCNull)
  369. return TargetMachine::CGFT_Null;
  370. else {
  371. assert(Action == Backend_EmitAssembly && "Invalid action!");
  372. return TargetMachine::CGFT_AssemblyFile;
  373. }
  374. }
  375. static void initTargetOptions(llvm::TargetOptions &Options,
  376. const CodeGenOptions &CodeGenOpts,
  377. const clang::TargetOptions &TargetOpts,
  378. const LangOptions &LangOpts,
  379. const HeaderSearchOptions &HSOpts) {
  380. Options.ThreadModel =
  381. llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
  382. .Case("posix", llvm::ThreadModel::POSIX)
  383. .Case("single", llvm::ThreadModel::Single);
  384. // Set float ABI type.
  385. assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
  386. CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
  387. "Invalid Floating Point ABI!");
  388. Options.FloatABIType =
  389. llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
  390. .Case("soft", llvm::FloatABI::Soft)
  391. .Case("softfp", llvm::FloatABI::Soft)
  392. .Case("hard", llvm::FloatABI::Hard)
  393. .Default(llvm::FloatABI::Default);
  394. // Set FP fusion mode.
  395. switch (LangOpts.getDefaultFPContractMode()) {
  396. case LangOptions::FPC_Off:
  397. // Preserve any contraction performed by the front-end. (Strict performs
  398. // splitting of the muladd intrinsic in the backend.)
  399. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  400. break;
  401. case LangOptions::FPC_On:
  402. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  403. break;
  404. case LangOptions::FPC_Fast:
  405. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  406. break;
  407. }
  408. Options.UseInitArray = CodeGenOpts.UseInitArray;
  409. Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
  410. Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
  411. Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
  412. // Set EABI version.
  413. Options.EABIVersion = TargetOpts.EABIVersion;
  414. if (LangOpts.SjLjExceptions)
  415. Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
  416. if (LangOpts.SEHExceptions)
  417. Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
  418. if (LangOpts.DWARFExceptions)
  419. Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
  420. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  421. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  422. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  423. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  424. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  425. Options.FunctionSections = CodeGenOpts.FunctionSections;
  426. Options.DataSections = CodeGenOpts.DataSections;
  427. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  428. Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
  429. Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
  430. Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
  431. Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
  432. Options.EmitAddrsig = CodeGenOpts.Addrsig;
  433. Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
  434. Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
  435. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  436. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  437. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  438. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  439. Options.MCOptions.MCIncrementalLinkerCompatible =
  440. CodeGenOpts.IncrementalLinkerCompatible;
  441. Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
  442. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  443. Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
  444. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  445. Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
  446. Options.MCOptions.ABIName = TargetOpts.ABI;
  447. for (const auto &Entry : HSOpts.UserEntries)
  448. if (!Entry.IsFramework &&
  449. (Entry.Group == frontend::IncludeDirGroup::Quoted ||
  450. Entry.Group == frontend::IncludeDirGroup::Angled ||
  451. Entry.Group == frontend::IncludeDirGroup::System))
  452. Options.MCOptions.IASSearchPaths.push_back(
  453. Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
  454. }
  455. static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
  456. if (CodeGenOpts.DisableGCov)
  457. return None;
  458. if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
  459. return None;
  460. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  461. // LLVM's -default-gcov-version flag is set to something invalid.
  462. GCOVOptions Options;
  463. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  464. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  465. llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
  466. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  467. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  468. Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
  469. Options.Filter = CodeGenOpts.ProfileFilterFiles;
  470. Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
  471. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  472. return Options;
  473. }
  474. static Optional<InstrProfOptions>
  475. getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
  476. const LangOptions &LangOpts) {
  477. if (!CodeGenOpts.hasProfileClangInstr())
  478. return None;
  479. InstrProfOptions Options;
  480. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  481. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  482. // TODO: Surface the option to emit atomic profile counter increments at
  483. // the driver level.
  484. Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
  485. return Options;
  486. }
  487. void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
  488. legacy::FunctionPassManager &FPM) {
  489. // Handle disabling of all LLVM passes, where we want to preserve the
  490. // internal module before any optimization.
  491. if (CodeGenOpts.DisableLLVMPasses)
  492. return;
  493. // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
  494. // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
  495. // are inserted before PMBuilder ones - they'd get the default-constructed
  496. // TLI with an unknown target otherwise.
  497. Triple TargetTriple(TheModule->getTargetTriple());
  498. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  499. createTLII(TargetTriple, CodeGenOpts));
  500. PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
  501. // At O0 and O1 we only run the always inliner which is more efficient. At
  502. // higher optimization levels we run the normal inliner.
  503. if (CodeGenOpts.OptimizationLevel <= 1) {
  504. bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
  505. !CodeGenOpts.DisableLifetimeMarkers);
  506. PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
  507. } else {
  508. // We do not want to inline hot callsites for SamplePGO module-summary build
  509. // because profile annotation will happen again in ThinLTO backend, and we
  510. // want the IR of the hot path to match the profile.
  511. PMBuilder.Inliner = createFunctionInliningPass(
  512. CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
  513. (!CodeGenOpts.SampleProfileFile.empty() &&
  514. CodeGenOpts.PrepareForThinLTO));
  515. }
  516. PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
  517. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  518. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  519. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  520. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  521. // Loop interleaving in the loop vectorizer has historically been set to be
  522. // enabled when loop unrolling is enabled.
  523. PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
  524. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  525. PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
  526. PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
  527. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  528. MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  529. if (TM)
  530. TM->adjustPassManager(PMBuilder);
  531. if (CodeGenOpts.DebugInfoForProfiling ||
  532. !CodeGenOpts.SampleProfileFile.empty())
  533. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  534. addAddDiscriminatorsPass);
  535. // In ObjC ARC mode, add the main ARC optimization passes.
  536. if (LangOpts.ObjCAutoRefCount) {
  537. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  538. addObjCARCExpandPass);
  539. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  540. addObjCARCAPElimPass);
  541. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  542. addObjCARCOptPass);
  543. }
  544. if (LangOpts.Coroutines)
  545. addCoroutinePassesToExtensionPoints(PMBuilder);
  546. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  547. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  548. addBoundsCheckingPass);
  549. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  550. addBoundsCheckingPass);
  551. }
  552. if (CodeGenOpts.SanitizeCoverageType ||
  553. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  554. CodeGenOpts.SanitizeCoverageTraceCmp) {
  555. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  556. addSanitizerCoveragePass);
  557. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  558. addSanitizerCoveragePass);
  559. }
  560. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  561. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  562. addAddressSanitizerPasses);
  563. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  564. addAddressSanitizerPasses);
  565. }
  566. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  567. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  568. addKernelAddressSanitizerPasses);
  569. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  570. addKernelAddressSanitizerPasses);
  571. }
  572. if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
  573. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  574. addHWAddressSanitizerPasses);
  575. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  576. addHWAddressSanitizerPasses);
  577. }
  578. if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
  579. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  580. addKernelHWAddressSanitizerPasses);
  581. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  582. addKernelHWAddressSanitizerPasses);
  583. }
  584. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  585. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  586. addMemorySanitizerPass);
  587. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  588. addMemorySanitizerPass);
  589. }
  590. if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
  591. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  592. addKernelMemorySanitizerPass);
  593. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  594. addKernelMemorySanitizerPass);
  595. }
  596. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  597. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  598. addThreadSanitizerPass);
  599. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  600. addThreadSanitizerPass);
  601. }
  602. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  603. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  604. addDataFlowSanitizerPass);
  605. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  606. addDataFlowSanitizerPass);
  607. }
  608. // Set up the per-function pass manager.
  609. FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  610. if (CodeGenOpts.VerifyModule)
  611. FPM.add(createVerifierPass());
  612. // Set up the per-module pass manager.
  613. if (!CodeGenOpts.RewriteMapFiles.empty())
  614. addSymbolRewriterPass(CodeGenOpts, &MPM);
  615. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
  616. MPM.add(createGCOVProfilerPass(*Options));
  617. if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
  618. MPM.add(createStripSymbolsPass(true));
  619. }
  620. if (Optional<InstrProfOptions> Options =
  621. getInstrProfOptions(CodeGenOpts, LangOpts))
  622. MPM.add(createInstrProfilingLegacyPass(*Options, false));
  623. bool hasIRInstr = false;
  624. if (CodeGenOpts.hasProfileIRInstr()) {
  625. PMBuilder.EnablePGOInstrGen = true;
  626. hasIRInstr = true;
  627. }
  628. if (CodeGenOpts.hasProfileCSIRInstr()) {
  629. assert(!CodeGenOpts.hasProfileCSIRUse() &&
  630. "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
  631. "same time");
  632. assert(!hasIRInstr &&
  633. "Cannot have both ProfileGen pass and CSProfileGen pass at the "
  634. "same time");
  635. PMBuilder.EnablePGOCSInstrGen = true;
  636. hasIRInstr = true;
  637. }
  638. if (hasIRInstr) {
  639. if (!CodeGenOpts.InstrProfileOutput.empty())
  640. PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
  641. else
  642. PMBuilder.PGOInstrGen = DefaultProfileGenName;
  643. }
  644. if (CodeGenOpts.hasProfileIRUse()) {
  645. PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
  646. PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
  647. }
  648. if (!CodeGenOpts.SampleProfileFile.empty())
  649. PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
  650. PMBuilder.populateFunctionPassManager(FPM);
  651. PMBuilder.populateModulePassManager(MPM);
  652. }
  653. static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
  654. SmallVector<const char *, 16> BackendArgs;
  655. BackendArgs.push_back("clang"); // Fake program name.
  656. if (!CodeGenOpts.DebugPass.empty()) {
  657. BackendArgs.push_back("-debug-pass");
  658. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  659. }
  660. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  661. BackendArgs.push_back("-limit-float-precision");
  662. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  663. }
  664. BackendArgs.push_back(nullptr);
  665. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  666. BackendArgs.data());
  667. }
  668. void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  669. // Create the TargetMachine for generating code.
  670. std::string Error;
  671. std::string Triple = TheModule->getTargetTriple();
  672. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  673. if (!TheTarget) {
  674. if (MustCreateTM)
  675. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  676. return;
  677. }
  678. Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
  679. std::string FeaturesStr =
  680. llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
  681. llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
  682. CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
  683. llvm::TargetOptions Options;
  684. initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
  685. TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
  686. Options, RM, CM, OptLevel));
  687. }
  688. bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
  689. BackendAction Action,
  690. raw_pwrite_stream &OS,
  691. raw_pwrite_stream *DwoOS) {
  692. // Add LibraryInfo.
  693. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  694. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  695. createTLII(TargetTriple, CodeGenOpts));
  696. CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
  697. // Normal mode, emit a .s or .o file by running the code generator. Note,
  698. // this also adds codegenerator level optimization passes.
  699. TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
  700. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  701. // "codegen" passes so that it isn't run multiple times when there is
  702. // inlining happening.
  703. if (CodeGenOpts.OptimizationLevel > 0)
  704. CodeGenPasses.add(createObjCARCContractPass());
  705. if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
  706. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  707. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  708. return false;
  709. }
  710. return true;
  711. }
  712. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  713. std::unique_ptr<raw_pwrite_stream> OS) {
  714. TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
  715. setCommandLineOpts(CodeGenOpts);
  716. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  717. Action != Backend_EmitBC &&
  718. Action != Backend_EmitLL);
  719. CreateTargetMachine(UsesCodeGen);
  720. if (UsesCodeGen && !TM)
  721. return;
  722. if (TM)
  723. TheModule->setDataLayout(TM->createDataLayout());
  724. legacy::PassManager PerModulePasses;
  725. PerModulePasses.add(
  726. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  727. legacy::FunctionPassManager PerFunctionPasses(TheModule);
  728. PerFunctionPasses.add(
  729. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  730. CreatePasses(PerModulePasses, PerFunctionPasses);
  731. legacy::PassManager CodeGenPasses;
  732. CodeGenPasses.add(
  733. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  734. std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
  735. switch (Action) {
  736. case Backend_EmitNothing:
  737. break;
  738. case Backend_EmitBC:
  739. if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
  740. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  741. ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
  742. if (!ThinLinkOS)
  743. return;
  744. }
  745. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  746. CodeGenOpts.EnableSplitLTOUnit);
  747. PerModulePasses.add(createWriteThinLTOBitcodePass(
  748. *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
  749. } else {
  750. // Emit a module summary by default for Regular LTO except for ld64
  751. // targets
  752. bool EmitLTOSummary =
  753. (CodeGenOpts.PrepareForLTO &&
  754. !CodeGenOpts.DisableLLVMPasses &&
  755. llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
  756. llvm::Triple::Apple);
  757. if (EmitLTOSummary) {
  758. if (!TheModule->getModuleFlag("ThinLTO"))
  759. TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
  760. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  761. uint32_t(1));
  762. }
  763. PerModulePasses.add(createBitcodeWriterPass(
  764. *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
  765. }
  766. break;
  767. case Backend_EmitLL:
  768. PerModulePasses.add(
  769. createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  770. break;
  771. default:
  772. if (!CodeGenOpts.SplitDwarfOutput.empty()) {
  773. DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
  774. if (!DwoOS)
  775. return;
  776. }
  777. if (!AddEmitPasses(CodeGenPasses, Action, *OS,
  778. DwoOS ? &DwoOS->os() : nullptr))
  779. return;
  780. }
  781. // Before executing passes, print the final values of the LLVM options.
  782. cl::PrintOptionValues();
  783. // Run passes. For now we do all passes at once, but eventually we
  784. // would like to have the option of streaming code generation.
  785. {
  786. PrettyStackTraceString CrashInfo("Per-function optimization");
  787. PerFunctionPasses.doInitialization();
  788. for (Function &F : *TheModule)
  789. if (!F.isDeclaration())
  790. PerFunctionPasses.run(F);
  791. PerFunctionPasses.doFinalization();
  792. }
  793. {
  794. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  795. PerModulePasses.run(*TheModule);
  796. }
  797. {
  798. PrettyStackTraceString CrashInfo("Code generation");
  799. CodeGenPasses.run(*TheModule);
  800. }
  801. if (ThinLinkOS)
  802. ThinLinkOS->keep();
  803. if (DwoOS)
  804. DwoOS->keep();
  805. }
  806. static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
  807. switch (Opts.OptimizationLevel) {
  808. default:
  809. llvm_unreachable("Invalid optimization level!");
  810. case 1:
  811. return PassBuilder::O1;
  812. case 2:
  813. switch (Opts.OptimizeSize) {
  814. default:
  815. llvm_unreachable("Invalid optimization level for size!");
  816. case 0:
  817. return PassBuilder::O2;
  818. case 1:
  819. return PassBuilder::Os;
  820. case 2:
  821. return PassBuilder::Oz;
  822. }
  823. case 3:
  824. return PassBuilder::O3;
  825. }
  826. }
  827. static void addSanitizersAtO0(ModulePassManager &MPM,
  828. const Triple &TargetTriple,
  829. const LangOptions &LangOpts,
  830. const CodeGenOptions &CodeGenOpts) {
  831. auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
  832. MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
  833. bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
  834. MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
  835. CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
  836. bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
  837. MPM.addPass(
  838. ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
  839. CodeGenOpts.SanitizeAddressUseOdrIndicator));
  840. };
  841. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  842. ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
  843. }
  844. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  845. ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
  846. }
  847. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  848. MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
  849. }
  850. if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
  851. MPM.addPass(createModuleToFunctionPassAdaptor(
  852. MemorySanitizerPass({0, false, /*Kernel=*/true})));
  853. }
  854. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  855. MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
  856. }
  857. }
  858. /// A clean version of `EmitAssembly` that uses the new pass manager.
  859. ///
  860. /// Not all features are currently supported in this system, but where
  861. /// necessary it falls back to the legacy pass manager to at least provide
  862. /// basic functionality.
  863. ///
  864. /// This API is planned to have its functionality finished and then to replace
  865. /// `EmitAssembly` at some point in the future when the default switches.
  866. void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
  867. BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
  868. TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
  869. setCommandLineOpts(CodeGenOpts);
  870. bool RequiresCodeGen = (Action != Backend_EmitNothing &&
  871. Action != Backend_EmitBC &&
  872. Action != Backend_EmitLL);
  873. CreateTargetMachine(RequiresCodeGen);
  874. if (RequiresCodeGen && !TM)
  875. return;
  876. if (TM)
  877. TheModule->setDataLayout(TM->createDataLayout());
  878. Optional<PGOOptions> PGOOpt;
  879. if (CodeGenOpts.hasProfileIRInstr())
  880. // -fprofile-generate.
  881. PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
  882. ? DefaultProfileGenName
  883. : CodeGenOpts.InstrProfileOutput,
  884. "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
  885. CodeGenOpts.DebugInfoForProfiling);
  886. else if (CodeGenOpts.hasProfileIRUse()) {
  887. // -fprofile-use.
  888. auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
  889. : PGOOptions::NoCSAction;
  890. PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
  891. CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
  892. CSAction, CodeGenOpts.DebugInfoForProfiling);
  893. } else if (!CodeGenOpts.SampleProfileFile.empty())
  894. // -fprofile-sample-use
  895. PGOOpt =
  896. PGOOptions(CodeGenOpts.SampleProfileFile, "",
  897. CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
  898. PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
  899. else if (CodeGenOpts.DebugInfoForProfiling)
  900. // -fdebug-info-for-profiling
  901. PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
  902. PGOOptions::NoCSAction, true);
  903. // Check to see if we want to generate a CS profile.
  904. if (CodeGenOpts.hasProfileCSIRInstr()) {
  905. assert(!CodeGenOpts.hasProfileCSIRUse() &&
  906. "Cannot have both CSProfileUse pass and CSProfileGen pass at "
  907. "the same time");
  908. if (PGOOpt.hasValue()) {
  909. assert(PGOOpt->Action != PGOOptions::IRInstr &&
  910. PGOOpt->Action != PGOOptions::SampleUse &&
  911. "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
  912. " pass");
  913. PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
  914. ? DefaultProfileGenName
  915. : CodeGenOpts.InstrProfileOutput;
  916. PGOOpt->CSAction = PGOOptions::CSIRInstr;
  917. } else
  918. PGOOpt = PGOOptions("",
  919. CodeGenOpts.InstrProfileOutput.empty()
  920. ? DefaultProfileGenName
  921. : CodeGenOpts.InstrProfileOutput,
  922. "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
  923. CodeGenOpts.DebugInfoForProfiling);
  924. }
  925. PipelineTuningOptions PTO;
  926. PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
  927. // For historical reasons, loop interleaving is set to mirror setting for loop
  928. // unrolling.
  929. PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
  930. PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
  931. PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
  932. PassInstrumentationCallbacks PIC;
  933. StandardInstrumentations SI;
  934. SI.registerCallbacks(PIC);
  935. PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
  936. // Attempt to load pass plugins and register their callbacks with PB.
  937. for (auto &PluginFN : CodeGenOpts.PassPlugins) {
  938. auto PassPlugin = PassPlugin::Load(PluginFN);
  939. if (PassPlugin) {
  940. PassPlugin->registerPassBuilderCallbacks(PB);
  941. } else {
  942. Diags.Report(diag::err_fe_unable_to_load_plugin)
  943. << PluginFN << toString(PassPlugin.takeError());
  944. }
  945. }
  946. LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
  947. FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
  948. CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
  949. ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
  950. // Register the AA manager first so that our version is the one used.
  951. FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
  952. // Register the target library analysis directly and give it a customized
  953. // preset TLI.
  954. Triple TargetTriple(TheModule->getTargetTriple());
  955. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  956. createTLII(TargetTriple, CodeGenOpts));
  957. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  958. // Register all the basic analyses with the managers.
  959. PB.registerModuleAnalyses(MAM);
  960. PB.registerCGSCCAnalyses(CGAM);
  961. PB.registerFunctionAnalyses(FAM);
  962. PB.registerLoopAnalyses(LAM);
  963. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  964. ModulePassManager MPM(CodeGenOpts.DebugPassManager);
  965. if (!CodeGenOpts.DisableLLVMPasses) {
  966. bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
  967. bool IsLTO = CodeGenOpts.PrepareForLTO;
  968. if (CodeGenOpts.OptimizationLevel == 0) {
  969. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
  970. MPM.addPass(GCOVProfilerPass(*Options));
  971. if (Optional<InstrProfOptions> Options =
  972. getInstrProfOptions(CodeGenOpts, LangOpts))
  973. MPM.addPass(InstrProfiling(*Options, false));
  974. // Build a minimal pipeline based on the semantics required by Clang,
  975. // which is just that always inlining occurs. Further, disable generating
  976. // lifetime intrinsics to avoid enabling further optimizations during
  977. // code generation.
  978. MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
  979. // At -O0, we can still do PGO. Add all the requested passes for
  980. // instrumentation PGO, if requested.
  981. if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
  982. PGOOpt->Action == PGOOptions::IRUse))
  983. PB.addPGOInstrPassesForO0(
  984. MPM, CodeGenOpts.DebugPassManager,
  985. /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
  986. /* IsCS */ false, PGOOpt->ProfileFile,
  987. PGOOpt->ProfileRemappingFile);
  988. // At -O0 we directly run necessary sanitizer passes.
  989. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  990. MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
  991. // Lastly, add semantically necessary passes for LTO.
  992. if (IsLTO || IsThinLTO) {
  993. MPM.addPass(CanonicalizeAliasesPass());
  994. MPM.addPass(NameAnonGlobalPass());
  995. }
  996. } else {
  997. // Map our optimization levels into one of the distinct levels used to
  998. // configure the pipeline.
  999. PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
  1000. PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
  1001. MPM.addPass(createModuleToFunctionPassAdaptor(
  1002. EntryExitInstrumenterPass(/*PostInlining=*/false)));
  1003. });
  1004. if (CodeGenOpts.SanitizeCoverageType ||
  1005. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  1006. CodeGenOpts.SanitizeCoverageTraceCmp) {
  1007. auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
  1008. PB.registerPipelineStartEPCallback(
  1009. [SancovOpts](ModulePassManager &MPM) {
  1010. MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
  1011. });
  1012. }
  1013. // Register callbacks to schedule sanitizer passes at the appropriate part of
  1014. // the pipeline.
  1015. // FIXME: either handle asan/the remaining sanitizers or error out
  1016. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  1017. PB.registerScalarOptimizerLateEPCallback(
  1018. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1019. FPM.addPass(BoundsCheckingPass());
  1020. });
  1021. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  1022. PB.registerOptimizerLastEPCallback(
  1023. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1024. FPM.addPass(MemorySanitizerPass({}));
  1025. });
  1026. if (LangOpts.Sanitize.has(SanitizerKind::Thread))
  1027. PB.registerOptimizerLastEPCallback(
  1028. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1029. FPM.addPass(ThreadSanitizerPass());
  1030. });
  1031. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  1032. PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
  1033. MPM.addPass(
  1034. RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
  1035. });
  1036. bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
  1037. bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
  1038. PB.registerOptimizerLastEPCallback(
  1039. [Recover, UseAfterScope](FunctionPassManager &FPM,
  1040. PassBuilder::OptimizationLevel Level) {
  1041. FPM.addPass(AddressSanitizerPass(
  1042. /*CompileKernel=*/false, Recover, UseAfterScope));
  1043. });
  1044. bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
  1045. bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
  1046. PB.registerPipelineStartEPCallback(
  1047. [Recover, ModuleUseAfterScope,
  1048. UseOdrIndicator](ModulePassManager &MPM) {
  1049. MPM.addPass(ModuleAddressSanitizerPass(
  1050. /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
  1051. UseOdrIndicator));
  1052. });
  1053. }
  1054. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
  1055. PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
  1056. MPM.addPass(GCOVProfilerPass(*Options));
  1057. });
  1058. if (Optional<InstrProfOptions> Options =
  1059. getInstrProfOptions(CodeGenOpts, LangOpts))
  1060. PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
  1061. MPM.addPass(InstrProfiling(*Options, false));
  1062. });
  1063. if (IsThinLTO) {
  1064. MPM = PB.buildThinLTOPreLinkDefaultPipeline(
  1065. Level, CodeGenOpts.DebugPassManager);
  1066. MPM.addPass(CanonicalizeAliasesPass());
  1067. MPM.addPass(NameAnonGlobalPass());
  1068. } else if (IsLTO) {
  1069. MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
  1070. CodeGenOpts.DebugPassManager);
  1071. MPM.addPass(CanonicalizeAliasesPass());
  1072. MPM.addPass(NameAnonGlobalPass());
  1073. } else {
  1074. MPM = PB.buildPerModuleDefaultPipeline(Level,
  1075. CodeGenOpts.DebugPassManager);
  1076. }
  1077. }
  1078. if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
  1079. bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
  1080. MPM.addPass(HWAddressSanitizerPass(
  1081. /*CompileKernel=*/false, Recover));
  1082. }
  1083. if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
  1084. MPM.addPass(HWAddressSanitizerPass(
  1085. /*CompileKernel=*/true, /*Recover=*/true));
  1086. }
  1087. if (CodeGenOpts.OptimizationLevel == 0) {
  1088. if (CodeGenOpts.SanitizeCoverageType ||
  1089. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  1090. CodeGenOpts.SanitizeCoverageTraceCmp) {
  1091. auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
  1092. MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
  1093. }
  1094. addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
  1095. }
  1096. }
  1097. // FIXME: We still use the legacy pass manager to do code generation. We
  1098. // create that pass manager here and use it as needed below.
  1099. legacy::PassManager CodeGenPasses;
  1100. bool NeedCodeGen = false;
  1101. std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
  1102. // Append any output we need to the pass manager.
  1103. switch (Action) {
  1104. case Backend_EmitNothing:
  1105. break;
  1106. case Backend_EmitBC:
  1107. if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
  1108. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  1109. ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
  1110. if (!ThinLinkOS)
  1111. return;
  1112. }
  1113. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  1114. CodeGenOpts.EnableSplitLTOUnit);
  1115. MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
  1116. : nullptr));
  1117. } else {
  1118. // Emit a module summary by default for Regular LTO except for ld64
  1119. // targets
  1120. bool EmitLTOSummary =
  1121. (CodeGenOpts.PrepareForLTO &&
  1122. !CodeGenOpts.DisableLLVMPasses &&
  1123. llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
  1124. llvm::Triple::Apple);
  1125. if (EmitLTOSummary) {
  1126. if (!TheModule->getModuleFlag("ThinLTO"))
  1127. TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
  1128. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  1129. uint32_t(1));
  1130. }
  1131. MPM.addPass(
  1132. BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
  1133. }
  1134. break;
  1135. case Backend_EmitLL:
  1136. MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  1137. break;
  1138. case Backend_EmitAssembly:
  1139. case Backend_EmitMCNull:
  1140. case Backend_EmitObj:
  1141. NeedCodeGen = true;
  1142. CodeGenPasses.add(
  1143. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  1144. if (!CodeGenOpts.SplitDwarfOutput.empty()) {
  1145. DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
  1146. if (!DwoOS)
  1147. return;
  1148. }
  1149. if (!AddEmitPasses(CodeGenPasses, Action, *OS,
  1150. DwoOS ? &DwoOS->os() : nullptr))
  1151. // FIXME: Should we handle this error differently?
  1152. return;
  1153. break;
  1154. }
  1155. // Before executing passes, print the final values of the LLVM options.
  1156. cl::PrintOptionValues();
  1157. // Now that we have all of the passes ready, run them.
  1158. {
  1159. PrettyStackTraceString CrashInfo("Optimizer");
  1160. MPM.run(*TheModule, MAM);
  1161. }
  1162. // Now if needed, run the legacy PM for codegen.
  1163. if (NeedCodeGen) {
  1164. PrettyStackTraceString CrashInfo("Code generation");
  1165. CodeGenPasses.run(*TheModule);
  1166. }
  1167. if (ThinLinkOS)
  1168. ThinLinkOS->keep();
  1169. if (DwoOS)
  1170. DwoOS->keep();
  1171. }
  1172. Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
  1173. Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
  1174. if (!BMsOrErr)
  1175. return BMsOrErr.takeError();
  1176. // The bitcode file may contain multiple modules, we want the one that is
  1177. // marked as being the ThinLTO module.
  1178. if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
  1179. return *Bm;
  1180. return make_error<StringError>("Could not find module summary",
  1181. inconvertibleErrorCode());
  1182. }
  1183. BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
  1184. for (BitcodeModule &BM : BMs) {
  1185. Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
  1186. if (LTOInfo && LTOInfo->IsThinLTO)
  1187. return &BM;
  1188. }
  1189. return nullptr;
  1190. }
  1191. static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
  1192. const HeaderSearchOptions &HeaderOpts,
  1193. const CodeGenOptions &CGOpts,
  1194. const clang::TargetOptions &TOpts,
  1195. const LangOptions &LOpts,
  1196. std::unique_ptr<raw_pwrite_stream> OS,
  1197. std::string SampleProfile,
  1198. std::string ProfileRemapping,
  1199. BackendAction Action) {
  1200. StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
  1201. ModuleToDefinedGVSummaries;
  1202. CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
  1203. setCommandLineOpts(CGOpts);
  1204. // We can simply import the values mentioned in the combined index, since
  1205. // we should only invoke this using the individual indexes written out
  1206. // via a WriteIndexesThinBackend.
  1207. FunctionImporter::ImportMapTy ImportList;
  1208. for (auto &GlobalList : *CombinedIndex) {
  1209. // Ignore entries for undefined references.
  1210. if (GlobalList.second.SummaryList.empty())
  1211. continue;
  1212. auto GUID = GlobalList.first;
  1213. for (auto &Summary : GlobalList.second.SummaryList) {
  1214. // Skip the summaries for the importing module. These are included to
  1215. // e.g. record required linkage changes.
  1216. if (Summary->modulePath() == M->getModuleIdentifier())
  1217. continue;
  1218. // Add an entry to provoke importing by thinBackend.
  1219. ImportList[Summary->modulePath()].insert(GUID);
  1220. }
  1221. }
  1222. std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
  1223. MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
  1224. for (auto &I : ImportList) {
  1225. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
  1226. llvm::MemoryBuffer::getFile(I.first());
  1227. if (!MBOrErr) {
  1228. errs() << "Error loading imported file '" << I.first()
  1229. << "': " << MBOrErr.getError().message() << "\n";
  1230. return;
  1231. }
  1232. Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
  1233. if (!BMOrErr) {
  1234. handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  1235. errs() << "Error loading imported file '" << I.first()
  1236. << "': " << EIB.message() << '\n';
  1237. });
  1238. return;
  1239. }
  1240. ModuleMap.insert({I.first(), *BMOrErr});
  1241. OwnedImports.push_back(std::move(*MBOrErr));
  1242. }
  1243. auto AddStream = [&](size_t Task) {
  1244. return std::make_unique<lto::NativeObjectStream>(std::move(OS));
  1245. };
  1246. lto::Config Conf;
  1247. if (CGOpts.SaveTempsFilePrefix != "") {
  1248. if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
  1249. /* UseInputModulePath */ false)) {
  1250. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1251. errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
  1252. << '\n';
  1253. });
  1254. }
  1255. }
  1256. Conf.CPU = TOpts.CPU;
  1257. Conf.CodeModel = getCodeModel(CGOpts);
  1258. Conf.MAttrs = TOpts.Features;
  1259. Conf.RelocModel = CGOpts.RelocationModel;
  1260. Conf.CGOptLevel = getCGOptLevel(CGOpts);
  1261. Conf.OptLevel = CGOpts.OptimizationLevel;
  1262. initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
  1263. Conf.SampleProfile = std::move(SampleProfile);
  1264. // Context sensitive profile.
  1265. if (CGOpts.hasProfileCSIRInstr()) {
  1266. Conf.RunCSIRInstr = true;
  1267. Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
  1268. } else if (CGOpts.hasProfileCSIRUse()) {
  1269. Conf.RunCSIRInstr = false;
  1270. Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
  1271. }
  1272. Conf.ProfileRemapping = std::move(ProfileRemapping);
  1273. Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
  1274. Conf.DebugPassManager = CGOpts.DebugPassManager;
  1275. Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
  1276. Conf.RemarksFilename = CGOpts.OptRecordFile;
  1277. Conf.RemarksPasses = CGOpts.OptRecordPasses;
  1278. Conf.RemarksFormat = CGOpts.OptRecordFormat;
  1279. Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
  1280. Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
  1281. switch (Action) {
  1282. case Backend_EmitNothing:
  1283. Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
  1284. return false;
  1285. };
  1286. break;
  1287. case Backend_EmitLL:
  1288. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1289. M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
  1290. return false;
  1291. };
  1292. break;
  1293. case Backend_EmitBC:
  1294. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1295. WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
  1296. return false;
  1297. };
  1298. break;
  1299. default:
  1300. Conf.CGFileType = getCodeGenFileType(Action);
  1301. break;
  1302. }
  1303. if (Error E = thinBackend(
  1304. Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
  1305. ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
  1306. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1307. errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
  1308. });
  1309. }
  1310. }
  1311. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  1312. const HeaderSearchOptions &HeaderOpts,
  1313. const CodeGenOptions &CGOpts,
  1314. const clang::TargetOptions &TOpts,
  1315. const LangOptions &LOpts,
  1316. const llvm::DataLayout &TDesc, Module *M,
  1317. BackendAction Action,
  1318. std::unique_ptr<raw_pwrite_stream> OS) {
  1319. llvm::TimeTraceScope TimeScope("Backend", StringRef(""));
  1320. std::unique_ptr<llvm::Module> EmptyModule;
  1321. if (!CGOpts.ThinLTOIndexFile.empty()) {
  1322. // If we are performing a ThinLTO importing compile, load the function index
  1323. // into memory and pass it into runThinLTOBackend, which will run the
  1324. // function importer and invoke LTO passes.
  1325. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
  1326. llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
  1327. /*IgnoreEmptyThinLTOIndexFile*/true);
  1328. if (!IndexOrErr) {
  1329. logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
  1330. "Error loading index file '" +
  1331. CGOpts.ThinLTOIndexFile + "': ");
  1332. return;
  1333. }
  1334. std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
  1335. // A null CombinedIndex means we should skip ThinLTO compilation
  1336. // (LLVM will optionally ignore empty index files, returning null instead
  1337. // of an error).
  1338. if (CombinedIndex) {
  1339. if (!CombinedIndex->skipModuleByDistributedBackend()) {
  1340. runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
  1341. LOpts, std::move(OS), CGOpts.SampleProfileFile,
  1342. CGOpts.ProfileRemappingFile, Action);
  1343. return;
  1344. }
  1345. // Distributed indexing detected that nothing from the module is needed
  1346. // for the final linking. So we can skip the compilation. We sill need to
  1347. // output an empty object file to make sure that a linker does not fail
  1348. // trying to read it. Also for some features, like CFI, we must skip
  1349. // the compilation as CombinedIndex does not contain all required
  1350. // information.
  1351. EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
  1352. EmptyModule->setTargetTriple(M->getTargetTriple());
  1353. M = EmptyModule.get();
  1354. }
  1355. }
  1356. EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
  1357. if (CGOpts.ExperimentalNewPassManager)
  1358. AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
  1359. else
  1360. AsmHelper.EmitAssembly(Action, std::move(OS));
  1361. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  1362. // DataLayout.
  1363. if (AsmHelper.TM) {
  1364. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  1365. if (DLDesc != TDesc.getStringRepresentation()) {
  1366. unsigned DiagID = Diags.getCustomDiagID(
  1367. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  1368. "expected target description '%1'");
  1369. Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
  1370. }
  1371. }
  1372. }
  1373. static const char* getSectionNameForBitcode(const Triple &T) {
  1374. switch (T.getObjectFormat()) {
  1375. case Triple::MachO:
  1376. return "__LLVM,__bitcode";
  1377. case Triple::COFF:
  1378. case Triple::ELF:
  1379. case Triple::Wasm:
  1380. case Triple::UnknownObjectFormat:
  1381. return ".llvmbc";
  1382. case Triple::XCOFF:
  1383. llvm_unreachable("XCOFF is not yet implemented");
  1384. break;
  1385. }
  1386. llvm_unreachable("Unimplemented ObjectFormatType");
  1387. }
  1388. static const char* getSectionNameForCommandline(const Triple &T) {
  1389. switch (T.getObjectFormat()) {
  1390. case Triple::MachO:
  1391. return "__LLVM,__cmdline";
  1392. case Triple::COFF:
  1393. case Triple::ELF:
  1394. case Triple::Wasm:
  1395. case Triple::UnknownObjectFormat:
  1396. return ".llvmcmd";
  1397. case Triple::XCOFF:
  1398. llvm_unreachable("XCOFF is not yet implemented");
  1399. break;
  1400. }
  1401. llvm_unreachable("Unimplemented ObjectFormatType");
  1402. }
  1403. // With -fembed-bitcode, save a copy of the llvm IR as data in the
  1404. // __LLVM,__bitcode section.
  1405. void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
  1406. llvm::MemoryBufferRef Buf) {
  1407. if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
  1408. return;
  1409. // Save llvm.compiler.used and remote it.
  1410. SmallVector<Constant*, 2> UsedArray;
  1411. SmallPtrSet<GlobalValue*, 4> UsedGlobals;
  1412. Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
  1413. GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
  1414. for (auto *GV : UsedGlobals) {
  1415. if (GV->getName() != "llvm.embedded.module" &&
  1416. GV->getName() != "llvm.cmdline")
  1417. UsedArray.push_back(
  1418. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1419. }
  1420. if (Used)
  1421. Used->eraseFromParent();
  1422. // Embed the bitcode for the llvm module.
  1423. std::string Data;
  1424. ArrayRef<uint8_t> ModuleData;
  1425. Triple T(M->getTargetTriple());
  1426. // Create a constant that contains the bitcode.
  1427. // In case of embedding a marker, ignore the input Buf and use the empty
  1428. // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
  1429. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
  1430. if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
  1431. (const unsigned char *)Buf.getBufferEnd())) {
  1432. // If the input is LLVM Assembly, bitcode is produced by serializing
  1433. // the module. Use-lists order need to be perserved in this case.
  1434. llvm::raw_string_ostream OS(Data);
  1435. llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
  1436. ModuleData =
  1437. ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
  1438. } else
  1439. // If the input is LLVM bitcode, write the input byte stream directly.
  1440. ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
  1441. Buf.getBufferSize());
  1442. }
  1443. llvm::Constant *ModuleConstant =
  1444. llvm::ConstantDataArray::get(M->getContext(), ModuleData);
  1445. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  1446. *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
  1447. ModuleConstant);
  1448. GV->setSection(getSectionNameForBitcode(T));
  1449. UsedArray.push_back(
  1450. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1451. if (llvm::GlobalVariable *Old =
  1452. M->getGlobalVariable("llvm.embedded.module", true)) {
  1453. assert(Old->hasOneUse() &&
  1454. "llvm.embedded.module can only be used once in llvm.compiler.used");
  1455. GV->takeName(Old);
  1456. Old->eraseFromParent();
  1457. } else {
  1458. GV->setName("llvm.embedded.module");
  1459. }
  1460. // Skip if only bitcode needs to be embedded.
  1461. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
  1462. // Embed command-line options.
  1463. ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
  1464. CGOpts.CmdArgs.size());
  1465. llvm::Constant *CmdConstant =
  1466. llvm::ConstantDataArray::get(M->getContext(), CmdData);
  1467. GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
  1468. llvm::GlobalValue::PrivateLinkage,
  1469. CmdConstant);
  1470. GV->setSection(getSectionNameForCommandline(T));
  1471. UsedArray.push_back(
  1472. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1473. if (llvm::GlobalVariable *Old =
  1474. M->getGlobalVariable("llvm.cmdline", true)) {
  1475. assert(Old->hasOneUse() &&
  1476. "llvm.cmdline can only be used once in llvm.compiler.used");
  1477. GV->takeName(Old);
  1478. Old->eraseFromParent();
  1479. } else {
  1480. GV->setName("llvm.cmdline");
  1481. }
  1482. }
  1483. if (UsedArray.empty())
  1484. return;
  1485. // Recreate llvm.compiler.used.
  1486. ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
  1487. auto *NewUsed = new GlobalVariable(
  1488. *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
  1489. llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
  1490. NewUsed->setSection("llvm.metadata");
  1491. }