blob: bc500085a72b82e9cadc49897bd5bc3eed16c603 [file] [log] [blame]
Nick Kledzik07b4a622008-02-26 20:26:43 +00001//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
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.
Bill Wendling39d942b2012-03-31 10:50:14 +00007//
Nick Kledzik07b4a622008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling39d942b2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik07b4a622008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000015#include "llvm/LTO/LTOCodeGenerator.h"
Mehdi Aminif59f2bb12016-04-12 06:34:10 +000016
Mehdi Aminice23e972016-04-13 06:32:46 +000017#include "UpdateCompilerUsed.h"
Adam Nemet106feda2016-02-16 21:41:51 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/ADT/StringExtras.h"
Nick Lewycky510dae32009-06-17 06:52:10 +000020#include "llvm/Analysis/Passes.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth93dcdc42015-01-31 11:17:59 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000023#include "llvm/Bitcode/ReaderWriter.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000024#include "llvm/CodeGen/ParallelCG.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000025#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000026#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000030#include "llvm/IR/DiagnosticInfo.h"
31#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000033#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000034#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000037#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000038#include "llvm/LTO/LTOModule.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000039#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000040#include "llvm/MC/MCAsmInfo.h"
41#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000042#include "llvm/MC/SubtargetFeature.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000043#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000044#include "llvm/Support/FileSystem.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000045#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000046#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000047#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000048#include "llvm/Support/TargetRegistry.h"
49#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000050#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000051#include "llvm/Support/raw_ostream.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000052#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000053#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000054#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000055#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000056#include "llvm/Transforms/IPO.h"
Mehdi Aminice23e972016-04-13 06:32:46 +000057#include "llvm/Transforms/IPO/Internalize.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000058#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000059#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000060#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000061using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000062
Bill Wendling534a6582012-03-31 10:49:43 +000063const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000064#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000065 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000066#else
Bill Wendling534a6582012-03-31 10:49:43 +000067 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000068#endif
69}
70
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000071namespace llvm {
72cl::opt<bool> LTODiscardValueNames(
Mehdi Amini1592cb92016-03-10 17:06:52 +000073 "lto-discard-value-names",
74 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000075#ifdef NDEBUG
76 cl::init(true),
77#else
78 cl::init(false),
79#endif
80 cl::Hidden);
81}
82
Rafael Espindola7b8a24e2015-12-04 02:42:28 +000083LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
Rafael Espindolaf49a38f2015-12-04 22:08:53 +000084 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
Teresa Johnsonbef54362015-12-18 19:28:59 +000085 TheLinker(new Linker(*MergedModule)) {
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000086 Context.setDiscardValueNames(LTODiscardValueNames);
Duncan P. N. Exon Smith7832e0a2015-04-27 23:19:26 +000087 initializeLTOPasses();
Duncan P. N. Exon Smithde5e32b2014-11-11 23:03:29 +000088}
89
Peter Collingbourne9c8909d2015-08-24 22:22:53 +000090LTOCodeGenerator::~LTOCodeGenerator() {}
Nick Kledzik07b4a622008-02-26 20:26:43 +000091
Yaron Keren55f5c3d2015-09-01 10:13:49 +000092// Initialize LTO passes. Please keep this function in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000093// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +000094// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000095void LTOCodeGenerator::initializeLTOPasses() {
96 PassRegistry &R = *PassRegistry::getPassRegistry();
97
98 initializeInternalizePassPass(R);
99 initializeIPSCCPPass(R);
100 initializeGlobalOptPass(R);
101 initializeConstantMergePass(R);
102 initializeDAHPass(R);
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000103 initializeInstructionCombiningPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000104 initializeSimpleInlinerPass(R);
105 initializePruneEHPass(R);
106 initializeGlobalDCEPass(R);
107 initializeArgPromotionPass(R);
108 initializeJumpThreadingPass(R);
Chandler Carruth29a18a42015-09-12 09:09:14 +0000109 initializeSROALegacyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000110 initializeSROA_DTPass(R);
111 initializeSROA_SSAUpPass(R);
Chandler Carruth9c4ed172016-02-18 11:03:11 +0000112 initializePostOrderFunctionAttrsLegacyPassPass(R);
Chandler Carruth1926b702016-01-08 10:55:52 +0000113 initializeReversePostOrderFunctionAttrsPass(R);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000114 initializeGlobalsAAWrapperPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000115 initializeLICMPass(R);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000116 initializeMergedLoadStoreMotionPass(R);
Chandler Carruth89c45a12016-03-11 08:50:55 +0000117 initializeGVNLegacyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000118 initializeMemCpyOptPass(R);
119 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000120 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000121}
122
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000123bool LTOCodeGenerator::addModule(LTOModule *Mod) {
124 assert(&Mod->getModule().getContext() == &Context &&
Duncan P. N. Exon Smith94198632014-11-11 23:13:10 +0000125 "Expected module in same context");
126
Teresa Johnsonbef54362015-12-18 19:28:59 +0000127 bool ret = TheLinker->linkInModule(Mod->takeModule());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000128
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000129 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000130 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000131 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000132
Shuxin Yangb6696a92013-08-07 05:19:23 +0000133 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000134}
Bill Wendling39d942b2012-03-31 10:50:14 +0000135
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000136void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
Manman Ren6487ce92015-02-24 00:45:56 +0000137 assert(&Mod->getModule().getContext() == &Context &&
138 "Expected module in same context");
139
Manman Ren6487ce92015-02-24 00:45:56 +0000140 AsmUndefinedRefs.clear();
141
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000142 MergedModule = Mod->takeModule();
Teresa Johnsonbef54362015-12-18 19:28:59 +0000143 TheLinker = make_unique<Linker>(*MergedModule);
Manman Ren6487ce92015-02-24 00:45:56 +0000144
145 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
146 for (int I = 0, E = Undefs.size(); I != E; ++I)
147 AsmUndefinedRefs[Undefs[I]] = 1;
148}
149
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000150void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
151 this->Options = Options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000152}
153
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000154void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
155 switch (Debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000156 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000157 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000158 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000159
Bill Wendling0e1824c2012-03-31 11:15:43 +0000160 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000161 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000162 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000163 }
164 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000165}
166
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000167void LTOCodeGenerator::setOptLevel(unsigned Level) {
168 OptLevel = Level;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000169 switch (OptLevel) {
170 case 0:
171 CGOptLevel = CodeGenOpt::None;
172 break;
173 case 1:
174 CGOptLevel = CodeGenOpt::Less;
175 break;
176 case 2:
177 CGOptLevel = CodeGenOpt::Default;
178 break;
179 case 3:
180 CGOptLevel = CodeGenOpt::Aggressive;
181 break;
182 }
183}
184
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000185bool LTOCodeGenerator::writeMergedModules(const char *Path) {
186 if (!determineTarget())
Shuxin Yangb6696a92013-08-07 05:19:23 +0000187 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000188
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000189 // mark which symbols can not be internalized
190 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000191
Chris Lattner69733952009-08-23 07:49:08 +0000192 // create output file
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000193 std::error_code EC;
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000194 tool_output_file Out(Path, EC, sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000195 if (EC) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000196 std::string ErrMsg = "could not open bitcode file for writing: ";
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000197 ErrMsg += Path;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000198 emitError(ErrMsg);
Shuxin Yangb6696a92013-08-07 05:19:23 +0000199 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000200 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000201
Chris Lattner69733952009-08-23 07:49:08 +0000202 // write bitcode to it
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000203 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
Dan Gohmana2233f22010-09-01 14:20:41 +0000204 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000205
Dan Gohmana2233f22010-09-01 14:20:41 +0000206 if (Out.os().has_error()) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000207 std::string ErrMsg = "could not write bitcode file: ";
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000208 ErrMsg += Path;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000209 emitError(ErrMsg);
Dan Gohmana2233f22010-09-01 14:20:41 +0000210 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000211 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000212 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000213
Dan Gohman8525fe72010-08-20 16:59:15 +0000214 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000215 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000216}
217
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000218bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000219 // make unique temp output file to put generated code
Shuxin Yang1826ae22013-08-12 21:07:31 +0000220 SmallString<128> Filename;
221 int FD;
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000222
223 const char *Extension =
224 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
225
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000226 std::error_code EC =
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000227 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000228 if (EC) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000229 emitError(EC.message());
Shuxin Yangb6696a92013-08-07 05:19:23 +0000230 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000231 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000232
Shuxin Yang1826ae22013-08-12 21:07:31 +0000233 // generate object file
234 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000235
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000236 bool genResult = compileOptimized(&objFile.os());
Shuxin Yang1826ae22013-08-12 21:07:31 +0000237 objFile.os().close();
238 if (objFile.os().has_error()) {
239 objFile.os().clear_error();
240 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000241 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000242 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000243
Shuxin Yang1826ae22013-08-12 21:07:31 +0000244 objFile.keep();
245 if (!genResult) {
246 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000247 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000248 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000249
Rafael Espindolac80c9692013-09-04 17:44:24 +0000250 NativeObjectPath = Filename.c_str();
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000251 *Name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000252 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000253}
254
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000255std::unique_ptr<MemoryBuffer>
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000256LTOCodeGenerator::compileOptimized() {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000257 const char *name;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000258 if (!compileOptimizedToFile(&name))
Craig Topper2617dcc2014-04-15 06:32:26 +0000259 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000260
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000261 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000262 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
263 MemoryBuffer::getFile(name, -1, false);
264 if (std::error_code EC = BufferOrErr.getError()) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000265 emitError(EC.message());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000266 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000267 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000268 }
Rafael Espindolafac373c2011-02-24 21:04:06 +0000269
Shuxin Yang1826ae22013-08-12 21:07:31 +0000270 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000271 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000272
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000273 return std::move(*BufferOrErr);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000274}
275
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000276bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
277 bool DisableInline,
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000278 bool DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000279 bool DisableVectorization) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000280 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000281 DisableVectorization))
Manman Ren8121e1d2015-02-03 18:39:15 +0000282 return false;
283
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000284 return compileOptimizedToFile(Name);
Manman Ren8121e1d2015-02-03 18:39:15 +0000285}
286
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000287std::unique_ptr<MemoryBuffer>
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000288LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000289 bool DisableGVNLoadPRE, bool DisableVectorization) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000290 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000291 DisableVectorization))
Manman Ren8121e1d2015-02-03 18:39:15 +0000292 return nullptr;
293
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000294 return compileOptimized();
Manman Ren8121e1d2015-02-03 18:39:15 +0000295}
296
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000297bool LTOCodeGenerator::determineTarget() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000298 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000299 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000300
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000301 std::string TripleStr = MergedModule->getTargetTriple();
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000302 if (TripleStr.empty()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000303 TripleStr = sys::getDefaultTargetTriple();
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000304 MergedModule->setTargetTriple(TripleStr);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000305 }
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000306 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000307
Bill Wendling45f74e32012-08-06 22:52:45 +0000308 // create target machine from info for merged modules
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000309 std::string ErrMsg;
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000310 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000311 if (!march) {
312 emitError(ErrMsg);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000313 return false;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000314 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000315
Tom Roederfd1bc602014-04-25 21:46:51 +0000316 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
317 // the default set of features.
318 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000319 Features.getDefaultSubtargetFeatures(Triple);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000320 FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000321 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000322 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000323 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000324 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000325 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000326 MCpu = "yonah";
Tim Northovere19bed72014-07-23 12:32:47 +0000327 else if (Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000328 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000329 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000330
Peter Collingbourneec43d0f2015-08-21 04:45:57 +0000331 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
332 Options, RelocModel,
333 CodeModel::Default, CGOptLevel));
Shuxin Yang95866fa2013-08-06 21:51:21 +0000334 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000335}
336
Chris Lattner2eff5052010-03-12 18:44:54 +0000337void LTOCodeGenerator::applyScopeRestrictions() {
Manman Rence0a0662015-04-17 17:10:09 +0000338 if (ScopeRestrictionsDone || !ShouldInternalize)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000339 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000340
Mehdi Aminideee0032016-04-13 05:36:06 +0000341 if (ShouldRestoreGlobalsLinkage) {
342 // Record the linkage type of non-local symbols so they can be restored
343 // prior
344 // to module splitting.
345 auto RecordLinkage = [&](const GlobalValue &GV) {
346 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
347 GV.hasName())
348 ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
349 };
350 for (auto &GV : *MergedModule)
351 RecordLinkage(GV);
352 for (auto &GV : MergedModule->globals())
353 RecordLinkage(GV);
354 for (auto &GV : MergedModule->aliases())
355 RecordLinkage(GV);
356 }
357
Mehdi Aminice23e972016-04-13 06:32:46 +0000358 // Update the llvm.compiler_used globals to force preserving libcalls and
359 // symbols referenced from asm
360 UpdateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
361
Mehdi Amini40787092016-04-13 04:20:32 +0000362 // Declare a callback for the internalize pass that will ask for every
363 // candidate GlobalValue if it can be internalized or not.
364 Mangler Mangler;
365 SmallString<64> MangledName;
366 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
367 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
368 // with the linker supplied name, which on Darwin includes a leading
369 // underscore.
370 MangledName.clear();
371 MangledName.reserve(GV.getName().size() + 1);
372 Mangler::getNameWithPrefix(MangledName, GV.getName(),
373 MergedModule->getDataLayout());
374 return MustPreserveSymbols.count(MangledName);
375 };
376
Mehdi Aminice23e972016-04-13 06:32:46 +0000377 internalizeModule(*MergedModule, MustPreserveGV);
Bill Wendling39d942b2012-03-31 10:50:14 +0000378
Rafael Espindolac80c9692013-09-04 17:44:24 +0000379 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000380}
381
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000382/// Restore original linkage for symbols that may have been internalized
383void LTOCodeGenerator::restoreLinkageForExternals() {
384 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
385 return;
386
387 assert(ScopeRestrictionsDone &&
388 "Cannot externalize without internalization!");
389
390 if (ExternalSymbols.empty())
391 return;
392
393 auto externalize = [this](GlobalValue &GV) {
394 if (!GV.hasLocalLinkage() || !GV.hasName())
395 return;
396
397 auto I = ExternalSymbols.find(GV.getName());
398 if (I == ExternalSymbols.end())
399 return;
400
401 GV.setLinkage(I->second);
402 };
403
404 std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
405 std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
406 externalize);
407 std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
408 externalize);
409}
410
Nick Kledzik07b4a622008-02-26 20:26:43 +0000411/// Optimize merged modules using various IPO passes
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000412bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
413 bool DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000414 bool DisableVectorization) {
415 if (!this->determineTarget())
Shuxin Yang95866fa2013-08-06 21:51:21 +0000416 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000417
Mehdi Aminif59f2bb12016-04-12 06:34:10 +0000418 // We always run the verifier once on the merged module, the `DisableVerify`
419 // parameter only applies to subsequent verify.
420 if (verifyModule(*MergedModule, &dbgs()))
421 report_fatal_error("Broken module found, compilation aborted!");
422
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000423 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000424 this->applyScopeRestrictions();
425
Bill Wendling0e1824c2012-03-31 11:15:43 +0000426 // Instantiate the pass manager to organize the passes.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000427 legacy::PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000428
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000429 // Add an appropriate DataLayout instance for this module...
Peter Collingbournee34034c2015-08-24 21:15:35 +0000430 MergedModule->setDataLayout(TargetMach->createDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000431
Chandler Carruth5ec2b1d2015-02-01 12:26:09 +0000432 passes.add(
433 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000434
Rafael Espindola216e0c02014-08-21 18:49:52 +0000435 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000436 PassManagerBuilder PMB;
437 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000438 PMB.LoopVectorize = !DisableVectorization;
439 PMB.SLPVectorize = !DisableVectorization;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000440 if (!DisableInline)
441 PMB.Inliner = createFunctionInliningPass();
Chandler Carruthc0291862015-01-24 02:06:09 +0000442 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
Peter Collingbourne070843d2015-03-19 22:01:00 +0000443 PMB.OptLevel = OptLevel;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000444 PMB.VerifyInput = !DisableVerify;
445 PMB.VerifyOutput = !DisableVerify;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000446
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000447 PMB.populateLTOPassManager(passes);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000448
Manman Ren8121e1d2015-02-03 18:39:15 +0000449 // Run our queue of passes all at once now, efficiently.
Peter Collingbournee34034c2015-08-24 21:15:35 +0000450 passes.run(*MergedModule);
Manman Ren8121e1d2015-02-03 18:39:15 +0000451
452 return true;
453}
454
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000455bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
456 if (!this->determineTarget())
Manman Ren8121e1d2015-02-03 18:39:15 +0000457 return false;
458
Peter Collingbournec269ed52015-08-27 23:37:36 +0000459 legacy::PassManager preCodeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000460
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000461 // If the bitcode files contain ARC code and were compiled with optimization,
462 // the ObjCARCContractPass must be run, so do it unconditionally here.
Peter Collingbournec269ed52015-08-27 23:37:36 +0000463 preCodeGenPasses.add(createObjCARCContractPass());
464 preCodeGenPasses.run(*MergedModule);
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000465
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000466 // Re-externalize globals that may have been internalized to increase scope
467 // for splitting
468 restoreLinkageForExternals();
469
Peter Collingbournec269ed52015-08-27 23:37:36 +0000470 // Do code generation. We need to preserve the module in case the client calls
471 // writeMergedModules() after compilation, but we only need to allow this at
472 // parallelism level 1. This is achieved by having splitCodeGen return the
473 // original module at parallelism level 1 which we then assign back to
474 // MergedModule.
Evgeniy Stepanov268826a2016-04-06 18:32:13 +0000475 MergedModule = splitCodeGen(
476 std::move(MergedModule), Out, {}, MCpu, FeatureStr, Options, RelocModel,
477 CodeModel::Default, CGOptLevel, FileType, ShouldRestoreGlobalsLinkage);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000478
Adam Nemet106feda2016-02-16 21:41:51 +0000479 // If statistics were requested, print them out after codegen.
480 if (llvm::AreStatisticsEnabled())
481 llvm::PrintStatistics();
482
Shuxin Yang95866fa2013-08-06 21:51:21 +0000483 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000484}
485
Bill Wendling534a6582012-03-31 10:49:43 +0000486/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
487/// LTO problems.
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000488void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
489 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
490 o = getToken(o.second))
Peter Collingbourne22575122015-08-21 04:45:55 +0000491 CodegenOptions.push_back(o.first);
Nick Kledzikc2323472008-07-08 21:14:10 +0000492}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000493
494void LTOCodeGenerator::parseCodeGenDebugOptions() {
495 // if options were requested, set them
Peter Collingbourne22575122015-08-21 04:45:55 +0000496 if (!CodegenOptions.empty()) {
497 // ParseCommandLineOptions() expects argv[0] to be program name.
498 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
499 for (std::string &Arg : CodegenOptions)
500 CodegenArgv.push_back(Arg.c_str());
501 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
502 }
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000503}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000504
505void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
506 void *Context) {
507 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
508}
509
510void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
511 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
512 lto_codegen_diagnostic_severity_t Severity;
513 switch (DI.getSeverity()) {
514 case DS_Error:
515 Severity = LTO_DS_ERROR;
516 break;
517 case DS_Warning:
518 Severity = LTO_DS_WARNING;
519 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000520 case DS_Remark:
521 Severity = LTO_DS_REMARK;
522 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000523 case DS_Note:
524 Severity = LTO_DS_NOTE;
525 break;
526 }
527 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000528 std::string MsgStorage;
529 raw_string_ostream Stream(MsgStorage);
530 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000531 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000532 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000533
534 // If this method has been called it means someone has set up an external
535 // diagnostic handler. Assert on that.
536 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000537 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000538}
539
540void
541LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
542 void *Ctxt) {
543 this->DiagHandler = DiagHandler;
544 this->DiagContext = Ctxt;
545 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000546 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000547 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
548 // diagnostic to the external DiagHandler.
Duncan P. N. Exon Smithf02fe702014-10-02 21:11:04 +0000549 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
550 /* RespectFilters */ true);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000551}
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000552
553namespace {
554class LTODiagnosticInfo : public DiagnosticInfo {
555 const Twine &Msg;
556public:
557 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
558 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
559 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
560};
561}
562
563void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
564 if (DiagHandler)
565 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
566 else
567 Context.diagnose(LTODiagnosticInfo(ErrMsg));
568}