BackendUtil.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685
  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. //NH 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. if (LangOpts.WasmExceptions)
  421. Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
  422. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  423. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  424. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  425. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  426. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  427. Options.FunctionSections = CodeGenOpts.FunctionSections;
  428. Options.DataSections = CodeGenOpts.DataSections;
  429. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  430. Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
  431. Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
  432. Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
  433. Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
  434. Options.EmitAddrsig = CodeGenOpts.Addrsig;
  435. Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
  436. Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
  437. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  438. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  439. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  440. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  441. Options.MCOptions.MCIncrementalLinkerCompatible =
  442. CodeGenOpts.IncrementalLinkerCompatible;
  443. Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
  444. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  445. Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
  446. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  447. Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
  448. Options.MCOptions.ABIName = TargetOpts.ABI;
  449. for (const auto &Entry : HSOpts.UserEntries)
  450. if (!Entry.IsFramework &&
  451. (Entry.Group == frontend::IncludeDirGroup::Quoted ||
  452. Entry.Group == frontend::IncludeDirGroup::Angled ||
  453. Entry.Group == frontend::IncludeDirGroup::System))
  454. Options.MCOptions.IASSearchPaths.push_back(
  455. Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
  456. }
  457. static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
  458. if (CodeGenOpts.DisableGCov)
  459. return None;
  460. if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
  461. return None;
  462. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  463. // LLVM's -default-gcov-version flag is set to something invalid.
  464. GCOVOptions Options;
  465. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  466. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  467. llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
  468. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  469. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  470. Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
  471. Options.Filter = CodeGenOpts.ProfileFilterFiles;
  472. Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
  473. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  474. return Options;
  475. }
  476. static Optional<InstrProfOptions>
  477. getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
  478. const LangOptions &LangOpts) {
  479. if (!CodeGenOpts.hasProfileClangInstr())
  480. return None;
  481. InstrProfOptions Options;
  482. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  483. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  484. // TODO: Surface the option to emit atomic profile counter increments at
  485. // the driver level.
  486. Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
  487. return Options;
  488. }
  489. void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
  490. legacy::FunctionPassManager &FPM) {
  491. // Handle disabling of all LLVM passes, where we want to preserve the
  492. // internal module before any optimization.
  493. if (CodeGenOpts.DisableLLVMPasses)
  494. return;
  495. // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
  496. // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
  497. // are inserted before PMBuilder ones - they'd get the default-constructed
  498. // TLI with an unknown target otherwise.
  499. Triple TargetTriple(TheModule->getTargetTriple());
  500. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  501. createTLII(TargetTriple, CodeGenOpts));
  502. PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
  503. // At O0 and O1 we only run the always inliner which is more efficient. At
  504. // higher optimization levels we run the normal inliner.
  505. if (CodeGenOpts.OptimizationLevel <= 1) {
  506. bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
  507. !CodeGenOpts.DisableLifetimeMarkers);
  508. PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
  509. } else {
  510. // We do not want to inline hot callsites for SamplePGO module-summary build
  511. // because profile annotation will happen again in ThinLTO backend, and we
  512. // want the IR of the hot path to match the profile.
  513. PMBuilder.Inliner = createFunctionInliningPass(
  514. CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
  515. (!CodeGenOpts.SampleProfileFile.empty() &&
  516. CodeGenOpts.PrepareForThinLTO));
  517. }
  518. PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
  519. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  520. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  521. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  522. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  523. // Loop interleaving in the loop vectorizer has historically been set to be
  524. // enabled when loop unrolling is enabled.
  525. PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
  526. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  527. PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
  528. PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
  529. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  530. MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  531. if (TM)
  532. TM->adjustPassManager(PMBuilder);
  533. if (CodeGenOpts.DebugInfoForProfiling ||
  534. !CodeGenOpts.SampleProfileFile.empty())
  535. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  536. addAddDiscriminatorsPass);
  537. // In ObjC ARC mode, add the main ARC optimization passes.
  538. if (LangOpts.ObjCAutoRefCount) {
  539. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  540. addObjCARCExpandPass);
  541. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  542. addObjCARCAPElimPass);
  543. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  544. addObjCARCOptPass);
  545. }
  546. if (LangOpts.Coroutines)
  547. addCoroutinePassesToExtensionPoints(PMBuilder);
  548. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  549. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  550. addBoundsCheckingPass);
  551. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  552. addBoundsCheckingPass);
  553. }
  554. if (CodeGenOpts.SanitizeCoverageType ||
  555. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  556. CodeGenOpts.SanitizeCoverageTraceCmp) {
  557. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  558. addSanitizerCoveragePass);
  559. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  560. addSanitizerCoveragePass);
  561. }
  562. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  563. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  564. addAddressSanitizerPasses);
  565. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  566. addAddressSanitizerPasses);
  567. }
  568. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  569. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  570. addKernelAddressSanitizerPasses);
  571. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  572. addKernelAddressSanitizerPasses);
  573. }
  574. if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
  575. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  576. addHWAddressSanitizerPasses);
  577. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  578. addHWAddressSanitizerPasses);
  579. }
  580. if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
  581. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  582. addKernelHWAddressSanitizerPasses);
  583. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  584. addKernelHWAddressSanitizerPasses);
  585. }
  586. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  587. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  588. addMemorySanitizerPass);
  589. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  590. addMemorySanitizerPass);
  591. }
  592. if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
  593. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  594. addKernelMemorySanitizerPass);
  595. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  596. addKernelMemorySanitizerPass);
  597. }
  598. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  599. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  600. addThreadSanitizerPass);
  601. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  602. addThreadSanitizerPass);
  603. }
  604. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  605. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  606. addDataFlowSanitizerPass);
  607. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  608. addDataFlowSanitizerPass);
  609. }
  610. // Set up the per-function pass manager.
  611. FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  612. if (CodeGenOpts.VerifyModule)
  613. FPM.add(createVerifierPass());
  614. // Set up the per-module pass manager.
  615. if (!CodeGenOpts.RewriteMapFiles.empty())
  616. addSymbolRewriterPass(CodeGenOpts, &MPM);
  617. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
  618. MPM.add(createGCOVProfilerPass(*Options));
  619. if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
  620. MPM.add(createStripSymbolsPass(true));
  621. }
  622. if (Optional<InstrProfOptions> Options =
  623. getInstrProfOptions(CodeGenOpts, LangOpts))
  624. MPM.add(createInstrProfilingLegacyPass(*Options, false));
  625. bool hasIRInstr = false;
  626. if (CodeGenOpts.hasProfileIRInstr()) {
  627. PMBuilder.EnablePGOInstrGen = true;
  628. hasIRInstr = true;
  629. }
  630. if (CodeGenOpts.hasProfileCSIRInstr()) {
  631. assert(!CodeGenOpts.hasProfileCSIRUse() &&
  632. "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
  633. "same time");
  634. assert(!hasIRInstr &&
  635. "Cannot have both ProfileGen pass and CSProfileGen pass at the "
  636. "same time");
  637. PMBuilder.EnablePGOCSInstrGen = true;
  638. hasIRInstr = true;
  639. }
  640. if (hasIRInstr) {
  641. if (!CodeGenOpts.InstrProfileOutput.empty())
  642. PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
  643. else
  644. PMBuilder.PGOInstrGen = DefaultProfileGenName;
  645. }
  646. if (CodeGenOpts.hasProfileIRUse()) {
  647. PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
  648. PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
  649. }
  650. if (!CodeGenOpts.SampleProfileFile.empty())
  651. PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
  652. PMBuilder.populateFunctionPassManager(FPM);
  653. PMBuilder.populateModulePassManager(MPM);
  654. }
  655. static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
  656. SmallVector<const char *, 16> BackendArgs;
  657. BackendArgs.push_back("clang"); // Fake program name.
  658. if (!CodeGenOpts.DebugPass.empty()) {
  659. BackendArgs.push_back("-debug-pass");
  660. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  661. }
  662. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  663. BackendArgs.push_back("-limit-float-precision");
  664. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  665. }
  666. BackendArgs.push_back(nullptr);
  667. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  668. BackendArgs.data());
  669. }
  670. void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  671. // Create the TargetMachine for generating code.
  672. std::string Error;
  673. std::string Triple = TheModule->getTargetTriple();
  674. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  675. if (!TheTarget) {
  676. if (MustCreateTM)
  677. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  678. return;
  679. }
  680. Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
  681. std::string FeaturesStr =
  682. llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
  683. llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
  684. CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
  685. llvm::TargetOptions Options;
  686. initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
  687. TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
  688. Options, RM, CM, OptLevel));
  689. }
  690. bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
  691. BackendAction Action,
  692. raw_pwrite_stream &OS,
  693. raw_pwrite_stream *DwoOS) {
  694. // Add LibraryInfo.
  695. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  696. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  697. createTLII(TargetTriple, CodeGenOpts));
  698. CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
  699. // Normal mode, emit a .s or .o file by running the code generator. Note,
  700. // this also adds codegenerator level optimization passes.
  701. TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
  702. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  703. // "codegen" passes so that it isn't run multiple times when there is
  704. // inlining happening.
  705. if (CodeGenOpts.OptimizationLevel > 0)
  706. CodeGenPasses.add(createObjCARCContractPass());
  707. if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
  708. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  709. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  710. return false;
  711. }
  712. return true;
  713. }
  714. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  715. std::unique_ptr<raw_pwrite_stream> OS) {
  716. TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
  717. setCommandLineOpts(CodeGenOpts);
  718. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  719. Action != Backend_EmitBC &&
  720. Action != Backend_EmitLL);
  721. CreateTargetMachine(UsesCodeGen);
  722. if (UsesCodeGen && !TM)
  723. return;
  724. if (TM)
  725. TheModule->setDataLayout(TM->createDataLayout());
  726. legacy::PassManager PerModulePasses;
  727. PerModulePasses.add(
  728. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  729. legacy::FunctionPassManager PerFunctionPasses(TheModule);
  730. PerFunctionPasses.add(
  731. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  732. CreatePasses(PerModulePasses, PerFunctionPasses);
  733. legacy::PassManager CodeGenPasses;
  734. CodeGenPasses.add(
  735. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  736. std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
  737. switch (Action) {
  738. case Backend_EmitNothing:
  739. break;
  740. case Backend_EmitBC:
  741. if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
  742. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  743. ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
  744. if (!ThinLinkOS)
  745. return;
  746. }
  747. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  748. CodeGenOpts.EnableSplitLTOUnit);
  749. PerModulePasses.add(createWriteThinLTOBitcodePass(
  750. *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
  751. } else {
  752. // Emit a module summary by default for Regular LTO except for ld64
  753. // targets
  754. bool EmitLTOSummary =
  755. (CodeGenOpts.PrepareForLTO &&
  756. !CodeGenOpts.DisableLLVMPasses &&
  757. llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
  758. llvm::Triple::Apple);
  759. if (EmitLTOSummary) {
  760. if (!TheModule->getModuleFlag("ThinLTO"))
  761. TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
  762. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  763. uint32_t(1));
  764. }
  765. PerModulePasses.add(createBitcodeWriterPass(
  766. *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
  767. }
  768. break;
  769. case Backend_EmitLL:
  770. PerModulePasses.add(
  771. createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  772. break;
  773. default:
  774. if (!CodeGenOpts.SplitDwarfOutput.empty()) {
  775. DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
  776. if (!DwoOS)
  777. return;
  778. }
  779. if (!AddEmitPasses(CodeGenPasses, Action, *OS,
  780. DwoOS ? &DwoOS->os() : nullptr))
  781. return;
  782. }
  783. // Before executing passes, print the final values of the LLVM options.
  784. cl::PrintOptionValues();
  785. // Run passes. For now we do all passes at once, but eventually we
  786. // would like to have the option of streaming code generation.
  787. {
  788. PrettyStackTraceString CrashInfo("Per-function optimization");
  789. llvm::TimeTraceScope TimeScope("PerFunctionPasses", StringRef(""));
  790. PerFunctionPasses.doInitialization();
  791. for (Function &F : *TheModule)
  792. if (!F.isDeclaration())
  793. PerFunctionPasses.run(F);
  794. PerFunctionPasses.doFinalization();
  795. }
  796. {
  797. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  798. llvm::TimeTraceScope TimeScope("PerModulePasses", StringRef(""));
  799. PerModulePasses.run(*TheModule);
  800. }
  801. {
  802. PrettyStackTraceString CrashInfo("Code generation");
  803. llvm::TimeTraceScope TimeScope("CodeGenPasses", StringRef(""));
  804. CodeGenPasses.run(*TheModule);
  805. }
  806. if (ThinLinkOS)
  807. ThinLinkOS->keep();
  808. if (DwoOS)
  809. DwoOS->keep();
  810. }
  811. static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
  812. switch (Opts.OptimizationLevel) {
  813. default:
  814. llvm_unreachable("Invalid optimization level!");
  815. case 1:
  816. return PassBuilder::O1;
  817. case 2:
  818. switch (Opts.OptimizeSize) {
  819. default:
  820. llvm_unreachable("Invalid optimization level for size!");
  821. case 0:
  822. return PassBuilder::O2;
  823. case 1:
  824. return PassBuilder::Os;
  825. case 2:
  826. return PassBuilder::Oz;
  827. }
  828. case 3:
  829. return PassBuilder::O3;
  830. }
  831. }
  832. static void addSanitizersAtO0(ModulePassManager &MPM,
  833. const Triple &TargetTriple,
  834. const LangOptions &LangOpts,
  835. const CodeGenOptions &CodeGenOpts) {
  836. auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
  837. MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
  838. bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
  839. MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
  840. CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
  841. bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
  842. MPM.addPass(
  843. ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
  844. CodeGenOpts.SanitizeAddressUseOdrIndicator));
  845. };
  846. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  847. ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
  848. }
  849. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  850. ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
  851. }
  852. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  853. MPM.addPass(MemorySanitizerPass({}));
  854. MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
  855. }
  856. if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
  857. MPM.addPass(createModuleToFunctionPassAdaptor(
  858. MemorySanitizerPass({0, false, /*Kernel=*/true})));
  859. }
  860. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  861. MPM.addPass(ThreadSanitizerPass());
  862. MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
  863. }
  864. }
  865. /// A clean version of `EmitAssembly` that uses the new pass manager.
  866. ///
  867. /// Not all features are currently supported in this system, but where
  868. /// necessary it falls back to the legacy pass manager to at least provide
  869. /// basic functionality.
  870. ///
  871. /// This API is planned to have its functionality finished and then to replace
  872. /// `EmitAssembly` at some point in the future when the default switches.
  873. void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
  874. BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
  875. TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
  876. setCommandLineOpts(CodeGenOpts);
  877. bool RequiresCodeGen = (Action != Backend_EmitNothing &&
  878. Action != Backend_EmitBC &&
  879. Action != Backend_EmitLL);
  880. CreateTargetMachine(RequiresCodeGen);
  881. if (RequiresCodeGen && !TM)
  882. return;
  883. if (TM)
  884. TheModule->setDataLayout(TM->createDataLayout());
  885. Optional<PGOOptions> PGOOpt;
  886. if (CodeGenOpts.hasProfileIRInstr())
  887. // -fprofile-generate.
  888. PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
  889. ? DefaultProfileGenName
  890. : CodeGenOpts.InstrProfileOutput,
  891. "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
  892. CodeGenOpts.DebugInfoForProfiling);
  893. else if (CodeGenOpts.hasProfileIRUse()) {
  894. // -fprofile-use.
  895. auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
  896. : PGOOptions::NoCSAction;
  897. PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
  898. CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
  899. CSAction, CodeGenOpts.DebugInfoForProfiling);
  900. } else if (!CodeGenOpts.SampleProfileFile.empty())
  901. // -fprofile-sample-use
  902. PGOOpt =
  903. PGOOptions(CodeGenOpts.SampleProfileFile, "",
  904. CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
  905. PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
  906. else if (CodeGenOpts.DebugInfoForProfiling)
  907. // -fdebug-info-for-profiling
  908. PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
  909. PGOOptions::NoCSAction, true);
  910. // Check to see if we want to generate a CS profile.
  911. if (CodeGenOpts.hasProfileCSIRInstr()) {
  912. assert(!CodeGenOpts.hasProfileCSIRUse() &&
  913. "Cannot have both CSProfileUse pass and CSProfileGen pass at "
  914. "the same time");
  915. if (PGOOpt.hasValue()) {
  916. assert(PGOOpt->Action != PGOOptions::IRInstr &&
  917. PGOOpt->Action != PGOOptions::SampleUse &&
  918. "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
  919. " pass");
  920. PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
  921. ? DefaultProfileGenName
  922. : CodeGenOpts.InstrProfileOutput;
  923. PGOOpt->CSAction = PGOOptions::CSIRInstr;
  924. } else
  925. PGOOpt = PGOOptions("",
  926. CodeGenOpts.InstrProfileOutput.empty()
  927. ? DefaultProfileGenName
  928. : CodeGenOpts.InstrProfileOutput,
  929. "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
  930. CodeGenOpts.DebugInfoForProfiling);
  931. }
  932. PipelineTuningOptions PTO;
  933. PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
  934. // For historical reasons, loop interleaving is set to mirror setting for loop
  935. // unrolling.
  936. PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
  937. PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
  938. PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
  939. PassInstrumentationCallbacks PIC;
  940. StandardInstrumentations SI;
  941. SI.registerCallbacks(PIC);
  942. PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
  943. // Attempt to load pass plugins and register their callbacks with PB.
  944. for (auto &PluginFN : CodeGenOpts.PassPlugins) {
  945. auto PassPlugin = PassPlugin::Load(PluginFN);
  946. if (PassPlugin) {
  947. PassPlugin->registerPassBuilderCallbacks(PB);
  948. } else {
  949. Diags.Report(diag::err_fe_unable_to_load_plugin)
  950. << PluginFN << toString(PassPlugin.takeError());
  951. }
  952. }
  953. LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
  954. FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
  955. CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
  956. ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
  957. // Register the AA manager first so that our version is the one used.
  958. FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
  959. // Register the target library analysis directly and give it a customized
  960. // preset TLI.
  961. Triple TargetTriple(TheModule->getTargetTriple());
  962. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  963. createTLII(TargetTriple, CodeGenOpts));
  964. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  965. // Register all the basic analyses with the managers.
  966. PB.registerModuleAnalyses(MAM);
  967. PB.registerCGSCCAnalyses(CGAM);
  968. PB.registerFunctionAnalyses(FAM);
  969. PB.registerLoopAnalyses(LAM);
  970. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  971. ModulePassManager MPM(CodeGenOpts.DebugPassManager);
  972. if (!CodeGenOpts.DisableLLVMPasses) {
  973. bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
  974. bool IsLTO = CodeGenOpts.PrepareForLTO;
  975. if (CodeGenOpts.OptimizationLevel == 0) {
  976. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
  977. MPM.addPass(GCOVProfilerPass(*Options));
  978. if (Optional<InstrProfOptions> Options =
  979. getInstrProfOptions(CodeGenOpts, LangOpts))
  980. MPM.addPass(InstrProfiling(*Options, false));
  981. // Build a minimal pipeline based on the semantics required by Clang,
  982. // which is just that always inlining occurs. Further, disable generating
  983. // lifetime intrinsics to avoid enabling further optimizations during
  984. // code generation.
  985. MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
  986. // At -O0, we can still do PGO. Add all the requested passes for
  987. // instrumentation PGO, if requested.
  988. if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
  989. PGOOpt->Action == PGOOptions::IRUse))
  990. PB.addPGOInstrPassesForO0(
  991. MPM, CodeGenOpts.DebugPassManager,
  992. /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
  993. /* IsCS */ false, PGOOpt->ProfileFile,
  994. PGOOpt->ProfileRemappingFile);
  995. // At -O0 we directly run necessary sanitizer passes.
  996. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  997. MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
  998. // Lastly, add semantically necessary passes for LTO.
  999. if (IsLTO || IsThinLTO) {
  1000. MPM.addPass(CanonicalizeAliasesPass());
  1001. MPM.addPass(NameAnonGlobalPass());
  1002. }
  1003. } else {
  1004. // Map our optimization levels into one of the distinct levels used to
  1005. // configure the pipeline.
  1006. PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
  1007. PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
  1008. MPM.addPass(createModuleToFunctionPassAdaptor(
  1009. EntryExitInstrumenterPass(/*PostInlining=*/false)));
  1010. });
  1011. // Register callbacks to schedule sanitizer passes at the appropriate part of
  1012. // the pipeline.
  1013. // FIXME: either handle asan/the remaining sanitizers or error out
  1014. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  1015. PB.registerScalarOptimizerLateEPCallback(
  1016. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1017. FPM.addPass(BoundsCheckingPass());
  1018. });
  1019. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  1020. PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
  1021. MPM.addPass(MemorySanitizerPass({}));
  1022. });
  1023. PB.registerOptimizerLastEPCallback(
  1024. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1025. FPM.addPass(MemorySanitizerPass({}));
  1026. });
  1027. }
  1028. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  1029. PB.registerPipelineStartEPCallback(
  1030. [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
  1031. PB.registerOptimizerLastEPCallback(
  1032. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1033. FPM.addPass(ThreadSanitizerPass());
  1034. });
  1035. }
  1036. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  1037. PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
  1038. MPM.addPass(
  1039. RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
  1040. });
  1041. bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
  1042. bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
  1043. PB.registerOptimizerLastEPCallback(
  1044. [Recover, UseAfterScope](FunctionPassManager &FPM,
  1045. PassBuilder::OptimizationLevel Level) {
  1046. FPM.addPass(AddressSanitizerPass(
  1047. /*CompileKernel=*/false, Recover, UseAfterScope));
  1048. });
  1049. bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
  1050. bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
  1051. PB.registerPipelineStartEPCallback(
  1052. [Recover, ModuleUseAfterScope,
  1053. UseOdrIndicator](ModulePassManager &MPM) {
  1054. MPM.addPass(ModuleAddressSanitizerPass(
  1055. /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
  1056. UseOdrIndicator));
  1057. });
  1058. }
  1059. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
  1060. PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
  1061. MPM.addPass(GCOVProfilerPass(*Options));
  1062. });
  1063. if (Optional<InstrProfOptions> Options =
  1064. getInstrProfOptions(CodeGenOpts, LangOpts))
  1065. PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
  1066. MPM.addPass(InstrProfiling(*Options, false));
  1067. });
  1068. if (IsThinLTO) {
  1069. MPM = PB.buildThinLTOPreLinkDefaultPipeline(
  1070. Level, CodeGenOpts.DebugPassManager);
  1071. MPM.addPass(CanonicalizeAliasesPass());
  1072. MPM.addPass(NameAnonGlobalPass());
  1073. } else if (IsLTO) {
  1074. MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
  1075. CodeGenOpts.DebugPassManager);
  1076. MPM.addPass(CanonicalizeAliasesPass());
  1077. MPM.addPass(NameAnonGlobalPass());
  1078. } else {
  1079. MPM = PB.buildPerModuleDefaultPipeline(Level,
  1080. CodeGenOpts.DebugPassManager);
  1081. }
  1082. }
  1083. if (CodeGenOpts.SanitizeCoverageType ||
  1084. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  1085. CodeGenOpts.SanitizeCoverageTraceCmp) {
  1086. auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
  1087. MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
  1088. }
  1089. if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
  1090. bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
  1091. MPM.addPass(HWAddressSanitizerPass(
  1092. /*CompileKernel=*/false, Recover));
  1093. }
  1094. if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
  1095. MPM.addPass(HWAddressSanitizerPass(
  1096. /*CompileKernel=*/true, /*Recover=*/true));
  1097. }
  1098. if (CodeGenOpts.OptimizationLevel == 0) {
  1099. addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
  1100. }
  1101. }
  1102. // FIXME: We still use the legacy pass manager to do code generation. We
  1103. // create that pass manager here and use it as needed below.
  1104. legacy::PassManager CodeGenPasses;
  1105. bool NeedCodeGen = false;
  1106. std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
  1107. // Append any output we need to the pass manager.
  1108. switch (Action) {
  1109. case Backend_EmitNothing:
  1110. break;
  1111. case Backend_EmitBC:
  1112. if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
  1113. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  1114. ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
  1115. if (!ThinLinkOS)
  1116. return;
  1117. }
  1118. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  1119. CodeGenOpts.EnableSplitLTOUnit);
  1120. MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
  1121. : nullptr));
  1122. } else {
  1123. // Emit a module summary by default for Regular LTO except for ld64
  1124. // targets
  1125. bool EmitLTOSummary =
  1126. (CodeGenOpts.PrepareForLTO &&
  1127. !CodeGenOpts.DisableLLVMPasses &&
  1128. llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
  1129. llvm::Triple::Apple);
  1130. if (EmitLTOSummary) {
  1131. if (!TheModule->getModuleFlag("ThinLTO"))
  1132. TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
  1133. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  1134. uint32_t(1));
  1135. }
  1136. MPM.addPass(
  1137. BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
  1138. }
  1139. break;
  1140. case Backend_EmitLL:
  1141. MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  1142. break;
  1143. case Backend_EmitAssembly:
  1144. case Backend_EmitMCNull:
  1145. case Backend_EmitObj:
  1146. NeedCodeGen = true;
  1147. CodeGenPasses.add(
  1148. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  1149. if (!CodeGenOpts.SplitDwarfOutput.empty()) {
  1150. DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
  1151. if (!DwoOS)
  1152. return;
  1153. }
  1154. if (!AddEmitPasses(CodeGenPasses, Action, *OS,
  1155. DwoOS ? &DwoOS->os() : nullptr))
  1156. // FIXME: Should we handle this error differently?
  1157. return;
  1158. break;
  1159. }
  1160. // Before executing passes, print the final values of the LLVM options.
  1161. cl::PrintOptionValues();
  1162. // Now that we have all of the passes ready, run them.
  1163. {
  1164. PrettyStackTraceString CrashInfo("Optimizer");
  1165. MPM.run(*TheModule, MAM);
  1166. }
  1167. // Now if needed, run the legacy PM for codegen.
  1168. if (NeedCodeGen) {
  1169. PrettyStackTraceString CrashInfo("Code generation");
  1170. CodeGenPasses.run(*TheModule);
  1171. }
  1172. if (ThinLinkOS)
  1173. ThinLinkOS->keep();
  1174. if (DwoOS)
  1175. DwoOS->keep();
  1176. }
  1177. Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
  1178. Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
  1179. if (!BMsOrErr)
  1180. return BMsOrErr.takeError();
  1181. // The bitcode file may contain multiple modules, we want the one that is
  1182. // marked as being the ThinLTO module.
  1183. if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
  1184. return *Bm;
  1185. return make_error<StringError>("Could not find module summary",
  1186. inconvertibleErrorCode());
  1187. }
  1188. BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
  1189. for (BitcodeModule &BM : BMs) {
  1190. Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
  1191. if (LTOInfo && LTOInfo->IsThinLTO)
  1192. return &BM;
  1193. }
  1194. return nullptr;
  1195. }
  1196. static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
  1197. const HeaderSearchOptions &HeaderOpts,
  1198. const CodeGenOptions &CGOpts,
  1199. const clang::TargetOptions &TOpts,
  1200. const LangOptions &LOpts,
  1201. std::unique_ptr<raw_pwrite_stream> OS,
  1202. std::string SampleProfile,
  1203. std::string ProfileRemapping,
  1204. BackendAction Action) {
  1205. StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
  1206. ModuleToDefinedGVSummaries;
  1207. CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
  1208. setCommandLineOpts(CGOpts);
  1209. // We can simply import the values mentioned in the combined index, since
  1210. // we should only invoke this using the individual indexes written out
  1211. // via a WriteIndexesThinBackend.
  1212. FunctionImporter::ImportMapTy ImportList;
  1213. for (auto &GlobalList : *CombinedIndex) {
  1214. // Ignore entries for undefined references.
  1215. if (GlobalList.second.SummaryList.empty())
  1216. continue;
  1217. auto GUID = GlobalList.first;
  1218. for (auto &Summary : GlobalList.second.SummaryList) {
  1219. // Skip the summaries for the importing module. These are included to
  1220. // e.g. record required linkage changes.
  1221. if (Summary->modulePath() == M->getModuleIdentifier())
  1222. continue;
  1223. // Add an entry to provoke importing by thinBackend.
  1224. ImportList[Summary->modulePath()].insert(GUID);
  1225. }
  1226. }
  1227. std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
  1228. MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
  1229. for (auto &I : ImportList) {
  1230. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
  1231. llvm::MemoryBuffer::getFile(I.first());
  1232. if (!MBOrErr) {
  1233. errs() << "Error loading imported file '" << I.first()
  1234. << "': " << MBOrErr.getError().message() << "\n";
  1235. return;
  1236. }
  1237. Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
  1238. if (!BMOrErr) {
  1239. handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  1240. errs() << "Error loading imported file '" << I.first()
  1241. << "': " << EIB.message() << '\n';
  1242. });
  1243. return;
  1244. }
  1245. ModuleMap.insert({I.first(), *BMOrErr});
  1246. OwnedImports.push_back(std::move(*MBOrErr));
  1247. }
  1248. auto AddStream = [&](size_t Task) {
  1249. return std::make_unique<lto::NativeObjectStream>(std::move(OS));
  1250. };
  1251. lto::Config Conf;
  1252. if (CGOpts.SaveTempsFilePrefix != "") {
  1253. if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
  1254. /* UseInputModulePath */ false)) {
  1255. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1256. errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
  1257. << '\n';
  1258. });
  1259. }
  1260. }
  1261. Conf.CPU = TOpts.CPU;
  1262. Conf.CodeModel = getCodeModel(CGOpts);
  1263. Conf.MAttrs = TOpts.Features;
  1264. Conf.RelocModel = CGOpts.RelocationModel;
  1265. Conf.CGOptLevel = getCGOptLevel(CGOpts);
  1266. Conf.OptLevel = CGOpts.OptimizationLevel;
  1267. initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
  1268. Conf.SampleProfile = std::move(SampleProfile);
  1269. // Context sensitive profile.
  1270. if (CGOpts.hasProfileCSIRInstr()) {
  1271. Conf.RunCSIRInstr = true;
  1272. Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
  1273. } else if (CGOpts.hasProfileCSIRUse()) {
  1274. Conf.RunCSIRInstr = false;
  1275. Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
  1276. }
  1277. Conf.ProfileRemapping = std::move(ProfileRemapping);
  1278. Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
  1279. Conf.DebugPassManager = CGOpts.DebugPassManager;
  1280. Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
  1281. Conf.RemarksFilename = CGOpts.OptRecordFile;
  1282. Conf.RemarksPasses = CGOpts.OptRecordPasses;
  1283. Conf.RemarksFormat = CGOpts.OptRecordFormat;
  1284. Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
  1285. Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
  1286. switch (Action) {
  1287. case Backend_EmitNothing:
  1288. Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
  1289. return false;
  1290. };
  1291. break;
  1292. case Backend_EmitLL:
  1293. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1294. M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
  1295. return false;
  1296. };
  1297. break;
  1298. case Backend_EmitBC:
  1299. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1300. WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
  1301. return false;
  1302. };
  1303. break;
  1304. default:
  1305. Conf.CGFileType = getCodeGenFileType(Action);
  1306. break;
  1307. }
  1308. if (Error E = thinBackend(
  1309. Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
  1310. ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
  1311. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1312. errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
  1313. });
  1314. }
  1315. }
  1316. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  1317. const HeaderSearchOptions &HeaderOpts,
  1318. const CodeGenOptions &CGOpts,
  1319. const clang::TargetOptions &TOpts,
  1320. const LangOptions &LOpts,
  1321. const llvm::DataLayout &TDesc, Module *M,
  1322. BackendAction Action,
  1323. std::unique_ptr<raw_pwrite_stream> OS) {
  1324. llvm::TimeTraceScope TimeScope("Backend", StringRef(""));
  1325. std::unique_ptr<llvm::Module> EmptyModule;
  1326. if (!CGOpts.ThinLTOIndexFile.empty()) {
  1327. // If we are performing a ThinLTO importing compile, load the function index
  1328. // into memory and pass it into runThinLTOBackend, which will run the
  1329. // function importer and invoke LTO passes.
  1330. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
  1331. llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
  1332. /*IgnoreEmptyThinLTOIndexFile*/true);
  1333. if (!IndexOrErr) {
  1334. logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
  1335. "Error loading index file '" +
  1336. CGOpts.ThinLTOIndexFile + "': ");
  1337. return;
  1338. }
  1339. std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
  1340. // A null CombinedIndex means we should skip ThinLTO compilation
  1341. // (LLVM will optionally ignore empty index files, returning null instead
  1342. // of an error).
  1343. if (CombinedIndex) {
  1344. if (!CombinedIndex->skipModuleByDistributedBackend()) {
  1345. runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
  1346. LOpts, std::move(OS), CGOpts.SampleProfileFile,
  1347. CGOpts.ProfileRemappingFile, Action);
  1348. return;
  1349. }
  1350. // Distributed indexing detected that nothing from the module is needed
  1351. // for the final linking. So we can skip the compilation. We sill need to
  1352. // output an empty object file to make sure that a linker does not fail
  1353. // trying to read it. Also for some features, like CFI, we must skip
  1354. // the compilation as CombinedIndex does not contain all required
  1355. // information.
  1356. EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
  1357. EmptyModule->setTargetTriple(M->getTargetTriple());
  1358. M = EmptyModule.get();
  1359. }
  1360. }
  1361. EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
  1362. if (CGOpts.ExperimentalNewPassManager)
  1363. AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
  1364. else
  1365. AsmHelper.EmitAssembly(Action, std::move(OS));
  1366. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  1367. // DataLayout.
  1368. if (AsmHelper.TM) {
  1369. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  1370. if (DLDesc != TDesc.getStringRepresentation()) {
  1371. unsigned DiagID = Diags.getCustomDiagID(
  1372. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  1373. "expected target description '%1'");
  1374. Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
  1375. }
  1376. }
  1377. }
  1378. static const char* getSectionNameForBitcode(const Triple &T) {
  1379. switch (T.getObjectFormat()) {
  1380. case Triple::MachO:
  1381. return "__LLVM,__bitcode";
  1382. case Triple::COFF:
  1383. case Triple::ELF:
  1384. case Triple::Wasm:
  1385. case Triple::UnknownObjectFormat:
  1386. return ".llvmbc";
  1387. case Triple::XCOFF:
  1388. llvm_unreachable("XCOFF is not yet implemented");
  1389. break;
  1390. }
  1391. llvm_unreachable("Unimplemented ObjectFormatType");
  1392. }
  1393. static const char* getSectionNameForCommandline(const Triple &T) {
  1394. switch (T.getObjectFormat()) {
  1395. case Triple::MachO:
  1396. return "__LLVM,__cmdline";
  1397. case Triple::COFF:
  1398. case Triple::ELF:
  1399. case Triple::Wasm:
  1400. case Triple::UnknownObjectFormat:
  1401. return ".llvmcmd";
  1402. case Triple::XCOFF:
  1403. llvm_unreachable("XCOFF is not yet implemented");
  1404. break;
  1405. }
  1406. llvm_unreachable("Unimplemented ObjectFormatType");
  1407. }
  1408. // With -fembed-bitcode, save a copy of the llvm IR as data in the
  1409. // __LLVM,__bitcode section.
  1410. void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
  1411. llvm::MemoryBufferRef Buf) {
  1412. if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
  1413. return;
  1414. // Save llvm.compiler.used and remote it.
  1415. SmallVector<Constant*, 2> UsedArray;
  1416. SmallPtrSet<GlobalValue*, 4> UsedGlobals;
  1417. Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
  1418. GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
  1419. for (auto *GV : UsedGlobals) {
  1420. if (GV->getName() != "llvm.embedded.module" &&
  1421. GV->getName() != "llvm.cmdline")
  1422. UsedArray.push_back(
  1423. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1424. }
  1425. if (Used)
  1426. Used->eraseFromParent();
  1427. // Embed the bitcode for the llvm module.
  1428. std::string Data;
  1429. ArrayRef<uint8_t> ModuleData;
  1430. Triple T(M->getTargetTriple());
  1431. // Create a constant that contains the bitcode.
  1432. // In case of embedding a marker, ignore the input Buf and use the empty
  1433. // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
  1434. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
  1435. if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
  1436. (const unsigned char *)Buf.getBufferEnd())) {
  1437. // If the input is LLVM Assembly, bitcode is produced by serializing
  1438. // the module. Use-lists order need to be perserved in this case.
  1439. llvm::raw_string_ostream OS(Data);
  1440. llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
  1441. ModuleData =
  1442. ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
  1443. } else
  1444. // If the input is LLVM bitcode, write the input byte stream directly.
  1445. ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
  1446. Buf.getBufferSize());
  1447. }
  1448. llvm::Constant *ModuleConstant =
  1449. llvm::ConstantDataArray::get(M->getContext(), ModuleData);
  1450. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  1451. *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
  1452. ModuleConstant);
  1453. GV->setSection(getSectionNameForBitcode(T));
  1454. UsedArray.push_back(
  1455. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1456. if (llvm::GlobalVariable *Old =
  1457. M->getGlobalVariable("llvm.embedded.module", true)) {
  1458. assert(Old->hasOneUse() &&
  1459. "llvm.embedded.module can only be used once in llvm.compiler.used");
  1460. GV->takeName(Old);
  1461. Old->eraseFromParent();
  1462. } else {
  1463. GV->setName("llvm.embedded.module");
  1464. }
  1465. // Skip if only bitcode needs to be embedded.
  1466. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
  1467. // Embed command-line options.
  1468. ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
  1469. CGOpts.CmdArgs.size());
  1470. llvm::Constant *CmdConstant =
  1471. llvm::ConstantDataArray::get(M->getContext(), CmdData);
  1472. GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
  1473. llvm::GlobalValue::PrivateLinkage,
  1474. CmdConstant);
  1475. GV->setSection(getSectionNameForCommandline(T));
  1476. UsedArray.push_back(
  1477. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1478. if (llvm::GlobalVariable *Old =
  1479. M->getGlobalVariable("llvm.cmdline", true)) {
  1480. assert(Old->hasOneUse() &&
  1481. "llvm.cmdline can only be used once in llvm.compiler.used");
  1482. GV->takeName(Old);
  1483. Old->eraseFromParent();
  1484. } else {
  1485. GV->setName("llvm.cmdline");
  1486. }
  1487. }
  1488. if (UsedArray.empty())
  1489. return;
  1490. // Recreate llvm.compiler.used.
  1491. ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
  1492. auto *NewUsed = new GlobalVariable(
  1493. *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
  1494. llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
  1495. NewUsed->setSection("llvm.metadata");
  1496. }