BackendUtil.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  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. 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(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
  854. }
  855. if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
  856. MPM.addPass(createModuleToFunctionPassAdaptor(
  857. MemorySanitizerPass({0, false, /*Kernel=*/true})));
  858. }
  859. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  860. MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
  861. }
  862. }
  863. /// A clean version of `EmitAssembly` that uses the new pass manager.
  864. ///
  865. /// Not all features are currently supported in this system, but where
  866. /// necessary it falls back to the legacy pass manager to at least provide
  867. /// basic functionality.
  868. ///
  869. /// This API is planned to have its functionality finished and then to replace
  870. /// `EmitAssembly` at some point in the future when the default switches.
  871. void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
  872. BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
  873. TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
  874. setCommandLineOpts(CodeGenOpts);
  875. bool RequiresCodeGen = (Action != Backend_EmitNothing &&
  876. Action != Backend_EmitBC &&
  877. Action != Backend_EmitLL);
  878. CreateTargetMachine(RequiresCodeGen);
  879. if (RequiresCodeGen && !TM)
  880. return;
  881. if (TM)
  882. TheModule->setDataLayout(TM->createDataLayout());
  883. Optional<PGOOptions> PGOOpt;
  884. if (CodeGenOpts.hasProfileIRInstr())
  885. // -fprofile-generate.
  886. PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
  887. ? DefaultProfileGenName
  888. : CodeGenOpts.InstrProfileOutput,
  889. "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
  890. CodeGenOpts.DebugInfoForProfiling);
  891. else if (CodeGenOpts.hasProfileIRUse()) {
  892. // -fprofile-use.
  893. auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
  894. : PGOOptions::NoCSAction;
  895. PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
  896. CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
  897. CSAction, CodeGenOpts.DebugInfoForProfiling);
  898. } else if (!CodeGenOpts.SampleProfileFile.empty())
  899. // -fprofile-sample-use
  900. PGOOpt =
  901. PGOOptions(CodeGenOpts.SampleProfileFile, "",
  902. CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
  903. PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
  904. else if (CodeGenOpts.DebugInfoForProfiling)
  905. // -fdebug-info-for-profiling
  906. PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
  907. PGOOptions::NoCSAction, true);
  908. // Check to see if we want to generate a CS profile.
  909. if (CodeGenOpts.hasProfileCSIRInstr()) {
  910. assert(!CodeGenOpts.hasProfileCSIRUse() &&
  911. "Cannot have both CSProfileUse pass and CSProfileGen pass at "
  912. "the same time");
  913. if (PGOOpt.hasValue()) {
  914. assert(PGOOpt->Action != PGOOptions::IRInstr &&
  915. PGOOpt->Action != PGOOptions::SampleUse &&
  916. "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
  917. " pass");
  918. PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
  919. ? DefaultProfileGenName
  920. : CodeGenOpts.InstrProfileOutput;
  921. PGOOpt->CSAction = PGOOptions::CSIRInstr;
  922. } else
  923. PGOOpt = PGOOptions("",
  924. CodeGenOpts.InstrProfileOutput.empty()
  925. ? DefaultProfileGenName
  926. : CodeGenOpts.InstrProfileOutput,
  927. "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
  928. CodeGenOpts.DebugInfoForProfiling);
  929. }
  930. PipelineTuningOptions PTO;
  931. PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
  932. // For historical reasons, loop interleaving is set to mirror setting for loop
  933. // unrolling.
  934. PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
  935. PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
  936. PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
  937. PassInstrumentationCallbacks PIC;
  938. StandardInstrumentations SI;
  939. SI.registerCallbacks(PIC);
  940. PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
  941. // Attempt to load pass plugins and register their callbacks with PB.
  942. for (auto &PluginFN : CodeGenOpts.PassPlugins) {
  943. auto PassPlugin = PassPlugin::Load(PluginFN);
  944. if (PassPlugin) {
  945. PassPlugin->registerPassBuilderCallbacks(PB);
  946. } else {
  947. Diags.Report(diag::err_fe_unable_to_load_plugin)
  948. << PluginFN << toString(PassPlugin.takeError());
  949. }
  950. }
  951. LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
  952. FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
  953. CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
  954. ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
  955. // Register the AA manager first so that our version is the one used.
  956. FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
  957. // Register the target library analysis directly and give it a customized
  958. // preset TLI.
  959. Triple TargetTriple(TheModule->getTargetTriple());
  960. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  961. createTLII(TargetTriple, CodeGenOpts));
  962. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  963. // Register all the basic analyses with the managers.
  964. PB.registerModuleAnalyses(MAM);
  965. PB.registerCGSCCAnalyses(CGAM);
  966. PB.registerFunctionAnalyses(FAM);
  967. PB.registerLoopAnalyses(LAM);
  968. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  969. ModulePassManager MPM(CodeGenOpts.DebugPassManager);
  970. if (!CodeGenOpts.DisableLLVMPasses) {
  971. bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
  972. bool IsLTO = CodeGenOpts.PrepareForLTO;
  973. if (CodeGenOpts.OptimizationLevel == 0) {
  974. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
  975. MPM.addPass(GCOVProfilerPass(*Options));
  976. if (Optional<InstrProfOptions> Options =
  977. getInstrProfOptions(CodeGenOpts, LangOpts))
  978. MPM.addPass(InstrProfiling(*Options, false));
  979. // Build a minimal pipeline based on the semantics required by Clang,
  980. // which is just that always inlining occurs. Further, disable generating
  981. // lifetime intrinsics to avoid enabling further optimizations during
  982. // code generation.
  983. MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
  984. // At -O0, we can still do PGO. Add all the requested passes for
  985. // instrumentation PGO, if requested.
  986. if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
  987. PGOOpt->Action == PGOOptions::IRUse))
  988. PB.addPGOInstrPassesForO0(
  989. MPM, CodeGenOpts.DebugPassManager,
  990. /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
  991. /* IsCS */ false, PGOOpt->ProfileFile,
  992. PGOOpt->ProfileRemappingFile);
  993. // At -O0 we directly run necessary sanitizer passes.
  994. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  995. MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
  996. // Lastly, add semantically necessary passes for LTO.
  997. if (IsLTO || IsThinLTO) {
  998. MPM.addPass(CanonicalizeAliasesPass());
  999. MPM.addPass(NameAnonGlobalPass());
  1000. }
  1001. } else {
  1002. // Map our optimization levels into one of the distinct levels used to
  1003. // configure the pipeline.
  1004. PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
  1005. PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
  1006. MPM.addPass(createModuleToFunctionPassAdaptor(
  1007. EntryExitInstrumenterPass(/*PostInlining=*/false)));
  1008. });
  1009. // Register callbacks to schedule sanitizer passes at the appropriate part of
  1010. // the pipeline.
  1011. // FIXME: either handle asan/the remaining sanitizers or error out
  1012. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  1013. PB.registerScalarOptimizerLateEPCallback(
  1014. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1015. FPM.addPass(BoundsCheckingPass());
  1016. });
  1017. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  1018. PB.registerOptimizerLastEPCallback(
  1019. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1020. FPM.addPass(MemorySanitizerPass({}));
  1021. });
  1022. if (LangOpts.Sanitize.has(SanitizerKind::Thread))
  1023. PB.registerOptimizerLastEPCallback(
  1024. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  1025. FPM.addPass(ThreadSanitizerPass());
  1026. });
  1027. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  1028. PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
  1029. MPM.addPass(
  1030. RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
  1031. });
  1032. bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
  1033. bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
  1034. PB.registerOptimizerLastEPCallback(
  1035. [Recover, UseAfterScope](FunctionPassManager &FPM,
  1036. PassBuilder::OptimizationLevel Level) {
  1037. FPM.addPass(AddressSanitizerPass(
  1038. /*CompileKernel=*/false, Recover, UseAfterScope));
  1039. });
  1040. bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
  1041. bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
  1042. PB.registerPipelineStartEPCallback(
  1043. [Recover, ModuleUseAfterScope,
  1044. UseOdrIndicator](ModulePassManager &MPM) {
  1045. MPM.addPass(ModuleAddressSanitizerPass(
  1046. /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
  1047. UseOdrIndicator));
  1048. });
  1049. }
  1050. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
  1051. PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
  1052. MPM.addPass(GCOVProfilerPass(*Options));
  1053. });
  1054. if (Optional<InstrProfOptions> Options =
  1055. getInstrProfOptions(CodeGenOpts, LangOpts))
  1056. PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
  1057. MPM.addPass(InstrProfiling(*Options, false));
  1058. });
  1059. if (IsThinLTO) {
  1060. MPM = PB.buildThinLTOPreLinkDefaultPipeline(
  1061. Level, CodeGenOpts.DebugPassManager);
  1062. MPM.addPass(CanonicalizeAliasesPass());
  1063. MPM.addPass(NameAnonGlobalPass());
  1064. } else if (IsLTO) {
  1065. MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
  1066. CodeGenOpts.DebugPassManager);
  1067. MPM.addPass(CanonicalizeAliasesPass());
  1068. MPM.addPass(NameAnonGlobalPass());
  1069. } else {
  1070. MPM = PB.buildPerModuleDefaultPipeline(Level,
  1071. CodeGenOpts.DebugPassManager);
  1072. }
  1073. }
  1074. if (CodeGenOpts.SanitizeCoverageType ||
  1075. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  1076. CodeGenOpts.SanitizeCoverageTraceCmp) {
  1077. auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
  1078. MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
  1079. }
  1080. if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
  1081. bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
  1082. MPM.addPass(HWAddressSanitizerPass(
  1083. /*CompileKernel=*/false, Recover));
  1084. }
  1085. if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
  1086. MPM.addPass(HWAddressSanitizerPass(
  1087. /*CompileKernel=*/true, /*Recover=*/true));
  1088. }
  1089. if (CodeGenOpts.OptimizationLevel == 0) {
  1090. addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
  1091. }
  1092. }
  1093. // FIXME: We still use the legacy pass manager to do code generation. We
  1094. // create that pass manager here and use it as needed below.
  1095. legacy::PassManager CodeGenPasses;
  1096. bool NeedCodeGen = false;
  1097. std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
  1098. // Append any output we need to the pass manager.
  1099. switch (Action) {
  1100. case Backend_EmitNothing:
  1101. break;
  1102. case Backend_EmitBC:
  1103. if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
  1104. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  1105. ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
  1106. if (!ThinLinkOS)
  1107. return;
  1108. }
  1109. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  1110. CodeGenOpts.EnableSplitLTOUnit);
  1111. MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
  1112. : nullptr));
  1113. } else {
  1114. // Emit a module summary by default for Regular LTO except for ld64
  1115. // targets
  1116. bool EmitLTOSummary =
  1117. (CodeGenOpts.PrepareForLTO &&
  1118. !CodeGenOpts.DisableLLVMPasses &&
  1119. llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
  1120. llvm::Triple::Apple);
  1121. if (EmitLTOSummary) {
  1122. if (!TheModule->getModuleFlag("ThinLTO"))
  1123. TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
  1124. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  1125. uint32_t(1));
  1126. }
  1127. MPM.addPass(
  1128. BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
  1129. }
  1130. break;
  1131. case Backend_EmitLL:
  1132. MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  1133. break;
  1134. case Backend_EmitAssembly:
  1135. case Backend_EmitMCNull:
  1136. case Backend_EmitObj:
  1137. NeedCodeGen = true;
  1138. CodeGenPasses.add(
  1139. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  1140. if (!CodeGenOpts.SplitDwarfOutput.empty()) {
  1141. DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
  1142. if (!DwoOS)
  1143. return;
  1144. }
  1145. if (!AddEmitPasses(CodeGenPasses, Action, *OS,
  1146. DwoOS ? &DwoOS->os() : nullptr))
  1147. // FIXME: Should we handle this error differently?
  1148. return;
  1149. break;
  1150. }
  1151. // Before executing passes, print the final values of the LLVM options.
  1152. cl::PrintOptionValues();
  1153. // Now that we have all of the passes ready, run them.
  1154. {
  1155. PrettyStackTraceString CrashInfo("Optimizer");
  1156. MPM.run(*TheModule, MAM);
  1157. }
  1158. // Now if needed, run the legacy PM for codegen.
  1159. if (NeedCodeGen) {
  1160. PrettyStackTraceString CrashInfo("Code generation");
  1161. CodeGenPasses.run(*TheModule);
  1162. }
  1163. if (ThinLinkOS)
  1164. ThinLinkOS->keep();
  1165. if (DwoOS)
  1166. DwoOS->keep();
  1167. }
  1168. Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
  1169. Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
  1170. if (!BMsOrErr)
  1171. return BMsOrErr.takeError();
  1172. // The bitcode file may contain multiple modules, we want the one that is
  1173. // marked as being the ThinLTO module.
  1174. if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
  1175. return *Bm;
  1176. return make_error<StringError>("Could not find module summary",
  1177. inconvertibleErrorCode());
  1178. }
  1179. BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
  1180. for (BitcodeModule &BM : BMs) {
  1181. Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
  1182. if (LTOInfo && LTOInfo->IsThinLTO)
  1183. return &BM;
  1184. }
  1185. return nullptr;
  1186. }
  1187. static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
  1188. const HeaderSearchOptions &HeaderOpts,
  1189. const CodeGenOptions &CGOpts,
  1190. const clang::TargetOptions &TOpts,
  1191. const LangOptions &LOpts,
  1192. std::unique_ptr<raw_pwrite_stream> OS,
  1193. std::string SampleProfile,
  1194. std::string ProfileRemapping,
  1195. BackendAction Action) {
  1196. StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
  1197. ModuleToDefinedGVSummaries;
  1198. CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
  1199. setCommandLineOpts(CGOpts);
  1200. // We can simply import the values mentioned in the combined index, since
  1201. // we should only invoke this using the individual indexes written out
  1202. // via a WriteIndexesThinBackend.
  1203. FunctionImporter::ImportMapTy ImportList;
  1204. for (auto &GlobalList : *CombinedIndex) {
  1205. // Ignore entries for undefined references.
  1206. if (GlobalList.second.SummaryList.empty())
  1207. continue;
  1208. auto GUID = GlobalList.first;
  1209. for (auto &Summary : GlobalList.second.SummaryList) {
  1210. // Skip the summaries for the importing module. These are included to
  1211. // e.g. record required linkage changes.
  1212. if (Summary->modulePath() == M->getModuleIdentifier())
  1213. continue;
  1214. // Add an entry to provoke importing by thinBackend.
  1215. ImportList[Summary->modulePath()].insert(GUID);
  1216. }
  1217. }
  1218. std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
  1219. MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
  1220. for (auto &I : ImportList) {
  1221. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
  1222. llvm::MemoryBuffer::getFile(I.first());
  1223. if (!MBOrErr) {
  1224. errs() << "Error loading imported file '" << I.first()
  1225. << "': " << MBOrErr.getError().message() << "\n";
  1226. return;
  1227. }
  1228. Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
  1229. if (!BMOrErr) {
  1230. handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  1231. errs() << "Error loading imported file '" << I.first()
  1232. << "': " << EIB.message() << '\n';
  1233. });
  1234. return;
  1235. }
  1236. ModuleMap.insert({I.first(), *BMOrErr});
  1237. OwnedImports.push_back(std::move(*MBOrErr));
  1238. }
  1239. auto AddStream = [&](size_t Task) {
  1240. return std::make_unique<lto::NativeObjectStream>(std::move(OS));
  1241. };
  1242. lto::Config Conf;
  1243. if (CGOpts.SaveTempsFilePrefix != "") {
  1244. if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
  1245. /* UseInputModulePath */ false)) {
  1246. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1247. errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
  1248. << '\n';
  1249. });
  1250. }
  1251. }
  1252. Conf.CPU = TOpts.CPU;
  1253. Conf.CodeModel = getCodeModel(CGOpts);
  1254. Conf.MAttrs = TOpts.Features;
  1255. Conf.RelocModel = CGOpts.RelocationModel;
  1256. Conf.CGOptLevel = getCGOptLevel(CGOpts);
  1257. Conf.OptLevel = CGOpts.OptimizationLevel;
  1258. initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
  1259. Conf.SampleProfile = std::move(SampleProfile);
  1260. // Context sensitive profile.
  1261. if (CGOpts.hasProfileCSIRInstr()) {
  1262. Conf.RunCSIRInstr = true;
  1263. Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
  1264. } else if (CGOpts.hasProfileCSIRUse()) {
  1265. Conf.RunCSIRInstr = false;
  1266. Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
  1267. }
  1268. Conf.ProfileRemapping = std::move(ProfileRemapping);
  1269. Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
  1270. Conf.DebugPassManager = CGOpts.DebugPassManager;
  1271. Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
  1272. Conf.RemarksFilename = CGOpts.OptRecordFile;
  1273. Conf.RemarksPasses = CGOpts.OptRecordPasses;
  1274. Conf.RemarksFormat = CGOpts.OptRecordFormat;
  1275. Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
  1276. Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
  1277. switch (Action) {
  1278. case Backend_EmitNothing:
  1279. Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
  1280. return false;
  1281. };
  1282. break;
  1283. case Backend_EmitLL:
  1284. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1285. M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
  1286. return false;
  1287. };
  1288. break;
  1289. case Backend_EmitBC:
  1290. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1291. WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
  1292. return false;
  1293. };
  1294. break;
  1295. default:
  1296. Conf.CGFileType = getCodeGenFileType(Action);
  1297. break;
  1298. }
  1299. if (Error E = thinBackend(
  1300. Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
  1301. ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
  1302. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1303. errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
  1304. });
  1305. }
  1306. }
  1307. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  1308. const HeaderSearchOptions &HeaderOpts,
  1309. const CodeGenOptions &CGOpts,
  1310. const clang::TargetOptions &TOpts,
  1311. const LangOptions &LOpts,
  1312. const llvm::DataLayout &TDesc, Module *M,
  1313. BackendAction Action,
  1314. std::unique_ptr<raw_pwrite_stream> OS) {
  1315. llvm::TimeTraceScope TimeScope("Backend", StringRef(""));
  1316. std::unique_ptr<llvm::Module> EmptyModule;
  1317. if (!CGOpts.ThinLTOIndexFile.empty()) {
  1318. // If we are performing a ThinLTO importing compile, load the function index
  1319. // into memory and pass it into runThinLTOBackend, which will run the
  1320. // function importer and invoke LTO passes.
  1321. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
  1322. llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
  1323. /*IgnoreEmptyThinLTOIndexFile*/true);
  1324. if (!IndexOrErr) {
  1325. logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
  1326. "Error loading index file '" +
  1327. CGOpts.ThinLTOIndexFile + "': ");
  1328. return;
  1329. }
  1330. std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
  1331. // A null CombinedIndex means we should skip ThinLTO compilation
  1332. // (LLVM will optionally ignore empty index files, returning null instead
  1333. // of an error).
  1334. if (CombinedIndex) {
  1335. if (!CombinedIndex->skipModuleByDistributedBackend()) {
  1336. runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
  1337. LOpts, std::move(OS), CGOpts.SampleProfileFile,
  1338. CGOpts.ProfileRemappingFile, Action);
  1339. return;
  1340. }
  1341. // Distributed indexing detected that nothing from the module is needed
  1342. // for the final linking. So we can skip the compilation. We sill need to
  1343. // output an empty object file to make sure that a linker does not fail
  1344. // trying to read it. Also for some features, like CFI, we must skip
  1345. // the compilation as CombinedIndex does not contain all required
  1346. // information.
  1347. EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
  1348. EmptyModule->setTargetTriple(M->getTargetTriple());
  1349. M = EmptyModule.get();
  1350. }
  1351. }
  1352. EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
  1353. if (CGOpts.ExperimentalNewPassManager)
  1354. AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
  1355. else
  1356. AsmHelper.EmitAssembly(Action, std::move(OS));
  1357. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  1358. // DataLayout.
  1359. if (AsmHelper.TM) {
  1360. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  1361. if (DLDesc != TDesc.getStringRepresentation()) {
  1362. unsigned DiagID = Diags.getCustomDiagID(
  1363. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  1364. "expected target description '%1'");
  1365. Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
  1366. }
  1367. }
  1368. }
  1369. static const char* getSectionNameForBitcode(const Triple &T) {
  1370. switch (T.getObjectFormat()) {
  1371. case Triple::MachO:
  1372. return "__LLVM,__bitcode";
  1373. case Triple::COFF:
  1374. case Triple::ELF:
  1375. case Triple::Wasm:
  1376. case Triple::UnknownObjectFormat:
  1377. return ".llvmbc";
  1378. case Triple::XCOFF:
  1379. llvm_unreachable("XCOFF is not yet implemented");
  1380. break;
  1381. }
  1382. llvm_unreachable("Unimplemented ObjectFormatType");
  1383. }
  1384. static const char* getSectionNameForCommandline(const Triple &T) {
  1385. switch (T.getObjectFormat()) {
  1386. case Triple::MachO:
  1387. return "__LLVM,__cmdline";
  1388. case Triple::COFF:
  1389. case Triple::ELF:
  1390. case Triple::Wasm:
  1391. case Triple::UnknownObjectFormat:
  1392. return ".llvmcmd";
  1393. case Triple::XCOFF:
  1394. llvm_unreachable("XCOFF is not yet implemented");
  1395. break;
  1396. }
  1397. llvm_unreachable("Unimplemented ObjectFormatType");
  1398. }
  1399. // With -fembed-bitcode, save a copy of the llvm IR as data in the
  1400. // __LLVM,__bitcode section.
  1401. void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
  1402. llvm::MemoryBufferRef Buf) {
  1403. if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
  1404. return;
  1405. // Save llvm.compiler.used and remote it.
  1406. SmallVector<Constant*, 2> UsedArray;
  1407. SmallPtrSet<GlobalValue*, 4> UsedGlobals;
  1408. Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
  1409. GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
  1410. for (auto *GV : UsedGlobals) {
  1411. if (GV->getName() != "llvm.embedded.module" &&
  1412. GV->getName() != "llvm.cmdline")
  1413. UsedArray.push_back(
  1414. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1415. }
  1416. if (Used)
  1417. Used->eraseFromParent();
  1418. // Embed the bitcode for the llvm module.
  1419. std::string Data;
  1420. ArrayRef<uint8_t> ModuleData;
  1421. Triple T(M->getTargetTriple());
  1422. // Create a constant that contains the bitcode.
  1423. // In case of embedding a marker, ignore the input Buf and use the empty
  1424. // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
  1425. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
  1426. if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
  1427. (const unsigned char *)Buf.getBufferEnd())) {
  1428. // If the input is LLVM Assembly, bitcode is produced by serializing
  1429. // the module. Use-lists order need to be perserved in this case.
  1430. llvm::raw_string_ostream OS(Data);
  1431. llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
  1432. ModuleData =
  1433. ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
  1434. } else
  1435. // If the input is LLVM bitcode, write the input byte stream directly.
  1436. ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
  1437. Buf.getBufferSize());
  1438. }
  1439. llvm::Constant *ModuleConstant =
  1440. llvm::ConstantDataArray::get(M->getContext(), ModuleData);
  1441. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  1442. *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
  1443. ModuleConstant);
  1444. GV->setSection(getSectionNameForBitcode(T));
  1445. UsedArray.push_back(
  1446. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1447. if (llvm::GlobalVariable *Old =
  1448. M->getGlobalVariable("llvm.embedded.module", true)) {
  1449. assert(Old->hasOneUse() &&
  1450. "llvm.embedded.module can only be used once in llvm.compiler.used");
  1451. GV->takeName(Old);
  1452. Old->eraseFromParent();
  1453. } else {
  1454. GV->setName("llvm.embedded.module");
  1455. }
  1456. // Skip if only bitcode needs to be embedded.
  1457. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
  1458. // Embed command-line options.
  1459. ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
  1460. CGOpts.CmdArgs.size());
  1461. llvm::Constant *CmdConstant =
  1462. llvm::ConstantDataArray::get(M->getContext(), CmdData);
  1463. GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
  1464. llvm::GlobalValue::PrivateLinkage,
  1465. CmdConstant);
  1466. GV->setSection(getSectionNameForCommandline(T));
  1467. UsedArray.push_back(
  1468. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1469. if (llvm::GlobalVariable *Old =
  1470. M->getGlobalVariable("llvm.cmdline", true)) {
  1471. assert(Old->hasOneUse() &&
  1472. "llvm.cmdline can only be used once in llvm.compiler.used");
  1473. GV->takeName(Old);
  1474. Old->eraseFromParent();
  1475. } else {
  1476. GV->setName("llvm.cmdline");
  1477. }
  1478. }
  1479. if (UsedArray.empty())
  1480. return;
  1481. // Recreate llvm.compiler.used.
  1482. ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
  1483. auto *NewUsed = new GlobalVariable(
  1484. *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
  1485. llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
  1486. NewUsed->setSection("llvm.metadata");
  1487. }