fixes from review of first commit
[oota-llvm.git] / tools / lto2 / 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/SystemUtils.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/System/Signals.h"
30 #include "llvm/Analysis/Passes.h"
31 #include "llvm/Analysis/LoopPass.h"
32 #include "llvm/Analysis/Verifier.h"
33 #include "llvm/Analysis/LoadValueNumbering.h"
34 #include "llvm/CodeGen/FileWriters.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetMachineRegistry.h"
39 #include "llvm/Target/TargetAsmInfo.h"
40 #include "llvm/Transforms/IPO.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Config/config.h"
43
44
45 #include <fstream>
46 #include <unistd.h>
47 #include <stdlib.h>
48 #include <fcntl.h>
49
50
51 using namespace llvm;
52
53
54
55 const char* LTOCodeGenerator::getVersionString()
56 {
57 #ifdef LLVM_VERSION_INFO
58     return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
59 #else
60     return PACKAGE_NAME " version " PACKAGE_VERSION;
61 #endif
62 }
63
64
65 LTOCodeGenerator::LTOCodeGenerator() 
66     : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
67       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
68       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
69       _nativeObjectFile(NULL)
70 {
71
72 }
73
74 LTOCodeGenerator::~LTOCodeGenerator()
75 {
76     delete _target;
77     delete _nativeObjectFile;
78 }
79
80
81
82 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
83 {
84     return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
85 }
86     
87
88 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
89 {
90     switch (debug) {
91         case LTO_DEBUG_MODEL_NONE:
92             _emitDwarfDebugInfo = false;
93             return false;
94             
95         case LTO_DEBUG_MODEL_DWARF:
96             _emitDwarfDebugInfo = true;
97             return false;
98     }
99     errMsg = "unknown debug format";
100     return true;
101 }
102
103
104 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model, 
105                                                         std::string& errMsg)
106 {
107     switch (model) {
108         case LTO_CODEGEN_PIC_MODEL_STATIC:
109         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
110         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
111             _codeModel = model;
112             return false;
113     }
114     errMsg = "unknown pic model";
115     return true;
116 }
117
118
119 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
120 {
121     _mustPreserveSymbols[sym] = 1;
122 }
123
124
125 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
126 {
127     if ( this->determineTarget(errMsg) ) 
128         return true;
129
130     // mark which symbols can not be internalized 
131     this->applyScopeRestrictions();
132
133     // create output file
134     std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
135     if ( out.fail() ) {
136         errMsg = "could not open bitcode file for writing: ";
137         errMsg += path;
138         return true;
139     }
140     
141     // write bitcode to it
142     WriteBitcodeToFile(_linker.getModule(), out);
143     if ( out.fail() ) {
144         errMsg = "could not write bitcode file: ";
145         errMsg += path;
146         return true;
147     }
148     
149     return false;
150 }
151
152
153 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
154 {
155     // make unique temp .s file to put generated assembly code
156     sys::Path uniqueAsmPath("lto-llvm.s");
157     if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
158         return NULL;
159     sys::RemoveFileOnSignal(uniqueAsmPath);
160        
161     // generate assembly code
162     std::ofstream asmFile(uniqueAsmPath.c_str());
163     bool genResult = this->generateAssemblyCode(asmFile, errMsg);
164     asmFile.close();
165     if ( genResult ) {
166         if ( uniqueAsmPath.exists() )
167             uniqueAsmPath.eraseFromDisk();
168         return NULL;
169     }
170     
171     // make unique temp .o file to put generated object file
172     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
173     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
174         if ( uniqueAsmPath.exists() )
175             uniqueAsmPath.eraseFromDisk();
176         return NULL;
177     }
178     sys::RemoveFileOnSignal(uniqueObjPath);
179
180     // assemble the assembly code
181     const std::string& uniqueObjStr = uniqueObjPath.toString();
182     bool asmResult = this->assemble(uniqueAsmPath.toString(), 
183                                                         uniqueObjStr, errMsg);
184     if ( !asmResult ) {
185         // remove old buffer if compile() called twice
186         delete _nativeObjectFile;
187         
188         // read .o file into memory buffer
189         _nativeObjectFile = MemoryBuffer::getFile(&uniqueObjStr[0], 
190                                                 uniqueObjStr.size(), &errMsg);
191     }
192
193     // remove temp files
194     uniqueAsmPath.eraseFromDisk();
195     uniqueObjPath.eraseFromDisk();
196
197     // return buffer, unless error
198     if ( _nativeObjectFile == NULL )
199         return NULL;
200     *length = _nativeObjectFile->getBufferSize();
201     return _nativeObjectFile->getBufferStart();
202 }
203
204
205 bool 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
255 bool 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;
265         std::string features;
266         _target = march->CtorFn(*mergedModule, features);
267     }
268     return false;
269 }
270
271 void LTOCodeGenerator::applyScopeRestrictions()
272 {
273     if ( !_scopeRestrictionsDone ) {
274         Module* mergedModule = _linker.getModule();
275
276         // Start off with a verification pass.
277         PassManager passes;
278         passes.add(createVerifierPass());
279
280         // mark which symbols can not be internalized 
281         if ( !_mustPreserveSymbols.empty() ) {
282             Mangler mangler(*mergedModule, 
283                                 _target->getTargetAsmInfo()->getGlobalPrefix());
284             std::vector<const char*> mustPreserveList;
285             for (Module::iterator f = mergedModule->begin(), 
286                                         e = mergedModule->end(); f != e; ++f) {
287                 if ( !f->isDeclaration() 
288                   && _mustPreserveSymbols.count(mangler.getValueName(f)) )
289                     mustPreserveList.push_back(::strdup(f->getName().c_str()));
290             }
291             for (Module::global_iterator v = mergedModule->global_begin(), 
292                                  e = mergedModule->global_end(); v !=  e; ++v) {
293                 if ( !v->isDeclaration()
294                   && _mustPreserveSymbols.count(mangler.getValueName(v)) )
295                     mustPreserveList.push_back(::strdup(v->getName().c_str()));
296             }
297             passes.add(createInternalizePass(mustPreserveList));
298         }
299         // apply scope restrictions
300         passes.run(*mergedModule);
301         
302         _scopeRestrictionsDone = true;
303     }
304 }
305
306
307 /// Optimize merged modules using various IPO passes
308 bool LTOCodeGenerator::generateAssemblyCode(std::ostream& out, std::string& errMsg)
309 {
310     if (  this->determineTarget(errMsg) ) 
311         return true;
312
313     // mark which symbols can not be internalized 
314     this->applyScopeRestrictions();
315
316     Module* mergedModule = _linker.getModule();
317
318      // If target supports exception handling then enable it now.
319     if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
320         llvm::ExceptionHandling = true;
321
322     // set codegen model
323     switch( _codeModel ) {
324         case LTO_CODEGEN_PIC_MODEL_STATIC:
325             _target->setRelocationModel(Reloc::Static);
326             break;
327         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
328             _target->setRelocationModel(Reloc::PIC_);
329             break;
330         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
331             _target->setRelocationModel(Reloc::DynamicNoPIC);
332             break;
333     }
334
335     // Instantiate the pass manager to organize the passes.
336     PassManager passes;
337
338     // Start off with a verification pass.
339     passes.add(createVerifierPass());
340
341     // Add an appropriate TargetData instance for this module...
342     passes.add(new TargetData(*_target->getTargetData()));
343     
344     // Now that we internalized some globals, see if we can hack on them!
345     passes.add(createGlobalOptimizerPass());
346
347     // Linking modules together can lead to duplicated global constants, only
348     // keep one copy of each constant...
349     passes.add(createConstantMergePass());
350
351     // If the -s command line option was specified, strip the symbols out of the
352     // resulting program to make it smaller.  -s is a GLD option that we are
353     // supporting.
354     if( !llvm::ExceptionHandling ) {
355         // FIXME : This causes multiple nameless _.eh symbols on 
356         // darwin when EH is ON.
357         passes.add(createStripSymbolsPass());
358     }
359     
360     // Propagate constants at call sites into the functions they call.
361     passes.add(createIPConstantPropagationPass());
362
363     // Remove unused arguments from functions...
364     passes.add(createDeadArgEliminationPass());
365
366     passes.add(createFunctionInliningPass()); // Inline small functions
367
368     passes.add(createPruneEHPass());            // Remove dead EH info
369
370     passes.add(createGlobalDCEPass());          // Remove dead functions
371
372     // If we didn't decide to inline a function, check to see if we can
373     // transform it to pass arguments by value instead of by reference.
374     passes.add(createArgumentPromotionPass());
375
376     // The IPO passes may leave cruft around.  Clean up after them.
377     passes.add(createInstructionCombiningPass());
378
379     passes.add(createScalarReplAggregatesPass()); // Break up allocas
380
381     // Run a few AA driven optimizations here and now, to cleanup the code.
382     passes.add(createGlobalsModRefPass());      // IP alias analysis
383
384     passes.add(createLICMPass());               // Hoist loop invariants
385     passes.add(createLoadValueNumberingPass()); // GVN for load instrs
386     passes.add(createGCSEPass());               // Remove common subexprs
387     passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
388
389     // Cleanup and simplify the code after the scalar optimizations.
390     passes.add(createInstructionCombiningPass());
391
392     // Delete basic blocks, which optimization passes may have killed...
393     passes.add(createCFGSimplificationPass());
394
395     // Now that we have optimized the program, discard unreachable functions...
396     passes.add(createGlobalDCEPass());
397
398     // Make sure everything is still good.
399     passes.add(createVerifierPass());
400
401     FunctionPassManager* codeGenPasses =
402             new FunctionPassManager(new ExistingModuleProvider(mergedModule));
403
404     codeGenPasses->add(new TargetData(*_target->getTargetData()));
405
406     MachineCodeEmitter* mce = NULL;
407
408     switch (_target->addPassesToEmitFile(*codeGenPasses, out,
409                                       TargetMachine::AssemblyFile, true)) {
410         case FileModel::MachOFile:
411             mce = AddMachOWriter(*codeGenPasses, out, *_target);
412             break;
413         case FileModel::ElfFile:
414             mce = AddELFWriter(*codeGenPasses, out, *_target);
415             break;
416         case FileModel::AsmFile:
417             break;
418         case FileModel::Error:
419         case FileModel::None:
420             errMsg = "target file type not supported";
421             return true;
422     }
423
424     if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce, true)) {
425         errMsg = "target does not support generation of this file type";
426         return true;
427     }
428
429     // Run our queue of passes all at once now, efficiently.
430     passes.run(*mergedModule);
431
432     // Run the code generator, and write assembly file
433     codeGenPasses->doInitialization();
434     for (Module::iterator it = mergedModule->begin(),
435                 e = mergedModule->end(); it != e; ++it) {
436         if (!it->isDeclaration())
437             codeGenPasses->run(*it);
438     }
439     codeGenPasses->doFinalization();
440
441     return false; // success
442 }
443
444
445