blob: 54f5a6b4c506641aa5b877807d2a5d1e5a1cca9f [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"
Eric Christopherd9134482014-08-04 21:25:23 +000051#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000052#include "llvm/Transforms/IPO.h"
53#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000054#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000055#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000056using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000057
Bill Wendling534a6582012-03-31 10:49:43 +000058const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000059#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000060 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000061#else
Bill Wendling534a6582012-03-31 10:49:43 +000062 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000063#endif
64}
65
Bill Wendling39d942b2012-03-31 10:50:14 +000066LTOCodeGenerator::LTOCodeGenerator()
Rafael Espindola80df4bb2014-05-03 15:28:13 +000067 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)),
Craig Topper2617dcc2014-04-15 06:32:26 +000068 TargetMach(nullptr), EmitDwarfDebugInfo(false),
69 ScopeRestrictionsDone(false), CodeModel(LTO_CODEGEN_PIC_MODEL_DEFAULT),
70 NativeObjectFile(nullptr), DiagHandler(nullptr), DiagContext(nullptr) {
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000071 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000072}
73
Bill Wendling534a6582012-03-31 10:49:43 +000074LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindolac80c9692013-09-04 17:44:24 +000075 delete TargetMach;
76 delete NativeObjectFile;
Craig Topper2617dcc2014-04-15 06:32:26 +000077 TargetMach = nullptr;
78 NativeObjectFile = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +000079
Rafael Espindola80df4bb2014-05-03 15:28:13 +000080 IRLinker.deleteModule();
Bill Wendling534a6582012-03-31 10:49:43 +000081
Rafael Espindolac80c9692013-09-04 17:44:24 +000082 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
83 E = CodegenOptions.end();
84 I != E; ++I)
Bill Wendling534a6582012-03-31 10:49:43 +000085 free(*I);
Nick Kledzik07b4a622008-02-26 20:26:43 +000086}
87
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000088// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000089// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +000090// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000091void LTOCodeGenerator::initializeLTOPasses() {
92 PassRegistry &R = *PassRegistry::getPassRegistry();
93
94 initializeInternalizePassPass(R);
95 initializeIPSCCPPass(R);
96 initializeGlobalOptPass(R);
97 initializeConstantMergePass(R);
98 initializeDAHPass(R);
99 initializeInstCombinerPass(R);
100 initializeSimpleInlinerPass(R);
101 initializePruneEHPass(R);
102 initializeGlobalDCEPass(R);
103 initializeArgPromotionPass(R);
104 initializeJumpThreadingPass(R);
105 initializeSROAPass(R);
106 initializeSROA_DTPass(R);
107 initializeSROA_SSAUpPass(R);
108 initializeFunctionAttrsPass(R);
109 initializeGlobalsModRefPass(R);
110 initializeLICMPass(R);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000111 initializeMergedLoadStoreMotionPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000112 initializeGVNPass(R);
113 initializeMemCpyOptPass(R);
114 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000115 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000116}
117
Bill Wendling0e1824c2012-03-31 11:15:43 +0000118bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindoladddd1fd2014-07-04 18:40:36 +0000119 bool ret = IRLinker.linkInModule(&mod->getModule(), &errMsg);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000120
121 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
122 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000123 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000124
Shuxin Yangb6696a92013-08-07 05:19:23 +0000125 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000126}
Bill Wendling39d942b2012-03-31 10:50:14 +0000127
Rafael Espindola0b385c72013-09-30 16:39:19 +0000128void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
Rafael Espindola70d3c202014-06-19 22:27:46 +0000129 Options = options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000130}
131
Shuxin Yangb6696a92013-08-07 05:19:23 +0000132void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000133 switch (debug) {
134 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000135 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000136 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000137
Bill Wendling0e1824c2012-03-31 11:15:43 +0000138 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000139 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000140 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000141 }
142 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000143}
144
Shuxin Yangb6696a92013-08-07 05:19:23 +0000145void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000146 switch (model) {
147 case LTO_CODEGEN_PIC_MODEL_STATIC:
148 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
149 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
James Molloy951e5292014-04-14 13:54:16 +0000150 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000151 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000152 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000153 }
154 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000155}
156
Chris Lattner69733952009-08-23 07:49:08 +0000157bool LTOCodeGenerator::writeMergedModules(const char *path,
158 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000159 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000160 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000161
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000162 // mark which symbols can not be internalized
163 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000164
Chris Lattner69733952009-08-23 07:49:08 +0000165 // create output file
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000166 std::error_code EC;
167 tool_output_file Out(path, EC, sys::fs::F_None);
168 if (EC) {
Chris Lattner69733952009-08-23 07:49:08 +0000169 errMsg = "could not open bitcode file for writing: ";
170 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000171 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000172 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000173
Chris Lattner69733952009-08-23 07:49:08 +0000174 // write bitcode to it
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000175 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
Dan Gohmana2233f22010-09-01 14:20:41 +0000176 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000177
Dan Gohmana2233f22010-09-01 14:20:41 +0000178 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000179 errMsg = "could not write bitcode file: ";
180 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000181 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000182 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000183 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000184
Dan Gohman8525fe72010-08-20 16:59:15 +0000185 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000186 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000187}
188
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000189bool LTOCodeGenerator::compile_to_file(const char** name,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000190 bool disableOpt,
191 bool disableInline,
192 bool disableGVNLoadPRE,
193 std::string& errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000194 // make unique temp .o file to put generated object file
195 SmallString<128> Filename;
196 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000197 std::error_code EC =
198 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000199 if (EC) {
200 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000201 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000202 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000203
Shuxin Yang1826ae22013-08-12 21:07:31 +0000204 // generate object file
205 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000206
Rafael Espindola0b385c72013-09-30 16:39:19 +0000207 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
208 disableGVNLoadPRE, errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000209 objFile.os().close();
210 if (objFile.os().has_error()) {
211 objFile.os().clear_error();
212 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000213 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000214 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000215
Shuxin Yang1826ae22013-08-12 21:07:31 +0000216 objFile.keep();
217 if (!genResult) {
218 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000219 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000220 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000221
Rafael Espindolac80c9692013-09-04 17:44:24 +0000222 NativeObjectPath = Filename.c_str();
223 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000224 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000225}
226
Rafael Espindola0b385c72013-09-30 16:39:19 +0000227const void* LTOCodeGenerator::compile(size_t* length,
228 bool disableOpt,
229 bool disableInline,
230 bool disableGVNLoadPRE,
231 std::string& errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000232 const char *name;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000233 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
234 errMsg))
Craig Topper2617dcc2014-04-15 06:32:26 +0000235 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000236
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000237 // remove old buffer if compile() called twice
Rafael Espindolac80c9692013-09-04 17:44:24 +0000238 delete NativeObjectFile;
Nick Kledzik91a6dcf2008-02-27 22:25:36 +0000239
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000240 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000241 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
242 MemoryBuffer::getFile(name, -1, false);
243 if (std::error_code EC = BufferOrErr.getError()) {
244 errMsg = EC.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000245 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000246 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000247 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000248 NativeObjectFile = BufferOrErr.get().release();
Rafael Espindolafac373c2011-02-24 21:04:06 +0000249
Shuxin Yang1826ae22013-08-12 21:07:31 +0000250 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000251 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000252
Shuxin Yang1826ae22013-08-12 21:07:31 +0000253 // return buffer, unless error
Craig Topper2617dcc2014-04-15 06:32:26 +0000254 if (!NativeObjectFile)
255 return nullptr;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000256 *length = NativeObjectFile->getBufferSize();
257 return NativeObjectFile->getBufferStart();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000258}
259
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000260bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000261 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000262 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000263
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000264 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000265 if (TripleStr.empty())
266 TripleStr = sys::getDefaultTargetTriple();
267 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000268
Bill Wendling45f74e32012-08-06 22:52:45 +0000269 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000270 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Craig Topper2617dcc2014-04-15 06:32:26 +0000271 if (!march)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000272 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000273
Bill Wendling45f74e32012-08-06 22:52:45 +0000274 // The relocation model is actually a static member of TargetMachine and
275 // needs to be set before the TargetMachine is instantiated.
276 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000277 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000278 case LTO_CODEGEN_PIC_MODEL_STATIC:
279 RelocModel = Reloc::Static;
280 break;
281 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
282 RelocModel = Reloc::PIC_;
283 break;
284 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
285 RelocModel = Reloc::DynamicNoPIC;
286 break;
James Molloy951e5292014-04-14 13:54:16 +0000287 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
288 // RelocModel is already the default, so leave it that way.
289 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000290 }
Bill Wendling45f74e32012-08-06 22:52:45 +0000291
Tom Roederfd1bc602014-04-25 21:46:51 +0000292 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
293 // the default set of features.
294 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000295 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendling45f74e32012-08-06 22:52:45 +0000296 std::string FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000297 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000298 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000299 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000300 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000301 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000302 MCpu = "yonah";
Tim Northovere19bed72014-07-23 12:32:47 +0000303 else if (Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000304 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000305 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000306
Rafael Espindolac80c9692013-09-04 17:44:24 +0000307 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
308 RelocModel, CodeModel::Default,
309 CodeGenOpt::Aggressive);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000310 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000311}
312
Bill Wendling0e1824c2012-03-31 11:15:43 +0000313void LTOCodeGenerator::
314applyRestriction(GlobalValue &GV,
Justin Bognerb10a5202013-11-12 21:44:01 +0000315 const ArrayRef<StringRef> &Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000316 std::vector<const char*> &MustPreserveList,
Craig Topper71b7b682014-08-21 05:55:13 +0000317 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000318 Mangler &Mangler) {
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000319 // There are no restrictions to apply to declarations.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000320 if (GV.isDeclaration())
321 return;
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000322
323 // There is nothing more restrictive than private linkage.
324 if (GV.hasPrivateLinkage())
325 return;
326
327 SmallString<64> Buffer;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000328 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000329
Rafael Espindolac80c9692013-09-04 17:44:24 +0000330 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000331 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000332 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000333 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000334
335 // Conservatively append user-supplied runtime library functions to
336 // llvm.compiler.used. These could be internalized and deleted by
337 // optimizations like -globalopt, causing problems when later optimizations
338 // add new library calls (e.g., llvm.memset => memset and printf => puts).
339 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
340 if (isa<Function>(GV) &&
341 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
342 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000343}
344
345static void findUsedValues(GlobalVariable *LLVMUsed,
Craig Topper71b7b682014-08-21 05:55:13 +0000346 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000347 if (!LLVMUsed) return;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000348
Rafael Espindolacc111b22013-04-24 17:54:35 +0000349 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000350 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000351 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000352 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000353 UsedValues.insert(GV);
354}
355
Justin Bognerb10a5202013-11-12 21:44:01 +0000356static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
357 const TargetLibraryInfo& TLI,
358 const TargetLowering *Lowering)
359{
360 // TargetLibraryInfo has info on C runtime library calls on the current
361 // target.
362 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
363 I != E; ++I) {
364 LibFunc::Func F = static_cast<LibFunc::Func>(I);
365 if (TLI.has(F))
366 Libcalls.push_back(TLI.getName(F));
367 }
368
369 // TargetLowering has info on library calls that CodeGen expects to be
370 // available, both from the C runtime and compiler-rt.
371 if (Lowering)
372 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
373 I != E; ++I)
374 if (const char *Name
375 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
376 Libcalls.push_back(Name);
377
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000378 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000379 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
380 Libcalls.end());
381}
382
Chris Lattner2eff5052010-03-12 18:44:54 +0000383void LTOCodeGenerator::applyScopeRestrictions() {
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000384 if (ScopeRestrictionsDone)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000385 return;
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000386 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000387
Chris Lattner2eff5052010-03-12 18:44:54 +0000388 // Start off with a verification pass.
389 PassManager passes;
390 passes.add(createVerifierPass());
Duncan P. N. Exon Smith6ef5f282014-04-15 16:27:38 +0000391 passes.add(createDebugInfoVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000392
Bill Wendling39d942b2012-03-31 10:50:14 +0000393 // mark which symbols can not be internalized
Eric Christopherd9134482014-08-04 21:25:23 +0000394 Mangler Mangler(TargetMach->getSubtargetImpl()->getDataLayout());
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000395 std::vector<const char*> MustPreserveList;
396 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000397 std::vector<StringRef> Libcalls;
398 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
Eric Christopherd9134482014-08-04 21:25:23 +0000399 accumulateAndSortLibcalls(
400 Libcalls, TLI, TargetMach->getSubtargetImpl()->getTargetLowering());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000401
402 for (Module::iterator f = mergedModule->begin(),
403 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000404 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000405 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000406 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000407 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000408 for (Module::alias_iterator a = mergedModule->alias_begin(),
409 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000410 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000411
412 GlobalVariable *LLVMCompilerUsed =
413 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000414 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000415 if (LLVMCompilerUsed)
416 LLVMCompilerUsed->eraseFromParent();
417
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000418 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000419 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000420 std::vector<Constant*> asmUsed2;
Rafael Espindola9c8c96f2014-05-05 20:06:41 +0000421 for (auto *GV : AsmUsed) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000422 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
423 asmUsed2.push_back(c);
424 }
425
426 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
427 LLVMCompilerUsed =
428 new llvm::GlobalVariable(*mergedModule, ATy, false,
429 llvm::GlobalValue::AppendingLinkage,
430 llvm::ConstantArray::get(ATy, asmUsed2),
431 "llvm.compiler.used");
432
433 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000434 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000435
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000436 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000437
Chris Lattner2eff5052010-03-12 18:44:54 +0000438 // apply scope restrictions
439 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000440
Rafael Espindolac80c9692013-09-04 17:44:24 +0000441 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000442}
443
Nick Kledzik07b4a622008-02-26 20:26:43 +0000444/// Optimize merged modules using various IPO passes
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000445bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000446 bool DisableOpt,
447 bool DisableInline,
448 bool DisableGVNLoadPRE,
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000449 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000450 if (!this->determineTarget(errMsg))
451 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000452
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000453 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000454
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000455 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000456 this->applyScopeRestrictions();
457
Bill Wendling0e1824c2012-03-31 11:15:43 +0000458 // Instantiate the pass manager to organize the passes.
459 PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000460
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000461 // Add an appropriate DataLayout instance for this module...
Eric Christopherd9134482014-08-04 21:25:23 +0000462 mergedModule->setDataLayout(TargetMach->getSubtargetImpl()->getDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000463
Rafael Espindola216e0c02014-08-21 18:49:52 +0000464 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000465 PassManagerBuilder PMB;
466 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
467 if (!DisableInline)
468 PMB.Inliner = createFunctionInliningPass();
469 PMB.LibraryInfo = new TargetLibraryInfo(TargetTriple);
470 if (DisableOpt)
471 PMB.OptLevel = 0;
472 PMB.VerifyInput = true;
473 PMB.VerifyOutput = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000474
Rafael Espindola7cebf362014-08-21 20:03:44 +0000475 PMB.populateLTOPassManager(passes, TargetMach);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000476
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000477 PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000478
Rafael Espindola339430f2014-02-25 23:25:17 +0000479 codeGenPasses.add(new DataLayoutPass(mergedModule));
Nick Kledzik07b4a622008-02-26 20:26:43 +0000480
Bill Wendling0e1824c2012-03-31 11:15:43 +0000481 formatted_raw_ostream Out(out);
Dan Gohmana2233f22010-09-01 14:20:41 +0000482
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000483 // If the bitcode files contain ARC code and were compiled with optimization,
484 // the ObjCARCContractPass must be run, so do it unconditionally here.
485 codeGenPasses.add(createObjCARCContractPass());
486
Rafael Espindolac80c9692013-09-04 17:44:24 +0000487 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
488 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000489 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000490 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000491 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000492
Bill Wendling0e1824c2012-03-31 11:15:43 +0000493 // Run our queue of passes all at once now, efficiently.
494 passes.run(*mergedModule);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000495
Bill Wendling0e1824c2012-03-31 11:15:43 +0000496 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000497 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000498
Shuxin Yang95866fa2013-08-06 21:51:21 +0000499 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000500}
501
Bill Wendling534a6582012-03-31 10:49:43 +0000502/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
503/// LTO problems.
504void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
505 for (std::pair<StringRef, StringRef> o = getToken(options);
506 !o.first.empty(); o = getToken(o.second)) {
507 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
508 // that.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000509 if (CodegenOptions.empty())
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000510 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindolac80c9692013-09-04 17:44:24 +0000511 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendling534a6582012-03-31 10:49:43 +0000512 }
Nick Kledzikc2323472008-07-08 21:14:10 +0000513}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000514
515void LTOCodeGenerator::parseCodeGenDebugOptions() {
516 // if options were requested, set them
517 if (!CodegenOptions.empty())
518 cl::ParseCommandLineOptions(CodegenOptions.size(),
519 const_cast<char **>(&CodegenOptions[0]));
520}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000521
522void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
523 void *Context) {
524 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
525}
526
527void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
528 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
529 lto_codegen_diagnostic_severity_t Severity;
530 switch (DI.getSeverity()) {
531 case DS_Error:
532 Severity = LTO_DS_ERROR;
533 break;
534 case DS_Warning:
535 Severity = LTO_DS_WARNING;
536 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000537 case DS_Remark:
538 Severity = LTO_DS_REMARK;
539 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000540 case DS_Note:
541 Severity = LTO_DS_NOTE;
542 break;
543 }
544 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000545 std::string MsgStorage;
546 raw_string_ostream Stream(MsgStorage);
547 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000548 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000549 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000550
551 // If this method has been called it means someone has set up an external
552 // diagnostic handler. Assert on that.
553 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000554 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000555}
556
557void
558LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
559 void *Ctxt) {
560 this->DiagHandler = DiagHandler;
561 this->DiagContext = Ctxt;
562 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000563 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000564 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
565 // diagnostic to the external DiagHandler.
566 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
567}