blob: acce071ba5d1d008b934945613e66a02775793fd [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"
27#include "llvm/Analysis/LoopPass.h"
28#include "llvm/Analysis/Verifier.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000029#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000030#include "llvm/MC/MCAsmInfo.h"
31#include "llvm/MC/MCContext.h"
32#include "llvm/Target/Mangler.h"
33#include "llvm/Target/SubtargetFeature.h"
34#include "llvm/Target/TargetOptions.h"
35#include "llvm/Target/TargetData.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetRegistry.h"
38#include "llvm/Target/TargetSelect.h"
39#include "llvm/Transforms/IPO.h"
40#include "llvm/Transforms/Scalar.h"
Nick Kledzik920ae982008-07-08 21:14:10 +000041#include "llvm/Support/CommandLine.h"
David Greene71847812009-07-14 20:18:05 +000042#include "llvm/Support/FormattedStream.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000043#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar006a0342009-06-03 21:06:14 +000044#include "llvm/Support/StandardPasses.h"
45#include "llvm/Support/SystemUtils.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000046#include "llvm/System/Host.h"
Chris Lattnerb683ea42009-08-23 21:36:09 +000047#include "llvm/System/Program.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000048#include "llvm/System/Signals.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000049#include "llvm/Config/config.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000050#include <cstdlib>
Nick Kledzik77595fc2008-02-26 20:26:43 +000051#include <unistd.h>
Nick Kledzik77595fc2008-02-26 20:26:43 +000052#include <fcntl.h>
53
54
55using namespace llvm;
56
Nick Kledzik920ae982008-07-08 21:14:10 +000057static cl::opt<bool> DisableInline("disable-inlining",
58 cl::desc("Do not run the inliner pass"));
Nick Kledzik77595fc2008-02-26 20:26:43 +000059
60
61const char* LTOCodeGenerator::getVersionString()
62{
63#ifdef LLVM_VERSION_INFO
64 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
65#else
66 return PACKAGE_NAME " version " PACKAGE_VERSION;
67#endif
68}
69
70
Owen Anderson0e7a5462009-07-02 00:31:14 +000071LTOCodeGenerator::LTOCodeGenerator()
72 : _context(getGlobalContext()),
Owen Anderson8b477ed2009-07-01 16:58:40 +000073 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
Nick Kledzik77595fc2008-02-26 20:26:43 +000074 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzikef194ed2008-02-27 22:25:36 +000075 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Nick Lewycky3e4c41a2009-08-03 07:16:42 +000076 _nativeObjectFile(NULL), _assemblerPath(NULL)
Nick Kledzik77595fc2008-02-26 20:26:43 +000077{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000078 InitializeAllTargets();
79 InitializeAllAsmPrinters();
Nick Kledzik77595fc2008-02-26 20:26:43 +000080}
81
82LTOCodeGenerator::~LTOCodeGenerator()
83{
Nick Kledzikef194ed2008-02-27 22:25:36 +000084 delete _target;
85 delete _nativeObjectFile;
Nick Kledzik77595fc2008-02-26 20:26:43 +000086}
87
88
89
90bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
91{
92 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
93}
94
95
96bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
97{
98 switch (debug) {
99 case LTO_DEBUG_MODEL_NONE:
100 _emitDwarfDebugInfo = false;
101 return false;
102
103 case LTO_DEBUG_MODEL_DWARF:
104 _emitDwarfDebugInfo = true;
105 return false;
106 }
107 errMsg = "unknown debug format";
108 return true;
109}
110
111
112bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
Evan Cheng855a1682009-06-26 06:57:16 +0000113 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000114{
115 switch (model) {
116 case LTO_CODEGEN_PIC_MODEL_STATIC:
117 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
118 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
119 _codeModel = model;
120 return false;
121 }
122 errMsg = "unknown pic model";
123 return true;
124}
125
Nick Kledzikcbad5862009-06-04 00:28:45 +0000126void LTOCodeGenerator::setAssemblerPath(const char* path)
127{
128 if ( _assemblerPath )
129 delete _assemblerPath;
130 _assemblerPath = new sys::Path(path);
131}
132
Nick Kledzik77595fc2008-02-26 20:26:43 +0000133void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
134{
135 _mustPreserveSymbols[sym] = 1;
136}
137
138
Chris Lattnerb515d752009-08-23 07:49:08 +0000139bool LTOCodeGenerator::writeMergedModules(const char *path,
140 std::string &errMsg) {
141 if (determineTarget(errMsg))
142 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000143
Chris Lattnerb515d752009-08-23 07:49:08 +0000144 // mark which symbols can not be internalized
145 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000146
Chris Lattnerb515d752009-08-23 07:49:08 +0000147 // create output file
148 std::string ErrInfo;
149 raw_fd_ostream Out(path, ErrInfo,
Dan Gohmanbaa26392009-08-25 15:34:52 +0000150 raw_fd_ostream::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000151 if (!ErrInfo.empty()) {
152 errMsg = "could not open bitcode file for writing: ";
153 errMsg += path;
154 return true;
155 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000156
Chris Lattnerb515d752009-08-23 07:49:08 +0000157 // write bitcode to it
158 WriteBitcodeToFile(_linker.getModule(), Out);
159
160 if (Out.has_error()) {
161 errMsg = "could not write bitcode file: ";
162 errMsg += path;
163 return true;
164 }
165
166 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 .s file to put generated assembly code
Nick Kledzik77595fc2008-02-26 20:26:43 +0000173 sys::Path uniqueAsmPath("lto-llvm.s");
174 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
175 return NULL;
176 sys::RemoveFileOnSignal(uniqueAsmPath);
177
178 // generate assembly code
Owen Andersoncb371882008-08-21 00:14:44 +0000179 bool genResult = false;
180 {
Dan Gohmanbaa26392009-08-25 15:34:52 +0000181 raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg);
David Greene71847812009-07-14 20:18:05 +0000182 formatted_raw_ostream asmFile(asmFD);
Dan Gohmaned3e8b42008-08-21 15:33:45 +0000183 if (!errMsg.empty())
184 return NULL;
Owen Andersoncb371882008-08-21 00:14:44 +0000185 genResult = this->generateAssemblyCode(asmFile, errMsg);
186 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000187 if ( genResult ) {
188 if ( uniqueAsmPath.exists() )
189 uniqueAsmPath.eraseFromDisk();
190 return NULL;
191 }
192
Nick Kledzikef194ed2008-02-27 22:25:36 +0000193 // make unique temp .o file to put generated object file
Nick Kledzik77595fc2008-02-26 20:26:43 +0000194 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
195 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
196 if ( uniqueAsmPath.exists() )
197 uniqueAsmPath.eraseFromDisk();
198 return NULL;
199 }
200 sys::RemoveFileOnSignal(uniqueObjPath);
201
202 // assemble the assembly code
Chris Lattner74382b72009-08-23 22:45:37 +0000203 const std::string& uniqueObjStr = uniqueObjPath.str();
204 bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000205 if ( !asmResult ) {
Nick Kledzikef194ed2008-02-27 22:25:36 +0000206 // remove old buffer if compile() called twice
207 delete _nativeObjectFile;
208
Nick Kledzik77595fc2008-02-26 20:26:43 +0000209 // read .o file into memory buffer
Chris Lattner038112a2008-04-01 18:04:03 +0000210 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000211 }
Nick Kledzikef194ed2008-02-27 22:25:36 +0000212
213 // remove temp files
Nick Kledzik77595fc2008-02-26 20:26:43 +0000214 uniqueAsmPath.eraseFromDisk();
215 uniqueObjPath.eraseFromDisk();
Nick Kledzikef194ed2008-02-27 22:25:36 +0000216
217 // return buffer, unless error
218 if ( _nativeObjectFile == NULL )
219 return NULL;
220 *length = _nativeObjectFile->getBufferSize();
221 return _nativeObjectFile->getBufferStart();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000222}
223
224
225bool LTOCodeGenerator::assemble(const std::string& asmPath,
226 const std::string& objPath, std::string& errMsg)
227{
Nick Kledzikcbad5862009-06-04 00:28:45 +0000228 sys::Path tool;
229 bool needsCompilerOptions = true;
230 if ( _assemblerPath ) {
231 tool = *_assemblerPath;
232 needsCompilerOptions = false;
Nick Lewycky195bea32009-04-30 15:24:09 +0000233 } else {
234 // find compiler driver
Nick Kledzikcbad5862009-06-04 00:28:45 +0000235 tool = sys::Program::FindProgramByName("gcc");
236 if ( tool.isEmpty() ) {
Nick Lewycky195bea32009-04-30 15:24:09 +0000237 errMsg = "can't locate gcc";
238 return true;
239 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000240 }
241
242 // build argument list
243 std::vector<const char*> args;
Viktor Kutuzov51cdac02009-11-17 18:48:27 +0000244 llvm::Triple targetTriple(_linker.getModule()->getTargetTriple());
245 const char *arch = targetTriple.getArchNameForAssembler();
246
Nick Kledzikcbad5862009-06-04 00:28:45 +0000247 args.push_back(tool.c_str());
Viktor Kutuzov51cdac02009-11-17 18:48:27 +0000248
249 if (targetTriple.getOS() == Triple::Darwin) {
Nick Kledzikd8b47112009-06-04 19:14:08 +0000250 // darwin specific command line options
Viktor Kutuzov51cdac02009-11-17 18:48:27 +0000251 if (arch != NULL) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000252 args.push_back("-arch");
Viktor Kutuzov51cdac02009-11-17 18:48:27 +0000253 args.push_back(arch);
Bob Wilson75d6ffd2009-06-22 18:01:28 +0000254 }
Nick Kledzikd8b47112009-06-04 19:14:08 +0000255 // add -static to assembler command line when code model requires
Chris Lattner5ef31a02010-03-12 18:44:54 +0000256 if ( (_assemblerPath != NULL) &&
257 (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
Nick Kledzikd8b47112009-06-04 19:14:08 +0000258 args.push_back("-static");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000259 }
Nick Kledzikcbad5862009-06-04 00:28:45 +0000260 if ( needsCompilerOptions ) {
261 args.push_back("-c");
262 args.push_back("-x");
263 args.push_back("assembler");
264 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000265 args.push_back("-o");
266 args.push_back(objPath.c_str());
267 args.push_back(asmPath.c_str());
268 args.push_back(0);
269
270 // invoke assembler
Nick Kledzikcbad5862009-06-04 00:28:45 +0000271 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000272 errMsg = "error in assembly";
273 return true;
274 }
275 return false; // success
276}
277
278
279
280bool LTOCodeGenerator::determineTarget(std::string& errMsg)
281{
282 if ( _target == NULL ) {
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000283 std::string Triple = _linker.getModule()->getTargetTriple();
284 if (Triple.empty())
285 Triple = sys::getHostTriple();
286
Nick Kledzik77595fc2008-02-26 20:26:43 +0000287 // create target machine from info for merged modules
Daniel Dunbar4bd03ab2009-08-03 04:20:57 +0000288 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000289 if ( march == NULL )
290 return true;
Bill Wendling604a8182008-06-18 06:35:30 +0000291
Nick Kledzikf5a1c35f12009-06-03 22:52:12 +0000292 // The relocation model is actually a static member of TargetMachine
293 // and needs to be set before the TargetMachine is instantiated.
294 switch( _codeModel ) {
295 case LTO_CODEGEN_PIC_MODEL_STATIC:
296 TargetMachine::setRelocationModel(Reloc::Static);
297 break;
298 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
299 TargetMachine::setRelocationModel(Reloc::PIC_);
300 break;
301 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
302 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
303 break;
304 }
305
Bill Wendling604a8182008-06-18 06:35:30 +0000306 // construct LTModule, hand over ownership of module and target
Viktor Kutuzov308f6632009-11-25 22:44:18 +0000307 const std::string FeatureStr =
Chris Lattner5ef31a02010-03-12 18:44:54 +0000308 SubtargetFeatures::getDefaultSubtargetFeatures(llvm::Triple(Triple));
Viktor Kutuzov308f6632009-11-25 22:44:18 +0000309 _target = march->createTargetMachine(Triple, FeatureStr);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000310 }
311 return false;
312}
313
Chris Lattner5ef31a02010-03-12 18:44:54 +0000314void LTOCodeGenerator::applyScopeRestrictions() {
315 if (_scopeRestrictionsDone) return;
316 Module *mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000317
Chris Lattner5ef31a02010-03-12 18:44:54 +0000318 // Start off with a verification pass.
319 PassManager passes;
320 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000321
Chris Lattner5ef31a02010-03-12 18:44:54 +0000322 // mark which symbols can not be internalized
323 if (!_mustPreserveSymbols.empty()) {
324 MCContext Context(*_target->getMCAsmInfo());
325 Mangler mangler(Context);
326 std::vector<const char*> mustPreserveList;
327 for (Module::iterator f = mergedModule->begin(),
328 e = mergedModule->end(); f != e; ++f) {
329 if (!f->isDeclaration() &&
330 _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)))
331 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
Nick Kledzik77595fc2008-02-26 20:26:43 +0000332 }
Chris Lattner5ef31a02010-03-12 18:44:54 +0000333 for (Module::global_iterator v = mergedModule->global_begin(),
334 e = mergedModule->global_end(); v != e; ++v) {
335 if (v->isDeclaration() &&
336 _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)))
337 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
338 }
339 passes.add(createInternalizePass(mustPreserveList));
340 }
341
342 // apply scope restrictions
343 passes.run(*mergedModule);
344
345 _scopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000346}
347
Nick Kledzik77595fc2008-02-26 20:26:43 +0000348/// Optimize merged modules using various IPO passes
David Greene71847812009-07-14 20:18:05 +0000349bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
Owen Andersoncb371882008-08-21 00:14:44 +0000350 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000351{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000352 if ( this->determineTarget(errMsg) )
Nick Kledzik77595fc2008-02-26 20:26:43 +0000353 return true;
354
355 // mark which symbols can not be internalized
356 this->applyScopeRestrictions();
357
358 Module* mergedModule = _linker.getModule();
359
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000360 // If target supports exception handling then enable it now.
Chris Lattneraf76e592009-08-22 20:48:53 +0000361 switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000362 case ExceptionHandling::Dwarf:
363 llvm::DwarfExceptionHandling = true;
364 break;
365 case ExceptionHandling::SjLj:
366 llvm::SjLjExceptionHandling = true;
367 break;
368 case ExceptionHandling::None:
369 break;
370 default:
371 assert (0 && "Unknown exception handling model!");
372 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000373
Nick Kledzik920ae982008-07-08 21:14:10 +0000374 // if options were requested, set them
375 if ( !_codegenOptions.empty() )
376 cl::ParseCommandLineOptions(_codegenOptions.size(),
377 (char**)&_codegenOptions[0]);
Devang Patela93ae712008-07-03 22:53:14 +0000378
Nick Kledzik77595fc2008-02-26 20:26:43 +0000379 // Instantiate the pass manager to organize the passes.
380 PassManager passes;
381
382 // Start off with a verification pass.
383 passes.add(createVerifierPass());
384
385 // Add an appropriate TargetData instance for this module...
386 passes.add(new TargetData(*_target->getTargetData()));
387
Daniel Dunbar006a0342009-06-03 21:06:14 +0000388 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
Daniel Dunbar006a0342009-06-03 21:06:14 +0000389 /*VerifyEach=*/ false);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000390
391 // Make sure everything is still good.
392 passes.add(createVerifierPass());
393
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000394 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000395
396 codeGenPasses->add(new TargetData(*_target->getTargetData()));
397
Chris Lattner5669e302010-02-03 05:55:08 +0000398 if (_target->addPassesToEmitFile(*codeGenPasses, out,
399 TargetMachine::CGFT_AssemblyFile,
400 CodeGenOpt::Aggressive)) {
401 errMsg = "target file type not supported";
402 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000403 }
404
Nick Kledzik77595fc2008-02-26 20:26:43 +0000405 // Run our queue of passes all at once now, efficiently.
406 passes.run(*mergedModule);
407
408 // Run the code generator, and write assembly file
409 codeGenPasses->doInitialization();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000410
Bill Wendling604a8182008-06-18 06:35:30 +0000411 for (Module::iterator
412 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
413 if (!it->isDeclaration())
414 codeGenPasses->run(*it);
415
416 codeGenPasses->doFinalization();
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000417
Nick Kledzik77595fc2008-02-26 20:26:43 +0000418 return false; // success
419}
420
421
Nick Kledzik920ae982008-07-08 21:14:10 +0000422/// Optimize merged modules using various IPO passes
423void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
424{
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000425 for (std::pair<StringRef, StringRef> o = getToken(options);
426 !o.first.empty(); o = getToken(o.second)) {
Nick Kledzik920ae982008-07-08 21:14:10 +0000427 // ParseCommandLineOptions() expects argv[0] to be program name.
428 // Lazily add that.
429 if ( _codegenOptions.empty() )
430 _codegenOptions.push_back("libLTO");
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000431 _codegenOptions.push_back(strdup(o.first.str().c_str()));
Nick Kledzik920ae982008-07-08 21:14:10 +0000432 }
433}