BackendUtil.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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/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/Object/ModuleSummaryIndexObjectFile.h"
  38. #include "llvm/Passes/PassBuilder.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include "llvm/Support/MemoryBuffer.h"
  41. #include "llvm/Support/PrettyStackTrace.h"
  42. #include "llvm/Support/TargetRegistry.h"
  43. #include "llvm/Support/Timer.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include "llvm/Target/TargetMachine.h"
  46. #include "llvm/Target/TargetOptions.h"
  47. #include "llvm/Target/TargetSubtargetInfo.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/Instrumentation.h"
  53. #include "llvm/Transforms/ObjCARC.h"
  54. #include "llvm/Transforms/Scalar.h"
  55. #include "llvm/Transforms/Scalar/GVN.h"
  56. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  57. #include <memory>
  58. using namespace clang;
  59. using namespace llvm;
  60. namespace {
  61. // Default filename used for profile generation.
  62. static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
  63. class EmitAssemblyHelper {
  64. DiagnosticsEngine &Diags;
  65. const HeaderSearchOptions &HSOpts;
  66. const CodeGenOptions &CodeGenOpts;
  67. const clang::TargetOptions &TargetOpts;
  68. const LangOptions &LangOpts;
  69. Module *TheModule;
  70. Timer CodeGenerationTime;
  71. std::unique_ptr<raw_pwrite_stream> OS;
  72. TargetIRAnalysis getTargetIRAnalysis() const {
  73. if (TM)
  74. return TM->getTargetIRAnalysis();
  75. return TargetIRAnalysis();
  76. }
  77. /// Set LLVM command line options passed through -backend-option.
  78. void setCommandLineOpts();
  79. void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
  80. /// Generates the TargetMachine.
  81. /// Leaves TM unchanged if it is unable to create the target machine.
  82. /// Some of our clang tests specify triples which are not built
  83. /// into clang. This is okay because these tests check the generated
  84. /// IR, and they require DataLayout which depends on the triple.
  85. /// In this case, we allow this method to fail and not report an error.
  86. /// When MustCreateTM is used, we print an error if we are unable to load
  87. /// the requested target.
  88. void CreateTargetMachine(bool MustCreateTM);
  89. /// Add passes necessary to emit assembly or LLVM IR.
  90. ///
  91. /// \return True on success.
  92. bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
  93. raw_pwrite_stream &OS);
  94. public:
  95. EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  96. const HeaderSearchOptions &HeaderSearchOpts,
  97. const CodeGenOptions &CGOpts,
  98. const clang::TargetOptions &TOpts,
  99. const LangOptions &LOpts, Module *M)
  100. : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
  101. TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
  102. CodeGenerationTime("codegen", "Code Generation Time") {}
  103. ~EmitAssemblyHelper() {
  104. if (CodeGenOpts.DisableFree)
  105. BuryPointer(std::move(TM));
  106. }
  107. std::unique_ptr<TargetMachine> TM;
  108. void EmitAssembly(BackendAction Action,
  109. std::unique_ptr<raw_pwrite_stream> OS);
  110. void EmitAssemblyWithNewPassManager(BackendAction Action,
  111. std::unique_ptr<raw_pwrite_stream> OS);
  112. };
  113. // We need this wrapper to access LangOpts and CGOpts from extension functions
  114. // that we add to the PassManagerBuilder.
  115. class PassManagerBuilderWrapper : public PassManagerBuilder {
  116. public:
  117. PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
  118. const LangOptions &LangOpts)
  119. : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
  120. const CodeGenOptions &getCGOpts() const { return CGOpts; }
  121. const LangOptions &getLangOpts() const { return LangOpts; }
  122. private:
  123. const CodeGenOptions &CGOpts;
  124. const LangOptions &LangOpts;
  125. };
  126. }
  127. static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  128. if (Builder.OptLevel > 0)
  129. PM.add(createObjCARCAPElimPass());
  130. }
  131. static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  132. if (Builder.OptLevel > 0)
  133. PM.add(createObjCARCExpandPass());
  134. }
  135. static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  136. if (Builder.OptLevel > 0)
  137. PM.add(createObjCARCOptPass());
  138. }
  139. static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
  140. legacy::PassManagerBase &PM) {
  141. PM.add(createAddDiscriminatorsPass());
  142. }
  143. static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
  144. legacy::PassManagerBase &PM) {
  145. PM.add(createBoundsCheckingPass());
  146. }
  147. static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
  148. legacy::PassManagerBase &PM) {
  149. const PassManagerBuilderWrapper &BuilderWrapper =
  150. static_cast<const PassManagerBuilderWrapper&>(Builder);
  151. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  152. SanitizerCoverageOptions Opts;
  153. Opts.CoverageType =
  154. static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
  155. Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
  156. Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
  157. Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
  158. Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
  159. Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
  160. Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
  161. Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
  162. Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
  163. PM.add(createSanitizerCoverageModulePass(Opts));
  164. }
  165. static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
  166. legacy::PassManagerBase &PM) {
  167. const PassManagerBuilderWrapper &BuilderWrapper =
  168. static_cast<const PassManagerBuilderWrapper&>(Builder);
  169. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  170. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
  171. bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
  172. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
  173. UseAfterScope));
  174. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
  175. }
  176. static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
  177. legacy::PassManagerBase &PM) {
  178. PM.add(createAddressSanitizerFunctionPass(
  179. /*CompileKernel*/ true,
  180. /*Recover*/ true, /*UseAfterScope*/ false));
  181. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
  182. /*Recover*/true));
  183. }
  184. static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
  185. legacy::PassManagerBase &PM) {
  186. const PassManagerBuilderWrapper &BuilderWrapper =
  187. static_cast<const PassManagerBuilderWrapper&>(Builder);
  188. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  189. int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
  190. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
  191. PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
  192. // MemorySanitizer inserts complex instrumentation that mostly follows
  193. // the logic of the original code, but operates on "shadow" values.
  194. // It can benefit from re-running some general purpose optimization passes.
  195. if (Builder.OptLevel > 0) {
  196. PM.add(createEarlyCSEPass());
  197. PM.add(createReassociatePass());
  198. PM.add(createLICMPass());
  199. PM.add(createGVNPass());
  200. PM.add(createInstructionCombiningPass());
  201. PM.add(createDeadStoreEliminationPass());
  202. }
  203. }
  204. static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
  205. legacy::PassManagerBase &PM) {
  206. PM.add(createThreadSanitizerPass());
  207. }
  208. static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
  209. legacy::PassManagerBase &PM) {
  210. const PassManagerBuilderWrapper &BuilderWrapper =
  211. static_cast<const PassManagerBuilderWrapper&>(Builder);
  212. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  213. PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
  214. }
  215. static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
  216. legacy::PassManagerBase &PM) {
  217. const PassManagerBuilderWrapper &BuilderWrapper =
  218. static_cast<const PassManagerBuilderWrapper&>(Builder);
  219. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  220. EfficiencySanitizerOptions Opts;
  221. if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
  222. Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
  223. else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
  224. Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
  225. PM.add(createEfficiencySanitizerPass(Opts));
  226. }
  227. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  228. const CodeGenOptions &CodeGenOpts) {
  229. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  230. if (!CodeGenOpts.SimplifyLibCalls)
  231. TLII->disableAllFunctions();
  232. else {
  233. // Disable individual libc/libm calls in TargetLibraryInfo.
  234. LibFunc F;
  235. for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
  236. if (TLII->getLibFunc(FuncName, F))
  237. TLII->setUnavailable(F);
  238. }
  239. switch (CodeGenOpts.getVecLib()) {
  240. case CodeGenOptions::Accelerate:
  241. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
  242. break;
  243. case CodeGenOptions::SVML:
  244. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
  245. break;
  246. default:
  247. break;
  248. }
  249. return TLII;
  250. }
  251. static void addSymbolRewriterPass(const CodeGenOptions &Opts,
  252. legacy::PassManager *MPM) {
  253. llvm::SymbolRewriter::RewriteDescriptorList DL;
  254. llvm::SymbolRewriter::RewriteMapParser MapParser;
  255. for (const auto &MapFile : Opts.RewriteMapFiles)
  256. MapParser.parse(MapFile, &DL);
  257. MPM->add(createRewriteSymbolsPass(DL));
  258. }
  259. static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
  260. switch (CodeGenOpts.OptimizationLevel) {
  261. default:
  262. llvm_unreachable("Invalid optimization level!");
  263. case 0:
  264. return CodeGenOpt::None;
  265. case 1:
  266. return CodeGenOpt::Less;
  267. case 2:
  268. return CodeGenOpt::Default; // O2/Os/Oz
  269. case 3:
  270. return CodeGenOpt::Aggressive;
  271. }
  272. }
  273. static llvm::CodeModel::Model getCodeModel(const CodeGenOptions &CodeGenOpts) {
  274. unsigned CodeModel =
  275. llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  276. .Case("small", llvm::CodeModel::Small)
  277. .Case("kernel", llvm::CodeModel::Kernel)
  278. .Case("medium", llvm::CodeModel::Medium)
  279. .Case("large", llvm::CodeModel::Large)
  280. .Case("default", llvm::CodeModel::Default)
  281. .Default(~0u);
  282. assert(CodeModel != ~0u && "invalid code model!");
  283. return static_cast<llvm::CodeModel::Model>(CodeModel);
  284. }
  285. static llvm::Reloc::Model getRelocModel(const CodeGenOptions &CodeGenOpts) {
  286. // Keep this synced with the equivalent code in
  287. // lib/Frontend/CompilerInvocation.cpp
  288. llvm::Optional<llvm::Reloc::Model> RM;
  289. RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
  290. .Case("static", llvm::Reloc::Static)
  291. .Case("pic", llvm::Reloc::PIC_)
  292. .Case("ropi", llvm::Reloc::ROPI)
  293. .Case("rwpi", llvm::Reloc::RWPI)
  294. .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
  295. .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
  296. assert(RM.hasValue() && "invalid PIC model!");
  297. return *RM;
  298. }
  299. static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
  300. if (Action == Backend_EmitObj)
  301. return TargetMachine::CGFT_ObjectFile;
  302. else if (Action == Backend_EmitMCNull)
  303. return TargetMachine::CGFT_Null;
  304. else {
  305. assert(Action == Backend_EmitAssembly && "Invalid action!");
  306. return TargetMachine::CGFT_AssemblyFile;
  307. }
  308. }
  309. static void initTargetOptions(llvm::TargetOptions &Options,
  310. const CodeGenOptions &CodeGenOpts,
  311. const clang::TargetOptions &TargetOpts,
  312. const LangOptions &LangOpts,
  313. const HeaderSearchOptions &HSOpts) {
  314. Options.ThreadModel =
  315. llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
  316. .Case("posix", llvm::ThreadModel::POSIX)
  317. .Case("single", llvm::ThreadModel::Single);
  318. // Set float ABI type.
  319. assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
  320. CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
  321. "Invalid Floating Point ABI!");
  322. Options.FloatABIType =
  323. llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
  324. .Case("soft", llvm::FloatABI::Soft)
  325. .Case("softfp", llvm::FloatABI::Soft)
  326. .Case("hard", llvm::FloatABI::Hard)
  327. .Default(llvm::FloatABI::Default);
  328. // Set FP fusion mode.
  329. switch (LangOpts.getDefaultFPContractMode()) {
  330. case LangOptions::FPC_Off:
  331. Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
  332. break;
  333. case LangOptions::FPC_On:
  334. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  335. break;
  336. case LangOptions::FPC_Fast:
  337. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  338. break;
  339. }
  340. Options.UseInitArray = CodeGenOpts.UseInitArray;
  341. Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
  342. Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
  343. Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
  344. // Set EABI version.
  345. Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
  346. .Case("4", llvm::EABI::EABI4)
  347. .Case("5", llvm::EABI::EABI5)
  348. .Case("gnu", llvm::EABI::GNU)
  349. .Default(llvm::EABI::Default);
  350. if (LangOpts.SjLjExceptions)
  351. Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
  352. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  353. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  354. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  355. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  356. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  357. Options.FunctionSections = CodeGenOpts.FunctionSections;
  358. Options.DataSections = CodeGenOpts.DataSections;
  359. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  360. Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
  361. Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
  362. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  363. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  364. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  365. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  366. Options.MCOptions.MCIncrementalLinkerCompatible =
  367. CodeGenOpts.IncrementalLinkerCompatible;
  368. Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
  369. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  370. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  371. Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
  372. Options.MCOptions.ABIName = TargetOpts.ABI;
  373. for (const auto &Entry : HSOpts.UserEntries)
  374. if (!Entry.IsFramework &&
  375. (Entry.Group == frontend::IncludeDirGroup::Quoted ||
  376. Entry.Group == frontend::IncludeDirGroup::Angled ||
  377. Entry.Group == frontend::IncludeDirGroup::System))
  378. Options.MCOptions.IASSearchPaths.push_back(
  379. Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
  380. }
  381. void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
  382. legacy::FunctionPassManager &FPM) {
  383. // Handle disabling of all LLVM passes, where we want to preserve the
  384. // internal module before any optimization.
  385. if (CodeGenOpts.DisableLLVMPasses)
  386. return;
  387. PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
  388. // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
  389. // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
  390. // are inserted before PMBuilder ones - they'd get the default-constructed
  391. // TLI with an unknown target otherwise.
  392. Triple TargetTriple(TheModule->getTargetTriple());
  393. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  394. createTLII(TargetTriple, CodeGenOpts));
  395. // At O0 and O1 we only run the always inliner which is more efficient. At
  396. // higher optimization levels we run the normal inliner.
  397. if (CodeGenOpts.OptimizationLevel <= 1) {
  398. bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
  399. !CodeGenOpts.DisableLifetimeMarkers);
  400. PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
  401. } else {
  402. // We do not want to inline hot callsites for SamplePGO module-summary build
  403. // because profile annotation will happen again in ThinLTO backend, and we
  404. // want the IR of the hot path to match the profile.
  405. PMBuilder.Inliner = createFunctionInliningPass(
  406. CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
  407. (!CodeGenOpts.SampleProfileFile.empty() &&
  408. CodeGenOpts.EmitSummaryIndex));
  409. }
  410. PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
  411. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  412. PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
  413. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  414. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  415. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  416. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  417. PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
  418. PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
  419. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  420. MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  421. if (TM)
  422. TM->adjustPassManager(PMBuilder);
  423. if (CodeGenOpts.DebugInfoForProfiling ||
  424. !CodeGenOpts.SampleProfileFile.empty())
  425. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  426. addAddDiscriminatorsPass);
  427. // In ObjC ARC mode, add the main ARC optimization passes.
  428. if (LangOpts.ObjCAutoRefCount) {
  429. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  430. addObjCARCExpandPass);
  431. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  432. addObjCARCAPElimPass);
  433. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  434. addObjCARCOptPass);
  435. }
  436. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  437. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  438. addBoundsCheckingPass);
  439. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  440. addBoundsCheckingPass);
  441. }
  442. if (CodeGenOpts.SanitizeCoverageType ||
  443. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  444. CodeGenOpts.SanitizeCoverageTraceCmp) {
  445. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  446. addSanitizerCoveragePass);
  447. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  448. addSanitizerCoveragePass);
  449. }
  450. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  451. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  452. addAddressSanitizerPasses);
  453. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  454. addAddressSanitizerPasses);
  455. }
  456. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  457. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  458. addKernelAddressSanitizerPasses);
  459. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  460. addKernelAddressSanitizerPasses);
  461. }
  462. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  463. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  464. addMemorySanitizerPass);
  465. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  466. addMemorySanitizerPass);
  467. }
  468. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  469. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  470. addThreadSanitizerPass);
  471. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  472. addThreadSanitizerPass);
  473. }
  474. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  475. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  476. addDataFlowSanitizerPass);
  477. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  478. addDataFlowSanitizerPass);
  479. }
  480. if (LangOpts.CoroutinesTS)
  481. addCoroutinePassesToExtensionPoints(PMBuilder);
  482. if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
  483. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  484. addEfficiencySanitizerPass);
  485. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  486. addEfficiencySanitizerPass);
  487. }
  488. // Set up the per-function pass manager.
  489. FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  490. if (CodeGenOpts.VerifyModule)
  491. FPM.add(createVerifierPass());
  492. // Set up the per-module pass manager.
  493. if (!CodeGenOpts.RewriteMapFiles.empty())
  494. addSymbolRewriterPass(CodeGenOpts, &MPM);
  495. if (!CodeGenOpts.DisableGCov &&
  496. (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
  497. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  498. // LLVM's -default-gcov-version flag is set to something invalid.
  499. GCOVOptions Options;
  500. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  501. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  502. memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
  503. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  504. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  505. Options.FunctionNamesInData =
  506. !CodeGenOpts.CoverageNoFunctionNamesInData;
  507. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  508. MPM.add(createGCOVProfilerPass(Options));
  509. if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
  510. MPM.add(createStripSymbolsPass(true));
  511. }
  512. if (CodeGenOpts.hasProfileClangInstr()) {
  513. InstrProfOptions Options;
  514. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  515. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  516. MPM.add(createInstrProfilingLegacyPass(Options));
  517. }
  518. if (CodeGenOpts.hasProfileIRInstr()) {
  519. PMBuilder.EnablePGOInstrGen = true;
  520. if (!CodeGenOpts.InstrProfileOutput.empty())
  521. PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
  522. else
  523. PMBuilder.PGOInstrGen = DefaultProfileGenName;
  524. }
  525. if (CodeGenOpts.hasProfileIRUse())
  526. PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
  527. if (!CodeGenOpts.SampleProfileFile.empty())
  528. PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
  529. PMBuilder.populateFunctionPassManager(FPM);
  530. PMBuilder.populateModulePassManager(MPM);
  531. }
  532. void EmitAssemblyHelper::setCommandLineOpts() {
  533. SmallVector<const char *, 16> BackendArgs;
  534. BackendArgs.push_back("clang"); // Fake program name.
  535. if (!CodeGenOpts.DebugPass.empty()) {
  536. BackendArgs.push_back("-debug-pass");
  537. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  538. }
  539. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  540. BackendArgs.push_back("-limit-float-precision");
  541. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  542. }
  543. for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
  544. BackendArgs.push_back(BackendOption.c_str());
  545. BackendArgs.push_back(nullptr);
  546. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  547. BackendArgs.data());
  548. }
  549. void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  550. // Create the TargetMachine for generating code.
  551. std::string Error;
  552. std::string Triple = TheModule->getTargetTriple();
  553. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  554. if (!TheTarget) {
  555. if (MustCreateTM)
  556. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  557. return;
  558. }
  559. llvm::CodeModel::Model CM = getCodeModel(CodeGenOpts);
  560. std::string FeaturesStr =
  561. llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
  562. llvm::Reloc::Model RM = getRelocModel(CodeGenOpts);
  563. CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
  564. llvm::TargetOptions Options;
  565. initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
  566. TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
  567. Options, RM, CM, OptLevel));
  568. }
  569. bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
  570. BackendAction Action,
  571. raw_pwrite_stream &OS) {
  572. // Add LibraryInfo.
  573. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  574. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  575. createTLII(TargetTriple, CodeGenOpts));
  576. CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
  577. // Normal mode, emit a .s or .o file by running the code generator. Note,
  578. // this also adds codegenerator level optimization passes.
  579. TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
  580. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  581. // "codegen" passes so that it isn't run multiple times when there is
  582. // inlining happening.
  583. if (CodeGenOpts.OptimizationLevel > 0)
  584. CodeGenPasses.add(createObjCARCContractPass());
  585. if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
  586. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  587. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  588. return false;
  589. }
  590. return true;
  591. }
  592. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  593. std::unique_ptr<raw_pwrite_stream> OS) {
  594. TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
  595. setCommandLineOpts();
  596. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  597. Action != Backend_EmitBC &&
  598. Action != Backend_EmitLL);
  599. CreateTargetMachine(UsesCodeGen);
  600. if (UsesCodeGen && !TM)
  601. return;
  602. if (TM)
  603. TheModule->setDataLayout(TM->createDataLayout());
  604. legacy::PassManager PerModulePasses;
  605. PerModulePasses.add(
  606. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  607. legacy::FunctionPassManager PerFunctionPasses(TheModule);
  608. PerFunctionPasses.add(
  609. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  610. CreatePasses(PerModulePasses, PerFunctionPasses);
  611. legacy::PassManager CodeGenPasses;
  612. CodeGenPasses.add(
  613. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  614. std::unique_ptr<raw_fd_ostream> ThinLinkOS;
  615. switch (Action) {
  616. case Backend_EmitNothing:
  617. break;
  618. case Backend_EmitBC:
  619. if (CodeGenOpts.EmitSummaryIndex) {
  620. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  621. std::error_code EC;
  622. ThinLinkOS.reset(new llvm::raw_fd_ostream(
  623. CodeGenOpts.ThinLinkBitcodeFile, EC,
  624. llvm::sys::fs::F_None));
  625. if (EC) {
  626. Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
  627. << EC.message();
  628. return;
  629. }
  630. }
  631. PerModulePasses.add(
  632. createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
  633. }
  634. else
  635. PerModulePasses.add(
  636. createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
  637. break;
  638. case Backend_EmitLL:
  639. PerModulePasses.add(
  640. createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  641. break;
  642. default:
  643. if (!AddEmitPasses(CodeGenPasses, Action, *OS))
  644. return;
  645. }
  646. // Before executing passes, print the final values of the LLVM options.
  647. cl::PrintOptionValues();
  648. // Run passes. For now we do all passes at once, but eventually we
  649. // would like to have the option of streaming code generation.
  650. {
  651. PrettyStackTraceString CrashInfo("Per-function optimization");
  652. PerFunctionPasses.doInitialization();
  653. for (Function &F : *TheModule)
  654. if (!F.isDeclaration())
  655. PerFunctionPasses.run(F);
  656. PerFunctionPasses.doFinalization();
  657. }
  658. {
  659. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  660. PerModulePasses.run(*TheModule);
  661. }
  662. {
  663. PrettyStackTraceString CrashInfo("Code generation");
  664. CodeGenPasses.run(*TheModule);
  665. }
  666. }
  667. static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
  668. switch (Opts.OptimizationLevel) {
  669. default:
  670. llvm_unreachable("Invalid optimization level!");
  671. case 1:
  672. return PassBuilder::O1;
  673. case 2:
  674. switch (Opts.OptimizeSize) {
  675. default:
  676. llvm_unreachable("Invalide optimization level for size!");
  677. case 0:
  678. return PassBuilder::O2;
  679. case 1:
  680. return PassBuilder::Os;
  681. case 2:
  682. return PassBuilder::Oz;
  683. }
  684. case 3:
  685. return PassBuilder::O3;
  686. }
  687. }
  688. /// A clean version of `EmitAssembly` that uses the new pass manager.
  689. ///
  690. /// Not all features are currently supported in this system, but where
  691. /// necessary it falls back to the legacy pass manager to at least provide
  692. /// basic functionality.
  693. ///
  694. /// This API is planned to have its functionality finished and then to replace
  695. /// `EmitAssembly` at some point in the future when the default switches.
  696. void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
  697. BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
  698. TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
  699. setCommandLineOpts();
  700. // The new pass manager always makes a target machine available to passes
  701. // during construction.
  702. CreateTargetMachine(/*MustCreateTM*/ true);
  703. if (!TM)
  704. // This will already be diagnosed, just bail.
  705. return;
  706. TheModule->setDataLayout(TM->createDataLayout());
  707. PGOOptions PGOOpt;
  708. // -fprofile-generate.
  709. PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
  710. if (PGOOpt.RunProfileGen)
  711. PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
  712. DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
  713. // -fprofile-use.
  714. if (CodeGenOpts.hasProfileIRUse())
  715. PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
  716. // Only pass a PGO options struct if -fprofile-generate or
  717. // -fprofile-use were passed on the cmdline.
  718. PassBuilder PB(TM.get(),
  719. (PGOOpt.RunProfileGen ||
  720. !PGOOpt.ProfileUseFile.empty()) ?
  721. Optional<PGOOptions>(PGOOpt) : None);
  722. LoopAnalysisManager LAM;
  723. FunctionAnalysisManager FAM;
  724. CGSCCAnalysisManager CGAM;
  725. ModuleAnalysisManager MAM;
  726. // Register the AA manager first so that our version is the one used.
  727. FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
  728. // Register all the basic analyses with the managers.
  729. PB.registerModuleAnalyses(MAM);
  730. PB.registerCGSCCAnalyses(CGAM);
  731. PB.registerFunctionAnalyses(FAM);
  732. PB.registerLoopAnalyses(LAM);
  733. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  734. ModulePassManager MPM;
  735. if (!CodeGenOpts.DisableLLVMPasses) {
  736. if (CodeGenOpts.OptimizationLevel == 0) {
  737. // Build a minimal pipeline based on the semantics required by Clang,
  738. // which is just that always inlining occurs.
  739. MPM.addPass(AlwaysInlinerPass());
  740. } else {
  741. // Otherwise, use the default pass pipeline. We also have to map our
  742. // optimization levels into one of the distinct levels used to configure
  743. // the pipeline.
  744. PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
  745. MPM = PB.buildPerModuleDefaultPipeline(Level);
  746. }
  747. }
  748. // FIXME: We still use the legacy pass manager to do code generation. We
  749. // create that pass manager here and use it as needed below.
  750. legacy::PassManager CodeGenPasses;
  751. bool NeedCodeGen = false;
  752. // Append any output we need to the pass manager.
  753. switch (Action) {
  754. case Backend_EmitNothing:
  755. break;
  756. case Backend_EmitBC:
  757. MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
  758. CodeGenOpts.EmitSummaryIndex,
  759. CodeGenOpts.EmitSummaryIndex));
  760. break;
  761. case Backend_EmitLL:
  762. MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  763. break;
  764. case Backend_EmitAssembly:
  765. case Backend_EmitMCNull:
  766. case Backend_EmitObj:
  767. NeedCodeGen = true;
  768. CodeGenPasses.add(
  769. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  770. if (!AddEmitPasses(CodeGenPasses, Action, *OS))
  771. // FIXME: Should we handle this error differently?
  772. return;
  773. break;
  774. }
  775. // Before executing passes, print the final values of the LLVM options.
  776. cl::PrintOptionValues();
  777. // Now that we have all of the passes ready, run them.
  778. {
  779. PrettyStackTraceString CrashInfo("Optimizer");
  780. MPM.run(*TheModule, MAM);
  781. }
  782. // Now if needed, run the legacy PM for codegen.
  783. if (NeedCodeGen) {
  784. PrettyStackTraceString CrashInfo("Code generation");
  785. CodeGenPasses.run(*TheModule);
  786. }
  787. }
  788. Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
  789. Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
  790. if (!BMsOrErr)
  791. return BMsOrErr.takeError();
  792. // The bitcode file may contain multiple modules, we want the one with a
  793. // summary.
  794. for (BitcodeModule &BM : *BMsOrErr) {
  795. Expected<bool> HasSummary = BM.hasSummary();
  796. if (HasSummary && *HasSummary)
  797. return BM;
  798. }
  799. return make_error<StringError>("Could not find module summary",
  800. inconvertibleErrorCode());
  801. }
  802. static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
  803. const HeaderSearchOptions &HeaderOpts,
  804. const CodeGenOptions &CGOpts,
  805. const clang::TargetOptions &TOpts,
  806. const LangOptions &LOpts,
  807. std::unique_ptr<raw_pwrite_stream> OS,
  808. std::string SampleProfile,
  809. BackendAction Action) {
  810. StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
  811. ModuleToDefinedGVSummaries;
  812. CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
  813. // We can simply import the values mentioned in the combined index, since
  814. // we should only invoke this using the individual indexes written out
  815. // via a WriteIndexesThinBackend.
  816. FunctionImporter::ImportMapTy ImportList;
  817. for (auto &GlobalList : *CombinedIndex) {
  818. auto GUID = GlobalList.first;
  819. assert(GlobalList.second.size() == 1 &&
  820. "Expected individual combined index to have one summary per GUID");
  821. auto &Summary = GlobalList.second[0];
  822. // Skip the summaries for the importing module. These are included to
  823. // e.g. record required linkage changes.
  824. if (Summary->modulePath() == M->getModuleIdentifier())
  825. continue;
  826. // Doesn't matter what value we plug in to the map, just needs an entry
  827. // to provoke importing by thinBackend.
  828. ImportList[Summary->modulePath()][GUID] = 1;
  829. }
  830. std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
  831. MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
  832. for (auto &I : ImportList) {
  833. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
  834. llvm::MemoryBuffer::getFile(I.first());
  835. if (!MBOrErr) {
  836. errs() << "Error loading imported file '" << I.first()
  837. << "': " << MBOrErr.getError().message() << "\n";
  838. return;
  839. }
  840. Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
  841. if (!BMOrErr) {
  842. handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  843. errs() << "Error loading imported file '" << I.first()
  844. << "': " << EIB.message() << '\n';
  845. });
  846. return;
  847. }
  848. ModuleMap.insert({I.first(), *BMOrErr});
  849. OwnedImports.push_back(std::move(*MBOrErr));
  850. }
  851. auto AddStream = [&](size_t Task) {
  852. return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
  853. };
  854. lto::Config Conf;
  855. Conf.CPU = TOpts.CPU;
  856. Conf.CodeModel = getCodeModel(CGOpts);
  857. Conf.MAttrs = TOpts.Features;
  858. Conf.RelocModel = getRelocModel(CGOpts);
  859. Conf.CGOptLevel = getCGOptLevel(CGOpts);
  860. initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
  861. Conf.SampleProfile = std::move(SampleProfile);
  862. switch (Action) {
  863. case Backend_EmitNothing:
  864. Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
  865. return false;
  866. };
  867. break;
  868. case Backend_EmitLL:
  869. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  870. M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
  871. return false;
  872. };
  873. break;
  874. case Backend_EmitBC:
  875. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  876. WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
  877. return false;
  878. };
  879. break;
  880. default:
  881. Conf.CGFileType = getCodeGenFileType(Action);
  882. break;
  883. }
  884. if (Error E = thinBackend(
  885. Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
  886. ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
  887. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  888. errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
  889. });
  890. }
  891. }
  892. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  893. const HeaderSearchOptions &HeaderOpts,
  894. const CodeGenOptions &CGOpts,
  895. const clang::TargetOptions &TOpts,
  896. const LangOptions &LOpts,
  897. const llvm::DataLayout &TDesc, Module *M,
  898. BackendAction Action,
  899. std::unique_ptr<raw_pwrite_stream> OS) {
  900. if (!CGOpts.ThinLTOIndexFile.empty()) {
  901. // If we are performing a ThinLTO importing compile, load the function index
  902. // into memory and pass it into runThinLTOBackend, which will run the
  903. // function importer and invoke LTO passes.
  904. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
  905. llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
  906. if (!IndexOrErr) {
  907. logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
  908. "Error loading index file '" +
  909. CGOpts.ThinLTOIndexFile + "': ");
  910. return;
  911. }
  912. std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
  913. // A null CombinedIndex means we should skip ThinLTO compilation
  914. // (LLVM will optionally ignore empty index files, returning null instead
  915. // of an error).
  916. bool DoThinLTOBackend = CombinedIndex != nullptr;
  917. if (DoThinLTOBackend) {
  918. runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
  919. LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
  920. return;
  921. }
  922. }
  923. EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
  924. if (CGOpts.ExperimentalNewPassManager)
  925. AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
  926. else
  927. AsmHelper.EmitAssembly(Action, std::move(OS));
  928. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  929. // DataLayout.
  930. if (AsmHelper.TM) {
  931. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  932. if (DLDesc != TDesc.getStringRepresentation()) {
  933. unsigned DiagID = Diags.getCustomDiagID(
  934. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  935. "expected target description '%1'");
  936. Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
  937. }
  938. }
  939. }
  940. static const char* getSectionNameForBitcode(const Triple &T) {
  941. switch (T.getObjectFormat()) {
  942. case Triple::MachO:
  943. return "__LLVM,__bitcode";
  944. case Triple::COFF:
  945. case Triple::ELF:
  946. case Triple::Wasm:
  947. case Triple::UnknownObjectFormat:
  948. return ".llvmbc";
  949. }
  950. llvm_unreachable("Unimplemented ObjectFormatType");
  951. }
  952. static const char* getSectionNameForCommandline(const Triple &T) {
  953. switch (T.getObjectFormat()) {
  954. case Triple::MachO:
  955. return "__LLVM,__cmdline";
  956. case Triple::COFF:
  957. case Triple::ELF:
  958. case Triple::Wasm:
  959. case Triple::UnknownObjectFormat:
  960. return ".llvmcmd";
  961. }
  962. llvm_unreachable("Unimplemented ObjectFormatType");
  963. }
  964. // With -fembed-bitcode, save a copy of the llvm IR as data in the
  965. // __LLVM,__bitcode section.
  966. void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
  967. llvm::MemoryBufferRef Buf) {
  968. if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
  969. return;
  970. // Save llvm.compiler.used and remote it.
  971. SmallVector<Constant*, 2> UsedArray;
  972. SmallSet<GlobalValue*, 4> UsedGlobals;
  973. Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
  974. GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
  975. for (auto *GV : UsedGlobals) {
  976. if (GV->getName() != "llvm.embedded.module" &&
  977. GV->getName() != "llvm.cmdline")
  978. UsedArray.push_back(
  979. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  980. }
  981. if (Used)
  982. Used->eraseFromParent();
  983. // Embed the bitcode for the llvm module.
  984. std::string Data;
  985. ArrayRef<uint8_t> ModuleData;
  986. Triple T(M->getTargetTriple());
  987. // Create a constant that contains the bitcode.
  988. // In case of embedding a marker, ignore the input Buf and use the empty
  989. // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
  990. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
  991. if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
  992. (const unsigned char *)Buf.getBufferEnd())) {
  993. // If the input is LLVM Assembly, bitcode is produced by serializing
  994. // the module. Use-lists order need to be perserved in this case.
  995. llvm::raw_string_ostream OS(Data);
  996. llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
  997. ModuleData =
  998. ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
  999. } else
  1000. // If the input is LLVM bitcode, write the input byte stream directly.
  1001. ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
  1002. Buf.getBufferSize());
  1003. }
  1004. llvm::Constant *ModuleConstant =
  1005. llvm::ConstantDataArray::get(M->getContext(), ModuleData);
  1006. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  1007. *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
  1008. ModuleConstant);
  1009. GV->setSection(getSectionNameForBitcode(T));
  1010. UsedArray.push_back(
  1011. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1012. if (llvm::GlobalVariable *Old =
  1013. M->getGlobalVariable("llvm.embedded.module", true)) {
  1014. assert(Old->hasOneUse() &&
  1015. "llvm.embedded.module can only be used once in llvm.compiler.used");
  1016. GV->takeName(Old);
  1017. Old->eraseFromParent();
  1018. } else {
  1019. GV->setName("llvm.embedded.module");
  1020. }
  1021. // Skip if only bitcode needs to be embedded.
  1022. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
  1023. // Embed command-line options.
  1024. ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
  1025. CGOpts.CmdArgs.size());
  1026. llvm::Constant *CmdConstant =
  1027. llvm::ConstantDataArray::get(M->getContext(), CmdData);
  1028. GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
  1029. llvm::GlobalValue::PrivateLinkage,
  1030. CmdConstant);
  1031. GV->setSection(getSectionNameForCommandline(T));
  1032. UsedArray.push_back(
  1033. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1034. if (llvm::GlobalVariable *Old =
  1035. M->getGlobalVariable("llvm.cmdline", true)) {
  1036. assert(Old->hasOneUse() &&
  1037. "llvm.cmdline can only be used once in llvm.compiler.used");
  1038. GV->takeName(Old);
  1039. Old->eraseFromParent();
  1040. } else {
  1041. GV->setName("llvm.cmdline");
  1042. }
  1043. }
  1044. if (UsedArray.empty())
  1045. return;
  1046. // Recreate llvm.compiler.used.
  1047. ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
  1048. auto *NewUsed = new GlobalVariable(
  1049. *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
  1050. llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
  1051. NewUsed->setSection("llvm.metadata");
  1052. }