blob: 51c21c9f25d540e73670c17e894c13082e7b6df2 [file] [log] [blame]
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbarc1b17292010-06-15 17:48:49 +000010#include "clang/CodeGen/BackendUtil.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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000014#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Kostya Serebryanyce2c7262013-12-27 08:11:08 +000016#include "clang/Frontend/Utils.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000017#include "clang/Lex/HeaderSearchOptions.h"
Hal Finkel1a328f52016-12-15 02:19:17 +000018#include "llvm/ADT/SmallSet.h"
Eric Christopher583a1f72015-09-26 01:25:08 +000019#include "llvm/ADT/StringExtras.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000020#include "llvm/ADT/StringSwitch.h"
Steven Wu27fb5222016-05-11 16:26:03 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth418bd1a2015-01-15 02:16:55 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthaab5ec02015-01-31 11:18:46 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000025#include "llvm/Bitcode/BitcodeWriter.h"
26#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000027#include "llvm/CodeGen/RegAllocRegistry.h"
28#include "llvm/CodeGen/SchedulerRegistry.h"
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"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000039#include "llvm/Support/CommandLine.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000040#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000041#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000042#include "llvm/Support/TargetRegistry.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000043#include "llvm/Support/Timer.h"
44#include "llvm/Support/raw_ostream.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000045#include "llvm/Target/TargetMachine.h"
46#include "llvm/Target/TargetOptions.h"
Eric Christopher3de08532014-08-04 21:33:42 +000047#include "llvm/Target/TargetSubtargetInfo.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000048#include "llvm/Transforms/Coroutines.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000049#include "llvm/Transforms/IPO.h"
Chandler Carruthb72c19f2016-08-17 03:09:11 +000050#include "llvm/Transforms/IPO/AlwaysInliner.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000051#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include "llvm/Transforms/Instrumentation.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000053#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000054#include "llvm/Transforms/Scalar.h"
Chandler Carruth4ddaadc2016-03-11 09:02:43 +000055#include "llvm/Transforms/Scalar/GVN.h"
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +000056#include "llvm/Transforms/Utils/SymbolRewriter.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000057#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000058using namespace clang;
59using namespace llvm;
60
61namespace {
62
Davide Italiano945de432017-02-13 16:07:05 +000063// Default filename used for profile generation.
64static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
65
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000066class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000067 DiagnosticsEngine &Diags;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000068 const HeaderSearchOptions &HSOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000069 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000070 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000071 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000072 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000073
74 Timer CodeGenerationTime;
75
Peter Collingbourne03f89072016-07-15 00:55:40 +000076 std::unique_ptr<raw_pwrite_stream> OS;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000077
Chandler Carruthd294bdb2015-02-01 12:26:23 +000078 TargetIRAnalysis getTargetIRAnalysis() const {
Chandler Carruthaab5ec02015-01-31 11:18:46 +000079 if (TM)
Chandler Carruthd294bdb2015-02-01 12:26:23 +000080 return TM->getTargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +000081
Chandler Carruthd294bdb2015-02-01 12:26:23 +000082 return TargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +000083 }
84
Teresa Johnson9e3f4742016-08-12 18:12:08 +000085 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
Nadav Rotemec57ab32012-10-24 00:53:38 +000086
Rafael Espindola2f16bc12015-04-14 15:15:49 +000087 /// Generates the TargetMachine.
Peter Collingbourne03f89072016-07-15 00:55:40 +000088 /// Leaves TM unchanged if it is unable to create the target machine.
Nadav Rotemdc06b2d2012-10-24 03:52:31 +000089 /// Some of our clang tests specify triples which are not built
90 /// into clang. This is okay because these tests check the generated
91 /// IR, and they require DataLayout which depends on the triple.
92 /// In this case, we allow this method to fail and not report an error.
93 /// When MustCreateTM is used, we print an error if we are unable to load
94 /// the requested target.
Peter Collingbourne03f89072016-07-15 00:55:40 +000095 void CreateTargetMachine(bool MustCreateTM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000096
Rafael Espindola2f16bc12015-04-14 15:15:49 +000097 /// Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000098 ///
99 /// \return True on success.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000100 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
101 raw_pwrite_stream &OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000102
103public:
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000104 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
105 const HeaderSearchOptions &HeaderSearchOpts,
106 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000107 const clang::TargetOptions &TOpts,
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000108 const LangOptions &LOpts, Module *M)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000109 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
110 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
111 CodeGenerationTime("codegen", "Code Generation Time") {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000112
113 ~EmitAssemblyHelper() {
Alp Tokerf4e22382013-12-20 20:26:53 +0000114 if (CodeGenOpts.DisableFree)
David Blaikiea97eaa12014-08-29 16:53:14 +0000115 BuryPointer(std::move(TM));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000116 }
117
Ahmed Charlesb8984322014-03-07 20:03:18 +0000118 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000119
Peter Collingbourne03f89072016-07-15 00:55:40 +0000120 void EmitAssembly(BackendAction Action,
121 std::unique_ptr<raw_pwrite_stream> OS);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000122
123 void EmitAssemblyWithNewPassManager(BackendAction Action,
124 std::unique_ptr<raw_pwrite_stream> OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000125};
126
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000127// We need this wrapper to access LangOpts and CGOpts from extension functions
128// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000129class PassManagerBuilderWrapper : public PassManagerBuilder {
130public:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000131 PassManagerBuilderWrapper(const Triple &TargetTriple,
132 const CodeGenOptions &CGOpts,
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000133 const LangOptions &LangOpts)
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000134 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
135 LangOpts(LangOpts) {}
136 const Triple &getTargetTriple() const { return TargetTriple; }
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000137 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000138 const LangOptions &getLangOpts() const { return LangOpts; }
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000139
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000140private:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000141 const Triple &TargetTriple;
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000142 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000143 const LangOptions &LangOpts;
144};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000145}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000146
Dan Gohman5932ce22012-01-17 20:54:51 +0000147static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148 if (Builder.OptLevel > 0)
149 PM.add(createObjCARCAPElimPass());
150}
151
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000152static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153 if (Builder.OptLevel > 0)
154 PM.add(createObjCARCExpandPass());
155}
156
157static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
158 if (Builder.OptLevel > 0)
159 PM.add(createObjCARCOptPass());
160}
161
Diego Novillob56be642014-03-03 20:06:18 +0000162static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000163 legacy::PassManagerBase &PM) {
Diego Novillob56be642014-03-03 20:06:18 +0000164 PM.add(createAddDiscriminatorsPass());
165}
166
Nuno Lopesa4255892012-05-22 17:19:45 +0000167static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000168 legacy::PassManagerBase &PM) {
Joey Goulyebc59d52012-11-23 10:39:49 +0000169 PM.add(createBoundsCheckingPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000170}
171
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000172static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000173 legacy::PassManagerBase &PM) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000174 const PassManagerBuilderWrapper &BuilderWrapper =
175 static_cast<const PassManagerBuilderWrapper&>(Builder);
176 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000177 SanitizerCoverageOptions Opts;
178 Opts.CoverageType =
179 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
180 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
181 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
182 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
Kostya Serebryany3b419712016-08-30 01:27:03 +0000183 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
184 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000185 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000186 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000187 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000188 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000189 PM.add(createSanitizerCoverageModulePass(Opts));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000190}
191
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000192// Check if ASan should use GC-friendly instrumentation for globals.
193// First of all, there is no point if -fdata-sections is off (expect for MachO,
194// where this is not a factor). Also, on ELF this feature requires an assembler
195// extension that only works with -integrated-as at the moment.
196static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000197 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
198 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000199 switch (T.getObjectFormat()) {
200 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000201 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000202 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000203 case Triple::ELF:
204 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
205 default:
206 return false;
207 }
208}
209
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000210static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000211 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000212 const PassManagerBuilderWrapper &BuilderWrapper =
213 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000214 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000215 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
216 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000217 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000218 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000219 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
220 UseAfterScope));
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000221 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
222 UseGlobalsGC));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000223}
224
225static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
226 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000227 PM.add(createAddressSanitizerFunctionPass(
228 /*CompileKernel*/ true,
229 /*Recover*/ true, /*UseAfterScope*/ false));
Yury Gribov5bfeca12015-11-11 10:45:48 +0000230 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
231 /*Recover*/true));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000232}
233
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000234static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000235 legacy::PassManagerBase &PM) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000236 const PassManagerBuilderWrapper &BuilderWrapper =
237 static_cast<const PassManagerBuilderWrapper&>(Builder);
238 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000239 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
240 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
241 PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000242
243 // MemorySanitizer inserts complex instrumentation that mostly follows
244 // the logic of the original code, but operates on "shadow" values.
245 // It can benefit from re-running some general purpose optimization passes.
246 if (Builder.OptLevel > 0) {
247 PM.add(createEarlyCSEPass());
248 PM.add(createReassociatePass());
249 PM.add(createLICMPass());
250 PM.add(createGVNPass());
251 PM.add(createInstructionCombiningPass());
252 PM.add(createDeadStoreEliminationPass());
253 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000254}
255
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000256static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000257 legacy::PassManagerBase &PM) {
Alexey Samsonov1cf07ea2014-06-02 18:08:08 +0000258 PM.add(createThreadSanitizerPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000259}
260
Peter Collingbournec3772752013-08-07 22:47:34 +0000261static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000262 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000263 const PassManagerBuilderWrapper &BuilderWrapper =
264 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000265 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000266 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000267}
268
Derek Bruening256c2e12016-04-21 21:32:04 +0000269static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
270 legacy::PassManagerBase &PM) {
271 const PassManagerBuilderWrapper &BuilderWrapper =
272 static_cast<const PassManagerBuilderWrapper&>(Builder);
273 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
274 EfficiencySanitizerOptions Opts;
275 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
276 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
Derek Bruening293772e2016-05-25 00:41:24 +0000277 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
278 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
Derek Bruening256c2e12016-04-21 21:32:04 +0000279 PM.add(createEfficiencySanitizerPass(Opts));
280}
281
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000282static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
283 const CodeGenOptions &CodeGenOpts) {
284 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000285 if (!CodeGenOpts.SimplifyLibCalls)
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000286 TLII->disableAllFunctions();
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000287 else {
288 // Disable individual libc/libm calls in TargetLibraryInfo.
David L. Jones7a7dd032017-01-23 23:16:58 +0000289 LibFunc F;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000290 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
291 if (TLII->getLibFunc(FuncName, F))
292 TLII->setUnavailable(F);
293 }
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000294
295 switch (CodeGenOpts.getVecLib()) {
296 case CodeGenOptions::Accelerate:
297 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
298 break;
Matt Masten6731dea2016-07-29 16:44:24 +0000299 case CodeGenOptions::SVML:
300 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
301 break;
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000302 default:
303 break;
304 }
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000305 return TLII;
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000306}
307
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000308static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000309 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000310 llvm::SymbolRewriter::RewriteDescriptorList DL;
311
312 llvm::SymbolRewriter::RewriteMapParser MapParser;
313 for (const auto &MapFile : Opts.RewriteMapFiles)
314 MapParser.parse(MapFile, &DL);
315
316 MPM->add(createRewriteSymbolsPass(DL));
317}
318
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000319static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
320 switch (CodeGenOpts.OptimizationLevel) {
321 default:
322 llvm_unreachable("Invalid optimization level!");
323 case 0:
324 return CodeGenOpt::None;
325 case 1:
326 return CodeGenOpt::Less;
327 case 2:
328 return CodeGenOpt::Default; // O2/Os/Oz
329 case 3:
330 return CodeGenOpt::Aggressive;
331 }
332}
333
334static llvm::CodeModel::Model getCodeModel(const CodeGenOptions &CodeGenOpts) {
335 unsigned CodeModel =
336 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
337 .Case("small", llvm::CodeModel::Small)
338 .Case("kernel", llvm::CodeModel::Kernel)
339 .Case("medium", llvm::CodeModel::Medium)
340 .Case("large", llvm::CodeModel::Large)
341 .Case("default", llvm::CodeModel::Default)
342 .Default(~0u);
343 assert(CodeModel != ~0u && "invalid code model!");
344 return static_cast<llvm::CodeModel::Model>(CodeModel);
345}
346
347static llvm::Reloc::Model getRelocModel(const CodeGenOptions &CodeGenOpts) {
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000348 // Keep this synced with the equivalent code in
349 // lib/Frontend/CompilerInvocation.cpp
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000350 llvm::Optional<llvm::Reloc::Model> RM;
351 RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
352 .Case("static", llvm::Reloc::Static)
353 .Case("pic", llvm::Reloc::PIC_)
354 .Case("ropi", llvm::Reloc::ROPI)
355 .Case("rwpi", llvm::Reloc::RWPI)
356 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
357 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
358 assert(RM.hasValue() && "invalid PIC model!");
359 return *RM;
360}
361
362static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
363 if (Action == Backend_EmitObj)
364 return TargetMachine::CGFT_ObjectFile;
365 else if (Action == Backend_EmitMCNull)
366 return TargetMachine::CGFT_Null;
367 else {
368 assert(Action == Backend_EmitAssembly && "Invalid action!");
369 return TargetMachine::CGFT_AssemblyFile;
370 }
371}
372
373static void initTargetOptions(llvm::TargetOptions &Options,
374 const CodeGenOptions &CodeGenOpts,
375 const clang::TargetOptions &TargetOpts,
376 const LangOptions &LangOpts,
377 const HeaderSearchOptions &HSOpts) {
378 Options.ThreadModel =
379 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
380 .Case("posix", llvm::ThreadModel::POSIX)
381 .Case("single", llvm::ThreadModel::Single);
382
383 // Set float ABI type.
384 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
385 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
386 "Invalid Floating Point ABI!");
387 Options.FloatABIType =
388 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
389 .Case("soft", llvm::FloatABI::Soft)
390 .Case("softfp", llvm::FloatABI::Soft)
391 .Case("hard", llvm::FloatABI::Hard)
392 .Default(llvm::FloatABI::Default);
393
394 // Set FP fusion mode.
395 switch (LangOpts.getDefaultFPContractMode()) {
396 case LangOptions::FPC_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000397 // Preserve any contraction performed by the front-end. (Strict performs
398 // splitting of the muladd instrinsic in the backend.)
399 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000400 break;
401 case LangOptions::FPC_On:
402 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
403 break;
404 case LangOptions::FPC_Fast:
405 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
406 break;
407 }
408
409 Options.UseInitArray = CodeGenOpts.UseInitArray;
410 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
411 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
412 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
413
414 // Set EABI version.
415 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
416 .Case("4", llvm::EABI::EABI4)
417 .Case("5", llvm::EABI::EABI5)
418 .Case("gnu", llvm::EABI::GNU)
419 .Default(llvm::EABI::Default);
420
421 if (LangOpts.SjLjExceptions)
422 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
423
424 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
425 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
426 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
427 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
428 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
429 Options.FunctionSections = CodeGenOpts.FunctionSections;
430 Options.DataSections = CodeGenOpts.DataSections;
431 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
432 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
433 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
434
David Blaikie81503552017-04-21 23:35:36 +0000435 if (CodeGenOpts.EnableSplitDwarf)
436 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000437 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
438 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
439 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
440 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
441 Options.MCOptions.MCIncrementalLinkerCompatible =
442 CodeGenOpts.IncrementalLinkerCompatible;
443 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
444 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
445 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
446 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
447 Options.MCOptions.ABIName = TargetOpts.ABI;
448 for (const auto &Entry : HSOpts.UserEntries)
449 if (!Entry.IsFramework &&
450 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
451 Entry.Group == frontend::IncludeDirGroup::Angled ||
452 Entry.Group == frontend::IncludeDirGroup::System))
453 Options.MCOptions.IASSearchPaths.push_back(
454 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
455}
456
Peter Collingbourne03f89072016-07-15 00:55:40 +0000457void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000458 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000459 // Handle disabling of all LLVM passes, where we want to preserve the
460 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000461 if (CodeGenOpts.DisableLLVMPasses)
462 return;
463
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000464 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
465 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
466 // are inserted before PMBuilder ones - they'd get the default-constructed
467 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000468 Triple TargetTriple(TheModule->getTargetTriple());
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000469 std::unique_ptr<TargetLibraryInfoImpl> TLII(
470 createTLII(TargetTriple, CodeGenOpts));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000471
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000472 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
473
Chandler Carruthfcd33142016-12-23 01:24:49 +0000474 // At O0 and O1 we only run the always inliner which is more efficient. At
475 // higher optimization levels we run the normal inliner.
476 if (CodeGenOpts.OptimizationLevel <= 1) {
Mehdi Amini7f873072017-01-06 23:18:09 +0000477 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
478 !CodeGenOpts.DisableLifetimeMarkers);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000479 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
480 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000481 // We do not want to inline hot callsites for SamplePGO module-summary build
482 // because profile annotation will happen again in ThinLTO backend, and we
483 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000484 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000485 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
486 (!CodeGenOpts.SampleProfileFile.empty() &&
487 CodeGenOpts.EmitSummaryIndex));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000488 }
489
Chandler Carruthfcd33142016-12-23 01:24:49 +0000490 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000491 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000492 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
493 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
494 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000495
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000496 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000497 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Teresa Johnsona0d29402016-03-15 00:04:44 +0000498 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000499 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000500 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000501
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000502 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
503
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000504 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000505 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000506
Dehao Chen7810d4f2017-02-21 20:36:21 +0000507 if (CodeGenOpts.DebugInfoForProfiling ||
508 !CodeGenOpts.SampleProfileFile.empty())
509 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
510 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000511
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000512 // In ObjC ARC mode, add the main ARC optimization passes.
513 if (LangOpts.ObjCAutoRefCount) {
514 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
515 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000516 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
517 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000518 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
519 addObjCARCOptPass);
520 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000521
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000522 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000523 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
524 addBoundsCheckingPass);
525 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
526 addBoundsCheckingPass);
527 }
528
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000529 if (CodeGenOpts.SanitizeCoverageType ||
530 CodeGenOpts.SanitizeCoverageIndirectCalls ||
531 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000532 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
533 addSanitizerCoveragePass);
534 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
535 addSanitizerCoveragePass);
536 }
537
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000538 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000539 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000540 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000541 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000542 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000543 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000544
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000545 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
546 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
547 addKernelAddressSanitizerPasses);
548 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
549 addKernelAddressSanitizerPasses);
550 }
551
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000552 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000553 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
554 addMemorySanitizerPass);
555 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
556 addMemorySanitizerPass);
557 }
558
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000559 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000560 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000561 addThreadSanitizerPass);
562 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
563 addThreadSanitizerPass);
564 }
565
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000566 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000567 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
568 addDataFlowSanitizerPass);
569 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
570 addDataFlowSanitizerPass);
571 }
572
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000573 if (LangOpts.CoroutinesTS)
574 addCoroutinePassesToExtensionPoints(PMBuilder);
575
Derek Bruening256c2e12016-04-21 21:32:04 +0000576 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
577 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
578 addEfficiencySanitizerPass);
579 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
580 addEfficiencySanitizerPass);
581 }
582
Chris Lattner5c123672011-05-21 20:40:11 +0000583 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000584 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000585 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000586 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000587
Chris Lattner5c123672011-05-21 20:40:11 +0000588 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000589 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000590 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000591
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000592 if (!CodeGenOpts.DisableGCov &&
593 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000594 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
595 // LLVM's -default-gcov-version flag is set to something invalid.
596 GCOVOptions Options;
597 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
598 Options.EmitData = CodeGenOpts.EmitGcovArcs;
599 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
600 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
601 Options.NoRedZone = CodeGenOpts.DisableRedZone;
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000602 Options.FunctionNamesInData =
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000603 !CodeGenOpts.CoverageNoFunctionNamesInData;
Justin Bogner4e462372015-03-16 23:52:21 +0000604 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000605 MPM.add(createGCOVProfilerPass(Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000606 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000607 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000608 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000609
Rong Xu9837ef52016-02-04 18:39:09 +0000610 if (CodeGenOpts.hasProfileClangInstr()) {
Justin Bogner970ac602014-12-08 19:04:51 +0000611 InstrProfOptions Options;
612 Options.NoRedZone = CodeGenOpts.DisableRedZone;
Justin Bognera71e6812015-04-30 23:49:42 +0000613 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000614 MPM.add(createInstrProfilingLegacyPass(Options));
Justin Bogner970ac602014-12-08 19:04:51 +0000615 }
Rong Xu522b5cb2016-02-29 18:54:59 +0000616 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000617 PMBuilder.EnablePGOInstrGen = true;
Rong Xu522b5cb2016-02-29 18:54:59 +0000618 if (!CodeGenOpts.InstrProfileOutput.empty())
619 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
620 else
Davide Italiano945de432017-02-13 16:07:05 +0000621 PMBuilder.PGOInstrGen = DefaultProfileGenName;
Rong Xu522b5cb2016-02-29 18:54:59 +0000622 }
Rong Xu9c6f1532016-03-02 20:59:36 +0000623 if (CodeGenOpts.hasProfileIRUse())
624 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Justin Bogner970ac602014-12-08 19:04:51 +0000625
Dehao Chen5717aff2016-12-14 21:41:04 +0000626 if (!CodeGenOpts.SampleProfileFile.empty())
627 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000628
Peter Collingbourne03f89072016-07-15 00:55:40 +0000629 PMBuilder.populateFunctionPassManager(FPM);
630 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000631}
632
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000633static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000634 SmallVector<const char *, 16> BackendArgs;
635 BackendArgs.push_back("clang"); // Fake program name.
636 if (!CodeGenOpts.DebugPass.empty()) {
637 BackendArgs.push_back("-debug-pass");
638 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
639 }
640 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
641 BackendArgs.push_back("-limit-float-precision");
642 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
643 }
644 for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
645 BackendArgs.push_back(BackendOption.c_str());
646 BackendArgs.push_back(nullptr);
647 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
648 BackendArgs.data());
649}
650
Peter Collingbourne03f89072016-07-15 00:55:40 +0000651void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000652 // Create the TargetMachine for generating code.
653 std::string Error;
654 std::string Triple = TheModule->getTargetTriple();
655 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
656 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000657 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000658 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000659 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000660 }
661
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000662 llvm::CodeModel::Model CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000663 std::string FeaturesStr =
664 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000665 llvm::Reloc::Model RM = getRelocModel(CodeGenOpts);
666 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000667
Nick Lewycky432add52011-12-02 22:17:00 +0000668 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000669 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000670 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
671 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000672}
673
Peter Collingbourne03f89072016-07-15 00:55:40 +0000674bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
675 BackendAction Action,
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000676 raw_pwrite_stream &OS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000677 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000678 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000679 std::unique_ptr<TargetLibraryInfoImpl> TLII(
680 createTLII(TargetTriple, CodeGenOpts));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000681 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000682
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000683 // Normal mode, emit a .s or .o file by running the code generator. Note,
684 // this also adds codegenerator level optimization passes.
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000685 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000686
687 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
688 // "codegen" passes so that it isn't run multiple times when there is
689 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000690 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000691 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000692
Peter Collingbourne03f89072016-07-15 00:55:40 +0000693 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000694 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
695 Diags.Report(diag::err_fe_unable_to_interface_with_target);
696 return false;
697 }
698
699 return true;
700}
701
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000702void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000703 std::unique_ptr<raw_pwrite_stream> OS) {
Craig Topper8a13c412014-05-21 05:09:00 +0000704 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000705
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000706 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000707
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000708 bool UsesCodeGen = (Action != Backend_EmitNothing &&
709 Action != Backend_EmitBC &&
710 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000711 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000712
Rafael Espindolab633d202015-06-23 13:59:36 +0000713 if (UsesCodeGen && !TM)
714 return;
715 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000716 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000717
Peter Collingbourne03f89072016-07-15 00:55:40 +0000718 legacy::PassManager PerModulePasses;
719 PerModulePasses.add(
720 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
721
722 legacy::FunctionPassManager PerFunctionPasses(TheModule);
723 PerFunctionPasses.add(
724 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
725
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000726 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000727
728 legacy::PassManager CodeGenPasses;
729 CodeGenPasses.add(
730 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000731
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000732 std::unique_ptr<raw_fd_ostream> ThinLinkOS;
733
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000734 switch (Action) {
735 case Backend_EmitNothing:
736 break;
737
738 case Backend_EmitBC:
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000739 if (CodeGenOpts.EmitSummaryIndex) {
740 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
741 std::error_code EC;
742 ThinLinkOS.reset(new llvm::raw_fd_ostream(
743 CodeGenOpts.ThinLinkBitcodeFile, EC,
744 llvm::sys::fs::F_None));
745 if (EC) {
746 Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
747 << EC.message();
748 return;
749 }
750 }
751 PerModulePasses.add(
752 createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
753 }
Peter Collingbourneb8847162017-01-26 23:51:50 +0000754 else
755 PerModulePasses.add(
756 createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000757 break;
758
759 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000760 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000761 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000762 break;
763
764 default:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000765 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000766 return;
767 }
768
Andrew Trick15e36e82011-04-05 18:56:55 +0000769 // Before executing passes, print the final values of the LLVM options.
770 cl::PrintOptionValues();
771
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000772 // Run passes. For now we do all passes at once, but eventually we
773 // would like to have the option of streaming code generation.
774
Peter Collingbourne03f89072016-07-15 00:55:40 +0000775 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000776 PrettyStackTraceString CrashInfo("Per-function optimization");
777
Peter Collingbourne03f89072016-07-15 00:55:40 +0000778 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000779 for (Function &F : *TheModule)
780 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000781 PerFunctionPasses.run(F);
782 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000783 }
784
Peter Collingbourne03f89072016-07-15 00:55:40 +0000785 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000786 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000787 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000788 }
789
Peter Collingbourne03f89072016-07-15 00:55:40 +0000790 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000791 PrettyStackTraceString CrashInfo("Code generation");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000792 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000793 }
794}
795
Chandler Carruth50f9e892016-12-23 20:44:01 +0000796static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
797 switch (Opts.OptimizationLevel) {
798 default:
799 llvm_unreachable("Invalid optimization level!");
800
801 case 1:
802 return PassBuilder::O1;
803
804 case 2:
805 switch (Opts.OptimizeSize) {
806 default:
807 llvm_unreachable("Invalide optimization level for size!");
808
809 case 0:
810 return PassBuilder::O2;
811
812 case 1:
813 return PassBuilder::Os;
814
815 case 2:
816 return PassBuilder::Oz;
817 }
818
819 case 3:
820 return PassBuilder::O3;
821 }
822}
823
824/// A clean version of `EmitAssembly` that uses the new pass manager.
825///
826/// Not all features are currently supported in this system, but where
827/// necessary it falls back to the legacy pass manager to at least provide
828/// basic functionality.
829///
830/// This API is planned to have its functionality finished and then to replace
831/// `EmitAssembly` at some point in the future when the default switches.
832void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
833 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
834 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000835 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000836
837 // The new pass manager always makes a target machine available to passes
838 // during construction.
839 CreateTargetMachine(/*MustCreateTM*/ true);
840 if (!TM)
841 // This will already be diagnosed, just bail.
842 return;
843 TheModule->setDataLayout(TM->createDataLayout());
844
Davide Italiano945de432017-02-13 16:07:05 +0000845 PGOOptions PGOOpt;
846
847 // -fprofile-generate.
848 PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
849 if (PGOOpt.RunProfileGen)
850 PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
851 DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
852
853 // -fprofile-use.
854 if (CodeGenOpts.hasProfileIRUse())
855 PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
856
857 // Only pass a PGO options struct if -fprofile-generate or
858 // -fprofile-use were passed on the cmdline.
859 PassBuilder PB(TM.get(),
860 (PGOOpt.RunProfileGen ||
861 !PGOOpt.ProfileUseFile.empty()) ?
862 Optional<PGOOptions>(PGOOpt) : None);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000863
864 LoopAnalysisManager LAM;
865 FunctionAnalysisManager FAM;
866 CGSCCAnalysisManager CGAM;
867 ModuleAnalysisManager MAM;
868
869 // Register the AA manager first so that our version is the one used.
870 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
871
872 // Register all the basic analyses with the managers.
873 PB.registerModuleAnalyses(MAM);
874 PB.registerCGSCCAnalyses(CGAM);
875 PB.registerFunctionAnalyses(FAM);
876 PB.registerLoopAnalyses(LAM);
877 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
878
879 ModulePassManager MPM;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000880
Chandler Carruth6d1b83e2016-12-27 00:13:09 +0000881 if (!CodeGenOpts.DisableLLVMPasses) {
882 if (CodeGenOpts.OptimizationLevel == 0) {
883 // Build a minimal pipeline based on the semantics required by Clang,
884 // which is just that always inlining occurs.
885 MPM.addPass(AlwaysInlinerPass());
886 } else {
887 // Otherwise, use the default pass pipeline. We also have to map our
888 // optimization levels into one of the distinct levels used to configure
889 // the pipeline.
890 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
891
892 MPM = PB.buildPerModuleDefaultPipeline(Level);
893 }
Chandler Carruth50f9e892016-12-23 20:44:01 +0000894 }
895
896 // FIXME: We still use the legacy pass manager to do code generation. We
897 // create that pass manager here and use it as needed below.
898 legacy::PassManager CodeGenPasses;
899 bool NeedCodeGen = false;
900
901 // Append any output we need to the pass manager.
902 switch (Action) {
903 case Backend_EmitNothing:
904 break;
905
906 case Backend_EmitBC:
907 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
908 CodeGenOpts.EmitSummaryIndex,
909 CodeGenOpts.EmitSummaryIndex));
910 break;
911
912 case Backend_EmitLL:
913 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
914 break;
915
916 case Backend_EmitAssembly:
917 case Backend_EmitMCNull:
918 case Backend_EmitObj:
919 NeedCodeGen = true;
920 CodeGenPasses.add(
921 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
922 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
923 // FIXME: Should we handle this error differently?
924 return;
925 break;
926 }
927
928 // Before executing passes, print the final values of the LLVM options.
929 cl::PrintOptionValues();
930
931 // Now that we have all of the passes ready, run them.
932 {
933 PrettyStackTraceString CrashInfo("Optimizer");
934 MPM.run(*TheModule, MAM);
935 }
936
937 // Now if needed, run the legacy PM for codegen.
938 if (NeedCodeGen) {
939 PrettyStackTraceString CrashInfo("Code generation");
940 CodeGenPasses.run(*TheModule);
941 }
942}
943
Peter Collingbourne47d23642017-01-24 19:54:37 +0000944Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
945 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
946 if (!BMsOrErr)
947 return BMsOrErr.takeError();
948
949 // The bitcode file may contain multiple modules, we want the one with a
950 // summary.
951 for (BitcodeModule &BM : *BMsOrErr) {
952 Expected<bool> HasSummary = BM.hasSummary();
953 if (HasSummary && *HasSummary)
954 return BM;
955 }
956
957 return make_error<StringError>("Could not find module summary",
958 inconvertibleErrorCode());
959}
960
Teresa Johnsoncffeb542017-01-06 23:37:33 +0000961static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000962 const HeaderSearchOptions &HeaderOpts,
963 const CodeGenOptions &CGOpts,
964 const clang::TargetOptions &TOpts,
965 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +0000966 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000967 std::string SampleProfile,
968 BackendAction Action) {
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000969 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
970 ModuleToDefinedGVSummaries;
971 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
972
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000973 setCommandLineOpts(CGOpts);
974
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000975 // We can simply import the values mentioned in the combined index, since
976 // we should only invoke this using the individual indexes written out
977 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000978 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000979 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000980 // Ignore entries for undefined references.
981 if (GlobalList.second.SummaryList.empty())
982 continue;
983
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000984 auto GUID = GlobalList.first;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000985 assert(GlobalList.second.SummaryList.size() == 1 &&
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000986 "Expected individual combined index to have one summary per GUID");
Peter Collingbourne9667b912017-05-04 18:03:25 +0000987 auto &Summary = GlobalList.second.SummaryList[0];
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000988 // Skip the summaries for the importing module. These are included to
989 // e.g. record required linkage changes.
990 if (Summary->modulePath() == M->getModuleIdentifier())
991 continue;
992 // Doesn't matter what value we plug in to the map, just needs an entry
993 // to provoke importing by thinBackend.
994 ImportList[Summary->modulePath()][GUID] = 1;
995 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000996
997 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000998 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000999
1000 for (auto &I : ImportList) {
1001 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1002 llvm::MemoryBuffer::getFile(I.first());
1003 if (!MBOrErr) {
1004 errs() << "Error loading imported file '" << I.first()
1005 << "': " << MBOrErr.getError().message() << "\n";
1006 return;
1007 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001008
Peter Collingbourne47d23642017-01-24 19:54:37 +00001009 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1010 if (!BMOrErr) {
1011 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001012 errs() << "Error loading imported file '" << I.first()
1013 << "': " << EIB.message() << '\n';
1014 });
1015 return;
1016 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001017 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001018
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001019 OwnedImports.push_back(std::move(*MBOrErr));
1020 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001021 auto AddStream = [&](size_t Task) {
1022 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001023 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001024 lto::Config Conf;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001025 Conf.CPU = TOpts.CPU;
1026 Conf.CodeModel = getCodeModel(CGOpts);
1027 Conf.MAttrs = TOpts.Features;
1028 Conf.RelocModel = getRelocModel(CGOpts);
1029 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001030 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001031 Conf.SampleProfile = std::move(SampleProfile);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001032 switch (Action) {
1033 case Backend_EmitNothing:
1034 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1035 return false;
1036 };
1037 break;
1038 case Backend_EmitLL:
1039 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1040 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1041 return false;
1042 };
1043 break;
1044 case Backend_EmitBC:
1045 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1046 WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
1047 return false;
1048 };
1049 break;
1050 default:
1051 Conf.CGFileType = getCodeGenFileType(Action);
1052 break;
1053 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001054 if (Error E = thinBackend(
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001055 Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001056 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1057 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1058 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1059 });
1060 }
1061}
1062
David Blaikie9c902b52011-09-25 23:23:43 +00001063void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001064 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001065 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001066 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001067 const LangOptions &LOpts,
1068 const llvm::DataLayout &TDesc, Module *M,
1069 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001070 std::unique_ptr<raw_pwrite_stream> OS) {
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001071 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001072 // If we are performing a ThinLTO importing compile, load the function index
1073 // into memory and pass it into runThinLTOBackend, which will run the
1074 // function importer and invoke LTO passes.
1075 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1076 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
1077 if (!IndexOrErr) {
1078 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1079 "Error loading index file '" +
1080 CGOpts.ThinLTOIndexFile + "': ");
1081 return;
1082 }
1083 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1084 // A null CombinedIndex means we should skip ThinLTO compilation
1085 // (LLVM will optionally ignore empty index files, returning null instead
1086 // of an error).
1087 bool DoThinLTOBackend = CombinedIndex != nullptr;
1088 if (DoThinLTOBackend) {
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001089 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1090 LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001091 return;
1092 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001093 }
1094
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001095 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001096
Chandler Carruth50f9e892016-12-23 20:44:01 +00001097 if (CGOpts.ExperimentalNewPassManager)
1098 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1099 else
1100 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001101
James Y Knightb214cbc2016-03-04 19:00:41 +00001102 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1103 // DataLayout.
1104 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001105 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001106 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001107 unsigned DiagID = Diags.getCustomDiagID(
1108 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1109 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001110 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001111 }
1112 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001113}
Steven Wu27fb5222016-05-11 16:26:03 +00001114
1115static const char* getSectionNameForBitcode(const Triple &T) {
1116 switch (T.getObjectFormat()) {
1117 case Triple::MachO:
1118 return "__LLVM,__bitcode";
1119 case Triple::COFF:
1120 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001121 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001122 case Triple::UnknownObjectFormat:
1123 return ".llvmbc";
1124 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001125 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001126}
1127
1128static const char* getSectionNameForCommandline(const Triple &T) {
1129 switch (T.getObjectFormat()) {
1130 case Triple::MachO:
1131 return "__LLVM,__cmdline";
1132 case Triple::COFF:
1133 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001134 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001135 case Triple::UnknownObjectFormat:
1136 return ".llvmcmd";
1137 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001138 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001139}
1140
1141// With -fembed-bitcode, save a copy of the llvm IR as data in the
1142// __LLVM,__bitcode section.
1143void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1144 llvm::MemoryBufferRef Buf) {
1145 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1146 return;
1147
Steven Wu2c059a52016-05-16 18:54:58 +00001148 // Save llvm.compiler.used and remote it.
1149 SmallVector<Constant*, 2> UsedArray;
1150 SmallSet<GlobalValue*, 4> UsedGlobals;
1151 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1152 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1153 for (auto *GV : UsedGlobals) {
1154 if (GV->getName() != "llvm.embedded.module" &&
1155 GV->getName() != "llvm.cmdline")
1156 UsedArray.push_back(
1157 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1158 }
1159 if (Used)
1160 Used->eraseFromParent();
1161
Steven Wu27fb5222016-05-11 16:26:03 +00001162 // Embed the bitcode for the llvm module.
1163 std::string Data;
1164 ArrayRef<uint8_t> ModuleData;
1165 Triple T(M->getTargetTriple());
1166 // Create a constant that contains the bitcode.
1167 // In case of embedding a marker, ignore the input Buf and use the empty
1168 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1169 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1170 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1171 (const unsigned char *)Buf.getBufferEnd())) {
1172 // If the input is LLVM Assembly, bitcode is produced by serializing
1173 // the module. Use-lists order need to be perserved in this case.
1174 llvm::raw_string_ostream OS(Data);
1175 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1176 ModuleData =
1177 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1178 } else
1179 // If the input is LLVM bitcode, write the input byte stream directly.
1180 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1181 Buf.getBufferSize());
1182 }
1183 llvm::Constant *ModuleConstant =
1184 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
Steven Wu27fb5222016-05-11 16:26:03 +00001185 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
Steven Wu2c059a52016-05-16 18:54:58 +00001186 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
Steven Wu27fb5222016-05-11 16:26:03 +00001187 ModuleConstant);
1188 GV->setSection(getSectionNameForBitcode(T));
Steven Wu2c059a52016-05-16 18:54:58 +00001189 UsedArray.push_back(
1190 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
Steven Wu27fb5222016-05-11 16:26:03 +00001191 if (llvm::GlobalVariable *Old =
Steven Wu2c059a52016-05-16 18:54:58 +00001192 M->getGlobalVariable("llvm.embedded.module", true)) {
1193 assert(Old->hasOneUse() &&
1194 "llvm.embedded.module can only be used once in llvm.compiler.used");
Steven Wu27fb5222016-05-11 16:26:03 +00001195 GV->takeName(Old);
1196 Old->eraseFromParent();
1197 } else {
1198 GV->setName("llvm.embedded.module");
1199 }
1200
Steven Wu2c059a52016-05-16 18:54:58 +00001201 // Skip if only bitcode needs to be embedded.
1202 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1203 // Embed command-line options.
Saleem Abdulrasoolb1d50c12016-05-20 03:58:12 +00001204 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
Steven Wu2c059a52016-05-16 18:54:58 +00001205 CGOpts.CmdArgs.size());
1206 llvm::Constant *CmdConstant =
1207 llvm::ConstantDataArray::get(M->getContext(), CmdData);
1208 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1209 llvm::GlobalValue::PrivateLinkage,
1210 CmdConstant);
1211 GV->setSection(getSectionNameForCommandline(T));
1212 UsedArray.push_back(
1213 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1214 if (llvm::GlobalVariable *Old =
1215 M->getGlobalVariable("llvm.cmdline", true)) {
1216 assert(Old->hasOneUse() &&
1217 "llvm.cmdline can only be used once in llvm.compiler.used");
1218 GV->takeName(Old);
1219 Old->eraseFromParent();
1220 } else {
1221 GV->setName("llvm.cmdline");
1222 }
1223 }
1224
1225 if (UsedArray.empty())
Steven Wu27fb5222016-05-11 16:26:03 +00001226 return;
1227
Steven Wu2c059a52016-05-16 18:54:58 +00001228 // Recreate llvm.compiler.used.
1229 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1230 auto *NewUsed = new GlobalVariable(
1231 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1232 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1233 NewUsed->setSection("llvm.metadata");
Steven Wu27fb5222016-05-11 16:26:03 +00001234}