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