blob: 251b1fce6d85e2458940843bb0719dd5b0b58e7b [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"
Chandler Carruth418bd1a2015-01-15 02:16:55 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthaab5ec02015-01-31 11:18:46 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000024#include "llvm/Bitcode/BitcodeWriter.h"
25#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000026#include "llvm/CodeGen/RegAllocRegistry.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
David Blaikie7a4f7f52018-01-09 22:03:47 +000028#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
Chandler Carruth0a50c492014-01-12 11:11:50 +000030#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9828e692015-02-13 09:57:03 +000031#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Module.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000033#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruthca884742014-01-13 09:26:48 +000034#include "llvm/IR/Verifier.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000035#include "llvm/LTO/LTOBackend.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000036#include "llvm/MC/MCAsmInfo.h"
Evan Chengeeb486d2011-06-29 01:14:32 +000037#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000038#include "llvm/Passes/PassBuilder.h"
Philip Pfaffee3f105c2019-02-02 23:19:32 +000039#include "llvm/Passes/PassPlugin.h"
Taewook Ohd4c50f72019-08-14 07:11:09 +000040#include "llvm/Passes/StandardInstrumentations.h"
David Blaikie9941da42018-11-17 18:04:13 +000041#include "llvm/Support/BuryPointer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000042#include "llvm/Support/CommandLine.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000043#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000044#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000045#include "llvm/Support/TargetRegistry.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000046#include "llvm/Support/TimeProfiler.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000047#include "llvm/Support/Timer.h"
48#include "llvm/Support/raw_ostream.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000049#include "llvm/Target/TargetMachine.h"
50#include "llvm/Target/TargetOptions.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000051#include "llvm/Transforms/Coroutines.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000052#include "llvm/Transforms/IPO.h"
Chandler Carruthb72c19f2016-08-17 03:09:11 +000053#include "llvm/Transforms/IPO/AlwaysInliner.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000054#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Tim Shen50fedec2017-06-01 23:27:51 +000055#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
David Blaikied2a572202018-04-24 00:59:22 +000056#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000058#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruthafce4492017-11-14 01:47:24 +000059#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
David Blaikie4e1ae832018-03-23 22:16:59 +000060#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000061#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Rong Xu4059e142019-04-25 17:52:43 +000062#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000063#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Leonard Chan007f6742019-07-25 20:53:15 +000064#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000065#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000066#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000067#include "llvm/Transforms/Scalar.h"
Chandler Carruth4ddaadc2016-03-11 09:02:43 +000068#include "llvm/Transforms/Scalar/GVN.h"
David Blaikiec133b1e2018-03-28 17:45:10 +000069#include "llvm/Transforms/Utils.h"
Teresa Johnson6ed79132019-01-04 19:05:01 +000070#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Leonard Chanb2065132019-06-20 19:35:25 +000071#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Tim Shen66470692017-06-29 23:08:38 +000072#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +000073#include "llvm/Transforms/Utils/SymbolRewriter.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000074#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000075using namespace clang;
76using namespace llvm;
77
78namespace {
79
Davide Italiano945de432017-02-13 16:07:05 +000080// Default filename used for profile generation.
81static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
82
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000083class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000084 DiagnosticsEngine &Diags;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000085 const HeaderSearchOptions &HSOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000086 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000087 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000088 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000089 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000090
91 Timer CodeGenerationTime;
92
Peter Collingbourne03f89072016-07-15 00:55:40 +000093 std::unique_ptr<raw_pwrite_stream> OS;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000094
Chandler Carruthd294bdb2015-02-01 12:26:23 +000095 TargetIRAnalysis getTargetIRAnalysis() const {
Chandler Carruthaab5ec02015-01-31 11:18:46 +000096 if (TM)
Chandler Carruthd294bdb2015-02-01 12:26:23 +000097 return TM->getTargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +000098
Chandler Carruthd294bdb2015-02-01 12:26:23 +000099 return TargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000100 }
101
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000102 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
Nadav Rotemec57ab32012-10-24 00:53:38 +0000103
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000104 /// Generates the TargetMachine.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000105 /// Leaves TM unchanged if it is unable to create the target machine.
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000106 /// Some of our clang tests specify triples which are not built
107 /// into clang. This is okay because these tests check the generated
108 /// IR, and they require DataLayout which depends on the triple.
109 /// In this case, we allow this method to fail and not report an error.
110 /// When MustCreateTM is used, we print an error if we are unable to load
111 /// the requested target.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000112 void CreateTargetMachine(bool MustCreateTM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000113
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000114 /// Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000115 ///
116 /// \return True on success.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000117 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000118 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
119
120 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
121 std::error_code EC;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000122 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
Fangrui Songd9b948b2019-08-05 05:43:48 +0000123 llvm::sys::fs::OF_None);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000124 if (EC) {
125 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
126 F.reset();
127 }
128 return F;
129 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000130
131public:
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000132 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
133 const HeaderSearchOptions &HeaderSearchOpts,
134 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000135 const clang::TargetOptions &TOpts,
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000136 const LangOptions &LOpts, Module *M)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000137 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
138 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
139 CodeGenerationTime("codegen", "Code Generation Time") {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000140
141 ~EmitAssemblyHelper() {
Alp Tokerf4e22382013-12-20 20:26:53 +0000142 if (CodeGenOpts.DisableFree)
David Blaikiea97eaa12014-08-29 16:53:14 +0000143 BuryPointer(std::move(TM));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000144 }
145
Ahmed Charlesb8984322014-03-07 20:03:18 +0000146 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000147
Peter Collingbourne03f89072016-07-15 00:55:40 +0000148 void EmitAssembly(BackendAction Action,
149 std::unique_ptr<raw_pwrite_stream> OS);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000150
151 void EmitAssemblyWithNewPassManager(BackendAction Action,
152 std::unique_ptr<raw_pwrite_stream> OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000153};
154
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000155// We need this wrapper to access LangOpts and CGOpts from extension functions
156// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000157class PassManagerBuilderWrapper : public PassManagerBuilder {
158public:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000159 PassManagerBuilderWrapper(const Triple &TargetTriple,
160 const CodeGenOptions &CGOpts,
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000161 const LangOptions &LangOpts)
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000162 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
163 LangOpts(LangOpts) {}
164 const Triple &getTargetTriple() const { return TargetTriple; }
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000165 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000166 const LangOptions &getLangOpts() const { return LangOpts; }
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000167
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000168private:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000169 const Triple &TargetTriple;
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000170 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000171 const LangOptions &LangOpts;
172};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000173}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000174
Dan Gohman5932ce22012-01-17 20:54:51 +0000175static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
176 if (Builder.OptLevel > 0)
177 PM.add(createObjCARCAPElimPass());
178}
179
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000180static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
181 if (Builder.OptLevel > 0)
182 PM.add(createObjCARCExpandPass());
183}
184
185static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
186 if (Builder.OptLevel > 0)
187 PM.add(createObjCARCOptPass());
188}
189
Diego Novillob56be642014-03-03 20:06:18 +0000190static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000191 legacy::PassManagerBase &PM) {
Diego Novillob56be642014-03-03 20:06:18 +0000192 PM.add(createAddDiscriminatorsPass());
193}
194
Nuno Lopesa4255892012-05-22 17:19:45 +0000195static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000196 legacy::PassManagerBase &PM) {
Chandler Carruth00a301d2017-11-14 01:30:04 +0000197 PM.add(createBoundsCheckingLegacyPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000198}
199
Leonard Chan007f6742019-07-25 20:53:15 +0000200static SanitizerCoverageOptions
201getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000202 SanitizerCoverageOptions Opts;
203 Opts.CoverageType =
204 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
205 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
206 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
207 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
Kostya Serebryany3b419712016-08-30 01:27:03 +0000208 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
209 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000210 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000211 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000212 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000213 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000214 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
Kostya Serebryany61457762017-07-28 00:10:10 +0000215 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000216 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
Leonard Chan007f6742019-07-25 20:53:15 +0000217 return Opts;
218}
219
220static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
221 legacy::PassManagerBase &PM) {
222 const PassManagerBuilderWrapper &BuilderWrapper =
223 static_cast<const PassManagerBuilderWrapper &>(Builder);
224 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
225 auto Opts = getSancovOptsFromCGOpts(CGOpts);
226 PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000227}
228
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000229// Check if ASan should use GC-friendly instrumentation for globals.
230// First of all, there is no point if -fdata-sections is off (expect for MachO,
231// where this is not a factor). Also, on ELF this feature requires an assembler
232// extension that only works with -integrated-as at the moment.
233static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000234 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
235 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000236 switch (T.getObjectFormat()) {
237 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000238 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000239 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000240 case Triple::ELF:
241 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
Hubert Tong2711e162019-07-19 08:46:18 +0000242 case Triple::XCOFF:
243 llvm::report_fatal_error("ASan not implemented for XCOFF.");
244 case Triple::Wasm:
245 case Triple::UnknownObjectFormat:
246 break;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000247 }
Hubert Tong2711e162019-07-19 08:46:18 +0000248 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000249}
250
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000251static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000252 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000253 const PassManagerBuilderWrapper &BuilderWrapper =
254 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000255 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000256 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
257 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000258 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Vitaly Buka8076c572018-12-05 01:44:31 +0000259 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000260 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000261 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
262 UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000263 PM.add(createModuleAddressSanitizerLegacyPassPass(
264 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000265}
266
267static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
268 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000269 PM.add(createAddressSanitizerFunctionPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000270 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000271 PM.add(createModuleAddressSanitizerLegacyPassPass(
Vitaly Buka8076c572018-12-05 01:44:31 +0000272 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
273 /*UseOdrIndicator*/ false));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000274}
275
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000276static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
277 legacy::PassManagerBase &PM) {
Evgeniy Stepanov3fd1b1a2017-12-20 19:05:44 +0000278 const PassManagerBuilderWrapper &BuilderWrapper =
279 static_cast<const PassManagerBuilderWrapper &>(Builder);
280 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
281 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000282 PM.add(
283 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000284}
285
286static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
287 legacy::PassManagerBase &PM) {
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000288 PM.add(createHWAddressSanitizerLegacyPassPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000289 /*CompileKernel*/ true, /*Recover*/ true));
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000290}
291
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000292static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
293 legacy::PassManagerBase &PM,
294 bool CompileKernel) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000295 const PassManagerBuilderWrapper &BuilderWrapper =
296 static_cast<const PassManagerBuilderWrapper&>(Builder);
297 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000298 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
299 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
Philip Pfaffe0ee6a932019-02-04 21:02:49 +0000300 PM.add(createMemorySanitizerLegacyPassPass(
301 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000302
303 // MemorySanitizer inserts complex instrumentation that mostly follows
304 // the logic of the original code, but operates on "shadow" values.
305 // It can benefit from re-running some general purpose optimization passes.
306 if (Builder.OptLevel > 0) {
307 PM.add(createEarlyCSEPass());
308 PM.add(createReassociatePass());
309 PM.add(createLICMPass());
310 PM.add(createGVNPass());
311 PM.add(createInstructionCombiningPass());
312 PM.add(createDeadStoreEliminationPass());
313 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000314}
315
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000316static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
317 legacy::PassManagerBase &PM) {
318 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
319}
320
321static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
322 legacy::PassManagerBase &PM) {
323 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
324}
325
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000326static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000327 legacy::PassManagerBase &PM) {
Philip Pfaffe685c76d2019-01-16 09:28:01 +0000328 PM.add(createThreadSanitizerLegacyPassPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000329}
330
Peter Collingbournec3772752013-08-07 22:47:34 +0000331static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000332 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000333 const PassManagerBuilderWrapper &BuilderWrapper =
334 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000335 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000336 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000337}
338
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000339static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
340 const CodeGenOptions &CodeGenOpts) {
341 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000342 if (!CodeGenOpts.SimplifyLibCalls)
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000343 TLII->disableAllFunctions();
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000344 else {
345 // Disable individual libc/libm calls in TargetLibraryInfo.
David L. Jones7a7dd032017-01-23 23:16:58 +0000346 LibFunc F;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000347 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
348 if (TLII->getLibFunc(FuncName, F))
349 TLII->setUnavailable(F);
350 }
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000351
352 switch (CodeGenOpts.getVecLib()) {
353 case CodeGenOptions::Accelerate:
354 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
355 break;
Nemanja Ivanovic6321c682019-06-05 01:57:57 +0000356 case CodeGenOptions::MASSV:
357 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
358 break;
Matt Masten6731dea2016-07-29 16:44:24 +0000359 case CodeGenOptions::SVML:
360 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
361 break;
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000362 default:
363 break;
364 }
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000365 return TLII;
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000366}
367
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000368static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000369 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000370 llvm::SymbolRewriter::RewriteDescriptorList DL;
371
372 llvm::SymbolRewriter::RewriteMapParser MapParser;
373 for (const auto &MapFile : Opts.RewriteMapFiles)
374 MapParser.parse(MapFile, &DL);
375
376 MPM->add(createRewriteSymbolsPass(DL));
377}
378
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000379static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
380 switch (CodeGenOpts.OptimizationLevel) {
381 default:
382 llvm_unreachable("Invalid optimization level!");
383 case 0:
384 return CodeGenOpt::None;
385 case 1:
386 return CodeGenOpt::Less;
387 case 2:
388 return CodeGenOpt::Default; // O2/Os/Oz
389 case 3:
390 return CodeGenOpt::Aggressive;
391 }
392}
393
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000394static Optional<llvm::CodeModel::Model>
395getCodeModel(const CodeGenOptions &CodeGenOpts) {
396 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
David Greenecc69872018-08-22 11:34:28 +0000397 .Case("tiny", llvm::CodeModel::Tiny)
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000398 .Case("small", llvm::CodeModel::Small)
399 .Case("kernel", llvm::CodeModel::Kernel)
400 .Case("medium", llvm::CodeModel::Medium)
401 .Case("large", llvm::CodeModel::Large)
402 .Case("default", ~1u)
403 .Default(~0u);
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000404 assert(CodeModel != ~0u && "invalid code model!");
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000405 if (CodeModel == ~1u)
406 return None;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000407 return static_cast<llvm::CodeModel::Model>(CodeModel);
408}
409
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000410static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
411 if (Action == Backend_EmitObj)
412 return TargetMachine::CGFT_ObjectFile;
413 else if (Action == Backend_EmitMCNull)
414 return TargetMachine::CGFT_Null;
415 else {
416 assert(Action == Backend_EmitAssembly && "Invalid action!");
417 return TargetMachine::CGFT_AssemblyFile;
418 }
419}
420
421static void initTargetOptions(llvm::TargetOptions &Options,
422 const CodeGenOptions &CodeGenOpts,
423 const clang::TargetOptions &TargetOpts,
424 const LangOptions &LangOpts,
425 const HeaderSearchOptions &HSOpts) {
426 Options.ThreadModel =
427 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
428 .Case("posix", llvm::ThreadModel::POSIX)
429 .Case("single", llvm::ThreadModel::Single);
430
431 // Set float ABI type.
432 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
433 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
434 "Invalid Floating Point ABI!");
435 Options.FloatABIType =
436 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
437 .Case("soft", llvm::FloatABI::Soft)
438 .Case("softfp", llvm::FloatABI::Soft)
439 .Case("hard", llvm::FloatABI::Hard)
440 .Default(llvm::FloatABI::Default);
441
442 // Set FP fusion mode.
443 switch (LangOpts.getDefaultFPContractMode()) {
444 case LangOptions::FPC_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000445 // Preserve any contraction performed by the front-end. (Strict performs
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000446 // splitting of the muladd intrinsic in the backend.)
Adam Nemet03af4242017-04-20 17:09:35 +0000447 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000448 break;
449 case LangOptions::FPC_On:
450 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
451 break;
452 case LangOptions::FPC_Fast:
453 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
454 break;
455 }
456
457 Options.UseInitArray = CodeGenOpts.UseInitArray;
458 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000459 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000460 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
461
462 // Set EABI version.
Yuka Takahashidc771502017-07-01 07:57:23 +0000463 Options.EABIVersion = TargetOpts.EABIVersion;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000464
465 if (LangOpts.SjLjExceptions)
466 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
Martell Malonec950c652017-11-29 07:25:12 +0000467 if (LangOpts.SEHExceptions)
468 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
469 if (LangOpts.DWARFExceptions)
470 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000471
472 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
473 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
474 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
475 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
476 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
477 Options.FunctionSections = CodeGenOpts.FunctionSections;
478 Options.DataSections = CodeGenOpts.DataSections;
479 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
480 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +0000481 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000482 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
Sean Eveson5110d4f2018-01-08 13:42:26 +0000483 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
Peter Collingbourne14b468b2018-07-18 00:27:07 +0000484 Options.EmitAddrsig = CodeGenOpts.Addrsig;
Djordje Todorovic639d36b2019-06-26 09:38:09 +0000485 Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000486
Aaron Puchertb207bae2019-06-26 21:36:35 +0000487 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000488 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
489 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
490 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
491 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
492 Options.MCOptions.MCIncrementalLinkerCompatible =
493 CodeGenOpts.IncrementalLinkerCompatible;
494 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
495 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
Brian Cain7b953b62019-08-08 19:19:20 +0000496 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000497 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
498 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
499 Options.MCOptions.ABIName = TargetOpts.ABI;
500 for (const auto &Entry : HSOpts.UserEntries)
501 if (!Entry.IsFramework &&
502 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
503 Entry.Group == frontend::IncludeDirGroup::Angled ||
504 Entry.Group == frontend::IncludeDirGroup::System))
505 Options.MCOptions.IASSearchPaths.push_back(
506 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
507}
David Blaikie7a4f7f52018-01-09 22:03:47 +0000508static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
509 if (CodeGenOpts.DisableGCov)
510 return None;
511 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
512 return None;
513 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
514 // LLVM's -default-gcov-version flag is set to something invalid.
515 GCOVOptions Options;
516 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
517 Options.EmitData = CodeGenOpts.EmitGcovArcs;
518 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
519 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
520 Options.NoRedZone = CodeGenOpts.DisableRedZone;
521 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000522 Options.Filter = CodeGenOpts.ProfileFilterFiles;
523 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
David Blaikie7a4f7f52018-01-09 22:03:47 +0000524 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
525 return Options;
526}
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000527
Rong Xu4059e142019-04-25 17:52:43 +0000528static Optional<InstrProfOptions>
529getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
530 const LangOptions &LangOpts) {
531 if (!CodeGenOpts.hasProfileClangInstr())
532 return None;
533 InstrProfOptions Options;
534 Options.NoRedZone = CodeGenOpts.DisableRedZone;
535 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
536
537 // TODO: Surface the option to emit atomic profile counter increments at
538 // the driver level.
539 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
540 return Options;
541}
542
Peter Collingbourne03f89072016-07-15 00:55:40 +0000543void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000544 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000545 // Handle disabling of all LLVM passes, where we want to preserve the
546 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000547 if (CodeGenOpts.DisableLLVMPasses)
548 return;
549
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000550 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
551 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
552 // are inserted before PMBuilder ones - they'd get the default-constructed
553 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000554 Triple TargetTriple(TheModule->getTargetTriple());
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000555 std::unique_ptr<TargetLibraryInfoImpl> TLII(
556 createTLII(TargetTriple, CodeGenOpts));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000557
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000558 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
559
Chandler Carruthfcd33142016-12-23 01:24:49 +0000560 // At O0 and O1 we only run the always inliner which is more efficient. At
561 // higher optimization levels we run the normal inliner.
562 if (CodeGenOpts.OptimizationLevel <= 1) {
Mehdi Amini7f873072017-01-06 23:18:09 +0000563 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
564 !CodeGenOpts.DisableLifetimeMarkers);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000565 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
566 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000567 // We do not want to inline hot callsites for SamplePGO module-summary build
568 // because profile annotation will happen again in ThinLTO backend, and we
569 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000570 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000571 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
572 (!CodeGenOpts.SampleProfileFile.empty() &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000573 CodeGenOpts.PrepareForThinLTO));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000574 }
575
Chandler Carruthfcd33142016-12-23 01:24:49 +0000576 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000577 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000578 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
579 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000580
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000581 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Alina Sbirleaa9b9ab82019-04-30 21:29:23 +0000582 // Loop interleaving in the loop vectorizer has historically been set to be
583 // enabled when loop unrolling is enabled.
584 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000585 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000586 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000587 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000588 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000589
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000590 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
591
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000592 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000593 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000594
Dehao Chen7810d4f2017-02-21 20:36:21 +0000595 if (CodeGenOpts.DebugInfoForProfiling ||
596 !CodeGenOpts.SampleProfileFile.empty())
597 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
598 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000599
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000600 // In ObjC ARC mode, add the main ARC optimization passes.
601 if (LangOpts.ObjCAutoRefCount) {
602 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
603 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000604 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
605 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000606 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
607 addObjCARCOptPass);
608 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000609
Richard Smith10ab78e2019-02-23 21:06:26 +0000610 if (LangOpts.Coroutines)
Brian Gesiak91a4b5a2018-04-01 23:55:21 +0000611 addCoroutinePassesToExtensionPoints(PMBuilder);
612
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000613 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000614 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
615 addBoundsCheckingPass);
616 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
617 addBoundsCheckingPass);
618 }
619
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000620 if (CodeGenOpts.SanitizeCoverageType ||
621 CodeGenOpts.SanitizeCoverageIndirectCalls ||
622 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000623 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
624 addSanitizerCoveragePass);
625 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
626 addSanitizerCoveragePass);
627 }
628
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000629 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000630 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000631 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000632 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000633 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000634 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000635
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000636 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
637 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
638 addKernelAddressSanitizerPasses);
639 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
640 addKernelAddressSanitizerPasses);
641 }
642
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000643 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
644 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
645 addHWAddressSanitizerPasses);
646 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
647 addHWAddressSanitizerPasses);
648 }
649
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000650 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
651 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
652 addKernelHWAddressSanitizerPasses);
653 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
654 addKernelHWAddressSanitizerPasses);
655 }
656
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000657 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000658 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
659 addMemorySanitizerPass);
660 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
661 addMemorySanitizerPass);
662 }
663
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000664 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
665 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
666 addKernelMemorySanitizerPass);
667 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
668 addKernelMemorySanitizerPass);
669 }
670
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000671 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000672 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000673 addThreadSanitizerPass);
674 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
675 addThreadSanitizerPass);
676 }
677
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000678 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000679 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
680 addDataFlowSanitizerPass);
681 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
682 addDataFlowSanitizerPass);
683 }
684
Chris Lattner5c123672011-05-21 20:40:11 +0000685 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000686 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000687 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000688 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000689
Chris Lattner5c123672011-05-21 20:40:11 +0000690 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000691 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000692 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000693
David Blaikie7a4f7f52018-01-09 22:03:47 +0000694 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
695 MPM.add(createGCOVProfilerPass(*Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000696 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000697 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000698 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000699
Rong Xu4059e142019-04-25 17:52:43 +0000700 if (Optional<InstrProfOptions> Options =
701 getInstrProfOptions(CodeGenOpts, LangOpts))
702 MPM.add(createInstrProfilingLegacyPass(*Options, false));
Vedant Kumaree6c2332018-08-16 22:24:47 +0000703
Rong Xua4a09b22019-03-04 20:21:31 +0000704 bool hasIRInstr = false;
Rong Xu522b5cb2016-02-29 18:54:59 +0000705 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000706 PMBuilder.EnablePGOInstrGen = true;
Rong Xua4a09b22019-03-04 20:21:31 +0000707 hasIRInstr = true;
708 }
709 if (CodeGenOpts.hasProfileCSIRInstr()) {
710 assert(!CodeGenOpts.hasProfileCSIRUse() &&
711 "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
712 "same time");
713 assert(!hasIRInstr &&
714 "Cannot have both ProfileGen pass and CSProfileGen pass at the "
715 "same time");
716 PMBuilder.EnablePGOCSInstrGen = true;
717 hasIRInstr = true;
718 }
719 if (hasIRInstr) {
Rong Xu522b5cb2016-02-29 18:54:59 +0000720 if (!CodeGenOpts.InstrProfileOutput.empty())
721 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
722 else
Davide Italiano945de432017-02-13 16:07:05 +0000723 PMBuilder.PGOInstrGen = DefaultProfileGenName;
Rong Xu522b5cb2016-02-29 18:54:59 +0000724 }
Rong Xua4a09b22019-03-04 20:21:31 +0000725 if (CodeGenOpts.hasProfileIRUse()) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000726 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Rong Xua4a09b22019-03-04 20:21:31 +0000727 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
728 }
Justin Bogner970ac602014-12-08 19:04:51 +0000729
Dehao Chen5717aff2016-12-14 21:41:04 +0000730 if (!CodeGenOpts.SampleProfileFile.empty())
731 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000732
Peter Collingbourne03f89072016-07-15 00:55:40 +0000733 PMBuilder.populateFunctionPassManager(FPM);
734 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000735}
736
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000737static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000738 SmallVector<const char *, 16> BackendArgs;
739 BackendArgs.push_back("clang"); // Fake program name.
740 if (!CodeGenOpts.DebugPass.empty()) {
741 BackendArgs.push_back("-debug-pass");
742 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
743 }
744 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
745 BackendArgs.push_back("-limit-float-precision");
746 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
747 }
Yaxun Liub5e80c32016-04-12 20:22:32 +0000748 BackendArgs.push_back(nullptr);
749 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
750 BackendArgs.data());
751}
752
Peter Collingbourne03f89072016-07-15 00:55:40 +0000753void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000754 // Create the TargetMachine for generating code.
755 std::string Error;
756 std::string Triple = TheModule->getTargetTriple();
757 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
758 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000759 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000760 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000761 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000762 }
763
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000764 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000765 std::string FeaturesStr =
766 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Rafael Espindolae1d70532018-01-18 00:20:03 +0000767 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000768 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000769
Nick Lewycky432add52011-12-02 22:17:00 +0000770 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000771 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000772 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
773 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000774}
775
Peter Collingbourne03f89072016-07-15 00:55:40 +0000776bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
777 BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000778 raw_pwrite_stream &OS,
779 raw_pwrite_stream *DwoOS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000780 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000781 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000782 std::unique_ptr<TargetLibraryInfoImpl> TLII(
783 createTLII(TargetTriple, CodeGenOpts));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000784 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000785
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000786 // Normal mode, emit a .s or .o file by running the code generator. Note,
787 // this also adds codegenerator level optimization passes.
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000788 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000789
790 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
791 // "codegen" passes so that it isn't run multiple times when there is
792 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000793 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000794 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000795
Peter Collingbourne91d02842018-05-22 18:52:37 +0000796 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000797 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
798 Diags.Report(diag::err_fe_unable_to_interface_with_target);
799 return false;
800 }
801
802 return true;
803}
804
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000805void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000806 std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000807 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000808
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000809 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000810
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000811 bool UsesCodeGen = (Action != Backend_EmitNothing &&
812 Action != Backend_EmitBC &&
813 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000814 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000815
Rafael Espindolab633d202015-06-23 13:59:36 +0000816 if (UsesCodeGen && !TM)
817 return;
818 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000819 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000820
Peter Collingbourne03f89072016-07-15 00:55:40 +0000821 legacy::PassManager PerModulePasses;
822 PerModulePasses.add(
823 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
824
825 legacy::FunctionPassManager PerFunctionPasses(TheModule);
826 PerFunctionPasses.add(
827 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
828
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000829 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000830
831 legacy::PassManager CodeGenPasses;
832 CodeGenPasses.add(
833 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000834
Peter Collingbourne91d02842018-05-22 18:52:37 +0000835 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000836
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000837 switch (Action) {
838 case Backend_EmitNothing:
839 break;
840
841 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +0000842 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000843 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +0000844 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
845 if (!ThinLinkOS)
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000846 return;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000847 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000848 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
849 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000850 PerModulePasses.add(createWriteThinLTOBitcodePass(
851 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000852 } else {
853 // Emit a module summary by default for Regular LTO except for ld64
854 // targets
855 bool EmitLTOSummary =
856 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +0000857 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000858 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
859 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000860 if (EmitLTOSummary) {
861 if (!TheModule->getModuleFlag("ThinLTO"))
862 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
863 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Teresa Johnson604f8022019-07-19 23:02:58 +0000864 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000865 }
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000866
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000867 PerModulePasses.add(createBitcodeWriterPass(
868 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000869 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000870 break;
871
872 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000873 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000874 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000875 break;
876
877 default:
Aaron Puchertb207bae2019-06-26 21:36:35 +0000878 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +0000879 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000880 if (!DwoOS)
881 return;
882 }
883 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
884 DwoOS ? &DwoOS->os() : nullptr))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000885 return;
886 }
887
Andrew Trick15e36e82011-04-05 18:56:55 +0000888 // Before executing passes, print the final values of the LLVM options.
889 cl::PrintOptionValues();
890
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000891 // Run passes. For now we do all passes at once, but eventually we
892 // would like to have the option of streaming code generation.
893
Peter Collingbourne03f89072016-07-15 00:55:40 +0000894 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000895 PrettyStackTraceString CrashInfo("Per-function optimization");
896
Peter Collingbourne03f89072016-07-15 00:55:40 +0000897 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000898 for (Function &F : *TheModule)
899 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000900 PerFunctionPasses.run(F);
901 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000902 }
903
Peter Collingbourne03f89072016-07-15 00:55:40 +0000904 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000905 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000906 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000907 }
908
Peter Collingbourne03f89072016-07-15 00:55:40 +0000909 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000910 PrettyStackTraceString CrashInfo("Code generation");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000911 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000912 }
Peter Collingbourne91d02842018-05-22 18:52:37 +0000913
914 if (ThinLinkOS)
915 ThinLinkOS->keep();
916 if (DwoOS)
917 DwoOS->keep();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000918}
919
Chandler Carruth50f9e892016-12-23 20:44:01 +0000920static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
921 switch (Opts.OptimizationLevel) {
922 default:
923 llvm_unreachable("Invalid optimization level!");
924
925 case 1:
926 return PassBuilder::O1;
927
928 case 2:
929 switch (Opts.OptimizeSize) {
930 default:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000931 llvm_unreachable("Invalid optimization level for size!");
Chandler Carruth50f9e892016-12-23 20:44:01 +0000932
933 case 0:
934 return PassBuilder::O2;
935
936 case 1:
937 return PassBuilder::Os;
938
939 case 2:
940 return PassBuilder::Oz;
941 }
942
943 case 3:
944 return PassBuilder::O3;
945 }
946}
947
Benjamin Kramerba2ea932019-03-28 17:18:42 +0000948static void addSanitizersAtO0(ModulePassManager &MPM,
949 const Triple &TargetTriple,
950 const LangOptions &LangOpts,
951 const CodeGenOptions &CodeGenOpts) {
Petr Hosek366cda02019-05-09 06:09:35 +0000952 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000953 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
Petr Hosek366cda02019-05-09 06:09:35 +0000954 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
955 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
956 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000957 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Petr Hosek366cda02019-05-09 06:09:35 +0000958 MPM.addPass(
959 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
960 CodeGenOpts.SanitizeAddressUseOdrIndicator));
961 };
962
963 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
964 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
965 }
966
967 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
968 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
Leonard Chan436fb2b2019-02-13 22:22:48 +0000969 }
Leonard Chan1a240ed2019-02-20 03:50:11 +0000970
971 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
972 MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
973 }
974
Petr Hosek366cda02019-05-09 06:09:35 +0000975 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
976 MPM.addPass(createModuleToFunctionPassAdaptor(
977 MemorySanitizerPass({0, false, /*Kernel=*/true})));
978 }
979
Leonard Chan1a240ed2019-02-20 03:50:11 +0000980 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
981 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
982 }
Leonard Chan436fb2b2019-02-13 22:22:48 +0000983}
984
Chandler Carruth50f9e892016-12-23 20:44:01 +0000985/// A clean version of `EmitAssembly` that uses the new pass manager.
986///
987/// Not all features are currently supported in this system, but where
988/// necessary it falls back to the legacy pass manager to at least provide
989/// basic functionality.
990///
991/// This API is planned to have its functionality finished and then to replace
992/// `EmitAssembly` at some point in the future when the default switches.
993void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
994 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000995 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000996 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000997
Petr Hosek5f2e10e2019-05-06 23:24:17 +0000998 bool RequiresCodeGen = (Action != Backend_EmitNothing &&
999 Action != Backend_EmitBC &&
1000 Action != Backend_EmitLL);
1001 CreateTargetMachine(RequiresCodeGen);
1002
1003 if (RequiresCodeGen && !TM)
Chandler Carruth50f9e892016-12-23 20:44:01 +00001004 return;
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001005 if (TM)
1006 TheModule->setDataLayout(TM->createDataLayout());
Chandler Carruth50f9e892016-12-23 20:44:01 +00001007
Dehao Chenc76a27e2017-07-27 15:29:53 +00001008 Optional<PGOOptions> PGOOpt;
Davide Italiano945de432017-02-13 16:07:05 +00001009
Dehao Chenc76a27e2017-07-27 15:29:53 +00001010 if (CodeGenOpts.hasProfileIRInstr())
1011 // -fprofile-generate.
1012 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1013 ? DefaultProfileGenName
1014 : CodeGenOpts.InstrProfileOutput,
Rong Xua4a09b22019-03-04 20:21:31 +00001015 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
Richard Smith8654ae52018-10-10 23:13:35 +00001016 CodeGenOpts.DebugInfoForProfiling);
Rong Xua4a09b22019-03-04 20:21:31 +00001017 else if (CodeGenOpts.hasProfileIRUse()) {
Dehao Chenc76a27e2017-07-27 15:29:53 +00001018 // -fprofile-use.
Rong Xua4a09b22019-03-04 20:21:31 +00001019 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1020 : PGOOptions::NoCSAction;
1021 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1022 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1023 CSAction, CodeGenOpts.DebugInfoForProfiling);
1024 } else if (!CodeGenOpts.SampleProfileFile.empty())
Dehao Chenc76a27e2017-07-27 15:29:53 +00001025 // -fprofile-sample-use
Rong Xua4a09b22019-03-04 20:21:31 +00001026 PGOOpt =
1027 PGOOptions(CodeGenOpts.SampleProfileFile, "",
1028 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1029 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
Dehao Chenc76a27e2017-07-27 15:29:53 +00001030 else if (CodeGenOpts.DebugInfoForProfiling)
1031 // -fdebug-info-for-profiling
Rong Xua4a09b22019-03-04 20:21:31 +00001032 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1033 PGOOptions::NoCSAction, true);
1034
1035 // Check to see if we want to generate a CS profile.
1036 if (CodeGenOpts.hasProfileCSIRInstr()) {
1037 assert(!CodeGenOpts.hasProfileCSIRUse() &&
1038 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1039 "the same time");
1040 if (PGOOpt.hasValue()) {
1041 assert(PGOOpt->Action != PGOOptions::IRInstr &&
1042 PGOOpt->Action != PGOOptions::SampleUse &&
1043 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1044 " pass");
1045 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1046 ? DefaultProfileGenName
1047 : CodeGenOpts.InstrProfileOutput;
1048 PGOOpt->CSAction = PGOOptions::CSIRInstr;
1049 } else
1050 PGOOpt = PGOOptions("",
1051 CodeGenOpts.InstrProfileOutput.empty()
1052 ? DefaultProfileGenName
1053 : CodeGenOpts.InstrProfileOutput,
1054 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1055 CodeGenOpts.DebugInfoForProfiling);
1056 }
Davide Italiano945de432017-02-13 16:07:05 +00001057
Alina Sbirlea267ac922019-05-23 18:51:02 +00001058 PipelineTuningOptions PTO;
Alina Sbirlea21efe2a2019-05-24 17:40:52 +00001059 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001060 // For historical reasons, loop interleaving is set to mirror setting for loop
1061 // unrolling.
1062 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1063 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1064 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1065
Taewook Ohd4c50f72019-08-14 07:11:09 +00001066 PassInstrumentationCallbacks PIC;
1067 StandardInstrumentations SI;
1068 SI.registerCallbacks(PIC);
1069 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001070
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001071 // Attempt to load pass plugins and register their callbacks with PB.
1072 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1073 auto PassPlugin = PassPlugin::Load(PluginFN);
1074 if (PassPlugin) {
1075 PassPlugin->registerPassBuilderCallbacks(PB);
1076 } else {
1077 Diags.Report(diag::err_fe_unable_to_load_plugin)
1078 << PluginFN << toString(PassPlugin.takeError());
1079 }
1080 }
1081
Craig Topper926b95c2017-11-14 08:48:28 +00001082 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1083 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1084 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1085 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001086
1087 // Register the AA manager first so that our version is the one used.
1088 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1089
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001090 // Register the target library analysis directly and give it a customized
1091 // preset TLI.
1092 Triple TargetTriple(TheModule->getTargetTriple());
1093 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1094 createTLII(TargetTriple, CodeGenOpts));
1095 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001096
Chandler Carruth50f9e892016-12-23 20:44:01 +00001097 // Register all the basic analyses with the managers.
1098 PB.registerModuleAnalyses(MAM);
1099 PB.registerCGSCCAnalyses(CGAM);
1100 PB.registerFunctionAnalyses(FAM);
1101 PB.registerLoopAnalyses(LAM);
1102 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1103
Tim Shenb13eebe2017-06-29 23:10:13 +00001104 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001105
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001106 if (!CodeGenOpts.DisableLLVMPasses) {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001107 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
Tim Shen66470692017-06-29 23:08:38 +00001108 bool IsLTO = CodeGenOpts.PrepareForLTO;
1109
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001110 if (CodeGenOpts.OptimizationLevel == 0) {
David Blaikieac904d02018-01-23 01:25:24 +00001111 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1112 MPM.addPass(GCOVProfilerPass(*Options));
Rong Xu4059e142019-04-25 17:52:43 +00001113 if (Optional<InstrProfOptions> Options =
1114 getInstrProfOptions(CodeGenOpts, LangOpts))
1115 MPM.addPass(InstrProfiling(*Options, false));
David Blaikieac904d02018-01-23 01:25:24 +00001116
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001117 // Build a minimal pipeline based on the semantics required by Clang,
Leonard Chan587497b2019-06-13 16:45:29 +00001118 // which is just that always inlining occurs. Further, disable generating
1119 // lifetime intrinsics to avoid enabling further optimizations during
1120 // code generation.
1121 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001122
Rong Xuca161fa2019-08-01 22:36:34 +00001123 // At -O0, we can still do PGO. Add all the requested passes for
1124 // instrumentation PGO, if requested.
1125 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1126 PGOOpt->Action == PGOOptions::IRUse))
1127 PB.addPGOInstrPassesForO0(
1128 MPM, CodeGenOpts.DebugPassManager,
1129 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1130 /* IsCS */ false, PGOOpt->ProfileFile,
1131 PGOOpt->ProfileRemappingFile);
1132
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001133 // At -O0 we directly run necessary sanitizer passes.
1134 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1135 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1136
Teresa Johnson6ed79132019-01-04 19:05:01 +00001137 // Lastly, add semantically necessary passes for LTO.
1138 if (IsLTO || IsThinLTO) {
1139 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001140 MPM.addPass(NameAnonGlobalPass());
Teresa Johnson6ed79132019-01-04 19:05:01 +00001141 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001142 } else {
Tim Shen66470692017-06-29 23:08:38 +00001143 // Map our optimization levels into one of the distinct levels used to
1144 // configure the pipeline.
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001145 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1146
Leonard Chanb2065132019-06-20 19:35:25 +00001147 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1148 MPM.addPass(createModuleToFunctionPassAdaptor(
1149 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1150 });
1151
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001152 // Register callbacks to schedule sanitizer passes at the appropriate part of
1153 // the pipeline.
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001154 // FIXME: either handle asan/the remaining sanitizers or error out
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001155 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1156 PB.registerScalarOptimizerLateEPCallback(
1157 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1158 FPM.addPass(BoundsCheckingPass());
1159 });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001160 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
1161 PB.registerOptimizerLastEPCallback(
1162 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001163 FPM.addPass(MemorySanitizerPass({}));
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001164 });
1165 if (LangOpts.Sanitize.has(SanitizerKind::Thread))
1166 PB.registerOptimizerLastEPCallback(
1167 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1168 FPM.addPass(ThreadSanitizerPass());
1169 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001170 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1171 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1172 MPM.addPass(
1173 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1174 });
1175 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
Leonard Chan619b6d52019-02-14 01:07:47 +00001176 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
Leonard Chan436fb2b2019-02-13 22:22:48 +00001177 PB.registerOptimizerLastEPCallback(
Leonard Chan619b6d52019-02-14 01:07:47 +00001178 [Recover, UseAfterScope](FunctionPassManager &FPM,
1179 PassBuilder::OptimizationLevel Level) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001180 FPM.addPass(AddressSanitizerPass(
Leonard Chan619b6d52019-02-14 01:07:47 +00001181 /*CompileKernel=*/false, Recover, UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001182 });
1183 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Leonard Chan619b6d52019-02-14 01:07:47 +00001184 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1185 PB.registerPipelineStartEPCallback(
1186 [Recover, ModuleUseAfterScope,
1187 UseOdrIndicator](ModulePassManager &MPM) {
1188 MPM.addPass(ModuleAddressSanitizerPass(
1189 /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1190 UseOdrIndicator));
1191 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001192 }
David Blaikieac904d02018-01-23 01:25:24 +00001193 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1194 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1195 MPM.addPass(GCOVProfilerPass(*Options));
1196 });
Rong Xu4059e142019-04-25 17:52:43 +00001197 if (Optional<InstrProfOptions> Options =
1198 getInstrProfOptions(CodeGenOpts, LangOpts))
1199 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1200 MPM.addPass(InstrProfiling(*Options, false));
1201 });
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001202
Tim Shen66470692017-06-29 23:08:38 +00001203 if (IsThinLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001204 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1205 Level, CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001206 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001207 MPM.addPass(NameAnonGlobalPass());
1208 } else if (IsLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001209 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1210 CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001211 MPM.addPass(CanonicalizeAliasesPass());
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001212 MPM.addPass(NameAnonGlobalPass());
Tim Shen66470692017-06-29 23:08:38 +00001213 } else {
Tim Shenb13eebe2017-06-29 23:10:13 +00001214 MPM = PB.buildPerModuleDefaultPipeline(Level,
1215 CodeGenOpts.DebugPassManager);
Tim Shen66470692017-06-29 23:08:38 +00001216 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001217 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001218
Leonard Chan486b1732019-09-08 07:30:17 +00001219 if (CodeGenOpts.SanitizeCoverageType ||
1220 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1221 CodeGenOpts.SanitizeCoverageTraceCmp) {
1222 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1223 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1224 }
1225
Peter Collingbourne3b82b922019-07-17 21:45:19 +00001226 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1227 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1228 MPM.addPass(HWAddressSanitizerPass(
1229 /*CompileKernel=*/false, Recover));
1230 }
1231 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1232 MPM.addPass(HWAddressSanitizerPass(
1233 /*CompileKernel=*/true, /*Recover=*/true));
1234 }
1235
Leonard Chan007f6742019-07-25 20:53:15 +00001236 if (CodeGenOpts.OptimizationLevel == 0) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001237 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
Leonard Chan007f6742019-07-25 20:53:15 +00001238 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001239 }
1240
1241 // FIXME: We still use the legacy pass manager to do code generation. We
1242 // create that pass manager here and use it as needed below.
1243 legacy::PassManager CodeGenPasses;
1244 bool NeedCodeGen = false;
Peter Collingbourne91d02842018-05-22 18:52:37 +00001245 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Chandler Carruth50f9e892016-12-23 20:44:01 +00001246
1247 // Append any output we need to the pass manager.
1248 switch (Action) {
1249 case Backend_EmitNothing:
1250 break;
1251
1252 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +00001253 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Tim Shen50fedec2017-06-01 23:27:51 +00001254 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00001255 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1256 if (!ThinLinkOS)
Tim Shen50fedec2017-06-01 23:27:51 +00001257 return;
Tim Shen50fedec2017-06-01 23:27:51 +00001258 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001259 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1260 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001261 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1262 : nullptr));
Tim Shen50fedec2017-06-01 23:27:51 +00001263 } else {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001264 // Emit a module summary by default for Regular LTO except for ld64
1265 // targets
1266 bool EmitLTOSummary =
1267 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +00001268 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001269 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1270 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001271 if (EmitLTOSummary) {
1272 if (!TheModule->getModuleFlag("ThinLTO"))
1273 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1274 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Leonard Chan19ec31d2019-08-21 17:24:14 +00001275 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001276 }
1277 MPM.addPass(
1278 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tim Shen50fedec2017-06-01 23:27:51 +00001279 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001280 break;
1281
1282 case Backend_EmitLL:
1283 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1284 break;
1285
1286 case Backend_EmitAssembly:
1287 case Backend_EmitMCNull:
1288 case Backend_EmitObj:
1289 NeedCodeGen = true;
1290 CodeGenPasses.add(
1291 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Aaron Puchertb207bae2019-06-26 21:36:35 +00001292 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00001293 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001294 if (!DwoOS)
1295 return;
1296 }
1297 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1298 DwoOS ? &DwoOS->os() : nullptr))
Chandler Carruth50f9e892016-12-23 20:44:01 +00001299 // FIXME: Should we handle this error differently?
1300 return;
1301 break;
1302 }
1303
1304 // Before executing passes, print the final values of the LLVM options.
1305 cl::PrintOptionValues();
1306
1307 // Now that we have all of the passes ready, run them.
1308 {
1309 PrettyStackTraceString CrashInfo("Optimizer");
1310 MPM.run(*TheModule, MAM);
1311 }
1312
1313 // Now if needed, run the legacy PM for codegen.
1314 if (NeedCodeGen) {
1315 PrettyStackTraceString CrashInfo("Code generation");
1316 CodeGenPasses.run(*TheModule);
1317 }
Peter Collingbourne91d02842018-05-22 18:52:37 +00001318
1319 if (ThinLinkOS)
1320 ThinLinkOS->keep();
1321 if (DwoOS)
1322 DwoOS->keep();
Chandler Carruth50f9e892016-12-23 20:44:01 +00001323}
1324
Peter Collingbourne47d23642017-01-24 19:54:37 +00001325Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1326 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1327 if (!BMsOrErr)
1328 return BMsOrErr.takeError();
1329
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00001330 // The bitcode file may contain multiple modules, we want the one that is
1331 // marked as being the ThinLTO module.
Vitaly Bukac35ff822018-02-16 23:34:16 +00001332 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1333 return *Bm;
Peter Collingbourne47d23642017-01-24 19:54:37 +00001334
1335 return make_error<StringError>("Could not find module summary",
1336 inconvertibleErrorCode());
1337}
1338
Vitaly Bukac35ff822018-02-16 23:34:16 +00001339BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1340 for (BitcodeModule &BM : BMs) {
1341 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1342 if (LTOInfo && LTOInfo->IsThinLTO)
1343 return &BM;
1344 }
1345 return nullptr;
1346}
1347
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001348static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001349 const HeaderSearchOptions &HeaderOpts,
1350 const CodeGenOptions &CGOpts,
1351 const clang::TargetOptions &TOpts,
1352 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +00001353 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001354 std::string SampleProfile,
Richard Smith8654ae52018-10-10 23:13:35 +00001355 std::string ProfileRemapping,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001356 BackendAction Action) {
Dehao Chen5f83d0e2017-07-10 20:31:37 +00001357 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001358 ModuleToDefinedGVSummaries;
1359 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1360
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001361 setCommandLineOpts(CGOpts);
1362
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001363 // We can simply import the values mentioned in the combined index, since
1364 // we should only invoke this using the individual indexes written out
1365 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001366 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001367 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001368 // Ignore entries for undefined references.
1369 if (GlobalList.second.SummaryList.empty())
1370 continue;
1371
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001372 auto GUID = GlobalList.first;
Teresa Johnson5ed8b002018-11-29 17:02:59 +00001373 for (auto &Summary : GlobalList.second.SummaryList) {
1374 // Skip the summaries for the importing module. These are included to
1375 // e.g. record required linkage changes.
1376 if (Summary->modulePath() == M->getModuleIdentifier())
1377 continue;
1378 // Add an entry to provoke importing by thinBackend.
1379 ImportList[Summary->modulePath()].insert(GUID);
1380 }
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001381 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001382
1383 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001384 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001385
1386 for (auto &I : ImportList) {
1387 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1388 llvm::MemoryBuffer::getFile(I.first());
1389 if (!MBOrErr) {
1390 errs() << "Error loading imported file '" << I.first()
1391 << "': " << MBOrErr.getError().message() << "\n";
1392 return;
1393 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001394
Peter Collingbourne47d23642017-01-24 19:54:37 +00001395 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1396 if (!BMOrErr) {
1397 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001398 errs() << "Error loading imported file '" << I.first()
1399 << "': " << EIB.message() << '\n';
1400 });
1401 return;
1402 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001403 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001404
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001405 OwnedImports.push_back(std::move(*MBOrErr));
1406 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001407 auto AddStream = [&](size_t Task) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001408 return std::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001409 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001410 lto::Config Conf;
Teresa Johnson9e4321c2018-04-17 16:39:25 +00001411 if (CGOpts.SaveTempsFilePrefix != "") {
1412 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1413 /* UseInputModulePath */ false)) {
1414 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1415 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1416 << '\n';
1417 });
1418 }
1419 }
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001420 Conf.CPU = TOpts.CPU;
1421 Conf.CodeModel = getCodeModel(CGOpts);
1422 Conf.MAttrs = TOpts.Features;
Rafael Espindolae1d70532018-01-18 00:20:03 +00001423 Conf.RelocModel = CGOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001424 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson867bc392019-04-23 18:56:19 +00001425 Conf.OptLevel = CGOpts.OptimizationLevel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001426 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001427 Conf.SampleProfile = std::move(SampleProfile);
Rong Xua4a09b22019-03-04 20:21:31 +00001428
1429 // Context sensitive profile.
1430 if (CGOpts.hasProfileCSIRInstr()) {
1431 Conf.RunCSIRInstr = true;
1432 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1433 } else if (CGOpts.hasProfileCSIRUse()) {
1434 Conf.RunCSIRInstr = false;
1435 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1436 }
1437
Richard Smith8654ae52018-10-10 23:13:35 +00001438 Conf.ProfileRemapping = std::move(ProfileRemapping);
Tim Shen50fedec2017-06-01 23:27:51 +00001439 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
Teresa Johnson4cd016ab2017-11-13 15:38:33 +00001440 Conf.DebugPassManager = CGOpts.DebugPassManager;
Teresa Johnson66744f82018-05-05 14:37:29 +00001441 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1442 Conf.RemarksFilename = CGOpts.OptRecordFile;
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001443 Conf.RemarksPasses = CGOpts.OptRecordPasses;
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00001444 Conf.RemarksFormat = CGOpts.OptRecordFormat;
Aaron Pucherte1dc4952019-06-15 15:38:51 +00001445 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1446 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001447 switch (Action) {
1448 case Backend_EmitNothing:
1449 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1450 return false;
1451 };
1452 break;
1453 case Backend_EmitLL:
1454 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1455 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1456 return false;
1457 };
1458 break;
1459 case Backend_EmitBC:
1460 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
Rafael Espindola76c8f822018-02-14 19:11:37 +00001461 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001462 return false;
1463 };
1464 break;
1465 default:
1466 Conf.CGFileType = getCodeGenFileType(Action);
1467 break;
1468 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001469 if (Error E = thinBackend(
Teresa Johnson66744f82018-05-05 14:37:29 +00001470 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001471 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1472 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1473 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1474 });
1475 }
1476}
1477
David Blaikie9c902b52011-09-25 23:23:43 +00001478void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001479 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001480 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001481 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001482 const LangOptions &LOpts,
1483 const llvm::DataLayout &TDesc, Module *M,
1484 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001485 std::unique_ptr<raw_pwrite_stream> OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +00001486
1487 llvm::TimeTraceScope TimeScope("Backend", StringRef(""));
1488
Vitaly Buka769134d2018-02-16 23:38:22 +00001489 std::unique_ptr<llvm::Module> EmptyModule;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001490 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001491 // If we are performing a ThinLTO importing compile, load the function index
1492 // into memory and pass it into runThinLTOBackend, which will run the
1493 // function importer and invoke LTO passes.
1494 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
Teresa Johnson517729f2017-05-12 19:32:17 +00001495 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1496 /*IgnoreEmptyThinLTOIndexFile*/true);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001497 if (!IndexOrErr) {
1498 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1499 "Error loading index file '" +
1500 CGOpts.ThinLTOIndexFile + "': ");
1501 return;
1502 }
1503 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1504 // A null CombinedIndex means we should skip ThinLTO compilation
1505 // (LLVM will optionally ignore empty index files, returning null instead
1506 // of an error).
Vitaly Buka769134d2018-02-16 23:38:22 +00001507 if (CombinedIndex) {
1508 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1509 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1510 LOpts, std::move(OS), CGOpts.SampleProfileFile,
Richard Smith8654ae52018-10-10 23:13:35 +00001511 CGOpts.ProfileRemappingFile, Action);
Vitaly Buka769134d2018-02-16 23:38:22 +00001512 return;
1513 }
1514 // Distributed indexing detected that nothing from the module is needed
1515 // for the final linking. So we can skip the compilation. We sill need to
1516 // output an empty object file to make sure that a linker does not fail
1517 // trying to read it. Also for some features, like CFI, we must skip
1518 // the compilation as CombinedIndex does not contain all required
1519 // information.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001520 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
Vitaly Buka769134d2018-02-16 23:38:22 +00001521 EmptyModule->setTargetTriple(M->getTargetTriple());
1522 M = EmptyModule.get();
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001523 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001524 }
1525
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001526 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001527
Chandler Carruth50f9e892016-12-23 20:44:01 +00001528 if (CGOpts.ExperimentalNewPassManager)
1529 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1530 else
1531 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001532
James Y Knightb214cbc2016-03-04 19:00:41 +00001533 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1534 // DataLayout.
1535 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001536 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001537 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001538 unsigned DiagID = Diags.getCustomDiagID(
1539 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1540 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001541 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001542 }
1543 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001544}
Steven Wu27fb5222016-05-11 16:26:03 +00001545
1546static const char* getSectionNameForBitcode(const Triple &T) {
1547 switch (T.getObjectFormat()) {
1548 case Triple::MachO:
1549 return "__LLVM,__bitcode";
1550 case Triple::COFF:
1551 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001552 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001553 case Triple::UnknownObjectFormat:
1554 return ".llvmbc";
Jason Liua03ae732019-03-12 22:01:10 +00001555 case Triple::XCOFF:
1556 llvm_unreachable("XCOFF is not yet implemented");
1557 break;
Steven Wu27fb5222016-05-11 16:26:03 +00001558 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001559 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001560}
1561
1562static const char* getSectionNameForCommandline(const Triple &T) {
1563 switch (T.getObjectFormat()) {
1564 case Triple::MachO:
1565 return "__LLVM,__cmdline";
1566 case Triple::COFF:
1567 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001568 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001569 case Triple::UnknownObjectFormat:
1570 return ".llvmcmd";
Jason Liua03ae732019-03-12 22:01:10 +00001571 case Triple::XCOFF:
1572 llvm_unreachable("XCOFF is not yet implemented");
1573 break;
Steven Wu27fb5222016-05-11 16:26:03 +00001574 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001575 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001576}
1577
1578// With -fembed-bitcode, save a copy of the llvm IR as data in the
1579// __LLVM,__bitcode section.
1580void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1581 llvm::MemoryBufferRef Buf) {
1582 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1583 return;
1584
Steven Wu2c059a52016-05-16 18:54:58 +00001585 // Save llvm.compiler.used and remote it.
1586 SmallVector<Constant*, 2> UsedArray;
Craig Topper7c89d042018-06-09 00:30:45 +00001587 SmallPtrSet<GlobalValue*, 4> UsedGlobals;
Steven Wu2c059a52016-05-16 18:54:58 +00001588 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1589 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1590 for (auto *GV : UsedGlobals) {
1591 if (GV->getName() != "llvm.embedded.module" &&
1592 GV->getName() != "llvm.cmdline")
1593 UsedArray.push_back(
1594 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1595 }
1596 if (Used)
1597 Used->eraseFromParent();
1598
Steven Wu27fb5222016-05-11 16:26:03 +00001599 // Embed the bitcode for the llvm module.
1600 std::string Data;
1601 ArrayRef<uint8_t> ModuleData;
1602 Triple T(M->getTargetTriple());
1603 // Create a constant that contains the bitcode.
1604 // In case of embedding a marker, ignore the input Buf and use the empty
1605 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1606 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1607 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1608 (const unsigned char *)Buf.getBufferEnd())) {
1609 // If the input is LLVM Assembly, bitcode is produced by serializing
1610 // the module. Use-lists order need to be perserved in this case.
1611 llvm::raw_string_ostream OS(Data);
Rafael Espindola76c8f822018-02-14 19:11:37 +00001612 llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
Steven Wu27fb5222016-05-11 16:26:03 +00001613 ModuleData =
1614 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1615 } else
1616 // If the input is LLVM bitcode, write the input byte stream directly.
1617 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1618 Buf.getBufferSize());
1619 }
1620 llvm::Constant *ModuleConstant =
1621 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
Steven Wu27fb5222016-05-11 16:26:03 +00001622 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
Steven Wu2c059a52016-05-16 18:54:58 +00001623 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
Steven Wu27fb5222016-05-11 16:26:03 +00001624 ModuleConstant);
1625 GV->setSection(getSectionNameForBitcode(T));
Steven Wu2c059a52016-05-16 18:54:58 +00001626 UsedArray.push_back(
1627 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
Steven Wu27fb5222016-05-11 16:26:03 +00001628 if (llvm::GlobalVariable *Old =
Steven Wu2c059a52016-05-16 18:54:58 +00001629 M->getGlobalVariable("llvm.embedded.module", true)) {
1630 assert(Old->hasOneUse() &&
1631 "llvm.embedded.module can only be used once in llvm.compiler.used");
Steven Wu27fb5222016-05-11 16:26:03 +00001632 GV->takeName(Old);
1633 Old->eraseFromParent();
1634 } else {
1635 GV->setName("llvm.embedded.module");
1636 }
1637
Steven Wu2c059a52016-05-16 18:54:58 +00001638 // Skip if only bitcode needs to be embedded.
1639 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1640 // Embed command-line options.
Saleem Abdulrasoolb1d50c12016-05-20 03:58:12 +00001641 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
Steven Wu2c059a52016-05-16 18:54:58 +00001642 CGOpts.CmdArgs.size());
1643 llvm::Constant *CmdConstant =
1644 llvm::ConstantDataArray::get(M->getContext(), CmdData);
1645 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1646 llvm::GlobalValue::PrivateLinkage,
1647 CmdConstant);
1648 GV->setSection(getSectionNameForCommandline(T));
1649 UsedArray.push_back(
1650 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1651 if (llvm::GlobalVariable *Old =
1652 M->getGlobalVariable("llvm.cmdline", true)) {
1653 assert(Old->hasOneUse() &&
1654 "llvm.cmdline can only be used once in llvm.compiler.used");
1655 GV->takeName(Old);
1656 Old->eraseFromParent();
1657 } else {
1658 GV->setName("llvm.cmdline");
1659 }
1660 }
1661
1662 if (UsedArray.empty())
Steven Wu27fb5222016-05-11 16:26:03 +00001663 return;
1664
Steven Wu2c059a52016-05-16 18:54:58 +00001665 // Recreate llvm.compiler.used.
1666 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1667 auto *NewUsed = new GlobalVariable(
1668 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1669 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1670 NewUsed->setSection("llvm.metadata");
Steven Wu27fb5222016-05-11 16:26:03 +00001671}