blob: 38ff49cc8c51051827451e5ec82d8e3382acf0e1 [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 Kledzik6d886992008-02-26 20:26:43 +000026#include "llvm/Support/SystemUtils.h"
27#include "llvm/Support/Mangler.h"
28#include "llvm/Support/MemoryBuffer.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000029#include "llvm/System/Signals.h"
30#include "llvm/Analysis/Passes.h"
31#include "llvm/Analysis/LoopPass.h"
32#include "llvm/Analysis/Verifier.h"
Nick Kledzik79d0a052008-02-27 22:25:36 +000033#include "llvm/Analysis/LoadValueNumbering.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000034#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"
Nick Kledzik6d886992008-02-26 20:26:43 +000043#include "llvm/Config/config.h"
44
Nick Kledzik6d886992008-02-26 20:26:43 +000045
46#include <fstream>
47#include <unistd.h>
48#include <stdlib.h>
49#include <fcntl.h>
50
51
52using namespace llvm;
53
54
55
56const char* LTOCodeGenerator::getVersionString()
57{
58#ifdef LLVM_VERSION_INFO
59 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
60#else
61 return PACKAGE_NAME " version " PACKAGE_VERSION;
62#endif
63}
64
65
66LTOCodeGenerator::LTOCodeGenerator()
67 : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
68 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzik79d0a052008-02-27 22:25:36 +000069 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
70 _nativeObjectFile(NULL)
Nick Kledzik6d886992008-02-26 20:26:43 +000071{
72
73}
74
75LTOCodeGenerator::~LTOCodeGenerator()
76{
Nick Kledzik79d0a052008-02-27 22:25:36 +000077 delete _target;
78 delete _nativeObjectFile;
Nick Kledzik6d886992008-02-26 20:26:43 +000079}
80
81
82
83bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
84{
85 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
86}
87
88
89bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
90{
91 switch (debug) {
92 case LTO_DEBUG_MODEL_NONE:
93 _emitDwarfDebugInfo = false;
94 return false;
95
96 case LTO_DEBUG_MODEL_DWARF:
97 _emitDwarfDebugInfo = true;
98 return false;
99 }
100 errMsg = "unknown debug format";
101 return true;
102}
103
104
105bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
106 std::string& errMsg)
107{
108 switch (model) {
109 case LTO_CODEGEN_PIC_MODEL_STATIC:
110 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
111 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
112 _codeModel = model;
113 return false;
114 }
115 errMsg = "unknown pic model";
116 return true;
117}
118
119
120void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
121{
122 _mustPreserveSymbols[sym] = 1;
123}
124
125
126bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
127{
128 if ( this->determineTarget(errMsg) )
129 return true;
130
131 // mark which symbols can not be internalized
132 this->applyScopeRestrictions();
133
134 // create output file
135 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
136 if ( out.fail() ) {
137 errMsg = "could not open bitcode file for writing: ";
138 errMsg += path;
139 return true;
140 }
141
142 // write bitcode to it
143 WriteBitcodeToFile(_linker.getModule(), out);
144 if ( out.fail() ) {
145 errMsg = "could not write bitcode file: ";
146 errMsg += path;
147 return true;
148 }
149
150 return false;
151}
152
153
Nick Kledzik79d0a052008-02-27 22:25:36 +0000154const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000155{
Nick Kledzik79d0a052008-02-27 22:25:36 +0000156 // make unique temp .s file to put generated assembly code
Nick Kledzik6d886992008-02-26 20:26:43 +0000157 sys::Path uniqueAsmPath("lto-llvm.s");
158 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
159 return NULL;
160 sys::RemoveFileOnSignal(uniqueAsmPath);
161
162 // generate assembly code
163 std::ofstream asmFile(uniqueAsmPath.c_str());
164 bool genResult = this->generateAssemblyCode(asmFile, errMsg);
165 asmFile.close();
166 if ( genResult ) {
167 if ( uniqueAsmPath.exists() )
168 uniqueAsmPath.eraseFromDisk();
169 return NULL;
170 }
171
Nick Kledzik79d0a052008-02-27 22:25:36 +0000172 // make unique temp .o file to put generated object file
Nick Kledzik6d886992008-02-26 20:26:43 +0000173 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
174 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
175 if ( uniqueAsmPath.exists() )
176 uniqueAsmPath.eraseFromDisk();
177 return NULL;
178 }
179 sys::RemoveFileOnSignal(uniqueObjPath);
180
181 // assemble the assembly code
Nick Kledzik79d0a052008-02-27 22:25:36 +0000182 const std::string& uniqueObjStr = uniqueObjPath.toString();
Nick Kledzik6d886992008-02-26 20:26:43 +0000183 bool asmResult = this->assemble(uniqueAsmPath.toString(),
Nick Kledzik79d0a052008-02-27 22:25:36 +0000184 uniqueObjStr, errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000185 if ( !asmResult ) {
Nick Kledzik79d0a052008-02-27 22:25:36 +0000186 // remove old buffer if compile() called twice
187 delete _nativeObjectFile;
188
Nick Kledzik6d886992008-02-26 20:26:43 +0000189 // read .o file into memory buffer
Chris Lattnerfc003612008-04-01 18:04:03 +0000190 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000191 }
Nick Kledzik79d0a052008-02-27 22:25:36 +0000192
193 // remove temp files
Nick Kledzik6d886992008-02-26 20:26:43 +0000194 uniqueAsmPath.eraseFromDisk();
195 uniqueObjPath.eraseFromDisk();
Nick Kledzik79d0a052008-02-27 22:25:36 +0000196
197 // return buffer, unless error
198 if ( _nativeObjectFile == NULL )
199 return NULL;
200 *length = _nativeObjectFile->getBufferSize();
201 return _nativeObjectFile->getBufferStart();
Nick Kledzik6d886992008-02-26 20:26:43 +0000202}
203
204
205bool LTOCodeGenerator::assemble(const std::string& asmPath,
206 const std::string& objPath, std::string& errMsg)
207{
208 // find compiler driver
209 const sys::Path gcc = sys::Program::FindProgramByName("gcc");
210 if ( gcc.isEmpty() ) {
211 errMsg = "can't locate gcc";
212 return true;
213 }
214
215 // build argument list
216 std::vector<const char*> args;
217 std::string targetTriple = _linker.getModule()->getTargetTriple();
218 args.push_back(gcc.c_str());
219 if ( targetTriple.find("darwin") != targetTriple.size() ) {
220 if (strncmp(targetTriple.c_str(), "i686-apple-", 11) == 0) {
221 args.push_back("-arch");
222 args.push_back("i386");
223 }
224 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
225 args.push_back("-arch");
226 args.push_back("x86_64");
227 }
228 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
229 args.push_back("-arch");
230 args.push_back("ppc");
231 }
232 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
233 args.push_back("-arch");
234 args.push_back("ppc64");
235 }
236 }
237 args.push_back("-c");
238 args.push_back("-x");
239 args.push_back("assembler");
240 args.push_back("-o");
241 args.push_back(objPath.c_str());
242 args.push_back(asmPath.c_str());
243 args.push_back(0);
244
245 // invoke assembler
246 if ( sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 0, 0, &errMsg) ) {
247 errMsg = "error in assembly";
248 return true;
249 }
250 return false; // success
251}
252
253
254
255bool LTOCodeGenerator::determineTarget(std::string& errMsg)
256{
257 if ( _target == NULL ) {
258 // create target machine from info for merged modules
259 Module* mergedModule = _linker.getModule();
260 const TargetMachineRegistry::entry* march =
261 TargetMachineRegistry::getClosestStaticTargetForModule(
262 *mergedModule, errMsg);
263 if ( march == NULL )
264 return true;
Bill Wendling568e37c2008-06-18 06:35:30 +0000265
266 // construct LTModule, hand over ownership of module and target
267 //
268 // FIXME: This is an inelegant way of specifying the features of a
269 // subtarget. It would be better if we could encode this information
270 // into the IR. See <rdar://5972456>.
271 SubtargetFeatures Features;
272 std::string FeatureStr;
273 std::string TargetTriple = _linker.getModule()->getTargetTriple();
274
275 if (strncmp(TargetTriple.c_str(), "powerpc-apple-", 14) == 0) {
276 Features.AddFeature("altivec", true);
277 } else if (strncmp(TargetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
278 Features.AddFeature("64bit", true);
279 Features.AddFeature("altivec", true);
280 }
281
282 _target = march->CtorFn(*mergedModule, Features.getString());
Nick Kledzik6d886992008-02-26 20:26:43 +0000283 }
284 return false;
285}
286
287void LTOCodeGenerator::applyScopeRestrictions()
288{
289 if ( !_scopeRestrictionsDone ) {
290 Module* mergedModule = _linker.getModule();
291
292 // Start off with a verification pass.
293 PassManager passes;
294 passes.add(createVerifierPass());
295
296 // mark which symbols can not be internalized
297 if ( !_mustPreserveSymbols.empty() ) {
298 Mangler mangler(*mergedModule,
299 _target->getTargetAsmInfo()->getGlobalPrefix());
300 std::vector<const char*> mustPreserveList;
301 for (Module::iterator f = mergedModule->begin(),
302 e = mergedModule->end(); f != e; ++f) {
303 if ( !f->isDeclaration()
304 && _mustPreserveSymbols.count(mangler.getValueName(f)) )
305 mustPreserveList.push_back(::strdup(f->getName().c_str()));
306 }
307 for (Module::global_iterator v = mergedModule->global_begin(),
308 e = mergedModule->global_end(); v != e; ++v) {
309 if ( !v->isDeclaration()
310 && _mustPreserveSymbols.count(mangler.getValueName(v)) )
311 mustPreserveList.push_back(::strdup(v->getName().c_str()));
312 }
313 passes.add(createInternalizePass(mustPreserveList));
314 }
315 // apply scope restrictions
316 passes.run(*mergedModule);
317
318 _scopeRestrictionsDone = true;
319 }
320}
321
Nick Kledzik6d886992008-02-26 20:26:43 +0000322/// Optimize merged modules using various IPO passes
323bool LTOCodeGenerator::generateAssemblyCode(std::ostream& out, std::string& errMsg)
324{
325 if ( this->determineTarget(errMsg) )
326 return true;
327
328 // mark which symbols can not be internalized
329 this->applyScopeRestrictions();
330
331 Module* mergedModule = _linker.getModule();
332
333 // If target supports exception handling then enable it now.
334 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
335 llvm::ExceptionHandling = true;
336
337 // set codegen model
338 switch( _codeModel ) {
339 case LTO_CODEGEN_PIC_MODEL_STATIC:
340 _target->setRelocationModel(Reloc::Static);
341 break;
342 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
343 _target->setRelocationModel(Reloc::PIC_);
344 break;
345 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
346 _target->setRelocationModel(Reloc::DynamicNoPIC);
347 break;
348 }
349
350 // Instantiate the pass manager to organize the passes.
351 PassManager passes;
352
353 // Start off with a verification pass.
354 passes.add(createVerifierPass());
355
356 // Add an appropriate TargetData instance for this module...
357 passes.add(new TargetData(*_target->getTargetData()));
358
Devang Patel5b3920f2008-05-27 20:18:45 +0000359 // Propagate constants at call sites into the functions they call. This
360 // opens opportunities for globalopt (and inlining) by substituting function
361 // pointers passed as arguments to direct uses of functions.
362 passes.add(createIPSCCPPass());
363
Nick Kledzik6d886992008-02-26 20:26:43 +0000364 // Now that we internalized some globals, see if we can hack on them!
365 passes.add(createGlobalOptimizerPass());
366
367 // Linking modules together can lead to duplicated global constants, only
368 // keep one copy of each constant...
369 passes.add(createConstantMergePass());
370
Nick Kledzik6d886992008-02-26 20:26:43 +0000371 // Remove unused arguments from functions...
372 passes.add(createDeadArgEliminationPass());
373
Devang Patel2f5db1e2008-05-27 20:42:44 +0000374 // Reduce the code after globalopt and ipsccp. Both can open up significant
375 // simplification opportunities, and both can propagate functions through
376 // function pointers. When this happens, we often have to resolve varargs
377 // calls, etc, so let instcombine do this.
378 passes.add(createInstructionCombiningPass());
Bill Wendling568e37c2008-06-18 06:35:30 +0000379 passes.add(createFunctionInliningPass()); // Inline small functions
380 passes.add(createPruneEHPass()); // Remove dead EH info
381 passes.add(createGlobalDCEPass()); // Remove dead functions
Nick Kledzik6d886992008-02-26 20:26:43 +0000382
383 // If we didn't decide to inline a function, check to see if we can
384 // transform it to pass arguments by value instead of by reference.
385 passes.add(createArgumentPromotionPass());
386
387 // The IPO passes may leave cruft around. Clean up after them.
388 passes.add(createInstructionCombiningPass());
Chris Lattnerc0413652008-04-21 04:31:40 +0000389 passes.add(createJumpThreadingPass()); // Thread jumps.
Nick Kledzik6d886992008-02-26 20:26:43 +0000390 passes.add(createScalarReplAggregatesPass()); // Break up allocas
391
392 // Run a few AA driven optimizations here and now, to cleanup the code.
Bill Wendling568e37c2008-06-18 06:35:30 +0000393 passes.add(createGlobalsModRefPass()); // IP alias analysis
394 passes.add(createLICMPass()); // Hoist loop invariants
395 passes.add(createGVNPass()); // Remove common subexprs
396 passes.add(createMemCpyOptPass()); // Remove dead memcpy's
Nick Kledzik6d886992008-02-26 20:26:43 +0000397 passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
398
399 // Cleanup and simplify the code after the scalar optimizations.
400 passes.add(createInstructionCombiningPass());
Chris Lattnerc0413652008-04-21 04:31:40 +0000401 passes.add(createJumpThreadingPass()); // Thread jumps.
402
Nick Kledzik6d886992008-02-26 20:26:43 +0000403 // Delete basic blocks, which optimization passes may have killed...
404 passes.add(createCFGSimplificationPass());
405
406 // Now that we have optimized the program, discard unreachable functions...
407 passes.add(createGlobalDCEPass());
408
409 // Make sure everything is still good.
410 passes.add(createVerifierPass());
411
412 FunctionPassManager* codeGenPasses =
413 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
414
415 codeGenPasses->add(new TargetData(*_target->getTargetData()));
416
417 MachineCodeEmitter* mce = NULL;
418
419 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
420 TargetMachine::AssemblyFile, true)) {
421 case FileModel::MachOFile:
422 mce = AddMachOWriter(*codeGenPasses, out, *_target);
423 break;
424 case FileModel::ElfFile:
425 mce = AddELFWriter(*codeGenPasses, out, *_target);
426 break;
427 case FileModel::AsmFile:
428 break;
429 case FileModel::Error:
430 case FileModel::None:
431 errMsg = "target file type not supported";
432 return true;
433 }
434
435 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce, true)) {
436 errMsg = "target does not support generation of this file type";
437 return true;
438 }
439
440 // Run our queue of passes all at once now, efficiently.
441 passes.run(*mergedModule);
442
443 // Run the code generator, and write assembly file
444 codeGenPasses->doInitialization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000445
Bill Wendling568e37c2008-06-18 06:35:30 +0000446 for (Module::iterator
447 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
448 if (!it->isDeclaration())
449 codeGenPasses->run(*it);
450
451 codeGenPasses->doFinalization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000452 return false; // success
453}
454
455
456