Add the Object Code Emitter class. Original patch by Aaron Gray, I did some
[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/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Linker.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/Passes.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Analysis/Verifier.h"
30 #include "llvm/Bitcode/ReaderWriter.h"
31 #include "llvm/CodeGen/FileWriters.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Mangler.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/StandardPasses.h"
36 #include "llvm/Support/SystemUtils.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/System/Signals.h"
39 #include "llvm/Target/SubtargetFeature.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetAsmInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetMachineRegistry.h"
45 #include "llvm/Target/TargetSelect.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Config/config.h"
49
50
51 #include <cstdlib>
52 #include <fstream>
53 #include <unistd.h>
54 #include <fcntl.h>
55
56
57 using namespace llvm;
58
59 static cl::opt<bool> DisableInline("disable-inlining",
60   cl::desc("Do not run the inliner pass"));
61
62
63 const char* LTOCodeGenerator::getVersionString()
64 {
65 #ifdef LLVM_VERSION_INFO
66     return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 #else
68     return PACKAGE_NAME " version " PACKAGE_VERSION;
69 #endif
70 }
71
72
73 LTOCodeGenerator::LTOCodeGenerator() 
74     : _context(getGlobalContext()),
75       _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
76       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
77       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
78       _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(NULL)
79 {
80   InitializeAllTargets();
81   InitializeAllAsmPrinters();
82
83 }
84
85 LTOCodeGenerator::~LTOCodeGenerator()
86 {
87     delete _target;
88     delete _nativeObjectFile;
89 }
90
91
92
93 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
94 {
95     return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
96 }
97     
98
99 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
100 {
101     switch (debug) {
102         case LTO_DEBUG_MODEL_NONE:
103             _emitDwarfDebugInfo = false;
104             return false;
105             
106         case LTO_DEBUG_MODEL_DWARF:
107             _emitDwarfDebugInfo = true;
108             return false;
109     }
110     errMsg = "unknown debug format";
111     return true;
112 }
113
114
115 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model, 
116                                        std::string& errMsg)
117 {
118     switch (model) {
119         case LTO_CODEGEN_PIC_MODEL_STATIC:
120         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
121         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
122             _codeModel = model;
123             return false;
124     }
125     errMsg = "unknown pic model";
126     return true;
127 }
128
129 void LTOCodeGenerator::setGccPath(const char* path)
130 {
131     if ( _gccPath )
132         delete _gccPath;
133     _gccPath = new sys::Path(path);
134 }
135
136 void LTOCodeGenerator::setAssemblerPath(const char* path)
137 {
138     if ( _assemblerPath )
139         delete _assemblerPath;
140     _assemblerPath = new sys::Path(path);
141 }
142
143 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
144 {
145     _mustPreserveSymbols[sym] = 1;
146 }
147
148
149 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
150 {
151     if ( this->determineTarget(errMsg) ) 
152         return true;
153
154     // mark which symbols can not be internalized 
155     this->applyScopeRestrictions();
156
157     // create output file
158     std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
159     if ( out.fail() ) {
160         errMsg = "could not open bitcode file for writing: ";
161         errMsg += path;
162         return true;
163     }
164     
165     // write bitcode to it
166     WriteBitcodeToFile(_linker.getModule(), out);
167     if ( out.fail() ) {
168         errMsg = "could not write bitcode file: ";
169         errMsg += path;
170         return true;
171     }
172     
173     return false;
174 }
175
176
177 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
178 {
179     // make unique temp .s file to put generated assembly code
180     sys::Path uniqueAsmPath("lto-llvm.s");
181     if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
182         return NULL;
183     sys::RemoveFileOnSignal(uniqueAsmPath);
184        
185     // generate assembly code
186     bool genResult = false;
187     {
188       raw_fd_ostream asmFile(uniqueAsmPath.c_str(), false, errMsg);
189       if (!errMsg.empty())
190         return NULL;
191       genResult = this->generateAssemblyCode(asmFile, errMsg);
192     }
193     if ( genResult ) {
194         if ( uniqueAsmPath.exists() )
195             uniqueAsmPath.eraseFromDisk();
196         return NULL;
197     }
198     
199     // make unique temp .o file to put generated object file
200     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
201     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
202         if ( uniqueAsmPath.exists() )
203             uniqueAsmPath.eraseFromDisk();
204         return NULL;
205     }
206     sys::RemoveFileOnSignal(uniqueObjPath);
207
208     // assemble the assembly code
209     const std::string& uniqueObjStr = uniqueObjPath.toString();
210     bool asmResult = this->assemble(uniqueAsmPath.toString(), 
211                                                         uniqueObjStr, errMsg);
212     if ( !asmResult ) {
213         // remove old buffer if compile() called twice
214         delete _nativeObjectFile;
215         
216         // read .o file into memory buffer
217         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
218     }
219
220     // remove temp files
221     uniqueAsmPath.eraseFromDisk();
222     uniqueObjPath.eraseFromDisk();
223
224     // return buffer, unless error
225     if ( _nativeObjectFile == NULL )
226         return NULL;
227     *length = _nativeObjectFile->getBufferSize();
228     return _nativeObjectFile->getBufferStart();
229 }
230
231
232 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
233                                 const std::string& objPath, std::string& errMsg)
234 {
235     sys::Path tool;
236     bool needsCompilerOptions = true;
237     if ( _assemblerPath ) {
238         tool = *_assemblerPath;
239         needsCompilerOptions = false;
240     }
241     else if ( _gccPath ) {
242         tool = *_gccPath;
243     } else {
244         // find compiler driver
245         tool = sys::Program::FindProgramByName("gcc");
246         if ( tool.isEmpty() ) {
247             errMsg = "can't locate gcc";
248             return true;
249         }
250     }
251
252     // build argument list
253     std::vector<const char*> args;
254     std::string targetTriple = _linker.getModule()->getTargetTriple();
255     args.push_back(tool.c_str());
256     if ( targetTriple.find("darwin") != std::string::npos ) {
257         // darwin specific command line options
258         if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
259             args.push_back("-arch");
260             args.push_back("i386");
261         }
262         else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
263             args.push_back("-arch");
264             args.push_back("x86_64");
265         }
266         else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
267             args.push_back("-arch");
268             args.push_back("ppc");
269         }
270         else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
271             args.push_back("-arch");
272             args.push_back("ppc64");
273         }
274         else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
275             args.push_back("-arch");
276             args.push_back("arm");
277         }
278         else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
279                  (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
280             args.push_back("-arch");
281             args.push_back("armv4t");
282         }
283         else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
284                  (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
285                  (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
286                  (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
287             args.push_back("-arch");
288             args.push_back("armv5");
289         }
290         else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
291                  (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
292             args.push_back("-arch");
293             args.push_back("armv6");
294         }
295         else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
296                  (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
297             args.push_back("-arch");
298             args.push_back("armv7");
299         }
300         // add -static to assembler command line when code model requires
301         if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
302             args.push_back("-static");
303     }
304     if ( needsCompilerOptions ) {
305         args.push_back("-c");
306         args.push_back("-x");
307         args.push_back("assembler");
308     }
309     args.push_back("-o");
310     args.push_back(objPath.c_str());
311     args.push_back(asmPath.c_str());
312     args.push_back(0);
313
314     // invoke assembler
315     if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
316         errMsg = "error in assembly";    
317         return true;
318     }
319     return false; // success
320 }
321
322
323
324 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
325 {
326     if ( _target == NULL ) {
327         // create target machine from info for merged modules
328         Module* mergedModule = _linker.getModule();
329         const TargetMachineRegistry::entry* march = 
330           TargetMachineRegistry::getClosestStaticTargetForModule(
331                                                        *mergedModule, errMsg);
332         if ( march == NULL )
333             return true;
334
335         // The relocation model is actually a static member of TargetMachine
336         // and needs to be set before the TargetMachine is instantiated.
337         switch( _codeModel ) {
338         case LTO_CODEGEN_PIC_MODEL_STATIC:
339             TargetMachine::setRelocationModel(Reloc::Static);
340             break;
341         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
342             TargetMachine::setRelocationModel(Reloc::PIC_);
343             break;
344         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
345             TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
346             break;
347         }
348
349         // construct LTModule, hand over ownership of module and target
350         std::string FeatureStr =
351           getFeatureString(_linker.getModule()->getTargetTriple().c_str());
352         _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
353     }
354     return false;
355 }
356
357 void LTOCodeGenerator::applyScopeRestrictions()
358 {
359     if ( !_scopeRestrictionsDone ) {
360         Module* mergedModule = _linker.getModule();
361
362         // Start off with a verification pass.
363         PassManager passes;
364         passes.add(createVerifierPass());
365
366         // mark which symbols can not be internalized 
367         if ( !_mustPreserveSymbols.empty() ) {
368             Mangler mangler(*mergedModule, 
369                                 _target->getTargetAsmInfo()->getGlobalPrefix());
370             std::vector<const char*> mustPreserveList;
371             for (Module::iterator f = mergedModule->begin(), 
372                                         e = mergedModule->end(); f != e; ++f) {
373                 if ( !f->isDeclaration() 
374                   && _mustPreserveSymbols.count(mangler.getValueName(f)) )
375                     mustPreserveList.push_back(::strdup(f->getName().c_str()));
376             }
377             for (Module::global_iterator v = mergedModule->global_begin(), 
378                                  e = mergedModule->global_end(); v !=  e; ++v) {
379                 if ( !v->isDeclaration()
380                   && _mustPreserveSymbols.count(mangler.getValueName(v)) )
381                     mustPreserveList.push_back(::strdup(v->getName().c_str()));
382             }
383             passes.add(createInternalizePass(mustPreserveList));
384         }
385         // apply scope restrictions
386         passes.run(*mergedModule);
387         
388         _scopeRestrictionsDone = true;
389     }
390 }
391
392 /// Optimize merged modules using various IPO passes
393 bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
394                                             std::string& errMsg)
395 {
396     if (  this->determineTarget(errMsg) ) 
397         return true;
398
399     // mark which symbols can not be internalized 
400     this->applyScopeRestrictions();
401
402     Module* mergedModule = _linker.getModule();
403
404      // If target supports exception handling then enable it now.
405     if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
406         llvm::ExceptionHandling = true;
407
408     // if options were requested, set them
409     if ( !_codegenOptions.empty() )
410         cl::ParseCommandLineOptions(_codegenOptions.size(), 
411                                                 (char**)&_codegenOptions[0]);
412
413     // Instantiate the pass manager to organize the passes.
414     PassManager passes;
415
416     // Start off with a verification pass.
417     passes.add(createVerifierPass());
418
419     // Add an appropriate TargetData instance for this module...
420     passes.add(new TargetData(*_target->getTargetData()));
421     
422     createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
423                             /*VerifyEach=*/ false);
424
425     // Make sure everything is still good.
426     passes.add(createVerifierPass());
427
428     FunctionPassManager* codeGenPasses =
429             new FunctionPassManager(new ExistingModuleProvider(mergedModule));
430
431     codeGenPasses->add(new TargetData(*_target->getTargetData()));
432
433     ObjectCodeEmitter* oce = NULL;
434
435     switch (_target->addPassesToEmitFile(*codeGenPasses, out,
436                                          TargetMachine::AssemblyFile,
437                                          CodeGenOpt::Aggressive)) {
438         case FileModel::MachOFile:
439             oce = AddMachOWriter(*codeGenPasses, out, *_target);
440             break;
441         case FileModel::ElfFile:
442             oce = AddELFWriter(*codeGenPasses, out, *_target);
443             break;
444         case FileModel::AsmFile:
445             break;
446         case FileModel::Error:
447         case FileModel::None:
448             errMsg = "target file type not supported";
449             return true;
450     }
451
452     if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
453                                            CodeGenOpt::Aggressive)) {
454         errMsg = "target does not support generation of this file type";
455         return true;
456     }
457
458     // Run our queue of passes all at once now, efficiently.
459     passes.run(*mergedModule);
460
461     // Run the code generator, and write assembly file
462     codeGenPasses->doInitialization();
463
464     for (Module::iterator
465            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
466       if (!it->isDeclaration())
467         codeGenPasses->run(*it);
468
469     codeGenPasses->doFinalization();
470     return false; // success
471 }
472
473
474 /// Optimize merged modules using various IPO passes
475 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
476 {
477     std::string ops(options);
478     for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
479         // ParseCommandLineOptions() expects argv[0] to be program name.
480         // Lazily add that.
481         if ( _codegenOptions.empty() ) 
482             _codegenOptions.push_back("libLTO");
483         _codegenOptions.push_back(strdup(o.c_str()));
484     }
485 }