BackendUtil.cpp 35 KB

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