blob: bd1a4e50e7a560fa780f543581f16c682f8fb37c [file] [log] [blame]
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00006//
7//===----------------------------------------------------------------------===//
8
Daniel Dunbarc1b17292010-06-15 17:48:49 +00009#include "clang/CodeGen/BackendUtil.h"
Richard Trieu63688182018-12-11 03:18:39 +000010#include "clang/Basic/CodeGenOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
Dan Gohmanfec0ff82011-07-05 22:02:36 +000012#include "clang/Basic/LangOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/Basic/TargetOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000014#include "clang/Frontend/FrontendDiagnostic.h"
Kostya Serebryanyce2c7262013-12-27 08:11:08 +000015#include "clang/Frontend/Utils.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000016#include "clang/Lex/HeaderSearchOptions.h"
Hal Finkel1a328f52016-12-15 02:19:17 +000017#include "llvm/ADT/SmallSet.h"
Eric Christopher583a1f72015-09-26 01:25:08 +000018#include "llvm/ADT/StringExtras.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000019#include "llvm/ADT/StringSwitch.h"
Steven Wu27fb5222016-05-11 16:26:03 +000020#include "llvm/ADT/Triple.h"
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -080021#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth418bd1a2015-01-15 02:16:55 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthaab5ec02015-01-31 11:18:46 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000025#include "llvm/Bitcode/BitcodeWriter.h"
26#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000027#include "llvm/CodeGen/RegAllocRegistry.h"
28#include "llvm/CodeGen/SchedulerRegistry.h"
David Blaikie7a4f7f52018-01-09 22:03:47 +000029#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
Chandler Carruth0a50c492014-01-12 11:11:50 +000031#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9828e692015-02-13 09:57:03 +000032#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/Module.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000034#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruthca884742014-01-13 09:26:48 +000035#include "llvm/IR/Verifier.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000036#include "llvm/LTO/LTOBackend.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000037#include "llvm/MC/MCAsmInfo.h"
Evan Chengeeb486d2011-06-29 01:14:32 +000038#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000039#include "llvm/Passes/PassBuilder.h"
Philip Pfaffee3f105c2019-02-02 23:19:32 +000040#include "llvm/Passes/PassPlugin.h"
Taewook Ohd4c50f72019-08-14 07:11:09 +000041#include "llvm/Passes/StandardInstrumentations.h"
David Blaikie9941da42018-11-17 18:04:13 +000042#include "llvm/Support/BuryPointer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000043#include "llvm/Support/CommandLine.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000044#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000045#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000046#include "llvm/Support/TargetRegistry.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000047#include "llvm/Support/TimeProfiler.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000048#include "llvm/Support/Timer.h"
49#include "llvm/Support/raw_ostream.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000050#include "llvm/Target/TargetMachine.h"
51#include "llvm/Target/TargetOptions.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000052#include "llvm/Transforms/Coroutines.h"
Brian Gesiak048239e2019-12-26 08:00:00 -050053#include "llvm/Transforms/Coroutines/CoroCleanup.h"
54#include "llvm/Transforms/Coroutines/CoroEarly.h"
55#include "llvm/Transforms/Coroutines/CoroElide.h"
56#include "llvm/Transforms/Coroutines/CoroSplit.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000057#include "llvm/Transforms/IPO.h"
Chandler Carruthb72c19f2016-08-17 03:09:11 +000058#include "llvm/Transforms/IPO/AlwaysInliner.h"
Teresa Johnson2f63d542020-01-24 12:24:18 -080059#include "llvm/Transforms/IPO/LowerTypeTests.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000060#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Tim Shen50fedec2017-06-01 23:27:51 +000061#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
David Blaikied2a572202018-04-24 00:59:22 +000062#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000063#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000064#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruthafce4492017-11-14 01:47:24 +000065#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
David Blaikie4e1ae832018-03-23 22:16:59 +000066#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000067#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Rong Xu4059e142019-04-25 17:52:43 +000068#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000069#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Leonard Chan007f6742019-07-25 20:53:15 +000070#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000071#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000072#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000073#include "llvm/Transforms/Scalar.h"
Chandler Carruth4ddaadc2016-03-11 09:02:43 +000074#include "llvm/Transforms/Scalar/GVN.h"
David Blaikiec133b1e2018-03-28 17:45:10 +000075#include "llvm/Transforms/Utils.h"
Teresa Johnson6ed79132019-01-04 19:05:01 +000076#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Leonard Chanb2065132019-06-20 19:35:25 +000077#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Tim Shen66470692017-06-29 23:08:38 +000078#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +000079#include "llvm/Transforms/Utils/SymbolRewriter.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000080#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000081using namespace clang;
82using namespace llvm;
83
serge_sans_paille24ab9b52019-06-08 17:37:47 +020084#define HANDLE_EXTENSION(Ext) \
85 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
86#include "llvm/Support/Extension.def"
87
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000088namespace {
89
Davide Italiano945de432017-02-13 16:07:05 +000090// Default filename used for profile generation.
91static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
92
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000093class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000094 DiagnosticsEngine &Diags;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000095 const HeaderSearchOptions &HSOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000096 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000097 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000098 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000099 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000100
101 Timer CodeGenerationTime;
102
Peter Collingbourne03f89072016-07-15 00:55:40 +0000103 std::unique_ptr<raw_pwrite_stream> OS;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000104
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000105 TargetIRAnalysis getTargetIRAnalysis() const {
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000106 if (TM)
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000107 return TM->getTargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000108
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000109 return TargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000110 }
111
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000112 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
Nadav Rotemec57ab32012-10-24 00:53:38 +0000113
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000114 /// Generates the TargetMachine.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000115 /// Leaves TM unchanged if it is unable to create the target machine.
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000116 /// Some of our clang tests specify triples which are not built
117 /// into clang. This is okay because these tests check the generated
118 /// IR, and they require DataLayout which depends on the triple.
119 /// In this case, we allow this method to fail and not report an error.
120 /// When MustCreateTM is used, we print an error if we are unable to load
121 /// the requested target.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000122 void CreateTargetMachine(bool MustCreateTM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000123
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000124 /// Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000125 ///
126 /// \return True on success.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000127 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000128 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
129
130 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
131 std::error_code EC;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000132 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
Fangrui Songd9b948b2019-08-05 05:43:48 +0000133 llvm::sys::fs::OF_None);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000134 if (EC) {
135 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
136 F.reset();
137 }
138 return F;
139 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000140
141public:
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000142 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
143 const HeaderSearchOptions &HeaderSearchOpts,
144 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000145 const clang::TargetOptions &TOpts,
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000146 const LangOptions &LOpts, Module *M)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000147 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
148 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
149 CodeGenerationTime("codegen", "Code Generation Time") {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000150
151 ~EmitAssemblyHelper() {
Alp Tokerf4e22382013-12-20 20:26:53 +0000152 if (CodeGenOpts.DisableFree)
David Blaikiea97eaa12014-08-29 16:53:14 +0000153 BuryPointer(std::move(TM));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000154 }
155
Ahmed Charlesb8984322014-03-07 20:03:18 +0000156 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000157
Peter Collingbourne03f89072016-07-15 00:55:40 +0000158 void EmitAssembly(BackendAction Action,
159 std::unique_ptr<raw_pwrite_stream> OS);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000160
161 void EmitAssemblyWithNewPassManager(BackendAction Action,
162 std::unique_ptr<raw_pwrite_stream> OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000163};
164
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000165// We need this wrapper to access LangOpts and CGOpts from extension functions
166// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000167class PassManagerBuilderWrapper : public PassManagerBuilder {
168public:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000169 PassManagerBuilderWrapper(const Triple &TargetTriple,
170 const CodeGenOptions &CGOpts,
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000171 const LangOptions &LangOpts)
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000172 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
173 LangOpts(LangOpts) {}
174 const Triple &getTargetTriple() const { return TargetTriple; }
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000175 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000176 const LangOptions &getLangOpts() const { return LangOpts; }
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000177
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000178private:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000179 const Triple &TargetTriple;
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000180 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000181 const LangOptions &LangOpts;
182};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000183}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000184
Dan Gohman5932ce22012-01-17 20:54:51 +0000185static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
186 if (Builder.OptLevel > 0)
187 PM.add(createObjCARCAPElimPass());
188}
189
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000190static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
191 if (Builder.OptLevel > 0)
192 PM.add(createObjCARCExpandPass());
193}
194
195static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
196 if (Builder.OptLevel > 0)
197 PM.add(createObjCARCOptPass());
198}
199
Diego Novillob56be642014-03-03 20:06:18 +0000200static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000201 legacy::PassManagerBase &PM) {
Diego Novillob56be642014-03-03 20:06:18 +0000202 PM.add(createAddDiscriminatorsPass());
203}
204
Nuno Lopesa4255892012-05-22 17:19:45 +0000205static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000206 legacy::PassManagerBase &PM) {
Chandler Carruth00a301d2017-11-14 01:30:04 +0000207 PM.add(createBoundsCheckingLegacyPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000208}
209
Leonard Chan007f6742019-07-25 20:53:15 +0000210static SanitizerCoverageOptions
211getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000212 SanitizerCoverageOptions Opts;
213 Opts.CoverageType =
214 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
215 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
216 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
217 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
Kostya Serebryany3b419712016-08-30 01:27:03 +0000218 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
219 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000220 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000221 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000222 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000223 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000224 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
Pratyai Mazumderced398f2020-04-09 02:33:36 -0700225 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
Kostya Serebryany61457762017-07-28 00:10:10 +0000226 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000227 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
Leonard Chan007f6742019-07-25 20:53:15 +0000228 return Opts;
229}
230
231static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
232 legacy::PassManagerBase &PM) {
233 const PassManagerBuilderWrapper &BuilderWrapper =
234 static_cast<const PassManagerBuilderWrapper &>(Builder);
235 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
236 auto Opts = getSancovOptsFromCGOpts(CGOpts);
Matt Morehousebef187c2020-04-10 10:42:41 -0700237 PM.add(createModuleSanitizerCoverageLegacyPassPass(
238 Opts, CGOpts.SanitizeCoverageWhitelistFiles,
239 CGOpts.SanitizeCoverageBlacklistFiles));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000240}
241
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000242// Check if ASan should use GC-friendly instrumentation for globals.
243// First of all, there is no point if -fdata-sections is off (expect for MachO,
244// where this is not a factor). Also, on ELF this feature requires an assembler
245// extension that only works with -integrated-as at the moment.
246static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000247 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
248 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000249 switch (T.getObjectFormat()) {
250 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000251 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000252 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000253 case Triple::ELF:
254 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
Hubert Tong2711e162019-07-19 08:46:18 +0000255 case Triple::XCOFF:
256 llvm::report_fatal_error("ASan not implemented for XCOFF.");
257 case Triple::Wasm:
258 case Triple::UnknownObjectFormat:
259 break;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000260 }
Hubert Tong2711e162019-07-19 08:46:18 +0000261 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000262}
263
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000264static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000265 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000266 const PassManagerBuilderWrapper &BuilderWrapper =
267 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000268 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000269 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
270 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000271 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Vitaly Buka8076c572018-12-05 01:44:31 +0000272 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000273 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000274 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
275 UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000276 PM.add(createModuleAddressSanitizerLegacyPassPass(
277 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000278}
279
280static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
281 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000282 PM.add(createAddressSanitizerFunctionPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000283 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000284 PM.add(createModuleAddressSanitizerLegacyPassPass(
Vitaly Buka8076c572018-12-05 01:44:31 +0000285 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
286 /*UseOdrIndicator*/ false));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000287}
288
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000289static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
290 legacy::PassManagerBase &PM) {
Evgeniy Stepanov3fd1b1a2017-12-20 19:05:44 +0000291 const PassManagerBuilderWrapper &BuilderWrapper =
292 static_cast<const PassManagerBuilderWrapper &>(Builder);
293 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
294 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000295 PM.add(
296 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000297}
298
299static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
300 legacy::PassManagerBase &PM) {
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000301 PM.add(createHWAddressSanitizerLegacyPassPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000302 /*CompileKernel*/ true, /*Recover*/ true));
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000303}
304
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000305static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
306 legacy::PassManagerBase &PM,
307 bool CompileKernel) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000308 const PassManagerBuilderWrapper &BuilderWrapper =
309 static_cast<const PassManagerBuilderWrapper&>(Builder);
310 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000311 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
312 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
Philip Pfaffe0ee6a932019-02-04 21:02:49 +0000313 PM.add(createMemorySanitizerLegacyPassPass(
314 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000315
316 // MemorySanitizer inserts complex instrumentation that mostly follows
317 // the logic of the original code, but operates on "shadow" values.
318 // It can benefit from re-running some general purpose optimization passes.
319 if (Builder.OptLevel > 0) {
320 PM.add(createEarlyCSEPass());
321 PM.add(createReassociatePass());
322 PM.add(createLICMPass());
323 PM.add(createGVNPass());
324 PM.add(createInstructionCombiningPass());
325 PM.add(createDeadStoreEliminationPass());
326 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000327}
328
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000329static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
330 legacy::PassManagerBase &PM) {
331 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
332}
333
334static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
335 legacy::PassManagerBase &PM) {
336 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
337}
338
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000339static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000340 legacy::PassManagerBase &PM) {
Philip Pfaffe685c76d2019-01-16 09:28:01 +0000341 PM.add(createThreadSanitizerLegacyPassPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000342}
343
Peter Collingbournec3772752013-08-07 22:47:34 +0000344static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000345 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000346 const PassManagerBuilderWrapper &BuilderWrapper =
347 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000348 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000349 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000350}
351
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -0800352static void addMemTagOptimizationPasses(const PassManagerBuilder &Builder,
353 legacy::PassManagerBase &PM) {
354 PM.add(createStackSafetyGlobalInfoWrapperPass(/*SetMetadata=*/true));
355}
356
Wenlei He60c642e2020-04-06 23:54:14 -0700357static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple) {
358 return new TargetLibraryInfoImpl(TargetTriple);
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000359}
360
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000361static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000362 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000363 llvm::SymbolRewriter::RewriteDescriptorList DL;
364
365 llvm::SymbolRewriter::RewriteMapParser MapParser;
366 for (const auto &MapFile : Opts.RewriteMapFiles)
367 MapParser.parse(MapFile, &DL);
368
369 MPM->add(createRewriteSymbolsPass(DL));
370}
371
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000372static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
373 switch (CodeGenOpts.OptimizationLevel) {
374 default:
375 llvm_unreachable("Invalid optimization level!");
376 case 0:
377 return CodeGenOpt::None;
378 case 1:
379 return CodeGenOpt::Less;
380 case 2:
381 return CodeGenOpt::Default; // O2/Os/Oz
382 case 3:
383 return CodeGenOpt::Aggressive;
384 }
385}
386
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000387static Optional<llvm::CodeModel::Model>
388getCodeModel(const CodeGenOptions &CodeGenOpts) {
389 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
David Greenecc69872018-08-22 11:34:28 +0000390 .Case("tiny", llvm::CodeModel::Tiny)
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000391 .Case("small", llvm::CodeModel::Small)
392 .Case("kernel", llvm::CodeModel::Kernel)
393 .Case("medium", llvm::CodeModel::Medium)
394 .Case("large", llvm::CodeModel::Large)
395 .Case("default", ~1u)
396 .Default(~0u);
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000397 assert(CodeModel != ~0u && "invalid code model!");
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000398 if (CodeModel == ~1u)
399 return None;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000400 return static_cast<llvm::CodeModel::Model>(CodeModel);
401}
402
Reid Kleckner1dfede32019-11-13 15:17:46 -0800403static CodeGenFileType getCodeGenFileType(BackendAction Action) {
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000404 if (Action == Backend_EmitObj)
Reid Kleckner1dfede32019-11-13 15:17:46 -0800405 return CGFT_ObjectFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000406 else if (Action == Backend_EmitMCNull)
Reid Kleckner1dfede32019-11-13 15:17:46 -0800407 return CGFT_Null;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000408 else {
409 assert(Action == Backend_EmitAssembly && "Invalid action!");
Reid Kleckner1dfede32019-11-13 15:17:46 -0800410 return CGFT_AssemblyFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000411 }
412}
413
414static void initTargetOptions(llvm::TargetOptions &Options,
415 const CodeGenOptions &CodeGenOpts,
416 const clang::TargetOptions &TargetOpts,
417 const LangOptions &LangOpts,
418 const HeaderSearchOptions &HSOpts) {
419 Options.ThreadModel =
420 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
421 .Case("posix", llvm::ThreadModel::POSIX)
422 .Case("single", llvm::ThreadModel::Single);
423
424 // Set float ABI type.
425 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
426 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
427 "Invalid Floating Point ABI!");
428 Options.FloatABIType =
429 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
430 .Case("soft", llvm::FloatABI::Soft)
431 .Case("softfp", llvm::FloatABI::Soft)
432 .Case("hard", llvm::FloatABI::Hard)
433 .Default(llvm::FloatABI::Default);
434
435 // Set FP fusion mode.
436 switch (LangOpts.getDefaultFPContractMode()) {
437 case LangOptions::FPC_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000438 // Preserve any contraction performed by the front-end. (Strict performs
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000439 // splitting of the muladd intrinsic in the backend.)
Adam Nemet03af4242017-04-20 17:09:35 +0000440 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000441 break;
442 case LangOptions::FPC_On:
443 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
444 break;
445 case LangOptions::FPC_Fast:
446 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
447 break;
448 }
449
450 Options.UseInitArray = CodeGenOpts.UseInitArray;
451 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000452 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000453 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
454
455 // Set EABI version.
Yuka Takahashidc771502017-07-01 07:57:23 +0000456 Options.EABIVersion = TargetOpts.EABIVersion;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000457
458 if (LangOpts.SjLjExceptions)
459 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
Martell Malonec950c652017-11-29 07:25:12 +0000460 if (LangOpts.SEHExceptions)
461 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
462 if (LangOpts.DWARFExceptions)
463 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
Heejin Ahne8b2b882019-09-12 04:01:37 +0000464 if (LangOpts.WasmExceptions)
465 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000466
467 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
468 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
469 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
470 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
471 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
472 Options.FunctionSections = CodeGenOpts.FunctionSections;
473 Options.DataSections = CodeGenOpts.DataSections;
474 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
KAWASHIMA Takahiro10c11e42020-01-13 09:28:02 +0000475 Options.TLSSize = CodeGenOpts.TLSSize;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000476 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +0000477 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000478 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
Sean Eveson5110d4f2018-01-08 13:42:26 +0000479 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
Peter Collingbourne14b468b2018-07-18 00:27:07 +0000480 Options.EmitAddrsig = CodeGenOpts.Addrsig;
David Candler92aa0c22019-10-31 08:55:57 +0000481 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
Djordje Todorovicc15c68a2020-03-09 11:02:35 +0100482 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000483
Aaron Puchertb207bae2019-06-26 21:36:35 +0000484 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000485 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
486 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
487 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
488 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
489 Options.MCOptions.MCIncrementalLinkerCompatible =
490 CodeGenOpts.IncrementalLinkerCompatible;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000491 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
Brian Cain7b953b62019-08-08 19:19:20 +0000492 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000493 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
494 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
495 Options.MCOptions.ABIName = TargetOpts.ABI;
496 for (const auto &Entry : HSOpts.UserEntries)
497 if (!Entry.IsFramework &&
498 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
499 Entry.Group == frontend::IncludeDirGroup::Angled ||
500 Entry.Group == frontend::IncludeDirGroup::System))
501 Options.MCOptions.IASSearchPaths.push_back(
502 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
503}
David Blaikie7a4f7f52018-01-09 22:03:47 +0000504static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
505 if (CodeGenOpts.DisableGCov)
506 return None;
507 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
508 return None;
509 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
510 // LLVM's -default-gcov-version flag is set to something invalid.
511 GCOVOptions Options;
512 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
513 Options.EmitData = CodeGenOpts.EmitGcovArcs;
514 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
515 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
516 Options.NoRedZone = CodeGenOpts.DisableRedZone;
517 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000518 Options.Filter = CodeGenOpts.ProfileFilterFiles;
519 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
David Blaikie7a4f7f52018-01-09 22:03:47 +0000520 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
521 return Options;
522}
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000523
Rong Xu4059e142019-04-25 17:52:43 +0000524static Optional<InstrProfOptions>
525getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
526 const LangOptions &LangOpts) {
527 if (!CodeGenOpts.hasProfileClangInstr())
528 return None;
529 InstrProfOptions Options;
530 Options.NoRedZone = CodeGenOpts.DisableRedZone;
531 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
532
533 // TODO: Surface the option to emit atomic profile counter increments at
534 // the driver level.
535 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
536 return Options;
537}
538
Peter Collingbourne03f89072016-07-15 00:55:40 +0000539void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000540 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000541 // Handle disabling of all LLVM passes, where we want to preserve the
542 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000543 if (CodeGenOpts.DisableLLVMPasses)
544 return;
545
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000546 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
547 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
548 // are inserted before PMBuilder ones - they'd get the default-constructed
549 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000550 Triple TargetTriple(TheModule->getTargetTriple());
Wenlei He60c642e2020-04-06 23:54:14 -0700551 std::unique_ptr<TargetLibraryInfoImpl> TLII(createTLII(TargetTriple));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000552
Teresa Johnson2f63d542020-01-24 12:24:18 -0800553 // If we reached here with a non-empty index file name, then the index file
554 // was empty and we are not performing ThinLTO backend compilation (used in
555 // testing in a distributed build environment). Drop any the type test
556 // assume sequences inserted for whole program vtables so that codegen doesn't
557 // complain.
558 if (!CodeGenOpts.ThinLTOIndexFile.empty())
559 MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
560 /*ImportSummary=*/nullptr,
561 /*DropTypeTests=*/true));
562
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000563 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
564
Chandler Carruthfcd33142016-12-23 01:24:49 +0000565 // At O0 and O1 we only run the always inliner which is more efficient. At
566 // higher optimization levels we run the normal inliner.
567 if (CodeGenOpts.OptimizationLevel <= 1) {
Jun Mad0f4af82020-03-13 15:27:45 +0800568 bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
569 !CodeGenOpts.DisableLifetimeMarkers) ||
570 LangOpts.Coroutines);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000571 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
572 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000573 // We do not want to inline hot callsites for SamplePGO module-summary build
574 // because profile annotation will happen again in ThinLTO backend, and we
575 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000576 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000577 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
578 (!CodeGenOpts.SampleProfileFile.empty() &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000579 CodeGenOpts.PrepareForThinLTO));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000580 }
581
Chandler Carruthfcd33142016-12-23 01:24:49 +0000582 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000583 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000584 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
585 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000586
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000587 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Alina Sbirleaa9b9ab82019-04-30 21:29:23 +0000588 // Loop interleaving in the loop vectorizer has historically been set to be
589 // enabled when loop unrolling is enabled.
590 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000591 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000592 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000593 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000594 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000595
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000596 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
597
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000598 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000599 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000600
Dehao Chen7810d4f2017-02-21 20:36:21 +0000601 if (CodeGenOpts.DebugInfoForProfiling ||
602 !CodeGenOpts.SampleProfileFile.empty())
603 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
604 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000605
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000606 // In ObjC ARC mode, add the main ARC optimization passes.
607 if (LangOpts.ObjCAutoRefCount) {
608 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
609 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000610 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
611 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000612 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
613 addObjCARCOptPass);
614 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000615
Richard Smith10ab78e2019-02-23 21:06:26 +0000616 if (LangOpts.Coroutines)
Brian Gesiak91a4b5a2018-04-01 23:55:21 +0000617 addCoroutinePassesToExtensionPoints(PMBuilder);
618
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000619 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000620 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
621 addBoundsCheckingPass);
622 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
623 addBoundsCheckingPass);
624 }
625
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000626 if (CodeGenOpts.SanitizeCoverageType ||
627 CodeGenOpts.SanitizeCoverageIndirectCalls ||
628 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000629 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
630 addSanitizerCoveragePass);
631 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
632 addSanitizerCoveragePass);
633 }
634
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000635 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000636 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000637 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000638 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000639 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000640 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000641
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000642 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
643 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
644 addKernelAddressSanitizerPasses);
645 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
646 addKernelAddressSanitizerPasses);
647 }
648
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000649 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
650 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
651 addHWAddressSanitizerPasses);
652 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
653 addHWAddressSanitizerPasses);
654 }
655
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000656 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
657 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
658 addKernelHWAddressSanitizerPasses);
659 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
660 addKernelHWAddressSanitizerPasses);
661 }
662
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000663 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000664 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
665 addMemorySanitizerPass);
666 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
667 addMemorySanitizerPass);
668 }
669
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000670 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
671 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
672 addKernelMemorySanitizerPass);
673 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
674 addKernelMemorySanitizerPass);
675 }
676
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000677 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000678 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000679 addThreadSanitizerPass);
680 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
681 addThreadSanitizerPass);
682 }
683
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000684 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000685 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
686 addDataFlowSanitizerPass);
687 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
688 addDataFlowSanitizerPass);
689 }
690
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -0800691 if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
692 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
693 addMemTagOptimizationPasses);
694 }
695
Chris Lattner5c123672011-05-21 20:40:11 +0000696 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000697 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000698 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000699 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000700
Chris Lattner5c123672011-05-21 20:40:11 +0000701 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000702 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000703 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000704
David Blaikie7a4f7f52018-01-09 22:03:47 +0000705 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
706 MPM.add(createGCOVProfilerPass(*Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000707 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000708 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000709 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000710
Rong Xu4059e142019-04-25 17:52:43 +0000711 if (Optional<InstrProfOptions> Options =
712 getInstrProfOptions(CodeGenOpts, LangOpts))
713 MPM.add(createInstrProfilingLegacyPass(*Options, false));
Vedant Kumaree6c2332018-08-16 22:24:47 +0000714
Rong Xua4a09b22019-03-04 20:21:31 +0000715 bool hasIRInstr = false;
Rong Xu522b5cb2016-02-29 18:54:59 +0000716 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000717 PMBuilder.EnablePGOInstrGen = true;
Rong Xua4a09b22019-03-04 20:21:31 +0000718 hasIRInstr = true;
719 }
720 if (CodeGenOpts.hasProfileCSIRInstr()) {
721 assert(!CodeGenOpts.hasProfileCSIRUse() &&
722 "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
723 "same time");
724 assert(!hasIRInstr &&
725 "Cannot have both ProfileGen pass and CSProfileGen pass at the "
726 "same time");
727 PMBuilder.EnablePGOCSInstrGen = true;
728 hasIRInstr = true;
729 }
730 if (hasIRInstr) {
Rong Xu522b5cb2016-02-29 18:54:59 +0000731 if (!CodeGenOpts.InstrProfileOutput.empty())
732 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
733 else
Benjamin Krameradcd0262020-01-28 20:23:46 +0100734 PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
Rong Xu522b5cb2016-02-29 18:54:59 +0000735 }
Rong Xua4a09b22019-03-04 20:21:31 +0000736 if (CodeGenOpts.hasProfileIRUse()) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000737 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Rong Xua4a09b22019-03-04 20:21:31 +0000738 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
739 }
Justin Bogner970ac602014-12-08 19:04:51 +0000740
Dehao Chen5717aff2016-12-14 21:41:04 +0000741 if (!CodeGenOpts.SampleProfileFile.empty())
742 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000743
Peter Collingbourne03f89072016-07-15 00:55:40 +0000744 PMBuilder.populateFunctionPassManager(FPM);
745 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000746}
747
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000748static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000749 SmallVector<const char *, 16> BackendArgs;
750 BackendArgs.push_back("clang"); // Fake program name.
751 if (!CodeGenOpts.DebugPass.empty()) {
752 BackendArgs.push_back("-debug-pass");
753 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
754 }
755 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
756 BackendArgs.push_back("-limit-float-precision");
757 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
758 }
Yaxun Liub5e80c32016-04-12 20:22:32 +0000759 BackendArgs.push_back(nullptr);
760 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
761 BackendArgs.data());
762}
763
Peter Collingbourne03f89072016-07-15 00:55:40 +0000764void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000765 // Create the TargetMachine for generating code.
766 std::string Error;
767 std::string Triple = TheModule->getTargetTriple();
768 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
769 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000770 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000771 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000772 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000773 }
774
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000775 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000776 std::string FeaturesStr =
777 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Rafael Espindolae1d70532018-01-18 00:20:03 +0000778 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000779 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000780
Nick Lewycky432add52011-12-02 22:17:00 +0000781 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000782 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000783 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
784 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000785}
786
Peter Collingbourne03f89072016-07-15 00:55:40 +0000787bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
788 BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000789 raw_pwrite_stream &OS,
790 raw_pwrite_stream *DwoOS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000791 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000792 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Wenlei He60c642e2020-04-06 23:54:14 -0700793 std::unique_ptr<TargetLibraryInfoImpl> TLII(createTLII(TargetTriple));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000794 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000795
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000796 // Normal mode, emit a .s or .o file by running the code generator. Note,
797 // this also adds codegenerator level optimization passes.
Reid Kleckner1dfede32019-11-13 15:17:46 -0800798 CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000799
800 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
801 // "codegen" passes so that it isn't run multiple times when there is
802 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000803 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000804 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000805
Peter Collingbourne91d02842018-05-22 18:52:37 +0000806 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000807 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
808 Diags.Report(diag::err_fe_unable_to_interface_with_target);
809 return false;
810 }
811
812 return true;
813}
814
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000815void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000816 std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000817 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000818
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000819 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000820
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000821 bool UsesCodeGen = (Action != Backend_EmitNothing &&
822 Action != Backend_EmitBC &&
823 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000824 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000825
Rafael Espindolab633d202015-06-23 13:59:36 +0000826 if (UsesCodeGen && !TM)
827 return;
828 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000829 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000830
Peter Collingbourne03f89072016-07-15 00:55:40 +0000831 legacy::PassManager PerModulePasses;
832 PerModulePasses.add(
833 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
834
835 legacy::FunctionPassManager PerFunctionPasses(TheModule);
836 PerFunctionPasses.add(
837 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
838
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000839 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000840
841 legacy::PassManager CodeGenPasses;
842 CodeGenPasses.add(
843 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000844
Peter Collingbourne91d02842018-05-22 18:52:37 +0000845 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000846
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000847 switch (Action) {
848 case Backend_EmitNothing:
849 break;
850
851 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +0000852 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000853 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +0000854 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
855 if (!ThinLinkOS)
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000856 return;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000857 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000858 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
859 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000860 PerModulePasses.add(createWriteThinLTOBitcodePass(
861 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000862 } else {
863 // Emit a module summary by default for Regular LTO except for ld64
864 // targets
865 bool EmitLTOSummary =
866 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +0000867 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000868 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
869 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000870 if (EmitLTOSummary) {
871 if (!TheModule->getModuleFlag("ThinLTO"))
872 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
873 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Teresa Johnson604f8022019-07-19 23:02:58 +0000874 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000875 }
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000876
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000877 PerModulePasses.add(createBitcodeWriterPass(
878 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000879 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000880 break;
881
882 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000883 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000884 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000885 break;
886
887 default:
Aaron Puchertb207bae2019-06-26 21:36:35 +0000888 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +0000889 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000890 if (!DwoOS)
891 return;
892 }
893 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
894 DwoOS ? &DwoOS->os() : nullptr))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000895 return;
896 }
897
Andrew Trick15e36e82011-04-05 18:56:55 +0000898 // Before executing passes, print the final values of the LLVM options.
899 cl::PrintOptionValues();
900
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000901 // Run passes. For now we do all passes at once, but eventually we
902 // would like to have the option of streaming code generation.
903
Peter Collingbourne03f89072016-07-15 00:55:40 +0000904 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000905 PrettyStackTraceString CrashInfo("Per-function optimization");
Russell Gallopdf494f72019-12-11 11:49:42 +0000906 llvm::TimeTraceScope TimeScope("PerFunctionPasses");
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000907
Peter Collingbourne03f89072016-07-15 00:55:40 +0000908 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000909 for (Function &F : *TheModule)
910 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000911 PerFunctionPasses.run(F);
912 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000913 }
914
Peter Collingbourne03f89072016-07-15 00:55:40 +0000915 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000916 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Russell Gallopdf494f72019-12-11 11:49:42 +0000917 llvm::TimeTraceScope TimeScope("PerModulePasses");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000918 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000919 }
920
Peter Collingbourne03f89072016-07-15 00:55:40 +0000921 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000922 PrettyStackTraceString CrashInfo("Code generation");
Russell Gallopdf494f72019-12-11 11:49:42 +0000923 llvm::TimeTraceScope TimeScope("CodeGenPasses");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000924 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000925 }
Peter Collingbourne91d02842018-05-22 18:52:37 +0000926
927 if (ThinLinkOS)
928 ThinLinkOS->keep();
929 if (DwoOS)
930 DwoOS->keep();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000931}
932
Chandler Carruth50f9e892016-12-23 20:44:01 +0000933static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
934 switch (Opts.OptimizationLevel) {
935 default:
936 llvm_unreachable("Invalid optimization level!");
937
938 case 1:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800939 return PassBuilder::OptimizationLevel::O1;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000940
941 case 2:
942 switch (Opts.OptimizeSize) {
943 default:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000944 llvm_unreachable("Invalid optimization level for size!");
Chandler Carruth50f9e892016-12-23 20:44:01 +0000945
946 case 0:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800947 return PassBuilder::OptimizationLevel::O2;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000948
949 case 1:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800950 return PassBuilder::OptimizationLevel::Os;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000951
952 case 2:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800953 return PassBuilder::OptimizationLevel::Oz;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000954 }
955
956 case 3:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800957 return PassBuilder::OptimizationLevel::O3;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000958 }
959}
960
Brian Gesiak048239e2019-12-26 08:00:00 -0500961static void addCoroutinePassesAtO0(ModulePassManager &MPM,
962 const LangOptions &LangOpts,
963 const CodeGenOptions &CodeGenOpts) {
964 if (!LangOpts.Coroutines)
965 return;
966
967 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
968
969 CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
970 CGPM.addPass(CoroSplitPass());
971 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
972 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
973
974 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
975}
976
Benjamin Kramerba2ea932019-03-28 17:18:42 +0000977static void addSanitizersAtO0(ModulePassManager &MPM,
978 const Triple &TargetTriple,
979 const LangOptions &LangOpts,
980 const CodeGenOptions &CodeGenOpts) {
Petr Hosek366cda02019-05-09 06:09:35 +0000981 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000982 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
Petr Hosek366cda02019-05-09 06:09:35 +0000983 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
984 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
985 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000986 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Petr Hosek366cda02019-05-09 06:09:35 +0000987 MPM.addPass(
988 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
989 CodeGenOpts.SanitizeAddressUseOdrIndicator));
990 };
991
992 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
993 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
994 }
995
996 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
997 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
Leonard Chan436fb2b2019-02-13 22:22:48 +0000998 }
Leonard Chan1a240ed2019-02-20 03:50:11 +0000999
1000 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001001 MPM.addPass(MemorySanitizerPass({}));
Leonard Chan1a240ed2019-02-20 03:50:11 +00001002 MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
1003 }
1004
Petr Hosek366cda02019-05-09 06:09:35 +00001005 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1006 MPM.addPass(createModuleToFunctionPassAdaptor(
1007 MemorySanitizerPass({0, false, /*Kernel=*/true})));
1008 }
1009
Leonard Chan1a240ed2019-02-20 03:50:11 +00001010 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001011 MPM.addPass(ThreadSanitizerPass());
Leonard Chan1a240ed2019-02-20 03:50:11 +00001012 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1013 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001014}
1015
Chandler Carruth50f9e892016-12-23 20:44:01 +00001016/// A clean version of `EmitAssembly` that uses the new pass manager.
1017///
1018/// Not all features are currently supported in this system, but where
1019/// necessary it falls back to the legacy pass manager to at least provide
1020/// basic functionality.
1021///
1022/// This API is planned to have its functionality finished and then to replace
1023/// `EmitAssembly` at some point in the future when the default switches.
1024void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1025 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +00001026 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001027 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001028
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001029 bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1030 Action != Backend_EmitBC &&
1031 Action != Backend_EmitLL);
1032 CreateTargetMachine(RequiresCodeGen);
1033
1034 if (RequiresCodeGen && !TM)
Chandler Carruth50f9e892016-12-23 20:44:01 +00001035 return;
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001036 if (TM)
1037 TheModule->setDataLayout(TM->createDataLayout());
Chandler Carruth50f9e892016-12-23 20:44:01 +00001038
Dehao Chenc76a27e2017-07-27 15:29:53 +00001039 Optional<PGOOptions> PGOOpt;
Davide Italiano945de432017-02-13 16:07:05 +00001040
Dehao Chenc76a27e2017-07-27 15:29:53 +00001041 if (CodeGenOpts.hasProfileIRInstr())
1042 // -fprofile-generate.
1043 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001044 ? std::string(DefaultProfileGenName)
Dehao Chenc76a27e2017-07-27 15:29:53 +00001045 : CodeGenOpts.InstrProfileOutput,
Rong Xua4a09b22019-03-04 20:21:31 +00001046 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
Richard Smith8654ae52018-10-10 23:13:35 +00001047 CodeGenOpts.DebugInfoForProfiling);
Rong Xua4a09b22019-03-04 20:21:31 +00001048 else if (CodeGenOpts.hasProfileIRUse()) {
Dehao Chenc76a27e2017-07-27 15:29:53 +00001049 // -fprofile-use.
Rong Xua4a09b22019-03-04 20:21:31 +00001050 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1051 : PGOOptions::NoCSAction;
1052 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1053 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1054 CSAction, CodeGenOpts.DebugInfoForProfiling);
1055 } else if (!CodeGenOpts.SampleProfileFile.empty())
Dehao Chenc76a27e2017-07-27 15:29:53 +00001056 // -fprofile-sample-use
Rong Xua4a09b22019-03-04 20:21:31 +00001057 PGOOpt =
1058 PGOOptions(CodeGenOpts.SampleProfileFile, "",
1059 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1060 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
Dehao Chenc76a27e2017-07-27 15:29:53 +00001061 else if (CodeGenOpts.DebugInfoForProfiling)
1062 // -fdebug-info-for-profiling
Rong Xua4a09b22019-03-04 20:21:31 +00001063 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1064 PGOOptions::NoCSAction, true);
1065
1066 // Check to see if we want to generate a CS profile.
1067 if (CodeGenOpts.hasProfileCSIRInstr()) {
1068 assert(!CodeGenOpts.hasProfileCSIRUse() &&
1069 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1070 "the same time");
1071 if (PGOOpt.hasValue()) {
1072 assert(PGOOpt->Action != PGOOptions::IRInstr &&
1073 PGOOpt->Action != PGOOptions::SampleUse &&
1074 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1075 " pass");
1076 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001077 ? std::string(DefaultProfileGenName)
Rong Xua4a09b22019-03-04 20:21:31 +00001078 : CodeGenOpts.InstrProfileOutput;
1079 PGOOpt->CSAction = PGOOptions::CSIRInstr;
1080 } else
1081 PGOOpt = PGOOptions("",
1082 CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001083 ? std::string(DefaultProfileGenName)
Rong Xua4a09b22019-03-04 20:21:31 +00001084 : CodeGenOpts.InstrProfileOutput,
1085 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1086 CodeGenOpts.DebugInfoForProfiling);
1087 }
Davide Italiano945de432017-02-13 16:07:05 +00001088
Alina Sbirlea267ac922019-05-23 18:51:02 +00001089 PipelineTuningOptions PTO;
Alina Sbirlea21efe2a2019-05-24 17:40:52 +00001090 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001091 // For historical reasons, loop interleaving is set to mirror setting for loop
1092 // unrolling.
1093 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1094 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1095 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
zhizhouy94d91222020-03-31 10:23:17 -07001096 PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile;
Brian Gesiak048239e2019-12-26 08:00:00 -05001097 PTO.Coroutines = LangOpts.Coroutines;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001098
Taewook Ohd4c50f72019-08-14 07:11:09 +00001099 PassInstrumentationCallbacks PIC;
1100 StandardInstrumentations SI;
1101 SI.registerCallbacks(PIC);
1102 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001103
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001104 // Attempt to load pass plugins and register their callbacks with PB.
1105 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1106 auto PassPlugin = PassPlugin::Load(PluginFN);
1107 if (PassPlugin) {
1108 PassPlugin->registerPassBuilderCallbacks(PB);
1109 } else {
1110 Diags.Report(diag::err_fe_unable_to_load_plugin)
1111 << PluginFN << toString(PassPlugin.takeError());
1112 }
1113 }
serge_sans_paille24ab9b52019-06-08 17:37:47 +02001114#define HANDLE_EXTENSION(Ext) \
1115 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1116#include "llvm/Support/Extension.def"
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001117
Craig Topper926b95c2017-11-14 08:48:28 +00001118 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1119 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1120 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1121 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001122
1123 // Register the AA manager first so that our version is the one used.
1124 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1125
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001126 // Register the target library analysis directly and give it a customized
1127 // preset TLI.
1128 Triple TargetTriple(TheModule->getTargetTriple());
Wenlei He60c642e2020-04-06 23:54:14 -07001129 std::unique_ptr<TargetLibraryInfoImpl> TLII(createTLII(TargetTriple));
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001130 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001131
Chandler Carruth50f9e892016-12-23 20:44:01 +00001132 // Register all the basic analyses with the managers.
1133 PB.registerModuleAnalyses(MAM);
1134 PB.registerCGSCCAnalyses(CGAM);
1135 PB.registerFunctionAnalyses(FAM);
1136 PB.registerLoopAnalyses(LAM);
1137 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1138
Tim Shenb13eebe2017-06-29 23:10:13 +00001139 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001140
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001141 if (!CodeGenOpts.DisableLLVMPasses) {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001142 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
Tim Shen66470692017-06-29 23:08:38 +00001143 bool IsLTO = CodeGenOpts.PrepareForLTO;
1144
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001145 if (CodeGenOpts.OptimizationLevel == 0) {
Teresa Johnson2f63d542020-01-24 12:24:18 -08001146 // If we reached here with a non-empty index file name, then the index
1147 // file was empty and we are not performing ThinLTO backend compilation
1148 // (used in testing in a distributed build environment). Drop any the type
1149 // test assume sequences inserted for whole program vtables so that
1150 // codegen doesn't complain.
1151 if (!CodeGenOpts.ThinLTOIndexFile.empty())
1152 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1153 /*ImportSummary=*/nullptr,
1154 /*DropTypeTests=*/true));
David Blaikieac904d02018-01-23 01:25:24 +00001155 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1156 MPM.addPass(GCOVProfilerPass(*Options));
Rong Xu4059e142019-04-25 17:52:43 +00001157 if (Optional<InstrProfOptions> Options =
1158 getInstrProfOptions(CodeGenOpts, LangOpts))
1159 MPM.addPass(InstrProfiling(*Options, false));
David Blaikieac904d02018-01-23 01:25:24 +00001160
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001161 // Build a minimal pipeline based on the semantics required by Clang,
Leonard Chan587497b2019-06-13 16:45:29 +00001162 // which is just that always inlining occurs. Further, disable generating
1163 // lifetime intrinsics to avoid enabling further optimizations during
1164 // code generation.
Jun Mad0f4af82020-03-13 15:27:45 +08001165 // However, we need to insert lifetime intrinsics to avoid invalid access
1166 // caused by multithreaded coroutines.
1167 MPM.addPass(
1168 AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001169
Rong Xuca161fa2019-08-01 22:36:34 +00001170 // At -O0, we can still do PGO. Add all the requested passes for
1171 // instrumentation PGO, if requested.
1172 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1173 PGOOpt->Action == PGOOptions::IRUse))
1174 PB.addPGOInstrPassesForO0(
1175 MPM, CodeGenOpts.DebugPassManager,
1176 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1177 /* IsCS */ false, PGOOpt->ProfileFile,
1178 PGOOpt->ProfileRemappingFile);
1179
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001180 // At -O0 we directly run necessary sanitizer passes.
1181 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1182 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1183
Teresa Johnson6ed79132019-01-04 19:05:01 +00001184 // Lastly, add semantically necessary passes for LTO.
1185 if (IsLTO || IsThinLTO) {
1186 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001187 MPM.addPass(NameAnonGlobalPass());
Teresa Johnson6ed79132019-01-04 19:05:01 +00001188 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001189 } else {
Tim Shen66470692017-06-29 23:08:38 +00001190 // Map our optimization levels into one of the distinct levels used to
1191 // configure the pipeline.
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001192 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1193
Teresa Johnson2f63d542020-01-24 12:24:18 -08001194 // If we reached here with a non-empty index file name, then the index
1195 // file was empty and we are not performing ThinLTO backend compilation
1196 // (used in testing in a distributed build environment). Drop any the type
1197 // test assume sequences inserted for whole program vtables so that
1198 // codegen doesn't complain.
1199 if (!CodeGenOpts.ThinLTOIndexFile.empty())
1200 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1201 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1202 /*ImportSummary=*/nullptr,
1203 /*DropTypeTests=*/true));
1204 });
1205
Leonard Chanb2065132019-06-20 19:35:25 +00001206 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1207 MPM.addPass(createModuleToFunctionPassAdaptor(
1208 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1209 });
1210
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001211 // Register callbacks to schedule sanitizer passes at the appropriate part of
1212 // the pipeline.
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001213 // FIXME: either handle asan/the remaining sanitizers or error out
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001214 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1215 PB.registerScalarOptimizerLateEPCallback(
1216 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1217 FPM.addPass(BoundsCheckingPass());
1218 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001219 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1220 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1221 MPM.addPass(MemorySanitizerPass({}));
1222 });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001223 PB.registerOptimizerLastEPCallback(
1224 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001225 FPM.addPass(MemorySanitizerPass({}));
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001226 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001227 }
1228 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1229 PB.registerPipelineStartEPCallback(
1230 [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001231 PB.registerOptimizerLastEPCallback(
1232 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1233 FPM.addPass(ThreadSanitizerPass());
1234 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001235 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001236 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1237 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1238 MPM.addPass(
1239 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1240 });
1241 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
Leonard Chan619b6d52019-02-14 01:07:47 +00001242 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
Leonard Chan436fb2b2019-02-13 22:22:48 +00001243 PB.registerOptimizerLastEPCallback(
Leonard Chan619b6d52019-02-14 01:07:47 +00001244 [Recover, UseAfterScope](FunctionPassManager &FPM,
1245 PassBuilder::OptimizationLevel Level) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001246 FPM.addPass(AddressSanitizerPass(
Leonard Chan619b6d52019-02-14 01:07:47 +00001247 /*CompileKernel=*/false, Recover, UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001248 });
1249 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Leonard Chan619b6d52019-02-14 01:07:47 +00001250 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1251 PB.registerPipelineStartEPCallback(
1252 [Recover, ModuleUseAfterScope,
1253 UseOdrIndicator](ModulePassManager &MPM) {
1254 MPM.addPass(ModuleAddressSanitizerPass(
1255 /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1256 UseOdrIndicator));
1257 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001258 }
David Blaikieac904d02018-01-23 01:25:24 +00001259 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1260 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1261 MPM.addPass(GCOVProfilerPass(*Options));
1262 });
Rong Xu4059e142019-04-25 17:52:43 +00001263 if (Optional<InstrProfOptions> Options =
1264 getInstrProfOptions(CodeGenOpts, LangOpts))
1265 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1266 MPM.addPass(InstrProfiling(*Options, false));
1267 });
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001268
Tim Shen66470692017-06-29 23:08:38 +00001269 if (IsThinLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001270 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1271 Level, CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001272 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001273 MPM.addPass(NameAnonGlobalPass());
1274 } else if (IsLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001275 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1276 CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001277 MPM.addPass(CanonicalizeAliasesPass());
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001278 MPM.addPass(NameAnonGlobalPass());
Tim Shen66470692017-06-29 23:08:38 +00001279 } else {
Tim Shenb13eebe2017-06-29 23:10:13 +00001280 MPM = PB.buildPerModuleDefaultPipeline(Level,
1281 CodeGenOpts.DebugPassManager);
Tim Shen66470692017-06-29 23:08:38 +00001282 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001283 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001284
Leonard Chan486b1732019-09-08 07:30:17 +00001285 if (CodeGenOpts.SanitizeCoverageType ||
1286 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1287 CodeGenOpts.SanitizeCoverageTraceCmp) {
1288 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1289 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1290 }
1291
Peter Collingbourne3b82b922019-07-17 21:45:19 +00001292 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1293 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1294 MPM.addPass(HWAddressSanitizerPass(
1295 /*CompileKernel=*/false, Recover));
1296 }
1297 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1298 MPM.addPass(HWAddressSanitizerPass(
1299 /*CompileKernel=*/true, /*Recover=*/true));
1300 }
1301
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -08001302 if (CodeGenOpts.OptimizationLevel > 0 &&
1303 LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
1304 MPM.addPass(StackSafetyGlobalAnnotatorPass());
1305 }
1306
Leonard Chan007f6742019-07-25 20:53:15 +00001307 if (CodeGenOpts.OptimizationLevel == 0) {
Brian Gesiak048239e2019-12-26 08:00:00 -05001308 addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001309 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
Leonard Chan007f6742019-07-25 20:53:15 +00001310 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001311 }
1312
1313 // FIXME: We still use the legacy pass manager to do code generation. We
1314 // create that pass manager here and use it as needed below.
1315 legacy::PassManager CodeGenPasses;
1316 bool NeedCodeGen = false;
Peter Collingbourne91d02842018-05-22 18:52:37 +00001317 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Chandler Carruth50f9e892016-12-23 20:44:01 +00001318
1319 // Append any output we need to the pass manager.
1320 switch (Action) {
1321 case Backend_EmitNothing:
1322 break;
1323
1324 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +00001325 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Tim Shen50fedec2017-06-01 23:27:51 +00001326 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00001327 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1328 if (!ThinLinkOS)
Tim Shen50fedec2017-06-01 23:27:51 +00001329 return;
Tim Shen50fedec2017-06-01 23:27:51 +00001330 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001331 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1332 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001333 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1334 : nullptr));
Tim Shen50fedec2017-06-01 23:27:51 +00001335 } else {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001336 // Emit a module summary by default for Regular LTO except for ld64
1337 // targets
1338 bool EmitLTOSummary =
1339 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +00001340 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001341 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1342 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001343 if (EmitLTOSummary) {
1344 if (!TheModule->getModuleFlag("ThinLTO"))
1345 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1346 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Leonard Chan19ec31d2019-08-21 17:24:14 +00001347 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001348 }
1349 MPM.addPass(
1350 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tim Shen50fedec2017-06-01 23:27:51 +00001351 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001352 break;
1353
1354 case Backend_EmitLL:
1355 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1356 break;
1357
1358 case Backend_EmitAssembly:
1359 case Backend_EmitMCNull:
1360 case Backend_EmitObj:
1361 NeedCodeGen = true;
1362 CodeGenPasses.add(
1363 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Aaron Puchertb207bae2019-06-26 21:36:35 +00001364 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00001365 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001366 if (!DwoOS)
1367 return;
1368 }
1369 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1370 DwoOS ? &DwoOS->os() : nullptr))
Chandler Carruth50f9e892016-12-23 20:44:01 +00001371 // FIXME: Should we handle this error differently?
1372 return;
1373 break;
1374 }
1375
1376 // Before executing passes, print the final values of the LLVM options.
1377 cl::PrintOptionValues();
1378
1379 // Now that we have all of the passes ready, run them.
1380 {
1381 PrettyStackTraceString CrashInfo("Optimizer");
1382 MPM.run(*TheModule, MAM);
1383 }
1384
1385 // Now if needed, run the legacy PM for codegen.
1386 if (NeedCodeGen) {
1387 PrettyStackTraceString CrashInfo("Code generation");
1388 CodeGenPasses.run(*TheModule);
1389 }
Peter Collingbourne91d02842018-05-22 18:52:37 +00001390
1391 if (ThinLinkOS)
1392 ThinLinkOS->keep();
1393 if (DwoOS)
1394 DwoOS->keep();
Chandler Carruth50f9e892016-12-23 20:44:01 +00001395}
1396
Peter Collingbourne47d23642017-01-24 19:54:37 +00001397Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1398 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1399 if (!BMsOrErr)
1400 return BMsOrErr.takeError();
1401
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00001402 // The bitcode file may contain multiple modules, we want the one that is
1403 // marked as being the ThinLTO module.
Vitaly Bukac35ff822018-02-16 23:34:16 +00001404 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1405 return *Bm;
Peter Collingbourne47d23642017-01-24 19:54:37 +00001406
1407 return make_error<StringError>("Could not find module summary",
1408 inconvertibleErrorCode());
1409}
1410
Vitaly Bukac35ff822018-02-16 23:34:16 +00001411BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1412 for (BitcodeModule &BM : BMs) {
1413 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1414 if (LTOInfo && LTOInfo->IsThinLTO)
1415 return &BM;
1416 }
1417 return nullptr;
1418}
1419
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001420static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001421 const HeaderSearchOptions &HeaderOpts,
1422 const CodeGenOptions &CGOpts,
1423 const clang::TargetOptions &TOpts,
1424 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +00001425 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001426 std::string SampleProfile,
Richard Smith8654ae52018-10-10 23:13:35 +00001427 std::string ProfileRemapping,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001428 BackendAction Action) {
Dehao Chen5f83d0e2017-07-10 20:31:37 +00001429 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001430 ModuleToDefinedGVSummaries;
1431 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1432
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001433 setCommandLineOpts(CGOpts);
1434
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001435 // We can simply import the values mentioned in the combined index, since
1436 // we should only invoke this using the individual indexes written out
1437 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001438 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001439 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001440 // Ignore entries for undefined references.
1441 if (GlobalList.second.SummaryList.empty())
1442 continue;
1443
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001444 auto GUID = GlobalList.first;
Teresa Johnson5ed8b002018-11-29 17:02:59 +00001445 for (auto &Summary : GlobalList.second.SummaryList) {
1446 // Skip the summaries for the importing module. These are included to
1447 // e.g. record required linkage changes.
1448 if (Summary->modulePath() == M->getModuleIdentifier())
1449 continue;
1450 // Add an entry to provoke importing by thinBackend.
1451 ImportList[Summary->modulePath()].insert(GUID);
1452 }
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001453 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001454
1455 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001456 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001457
1458 for (auto &I : ImportList) {
1459 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1460 llvm::MemoryBuffer::getFile(I.first());
1461 if (!MBOrErr) {
1462 errs() << "Error loading imported file '" << I.first()
1463 << "': " << MBOrErr.getError().message() << "\n";
1464 return;
1465 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001466
Peter Collingbourne47d23642017-01-24 19:54:37 +00001467 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1468 if (!BMOrErr) {
1469 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001470 errs() << "Error loading imported file '" << I.first()
1471 << "': " << EIB.message() << '\n';
1472 });
1473 return;
1474 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001475 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001476
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001477 OwnedImports.push_back(std::move(*MBOrErr));
1478 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001479 auto AddStream = [&](size_t Task) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001480 return std::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001481 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001482 lto::Config Conf;
Teresa Johnson9e4321c2018-04-17 16:39:25 +00001483 if (CGOpts.SaveTempsFilePrefix != "") {
1484 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1485 /* UseInputModulePath */ false)) {
1486 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1487 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1488 << '\n';
1489 });
1490 }
1491 }
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001492 Conf.CPU = TOpts.CPU;
1493 Conf.CodeModel = getCodeModel(CGOpts);
1494 Conf.MAttrs = TOpts.Features;
Rafael Espindolae1d70532018-01-18 00:20:03 +00001495 Conf.RelocModel = CGOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001496 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson867bc392019-04-23 18:56:19 +00001497 Conf.OptLevel = CGOpts.OptimizationLevel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001498 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001499 Conf.SampleProfile = std::move(SampleProfile);
Wei Mi21a47102020-01-09 20:58:31 -08001500 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1501 // For historical reasons, loop interleaving is set to mirror setting for loop
1502 // unrolling.
1503 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1504 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1505 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
zhizhouy94d91222020-03-31 10:23:17 -07001506 Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile;
Rong Xua4a09b22019-03-04 20:21:31 +00001507
1508 // Context sensitive profile.
1509 if (CGOpts.hasProfileCSIRInstr()) {
1510 Conf.RunCSIRInstr = true;
1511 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1512 } else if (CGOpts.hasProfileCSIRUse()) {
1513 Conf.RunCSIRInstr = false;
1514 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1515 }
1516
Richard Smith8654ae52018-10-10 23:13:35 +00001517 Conf.ProfileRemapping = std::move(ProfileRemapping);
Tim Shen50fedec2017-06-01 23:27:51 +00001518 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
Teresa Johnson4cd016ab2017-11-13 15:38:33 +00001519 Conf.DebugPassManager = CGOpts.DebugPassManager;
Teresa Johnson66744f82018-05-05 14:37:29 +00001520 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1521 Conf.RemarksFilename = CGOpts.OptRecordFile;
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001522 Conf.RemarksPasses = CGOpts.OptRecordPasses;
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00001523 Conf.RemarksFormat = CGOpts.OptRecordFormat;
Aaron Pucherte1dc4952019-06-15 15:38:51 +00001524 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1525 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001526 switch (Action) {
1527 case Backend_EmitNothing:
1528 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1529 return false;
1530 };
1531 break;
1532 case Backend_EmitLL:
1533 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1534 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1535 return false;
1536 };
1537 break;
1538 case Backend_EmitBC:
1539 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
Rafael Espindola76c8f822018-02-14 19:11:37 +00001540 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001541 return false;
1542 };
1543 break;
1544 default:
1545 Conf.CGFileType = getCodeGenFileType(Action);
1546 break;
1547 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001548 if (Error E = thinBackend(
Teresa Johnson66744f82018-05-05 14:37:29 +00001549 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001550 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1551 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1552 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1553 });
1554 }
1555}
1556
David Blaikie9c902b52011-09-25 23:23:43 +00001557void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001558 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001559 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001560 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001561 const LangOptions &LOpts,
1562 const llvm::DataLayout &TDesc, Module *M,
1563 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001564 std::unique_ptr<raw_pwrite_stream> OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +00001565
Russell Gallopdf494f72019-12-11 11:49:42 +00001566 llvm::TimeTraceScope TimeScope("Backend");
Anton Afanasyevd880de22019-03-30 08:42:48 +00001567
Vitaly Buka769134d2018-02-16 23:38:22 +00001568 std::unique_ptr<llvm::Module> EmptyModule;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001569 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001570 // If we are performing a ThinLTO importing compile, load the function index
1571 // into memory and pass it into runThinLTOBackend, which will run the
1572 // function importer and invoke LTO passes.
1573 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
Teresa Johnson517729f2017-05-12 19:32:17 +00001574 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1575 /*IgnoreEmptyThinLTOIndexFile*/true);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001576 if (!IndexOrErr) {
1577 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1578 "Error loading index file '" +
1579 CGOpts.ThinLTOIndexFile + "': ");
1580 return;
1581 }
1582 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1583 // A null CombinedIndex means we should skip ThinLTO compilation
1584 // (LLVM will optionally ignore empty index files, returning null instead
1585 // of an error).
Vitaly Buka769134d2018-02-16 23:38:22 +00001586 if (CombinedIndex) {
1587 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1588 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1589 LOpts, std::move(OS), CGOpts.SampleProfileFile,
Richard Smith8654ae52018-10-10 23:13:35 +00001590 CGOpts.ProfileRemappingFile, Action);
Vitaly Buka769134d2018-02-16 23:38:22 +00001591 return;
1592 }
1593 // Distributed indexing detected that nothing from the module is needed
1594 // for the final linking. So we can skip the compilation. We sill need to
1595 // output an empty object file to make sure that a linker does not fail
1596 // trying to read it. Also for some features, like CFI, we must skip
1597 // the compilation as CombinedIndex does not contain all required
1598 // information.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001599 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
Vitaly Buka769134d2018-02-16 23:38:22 +00001600 EmptyModule->setTargetTriple(M->getTargetTriple());
1601 M = EmptyModule.get();
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001602 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001603 }
1604
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001605 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001606
Chandler Carruth50f9e892016-12-23 20:44:01 +00001607 if (CGOpts.ExperimentalNewPassManager)
1608 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1609 else
1610 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001611
James Y Knightb214cbc2016-03-04 19:00:41 +00001612 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1613 // DataLayout.
1614 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001615 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001616 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001617 unsigned DiagID = Diags.getCustomDiagID(
1618 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1619 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001620 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001621 }
1622 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001623}
Steven Wu27fb5222016-05-11 16:26:03 +00001624
Steven Wu27fb5222016-05-11 16:26:03 +00001625// With -fembed-bitcode, save a copy of the llvm IR as data in the
1626// __LLVM,__bitcode section.
1627void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1628 llvm::MemoryBufferRef Buf) {
1629 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1630 return;
Teresa Johnsonc8e0bb32019-12-12 11:59:36 -08001631 llvm::EmbedBitcodeInModule(
1632 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1633 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1634 &CGOpts.CmdArgs);
Steven Wu27fb5222016-05-11 16:26:03 +00001635}