Misc enhancements to LTO:
[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 "LTOPartition.h"
18 #include "LTOPostIPODriver.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/Passes.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/Config/config.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Linker.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/PassManager.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/ToolOutputFile.h"
45 #include "llvm/Support/system_error.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Target/Mangler.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Transforms/IPO.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/ObjCARC.h"
54
55 using namespace llvm;
56 using namespace lto;
57
58 // /////////////////////////////////////////////////////////////////////////////
59 //
60 //   Internal options. To avoid collision, most options start with "lto-".
61 // 
62 // /////////////////////////////////////////////////////////////////////////////
63 //
64 static cl::opt<bool>
65 DisableOpt("disable-opt", cl::init(false),
66   cl::desc("Do not run any optimization passes"));
67
68 static cl::opt<bool>
69 DisableInline("disable-inlining", cl::init(false),
70   cl::desc("Do not run the inliner pass"));
71
72 static cl::opt<bool>
73 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
74   cl::desc("Do not run the GVN load PRE pass"));
75
76 // To break merged module into partitions, and compile them independently.
77 static cl::opt<bool>
78 EnablePartition("lto-partition", cl::init(false),
79   cl::desc("Partition program and compile each piece in parallel"));
80
81 // Specify the work-directory for the LTO compilation. All intermeidate
82 // files will be created immediately under this dir. If it is not
83 // specified, compiler will create an unique directory under current-dir.
84 //
85 static cl::opt<std::string>
86 TmpWorkDir("lto-workdir", cl::init(""), cl::desc("Specify working directory"));
87
88 static cl::opt<bool>
89 KeepWorkDir("lto-keep", cl::init(false), cl::desc("Keep working directory"));
90
91
92 // /////////////////////////////////////////////////////////////////////////////
93 //
94 //                    Implementation of LTOCodeGenerator
95 //
96 // /////////////////////////////////////////////////////////////////////////////
97 //
98 const char* LTOCodeGenerator::getVersionString() {
99 #ifdef LLVM_VERSION_INFO
100   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
101 #else
102   return PACKAGE_NAME " version " PACKAGE_VERSION;
103 #endif
104 }
105
106 LTOCodeGenerator::LTOCodeGenerator()
107   : _context(getGlobalContext()),
108     _linker(new Module("ld-temp.o", _context)), _target(NULL),
109     _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
110     _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
111     _nativeObjectFile(NULL), PartitionMgr(FileMgr),
112     OptionsParsed(false) {
113   InitializeAllTargets();
114   InitializeAllTargetMCs();
115   InitializeAllAsmPrinters();
116   initializeLTOPasses();
117 }
118
119 LTOCodeGenerator::~LTOCodeGenerator() {
120   delete _target;
121   delete _nativeObjectFile;
122   delete _linker.getModule();
123
124   for (std::vector<char*>::iterator I = _codegenOptions.begin(),
125          E = _codegenOptions.end(); I != E; ++I)
126     free(*I);
127 }
128
129 // Initialize LTO passes. Please keep this funciton in sync with
130 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
131 // passes are initialized. 
132 //
133 void LTOCodeGenerator::initializeLTOPasses() {
134   PassRegistry &R = *PassRegistry::getPassRegistry();
135
136   initializeInternalizePassPass(R);
137   initializeIPSCCPPass(R);
138   initializeGlobalOptPass(R);
139   initializeConstantMergePass(R);
140   initializeDAHPass(R);
141   initializeInstCombinerPass(R);
142   initializeSimpleInlinerPass(R);
143   initializePruneEHPass(R);
144   initializeGlobalDCEPass(R);
145   initializeArgPromotionPass(R);
146   initializeJumpThreadingPass(R);
147   initializeSROAPass(R);
148   initializeSROA_DTPass(R);
149   initializeSROA_SSAUpPass(R);
150   initializeFunctionAttrsPass(R);
151   initializeGlobalsModRefPass(R);
152   initializeLICMPass(R);
153   initializeGVNPass(R);
154   initializeMemCpyOptPass(R);
155   initializeDCEPass(R);
156   initializeCFGSimplifyPassPass(R);
157 }
158
159 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
160   bool ret = _linker.linkInModule(mod->getLLVVMModule(), &errMsg);
161
162   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
163   for (int i = 0, e = undefs.size(); i != e; ++i)
164     _asmUndefinedRefs[undefs[i]] = 1;
165
166   return !ret;
167 }
168
169 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
170   switch (debug) {
171   case LTO_DEBUG_MODEL_NONE:
172     _emitDwarfDebugInfo = false;
173     return;
174
175   case LTO_DEBUG_MODEL_DWARF:
176     _emitDwarfDebugInfo = true;
177     return;
178   }
179   llvm_unreachable("Unknown debug format!");
180 }
181
182 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
183   switch (model) {
184   case LTO_CODEGEN_PIC_MODEL_STATIC:
185   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
186   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
187     _codeModel = model;
188     return;
189   }
190   llvm_unreachable("Unknown PIC model!");
191 }
192
193 bool LTOCodeGenerator::writeMergedModules(const char *path,
194                                           std::string &errMsg) {
195   if (!determineTarget(errMsg))
196     return false;
197
198   // mark which symbols can not be internalized
199   applyScopeRestrictions();
200
201   // create output file
202   std::string ErrInfo;
203   tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
204   if (!ErrInfo.empty()) {
205     errMsg = "could not open bitcode file for writing: ";
206     errMsg += path;
207     return false;
208   }
209
210   // write bitcode to it
211   WriteBitcodeToFile(_linker.getModule(), Out.os());
212   Out.os().close();
213
214   if (Out.os().has_error()) {
215     errMsg = "could not write bitcode file: ";
216     errMsg += path;
217     Out.os().clear_error();
218     return false;
219   }
220
221   Out.keep();
222   return true;
223 }
224
225 // This function is to ensure cl::ParseCommandLineOptions() is called no more
226 // than once. It would otherwise complain and exit the compilation prematurely.
227 // 
228 void LTOCodeGenerator::parseOptions() {
229   if (OptionsParsed)
230     return;
231
232   if (!_codegenOptions.empty())
233     cl::ParseCommandLineOptions(_codegenOptions.size(),
234                                 const_cast<char **>(&_codegenOptions[0]));
235
236   OptionsParsed = true;
237 }
238
239 // Do some prepartion right before compilation starts.
240 bool LTOCodeGenerator::prepareBeforeCompile(std::string &ErrMsg) {
241   parseOptions();
242
243   if (!determineTarget(ErrMsg))
244     return false;
245
246   FileMgr.setWorkDir(TmpWorkDir.c_str());
247   FileMgr.setKeepWorkDir(KeepWorkDir);
248   return FileMgr.createWorkDir(ErrMsg);
249 }
250
251 bool LTOCodeGenerator::compile_to_file(const char** Name, std::string& ErrMsg) {
252   if (!prepareBeforeCompile(ErrMsg))
253     return false;
254
255   performIPO(EnablePartition, ErrMsg);
256   if (!performPostIPO(ErrMsg))
257     return false;
258
259   *Name = PartitionMgr.getSinglePartition()->getObjFilePath().c_str();
260   return true;
261 }
262
263 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
264   const char *name;
265   if (!compile_to_file(&name, errMsg))
266     return NULL;
267
268   // remove old buffer if compile() called twice
269   delete _nativeObjectFile;
270
271   // read .o file into memory buffer
272   OwningPtr<MemoryBuffer> BuffPtr;
273   const char *BufStart = 0;
274
275   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
276     errMsg = ec.message();
277     _nativeObjectFile = 0;
278   } else {
279     if ((_nativeObjectFile = BuffPtr.take())) {
280       *length = _nativeObjectFile->getBufferSize();
281       BufStart = _nativeObjectFile->getBufferStart();
282     }
283   }
284
285   // Now that the resulting single object file is handed to linker via memory 
286   // buffer, it is safe to remove all intermediate files now. 
287   //
288   FileMgr.removeAllUnneededFiles();
289
290   return BufStart;
291 }
292
293 const char *LTOCodeGenerator::getFilesNeedToRemove() {
294   IPOFileMgr::FileNameVect ToRm;
295   FileMgr.getFilesNeedToRemove(ToRm);
296
297   ConcatStrings.clear();
298   for (IPOFileMgr::FileNameVect::iterator I = ToRm.begin(), E = ToRm.end();
299        I != E; I++) {
300     StringRef S(*I);
301     ConcatStrings.append(S.begin(), S.end());
302     ConcatStrings.push_back('\0');
303   }
304   ConcatStrings.push_back('\0');
305   ConcatStrings.push_back('\0');
306
307   return ConcatStrings.data();
308 }
309
310 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
311   if (_target != NULL)
312     return true;
313
314   // if options were requested, set them
315   parseOptions();
316
317   std::string TripleStr = _linker.getModule()->getTargetTriple();
318   if (TripleStr.empty())
319     TripleStr = sys::getDefaultTargetTriple();
320   llvm::Triple Triple(TripleStr);
321
322   // create target machine from info for merged modules
323   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
324   if (march == NULL)
325     return false;
326
327   // The relocation model is actually a static member of TargetMachine and
328   // needs to be set before the TargetMachine is instantiated.
329   Reloc::Model RelocModel = Reloc::Default;
330   switch (_codeModel) {
331   case LTO_CODEGEN_PIC_MODEL_STATIC:
332     RelocModel = Reloc::Static;
333     break;
334   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
335     RelocModel = Reloc::PIC_;
336     break;
337   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
338     RelocModel = Reloc::DynamicNoPIC;
339     break;
340   }
341
342   // construct LTOModule, hand over ownership of module and target
343   SubtargetFeatures Features;
344   Features.getDefaultSubtargetFeatures(Triple);
345   std::string FeatureStr = Features.getString();
346   // Set a default CPU for Darwin triples.
347   if (_mCpu.empty() && Triple.isOSDarwin()) {
348     if (Triple.getArch() == llvm::Triple::x86_64)
349       _mCpu = "core2";
350     else if (Triple.getArch() == llvm::Triple::x86)
351       _mCpu = "yonah";
352   }
353   TargetOptions Options;
354   LTOModule::getTargetOptions(Options);
355   _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
356                                        RelocModel, CodeModel::Default,
357                                        CodeGenOpt::Aggressive);
358   return true;
359 }
360
361 void LTOCodeGenerator::
362 applyRestriction(GlobalValue &GV,
363                  std::vector<const char*> &mustPreserveList,
364                  SmallPtrSet<GlobalValue*, 8> &asmUsed,
365                  Mangler &mangler) {
366   SmallString<64> Buffer;
367   mangler.getNameWithPrefix(Buffer, &GV, false);
368
369   if (GV.isDeclaration())
370     return;
371   if (_mustPreserveSymbols.count(Buffer))
372     mustPreserveList.push_back(GV.getName().data());
373   if (_asmUndefinedRefs.count(Buffer))
374     asmUsed.insert(&GV);
375 }
376
377 static void findUsedValues(GlobalVariable *LLVMUsed,
378                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
379   if (LLVMUsed == 0) return;
380
381   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
382   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
383     if (GlobalValue *GV =
384         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
385       UsedValues.insert(GV);
386 }
387
388 void LTOCodeGenerator::applyScopeRestrictions() {
389   if (_scopeRestrictionsDone) return;
390   Module *mergedModule = _linker.getModule();
391
392   // Start off with a verification pass.
393   PassManager passes;
394   passes.add(createVerifierPass());
395
396   // mark which symbols can not be internalized
397   MCContext Context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL);
398   Mangler mangler(Context, _target);
399   std::vector<const char*> mustPreserveList;
400   SmallPtrSet<GlobalValue*, 8> asmUsed;
401
402   for (Module::iterator f = mergedModule->begin(),
403          e = mergedModule->end(); f != e; ++f)
404     applyRestriction(*f, mustPreserveList, asmUsed, mangler);
405   for (Module::global_iterator v = mergedModule->global_begin(),
406          e = mergedModule->global_end(); v !=  e; ++v)
407     applyRestriction(*v, mustPreserveList, asmUsed, mangler);
408   for (Module::alias_iterator a = mergedModule->alias_begin(),
409          e = mergedModule->alias_end(); a != e; ++a)
410     applyRestriction(*a, mustPreserveList, asmUsed, mangler);
411
412   GlobalVariable *LLVMCompilerUsed =
413     mergedModule->getGlobalVariable("llvm.compiler.used");
414   findUsedValues(LLVMCompilerUsed, asmUsed);
415   if (LLVMCompilerUsed)
416     LLVMCompilerUsed->eraseFromParent();
417
418   if (!asmUsed.empty()) {
419     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
420     std::vector<Constant*> asmUsed2;
421     for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
422            e = asmUsed.end(); i !=e; ++i) {
423       GlobalValue *GV = *i;
424       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
425       asmUsed2.push_back(c);
426     }
427
428     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
429     LLVMCompilerUsed =
430       new llvm::GlobalVariable(*mergedModule, ATy, false,
431                                llvm::GlobalValue::AppendingLinkage,
432                                llvm::ConstantArray::get(ATy, asmUsed2),
433                                "llvm.compiler.used");
434
435     LLVMCompilerUsed->setSection("llvm.metadata");
436   }
437
438   passes.add(createInternalizePass(mustPreserveList));
439
440   // apply scope restrictions
441   passes.run(*mergedModule);
442
443   _scopeRestrictionsDone = true;
444 }
445
446 void LTOCodeGenerator::performIPO(bool ToPartition, std::string &errMsg) {
447   // Mark which symbols can not be internalized
448   applyScopeRestrictions();
449
450   // Instantiate the pass manager to organize the passes.
451   PassManager Passes;
452
453   // Start off with a verification pass.
454   Passes.add(createVerifierPass());
455
456   // Add an appropriate DataLayout instance for this module...
457   Passes.add(new DataLayout(*_target->getDataLayout()));
458   _target->addAnalysisPasses(Passes);
459
460   // Enabling internalize here would use its AllButMain variant. It
461   // keeps only main if it exists and does nothing for libraries. Instead
462   // we create the pass ourselves with the symbol list provided by the linker.
463   if (!DisableOpt)
464     PassManagerBuilder().populateLTOPassManager(Passes,
465                                                 /*Internalize=*/false,
466                                                 !DisableInline,
467                                                 DisableGVNLoadPRE);
468   // Make sure everything is still good.
469   Passes.add(createVerifierPass());
470
471   Module* M = _linker.getModule();
472   if (ToPartition)
473     assert(false && "TBD");
474   else {
475     Passes.run(*M);
476
477     // Create a partition for the merged module.
478     PartitionMgr.createIPOPart(M);
479   }
480 }
481
482 // Perform Post-IPO compilation. If the partition is enabled, there may
483 // be multiple partitions, and therefore there may be multiple objects.
484 // In this case, "MergeObjs" indicates to merge all object together (via ld -r)
485 // and return the path to the merged object via "MergObjPath".
486 // 
487 bool LTOCodeGenerator::performPostIPO(std::string &ErrMsg,
488                                       bool MergeObjs,
489                                       const char **MergObjPath) {
490   // Determine the variant of post-ipo driver
491   PostIPODriver::VariantTy DrvTy;
492   if (!EnablePartition) {
493     assert(!MergeObjs && !MergObjPath && "Invalid parameter");
494     DrvTy = PostIPODriver::PIDV_SERIAL;
495   } else {
496     DrvTy = PostIPODriver::PIDV_Invalid;
497     assert(false && "TBD");
498   }
499
500   PostIPODriver D(DrvTy, _target, PartitionMgr, FileMgr, MergeObjs);
501   if (D.Compile(ErrMsg)) {
502     if (MergeObjs)
503       *MergObjPath = D.getSingleObjFile()->getPath().c_str();
504     return true;
505   }
506
507   return false;
508 }
509
510 /// Optimize merged modules using various IPO passes
511 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
512                                           std::string &errMsg) {
513   if (!this->determineTarget(errMsg))
514     return false;
515
516   Module* mergedModule = _linker.getModule();
517
518   // Mark which symbols can not be internalized
519   this->applyScopeRestrictions();
520
521   // Instantiate the pass manager to organize the passes.
522   PassManager passes;
523
524   // Start off with a verification pass.
525   passes.add(createVerifierPass());
526
527   // Add an appropriate DataLayout instance for this module...
528   passes.add(new DataLayout(*_target->getDataLayout()));
529   _target->addAnalysisPasses(passes);
530
531   // Enabling internalize here would use its AllButMain variant. It
532   // keeps only main if it exists and does nothing for libraries. Instead
533   // we create the pass ourselves with the symbol list provided by the linker.
534   if (!DisableOpt)
535     PassManagerBuilder().populateLTOPassManager(passes,
536                                               /*Internalize=*/false,
537                                               !DisableInline,
538                                               DisableGVNLoadPRE);
539
540   // Make sure everything is still good.
541   passes.add(createVerifierPass());
542
543   PassManager codeGenPasses;
544
545   codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
546   _target->addAnalysisPasses(codeGenPasses);
547
548   formatted_raw_ostream Out(out);
549
550   // If the bitcode files contain ARC code and were compiled with optimization,
551   // the ObjCARCContractPass must be run, so do it unconditionally here.
552   codeGenPasses.add(createObjCARCContractPass());
553
554   if (_target->addPassesToEmitFile(codeGenPasses, Out,
555                                    TargetMachine::CGFT_ObjectFile)) {
556     errMsg = "target file type not supported";
557     return false;
558   }
559
560   // Run our queue of passes all at once now, efficiently.
561   passes.run(*mergedModule);
562
563   // Run the code generator, and write assembly file
564   codeGenPasses.run(*mergedModule);
565
566   return true;
567 }
568
569 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
570 /// LTO problems.
571 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
572   for (std::pair<StringRef, StringRef> o = getToken(options);
573        !o.first.empty(); o = getToken(o.second)) {
574     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
575     // that.
576     if (_codegenOptions.empty())
577       _codegenOptions.push_back(strdup("libLTO"));
578     _codegenOptions.push_back(strdup(o.first.str().c_str()));
579   }
580 }