blob: 03a11b687daabcd022111680931121fb8d4e5ccc [file] [log] [blame]
Nick Kledzik6d886992008-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 Kledzik79d0a052008-02-27 22:25:36 +000015#include "LTOModule.h"
16#include "LTOCodeGenerator.h"
17
18
Nick Kledzik6d886992008-02-26 20:26:43 +000019#include "llvm/Module.h"
20#include "llvm/PassManager.h"
21#include "llvm/Linker.h"
22#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/ModuleProvider.h"
25#include "llvm/Bitcode/ReaderWriter.h"
Nick Kledzik4059fb12008-07-08 21:14:10 +000026#include "llvm/Support/CommandLine.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000027#include "llvm/Support/Mangler.h"
28#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar9068de52009-06-03 21:06:14 +000029#include "llvm/Support/StandardPasses.h"
30#include "llvm/Support/SystemUtils.h"
Owen Anderson847b99b2008-08-21 00:14:44 +000031#include "llvm/Support/raw_ostream.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000032#include "llvm/System/Signals.h"
33#include "llvm/Analysis/Passes.h"
34#include "llvm/Analysis/LoopPass.h"
35#include "llvm/Analysis/Verifier.h"
36#include "llvm/CodeGen/FileWriters.h"
Bill Wendling568e37c2008-06-18 06:35:30 +000037#include "llvm/Target/SubtargetFeature.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000038#include "llvm/Target/TargetOptions.h"
39#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetMachine.h"
41#include "llvm/Target/TargetMachineRegistry.h"
42#include "llvm/Target/TargetAsmInfo.h"
43#include "llvm/Transforms/IPO.h"
44#include "llvm/Transforms/Scalar.h"
Devang Patel6fb60262008-07-03 22:53:14 +000045#include "llvm/ADT/StringExtras.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000046#include "llvm/Config/config.h"
47
Nick Kledzik6d886992008-02-26 20:26:43 +000048
49#include <fstream>
50#include <unistd.h>
51#include <stdlib.h>
52#include <fcntl.h>
53
54
55using namespace llvm;
56
Nick Kledzik4059fb12008-07-08 21:14:10 +000057static cl::opt<bool> DisableInline("disable-inlining",
58 cl::desc("Do not run the inliner pass"));
Nick Kledzik6d886992008-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
71LTOCodeGenerator::LTOCodeGenerator()
72 : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
73 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzik79d0a052008-02-27 22:25:36 +000074 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Nick Lewyckyef973202009-04-30 15:24:09 +000075 _nativeObjectFile(NULL), _gccPath(NULL)
Nick Kledzik6d886992008-02-26 20:26:43 +000076{
77
78}
79
80LTOCodeGenerator::~LTOCodeGenerator()
81{
Nick Kledzik79d0a052008-02-27 22:25:36 +000082 delete _target;
83 delete _nativeObjectFile;
Nick Kledzik6d886992008-02-26 20:26:43 +000084}
85
86
87
88bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
89{
90 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
91}
92
93
94bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
95{
96 switch (debug) {
97 case LTO_DEBUG_MODEL_NONE:
98 _emitDwarfDebugInfo = false;
99 return false;
100
101 case LTO_DEBUG_MODEL_DWARF:
102 _emitDwarfDebugInfo = true;
103 return false;
104 }
105 errMsg = "unknown debug format";
106 return true;
107}
108
109
110bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
111 std::string& errMsg)
112{
113 switch (model) {
114 case LTO_CODEGEN_PIC_MODEL_STATIC:
115 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
116 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
117 _codeModel = model;
118 return false;
119 }
120 errMsg = "unknown pic model";
121 return true;
122}
123
Nick Lewyckyef973202009-04-30 15:24:09 +0000124void LTOCodeGenerator::setGccPath(const char* path)
125{
126 if ( _gccPath )
127 delete _gccPath;
128 _gccPath = new sys::Path(path);
129}
130
Nick Kledzik6d886992008-02-26 20:26:43 +0000131void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
132{
133 _mustPreserveSymbols[sym] = 1;
134}
135
136
137bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
138{
139 if ( this->determineTarget(errMsg) )
140 return true;
141
142 // mark which symbols can not be internalized
143 this->applyScopeRestrictions();
144
145 // create output file
146 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
147 if ( out.fail() ) {
148 errMsg = "could not open bitcode file for writing: ";
149 errMsg += path;
150 return true;
151 }
152
153 // write bitcode to it
154 WriteBitcodeToFile(_linker.getModule(), out);
155 if ( out.fail() ) {
156 errMsg = "could not write bitcode file: ";
157 errMsg += path;
158 return true;
159 }
160
161 return false;
162}
163
164
Nick Kledzik79d0a052008-02-27 22:25:36 +0000165const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000166{
Nick Kledzik79d0a052008-02-27 22:25:36 +0000167 // make unique temp .s file to put generated assembly code
Nick Kledzik6d886992008-02-26 20:26:43 +0000168 sys::Path uniqueAsmPath("lto-llvm.s");
169 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
170 return NULL;
171 sys::RemoveFileOnSignal(uniqueAsmPath);
172
173 // generate assembly code
Owen Anderson847b99b2008-08-21 00:14:44 +0000174 bool genResult = false;
175 {
Daniel Dunbar8c009a32008-11-13 05:01:07 +0000176 raw_fd_ostream asmFile(uniqueAsmPath.c_str(), false, errMsg);
Dan Gohmande20df82008-08-21 15:33:45 +0000177 if (!errMsg.empty())
178 return NULL;
Owen Anderson847b99b2008-08-21 00:14:44 +0000179 genResult = this->generateAssemblyCode(asmFile, errMsg);
180 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000181 if ( genResult ) {
182 if ( uniqueAsmPath.exists() )
183 uniqueAsmPath.eraseFromDisk();
184 return NULL;
185 }
186
Nick Kledzik79d0a052008-02-27 22:25:36 +0000187 // make unique temp .o file to put generated object file
Nick Kledzik6d886992008-02-26 20:26:43 +0000188 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
189 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
190 if ( uniqueAsmPath.exists() )
191 uniqueAsmPath.eraseFromDisk();
192 return NULL;
193 }
194 sys::RemoveFileOnSignal(uniqueObjPath);
195
196 // assemble the assembly code
Nick Kledzik79d0a052008-02-27 22:25:36 +0000197 const std::string& uniqueObjStr = uniqueObjPath.toString();
Nick Kledzik6d886992008-02-26 20:26:43 +0000198 bool asmResult = this->assemble(uniqueAsmPath.toString(),
Nick Kledzik79d0a052008-02-27 22:25:36 +0000199 uniqueObjStr, errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000200 if ( !asmResult ) {
Nick Kledzik79d0a052008-02-27 22:25:36 +0000201 // remove old buffer if compile() called twice
202 delete _nativeObjectFile;
203
Nick Kledzik6d886992008-02-26 20:26:43 +0000204 // read .o file into memory buffer
Chris Lattnerfc003612008-04-01 18:04:03 +0000205 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000206 }
Nick Kledzik79d0a052008-02-27 22:25:36 +0000207
208 // remove temp files
Nick Kledzik6d886992008-02-26 20:26:43 +0000209 uniqueAsmPath.eraseFromDisk();
210 uniqueObjPath.eraseFromDisk();
Nick Kledzik79d0a052008-02-27 22:25:36 +0000211
212 // return buffer, unless error
213 if ( _nativeObjectFile == NULL )
214 return NULL;
215 *length = _nativeObjectFile->getBufferSize();
216 return _nativeObjectFile->getBufferStart();
Nick Kledzik6d886992008-02-26 20:26:43 +0000217}
218
219
220bool LTOCodeGenerator::assemble(const std::string& asmPath,
221 const std::string& objPath, std::string& errMsg)
222{
Nick Lewyckyef973202009-04-30 15:24:09 +0000223 sys::Path gcc;
224 if ( _gccPath ) {
225 gcc = *_gccPath;
226 } else {
227 // find compiler driver
228 gcc = sys::Program::FindProgramByName("gcc");
229 if ( gcc.isEmpty() ) {
230 errMsg = "can't locate gcc";
231 return true;
232 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000233 }
234
235 // build argument list
236 std::vector<const char*> args;
237 std::string targetTriple = _linker.getModule()->getTargetTriple();
238 args.push_back(gcc.c_str());
239 if ( targetTriple.find("darwin") != targetTriple.size() ) {
Devang Patelaa6cd1f2008-11-04 23:13:50 +0000240 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000241 args.push_back("-arch");
242 args.push_back("i386");
243 }
244 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
245 args.push_back("-arch");
246 args.push_back("x86_64");
247 }
248 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
249 args.push_back("-arch");
250 args.push_back("ppc");
251 }
252 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
253 args.push_back("-arch");
254 args.push_back("ppc64");
255 }
Evan Chengdc5b6d62009-04-01 18:54:56 +0000256 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
257 args.push_back("-arch");
258 args.push_back("arm");
259 }
260 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
261 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
262 args.push_back("-arch");
263 args.push_back("armv4t");
264 }
265 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
266 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
267 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
268 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
269 args.push_back("-arch");
270 args.push_back("armv5");
271 }
272 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
273 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
274 args.push_back("-arch");
275 args.push_back("armv6");
276 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000277 }
278 args.push_back("-c");
279 args.push_back("-x");
280 args.push_back("assembler");
281 args.push_back("-o");
282 args.push_back(objPath.c_str());
283 args.push_back(asmPath.c_str());
284 args.push_back(0);
285
286 // invoke assembler
287 if ( sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 0, 0, &errMsg) ) {
288 errMsg = "error in assembly";
289 return true;
290 }
291 return false; // success
292}
293
294
295
296bool LTOCodeGenerator::determineTarget(std::string& errMsg)
297{
298 if ( _target == NULL ) {
299 // create target machine from info for merged modules
300 Module* mergedModule = _linker.getModule();
301 const TargetMachineRegistry::entry* march =
302 TargetMachineRegistry::getClosestStaticTargetForModule(
303 *mergedModule, errMsg);
304 if ( march == NULL )
305 return true;
Bill Wendling568e37c2008-06-18 06:35:30 +0000306
307 // construct LTModule, hand over ownership of module and target
Bill Wendling0478d1a2008-06-18 21:39:02 +0000308 std::string FeatureStr =
309 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
310 _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
Nick Kledzik6d886992008-02-26 20:26:43 +0000311 }
312 return false;
313}
314
315void LTOCodeGenerator::applyScopeRestrictions()
316{
317 if ( !_scopeRestrictionsDone ) {
318 Module* mergedModule = _linker.getModule();
319
320 // Start off with a verification pass.
321 PassManager passes;
322 passes.add(createVerifierPass());
323
324 // mark which symbols can not be internalized
325 if ( !_mustPreserveSymbols.empty() ) {
326 Mangler mangler(*mergedModule,
327 _target->getTargetAsmInfo()->getGlobalPrefix());
328 std::vector<const char*> mustPreserveList;
329 for (Module::iterator f = mergedModule->begin(),
330 e = mergedModule->end(); f != e; ++f) {
331 if ( !f->isDeclaration()
332 && _mustPreserveSymbols.count(mangler.getValueName(f)) )
333 mustPreserveList.push_back(::strdup(f->getName().c_str()));
334 }
335 for (Module::global_iterator v = mergedModule->global_begin(),
336 e = mergedModule->global_end(); v != e; ++v) {
337 if ( !v->isDeclaration()
338 && _mustPreserveSymbols.count(mangler.getValueName(v)) )
339 mustPreserveList.push_back(::strdup(v->getName().c_str()));
340 }
341 passes.add(createInternalizePass(mustPreserveList));
342 }
343 // apply scope restrictions
344 passes.run(*mergedModule);
345
346 _scopeRestrictionsDone = true;
347 }
348}
349
Nick Kledzik6d886992008-02-26 20:26:43 +0000350/// Optimize merged modules using various IPO passes
Owen Anderson847b99b2008-08-21 00:14:44 +0000351bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
352 std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000353{
354 if ( this->determineTarget(errMsg) )
355 return true;
356
357 // mark which symbols can not be internalized
358 this->applyScopeRestrictions();
359
360 Module* mergedModule = _linker.getModule();
361
362 // If target supports exception handling then enable it now.
363 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
364 llvm::ExceptionHandling = true;
365
366 // set codegen model
367 switch( _codeModel ) {
368 case LTO_CODEGEN_PIC_MODEL_STATIC:
369 _target->setRelocationModel(Reloc::Static);
370 break;
371 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
372 _target->setRelocationModel(Reloc::PIC_);
373 break;
374 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
375 _target->setRelocationModel(Reloc::DynamicNoPIC);
376 break;
377 }
378
Nick Kledzik4059fb12008-07-08 21:14:10 +0000379 // if options were requested, set them
380 if ( !_codegenOptions.empty() )
381 cl::ParseCommandLineOptions(_codegenOptions.size(),
382 (char**)&_codegenOptions[0]);
Devang Patel6fb60262008-07-03 22:53:14 +0000383
Nick Kledzik6d886992008-02-26 20:26:43 +0000384 // Instantiate the pass manager to organize the passes.
385 PassManager passes;
386
387 // Start off with a verification pass.
388 passes.add(createVerifierPass());
389
390 // Add an appropriate TargetData instance for this module...
391 passes.add(new TargetData(*_target->getTargetData()));
392
Daniel Dunbar9068de52009-06-03 21:06:14 +0000393 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
394 /*RunSecondGlobalOpt=*/ false,
395 /*VerifyEach=*/ false);
Nick Kledzik6d886992008-02-26 20:26:43 +0000396
397 // Make sure everything is still good.
398 passes.add(createVerifierPass());
399
400 FunctionPassManager* codeGenPasses =
401 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
402
403 codeGenPasses->add(new TargetData(*_target->getTargetData()));
404
405 MachineCodeEmitter* mce = NULL;
406
407 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
Bill Wendling5ed22ac2009-04-29 23:29:43 +0000408 TargetMachine::AssemblyFile,
Bill Wendling2d1c1162009-04-29 23:40:42 +0000409 CodeGenOpt::Aggressive)) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000410 case FileModel::MachOFile:
411 mce = AddMachOWriter(*codeGenPasses, out, *_target);
412 break;
413 case FileModel::ElfFile:
414 mce = AddELFWriter(*codeGenPasses, out, *_target);
415 break;
416 case FileModel::AsmFile:
417 break;
418 case FileModel::Error:
419 case FileModel::None:
420 errMsg = "target file type not supported";
421 return true;
422 }
423
Bill Wendling5ed22ac2009-04-29 23:29:43 +0000424 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce,
Bill Wendling2d1c1162009-04-29 23:40:42 +0000425 CodeGenOpt::Aggressive)) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000426 errMsg = "target does not support generation of this file type";
427 return true;
428 }
429
430 // Run our queue of passes all at once now, efficiently.
431 passes.run(*mergedModule);
432
433 // Run the code generator, and write assembly file
434 codeGenPasses->doInitialization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000435
Bill Wendling568e37c2008-06-18 06:35:30 +0000436 for (Module::iterator
437 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
438 if (!it->isDeclaration())
439 codeGenPasses->run(*it);
440
441 codeGenPasses->doFinalization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000442 return false; // success
443}
444
445
Nick Kledzik4059fb12008-07-08 21:14:10 +0000446/// Optimize merged modules using various IPO passes
447void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
448{
449 std::string ops(options);
450 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
451 // ParseCommandLineOptions() expects argv[0] to be program name.
452 // Lazily add that.
453 if ( _codegenOptions.empty() )
454 _codegenOptions.push_back("libLTO");
455 _codegenOptions.push_back(strdup(o.c_str()));
456 }
457}