BackendUtil.cpp 61 KB

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