blob: 17c83bb5cf68426a47e5f7dcbcb0929cd5f22781 [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 Kledzik39d9b412009-06-04 00:28:45 +000075 _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(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 Kledzik39d9b412009-06-04 00:28:45 +0000131void LTOCodeGenerator::setAssemblerPath(const char* path)
132{
133 if ( _assemblerPath )
134 delete _assemblerPath;
135 _assemblerPath = new sys::Path(path);
136}
137
Nick Kledzik6d886992008-02-26 20:26:43 +0000138void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
139{
140 _mustPreserveSymbols[sym] = 1;
141}
142
143
144bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
145{
146 if ( this->determineTarget(errMsg) )
147 return true;
148
149 // mark which symbols can not be internalized
150 this->applyScopeRestrictions();
151
152 // create output file
153 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
154 if ( out.fail() ) {
155 errMsg = "could not open bitcode file for writing: ";
156 errMsg += path;
157 return true;
158 }
159
160 // write bitcode to it
161 WriteBitcodeToFile(_linker.getModule(), out);
162 if ( out.fail() ) {
163 errMsg = "could not write bitcode file: ";
164 errMsg += path;
165 return true;
166 }
167
168 return false;
169}
170
171
Nick Kledzik79d0a052008-02-27 22:25:36 +0000172const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000173{
Nick Kledzik79d0a052008-02-27 22:25:36 +0000174 // make unique temp .s file to put generated assembly code
Nick Kledzik6d886992008-02-26 20:26:43 +0000175 sys::Path uniqueAsmPath("lto-llvm.s");
176 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
177 return NULL;
178 sys::RemoveFileOnSignal(uniqueAsmPath);
179
180 // generate assembly code
Owen Anderson847b99b2008-08-21 00:14:44 +0000181 bool genResult = false;
182 {
Daniel Dunbar8c009a32008-11-13 05:01:07 +0000183 raw_fd_ostream asmFile(uniqueAsmPath.c_str(), false, errMsg);
Dan Gohmande20df82008-08-21 15:33:45 +0000184 if (!errMsg.empty())
185 return NULL;
Owen Anderson847b99b2008-08-21 00:14:44 +0000186 genResult = this->generateAssemblyCode(asmFile, errMsg);
187 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000188 if ( genResult ) {
189 if ( uniqueAsmPath.exists() )
190 uniqueAsmPath.eraseFromDisk();
191 return NULL;
192 }
193
Nick Kledzik79d0a052008-02-27 22:25:36 +0000194 // make unique temp .o file to put generated object file
Nick Kledzik6d886992008-02-26 20:26:43 +0000195 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
196 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
197 if ( uniqueAsmPath.exists() )
198 uniqueAsmPath.eraseFromDisk();
199 return NULL;
200 }
201 sys::RemoveFileOnSignal(uniqueObjPath);
202
203 // assemble the assembly code
Nick Kledzik79d0a052008-02-27 22:25:36 +0000204 const std::string& uniqueObjStr = uniqueObjPath.toString();
Nick Kledzik6d886992008-02-26 20:26:43 +0000205 bool asmResult = this->assemble(uniqueAsmPath.toString(),
Nick Kledzik79d0a052008-02-27 22:25:36 +0000206 uniqueObjStr, errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000207 if ( !asmResult ) {
Nick Kledzik79d0a052008-02-27 22:25:36 +0000208 // remove old buffer if compile() called twice
209 delete _nativeObjectFile;
210
Nick Kledzik6d886992008-02-26 20:26:43 +0000211 // read .o file into memory buffer
Chris Lattnerfc003612008-04-01 18:04:03 +0000212 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000213 }
Nick Kledzik79d0a052008-02-27 22:25:36 +0000214
215 // remove temp files
Nick Kledzik6d886992008-02-26 20:26:43 +0000216 uniqueAsmPath.eraseFromDisk();
217 uniqueObjPath.eraseFromDisk();
Nick Kledzik79d0a052008-02-27 22:25:36 +0000218
219 // return buffer, unless error
220 if ( _nativeObjectFile == NULL )
221 return NULL;
222 *length = _nativeObjectFile->getBufferSize();
223 return _nativeObjectFile->getBufferStart();
Nick Kledzik6d886992008-02-26 20:26:43 +0000224}
225
226
227bool LTOCodeGenerator::assemble(const std::string& asmPath,
228 const std::string& objPath, std::string& errMsg)
229{
Nick Kledzik39d9b412009-06-04 00:28:45 +0000230 sys::Path tool;
231 bool needsCompilerOptions = true;
232 if ( _assemblerPath ) {
233 tool = *_assemblerPath;
234 needsCompilerOptions = false;
235 }
236 else if ( _gccPath ) {
237 tool = *_gccPath;
Nick Lewyckyef973202009-04-30 15:24:09 +0000238 } else {
239 // find compiler driver
Nick Kledzik39d9b412009-06-04 00:28:45 +0000240 tool = sys::Program::FindProgramByName("gcc");
241 if ( tool.isEmpty() ) {
Nick Lewyckyef973202009-04-30 15:24:09 +0000242 errMsg = "can't locate gcc";
243 return true;
244 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000245 }
246
247 // build argument list
248 std::vector<const char*> args;
249 std::string targetTriple = _linker.getModule()->getTargetTriple();
Nick Kledzik39d9b412009-06-04 00:28:45 +0000250 args.push_back(tool.c_str());
Nick Kledzik6d886992008-02-26 20:26:43 +0000251 if ( targetTriple.find("darwin") != targetTriple.size() ) {
Devang Patelaa6cd1f2008-11-04 23:13:50 +0000252 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000253 args.push_back("-arch");
254 args.push_back("i386");
255 }
256 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
257 args.push_back("-arch");
258 args.push_back("x86_64");
259 }
260 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
261 args.push_back("-arch");
262 args.push_back("ppc");
263 }
264 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
265 args.push_back("-arch");
266 args.push_back("ppc64");
267 }
Evan Chengdc5b6d62009-04-01 18:54:56 +0000268 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
269 args.push_back("-arch");
270 args.push_back("arm");
271 }
272 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
273 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
274 args.push_back("-arch");
275 args.push_back("armv4t");
276 }
277 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
278 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
279 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
280 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
281 args.push_back("-arch");
282 args.push_back("armv5");
283 }
284 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
285 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
286 args.push_back("-arch");
287 args.push_back("armv6");
288 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000289 }
Nick Kledzik39d9b412009-06-04 00:28:45 +0000290 if ( needsCompilerOptions ) {
291 args.push_back("-c");
292 args.push_back("-x");
293 args.push_back("assembler");
294 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000295 args.push_back("-o");
296 args.push_back(objPath.c_str());
297 args.push_back(asmPath.c_str());
298 args.push_back(0);
299
300 // invoke assembler
Nick Kledzik39d9b412009-06-04 00:28:45 +0000301 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000302 errMsg = "error in assembly";
303 return true;
304 }
305 return false; // success
306}
307
308
309
310bool LTOCodeGenerator::determineTarget(std::string& errMsg)
311{
312 if ( _target == NULL ) {
313 // create target machine from info for merged modules
314 Module* mergedModule = _linker.getModule();
315 const TargetMachineRegistry::entry* march =
316 TargetMachineRegistry::getClosestStaticTargetForModule(
317 *mergedModule, errMsg);
318 if ( march == NULL )
319 return true;
Bill Wendling568e37c2008-06-18 06:35:30 +0000320
Nick Kledzik3e843222009-06-03 22:52:12 +0000321 // The relocation model is actually a static member of TargetMachine
322 // and needs to be set before the TargetMachine is instantiated.
323 switch( _codeModel ) {
324 case LTO_CODEGEN_PIC_MODEL_STATIC:
325 TargetMachine::setRelocationModel(Reloc::Static);
326 break;
327 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
328 TargetMachine::setRelocationModel(Reloc::PIC_);
329 break;
330 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
331 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
332 break;
333 }
334
Bill Wendling568e37c2008-06-18 06:35:30 +0000335 // construct LTModule, hand over ownership of module and target
Bill Wendling0478d1a2008-06-18 21:39:02 +0000336 std::string FeatureStr =
337 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
338 _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
Nick Kledzik6d886992008-02-26 20:26:43 +0000339 }
340 return false;
341}
342
343void LTOCodeGenerator::applyScopeRestrictions()
344{
345 if ( !_scopeRestrictionsDone ) {
346 Module* mergedModule = _linker.getModule();
347
348 // Start off with a verification pass.
349 PassManager passes;
350 passes.add(createVerifierPass());
351
352 // mark which symbols can not be internalized
353 if ( !_mustPreserveSymbols.empty() ) {
354 Mangler mangler(*mergedModule,
355 _target->getTargetAsmInfo()->getGlobalPrefix());
356 std::vector<const char*> mustPreserveList;
357 for (Module::iterator f = mergedModule->begin(),
358 e = mergedModule->end(); f != e; ++f) {
359 if ( !f->isDeclaration()
360 && _mustPreserveSymbols.count(mangler.getValueName(f)) )
361 mustPreserveList.push_back(::strdup(f->getName().c_str()));
362 }
363 for (Module::global_iterator v = mergedModule->global_begin(),
364 e = mergedModule->global_end(); v != e; ++v) {
365 if ( !v->isDeclaration()
366 && _mustPreserveSymbols.count(mangler.getValueName(v)) )
367 mustPreserveList.push_back(::strdup(v->getName().c_str()));
368 }
369 passes.add(createInternalizePass(mustPreserveList));
370 }
371 // apply scope restrictions
372 passes.run(*mergedModule);
373
374 _scopeRestrictionsDone = true;
375 }
376}
377
Nick Kledzik6d886992008-02-26 20:26:43 +0000378/// Optimize merged modules using various IPO passes
Owen Anderson847b99b2008-08-21 00:14:44 +0000379bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
380 std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000381{
382 if ( this->determineTarget(errMsg) )
383 return true;
384
385 // mark which symbols can not be internalized
386 this->applyScopeRestrictions();
387
388 Module* mergedModule = _linker.getModule();
389
390 // If target supports exception handling then enable it now.
391 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
392 llvm::ExceptionHandling = true;
393
Nick Kledzik4059fb12008-07-08 21:14:10 +0000394 // if options were requested, set them
395 if ( !_codegenOptions.empty() )
396 cl::ParseCommandLineOptions(_codegenOptions.size(),
397 (char**)&_codegenOptions[0]);
Devang Patel6fb60262008-07-03 22:53:14 +0000398
Nick Kledzik6d886992008-02-26 20:26:43 +0000399 // Instantiate the pass manager to organize the passes.
400 PassManager passes;
401
402 // Start off with a verification pass.
403 passes.add(createVerifierPass());
404
405 // Add an appropriate TargetData instance for this module...
406 passes.add(new TargetData(*_target->getTargetData()));
407
Daniel Dunbar9068de52009-06-03 21:06:14 +0000408 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
Daniel Dunbar9068de52009-06-03 21:06:14 +0000409 /*VerifyEach=*/ false);
Nick Kledzik6d886992008-02-26 20:26:43 +0000410
411 // Make sure everything is still good.
412 passes.add(createVerifierPass());
413
414 FunctionPassManager* codeGenPasses =
415 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
416
417 codeGenPasses->add(new TargetData(*_target->getTargetData()));
418
419 MachineCodeEmitter* mce = NULL;
420
421 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
Bill Wendling5ed22ac2009-04-29 23:29:43 +0000422 TargetMachine::AssemblyFile,
Bill Wendling2d1c1162009-04-29 23:40:42 +0000423 CodeGenOpt::Aggressive)) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000424 case FileModel::MachOFile:
425 mce = AddMachOWriter(*codeGenPasses, out, *_target);
426 break;
427 case FileModel::ElfFile:
428 mce = AddELFWriter(*codeGenPasses, out, *_target);
429 break;
430 case FileModel::AsmFile:
431 break;
432 case FileModel::Error:
433 case FileModel::None:
434 errMsg = "target file type not supported";
435 return true;
436 }
437
Bill Wendling5ed22ac2009-04-29 23:29:43 +0000438 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce,
Bill Wendling2d1c1162009-04-29 23:40:42 +0000439 CodeGenOpt::Aggressive)) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000440 errMsg = "target does not support generation of this file type";
441 return true;
442 }
443
444 // Run our queue of passes all at once now, efficiently.
445 passes.run(*mergedModule);
446
447 // Run the code generator, and write assembly file
448 codeGenPasses->doInitialization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000449
Bill Wendling568e37c2008-06-18 06:35:30 +0000450 for (Module::iterator
451 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
452 if (!it->isDeclaration())
453 codeGenPasses->run(*it);
454
455 codeGenPasses->doFinalization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000456 return false; // success
457}
458
459
Nick Kledzik4059fb12008-07-08 21:14:10 +0000460/// Optimize merged modules using various IPO passes
461void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
462{
463 std::string ops(options);
464 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
465 // ParseCommandLineOptions() expects argv[0] to be program name.
466 // Lazily add that.
467 if ( _codegenOptions.empty() )
468 _codegenOptions.push_back("libLTO");
469 _codegenOptions.push_back(strdup(o.c_str()));
470 }
471}