BackendUtil.cpp 25 KB

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