blob: 27b8776406531fa5b7df009fc7ae6d0b52bd784f [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"
Chandler Carruth62d42152015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth93dcdc42015-01-31 11:17:59 +000019#include "llvm/Analysis/TargetTransformInfo.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000020#include "llvm/Bitcode/ReaderWriter.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000021#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000022#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000026#include "llvm/IR/DiagnosticInfo.h"
27#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/LLVMContext.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000029#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000032#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000033#include "llvm/LTO/LTOModule.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000034#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000035#include "llvm/MC/MCAsmInfo.h"
36#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000037#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/PassManager.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000039#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000040#include "llvm/Support/FileSystem.h"
David Greenea31f96c2009-07-14 20:18:05 +000041#include "llvm/Support/FormattedStream.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000042#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000044#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000045#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000047#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000048#include "llvm/Support/raw_ostream.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000049#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000050#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000051#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000052#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000053#include "llvm/Transforms/IPO.h"
54#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000055#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000056#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000057using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000058
Bill Wendling534a6582012-03-31 10:49:43 +000059const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000060#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000061 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000062#else
Bill Wendling534a6582012-03-31 10:49:43 +000063 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000064#endif
65}
66
Bill Wendling39d942b2012-03-31 10:50:14 +000067LTOCodeGenerator::LTOCodeGenerator()
Duncan P. N. Exon Smithde5e32b2014-11-11 23:03:29 +000068 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
69 initialize();
70}
71
72LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
73 : OwnedContext(std::move(Context)), Context(*OwnedContext),
74 IRLinker(new Module("ld-temp.o", *OwnedContext)) {
75 initialize();
76}
77
78void LTOCodeGenerator::initialize() {
79 TargetMach = nullptr;
80 EmitDwarfDebugInfo = false;
81 ScopeRestrictionsDone = false;
82 CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
83 DiagHandler = nullptr;
84 DiagContext = nullptr;
85
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000086 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000087}
88
Bill Wendling534a6582012-03-31 10:49:43 +000089LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindolac80c9692013-09-04 17:44:24 +000090 delete TargetMach;
Craig Topper2617dcc2014-04-15 06:32:26 +000091 TargetMach = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +000092
Rafael Espindola80df4bb2014-05-03 15:28:13 +000093 IRLinker.deleteModule();
Bill Wendling534a6582012-03-31 10:49:43 +000094
Rafael Espindolac80c9692013-09-04 17:44:24 +000095 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
96 E = CodegenOptions.end();
97 I != E; ++I)
Bill Wendling534a6582012-03-31 10:49:43 +000098 free(*I);
Nick Kledzik07b4a622008-02-26 20:26:43 +000099}
100
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000101// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +0000102// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000103// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000104void LTOCodeGenerator::initializeLTOPasses() {
105 PassRegistry &R = *PassRegistry::getPassRegistry();
106
107 initializeInternalizePassPass(R);
108 initializeIPSCCPPass(R);
109 initializeGlobalOptPass(R);
110 initializeConstantMergePass(R);
111 initializeDAHPass(R);
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000112 initializeInstructionCombiningPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000113 initializeSimpleInlinerPass(R);
114 initializePruneEHPass(R);
115 initializeGlobalDCEPass(R);
116 initializeArgPromotionPass(R);
117 initializeJumpThreadingPass(R);
118 initializeSROAPass(R);
119 initializeSROA_DTPass(R);
120 initializeSROA_SSAUpPass(R);
121 initializeFunctionAttrsPass(R);
122 initializeGlobalsModRefPass(R);
123 initializeLICMPass(R);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000124 initializeMergedLoadStoreMotionPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000125 initializeGVNPass(R);
126 initializeMemCpyOptPass(R);
127 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000128 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000129}
130
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000131bool LTOCodeGenerator::addModule(LTOModule *mod) {
Duncan P. N. Exon Smith94198632014-11-11 23:13:10 +0000132 assert(&mod->getModule().getContext() == &Context &&
133 "Expected module in same context");
134
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000135 bool ret = IRLinker.linkInModule(&mod->getModule());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000136
137 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
138 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000139 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000140
Shuxin Yangb6696a92013-08-07 05:19:23 +0000141 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000142}
Bill Wendling39d942b2012-03-31 10:50:14 +0000143
Rafael Espindola0b385c72013-09-30 16:39:19 +0000144void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
Rafael Espindola70d3c202014-06-19 22:27:46 +0000145 Options = options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000146}
147
Shuxin Yangb6696a92013-08-07 05:19:23 +0000148void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000149 switch (debug) {
150 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000151 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000152 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000153
Bill Wendling0e1824c2012-03-31 11:15:43 +0000154 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000155 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000156 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000157 }
158 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000159}
160
Shuxin Yangb6696a92013-08-07 05:19:23 +0000161void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000162 switch (model) {
163 case LTO_CODEGEN_PIC_MODEL_STATIC:
164 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
165 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
James Molloy951e5292014-04-14 13:54:16 +0000166 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000167 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000168 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000169 }
170 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000171}
172
Chris Lattner69733952009-08-23 07:49:08 +0000173bool LTOCodeGenerator::writeMergedModules(const char *path,
174 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000175 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000176 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000177
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000178 // mark which symbols can not be internalized
179 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000180
Chris Lattner69733952009-08-23 07:49:08 +0000181 // create output file
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000182 std::error_code EC;
183 tool_output_file Out(path, EC, sys::fs::F_None);
184 if (EC) {
Chris Lattner69733952009-08-23 07:49:08 +0000185 errMsg = "could not open bitcode file for writing: ";
186 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000187 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000188 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000189
Chris Lattner69733952009-08-23 07:49:08 +0000190 // write bitcode to it
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000191 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
Dan Gohmana2233f22010-09-01 14:20:41 +0000192 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000193
Dan Gohmana2233f22010-09-01 14:20:41 +0000194 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000195 errMsg = "could not write bitcode file: ";
196 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000197 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000198 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000199 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000200
Dan Gohman8525fe72010-08-20 16:59:15 +0000201 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000202 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000203}
204
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000205bool LTOCodeGenerator::compile_to_file(const char** name,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000206 bool disableOpt,
207 bool disableInline,
208 bool disableGVNLoadPRE,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000209 bool disableVectorization,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000210 std::string& errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000211 // make unique temp .o file to put generated object file
212 SmallString<128> Filename;
213 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000214 std::error_code EC =
215 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000216 if (EC) {
217 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000218 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000219 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000220
Shuxin Yang1826ae22013-08-12 21:07:31 +0000221 // generate object file
222 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000223
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000224 bool genResult =
225 generateObjectFile(objFile.os(), disableOpt, disableInline,
226 disableGVNLoadPRE, disableVectorization, errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000227 objFile.os().close();
228 if (objFile.os().has_error()) {
229 objFile.os().clear_error();
230 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000231 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000232 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000233
Shuxin Yang1826ae22013-08-12 21:07:31 +0000234 objFile.keep();
235 if (!genResult) {
236 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000237 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000238 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000239
Rafael Espindolac80c9692013-09-04 17:44:24 +0000240 NativeObjectPath = Filename.c_str();
241 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000242 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000243}
244
Rafael Espindola0b385c72013-09-30 16:39:19 +0000245const void* LTOCodeGenerator::compile(size_t* length,
246 bool disableOpt,
247 bool disableInline,
248 bool disableGVNLoadPRE,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000249 bool disableVectorization,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000250 std::string& errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000251 const char *name;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000252 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000253 disableVectorization, errMsg))
Craig Topper2617dcc2014-04-15 06:32:26 +0000254 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000255
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000256 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000257 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
258 MemoryBuffer::getFile(name, -1, false);
259 if (std::error_code EC = BufferOrErr.getError()) {
260 errMsg = EC.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000261 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000262 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000263 }
David Blaikie78fdec52014-09-02 18:21:06 +0000264 NativeObjectFile = std::move(*BufferOrErr);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000265
Shuxin Yang1826ae22013-08-12 21:07:31 +0000266 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000267 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000268
Shuxin Yang1826ae22013-08-12 21:07:31 +0000269 // return buffer, unless error
Craig Topper2617dcc2014-04-15 06:32:26 +0000270 if (!NativeObjectFile)
271 return nullptr;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000272 *length = NativeObjectFile->getBufferSize();
273 return NativeObjectFile->getBufferStart();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000274}
275
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000276bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000277 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000278 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000279
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000280 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000281 if (TripleStr.empty())
282 TripleStr = sys::getDefaultTargetTriple();
283 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000284
Bill Wendling45f74e32012-08-06 22:52:45 +0000285 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000286 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Craig Topper2617dcc2014-04-15 06:32:26 +0000287 if (!march)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000288 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000289
Bill Wendling45f74e32012-08-06 22:52:45 +0000290 // The relocation model is actually a static member of TargetMachine and
291 // needs to be set before the TargetMachine is instantiated.
292 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000293 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000294 case LTO_CODEGEN_PIC_MODEL_STATIC:
295 RelocModel = Reloc::Static;
296 break;
297 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
298 RelocModel = Reloc::PIC_;
299 break;
300 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
301 RelocModel = Reloc::DynamicNoPIC;
302 break;
James Molloy951e5292014-04-14 13:54:16 +0000303 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
304 // RelocModel is already the default, so leave it that way.
305 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000306 }
Bill Wendling45f74e32012-08-06 22:52:45 +0000307
Tom Roederfd1bc602014-04-25 21:46:51 +0000308 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
309 // the default set of features.
310 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000311 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendling45f74e32012-08-06 22:52:45 +0000312 std::string FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000313 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000314 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000315 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000316 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000317 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000318 MCpu = "yonah";
Tim Northovere19bed72014-07-23 12:32:47 +0000319 else if (Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000320 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000321 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000322
Rafael Espindolac80c9692013-09-04 17:44:24 +0000323 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
324 RelocModel, CodeModel::Default,
325 CodeGenOpt::Aggressive);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000326 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000327}
328
Bill Wendling0e1824c2012-03-31 11:15:43 +0000329void LTOCodeGenerator::
330applyRestriction(GlobalValue &GV,
Craig Topper3af97222014-08-27 05:25:00 +0000331 ArrayRef<StringRef> Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000332 std::vector<const char*> &MustPreserveList,
Craig Topper71b7b682014-08-21 05:55:13 +0000333 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000334 Mangler &Mangler) {
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000335 // There are no restrictions to apply to declarations.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000336 if (GV.isDeclaration())
337 return;
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000338
339 // There is nothing more restrictive than private linkage.
340 if (GV.hasPrivateLinkage())
341 return;
342
343 SmallString<64> Buffer;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000344 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000345
Rafael Espindolac80c9692013-09-04 17:44:24 +0000346 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000347 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000348 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000349 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000350
351 // Conservatively append user-supplied runtime library functions to
352 // llvm.compiler.used. These could be internalized and deleted by
353 // optimizations like -globalopt, causing problems when later optimizations
354 // add new library calls (e.g., llvm.memset => memset and printf => puts).
355 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
356 if (isa<Function>(GV) &&
357 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
358 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000359}
360
361static void findUsedValues(GlobalVariable *LLVMUsed,
Craig Topper71b7b682014-08-21 05:55:13 +0000362 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000363 if (!LLVMUsed) return;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000364
Rafael Espindolacc111b22013-04-24 17:54:35 +0000365 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000366 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000367 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000368 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000369 UsedValues.insert(GV);
370}
371
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000372// Collect names of runtime library functions. User-defined functions with the
373// same names are added to llvm.compiler.used to prevent them from being
374// deleted by optimizations.
Justin Bognerb10a5202013-11-12 21:44:01 +0000375static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
376 const TargetLibraryInfo& TLI,
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000377 const Module &Mod,
378 const TargetMachine &TM) {
Justin Bognerb10a5202013-11-12 21:44:01 +0000379 // TargetLibraryInfo has info on C runtime library calls on the current
380 // target.
381 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
382 I != E; ++I) {
383 LibFunc::Func F = static_cast<LibFunc::Func>(I);
384 if (TLI.has(F))
385 Libcalls.push_back(TLI.getName(F));
386 }
387
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000388 SmallPtrSet<const TargetLowering *, 1> TLSet;
389
390 for (const Function &F : Mod) {
391 const TargetLowering *Lowering =
392 TM.getSubtargetImpl(F)->getTargetLowering();
393
394 if (Lowering && TLSet.insert(Lowering).second)
395 // TargetLowering has info on library calls that CodeGen expects to be
396 // available, both from the C runtime and compiler-rt.
397 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
398 I != E; ++I)
399 if (const char *Name =
400 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
401 Libcalls.push_back(Name);
402 }
Justin Bognerb10a5202013-11-12 21:44:01 +0000403
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000404 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000405 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
406 Libcalls.end());
407}
408
Chris Lattner2eff5052010-03-12 18:44:54 +0000409void LTOCodeGenerator::applyScopeRestrictions() {
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000410 if (ScopeRestrictionsDone)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000411 return;
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000412 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000413
Chris Lattner2eff5052010-03-12 18:44:54 +0000414 // Start off with a verification pass.
415 PassManager passes;
416 passes.add(createVerifierPass());
Duncan P. N. Exon Smith6ef5f282014-04-15 16:27:38 +0000417 passes.add(createDebugInfoVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000418
Bill Wendling39d942b2012-03-31 10:50:14 +0000419 // mark which symbols can not be internalized
Eric Christopher8b770652015-01-26 19:03:15 +0000420 Mangler Mangler(TargetMach->getDataLayout());
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000421 std::vector<const char*> MustPreserveList;
422 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000423 std::vector<StringRef> Libcalls;
Chandler Carruthc0291862015-01-24 02:06:09 +0000424 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
425 TargetLibraryInfo TLI(TLII);
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000426
427 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000428
429 for (Module::iterator f = mergedModule->begin(),
430 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000431 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000432 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000433 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000434 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000435 for (Module::alias_iterator a = mergedModule->alias_begin(),
436 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000437 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000438
439 GlobalVariable *LLVMCompilerUsed =
440 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000441 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000442 if (LLVMCompilerUsed)
443 LLVMCompilerUsed->eraseFromParent();
444
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000445 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000446 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000447 std::vector<Constant*> asmUsed2;
Rafael Espindola9c8c96f2014-05-05 20:06:41 +0000448 for (auto *GV : AsmUsed) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000449 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
450 asmUsed2.push_back(c);
451 }
452
453 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
454 LLVMCompilerUsed =
455 new llvm::GlobalVariable(*mergedModule, ATy, false,
456 llvm::GlobalValue::AppendingLinkage,
457 llvm::ConstantArray::get(ATy, asmUsed2),
458 "llvm.compiler.used");
459
460 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000461 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000462
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000463 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000464
Chris Lattner2eff5052010-03-12 18:44:54 +0000465 // apply scope restrictions
466 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000467
Rafael Espindolac80c9692013-09-04 17:44:24 +0000468 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000469}
470
Nick Kledzik07b4a622008-02-26 20:26:43 +0000471/// Optimize merged modules using various IPO passes
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000472bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000473 bool DisableOpt,
474 bool DisableInline,
475 bool DisableGVNLoadPRE,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000476 bool DisableVectorization,
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000477 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000478 if (!this->determineTarget(errMsg))
479 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000480
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000481 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000482
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000483 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000484 this->applyScopeRestrictions();
485
Bill Wendling0e1824c2012-03-31 11:15:43 +0000486 // Instantiate the pass manager to organize the passes.
487 PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000488
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000489 // Add an appropriate DataLayout instance for this module...
Eric Christopher8b770652015-01-26 19:03:15 +0000490 mergedModule->setDataLayout(TargetMach->getDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000491
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000492 passes.add(new DataLayoutPass());
Chandler Carruth5ec2b1d2015-02-01 12:26:09 +0000493 passes.add(
494 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000495
Rafael Espindola216e0c02014-08-21 18:49:52 +0000496 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000497 PassManagerBuilder PMB;
498 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000499 PMB.LoopVectorize = !DisableVectorization;
500 PMB.SLPVectorize = !DisableVectorization;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000501 if (!DisableInline)
502 PMB.Inliner = createFunctionInliningPass();
Chandler Carruthc0291862015-01-24 02:06:09 +0000503 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
Rafael Espindola7cebf362014-08-21 20:03:44 +0000504 if (DisableOpt)
505 PMB.OptLevel = 0;
506 PMB.VerifyInput = true;
507 PMB.VerifyOutput = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000508
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000509 PMB.populateLTOPassManager(passes);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000510
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000511 PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000512
Rafael Espindolac435adc2014-09-10 21:27:43 +0000513 codeGenPasses.add(new DataLayoutPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000514
Bill Wendling0e1824c2012-03-31 11:15:43 +0000515 formatted_raw_ostream Out(out);
Dan Gohmana2233f22010-09-01 14:20:41 +0000516
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000517 // If the bitcode files contain ARC code and were compiled with optimization,
518 // the ObjCARCContractPass must be run, so do it unconditionally here.
519 codeGenPasses.add(createObjCARCContractPass());
520
Rafael Espindolac80c9692013-09-04 17:44:24 +0000521 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
522 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000523 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000524 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000525 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000526
Bill Wendling0e1824c2012-03-31 11:15:43 +0000527 // Run our queue of passes all at once now, efficiently.
528 passes.run(*mergedModule);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000529
Bill Wendling0e1824c2012-03-31 11:15:43 +0000530 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000531 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000532
Shuxin Yang95866fa2013-08-06 21:51:21 +0000533 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000534}
535
Bill Wendling534a6582012-03-31 10:49:43 +0000536/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
537/// LTO problems.
538void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
539 for (std::pair<StringRef, StringRef> o = getToken(options);
540 !o.first.empty(); o = getToken(o.second)) {
541 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
542 // that.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000543 if (CodegenOptions.empty())
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000544 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindolac80c9692013-09-04 17:44:24 +0000545 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendling534a6582012-03-31 10:49:43 +0000546 }
Nick Kledzikc2323472008-07-08 21:14:10 +0000547}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000548
549void LTOCodeGenerator::parseCodeGenDebugOptions() {
550 // if options were requested, set them
551 if (!CodegenOptions.empty())
552 cl::ParseCommandLineOptions(CodegenOptions.size(),
553 const_cast<char **>(&CodegenOptions[0]));
554}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000555
556void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
557 void *Context) {
558 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
559}
560
561void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
562 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
563 lto_codegen_diagnostic_severity_t Severity;
564 switch (DI.getSeverity()) {
565 case DS_Error:
566 Severity = LTO_DS_ERROR;
567 break;
568 case DS_Warning:
569 Severity = LTO_DS_WARNING;
570 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000571 case DS_Remark:
572 Severity = LTO_DS_REMARK;
573 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000574 case DS_Note:
575 Severity = LTO_DS_NOTE;
576 break;
577 }
578 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000579 std::string MsgStorage;
580 raw_string_ostream Stream(MsgStorage);
581 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000582 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000583 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000584
585 // If this method has been called it means someone has set up an external
586 // diagnostic handler. Assert on that.
587 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000588 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000589}
590
591void
592LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
593 void *Ctxt) {
594 this->DiagHandler = DiagHandler;
595 this->DiagContext = Ctxt;
596 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000597 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000598 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
599 // diagnostic to the external DiagHandler.
Duncan P. N. Exon Smithf02fe702014-10-02 21:11:04 +0000600 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
601 /* RespectFilters */ true);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000602}