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