BackendUtil.cpp 27 KB

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