blob: f72fdb0fca9499abe22d606c691bd4d70c2cf5e6 [file] [log] [blame]
Nick Kledzik77595fc2008-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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Nick Kledzikef194ed2008-02-27 22:25:36 +000015#include "LTOModule.h"
16#include "LTOCodeGenerator.h"
17
Nick Kledzik77595fc2008-02-26 20:26:43 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000020#include "llvm/Linker.h"
Owen Anderson0e7a5462009-07-02 00:31:14 +000021#include "llvm/LLVMContext.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000022#include "llvm/Module.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000023#include "llvm/PassManager.h"
24#include "llvm/ADT/StringExtras.h"
Viktor Kutuzov51cdac02009-11-17 18:48:27 +000025#include "llvm/ADT/Triple.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000026#include "llvm/Analysis/Passes.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000027#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000028#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCContext.h"
30#include "llvm/Target/Mangler.h"
31#include "llvm/Target/SubtargetFeature.h"
32#include "llvm/Target/TargetOptions.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetRegistry.h"
36#include "llvm/Target/TargetSelect.h"
Nick Kledzik920ae982008-07-08 21:14:10 +000037#include "llvm/Support/CommandLine.h"
David Greene71847812009-07-14 20:18:05 +000038#include "llvm/Support/FormattedStream.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000039#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar006a0342009-06-03 21:06:14 +000040#include "llvm/Support/StandardPasses.h"
41#include "llvm/Support/SystemUtils.h"
Dan Gohman9f36c4e2010-10-07 20:48:46 +000042#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000046#include "llvm/Support/system_error.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000047#include "llvm/Config/config.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000048#include <cstdlib>
Nick Kledzik77595fc2008-02-26 20:26:43 +000049#include <unistd.h>
Nick Kledzik77595fc2008-02-26 20:26:43 +000050#include <fcntl.h>
51
52
53using namespace llvm;
54
Nick Kledzik920ae982008-07-08 21:14:10 +000055static cl::opt<bool> DisableInline("disable-inlining",
56 cl::desc("Do not run the inliner pass"));
Nick Kledzik77595fc2008-02-26 20:26:43 +000057
58
59const char* LTOCodeGenerator::getVersionString()
60{
61#ifdef LLVM_VERSION_INFO
62 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
63#else
64 return PACKAGE_NAME " version " PACKAGE_VERSION;
65#endif
66}
67
68
Owen Anderson0e7a5462009-07-02 00:31:14 +000069LTOCodeGenerator::LTOCodeGenerator()
70 : _context(getGlobalContext()),
Owen Anderson8b477ed2009-07-01 16:58:40 +000071 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
Nick Kledzik77595fc2008-02-26 20:26:43 +000072 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzikef194ed2008-02-27 22:25:36 +000073 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Rafael Espindolae9efea12011-02-24 21:04:06 +000074 _nativeObjectFile(NULL)
Nick Kledzik77595fc2008-02-26 20:26:43 +000075{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000076 InitializeAllTargets();
77 InitializeAllAsmPrinters();
Rafael Espindolae9efea12011-02-24 21:04:06 +000078 InitializeAllAsmParsers();
Nick Kledzik77595fc2008-02-26 20:26:43 +000079}
80
81LTOCodeGenerator::~LTOCodeGenerator()
82{
Nick Kledzikef194ed2008-02-27 22:25:36 +000083 delete _target;
84 delete _nativeObjectFile;
Nick Kledzik77595fc2008-02-26 20:26:43 +000085}
86
87
88
89bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
90{
91 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
92}
93
94
95bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
96{
97 switch (debug) {
98 case LTO_DEBUG_MODEL_NONE:
99 _emitDwarfDebugInfo = false;
100 return false;
101
102 case LTO_DEBUG_MODEL_DWARF:
103 _emitDwarfDebugInfo = true;
104 return false;
105 }
106 errMsg = "unknown debug format";
107 return true;
108}
109
110
111bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
Evan Cheng855a1682009-06-26 06:57:16 +0000112 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000113{
114 switch (model) {
115 case LTO_CODEGEN_PIC_MODEL_STATIC:
116 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
117 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
118 _codeModel = model;
119 return false;
120 }
121 errMsg = "unknown pic model";
122 return true;
123}
124
Rafael Espindola2d643ef2010-08-11 00:15:13 +0000125void LTOCodeGenerator::setCpu(const char* mCpu)
126{
127 _mCpu = mCpu;
128}
129
Nick Kledzik77595fc2008-02-26 20:26:43 +0000130void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
131{
132 _mustPreserveSymbols[sym] = 1;
133}
134
135
Chris Lattnerb515d752009-08-23 07:49:08 +0000136bool LTOCodeGenerator::writeMergedModules(const char *path,
137 std::string &errMsg) {
138 if (determineTarget(errMsg))
139 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000140
Chris Lattnerb515d752009-08-23 07:49:08 +0000141 // mark which symbols can not be internalized
142 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000143
Chris Lattnerb515d752009-08-23 07:49:08 +0000144 // create output file
145 std::string ErrInfo;
Dan Gohmanf2914012010-08-20 16:59:15 +0000146 tool_output_file Out(path, ErrInfo,
147 raw_fd_ostream::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000148 if (!ErrInfo.empty()) {
149 errMsg = "could not open bitcode file for writing: ";
150 errMsg += path;
151 return true;
152 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000153
Chris Lattnerb515d752009-08-23 07:49:08 +0000154 // write bitcode to it
Dan Gohmand4c45432010-09-01 14:20:41 +0000155 WriteBitcodeToFile(_linker.getModule(), Out.os());
156 Out.os().close();
Dan Gohman4b7416b2010-05-27 20:19:47 +0000157
Dan Gohmand4c45432010-09-01 14:20:41 +0000158 if (Out.os().has_error()) {
Chris Lattnerb515d752009-08-23 07:49:08 +0000159 errMsg = "could not write bitcode file: ";
160 errMsg += path;
Dan Gohmand4c45432010-09-01 14:20:41 +0000161 Out.os().clear_error();
Chris Lattnerb515d752009-08-23 07:49:08 +0000162 return true;
163 }
164
Dan Gohmanf2914012010-08-20 16:59:15 +0000165 Out.keep();
Chris Lattnerb515d752009-08-23 07:49:08 +0000166 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000167}
168
169
Nick Kledzikef194ed2008-02-27 22:25:36 +0000170const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000171{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000172 // make unique temp .o file to put generated object file
Nick Kledzik77595fc2008-02-26 20:26:43 +0000173 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
Devang Patelb7bbd462010-12-03 23:58:31 +0000174 if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
Rafael Espindolae9efea12011-02-24 21:04:06 +0000175 uniqueObjPath.eraseFromDisk();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000176 return NULL;
177 }
178 sys::RemoveFileOnSignal(uniqueObjPath);
179
Rafael Espindolae9efea12011-02-24 21:04:06 +0000180 // generate object file
181 bool genResult = false;
182 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
183 if (!errMsg.empty())
184 return NULL;
185 genResult = this->generateObjectFile(objFile.os(), errMsg);
186 objFile.os().close();
187 if (objFile.os().has_error()) {
188 objFile.os().clear_error();
189 return NULL;
190 }
191 objFile.keep();
192 if ( genResult ) {
193 uniqueObjPath.eraseFromDisk();
194 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000195 }
Nick Kledzikef194ed2008-02-27 22:25:36 +0000196
Rafael Espindolae9efea12011-02-24 21:04:06 +0000197 const std::string& uniqueObjStr = uniqueObjPath.str();
198 // remove old buffer if compile() called twice
199 delete _nativeObjectFile;
200
201 // read .o file into memory buffer
202 OwningPtr<MemoryBuffer> BuffPtr;
203 if (error_code ec = MemoryBuffer::getFile(uniqueObjStr.c_str(),BuffPtr))
204 errMsg = ec.message();
205 _nativeObjectFile = BuffPtr.take();
206
Nick Kledzikef194ed2008-02-27 22:25:36 +0000207 // remove temp files
Nick Kledzik77595fc2008-02-26 20:26:43 +0000208 uniqueObjPath.eraseFromDisk();
Nick Kledzikef194ed2008-02-27 22:25:36 +0000209
210 // return buffer, unless error
211 if ( _nativeObjectFile == NULL )
212 return NULL;
213 *length = _nativeObjectFile->getBufferSize();
214 return _nativeObjectFile->getBufferStart();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000215}
216
Nick Kledzik77595fc2008-02-26 20:26:43 +0000217bool LTOCodeGenerator::determineTarget(std::string& errMsg)
218{
219 if ( _target == NULL ) {
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000220 std::string Triple = _linker.getModule()->getTargetTriple();
221 if (Triple.empty())
222 Triple = sys::getHostTriple();
223
Nick Kledzik77595fc2008-02-26 20:26:43 +0000224 // create target machine from info for merged modules
Daniel Dunbar4bd03ab2009-08-03 04:20:57 +0000225 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000226 if ( march == NULL )
227 return true;
Bill Wendling604a8182008-06-18 06:35:30 +0000228
Nick Kledzikf5a1c35f12009-06-03 22:52:12 +0000229 // The relocation model is actually a static member of TargetMachine
230 // and needs to be set before the TargetMachine is instantiated.
231 switch( _codeModel ) {
232 case LTO_CODEGEN_PIC_MODEL_STATIC:
233 TargetMachine::setRelocationModel(Reloc::Static);
234 break;
235 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
236 TargetMachine::setRelocationModel(Reloc::PIC_);
237 break;
238 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
239 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
240 break;
241 }
242
Bill Wendling604a8182008-06-18 06:35:30 +0000243 // construct LTModule, hand over ownership of module and target
Bill Wendling81043ee2010-05-11 00:30:02 +0000244 SubtargetFeatures Features;
Rafael Espindola2d643ef2010-08-11 00:15:13 +0000245 Features.getDefaultSubtargetFeatures(_mCpu, llvm::Triple(Triple));
Bill Wendling81043ee2010-05-11 00:30:02 +0000246 std::string FeatureStr = Features.getString();
Viktor Kutuzov308f6632009-11-25 22:44:18 +0000247 _target = march->createTargetMachine(Triple, FeatureStr);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000248 }
249 return false;
250}
251
Chris Lattner5ef31a02010-03-12 18:44:54 +0000252void LTOCodeGenerator::applyScopeRestrictions() {
253 if (_scopeRestrictionsDone) return;
254 Module *mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000255
Chris Lattner5ef31a02010-03-12 18:44:54 +0000256 // Start off with a verification pass.
257 PassManager passes;
258 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000259
Chris Lattner5ef31a02010-03-12 18:44:54 +0000260 // mark which symbols can not be internalized
261 if (!_mustPreserveSymbols.empty()) {
Rafael Espindola89b93722010-12-10 07:39:47 +0000262 MCContext Context(*_target->getMCAsmInfo(), NULL);
Chris Lattnerb87c3052010-03-12 20:47:28 +0000263 Mangler mangler(Context, *_target->getTargetData());
Chris Lattner5ef31a02010-03-12 18:44:54 +0000264 std::vector<const char*> mustPreserveList;
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000265 SmallString<64> Buffer;
Chris Lattner5ef31a02010-03-12 18:44:54 +0000266 for (Module::iterator f = mergedModule->begin(),
267 e = mergedModule->end(); f != e; ++f) {
Rafael Espindolad7401b32011-02-12 00:19:56 +0000268 Buffer.clear();
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000269 mangler.getNameWithPrefix(Buffer, f, false);
Chris Lattner5ef31a02010-03-12 18:44:54 +0000270 if (!f->isDeclaration() &&
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000271 _mustPreserveSymbols.count(Buffer))
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000272 mustPreserveList.push_back(f->getName().data());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000273 }
Chris Lattner5ef31a02010-03-12 18:44:54 +0000274 for (Module::global_iterator v = mergedModule->global_begin(),
275 e = mergedModule->global_end(); v != e; ++v) {
Rafael Espindolad7401b32011-02-12 00:19:56 +0000276 Buffer.clear();
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000277 mangler.getNameWithPrefix(Buffer, v, false);
Bill Wendlingc3d0e0c2010-04-27 00:55:25 +0000278 if (!v->isDeclaration() &&
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000279 _mustPreserveSymbols.count(Buffer))
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000280 mustPreserveList.push_back(v->getName().data());
Chris Lattner5ef31a02010-03-12 18:44:54 +0000281 }
Rafael Espindola2e3066b2011-02-12 18:03:13 +0000282 for (Module::alias_iterator a = mergedModule->alias_begin(),
283 e = mergedModule->alias_end(); a != e; ++a) {
284 Buffer.clear();
285 mangler.getNameWithPrefix(Buffer, a, false);
286 if (!a->isDeclaration() &&
287 _mustPreserveSymbols.count(Buffer))
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000288 mustPreserveList.push_back(a->getName().data());
Rafael Espindola2e3066b2011-02-12 18:03:13 +0000289 }
Chris Lattner5ef31a02010-03-12 18:44:54 +0000290 passes.add(createInternalizePass(mustPreserveList));
291 }
292
293 // apply scope restrictions
294 passes.run(*mergedModule);
295
296 _scopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000297}
298
Nick Kledzik77595fc2008-02-26 20:26:43 +0000299/// Optimize merged modules using various IPO passes
Rafael Espindolae9efea12011-02-24 21:04:06 +0000300bool LTOCodeGenerator::generateObjectFile(raw_ostream& out,
301 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000302{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000303 if ( this->determineTarget(errMsg) )
Nick Kledzik77595fc2008-02-26 20:26:43 +0000304 return true;
305
306 // mark which symbols can not be internalized
307 this->applyScopeRestrictions();
308
309 Module* mergedModule = _linker.getModule();
310
Nick Kledzik920ae982008-07-08 21:14:10 +0000311 // if options were requested, set them
312 if ( !_codegenOptions.empty() )
313 cl::ParseCommandLineOptions(_codegenOptions.size(),
Dan Gohman43bc70e2010-04-17 17:44:03 +0000314 const_cast<char **>(&_codegenOptions[0]));
Devang Patela93ae712008-07-03 22:53:14 +0000315
Nick Kledzik77595fc2008-02-26 20:26:43 +0000316 // Instantiate the pass manager to organize the passes.
317 PassManager passes;
318
319 // Start off with a verification pass.
320 passes.add(createVerifierPass());
321
322 // Add an appropriate TargetData instance for this module...
323 passes.add(new TargetData(*_target->getTargetData()));
324
Daniel Dunbar006a0342009-06-03 21:06:14 +0000325 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
Daniel Dunbar006a0342009-06-03 21:06:14 +0000326 /*VerifyEach=*/ false);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000327
328 // Make sure everything is still good.
329 passes.add(createVerifierPass());
330
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000331 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000332
333 codeGenPasses->add(new TargetData(*_target->getTargetData()));
334
Dan Gohmand4c45432010-09-01 14:20:41 +0000335 formatted_raw_ostream Out(out);
336
337 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
Rafael Espindolae9efea12011-02-24 21:04:06 +0000338 TargetMachine::CGFT_ObjectFile,
Chris Lattner5669e302010-02-03 05:55:08 +0000339 CodeGenOpt::Aggressive)) {
340 errMsg = "target file type not supported";
341 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000342 }
343
Nick Kledzik77595fc2008-02-26 20:26:43 +0000344 // Run our queue of passes all at once now, efficiently.
345 passes.run(*mergedModule);
346
347 // Run the code generator, and write assembly file
348 codeGenPasses->doInitialization();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000349
Bill Wendling604a8182008-06-18 06:35:30 +0000350 for (Module::iterator
351 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
352 if (!it->isDeclaration())
353 codeGenPasses->run(*it);
354
355 codeGenPasses->doFinalization();
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000356 delete codeGenPasses;
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000357
Nick Kledzik77595fc2008-02-26 20:26:43 +0000358 return false; // success
359}
360
361
Nick Kledzik920ae982008-07-08 21:14:10 +0000362/// Optimize merged modules using various IPO passes
363void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
364{
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000365 for (std::pair<StringRef, StringRef> o = getToken(options);
366 !o.first.empty(); o = getToken(o.second)) {
Nick Kledzik920ae982008-07-08 21:14:10 +0000367 // ParseCommandLineOptions() expects argv[0] to be program name.
368 // Lazily add that.
369 if ( _codegenOptions.empty() )
370 _codegenOptions.push_back("libLTO");
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000371 _codegenOptions.push_back(strdup(o.first.str().c_str()));
Nick Kledzik920ae982008-07-08 21:14:10 +0000372 }
373}