BackendUtil.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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 "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/StringSwitch.h"
  18. #include "llvm/Analysis/TargetLibraryInfo.h"
  19. #include "llvm/Analysis/TargetTransformInfo.h"
  20. #include "llvm/Bitcode/BitcodeWriterPass.h"
  21. #include "llvm/CodeGen/RegAllocRegistry.h"
  22. #include "llvm/CodeGen/SchedulerRegistry.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/ModuleSummaryIndex.h"
  25. #include "llvm/IR/IRPrintingPasses.h"
  26. #include "llvm/IR/LegacyPassManager.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IR/Verifier.h"
  29. #include "llvm/MC/SubtargetFeature.h"
  30. #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/PrettyStackTrace.h"
  33. #include "llvm/Support/TargetRegistry.h"
  34. #include "llvm/Support/Timer.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Target/TargetMachine.h"
  37. #include "llvm/Target/TargetOptions.h"
  38. #include "llvm/Target/TargetSubtargetInfo.h"
  39. #include "llvm/Transforms/IPO.h"
  40. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  41. #include "llvm/Transforms/Instrumentation.h"
  42. #include "llvm/Transforms/ObjCARC.h"
  43. #include "llvm/Transforms/Scalar.h"
  44. #include "llvm/Transforms/Scalar/GVN.h"
  45. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  46. #include <memory>
  47. using namespace clang;
  48. using namespace llvm;
  49. namespace {
  50. class EmitAssemblyHelper {
  51. DiagnosticsEngine &Diags;
  52. const CodeGenOptions &CodeGenOpts;
  53. const clang::TargetOptions &TargetOpts;
  54. const LangOptions &LangOpts;
  55. Module *TheModule;
  56. Timer CodeGenerationTime;
  57. mutable legacy::PassManager *CodeGenPasses;
  58. mutable legacy::PassManager *PerModulePasses;
  59. mutable legacy::FunctionPassManager *PerFunctionPasses;
  60. private:
  61. TargetIRAnalysis getTargetIRAnalysis() const {
  62. if (TM)
  63. return TM->getTargetIRAnalysis();
  64. return TargetIRAnalysis();
  65. }
  66. legacy::PassManager *getCodeGenPasses() const {
  67. if (!CodeGenPasses) {
  68. CodeGenPasses = new legacy::PassManager();
  69. CodeGenPasses->add(
  70. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  71. }
  72. return CodeGenPasses;
  73. }
  74. legacy::PassManager *getPerModulePasses() const {
  75. if (!PerModulePasses) {
  76. PerModulePasses = new legacy::PassManager();
  77. PerModulePasses->add(
  78. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  79. }
  80. return PerModulePasses;
  81. }
  82. legacy::FunctionPassManager *getPerFunctionPasses() const {
  83. if (!PerFunctionPasses) {
  84. PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
  85. PerFunctionPasses->add(
  86. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  87. }
  88. return PerFunctionPasses;
  89. }
  90. /// Set LLVM command line options passed through -backend-option.
  91. void setCommandLineOpts();
  92. void CreatePasses(ModuleSummaryIndex *ModuleSummary);
  93. /// Generates the TargetMachine.
  94. /// Returns Null if it is unable to create the target machine.
  95. /// Some of our clang tests specify triples which are not built
  96. /// into clang. This is okay because these tests check the generated
  97. /// IR, and they require DataLayout which depends on the triple.
  98. /// In this case, we allow this method to fail and not report an error.
  99. /// When MustCreateTM is used, we print an error if we are unable to load
  100. /// the requested target.
  101. TargetMachine *CreateTargetMachine(bool MustCreateTM);
  102. /// Add passes necessary to emit assembly or LLVM IR.
  103. ///
  104. /// \return True on success.
  105. bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
  106. public:
  107. EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts,
  108. const clang::TargetOptions &TOpts,
  109. const LangOptions &LOpts, Module *M)
  110. : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
  111. TheModule(M), CodeGenerationTime("Code Generation Time"),
  112. CodeGenPasses(nullptr), PerModulePasses(nullptr),
  113. PerFunctionPasses(nullptr) {}
  114. ~EmitAssemblyHelper() {
  115. delete CodeGenPasses;
  116. delete PerModulePasses;
  117. delete PerFunctionPasses;
  118. if (CodeGenOpts.DisableFree)
  119. BuryPointer(std::move(TM));
  120. }
  121. std::unique_ptr<TargetMachine> TM;
  122. void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS);
  123. };
  124. // We need this wrapper to access LangOpts and CGOpts from extension functions
  125. // that we add to the PassManagerBuilder.
  126. class PassManagerBuilderWrapper : public PassManagerBuilder {
  127. public:
  128. PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
  129. const LangOptions &LangOpts)
  130. : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
  131. const CodeGenOptions &getCGOpts() const { return CGOpts; }
  132. const LangOptions &getLangOpts() const { return LangOpts; }
  133. private:
  134. const CodeGenOptions &CGOpts;
  135. const LangOptions &LangOpts;
  136. };
  137. }
  138. static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  139. if (Builder.OptLevel > 0)
  140. PM.add(createObjCARCAPElimPass());
  141. }
  142. static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  143. if (Builder.OptLevel > 0)
  144. PM.add(createObjCARCExpandPass());
  145. }
  146. static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  147. if (Builder.OptLevel > 0)
  148. PM.add(createObjCARCOptPass());
  149. }
  150. static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
  151. legacy::PassManagerBase &PM) {
  152. PM.add(createAddDiscriminatorsPass());
  153. }
  154. static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
  155. legacy::PassManagerBase &PM) {
  156. PM.add(createBoundsCheckingPass());
  157. }
  158. static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
  159. legacy::PassManagerBase &PM) {
  160. const PassManagerBuilderWrapper &BuilderWrapper =
  161. static_cast<const PassManagerBuilderWrapper&>(Builder);
  162. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  163. SanitizerCoverageOptions Opts;
  164. Opts.CoverageType =
  165. static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
  166. Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
  167. Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
  168. Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
  169. Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
  170. Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
  171. PM.add(createSanitizerCoverageModulePass(Opts));
  172. }
  173. static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
  174. legacy::PassManagerBase &PM) {
  175. const PassManagerBuilderWrapper &BuilderWrapper =
  176. static_cast<const PassManagerBuilderWrapper&>(Builder);
  177. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  178. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
  179. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false, Recover));
  180. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
  181. }
  182. static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
  183. legacy::PassManagerBase &PM) {
  184. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true,
  185. /*Recover*/true));
  186. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
  187. /*Recover*/true));
  188. }
  189. static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
  190. legacy::PassManagerBase &PM) {
  191. const PassManagerBuilderWrapper &BuilderWrapper =
  192. static_cast<const PassManagerBuilderWrapper&>(Builder);
  193. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  194. PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
  195. // MemorySanitizer inserts complex instrumentation that mostly follows
  196. // the logic of the original code, but operates on "shadow" values.
  197. // It can benefit from re-running some general purpose optimization passes.
  198. if (Builder.OptLevel > 0) {
  199. PM.add(createEarlyCSEPass());
  200. PM.add(createReassociatePass());
  201. PM.add(createLICMPass());
  202. PM.add(createGVNPass());
  203. PM.add(createInstructionCombiningPass());
  204. PM.add(createDeadStoreEliminationPass());
  205. }
  206. }
  207. static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
  208. legacy::PassManagerBase &PM) {
  209. PM.add(createThreadSanitizerPass());
  210. }
  211. static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
  212. legacy::PassManagerBase &PM) {
  213. const PassManagerBuilderWrapper &BuilderWrapper =
  214. static_cast<const PassManagerBuilderWrapper&>(Builder);
  215. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  216. PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
  217. }
  218. static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
  219. legacy::PassManagerBase &PM) {
  220. const PassManagerBuilderWrapper &BuilderWrapper =
  221. static_cast<const PassManagerBuilderWrapper&>(Builder);
  222. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  223. EfficiencySanitizerOptions Opts;
  224. if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
  225. Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
  226. PM.add(createEfficiencySanitizerPass(Opts));
  227. }
  228. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  229. const CodeGenOptions &CodeGenOpts) {
  230. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  231. if (!CodeGenOpts.SimplifyLibCalls)
  232. TLII->disableAllFunctions();
  233. else {
  234. // Disable individual libc/libm calls in TargetLibraryInfo.
  235. LibFunc::Func F;
  236. for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
  237. if (TLII->getLibFunc(FuncName, F))
  238. TLII->setUnavailable(F);
  239. }
  240. switch (CodeGenOpts.getVecLib()) {
  241. case CodeGenOptions::Accelerate:
  242. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
  243. break;
  244. default:
  245. break;
  246. }
  247. return TLII;
  248. }
  249. static void addSymbolRewriterPass(const CodeGenOptions &Opts,
  250. legacy::PassManager *MPM) {
  251. llvm::SymbolRewriter::RewriteDescriptorList DL;
  252. llvm::SymbolRewriter::RewriteMapParser MapParser;
  253. for (const auto &MapFile : Opts.RewriteMapFiles)
  254. MapParser.parse(MapFile, &DL);
  255. MPM->add(createRewriteSymbolsPass(DL));
  256. }
  257. void EmitAssemblyHelper::CreatePasses(ModuleSummaryIndex *ModuleSummary) {
  258. if (CodeGenOpts.DisableLLVMPasses)
  259. return;
  260. unsigned OptLevel = CodeGenOpts.OptimizationLevel;
  261. CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
  262. // Handle disabling of LLVM optimization, where we want to preserve the
  263. // internal module before any optimization.
  264. if (CodeGenOpts.DisableLLVMOpts) {
  265. OptLevel = 0;
  266. Inlining = CodeGenOpts.NoInlining;
  267. }
  268. PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
  269. // Figure out TargetLibraryInfo.
  270. Triple TargetTriple(TheModule->getTargetTriple());
  271. PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
  272. switch (Inlining) {
  273. case CodeGenOptions::NoInlining:
  274. break;
  275. case CodeGenOptions::NormalInlining: {
  276. PMBuilder.Inliner =
  277. createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
  278. break;
  279. }
  280. case CodeGenOptions::OnlyAlwaysInlining:
  281. // Respect always_inline.
  282. if (OptLevel == 0)
  283. // Do not insert lifetime intrinsics at -O0.
  284. PMBuilder.Inliner = createAlwaysInlinerPass(false);
  285. else
  286. PMBuilder.Inliner = createAlwaysInlinerPass();
  287. break;
  288. }
  289. PMBuilder.OptLevel = OptLevel;
  290. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  291. PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
  292. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  293. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  294. PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
  295. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  296. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  297. PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
  298. PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
  299. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  300. legacy::PassManager *MPM = getPerModulePasses();
  301. // If we are performing a ThinLTO importing compile, invoke the LTO
  302. // pipeline and pass down the in-memory module summary index.
  303. if (ModuleSummary) {
  304. PMBuilder.ModuleSummary = ModuleSummary;
  305. PMBuilder.populateThinLTOPassManager(*MPM);
  306. return;
  307. }
  308. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  309. addAddDiscriminatorsPass);
  310. // In ObjC ARC mode, add the main ARC optimization passes.
  311. if (LangOpts.ObjCAutoRefCount) {
  312. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  313. addObjCARCExpandPass);
  314. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  315. addObjCARCAPElimPass);
  316. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  317. addObjCARCOptPass);
  318. }
  319. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  320. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  321. addBoundsCheckingPass);
  322. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  323. addBoundsCheckingPass);
  324. }
  325. if (CodeGenOpts.SanitizeCoverageType ||
  326. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  327. CodeGenOpts.SanitizeCoverageTraceCmp) {
  328. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  329. addSanitizerCoveragePass);
  330. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  331. addSanitizerCoveragePass);
  332. }
  333. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  334. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  335. addAddressSanitizerPasses);
  336. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  337. addAddressSanitizerPasses);
  338. }
  339. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  340. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  341. addKernelAddressSanitizerPasses);
  342. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  343. addKernelAddressSanitizerPasses);
  344. }
  345. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  346. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  347. addMemorySanitizerPass);
  348. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  349. addMemorySanitizerPass);
  350. }
  351. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  352. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  353. addThreadSanitizerPass);
  354. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  355. addThreadSanitizerPass);
  356. }
  357. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  358. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  359. addDataFlowSanitizerPass);
  360. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  361. addDataFlowSanitizerPass);
  362. }
  363. if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
  364. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  365. addEfficiencySanitizerPass);
  366. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  367. addEfficiencySanitizerPass);
  368. }
  369. // Set up the per-function pass manager.
  370. legacy::FunctionPassManager *FPM = getPerFunctionPasses();
  371. if (CodeGenOpts.VerifyModule)
  372. FPM->add(createVerifierPass());
  373. PMBuilder.populateFunctionPassManager(*FPM);
  374. // Set up the per-module pass manager.
  375. if (!CodeGenOpts.RewriteMapFiles.empty())
  376. addSymbolRewriterPass(CodeGenOpts, MPM);
  377. if (!CodeGenOpts.DisableGCov &&
  378. (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
  379. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  380. // LLVM's -default-gcov-version flag is set to something invalid.
  381. GCOVOptions Options;
  382. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  383. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  384. memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
  385. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  386. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  387. Options.FunctionNamesInData =
  388. !CodeGenOpts.CoverageNoFunctionNamesInData;
  389. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  390. MPM->add(createGCOVProfilerPass(Options));
  391. if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
  392. MPM->add(createStripSymbolsPass(true));
  393. }
  394. if (CodeGenOpts.hasProfileClangInstr()) {
  395. InstrProfOptions Options;
  396. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  397. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  398. MPM->add(createInstrProfilingLegacyPass(Options));
  399. }
  400. if (CodeGenOpts.hasProfileIRInstr()) {
  401. if (!CodeGenOpts.InstrProfileOutput.empty())
  402. PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
  403. else
  404. PMBuilder.PGOInstrGen = "default.profraw";
  405. }
  406. if (CodeGenOpts.hasProfileIRUse())
  407. PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
  408. if (!CodeGenOpts.SampleProfileFile.empty())
  409. MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
  410. PMBuilder.populateModulePassManager(*MPM);
  411. }
  412. void EmitAssemblyHelper::setCommandLineOpts() {
  413. SmallVector<const char *, 16> BackendArgs;
  414. BackendArgs.push_back("clang"); // Fake program name.
  415. if (!CodeGenOpts.DebugPass.empty()) {
  416. BackendArgs.push_back("-debug-pass");
  417. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  418. }
  419. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  420. BackendArgs.push_back("-limit-float-precision");
  421. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  422. }
  423. for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
  424. BackendArgs.push_back(BackendOption.c_str());
  425. BackendArgs.push_back(nullptr);
  426. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  427. BackendArgs.data());
  428. }
  429. TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  430. // Create the TargetMachine for generating code.
  431. std::string Error;
  432. std::string Triple = TheModule->getTargetTriple();
  433. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  434. if (!TheTarget) {
  435. if (MustCreateTM)
  436. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  437. return nullptr;
  438. }
  439. unsigned CodeModel =
  440. llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  441. .Case("small", llvm::CodeModel::Small)
  442. .Case("kernel", llvm::CodeModel::Kernel)
  443. .Case("medium", llvm::CodeModel::Medium)
  444. .Case("large", llvm::CodeModel::Large)
  445. .Case("default", llvm::CodeModel::Default)
  446. .Default(~0u);
  447. assert(CodeModel != ~0u && "invalid code model!");
  448. llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
  449. std::string FeaturesStr =
  450. llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
  451. // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
  452. llvm::Reloc::Model RM = llvm::Reloc::Default;
  453. if (CodeGenOpts.RelocationModel == "static") {
  454. RM = llvm::Reloc::Static;
  455. } else if (CodeGenOpts.RelocationModel == "pic") {
  456. RM = llvm::Reloc::PIC_;
  457. } else {
  458. assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
  459. "Invalid PIC model!");
  460. RM = llvm::Reloc::DynamicNoPIC;
  461. }
  462. CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
  463. switch (CodeGenOpts.OptimizationLevel) {
  464. default: break;
  465. case 0: OptLevel = CodeGenOpt::None; break;
  466. case 3: OptLevel = CodeGenOpt::Aggressive; break;
  467. }
  468. llvm::TargetOptions Options;
  469. if (!TargetOpts.Reciprocals.empty())
  470. Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
  471. Options.ThreadModel =
  472. llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
  473. .Case("posix", llvm::ThreadModel::POSIX)
  474. .Case("single", llvm::ThreadModel::Single);
  475. // Set float ABI type.
  476. assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
  477. CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
  478. "Invalid Floating Point ABI!");
  479. Options.FloatABIType =
  480. llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
  481. .Case("soft", llvm::FloatABI::Soft)
  482. .Case("softfp", llvm::FloatABI::Soft)
  483. .Case("hard", llvm::FloatABI::Hard)
  484. .Default(llvm::FloatABI::Default);
  485. // Set FP fusion mode.
  486. switch (CodeGenOpts.getFPContractMode()) {
  487. case CodeGenOptions::FPC_Off:
  488. Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
  489. break;
  490. case CodeGenOptions::FPC_On:
  491. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  492. break;
  493. case CodeGenOptions::FPC_Fast:
  494. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  495. break;
  496. }
  497. Options.UseInitArray = CodeGenOpts.UseInitArray;
  498. Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
  499. Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
  500. // Set EABI version.
  501. Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
  502. .Case("4", llvm::EABI::EABI4)
  503. .Case("5", llvm::EABI::EABI5)
  504. .Case("gnu", llvm::EABI::GNU)
  505. .Default(llvm::EABI::Default);
  506. Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
  507. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  508. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  509. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  510. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  511. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  512. Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
  513. Options.FunctionSections = CodeGenOpts.FunctionSections;
  514. Options.DataSections = CodeGenOpts.DataSections;
  515. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  516. Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
  517. Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
  518. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  519. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  520. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  521. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  522. Options.MCOptions.MCIncrementalLinkerCompatible =
  523. CodeGenOpts.IncrementalLinkerCompatible;
  524. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  525. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  526. Options.MCOptions.ABIName = TargetOpts.ABI;
  527. TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
  528. FeaturesStr, Options,
  529. RM, CM, OptLevel);
  530. return TM;
  531. }
  532. bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
  533. raw_pwrite_stream &OS) {
  534. // Create the code generator passes.
  535. legacy::PassManager *PM = getCodeGenPasses();
  536. // Add LibraryInfo.
  537. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  538. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  539. createTLII(TargetTriple, CodeGenOpts));
  540. PM->add(new TargetLibraryInfoWrapperPass(*TLII));
  541. // Normal mode, emit a .s or .o file by running the code generator. Note,
  542. // this also adds codegenerator level optimization passes.
  543. TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
  544. if (Action == Backend_EmitObj)
  545. CGFT = TargetMachine::CGFT_ObjectFile;
  546. else if (Action == Backend_EmitMCNull)
  547. CGFT = TargetMachine::CGFT_Null;
  548. else
  549. assert(Action == Backend_EmitAssembly && "Invalid action!");
  550. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  551. // "codegen" passes so that it isn't run multiple times when there is
  552. // inlining happening.
  553. if (CodeGenOpts.OptimizationLevel > 0)
  554. PM->add(createObjCARCContractPass());
  555. if (TM->addPassesToEmitFile(*PM, OS, CGFT,
  556. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  557. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  558. return false;
  559. }
  560. return true;
  561. }
  562. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  563. raw_pwrite_stream *OS) {
  564. TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
  565. setCommandLineOpts();
  566. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  567. Action != Backend_EmitBC &&
  568. Action != Backend_EmitLL);
  569. if (!TM)
  570. TM.reset(CreateTargetMachine(UsesCodeGen));
  571. if (UsesCodeGen && !TM)
  572. return;
  573. if (TM)
  574. TheModule->setDataLayout(TM->createDataLayout());
  575. // If we are performing a ThinLTO importing compile, load the function
  576. // index into memory and pass it into CreatePasses, which will add it
  577. // to the PassManagerBuilder and invoke LTO passes.
  578. std::unique_ptr<ModuleSummaryIndex> ModuleSummary;
  579. if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
  580. ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
  581. llvm::getModuleSummaryIndexForFile(
  582. CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) {
  583. TheModule->getContext().diagnose(DI);
  584. });
  585. if (std::error_code EC = IndexOrErr.getError()) {
  586. std::string Error = EC.message();
  587. errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile
  588. << "': " << Error << "\n";
  589. return;
  590. }
  591. ModuleSummary = std::move(IndexOrErr.get());
  592. assert(ModuleSummary && "Expected non-empty module summary index");
  593. }
  594. CreatePasses(ModuleSummary.get());
  595. switch (Action) {
  596. case Backend_EmitNothing:
  597. break;
  598. case Backend_EmitBC:
  599. getPerModulePasses()->add(createBitcodeWriterPass(
  600. *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex,
  601. CodeGenOpts.EmitSummaryIndex));
  602. break;
  603. case Backend_EmitLL:
  604. getPerModulePasses()->add(
  605. createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  606. break;
  607. default:
  608. if (!AddEmitPasses(Action, *OS))
  609. return;
  610. }
  611. // Before executing passes, print the final values of the LLVM options.
  612. cl::PrintOptionValues();
  613. // Run passes. For now we do all passes at once, but eventually we
  614. // would like to have the option of streaming code generation.
  615. if (PerFunctionPasses) {
  616. PrettyStackTraceString CrashInfo("Per-function optimization");
  617. PerFunctionPasses->doInitialization();
  618. for (Function &F : *TheModule)
  619. if (!F.isDeclaration())
  620. PerFunctionPasses->run(F);
  621. PerFunctionPasses->doFinalization();
  622. }
  623. if (PerModulePasses) {
  624. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  625. PerModulePasses->run(*TheModule);
  626. }
  627. if (CodeGenPasses) {
  628. PrettyStackTraceString CrashInfo("Code generation");
  629. CodeGenPasses->run(*TheModule);
  630. }
  631. }
  632. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  633. const CodeGenOptions &CGOpts,
  634. const clang::TargetOptions &TOpts,
  635. const LangOptions &LOpts, const llvm::DataLayout &TDesc,
  636. Module *M, BackendAction Action,
  637. raw_pwrite_stream *OS) {
  638. EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
  639. AsmHelper.EmitAssembly(Action, OS);
  640. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  641. // DataLayout.
  642. if (AsmHelper.TM) {
  643. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  644. if (DLDesc != TDesc.getStringRepresentation()) {
  645. unsigned DiagID = Diags.getCustomDiagID(
  646. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  647. "expected target description '%1'");
  648. Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
  649. }
  650. }
  651. }