BackendUtil.cpp 55 KB

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