The command line options need to be processed before we create the TargetMachine.
[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 "LTOCodeGenerator.h"
16 #include "LTOModule.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/Verifier.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Linker.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/Support/system_error.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Transforms/IPO.h"
46 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 #include "llvm/Transforms/ObjCARC.h"
48 using namespace llvm;
49
50 static cl::opt<bool>
51 DisableOpt("disable-opt", cl::init(false),
52   cl::desc("Do not run any optimization passes"));
53
54 static cl::opt<bool>
55 DisableInline("disable-inlining", cl::init(false),
56   cl::desc("Do not run the inliner pass"));
57
58 static cl::opt<bool>
59 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
60   cl::desc("Do not run the GVN load PRE pass"));
61
62 const char* LTOCodeGenerator::getVersionString() {
63 #ifdef LLVM_VERSION_INFO
64   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
65 #else
66   return PACKAGE_NAME " version " PACKAGE_VERSION;
67 #endif
68 }
69
70 LTOCodeGenerator::LTOCodeGenerator()
71   : _context(getGlobalContext()),
72     _linker(new Module("ld-temp.o", _context)), _target(NULL),
73     _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
74     _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
75     _nativeObjectFile(NULL) {
76   InitializeAllTargets();
77   InitializeAllTargetMCs();
78   InitializeAllAsmPrinters();
79 }
80
81 LTOCodeGenerator::~LTOCodeGenerator() {
82   delete _target;
83   delete _nativeObjectFile;
84   delete _linker.getModule();
85
86   for (std::vector<char*>::iterator I = _codegenOptions.begin(),
87          E = _codegenOptions.end(); I != E; ++I)
88     free(*I);
89 }
90
91 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
92   bool ret = _linker.linkInModule(mod->getLLVVMModule(), &errMsg);
93
94   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
95   for (int i = 0, e = undefs.size(); i != e; ++i)
96     _asmUndefinedRefs[undefs[i]] = 1;
97
98   return ret;
99 }
100
101 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
102                                     std::string& errMsg) {
103   switch (debug) {
104   case LTO_DEBUG_MODEL_NONE:
105     _emitDwarfDebugInfo = false;
106     return false;
107
108   case LTO_DEBUG_MODEL_DWARF:
109     _emitDwarfDebugInfo = true;
110     return false;
111   }
112   llvm_unreachable("Unknown debug format!");
113 }
114
115 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
116                                        std::string& errMsg) {
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   llvm_unreachable("Unknown PIC model!");
125 }
126
127 bool LTOCodeGenerator::writeMergedModules(const char *path,
128                                           std::string &errMsg) {
129   if (determineTarget(errMsg))
130     return true;
131
132   // mark which symbols can not be internalized
133   applyScopeRestrictions();
134
135   // create output file
136   std::string ErrInfo;
137   tool_output_file Out(path, ErrInfo,
138                        raw_fd_ostream::F_Binary);
139   if (!ErrInfo.empty()) {
140     errMsg = "could not open bitcode file for writing: ";
141     errMsg += path;
142     return true;
143   }
144
145   // write bitcode to it
146   WriteBitcodeToFile(_linker.getModule(), Out.os());
147   Out.os().close();
148
149   if (Out.os().has_error()) {
150     errMsg = "could not write bitcode file: ";
151     errMsg += path;
152     Out.os().clear_error();
153     return true;
154   }
155
156   Out.keep();
157   return false;
158 }
159
160 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
161   // make unique temp .o file to put generated object file
162   sys::PathWithStatus uniqueObjPath("lto-llvm.o");
163   if (uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg)) {
164     uniqueObjPath.eraseFromDisk();
165     return true;
166   }
167   sys::RemoveFileOnSignal(uniqueObjPath);
168
169   // generate object file
170   bool genResult = false;
171   tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
172   if (!errMsg.empty()) {
173     uniqueObjPath.eraseFromDisk();
174     return true;
175   }
176
177   genResult = this->generateObjectFile(objFile.os(), errMsg);
178   objFile.os().close();
179   if (objFile.os().has_error()) {
180     objFile.os().clear_error();
181     uniqueObjPath.eraseFromDisk();
182     return true;
183   }
184
185   objFile.keep();
186   if (genResult) {
187     uniqueObjPath.eraseFromDisk();
188     return true;
189   }
190
191   _nativeObjectPath = uniqueObjPath.str();
192   *name = _nativeObjectPath.c_str();
193   return false;
194 }
195
196 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
197   const char *name;
198   if (compile_to_file(&name, errMsg))
199     return NULL;
200
201   // remove old buffer if compile() called twice
202   delete _nativeObjectFile;
203
204   // read .o file into memory buffer
205   OwningPtr<MemoryBuffer> BuffPtr;
206   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
207     errMsg = ec.message();
208     sys::Path(_nativeObjectPath).eraseFromDisk();
209     return NULL;
210   }
211   _nativeObjectFile = BuffPtr.take();
212
213   // remove temp files
214   sys::Path(_nativeObjectPath).eraseFromDisk();
215
216   // return buffer, unless error
217   if (_nativeObjectFile == NULL)
218     return NULL;
219   *length = _nativeObjectFile->getBufferSize();
220   return _nativeObjectFile->getBufferStart();
221 }
222
223 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
224   if (_target != NULL)
225     return false;
226
227   // if options were requested, set them
228   if (!_codegenOptions.empty())
229     cl::ParseCommandLineOptions(_codegenOptions.size(),
230                                 const_cast<char **>(&_codegenOptions[0]));
231
232   std::string TripleStr = _linker.getModule()->getTargetTriple();
233   if (TripleStr.empty())
234     TripleStr = sys::getDefaultTargetTriple();
235   llvm::Triple Triple(TripleStr);
236
237   // create target machine from info for merged modules
238   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
239   if (march == NULL)
240     return true;
241
242   // The relocation model is actually a static member of TargetMachine and
243   // needs to be set before the TargetMachine is instantiated.
244   Reloc::Model RelocModel = Reloc::Default;
245   switch (_codeModel) {
246   case LTO_CODEGEN_PIC_MODEL_STATIC:
247     RelocModel = Reloc::Static;
248     break;
249   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
250     RelocModel = Reloc::PIC_;
251     break;
252   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
253     RelocModel = Reloc::DynamicNoPIC;
254     break;
255   }
256
257   // construct LTOModule, hand over ownership of module and target
258   SubtargetFeatures Features;
259   Features.getDefaultSubtargetFeatures(Triple);
260   std::string FeatureStr = Features.getString();
261   // Set a default CPU for Darwin triples.
262   if (_mCpu.empty() && Triple.isOSDarwin()) {
263     if (Triple.getArch() == llvm::Triple::x86_64)
264       _mCpu = "core2";
265     else if (Triple.getArch() == llvm::Triple::x86)
266       _mCpu = "yonah";
267   }
268   TargetOptions Options;
269   LTOModule::getTargetOptions(Options);
270   _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
271                                        RelocModel, CodeModel::Default,
272                                        CodeGenOpt::Aggressive);
273   return false;
274 }
275
276 void LTOCodeGenerator::
277 applyRestriction(GlobalValue &GV,
278                  std::vector<const char*> &mustPreserveList,
279                  SmallPtrSet<GlobalValue*, 8> &asmUsed,
280                  Mangler &mangler) {
281   SmallString<64> Buffer;
282   mangler.getNameWithPrefix(Buffer, &GV, false);
283
284   if (GV.isDeclaration())
285     return;
286   if (_mustPreserveSymbols.count(Buffer))
287     mustPreserveList.push_back(GV.getName().data());
288   if (_asmUndefinedRefs.count(Buffer))
289     asmUsed.insert(&GV);
290 }
291
292 static void findUsedValues(GlobalVariable *LLVMUsed,
293                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
294   if (LLVMUsed == 0) return;
295
296   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
297   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
298     if (GlobalValue *GV =
299         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
300       UsedValues.insert(GV);
301 }
302
303 void LTOCodeGenerator::applyScopeRestrictions() {
304   if (_scopeRestrictionsDone) return;
305   Module *mergedModule = _linker.getModule();
306
307   // Start off with a verification pass.
308   PassManager passes;
309   passes.add(createVerifierPass());
310
311   // mark which symbols can not be internalized
312   MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
313   Mangler mangler(Context, *_target->getDataLayout());
314   std::vector<const char*> mustPreserveList;
315   SmallPtrSet<GlobalValue*, 8> asmUsed;
316
317   for (Module::iterator f = mergedModule->begin(),
318          e = mergedModule->end(); f != e; ++f)
319     applyRestriction(*f, mustPreserveList, asmUsed, mangler);
320   for (Module::global_iterator v = mergedModule->global_begin(),
321          e = mergedModule->global_end(); v !=  e; ++v)
322     applyRestriction(*v, mustPreserveList, asmUsed, mangler);
323   for (Module::alias_iterator a = mergedModule->alias_begin(),
324          e = mergedModule->alias_end(); a != e; ++a)
325     applyRestriction(*a, mustPreserveList, asmUsed, mangler);
326
327   GlobalVariable *LLVMCompilerUsed =
328     mergedModule->getGlobalVariable("llvm.compiler.used");
329   findUsedValues(LLVMCompilerUsed, asmUsed);
330   if (LLVMCompilerUsed)
331     LLVMCompilerUsed->eraseFromParent();
332
333   if (!asmUsed.empty()) {
334     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
335     std::vector<Constant*> asmUsed2;
336     for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
337            e = asmUsed.end(); i !=e; ++i) {
338       GlobalValue *GV = *i;
339       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
340       asmUsed2.push_back(c);
341     }
342
343     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
344     LLVMCompilerUsed =
345       new llvm::GlobalVariable(*mergedModule, ATy, false,
346                                llvm::GlobalValue::AppendingLinkage,
347                                llvm::ConstantArray::get(ATy, asmUsed2),
348                                "llvm.compiler.used");
349
350     LLVMCompilerUsed->setSection("llvm.metadata");
351   }
352
353   passes.add(createInternalizePass(mustPreserveList));
354
355   // apply scope restrictions
356   passes.run(*mergedModule);
357
358   _scopeRestrictionsDone = true;
359 }
360
361 /// Optimize merged modules using various IPO passes
362 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
363                                           std::string &errMsg) {
364   if (this->determineTarget(errMsg))
365     return true;
366
367   Module* mergedModule = _linker.getModule();
368
369   // Mark which symbols can not be internalized
370   this->applyScopeRestrictions();
371
372   // Instantiate the pass manager to organize the passes.
373   PassManager passes;
374
375   // Start off with a verification pass.
376   passes.add(createVerifierPass());
377
378   // Add an appropriate DataLayout instance for this module...
379   passes.add(new DataLayout(*_target->getDataLayout()));
380   _target->addAnalysisPasses(passes);
381
382   // Enabling internalize here would use its AllButMain variant. It
383   // keeps only main if it exists and does nothing for libraries. Instead
384   // we create the pass ourselves with the symbol list provided by the linker.
385   if (!DisableOpt)
386     PassManagerBuilder().populateLTOPassManager(passes,
387                                               /*Internalize=*/false,
388                                               !DisableInline,
389                                               DisableGVNLoadPRE);
390
391   // Make sure everything is still good.
392   passes.add(createVerifierPass());
393
394   PassManager codeGenPasses;
395
396   codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
397   _target->addAnalysisPasses(codeGenPasses);
398
399   formatted_raw_ostream Out(out);
400
401   // If the bitcode files contain ARC code and were compiled with optimization,
402   // the ObjCARCContractPass must be run, so do it unconditionally here.
403   codeGenPasses.add(createObjCARCContractPass());
404
405   if (_target->addPassesToEmitFile(codeGenPasses, Out,
406                                    TargetMachine::CGFT_ObjectFile)) {
407     errMsg = "target file type not supported";
408     return true;
409   }
410
411   // Run our queue of passes all at once now, efficiently.
412   passes.run(*mergedModule);
413
414   // Run the code generator, and write assembly file
415   codeGenPasses.run(*mergedModule);
416
417   return false; // success
418 }
419
420 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
421 /// LTO problems.
422 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
423   for (std::pair<StringRef, StringRef> o = getToken(options);
424        !o.first.empty(); o = getToken(o.second)) {
425     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
426     // that.
427     if (_codegenOptions.empty())
428       _codegenOptions.push_back(strdup("libLTO"));
429     _codegenOptions.push_back(strdup(o.first.str().c_str()));
430   }
431 }