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