Run the ObjCARCContract pass for LTO. <rdar://problem/13538084>
[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("LinkTimeOptimizer", "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
85   for (std::vector<char*>::iterator I = _codegenOptions.begin(),
86          E = _codegenOptions.end(); I != E; ++I)
87     free(*I);
88 }
89
90 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
91   bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
92
93   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
94   for (int i = 0, e = undefs.size(); i != e; ++i)
95     _asmUndefinedRefs[undefs[i]] = 1;
96
97   return ret;
98 }
99
100 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
101                                     std::string& errMsg) {
102   switch (debug) {
103   case LTO_DEBUG_MODEL_NONE:
104     _emitDwarfDebugInfo = false;
105     return false;
106
107   case LTO_DEBUG_MODEL_DWARF:
108     _emitDwarfDebugInfo = true;
109     return false;
110   }
111   llvm_unreachable("Unknown debug format!");
112 }
113
114 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
115                                        std::string& errMsg) {
116   switch (model) {
117   case LTO_CODEGEN_PIC_MODEL_STATIC:
118   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
119   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
120     _codeModel = model;
121     return false;
122   }
123   llvm_unreachable("Unknown PIC model!");
124 }
125
126 bool LTOCodeGenerator::writeMergedModules(const char *path,
127                                           std::string &errMsg) {
128   if (determineTarget(errMsg))
129     return true;
130
131   // mark which symbols can not be internalized
132   applyScopeRestrictions();
133
134   // create output file
135   std::string ErrInfo;
136   tool_output_file Out(path, ErrInfo,
137                        raw_fd_ostream::F_Binary);
138   if (!ErrInfo.empty()) {
139     errMsg = "could not open bitcode file for writing: ";
140     errMsg += path;
141     return true;
142   }
143
144   // write bitcode to it
145   WriteBitcodeToFile(_linker.getModule(), Out.os());
146   Out.os().close();
147
148   if (Out.os().has_error()) {
149     errMsg = "could not write bitcode file: ";
150     errMsg += path;
151     Out.os().clear_error();
152     return true;
153   }
154
155   Out.keep();
156   return false;
157 }
158
159 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
160   // make unique temp .o file to put generated object file
161   sys::PathWithStatus uniqueObjPath("lto-llvm.o");
162   if (uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg)) {
163     uniqueObjPath.eraseFromDisk();
164     return true;
165   }
166   sys::RemoveFileOnSignal(uniqueObjPath);
167
168   // generate object file
169   bool genResult = false;
170   tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
171   if (!errMsg.empty()) {
172     uniqueObjPath.eraseFromDisk();
173     return true;
174   }
175
176   genResult = this->generateObjectFile(objFile.os(), errMsg);
177   objFile.os().close();
178   if (objFile.os().has_error()) {
179     objFile.os().clear_error();
180     uniqueObjPath.eraseFromDisk();
181     return true;
182   }
183
184   objFile.keep();
185   if (genResult) {
186     uniqueObjPath.eraseFromDisk();
187     return true;
188   }
189
190   _nativeObjectPath = uniqueObjPath.str();
191   *name = _nativeObjectPath.c_str();
192   return false;
193 }
194
195 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
196   const char *name;
197   if (compile_to_file(&name, errMsg))
198     return NULL;
199
200   // remove old buffer if compile() called twice
201   delete _nativeObjectFile;
202
203   // read .o file into memory buffer
204   OwningPtr<MemoryBuffer> BuffPtr;
205   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
206     errMsg = ec.message();
207     sys::Path(_nativeObjectPath).eraseFromDisk();
208     return NULL;
209   }
210   _nativeObjectFile = BuffPtr.take();
211
212   // remove temp files
213   sys::Path(_nativeObjectPath).eraseFromDisk();
214
215   // return buffer, unless error
216   if (_nativeObjectFile == NULL)
217     return NULL;
218   *length = _nativeObjectFile->getBufferSize();
219   return _nativeObjectFile->getBufferStart();
220 }
221
222 bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
223   if (_target != NULL)
224     return false;
225
226   std::string TripleStr = _linker.getModule()->getTargetTriple();
227   if (TripleStr.empty())
228     TripleStr = sys::getDefaultTargetTriple();
229   llvm::Triple Triple(TripleStr);
230
231   // create target machine from info for merged modules
232   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
233   if (march == NULL)
234     return true;
235
236   // The relocation model is actually a static member of TargetMachine and
237   // needs to be set before the TargetMachine is instantiated.
238   Reloc::Model RelocModel = Reloc::Default;
239   switch (_codeModel) {
240   case LTO_CODEGEN_PIC_MODEL_STATIC:
241     RelocModel = Reloc::Static;
242     break;
243   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
244     RelocModel = Reloc::PIC_;
245     break;
246   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
247     RelocModel = Reloc::DynamicNoPIC;
248     break;
249   }
250
251   // construct LTOModule, hand over ownership of module and target
252   SubtargetFeatures Features;
253   Features.getDefaultSubtargetFeatures(Triple);
254   std::string FeatureStr = Features.getString();
255   // Set a default CPU for Darwin triples.
256   if (_mCpu.empty() && Triple.isOSDarwin()) {
257     if (Triple.getArch() == llvm::Triple::x86_64)
258       _mCpu = "core2";
259     else if (Triple.getArch() == llvm::Triple::x86)
260       _mCpu = "yonah";
261   }
262   TargetOptions Options;
263   LTOModule::getTargetOptions(Options);
264   _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
265                                        RelocModel, CodeModel::Default,
266                                        CodeGenOpt::Aggressive);
267   return false;
268 }
269
270 void LTOCodeGenerator::
271 applyRestriction(GlobalValue &GV,
272                  std::vector<const char*> &mustPreserveList,
273                  SmallPtrSet<GlobalValue*, 8> &asmUsed,
274                  Mangler &mangler) {
275   SmallString<64> Buffer;
276   mangler.getNameWithPrefix(Buffer, &GV, false);
277
278   if (GV.isDeclaration())
279     return;
280   if (_mustPreserveSymbols.count(Buffer))
281     mustPreserveList.push_back(GV.getName().data());
282   if (_asmUndefinedRefs.count(Buffer))
283     asmUsed.insert(&GV);
284 }
285
286 static void findUsedValues(GlobalVariable *LLVMUsed,
287                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
288   if (LLVMUsed == 0) return;
289
290   ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
291   if (Inits == 0) return;
292
293   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
294     if (GlobalValue *GV =
295         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
296       UsedValues.insert(GV);
297 }
298
299 void LTOCodeGenerator::applyScopeRestrictions() {
300   if (_scopeRestrictionsDone) return;
301   Module *mergedModule = _linker.getModule();
302
303   // Start off with a verification pass.
304   PassManager passes;
305   passes.add(createVerifierPass());
306
307   // mark which symbols can not be internalized
308   MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
309   Mangler mangler(Context, *_target->getDataLayout());
310   std::vector<const char*> mustPreserveList;
311   SmallPtrSet<GlobalValue*, 8> asmUsed;
312
313   for (Module::iterator f = mergedModule->begin(),
314          e = mergedModule->end(); f != e; ++f)
315     applyRestriction(*f, mustPreserveList, asmUsed, mangler);
316   for (Module::global_iterator v = mergedModule->global_begin(),
317          e = mergedModule->global_end(); v !=  e; ++v)
318     applyRestriction(*v, mustPreserveList, asmUsed, mangler);
319   for (Module::alias_iterator a = mergedModule->alias_begin(),
320          e = mergedModule->alias_end(); a != e; ++a)
321     applyRestriction(*a, mustPreserveList, asmUsed, mangler);
322
323   GlobalVariable *LLVMCompilerUsed =
324     mergedModule->getGlobalVariable("llvm.compiler.used");
325   findUsedValues(LLVMCompilerUsed, asmUsed);
326   if (LLVMCompilerUsed)
327     LLVMCompilerUsed->eraseFromParent();
328
329   llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
330   std::vector<Constant*> asmUsed2;
331   for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
332          e = asmUsed.end(); i !=e; ++i) {
333     GlobalValue *GV = *i;
334     Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
335     asmUsed2.push_back(c);
336   }
337
338   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
339   LLVMCompilerUsed =
340     new llvm::GlobalVariable(*mergedModule, ATy, false,
341                              llvm::GlobalValue::AppendingLinkage,
342                              llvm::ConstantArray::get(ATy, asmUsed2),
343                              "llvm.compiler.used");
344
345   LLVMCompilerUsed->setSection("llvm.metadata");
346
347   passes.add(createInternalizePass(mustPreserveList));
348
349   // apply scope restrictions
350   passes.run(*mergedModule);
351
352   _scopeRestrictionsDone = true;
353 }
354
355 /// Optimize merged modules using various IPO passes
356 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
357                                           std::string &errMsg) {
358   if (this->determineTarget(errMsg))
359     return true;
360
361   Module* mergedModule = _linker.getModule();
362
363   // if options were requested, set them
364   if (!_codegenOptions.empty())
365     cl::ParseCommandLineOptions(_codegenOptions.size(),
366                                 const_cast<char **>(&_codegenOptions[0]));
367
368   // mark which symbols can not be internalized
369   this->applyScopeRestrictions();
370
371   // Instantiate the pass manager to organize the passes.
372   PassManager passes;
373
374   // Start off with a verification pass.
375   passes.add(createVerifierPass());
376
377   // Add an appropriate DataLayout instance for this module...
378   passes.add(new DataLayout(*_target->getDataLayout()));
379   _target->addAnalysisPasses(passes);
380
381   // Enabling internalize here would use its AllButMain variant. It
382   // keeps only main if it exists and does nothing for libraries. Instead
383   // we create the pass ourselves with the symbol list provided by the linker.
384   if (!DisableOpt) {
385     PassManagerBuilder().populateLTOPassManager(passes,
386                                               /*Internalize=*/false,
387                                               !DisableInline,
388                                               DisableGVNLoadPRE);
389   }
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 }