BackendUtil.cpp 33 KB

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