blob: e60dc171bba32212302fb51f4812c70ecbfa1462 [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/SystemUtils.h"
28#include "llvm/Support/Mangler.h"
29#include "llvm/Support/MemoryBuffer.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000030#include "llvm/System/Signals.h"
31#include "llvm/Analysis/Passes.h"
32#include "llvm/Analysis/LoopPass.h"
33#include "llvm/Analysis/Verifier.h"
Nick Kledzik79d0a052008-02-27 22:25:36 +000034#include "llvm/Analysis/LoadValueNumbering.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000035#include "llvm/CodeGen/FileWriters.h"
Bill Wendling568e37c2008-06-18 06:35:30 +000036#include "llvm/Target/SubtargetFeature.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000037#include "llvm/Target/TargetOptions.h"
38#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetMachine.h"
40#include "llvm/Target/TargetMachineRegistry.h"
41#include "llvm/Target/TargetAsmInfo.h"
42#include "llvm/Transforms/IPO.h"
43#include "llvm/Transforms/Scalar.h"
Devang Patel6fb60262008-07-03 22:53:14 +000044#include "llvm/ADT/StringExtras.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000045#include "llvm/Config/config.h"
46
Nick Kledzik6d886992008-02-26 20:26:43 +000047
48#include <fstream>
49#include <unistd.h>
50#include <stdlib.h>
51#include <fcntl.h>
52
53
54using namespace llvm;
55
Nick Kledzik4059fb12008-07-08 21:14:10 +000056static cl::opt<bool> DisableInline("disable-inlining",
57 cl::desc("Do not run the inliner pass"));
Nick Kledzik6d886992008-02-26 20:26:43 +000058
59
60const char* LTOCodeGenerator::getVersionString()
61{
62#ifdef LLVM_VERSION_INFO
63 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
64#else
65 return PACKAGE_NAME " version " PACKAGE_VERSION;
66#endif
67}
68
69
70LTOCodeGenerator::LTOCodeGenerator()
71 : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
72 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzik79d0a052008-02-27 22:25:36 +000073 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
74 _nativeObjectFile(NULL)
Nick Kledzik6d886992008-02-26 20:26:43 +000075{
76
77}
78
79LTOCodeGenerator::~LTOCodeGenerator()
80{
Nick Kledzik79d0a052008-02-27 22:25:36 +000081 delete _target;
82 delete _nativeObjectFile;
Nick Kledzik6d886992008-02-26 20:26:43 +000083}
84
85
86
87bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
88{
89 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
90}
91
92
93bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
94{
95 switch (debug) {
96 case LTO_DEBUG_MODEL_NONE:
97 _emitDwarfDebugInfo = false;
98 return false;
99
100 case LTO_DEBUG_MODEL_DWARF:
101 _emitDwarfDebugInfo = true;
102 return false;
103 }
104 errMsg = "unknown debug format";
105 return true;
106}
107
108
109bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
110 std::string& errMsg)
111{
112 switch (model) {
113 case LTO_CODEGEN_PIC_MODEL_STATIC:
114 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
115 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
116 _codeModel = model;
117 return false;
118 }
119 errMsg = "unknown pic model";
120 return true;
121}
122
Nick Kledzik6d886992008-02-26 20:26:43 +0000123void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
124{
125 _mustPreserveSymbols[sym] = 1;
126}
127
128
129bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
130{
131 if ( this->determineTarget(errMsg) )
132 return true;
133
134 // mark which symbols can not be internalized
135 this->applyScopeRestrictions();
136
137 // create output file
138 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
139 if ( out.fail() ) {
140 errMsg = "could not open bitcode file for writing: ";
141 errMsg += path;
142 return true;
143 }
144
145 // write bitcode to it
146 WriteBitcodeToFile(_linker.getModule(), out);
147 if ( out.fail() ) {
148 errMsg = "could not write bitcode file: ";
149 errMsg += path;
150 return true;
151 }
152
153 return false;
154}
155
156
Nick Kledzik79d0a052008-02-27 22:25:36 +0000157const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000158{
Nick Kledzik79d0a052008-02-27 22:25:36 +0000159 // make unique temp .s file to put generated assembly code
Nick Kledzik6d886992008-02-26 20:26:43 +0000160 sys::Path uniqueAsmPath("lto-llvm.s");
161 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
162 return NULL;
163 sys::RemoveFileOnSignal(uniqueAsmPath);
164
165 // generate assembly code
166 std::ofstream asmFile(uniqueAsmPath.c_str());
167 bool genResult = this->generateAssemblyCode(asmFile, errMsg);
168 asmFile.close();
169 if ( genResult ) {
170 if ( uniqueAsmPath.exists() )
171 uniqueAsmPath.eraseFromDisk();
172 return NULL;
173 }
174
Nick Kledzik79d0a052008-02-27 22:25:36 +0000175 // make unique temp .o file to put generated object file
Nick Kledzik6d886992008-02-26 20:26:43 +0000176 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
177 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
178 if ( uniqueAsmPath.exists() )
179 uniqueAsmPath.eraseFromDisk();
180 return NULL;
181 }
182 sys::RemoveFileOnSignal(uniqueObjPath);
183
184 // assemble the assembly code
Nick Kledzik79d0a052008-02-27 22:25:36 +0000185 const std::string& uniqueObjStr = uniqueObjPath.toString();
Nick Kledzik6d886992008-02-26 20:26:43 +0000186 bool asmResult = this->assemble(uniqueAsmPath.toString(),
Nick Kledzik79d0a052008-02-27 22:25:36 +0000187 uniqueObjStr, errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000188 if ( !asmResult ) {
Nick Kledzik79d0a052008-02-27 22:25:36 +0000189 // remove old buffer if compile() called twice
190 delete _nativeObjectFile;
191
Nick Kledzik6d886992008-02-26 20:26:43 +0000192 // read .o file into memory buffer
Chris Lattnerfc003612008-04-01 18:04:03 +0000193 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000194 }
Nick Kledzik79d0a052008-02-27 22:25:36 +0000195
196 // remove temp files
Nick Kledzik6d886992008-02-26 20:26:43 +0000197 uniqueAsmPath.eraseFromDisk();
198 uniqueObjPath.eraseFromDisk();
Nick Kledzik79d0a052008-02-27 22:25:36 +0000199
200 // return buffer, unless error
201 if ( _nativeObjectFile == NULL )
202 return NULL;
203 *length = _nativeObjectFile->getBufferSize();
204 return _nativeObjectFile->getBufferStart();
Nick Kledzik6d886992008-02-26 20:26:43 +0000205}
206
207
208bool LTOCodeGenerator::assemble(const std::string& asmPath,
209 const std::string& objPath, std::string& errMsg)
210{
211 // find compiler driver
212 const sys::Path gcc = sys::Program::FindProgramByName("gcc");
213 if ( gcc.isEmpty() ) {
214 errMsg = "can't locate gcc";
215 return true;
216 }
217
218 // build argument list
219 std::vector<const char*> args;
220 std::string targetTriple = _linker.getModule()->getTargetTriple();
221 args.push_back(gcc.c_str());
222 if ( targetTriple.find("darwin") != targetTriple.size() ) {
223 if (strncmp(targetTriple.c_str(), "i686-apple-", 11) == 0) {
224 args.push_back("-arch");
225 args.push_back("i386");
226 }
227 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
228 args.push_back("-arch");
229 args.push_back("x86_64");
230 }
231 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
232 args.push_back("-arch");
233 args.push_back("ppc");
234 }
235 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
236 args.push_back("-arch");
237 args.push_back("ppc64");
238 }
239 }
240 args.push_back("-c");
241 args.push_back("-x");
242 args.push_back("assembler");
243 args.push_back("-o");
244 args.push_back(objPath.c_str());
245 args.push_back(asmPath.c_str());
246 args.push_back(0);
247
248 // invoke assembler
249 if ( sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 0, 0, &errMsg) ) {
250 errMsg = "error in assembly";
251 return true;
252 }
253 return false; // success
254}
255
256
257
258bool LTOCodeGenerator::determineTarget(std::string& errMsg)
259{
260 if ( _target == NULL ) {
261 // create target machine from info for merged modules
262 Module* mergedModule = _linker.getModule();
263 const TargetMachineRegistry::entry* march =
264 TargetMachineRegistry::getClosestStaticTargetForModule(
265 *mergedModule, errMsg);
266 if ( march == NULL )
267 return true;
Bill Wendling568e37c2008-06-18 06:35:30 +0000268
269 // construct LTModule, hand over ownership of module and target
Bill Wendling0478d1a2008-06-18 21:39:02 +0000270 std::string FeatureStr =
271 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
272 _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
Nick Kledzik6d886992008-02-26 20:26:43 +0000273 }
274 return false;
275}
276
277void LTOCodeGenerator::applyScopeRestrictions()
278{
279 if ( !_scopeRestrictionsDone ) {
280 Module* mergedModule = _linker.getModule();
281
282 // Start off with a verification pass.
283 PassManager passes;
284 passes.add(createVerifierPass());
285
286 // mark which symbols can not be internalized
287 if ( !_mustPreserveSymbols.empty() ) {
288 Mangler mangler(*mergedModule,
289 _target->getTargetAsmInfo()->getGlobalPrefix());
290 std::vector<const char*> mustPreserveList;
291 for (Module::iterator f = mergedModule->begin(),
292 e = mergedModule->end(); f != e; ++f) {
293 if ( !f->isDeclaration()
294 && _mustPreserveSymbols.count(mangler.getValueName(f)) )
295 mustPreserveList.push_back(::strdup(f->getName().c_str()));
296 }
297 for (Module::global_iterator v = mergedModule->global_begin(),
298 e = mergedModule->global_end(); v != e; ++v) {
299 if ( !v->isDeclaration()
300 && _mustPreserveSymbols.count(mangler.getValueName(v)) )
301 mustPreserveList.push_back(::strdup(v->getName().c_str()));
302 }
303 passes.add(createInternalizePass(mustPreserveList));
304 }
305 // apply scope restrictions
306 passes.run(*mergedModule);
307
308 _scopeRestrictionsDone = true;
309 }
310}
311
Nick Kledzik6d886992008-02-26 20:26:43 +0000312/// Optimize merged modules using various IPO passes
313bool LTOCodeGenerator::generateAssemblyCode(std::ostream& out, std::string& errMsg)
314{
315 if ( this->determineTarget(errMsg) )
316 return true;
317
318 // mark which symbols can not be internalized
319 this->applyScopeRestrictions();
320
321 Module* mergedModule = _linker.getModule();
322
323 // If target supports exception handling then enable it now.
324 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
325 llvm::ExceptionHandling = true;
326
327 // set codegen model
328 switch( _codeModel ) {
329 case LTO_CODEGEN_PIC_MODEL_STATIC:
330 _target->setRelocationModel(Reloc::Static);
331 break;
332 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
333 _target->setRelocationModel(Reloc::PIC_);
334 break;
335 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
336 _target->setRelocationModel(Reloc::DynamicNoPIC);
337 break;
338 }
339
Nick Kledzik4059fb12008-07-08 21:14:10 +0000340 // if options were requested, set them
341 if ( !_codegenOptions.empty() )
342 cl::ParseCommandLineOptions(_codegenOptions.size(),
343 (char**)&_codegenOptions[0]);
Devang Patel6fb60262008-07-03 22:53:14 +0000344
Nick Kledzik6d886992008-02-26 20:26:43 +0000345 // Instantiate the pass manager to organize the passes.
346 PassManager passes;
347
348 // Start off with a verification pass.
349 passes.add(createVerifierPass());
350
351 // Add an appropriate TargetData instance for this module...
352 passes.add(new TargetData(*_target->getTargetData()));
353
Devang Patel5b3920f2008-05-27 20:18:45 +0000354 // Propagate constants at call sites into the functions they call. This
355 // opens opportunities for globalopt (and inlining) by substituting function
356 // pointers passed as arguments to direct uses of functions.
357 passes.add(createIPSCCPPass());
358
Nick Kledzik6d886992008-02-26 20:26:43 +0000359 // Now that we internalized some globals, see if we can hack on them!
360 passes.add(createGlobalOptimizerPass());
361
362 // Linking modules together can lead to duplicated global constants, only
363 // keep one copy of each constant...
364 passes.add(createConstantMergePass());
365
Nick Kledzik6d886992008-02-26 20:26:43 +0000366 // Remove unused arguments from functions...
367 passes.add(createDeadArgEliminationPass());
368
Devang Patel2f5db1e2008-05-27 20:42:44 +0000369 // Reduce the code after globalopt and ipsccp. Both can open up significant
370 // simplification opportunities, and both can propagate functions through
371 // function pointers. When this happens, we often have to resolve varargs
372 // calls, etc, so let instcombine do this.
373 passes.add(createInstructionCombiningPass());
Nick Kledzik4059fb12008-07-08 21:14:10 +0000374 if (!DisableInline)
375 passes.add(createFunctionInliningPass()); // Inline small functions
Bill Wendling568e37c2008-06-18 06:35:30 +0000376 passes.add(createPruneEHPass()); // Remove dead EH info
377 passes.add(createGlobalDCEPass()); // Remove dead functions
Nick Kledzik6d886992008-02-26 20:26:43 +0000378
379 // If we didn't decide to inline a function, check to see if we can
380 // transform it to pass arguments by value instead of by reference.
381 passes.add(createArgumentPromotionPass());
382
383 // The IPO passes may leave cruft around. Clean up after them.
384 passes.add(createInstructionCombiningPass());
Chris Lattnerc0413652008-04-21 04:31:40 +0000385 passes.add(createJumpThreadingPass()); // Thread jumps.
Nick Kledzik6d886992008-02-26 20:26:43 +0000386 passes.add(createScalarReplAggregatesPass()); // Break up allocas
387
388 // Run a few AA driven optimizations here and now, to cleanup the code.
Bill Wendling568e37c2008-06-18 06:35:30 +0000389 passes.add(createGlobalsModRefPass()); // IP alias analysis
390 passes.add(createLICMPass()); // Hoist loop invariants
391 passes.add(createGVNPass()); // Remove common subexprs
392 passes.add(createMemCpyOptPass()); // Remove dead memcpy's
Nick Kledzik6d886992008-02-26 20:26:43 +0000393 passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
394
395 // Cleanup and simplify the code after the scalar optimizations.
396 passes.add(createInstructionCombiningPass());
Chris Lattnerc0413652008-04-21 04:31:40 +0000397 passes.add(createJumpThreadingPass()); // Thread jumps.
Chris Lattner93312c62008-06-25 16:54:18 +0000398 passes.add(createPromoteMemoryToRegisterPass()); // Cleanup after threading.
399
Chris Lattnerc0413652008-04-21 04:31:40 +0000400
Nick Kledzik6d886992008-02-26 20:26:43 +0000401 // Delete basic blocks, which optimization passes may have killed...
402 passes.add(createCFGSimplificationPass());
403
404 // Now that we have optimized the program, discard unreachable functions...
405 passes.add(createGlobalDCEPass());
406
407 // Make sure everything is still good.
408 passes.add(createVerifierPass());
409
410 FunctionPassManager* codeGenPasses =
411 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
412
413 codeGenPasses->add(new TargetData(*_target->getTargetData()));
414
415 MachineCodeEmitter* mce = NULL;
416
417 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
418 TargetMachine::AssemblyFile, true)) {
419 case FileModel::MachOFile:
420 mce = AddMachOWriter(*codeGenPasses, out, *_target);
421 break;
422 case FileModel::ElfFile:
423 mce = AddELFWriter(*codeGenPasses, out, *_target);
424 break;
425 case FileModel::AsmFile:
426 break;
427 case FileModel::Error:
428 case FileModel::None:
429 errMsg = "target file type not supported";
430 return true;
431 }
432
433 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce, true)) {
434 errMsg = "target does not support generation of this file type";
435 return true;
436 }
437
438 // Run our queue of passes all at once now, efficiently.
439 passes.run(*mergedModule);
440
441 // Run the code generator, and write assembly file
442 codeGenPasses->doInitialization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000443
Bill Wendling568e37c2008-06-18 06:35:30 +0000444 for (Module::iterator
445 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
446 if (!it->isDeclaration())
447 codeGenPasses->run(*it);
448
449 codeGenPasses->doFinalization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000450 return false; // success
451}
452
453
Nick Kledzik4059fb12008-07-08 21:14:10 +0000454/// Optimize merged modules using various IPO passes
455void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
456{
457 std::string ops(options);
458 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
459 // ParseCommandLineOptions() expects argv[0] to be program name.
460 // Lazily add that.
461 if ( _codegenOptions.empty() )
462 _codegenOptions.push_back("libLTO");
463 _codegenOptions.push_back(strdup(o.c_str()));
464 }
465}