blob: a1709f60fff219adac9c949ac2b79b936ab3ab5d [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"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "llvm/ADT/StringExtras.h"
Nick Lewycky510dae32009-06-17 06:52:10 +000017#include "llvm/Analysis/Passes.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000018#include "llvm/Bitcode/ReaderWriter.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000019#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000020#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000024#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/LLVMContext.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000027#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000030#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000031#include "llvm/LTO/LTOModule.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000032#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000033#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000035#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/PassManager.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000037#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000038#include "llvm/Support/FileSystem.h"
David Greenea31f96c2009-07-14 20:18:05 +000039#include "llvm/Support/FormattedStream.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000040#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000042#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000043#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000045#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000046#include "llvm/Support/raw_ostream.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000047#include "llvm/Target/TargetLibraryInfo.h"
48#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000049#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000050#include "llvm/Target/TargetRegisterInfo.h"
51#include "llvm/Transforms/IPO.h"
52#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000053#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000054#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000055using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000056
Bill Wendling534a6582012-03-31 10:49:43 +000057const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000058#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000059 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000060#else
Bill Wendling534a6582012-03-31 10:49:43 +000061 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000062#endif
63}
64
Bill Wendling39d942b2012-03-31 10:50:14 +000065LTOCodeGenerator::LTOCodeGenerator()
Rafael Espindola80df4bb2014-05-03 15:28:13 +000066 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)),
Craig Topper2617dcc2014-04-15 06:32:26 +000067 TargetMach(nullptr), EmitDwarfDebugInfo(false),
68 ScopeRestrictionsDone(false), CodeModel(LTO_CODEGEN_PIC_MODEL_DEFAULT),
69 NativeObjectFile(nullptr), DiagHandler(nullptr), DiagContext(nullptr) {
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000070 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000071}
72
Bill Wendling534a6582012-03-31 10:49:43 +000073LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindolac80c9692013-09-04 17:44:24 +000074 delete TargetMach;
75 delete NativeObjectFile;
Craig Topper2617dcc2014-04-15 06:32:26 +000076 TargetMach = nullptr;
77 NativeObjectFile = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +000078
Rafael Espindola80df4bb2014-05-03 15:28:13 +000079 IRLinker.deleteModule();
Bill Wendling534a6582012-03-31 10:49:43 +000080
Rafael Espindolac80c9692013-09-04 17:44:24 +000081 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
82 E = CodegenOptions.end();
83 I != E; ++I)
Bill Wendling534a6582012-03-31 10:49:43 +000084 free(*I);
Nick Kledzik07b4a622008-02-26 20:26:43 +000085}
86
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000087// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000088// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +000089// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000090void LTOCodeGenerator::initializeLTOPasses() {
91 PassRegistry &R = *PassRegistry::getPassRegistry();
92
93 initializeInternalizePassPass(R);
94 initializeIPSCCPPass(R);
95 initializeGlobalOptPass(R);
96 initializeConstantMergePass(R);
97 initializeDAHPass(R);
98 initializeInstCombinerPass(R);
99 initializeSimpleInlinerPass(R);
100 initializePruneEHPass(R);
101 initializeGlobalDCEPass(R);
102 initializeArgPromotionPass(R);
103 initializeJumpThreadingPass(R);
104 initializeSROAPass(R);
105 initializeSROA_DTPass(R);
106 initializeSROA_SSAUpPass(R);
107 initializeFunctionAttrsPass(R);
108 initializeGlobalsModRefPass(R);
109 initializeLICMPass(R);
110 initializeGVNPass(R);
111 initializeMemCpyOptPass(R);
112 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000113 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000114}
115
Bill Wendling0e1824c2012-03-31 11:15:43 +0000116bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000117 bool ret = IRLinker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000118
119 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
120 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000121 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000122
Shuxin Yangb6696a92013-08-07 05:19:23 +0000123 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000124}
Bill Wendling39d942b2012-03-31 10:50:14 +0000125
Rafael Espindola0b385c72013-09-30 16:39:19 +0000126void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
Rafael Espindola70d3c202014-06-19 22:27:46 +0000127 Options = options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000128}
129
Shuxin Yangb6696a92013-08-07 05:19:23 +0000130void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000131 switch (debug) {
132 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000133 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000134 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000135
Bill Wendling0e1824c2012-03-31 11:15:43 +0000136 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000137 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000138 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000139 }
140 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000141}
142
Shuxin Yangb6696a92013-08-07 05:19:23 +0000143void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000144 switch (model) {
145 case LTO_CODEGEN_PIC_MODEL_STATIC:
146 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
147 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
James Molloy951e5292014-04-14 13:54:16 +0000148 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000149 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000150 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000151 }
152 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000153}
154
Chris Lattner69733952009-08-23 07:49:08 +0000155bool LTOCodeGenerator::writeMergedModules(const char *path,
156 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000157 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000158 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000159
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000160 // mark which symbols can not be internalized
161 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000162
Chris Lattner69733952009-08-23 07:49:08 +0000163 // create output file
164 std::string ErrInfo;
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000165 tool_output_file Out(path, ErrInfo, sys::fs::F_None);
Chris Lattner69733952009-08-23 07:49:08 +0000166 if (!ErrInfo.empty()) {
167 errMsg = "could not open bitcode file for writing: ";
168 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000169 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000170 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000171
Chris Lattner69733952009-08-23 07:49:08 +0000172 // write bitcode to it
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000173 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
Dan Gohmana2233f22010-09-01 14:20:41 +0000174 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000175
Dan Gohmana2233f22010-09-01 14:20:41 +0000176 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000177 errMsg = "could not write bitcode file: ";
178 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000179 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000180 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000181 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000182
Dan Gohman8525fe72010-08-20 16:59:15 +0000183 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000184 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000185}
186
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000187bool LTOCodeGenerator::compile_to_file(const char** name,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000188 bool disableOpt,
189 bool disableInline,
190 bool disableGVNLoadPRE,
191 std::string& errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000192 // make unique temp .o file to put generated object file
193 SmallString<128> Filename;
194 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000195 std::error_code EC =
196 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000197 if (EC) {
198 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000199 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000200 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000201
Shuxin Yang1826ae22013-08-12 21:07:31 +0000202 // generate object file
203 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000204
Rafael Espindola0b385c72013-09-30 16:39:19 +0000205 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
206 disableGVNLoadPRE, errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000207 objFile.os().close();
208 if (objFile.os().has_error()) {
209 objFile.os().clear_error();
210 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000211 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000212 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000213
Shuxin Yang1826ae22013-08-12 21:07:31 +0000214 objFile.keep();
215 if (!genResult) {
216 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000217 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000218 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000219
Rafael Espindolac80c9692013-09-04 17:44:24 +0000220 NativeObjectPath = Filename.c_str();
221 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000222 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000223}
224
Rafael Espindola0b385c72013-09-30 16:39:19 +0000225const void* LTOCodeGenerator::compile(size_t* length,
226 bool disableOpt,
227 bool disableInline,
228 bool disableGVNLoadPRE,
229 std::string& errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000230 const char *name;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000231 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
232 errMsg))
Craig Topper2617dcc2014-04-15 06:32:26 +0000233 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000234
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000235 // remove old buffer if compile() called twice
Rafael Espindolac80c9692013-09-04 17:44:24 +0000236 delete NativeObjectFile;
Nick Kledzik91a6dcf2008-02-27 22:25:36 +0000237
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000238 // read .o file into memory buffer
Ahmed Charles56440fd2014-03-06 05:51:42 +0000239 std::unique_ptr<MemoryBuffer> BuffPtr;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000240 if (std::error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000241 errMsg = ec.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000242 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000243 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000244 }
Ahmed Charles96c9d952014-03-05 10:19:29 +0000245 NativeObjectFile = BuffPtr.release();
Rafael Espindolafac373c2011-02-24 21:04:06 +0000246
Shuxin Yang1826ae22013-08-12 21:07:31 +0000247 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000248 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000249
Shuxin Yang1826ae22013-08-12 21:07:31 +0000250 // return buffer, unless error
Craig Topper2617dcc2014-04-15 06:32:26 +0000251 if (!NativeObjectFile)
252 return nullptr;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000253 *length = NativeObjectFile->getBufferSize();
254 return NativeObjectFile->getBufferStart();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000255}
256
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000257bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000258 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000259 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000260
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000261 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000262 if (TripleStr.empty())
263 TripleStr = sys::getDefaultTargetTriple();
264 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000265
Bill Wendling45f74e32012-08-06 22:52:45 +0000266 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000267 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Craig Topper2617dcc2014-04-15 06:32:26 +0000268 if (!march)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000269 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000270
Bill Wendling45f74e32012-08-06 22:52:45 +0000271 // The relocation model is actually a static member of TargetMachine and
272 // needs to be set before the TargetMachine is instantiated.
273 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000274 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000275 case LTO_CODEGEN_PIC_MODEL_STATIC:
276 RelocModel = Reloc::Static;
277 break;
278 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
279 RelocModel = Reloc::PIC_;
280 break;
281 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
282 RelocModel = Reloc::DynamicNoPIC;
283 break;
James Molloy951e5292014-04-14 13:54:16 +0000284 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
285 // RelocModel is already the default, so leave it that way.
286 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000287 }
Bill Wendling45f74e32012-08-06 22:52:45 +0000288
Tom Roederfd1bc602014-04-25 21:46:51 +0000289 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
290 // the default set of features.
291 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000292 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendling45f74e32012-08-06 22:52:45 +0000293 std::string FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000294 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000295 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000296 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000297 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000298 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000299 MCpu = "yonah";
Tim Northover3b0846e2014-05-24 12:50:23 +0000300 else if (Triple.getArch() == llvm::Triple::arm64 ||
301 Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000302 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000303 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000304
Rafael Espindolac80c9692013-09-04 17:44:24 +0000305 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
306 RelocModel, CodeModel::Default,
307 CodeGenOpt::Aggressive);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000308 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000309}
310
Bill Wendling0e1824c2012-03-31 11:15:43 +0000311void LTOCodeGenerator::
312applyRestriction(GlobalValue &GV,
Justin Bognerb10a5202013-11-12 21:44:01 +0000313 const ArrayRef<StringRef> &Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000314 std::vector<const char*> &MustPreserveList,
315 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
316 Mangler &Mangler) {
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000317 // There are no restrictions to apply to declarations.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000318 if (GV.isDeclaration())
319 return;
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000320
321 // There is nothing more restrictive than private linkage.
322 if (GV.hasPrivateLinkage())
323 return;
324
325 SmallString<64> Buffer;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000326 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000327
Rafael Espindolac80c9692013-09-04 17:44:24 +0000328 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000329 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000330 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000331 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000332
333 // Conservatively append user-supplied runtime library functions to
334 // llvm.compiler.used. These could be internalized and deleted by
335 // optimizations like -globalopt, causing problems when later optimizations
336 // add new library calls (e.g., llvm.memset => memset and printf => puts).
337 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
338 if (isa<Function>(GV) &&
339 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
340 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000341}
342
343static void findUsedValues(GlobalVariable *LLVMUsed,
344 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000345 if (!LLVMUsed) return;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000346
Rafael Espindolacc111b22013-04-24 17:54:35 +0000347 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000348 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000349 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000350 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000351 UsedValues.insert(GV);
352}
353
Justin Bognerb10a5202013-11-12 21:44:01 +0000354static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
355 const TargetLibraryInfo& TLI,
356 const TargetLowering *Lowering)
357{
358 // TargetLibraryInfo has info on C runtime library calls on the current
359 // target.
360 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
361 I != E; ++I) {
362 LibFunc::Func F = static_cast<LibFunc::Func>(I);
363 if (TLI.has(F))
364 Libcalls.push_back(TLI.getName(F));
365 }
366
367 // TargetLowering has info on library calls that CodeGen expects to be
368 // available, both from the C runtime and compiler-rt.
369 if (Lowering)
370 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
371 I != E; ++I)
372 if (const char *Name
373 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
374 Libcalls.push_back(Name);
375
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000376 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000377 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
378 Libcalls.end());
379}
380
Chris Lattner2eff5052010-03-12 18:44:54 +0000381void LTOCodeGenerator::applyScopeRestrictions() {
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000382 if (ScopeRestrictionsDone)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000383 return;
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000384 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000385
Chris Lattner2eff5052010-03-12 18:44:54 +0000386 // Start off with a verification pass.
387 PassManager passes;
388 passes.add(createVerifierPass());
Duncan P. N. Exon Smith6ef5f282014-04-15 16:27:38 +0000389 passes.add(createDebugInfoVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000390
Bill Wendling39d942b2012-03-31 10:50:14 +0000391 // mark which symbols can not be internalized
Rafael Espindola58873562014-01-03 19:21:54 +0000392 Mangler Mangler(TargetMach->getDataLayout());
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000393 std::vector<const char*> MustPreserveList;
394 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000395 std::vector<StringRef> Libcalls;
396 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
397 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000398
399 for (Module::iterator f = mergedModule->begin(),
400 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000401 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000402 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000403 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000404 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000405 for (Module::alias_iterator a = mergedModule->alias_begin(),
406 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000407 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000408
409 GlobalVariable *LLVMCompilerUsed =
410 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000411 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000412 if (LLVMCompilerUsed)
413 LLVMCompilerUsed->eraseFromParent();
414
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000415 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000416 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000417 std::vector<Constant*> asmUsed2;
Rafael Espindola9c8c96f2014-05-05 20:06:41 +0000418 for (auto *GV : AsmUsed) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000419 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
420 asmUsed2.push_back(c);
421 }
422
423 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
424 LLVMCompilerUsed =
425 new llvm::GlobalVariable(*mergedModule, ATy, false,
426 llvm::GlobalValue::AppendingLinkage,
427 llvm::ConstantArray::get(ATy, asmUsed2),
428 "llvm.compiler.used");
429
430 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000431 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000432
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000433 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000434
Chris Lattner2eff5052010-03-12 18:44:54 +0000435 // apply scope restrictions
436 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000437
Rafael Espindolac80c9692013-09-04 17:44:24 +0000438 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000439}
440
Nick Kledzik07b4a622008-02-26 20:26:43 +0000441/// Optimize merged modules using various IPO passes
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000442bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000443 bool DisableOpt,
444 bool DisableInline,
445 bool DisableGVNLoadPRE,
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000446 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000447 if (!this->determineTarget(errMsg))
448 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000449
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000450 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000451
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000452 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000453 this->applyScopeRestrictions();
454
Bill Wendling0e1824c2012-03-31 11:15:43 +0000455 // Instantiate the pass manager to organize the passes.
456 PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000457
Bill Wendling0e1824c2012-03-31 11:15:43 +0000458 // Start off with a verification pass.
459 passes.add(createVerifierPass());
Duncan P. N. Exon Smith6ef5f282014-04-15 16:27:38 +0000460 passes.add(createDebugInfoVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000461
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000462 // Add an appropriate DataLayout instance for this module...
Rafael Espindola339430f2014-02-25 23:25:17 +0000463 mergedModule->setDataLayout(TargetMach->getDataLayout());
464 passes.add(new DataLayoutPass(mergedModule));
Yi Jiang53823be2013-12-12 01:37:39 +0000465
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000466 // Add appropriate TargetLibraryInfo for this module.
Yi Jiang53823be2013-12-12 01:37:39 +0000467 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
468
Rafael Espindolac80c9692013-09-04 17:44:24 +0000469 TargetMach->addAnalysisPasses(passes);
Bill Wendling39d942b2012-03-31 10:50:14 +0000470
Rafael Espindola0ecb8fa2012-04-16 10:58:38 +0000471 // Enabling internalize here would use its AllButMain variant. It
472 // keeps only main if it exists and does nothing for libraries. Instead
473 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000474 if (!DisableOpt)
Bill Wendlingc7e0a042013-02-28 14:11:10 +0000475 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling4a8fc8f2012-12-10 21:33:45 +0000476 /*Internalize=*/false,
Bill Wendling932b9922012-04-02 22:16:50 +0000477 !DisableInline,
478 DisableGVNLoadPRE);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000479
Bill Wendling0e1824c2012-03-31 11:15:43 +0000480 // Make sure everything is still good.
481 passes.add(createVerifierPass());
Duncan P. N. Exon Smith6ef5f282014-04-15 16:27:38 +0000482 passes.add(createDebugInfoVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000483
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000484 PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000485
Rafael Espindola339430f2014-02-25 23:25:17 +0000486 codeGenPasses.add(new DataLayoutPass(mergedModule));
Nick Kledzik07b4a622008-02-26 20:26:43 +0000487
Bill Wendling0e1824c2012-03-31 11:15:43 +0000488 formatted_raw_ostream Out(out);
Dan Gohmana2233f22010-09-01 14:20:41 +0000489
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000490 // If the bitcode files contain ARC code and were compiled with optimization,
491 // the ObjCARCContractPass must be run, so do it unconditionally here.
492 codeGenPasses.add(createObjCARCContractPass());
493
Rafael Espindolac80c9692013-09-04 17:44:24 +0000494 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
495 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000496 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000497 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000498 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000499
Bill Wendling0e1824c2012-03-31 11:15:43 +0000500 // Run our queue of passes all at once now, efficiently.
501 passes.run(*mergedModule);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000502
Bill Wendling0e1824c2012-03-31 11:15:43 +0000503 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000504 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000505
Shuxin Yang95866fa2013-08-06 21:51:21 +0000506 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000507}
508
Bill Wendling534a6582012-03-31 10:49:43 +0000509/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
510/// LTO problems.
511void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
512 for (std::pair<StringRef, StringRef> o = getToken(options);
513 !o.first.empty(); o = getToken(o.second)) {
514 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
515 // that.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000516 if (CodegenOptions.empty())
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000517 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindolac80c9692013-09-04 17:44:24 +0000518 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendling534a6582012-03-31 10:49:43 +0000519 }
Nick Kledzikc2323472008-07-08 21:14:10 +0000520}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000521
522void LTOCodeGenerator::parseCodeGenDebugOptions() {
523 // if options were requested, set them
524 if (!CodegenOptions.empty())
525 cl::ParseCommandLineOptions(CodegenOptions.size(),
526 const_cast<char **>(&CodegenOptions[0]));
527}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000528
529void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
530 void *Context) {
531 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
532}
533
534void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
535 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
536 lto_codegen_diagnostic_severity_t Severity;
537 switch (DI.getSeverity()) {
538 case DS_Error:
539 Severity = LTO_DS_ERROR;
540 break;
541 case DS_Warning:
542 Severity = LTO_DS_WARNING;
543 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000544 case DS_Remark:
545 Severity = LTO_DS_REMARK;
546 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000547 case DS_Note:
548 Severity = LTO_DS_NOTE;
549 break;
550 }
551 // Create the string that will be reported to the external diagnostic handler.
552 std::string MsgStorage;
553 raw_string_ostream Stream(MsgStorage);
554 DiagnosticPrinterRawOStream DP(Stream);
555 DI.print(DP);
556 Stream.flush();
557
558 // If this method has been called it means someone has set up an external
559 // diagnostic handler. Assert on that.
560 assert(DiagHandler && "Invalid diagnostic handler");
561 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
562}
563
564void
565LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
566 void *Ctxt) {
567 this->DiagHandler = DiagHandler;
568 this->DiagContext = Ctxt;
569 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000570 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000571 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
572 // diagnostic to the external DiagHandler.
573 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
574}