BackendUtil.cpp 27 KB

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