Kill off last uses of TargetMachineRegistry class.
[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/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/StandardPasses.h"
37 #include "llvm/Support/SystemUtils.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/TargetRegistry.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 asmFD(raw_fd_ostream(uniqueAsmPath.c_str(),
189                                           /*Binary=*/false, /*Force=*/true,
190                                           errMsg));
191       formatted_raw_ostream asmFile(asmFD);
192       if (!errMsg.empty())
193         return NULL;
194       genResult = this->generateAssemblyCode(asmFile, errMsg);
195     }
196     if ( genResult ) {
197         if ( uniqueAsmPath.exists() )
198             uniqueAsmPath.eraseFromDisk();
199         return NULL;
200     }
201     
202     // make unique temp .o file to put generated object file
203     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
204     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
205         if ( uniqueAsmPath.exists() )
206             uniqueAsmPath.eraseFromDisk();
207         return NULL;
208     }
209     sys::RemoveFileOnSignal(uniqueObjPath);
210
211     // assemble the assembly code
212     const std::string& uniqueObjStr = uniqueObjPath.toString();
213     bool asmResult = this->assemble(uniqueAsmPath.toString(), 
214                                                         uniqueObjStr, errMsg);
215     if ( !asmResult ) {
216         // remove old buffer if compile() called twice
217         delete _nativeObjectFile;
218         
219         // read .o file into memory buffer
220         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
221     }
222
223     // remove temp files
224     uniqueAsmPath.eraseFromDisk();
225     uniqueObjPath.eraseFromDisk();
226
227     // return buffer, unless error
228     if ( _nativeObjectFile == NULL )
229         return NULL;
230     *length = _nativeObjectFile->getBufferSize();
231     return _nativeObjectFile->getBufferStart();
232 }
233
234
235 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
236                                 const std::string& objPath, std::string& errMsg)
237 {
238     sys::Path tool;
239     bool needsCompilerOptions = true;
240     if ( _assemblerPath ) {
241         tool = *_assemblerPath;
242         needsCompilerOptions = false;
243     }
244     else if ( _gccPath ) {
245         tool = *_gccPath;
246     } else {
247         // find compiler driver
248         tool = sys::Program::FindProgramByName("gcc");
249         if ( tool.isEmpty() ) {
250             errMsg = "can't locate gcc";
251             return true;
252         }
253     }
254
255     // build argument list
256     std::vector<const char*> args;
257     std::string targetTriple = _linker.getModule()->getTargetTriple();
258     args.push_back(tool.c_str());
259     if ( targetTriple.find("darwin") != std::string::npos ) {
260         // darwin specific command line options
261         if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
262             args.push_back("-arch");
263             args.push_back("i386");
264         }
265         else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
266             args.push_back("-arch");
267             args.push_back("x86_64");
268         }
269         else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
270             args.push_back("-arch");
271             args.push_back("ppc");
272         }
273         else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
274             args.push_back("-arch");
275             args.push_back("ppc64");
276         }
277         else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
278             args.push_back("-arch");
279             args.push_back("arm");
280         }
281         else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
282                  (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
283             args.push_back("-arch");
284             args.push_back("armv4t");
285         }
286         else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
287                  (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
288                  (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
289                  (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
290             args.push_back("-arch");
291             args.push_back("armv5");
292         }
293         else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
294                  (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
295             args.push_back("-arch");
296             args.push_back("armv6");
297         }
298         else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
299                  (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
300             args.push_back("-arch");
301             args.push_back("armv7");
302         }
303         // add -static to assembler command line when code model requires
304         if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
305             args.push_back("-static");
306     }
307     if ( needsCompilerOptions ) {
308         args.push_back("-c");
309         args.push_back("-x");
310         args.push_back("assembler");
311     }
312     args.push_back("-o");
313     args.push_back(objPath.c_str());
314     args.push_back(asmPath.c_str());
315     args.push_back(0);
316
317     // invoke assembler
318     if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
319         errMsg = "error in assembly";    
320         return true;
321     }
322     return false; // success
323 }
324
325
326
327 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
328 {
329     if ( _target == NULL ) {
330         // create target machine from info for merged modules
331         Module* mergedModule = _linker.getModule();
332         const Target *march = 
333           TargetRegistry::getClosestStaticTargetForModule(*mergedModule, 
334                                                           errMsg);
335         if ( march == NULL )
336             return true;
337
338         // The relocation model is actually a static member of TargetMachine
339         // and needs to be set before the TargetMachine is instantiated.
340         switch( _codeModel ) {
341         case LTO_CODEGEN_PIC_MODEL_STATIC:
342             TargetMachine::setRelocationModel(Reloc::Static);
343             break;
344         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
345             TargetMachine::setRelocationModel(Reloc::PIC_);
346             break;
347         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
348             TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
349             break;
350         }
351
352         // construct LTModule, hand over ownership of module and target
353         std::string FeatureStr =
354           getFeatureString(_linker.getModule()->getTargetTriple().c_str());
355         _target = march->createTargetMachine(*mergedModule, FeatureStr.c_str());
356     }
357     return false;
358 }
359
360 void LTOCodeGenerator::applyScopeRestrictions()
361 {
362     if ( !_scopeRestrictionsDone ) {
363         Module* mergedModule = _linker.getModule();
364
365         // Start off with a verification pass.
366         PassManager passes;
367         passes.add(createVerifierPass());
368
369         // mark which symbols can not be internalized 
370         if ( !_mustPreserveSymbols.empty() ) {
371             Mangler mangler(*mergedModule, 
372                                 _target->getTargetAsmInfo()->getGlobalPrefix());
373             std::vector<const char*> mustPreserveList;
374             for (Module::iterator f = mergedModule->begin(), 
375                                         e = mergedModule->end(); f != e; ++f) {
376                 if ( !f->isDeclaration() 
377                   && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
378                     mustPreserveList.push_back(::strdup(f->getName().c_str()));
379             }
380             for (Module::global_iterator v = mergedModule->global_begin(), 
381                                  e = mergedModule->global_end(); v !=  e; ++v) {
382                 if ( !v->isDeclaration()
383                   && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
384                     mustPreserveList.push_back(::strdup(v->getName().c_str()));
385             }
386             passes.add(createInternalizePass(mustPreserveList));
387         }
388         // apply scope restrictions
389         passes.run(*mergedModule);
390         
391         _scopeRestrictionsDone = true;
392     }
393 }
394
395 /// Optimize merged modules using various IPO passes
396 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
397                                             std::string& errMsg)
398 {
399     if (  this->determineTarget(errMsg) ) 
400         return true;
401
402     // mark which symbols can not be internalized 
403     this->applyScopeRestrictions();
404
405     Module* mergedModule = _linker.getModule();
406
407      // If target supports exception handling then enable it now.
408     if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
409         llvm::ExceptionHandling = true;
410
411     // if options were requested, set them
412     if ( !_codegenOptions.empty() )
413         cl::ParseCommandLineOptions(_codegenOptions.size(), 
414                                                 (char**)&_codegenOptions[0]);
415
416     // Instantiate the pass manager to organize the passes.
417     PassManager passes;
418
419     // Start off with a verification pass.
420     passes.add(createVerifierPass());
421
422     // Add an appropriate TargetData instance for this module...
423     passes.add(new TargetData(*_target->getTargetData()));
424     
425     createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
426                             /*VerifyEach=*/ false);
427
428     // Make sure everything is still good.
429     passes.add(createVerifierPass());
430
431     FunctionPassManager* codeGenPasses =
432             new FunctionPassManager(new ExistingModuleProvider(mergedModule));
433
434     codeGenPasses->add(new TargetData(*_target->getTargetData()));
435
436     ObjectCodeEmitter* oce = NULL;
437
438     switch (_target->addPassesToEmitFile(*codeGenPasses, out,
439                                          TargetMachine::AssemblyFile,
440                                          CodeGenOpt::Aggressive)) {
441         case FileModel::MachOFile:
442             oce = AddMachOWriter(*codeGenPasses, out, *_target);
443             break;
444         case FileModel::ElfFile:
445             oce = AddELFWriter(*codeGenPasses, out, *_target);
446             break;
447         case FileModel::AsmFile:
448             break;
449         case FileModel::Error:
450         case FileModel::None:
451             errMsg = "target file type not supported";
452             return true;
453     }
454
455     if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
456                                            CodeGenOpt::Aggressive)) {
457         errMsg = "target does not support generation of this file type";
458         return true;
459     }
460
461     // Run our queue of passes all at once now, efficiently.
462     passes.run(*mergedModule);
463
464     // Run the code generator, and write assembly file
465     codeGenPasses->doInitialization();
466
467     for (Module::iterator
468            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
469       if (!it->isDeclaration())
470         codeGenPasses->run(*it);
471
472     codeGenPasses->doFinalization();
473     return false; // success
474 }
475
476
477 /// Optimize merged modules using various IPO passes
478 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
479 {
480     std::string ops(options);
481     for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
482         // ParseCommandLineOptions() expects argv[0] to be program name.
483         // Lazily add that.
484         if ( _codegenOptions.empty() ) 
485             _codegenOptions.push_back("libLTO");
486         _codegenOptions.push_back(strdup(o.c_str()));
487     }
488 }