blob: ffe244dbcdc172a7fe33d105694c2f764fc9bdee [file] [log] [blame]
Nick Kledzik77595fc2008-02-26 20:26:43 +00001//===-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
Nick Kledzikef194ed2008-02-27 22:25:36 +000015#include "LTOModule.h"
16#include "LTOCodeGenerator.h"
17
Nick Kledzik77595fc2008-02-26 20:26:43 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000020#include "llvm/Linker.h"
Owen Anderson0e7a5462009-07-02 00:31:14 +000021#include "llvm/LLVMContext.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000022#include "llvm/Module.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000023#include "llvm/PassManager.h"
24#include "llvm/ADT/StringExtras.h"
Viktor Kutuzov51cdac02009-11-17 18:48:27 +000025#include "llvm/ADT/Triple.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000026#include "llvm/Analysis/Passes.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000027#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000028#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCContext.h"
30#include "llvm/Target/Mangler.h"
31#include "llvm/Target/SubtargetFeature.h"
32#include "llvm/Target/TargetOptions.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetRegistry.h"
36#include "llvm/Target/TargetSelect.h"
Nick Kledzik920ae982008-07-08 21:14:10 +000037#include "llvm/Support/CommandLine.h"
David Greene71847812009-07-14 20:18:05 +000038#include "llvm/Support/FormattedStream.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000039#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar006a0342009-06-03 21:06:14 +000040#include "llvm/Support/StandardPasses.h"
41#include "llvm/Support/SystemUtils.h"
Dan Gohman9f36c4e2010-10-07 20:48:46 +000042#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000046#include "llvm/Support/system_error.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000047#include "llvm/Config/config.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000048#include <cstdlib>
Nick Kledzik77595fc2008-02-26 20:26:43 +000049#include <unistd.h>
Nick Kledzik77595fc2008-02-26 20:26:43 +000050#include <fcntl.h>
51
52
53using namespace llvm;
54
Nick Kledzik920ae982008-07-08 21:14:10 +000055static cl::opt<bool> DisableInline("disable-inlining",
56 cl::desc("Do not run the inliner pass"));
Nick Kledzik77595fc2008-02-26 20:26:43 +000057
58
59const char* LTOCodeGenerator::getVersionString()
60{
61#ifdef LLVM_VERSION_INFO
62 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
63#else
64 return PACKAGE_NAME " version " PACKAGE_VERSION;
65#endif
66}
67
68
Owen Anderson0e7a5462009-07-02 00:31:14 +000069LTOCodeGenerator::LTOCodeGenerator()
70 : _context(getGlobalContext()),
Owen Anderson8b477ed2009-07-01 16:58:40 +000071 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
Nick Kledzik77595fc2008-02-26 20:26:43 +000072 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzikef194ed2008-02-27 22:25:36 +000073 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Rafael Espindolae9efea12011-02-24 21:04:06 +000074 _nativeObjectFile(NULL)
Nick Kledzik77595fc2008-02-26 20:26:43 +000075{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000076 InitializeAllTargets();
77 InitializeAllAsmPrinters();
Nick Kledzik77595fc2008-02-26 20:26:43 +000078}
79
80LTOCodeGenerator::~LTOCodeGenerator()
81{
Nick Kledzikef194ed2008-02-27 22:25:36 +000082 delete _target;
83 delete _nativeObjectFile;
Nick Kledzik77595fc2008-02-26 20:26:43 +000084}
85
86
87
88bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
89{
Rafael Espindolaf19d7a72011-03-18 19:51:00 +000090
91 if(mod->getLLVVMModule()->MaterializeAllPermanently(&errMsg))
92 return true;
93
Rafael Espindola38c4e532011-03-02 04:14:42 +000094 bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
95
96 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
97 for (int i = 0, e = undefs.size(); i != e; ++i)
98 _asmUndefinedRefs[undefs[i]] = 1;
99
100 return ret;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000101}
102
103
104bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
105{
106 switch (debug) {
107 case LTO_DEBUG_MODEL_NONE:
108 _emitDwarfDebugInfo = false;
109 return false;
110
111 case LTO_DEBUG_MODEL_DWARF:
112 _emitDwarfDebugInfo = true;
113 return false;
114 }
115 errMsg = "unknown debug format";
116 return true;
117}
118
119
120bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
Evan Cheng855a1682009-06-26 06:57:16 +0000121 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000122{
123 switch (model) {
124 case LTO_CODEGEN_PIC_MODEL_STATIC:
125 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
126 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
127 _codeModel = model;
128 return false;
129 }
130 errMsg = "unknown pic model";
131 return true;
132}
133
Rafael Espindola2d643ef2010-08-11 00:15:13 +0000134void LTOCodeGenerator::setCpu(const char* mCpu)
135{
136 _mCpu = mCpu;
137}
138
Nick Kledzik77595fc2008-02-26 20:26:43 +0000139void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
140{
141 _mustPreserveSymbols[sym] = 1;
142}
143
144
Chris Lattnerb515d752009-08-23 07:49:08 +0000145bool LTOCodeGenerator::writeMergedModules(const char *path,
146 std::string &errMsg) {
147 if (determineTarget(errMsg))
148 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000149
Chris Lattnerb515d752009-08-23 07:49:08 +0000150 // mark which symbols can not be internalized
151 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000152
Chris Lattnerb515d752009-08-23 07:49:08 +0000153 // create output file
154 std::string ErrInfo;
Dan Gohmanf2914012010-08-20 16:59:15 +0000155 tool_output_file Out(path, ErrInfo,
156 raw_fd_ostream::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000157 if (!ErrInfo.empty()) {
158 errMsg = "could not open bitcode file for writing: ";
159 errMsg += path;
160 return true;
161 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000162
Chris Lattnerb515d752009-08-23 07:49:08 +0000163 // write bitcode to it
Dan Gohmand4c45432010-09-01 14:20:41 +0000164 WriteBitcodeToFile(_linker.getModule(), Out.os());
165 Out.os().close();
Dan Gohman4b7416b2010-05-27 20:19:47 +0000166
Dan Gohmand4c45432010-09-01 14:20:41 +0000167 if (Out.os().has_error()) {
Chris Lattnerb515d752009-08-23 07:49:08 +0000168 errMsg = "could not write bitcode file: ";
169 errMsg += path;
Dan Gohmand4c45432010-09-01 14:20:41 +0000170 Out.os().clear_error();
Chris Lattnerb515d752009-08-23 07:49:08 +0000171 return true;
172 }
173
Dan Gohmanf2914012010-08-20 16:59:15 +0000174 Out.keep();
Chris Lattnerb515d752009-08-23 07:49:08 +0000175 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000176}
177
178
Nick Kledzikef194ed2008-02-27 22:25:36 +0000179const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000180{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000181 // make unique temp .o file to put generated object file
Nick Kledzik77595fc2008-02-26 20:26:43 +0000182 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
Devang Patelb7bbd462010-12-03 23:58:31 +0000183 if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
Rafael Espindolae9efea12011-02-24 21:04:06 +0000184 uniqueObjPath.eraseFromDisk();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000185 return NULL;
186 }
187 sys::RemoveFileOnSignal(uniqueObjPath);
188
Rafael Espindolae9efea12011-02-24 21:04:06 +0000189 // generate object file
190 bool genResult = false;
191 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
192 if (!errMsg.empty())
193 return NULL;
194 genResult = this->generateObjectFile(objFile.os(), errMsg);
195 objFile.os().close();
196 if (objFile.os().has_error()) {
197 objFile.os().clear_error();
198 return NULL;
199 }
200 objFile.keep();
201 if ( genResult ) {
202 uniqueObjPath.eraseFromDisk();
203 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000204 }
Nick Kledzikef194ed2008-02-27 22:25:36 +0000205
Rafael Espindolae9efea12011-02-24 21:04:06 +0000206 const std::string& uniqueObjStr = uniqueObjPath.str();
207 // remove old buffer if compile() called twice
208 delete _nativeObjectFile;
209
210 // read .o file into memory buffer
211 OwningPtr<MemoryBuffer> BuffPtr;
212 if (error_code ec = MemoryBuffer::getFile(uniqueObjStr.c_str(),BuffPtr))
213 errMsg = ec.message();
214 _nativeObjectFile = BuffPtr.take();
215
Nick Kledzikef194ed2008-02-27 22:25:36 +0000216 // remove temp files
Nick Kledzik77595fc2008-02-26 20:26:43 +0000217 uniqueObjPath.eraseFromDisk();
Nick Kledzikef194ed2008-02-27 22:25:36 +0000218
219 // return buffer, unless error
220 if ( _nativeObjectFile == NULL )
221 return NULL;
222 *length = _nativeObjectFile->getBufferSize();
223 return _nativeObjectFile->getBufferStart();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000224}
225
Nick Kledzik77595fc2008-02-26 20:26:43 +0000226bool LTOCodeGenerator::determineTarget(std::string& errMsg)
227{
228 if ( _target == NULL ) {
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000229 std::string Triple = _linker.getModule()->getTargetTriple();
230 if (Triple.empty())
231 Triple = sys::getHostTriple();
232
Nick Kledzik77595fc2008-02-26 20:26:43 +0000233 // create target machine from info for merged modules
Daniel Dunbar4bd03ab2009-08-03 04:20:57 +0000234 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000235 if ( march == NULL )
236 return true;
Bill Wendling604a8182008-06-18 06:35:30 +0000237
Nick Kledzikf5a1c35f12009-06-03 22:52:12 +0000238 // The relocation model is actually a static member of TargetMachine
239 // and needs to be set before the TargetMachine is instantiated.
240 switch( _codeModel ) {
241 case LTO_CODEGEN_PIC_MODEL_STATIC:
242 TargetMachine::setRelocationModel(Reloc::Static);
243 break;
244 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
245 TargetMachine::setRelocationModel(Reloc::PIC_);
246 break;
247 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
248 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
249 break;
250 }
251
Bill Wendling604a8182008-06-18 06:35:30 +0000252 // construct LTModule, hand over ownership of module and target
Bill Wendling81043ee2010-05-11 00:30:02 +0000253 SubtargetFeatures Features;
Rafael Espindola2d643ef2010-08-11 00:15:13 +0000254 Features.getDefaultSubtargetFeatures(_mCpu, llvm::Triple(Triple));
Bill Wendling81043ee2010-05-11 00:30:02 +0000255 std::string FeatureStr = Features.getString();
Viktor Kutuzov308f6632009-11-25 22:44:18 +0000256 _target = march->createTargetMachine(Triple, FeatureStr);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000257 }
258 return false;
259}
260
Rafael Espindola38c4e532011-03-02 04:14:42 +0000261void LTOCodeGenerator::applyRestriction(GlobalValue &GV,
262 std::vector<const char*> &mustPreserveList,
263 SmallPtrSet<GlobalValue*, 8> &asmUsed,
264 Mangler &mangler) {
265 SmallString<64> Buffer;
266 mangler.getNameWithPrefix(Buffer, &GV, false);
267
268 if (GV.isDeclaration())
269 return;
270 if (_mustPreserveSymbols.count(Buffer))
271 mustPreserveList.push_back(GV.getName().data());
272 if (_asmUndefinedRefs.count(Buffer))
273 asmUsed.insert(&GV);
274}
275
276static void findUsedValues(GlobalVariable *LLVMUsed,
277 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
278 if (LLVMUsed == 0) return;
279
280 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
281 if (Inits == 0) return;
282
283 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
284 if (GlobalValue *GV =
285 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
286 UsedValues.insert(GV);
287}
288
Chris Lattner5ef31a02010-03-12 18:44:54 +0000289void LTOCodeGenerator::applyScopeRestrictions() {
290 if (_scopeRestrictionsDone) return;
291 Module *mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000292
Chris Lattner5ef31a02010-03-12 18:44:54 +0000293 // Start off with a verification pass.
294 PassManager passes;
295 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000296
Chris Lattner5ef31a02010-03-12 18:44:54 +0000297 // mark which symbols can not be internalized
Rafael Espindola38c4e532011-03-02 04:14:42 +0000298 MCContext Context(*_target->getMCAsmInfo(), NULL);
299 Mangler mangler(Context, *_target->getTargetData());
300 std::vector<const char*> mustPreserveList;
301 SmallPtrSet<GlobalValue*, 8> asmUsed;
302
303 for (Module::iterator f = mergedModule->begin(),
304 e = mergedModule->end(); f != e; ++f)
305 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
306 for (Module::global_iterator v = mergedModule->global_begin(),
307 e = mergedModule->global_end(); v != e; ++v)
308 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
309 for (Module::alias_iterator a = mergedModule->alias_begin(),
310 e = mergedModule->alias_end(); a != e; ++a)
311 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
312
313 GlobalVariable *LLVMCompilerUsed =
314 mergedModule->getGlobalVariable("llvm.compiler.used");
315 findUsedValues(LLVMCompilerUsed, asmUsed);
316 if (LLVMCompilerUsed)
317 LLVMCompilerUsed->eraseFromParent();
318
319 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
320 std::vector<Constant*> asmUsed2;
321 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
322 e = asmUsed.end(); i !=e; ++i) {
323 GlobalValue *GV = *i;
324 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
325 asmUsed2.push_back(c);
Chris Lattner5ef31a02010-03-12 18:44:54 +0000326 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000327
328 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
329 LLVMCompilerUsed =
330 new llvm::GlobalVariable(*mergedModule, ATy, false,
331 llvm::GlobalValue::AppendingLinkage,
332 llvm::ConstantArray::get(ATy, asmUsed2),
333 "llvm.compiler.used");
334
335 LLVMCompilerUsed->setSection("llvm.metadata");
336
337 passes.add(createInternalizePass(mustPreserveList));
338
Chris Lattner5ef31a02010-03-12 18:44:54 +0000339 // apply scope restrictions
340 passes.run(*mergedModule);
341
342 _scopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000343}
344
Nick Kledzik77595fc2008-02-26 20:26:43 +0000345/// Optimize merged modules using various IPO passes
Rafael Espindolae9efea12011-02-24 21:04:06 +0000346bool LTOCodeGenerator::generateObjectFile(raw_ostream& out,
347 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000348{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000349 if ( this->determineTarget(errMsg) )
Nick Kledzik77595fc2008-02-26 20:26:43 +0000350 return true;
351
352 // mark which symbols can not be internalized
353 this->applyScopeRestrictions();
354
355 Module* mergedModule = _linker.getModule();
356
Nick Kledzik920ae982008-07-08 21:14:10 +0000357 // if options were requested, set them
358 if ( !_codegenOptions.empty() )
359 cl::ParseCommandLineOptions(_codegenOptions.size(),
Dan Gohman43bc70e2010-04-17 17:44:03 +0000360 const_cast<char **>(&_codegenOptions[0]));
Devang Patela93ae712008-07-03 22:53:14 +0000361
Nick Kledzik77595fc2008-02-26 20:26:43 +0000362 // Instantiate the pass manager to organize the passes.
363 PassManager passes;
364
365 // Start off with a verification pass.
366 passes.add(createVerifierPass());
367
368 // Add an appropriate TargetData instance for this module...
369 passes.add(new TargetData(*_target->getTargetData()));
370
Daniel Dunbar006a0342009-06-03 21:06:14 +0000371 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
Daniel Dunbar006a0342009-06-03 21:06:14 +0000372 /*VerifyEach=*/ false);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000373
374 // Make sure everything is still good.
375 passes.add(createVerifierPass());
376
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000377 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000378
379 codeGenPasses->add(new TargetData(*_target->getTargetData()));
380
Dan Gohmand4c45432010-09-01 14:20:41 +0000381 formatted_raw_ostream Out(out);
382
383 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
Rafael Espindolae9efea12011-02-24 21:04:06 +0000384 TargetMachine::CGFT_ObjectFile,
Chris Lattner5669e302010-02-03 05:55:08 +0000385 CodeGenOpt::Aggressive)) {
386 errMsg = "target file type not supported";
387 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000388 }
389
Nick Kledzik77595fc2008-02-26 20:26:43 +0000390 // Run our queue of passes all at once now, efficiently.
391 passes.run(*mergedModule);
392
393 // Run the code generator, and write assembly file
394 codeGenPasses->doInitialization();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000395
Bill Wendling604a8182008-06-18 06:35:30 +0000396 for (Module::iterator
397 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
398 if (!it->isDeclaration())
399 codeGenPasses->run(*it);
400
401 codeGenPasses->doFinalization();
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000402 delete codeGenPasses;
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000403
Nick Kledzik77595fc2008-02-26 20:26:43 +0000404 return false; // success
405}
406
407
Nick Kledzik920ae982008-07-08 21:14:10 +0000408/// Optimize merged modules using various IPO passes
409void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
410{
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000411 for (std::pair<StringRef, StringRef> o = getToken(options);
412 !o.first.empty(); o = getToken(o.second)) {
Nick Kledzik920ae982008-07-08 21:14:10 +0000413 // ParseCommandLineOptions() expects argv[0] to be program name.
414 // Lazily add that.
415 if ( _codegenOptions.empty() )
416 _codegenOptions.push_back("libLTO");
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000417 _codegenOptions.push_back(strdup(o.first.str().c_str()));
Nick Kledzik920ae982008-07-08 21:14:10 +0000418 }
419}