190578e2630c484d40d41d897a1b211d257e8684
[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/Host.h"
39 #include "llvm/System/Signals.h"
40 #include "llvm/Target/SubtargetFeature.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetAsmInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetRegistry.h"
46 #include "llvm/Target/TargetSelect.h"
47 #include "llvm/Transforms/IPO.h"
48 #include "llvm/Transforms/Scalar.h"
49 #include "llvm/Config/config.h"
50
51
52 #include <cstdlib>
53 #include <fstream>
54 #include <unistd.h>
55 #include <fcntl.h>
56
57
58 using namespace llvm;
59
60 static cl::opt<bool> DisableInline("disable-inlining",
61   cl::desc("Do not run the inliner pass"));
62
63
64 const char* LTOCodeGenerator::getVersionString()
65 {
66 #ifdef LLVM_VERSION_INFO
67     return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
68 #else
69     return PACKAGE_NAME " version " PACKAGE_VERSION;
70 #endif
71 }
72
73
74 LTOCodeGenerator::LTOCodeGenerator() 
75     : _context(getGlobalContext()),
76       _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
77       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
78       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
79       _nativeObjectFile(NULL), _assemblerPath(NULL)
80 {
81     InitializeAllTargets();
82     InitializeAllAsmPrinters();
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::setAssemblerPath(const char* path)
130 {
131     if ( _assemblerPath )
132         delete _assemblerPath;
133     _assemblerPath = new sys::Path(path);
134 }
135
136 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
137 {
138     _mustPreserveSymbols[sym] = 1;
139 }
140
141
142 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
143 {
144     if ( this->determineTarget(errMsg) ) 
145         return true;
146
147     // mark which symbols can not be internalized 
148     this->applyScopeRestrictions();
149
150     // create output file
151     std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
152     if ( out.fail() ) {
153         errMsg = "could not open bitcode file for writing: ";
154         errMsg += path;
155         return true;
156     }
157     
158     // write bitcode to it
159     WriteBitcodeToFile(_linker.getModule(), out);
160     if ( out.fail() ) {
161         errMsg = "could not write bitcode file: ";
162         errMsg += path;
163         return true;
164     }
165     
166     return false;
167 }
168
169
170 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
171 {
172     // make unique temp .s file to put generated assembly code
173     sys::Path uniqueAsmPath("lto-llvm.s");
174     if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
175         return NULL;
176     sys::RemoveFileOnSignal(uniqueAsmPath);
177        
178     // generate assembly code
179     bool genResult = false;
180     {
181       raw_fd_ostream asmFD(uniqueAsmPath.c_str(),
182                            /*Binary=*/false, /*Force=*/true,
183                            errMsg);
184       formatted_raw_ostream asmFile(asmFD);
185       if (!errMsg.empty())
186         return NULL;
187       genResult = this->generateAssemblyCode(asmFile, errMsg);
188     }
189     if ( genResult ) {
190         if ( uniqueAsmPath.exists() )
191             uniqueAsmPath.eraseFromDisk();
192         return NULL;
193     }
194     
195     // make unique temp .o file to put generated object file
196     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
197     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
198         if ( uniqueAsmPath.exists() )
199             uniqueAsmPath.eraseFromDisk();
200         return NULL;
201     }
202     sys::RemoveFileOnSignal(uniqueObjPath);
203
204     // assemble the assembly code
205     const std::string& uniqueObjStr = uniqueObjPath.toString();
206     bool asmResult = this->assemble(uniqueAsmPath.toString(), 
207                                                         uniqueObjStr, errMsg);
208     if ( !asmResult ) {
209         // remove old buffer if compile() called twice
210         delete _nativeObjectFile;
211         
212         // read .o file into memory buffer
213         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
214     }
215
216     // remove temp files
217     uniqueAsmPath.eraseFromDisk();
218     uniqueObjPath.eraseFromDisk();
219
220     // return buffer, unless error
221     if ( _nativeObjectFile == NULL )
222         return NULL;
223     *length = _nativeObjectFile->getBufferSize();
224     return _nativeObjectFile->getBufferStart();
225 }
226
227
228 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
229                                 const std::string& objPath, std::string& errMsg)
230 {
231     sys::Path tool;
232     bool needsCompilerOptions = true;
233     if ( _assemblerPath ) {
234         tool = *_assemblerPath;
235         needsCompilerOptions = false;
236     } else {
237         // find compiler driver
238         tool = sys::Program::FindProgramByName("gcc");
239         if ( tool.isEmpty() ) {
240             errMsg = "can't locate gcc";
241             return true;
242         }
243     }
244
245     // build argument list
246     std::vector<const char*> args;
247     std::string targetTriple = _linker.getModule()->getTargetTriple();
248     args.push_back(tool.c_str());
249     if ( targetTriple.find("darwin") != std::string::npos ) {
250         // darwin specific command line options
251         if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
252             args.push_back("-arch");
253             args.push_back("i386");
254         }
255         else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
256             args.push_back("-arch");
257             args.push_back("x86_64");
258         }
259         else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
260             args.push_back("-arch");
261             args.push_back("ppc");
262         }
263         else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
264             args.push_back("-arch");
265             args.push_back("ppc64");
266         }
267         else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
268             args.push_back("-arch");
269             args.push_back("arm");
270         }
271         else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
272                  (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
273             args.push_back("-arch");
274             args.push_back("armv4t");
275         }
276         else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
277                  (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
278                  (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
279                  (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
280             args.push_back("-arch");
281             args.push_back("armv5");
282         }
283         else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
284                  (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
285             args.push_back("-arch");
286             args.push_back("armv6");
287         }
288         else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
289                  (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
290             args.push_back("-arch");
291             args.push_back("armv7");
292         }
293         // add -static to assembler command line when code model requires
294         if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
295             args.push_back("-static");
296     }
297     if ( needsCompilerOptions ) {
298         args.push_back("-c");
299         args.push_back("-x");
300         args.push_back("assembler");
301     }
302     args.push_back("-o");
303     args.push_back(objPath.c_str());
304     args.push_back(asmPath.c_str());
305     args.push_back(0);
306
307     // invoke assembler
308     if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
309         errMsg = "error in assembly";    
310         return true;
311     }
312     return false; // success
313 }
314
315
316
317 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
318 {
319     if ( _target == NULL ) {
320         std::string Triple = _linker.getModule()->getTargetTriple();
321         if (Triple.empty())
322           Triple = sys::getHostTriple();
323
324         // create target machine from info for merged modules
325         const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
326         if ( march == NULL )
327             return true;
328
329         // The relocation model is actually a static member of TargetMachine
330         // and needs to be set before the TargetMachine is instantiated.
331         switch( _codeModel ) {
332         case LTO_CODEGEN_PIC_MODEL_STATIC:
333             TargetMachine::setRelocationModel(Reloc::Static);
334             break;
335         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
336             TargetMachine::setRelocationModel(Reloc::PIC_);
337             break;
338         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
339             TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
340             break;
341         }
342
343         // construct LTModule, hand over ownership of module and target
344         std::string FeatureStr = getFeatureString(Triple.c_str());
345         _target = march->createTargetMachine(Triple, FeatureStr);
346     }
347     return false;
348 }
349
350 void LTOCodeGenerator::applyScopeRestrictions()
351 {
352     if ( !_scopeRestrictionsDone ) {
353         Module* mergedModule = _linker.getModule();
354
355         // Start off with a verification pass.
356         PassManager passes;
357         passes.add(createVerifierPass());
358
359         // mark which symbols can not be internalized 
360         if ( !_mustPreserveSymbols.empty() ) {
361             Mangler mangler(*mergedModule, 
362                                 _target->getTargetAsmInfo()->getGlobalPrefix());
363             std::vector<const char*> mustPreserveList;
364             for (Module::iterator f = mergedModule->begin(), 
365                                         e = mergedModule->end(); f != e; ++f) {
366                 if ( !f->isDeclaration() 
367                   && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
368                   mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
369             }
370             for (Module::global_iterator v = mergedModule->global_begin(), 
371                                  e = mergedModule->global_end(); v !=  e; ++v) {
372                 if ( !v->isDeclaration()
373                   && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
374                   mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
375             }
376             passes.add(createInternalizePass(mustPreserveList));
377         }
378         // apply scope restrictions
379         passes.run(*mergedModule);
380         
381         _scopeRestrictionsDone = true;
382     }
383 }
384
385 /// Optimize merged modules using various IPO passes
386 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
387                                             std::string& errMsg)
388 {
389     if ( this->determineTarget(errMsg) ) 
390         return true;
391
392     // mark which symbols can not be internalized 
393     this->applyScopeRestrictions();
394
395     Module* mergedModule = _linker.getModule();
396
397     // If target supports exception handling then enable it now.
398     switch (_target->getTargetAsmInfo()->getExceptionHandlingType()) {
399     case ExceptionHandling::Dwarf:
400       llvm::DwarfExceptionHandling = true;
401       break;
402     case ExceptionHandling::SjLj:
403       llvm::SjLjExceptionHandling = true;
404       break;
405     case ExceptionHandling::None:
406       break;
407     default:
408       assert (0 && "Unknown exception handling model!");
409     }
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
474     out.flush();
475
476     return false; // success
477 }
478
479
480 /// Optimize merged modules using various IPO passes
481 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
482 {
483     std::string ops(options);
484     for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
485         // ParseCommandLineOptions() expects argv[0] to be program name.
486         // Lazily add that.
487         if ( _codegenOptions.empty() ) 
488             _codegenOptions.push_back("libLTO");
489         _codegenOptions.push_back(strdup(o.c_str()));
490     }
491 }