275aac208f3f174ecfb1b1b4538d394cfd8ed971
[oota-llvm.git] / tools / lto / LTOCodeGenerator.cpp
1 //===-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
15 #include "LTOModule.h"
16 #include "LTOCodeGenerator.h"
17
18
19 #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"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/System/Signals.h"
32 #include "llvm/Analysis/Passes.h"
33 #include "llvm/Analysis/LoopPass.h"
34 #include "llvm/Analysis/Verifier.h"
35 #include "llvm/CodeGen/FileWriters.h"
36 #include "llvm/Target/SubtargetFeature.h"
37 #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"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/Config/config.h"
46
47
48 #include <fstream>
49 #include <unistd.h>
50 #include <stdlib.h>
51 #include <fcntl.h>
52
53
54 using namespace llvm;
55
56 static cl::opt<bool> DisableInline("disable-inlining",
57   cl::desc("Do not run the inliner pass"));
58
59
60 const 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
70 LTOCodeGenerator::LTOCodeGenerator() 
71     : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
72       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
73       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
74       _nativeObjectFile(NULL)
75 {
76
77 }
78
79 LTOCodeGenerator::~LTOCodeGenerator()
80 {
81     delete _target;
82     delete _nativeObjectFile;
83 }
84
85
86
87 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
88 {
89     return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
90 }
91     
92
93 bool 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
109 bool 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
123 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
124 {
125     _mustPreserveSymbols[sym] = 1;
126 }
127
128
129 bool 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
157 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
158 {
159     // make unique temp .s file to put generated assembly code
160     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::string error;
167     bool genResult = false;
168     {
169       raw_fd_ostream asmFile(uniqueAsmPath.c_str(), error);
170       genResult = this->generateAssemblyCode(asmFile, errMsg);
171     }
172     if ( genResult ) {
173         if ( uniqueAsmPath.exists() )
174             uniqueAsmPath.eraseFromDisk();
175         return NULL;
176     }
177     
178     // make unique temp .o file to put generated object file
179     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
180     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
181         if ( uniqueAsmPath.exists() )
182             uniqueAsmPath.eraseFromDisk();
183         return NULL;
184     }
185     sys::RemoveFileOnSignal(uniqueObjPath);
186
187     // assemble the assembly code
188     const std::string& uniqueObjStr = uniqueObjPath.toString();
189     bool asmResult = this->assemble(uniqueAsmPath.toString(), 
190                                                         uniqueObjStr, errMsg);
191     if ( !asmResult ) {
192         // remove old buffer if compile() called twice
193         delete _nativeObjectFile;
194         
195         // read .o file into memory buffer
196         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
197     }
198
199     // remove temp files
200     uniqueAsmPath.eraseFromDisk();
201     uniqueObjPath.eraseFromDisk();
202
203     // return buffer, unless error
204     if ( _nativeObjectFile == NULL )
205         return NULL;
206     *length = _nativeObjectFile->getBufferSize();
207     return _nativeObjectFile->getBufferStart();
208 }
209
210
211 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
212                                 const std::string& objPath, std::string& errMsg)
213 {
214     // find compiler driver
215     const sys::Path gcc = sys::Program::FindProgramByName("gcc");
216     if ( gcc.isEmpty() ) {
217         errMsg = "can't locate gcc";
218         return true;
219     }
220
221     // build argument list
222     std::vector<const char*> args;
223     std::string targetTriple = _linker.getModule()->getTargetTriple();
224     args.push_back(gcc.c_str());
225     if ( targetTriple.find("darwin") != targetTriple.size() ) {
226         if (strncmp(targetTriple.c_str(), "i686-apple-", 11) == 0) {
227             args.push_back("-arch");
228             args.push_back("i386");
229         }
230         else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
231             args.push_back("-arch");
232             args.push_back("x86_64");
233         }
234         else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
235             args.push_back("-arch");
236             args.push_back("ppc");
237         }
238         else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
239             args.push_back("-arch");
240             args.push_back("ppc64");
241         }
242     }
243     args.push_back("-c");
244     args.push_back("-x");
245     args.push_back("assembler");
246     args.push_back("-o");
247     args.push_back(objPath.c_str());
248     args.push_back(asmPath.c_str());
249     args.push_back(0);
250
251     // invoke assembler
252     if ( sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 0, 0, &errMsg) ) {
253         errMsg = "error in assembly";    
254         return true;
255     }
256     return false; // success
257 }
258
259
260
261 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
262 {
263     if ( _target == NULL ) {
264         // create target machine from info for merged modules
265         Module* mergedModule = _linker.getModule();
266         const TargetMachineRegistry::entry* march = 
267           TargetMachineRegistry::getClosestStaticTargetForModule(
268                                                        *mergedModule, errMsg);
269         if ( march == NULL )
270             return true;
271
272         // construct LTModule, hand over ownership of module and target
273         std::string FeatureStr =
274           getFeatureString(_linker.getModule()->getTargetTriple().c_str());
275         _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
276     }
277     return false;
278 }
279
280 void LTOCodeGenerator::applyScopeRestrictions()
281 {
282     if ( !_scopeRestrictionsDone ) {
283         Module* mergedModule = _linker.getModule();
284
285         // Start off with a verification pass.
286         PassManager passes;
287         passes.add(createVerifierPass());
288
289         // mark which symbols can not be internalized 
290         if ( !_mustPreserveSymbols.empty() ) {
291             Mangler mangler(*mergedModule, 
292                                 _target->getTargetAsmInfo()->getGlobalPrefix());
293             std::vector<const char*> mustPreserveList;
294             for (Module::iterator f = mergedModule->begin(), 
295                                         e = mergedModule->end(); f != e; ++f) {
296                 if ( !f->isDeclaration() 
297                   && _mustPreserveSymbols.count(mangler.getValueName(f)) )
298                     mustPreserveList.push_back(::strdup(f->getName().c_str()));
299             }
300             for (Module::global_iterator v = mergedModule->global_begin(), 
301                                  e = mergedModule->global_end(); v !=  e; ++v) {
302                 if ( !v->isDeclaration()
303                   && _mustPreserveSymbols.count(mangler.getValueName(v)) )
304                     mustPreserveList.push_back(::strdup(v->getName().c_str()));
305             }
306             passes.add(createInternalizePass(mustPreserveList));
307         }
308         // apply scope restrictions
309         passes.run(*mergedModule);
310         
311         _scopeRestrictionsDone = true;
312     }
313 }
314
315 /// Optimize merged modules using various IPO passes
316 bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
317                                             std::string& errMsg)
318 {
319     if (  this->determineTarget(errMsg) ) 
320         return true;
321
322     // mark which symbols can not be internalized 
323     this->applyScopeRestrictions();
324
325     Module* mergedModule = _linker.getModule();
326
327      // If target supports exception handling then enable it now.
328     if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
329         llvm::ExceptionHandling = true;
330
331     // set codegen model
332     switch( _codeModel ) {
333         case LTO_CODEGEN_PIC_MODEL_STATIC:
334             _target->setRelocationModel(Reloc::Static);
335             break;
336         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
337             _target->setRelocationModel(Reloc::PIC_);
338             break;
339         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
340             _target->setRelocationModel(Reloc::DynamicNoPIC);
341             break;
342     }
343
344     // if options were requested, set them
345     if ( !_codegenOptions.empty() )
346         cl::ParseCommandLineOptions(_codegenOptions.size(), 
347                                                 (char**)&_codegenOptions[0]);
348
349     // Instantiate the pass manager to organize the passes.
350     PassManager passes;
351
352     // Start off with a verification pass.
353     passes.add(createVerifierPass());
354
355     // Add an appropriate TargetData instance for this module...
356     passes.add(new TargetData(*_target->getTargetData()));
357     
358     // Propagate constants at call sites into the functions they call.  This
359     // opens opportunities for globalopt (and inlining) by substituting function
360     // pointers passed as arguments to direct uses of functions.  
361     passes.add(createIPSCCPPass());
362
363     // Now that we internalized some globals, see if we can hack on them!
364     passes.add(createGlobalOptimizerPass());
365
366     // Linking modules together can lead to duplicated global constants, only
367     // keep one copy of each constant...
368     passes.add(createConstantMergePass());
369
370     // Remove unused arguments from functions...
371     passes.add(createDeadArgEliminationPass());
372
373     // Reduce the code after globalopt and ipsccp.  Both can open up significant
374     // simplification opportunities, and both can propagate functions through
375     // function pointers.  When this happens, we often have to resolve varargs
376     // calls, etc, so let instcombine do this.
377     passes.add(createInstructionCombiningPass());
378     if (!DisableInline)
379         passes.add(createFunctionInliningPass()); // Inline small functions
380     passes.add(createPruneEHPass());              // Remove dead EH info
381     passes.add(createGlobalDCEPass());            // Remove dead functions
382
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());
389     passes.add(createJumpThreadingPass());        // Thread jumps.
390     passes.add(createScalarReplAggregatesPass()); // Break up allocas
391
392     // Run a few AA driven optimizations here and now, to cleanup the code.
393     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
397     passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
398
399     // Cleanup and simplify the code after the scalar optimizations.
400     passes.add(createInstructionCombiningPass());
401     passes.add(createJumpThreadingPass());        // Thread jumps.
402     passes.add(createPromoteMemoryToRegisterPass()); // Cleanup after threading.
403
404
405     // Delete basic blocks, which optimization passes may have killed...
406     passes.add(createCFGSimplificationPass());
407
408     // Now that we have optimized the program, discard unreachable functions...
409     passes.add(createGlobalDCEPass());
410
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,
422                                       TargetMachine::AssemblyFile, true)) {
423         case FileModel::MachOFile:
424             mce = AddMachOWriter(*codeGenPasses, out, *_target);
425             break;
426         case FileModel::ElfFile:
427             mce = AddELFWriter(*codeGenPasses, out, *_target);
428             break;
429         case FileModel::AsmFile:
430             break;
431         case FileModel::Error:
432         case FileModel::None:
433             errMsg = "target file type not supported";
434             return true;
435     }
436
437     if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce, true)) {
438         errMsg = "target does not support generation of this file type";
439         return true;
440     }
441
442     // Run our queue of passes all at once now, efficiently.
443     passes.run(*mergedModule);
444
445     // Run the code generator, and write assembly file
446     codeGenPasses->doInitialization();
447
448     for (Module::iterator
449            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
450       if (!it->isDeclaration())
451         codeGenPasses->run(*it);
452
453     codeGenPasses->doFinalization();
454     return false; // success
455 }
456
457
458 /// Optimize merged modules using various IPO passes
459 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
460 {
461     std::string ops(options);
462     for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
463         // ParseCommandLineOptions() expects argv[0] to be program name.
464         // Lazily add that.
465         if ( _codegenOptions.empty() ) 
466             _codegenOptions.push_back("libLTO");
467         _codegenOptions.push_back(strdup(o.c_str()));
468     }
469 }