1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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"
58 // /////////////////////////////////////////////////////////////////////////////
60 // Internal options. To avoid collision, most options start with "lto-".
62 // /////////////////////////////////////////////////////////////////////////////
65 DisableOpt("disable-opt", cl::init(false),
66 cl::desc("Do not run any optimization passes"));
69 DisableInline("disable-inlining", cl::init(false),
70 cl::desc("Do not run the inliner pass"));
73 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
74 cl::desc("Do not run the GVN load PRE pass"));
76 // To break merged module into partitions, and compile them independently.
78 EnablePartition("lto-partition", cl::init(false),
79 cl::desc("Partition program and compile each piece in parallel"));
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.
85 static cl::opt<std::string>
86 TmpWorkDir("lto-workdir", cl::init(""), cl::desc("Specify working directory"));
89 KeepWorkDir("lto-keep", cl::init(false), cl::desc("Keep working directory"));
92 // /////////////////////////////////////////////////////////////////////////////
94 // Implementation of LTOCodeGenerator
96 // /////////////////////////////////////////////////////////////////////////////
98 const char* LTOCodeGenerator::getVersionString() {
99 #ifdef LLVM_VERSION_INFO
100 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
102 return PACKAGE_NAME " version " PACKAGE_VERSION;
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();
119 LTOCodeGenerator::~LTOCodeGenerator() {
121 delete _nativeObjectFile;
122 delete _linker.getModule();
124 for (std::vector<char*>::iterator I = _codegenOptions.begin(),
125 E = _codegenOptions.end(); I != E; ++I)
129 // Initialize LTO passes. Please keep this funciton in sync with
130 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
131 // passes are initialized.
133 void LTOCodeGenerator::initializeLTOPasses() {
134 PassRegistry &R = *PassRegistry::getPassRegistry();
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);
159 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
160 bool ret = _linker.linkInModule(mod->getLLVVMModule(), &errMsg);
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;
169 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
171 case LTO_DEBUG_MODEL_NONE:
172 _emitDwarfDebugInfo = false;
175 case LTO_DEBUG_MODEL_DWARF:
176 _emitDwarfDebugInfo = true;
179 llvm_unreachable("Unknown debug format!");
182 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
184 case LTO_CODEGEN_PIC_MODEL_STATIC:
185 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
186 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
190 llvm_unreachable("Unknown PIC model!");
193 bool LTOCodeGenerator::writeMergedModules(const char *path,
194 std::string &errMsg) {
195 if (!determineTarget(errMsg))
198 // mark which symbols can not be internalized
199 applyScopeRestrictions();
201 // create output file
203 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
204 if (!ErrInfo.empty()) {
205 errMsg = "could not open bitcode file for writing: ";
210 // write bitcode to it
211 WriteBitcodeToFile(_linker.getModule(), Out.os());
214 if (Out.os().has_error()) {
215 errMsg = "could not write bitcode file: ";
217 Out.os().clear_error();
225 // This function is to ensure cl::ParseCommandLineOptions() is called no more
226 // than once. It would otherwise complain and exit the compilation prematurely.
228 void LTOCodeGenerator::parseOptions() {
232 if (!_codegenOptions.empty())
233 cl::ParseCommandLineOptions(_codegenOptions.size(),
234 const_cast<char **>(&_codegenOptions[0]));
236 OptionsParsed = true;
239 // Do some prepartion right before compilation starts.
240 bool LTOCodeGenerator::prepareBeforeCompile(std::string &ErrMsg) {
243 if (!determineTarget(ErrMsg))
246 FileMgr.setWorkDir(TmpWorkDir.c_str());
247 FileMgr.setKeepWorkDir(KeepWorkDir);
248 return FileMgr.createWorkDir(ErrMsg);
251 bool LTOCodeGenerator::compile_to_file(const char** Name, std::string& ErrMsg) {
252 if (!prepareBeforeCompile(ErrMsg))
255 performIPO(EnablePartition, ErrMsg);
256 if (!performPostIPO(ErrMsg))
259 *Name = PartitionMgr.getSinglePartition()->getObjFilePath().c_str();
263 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
265 if (!compile_to_file(&name, errMsg))
268 // remove old buffer if compile() called twice
269 delete _nativeObjectFile;
271 // read .o file into memory buffer
272 OwningPtr<MemoryBuffer> BuffPtr;
273 const char *BufStart = 0;
275 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
276 errMsg = ec.message();
277 _nativeObjectFile = 0;
279 if ((_nativeObjectFile = BuffPtr.take())) {
280 *length = _nativeObjectFile->getBufferSize();
281 BufStart = _nativeObjectFile->getBufferStart();
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.
288 FileMgr.removeAllUnneededFiles();
293 const char *LTOCodeGenerator::getFilesNeedToRemove() {
294 IPOFileMgr::FileNameVect ToRm;
295 FileMgr.getFilesNeedToRemove(ToRm);
297 ConcatStrings.clear();
298 for (IPOFileMgr::FileNameVect::iterator I = ToRm.begin(), E = ToRm.end();
301 ConcatStrings.append(S.begin(), S.end());
302 ConcatStrings.push_back('\0');
304 ConcatStrings.push_back('\0');
305 ConcatStrings.push_back('\0');
307 return ConcatStrings.data();
310 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
314 // if options were requested, set them
317 std::string TripleStr = _linker.getModule()->getTargetTriple();
318 if (TripleStr.empty())
319 TripleStr = sys::getDefaultTargetTriple();
320 llvm::Triple Triple(TripleStr);
322 // create target machine from info for merged modules
323 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
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;
334 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
335 RelocModel = Reloc::PIC_;
337 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
338 RelocModel = Reloc::DynamicNoPIC;
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)
350 else if (Triple.getArch() == llvm::Triple::x86)
353 TargetOptions Options;
354 LTOModule::getTargetOptions(Options);
355 _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
356 RelocModel, CodeModel::Default,
357 CodeGenOpt::Aggressive);
361 void LTOCodeGenerator::
362 applyRestriction(GlobalValue &GV,
363 std::vector<const char*> &mustPreserveList,
364 SmallPtrSet<GlobalValue*, 8> &asmUsed,
366 SmallString<64> Buffer;
367 mangler.getNameWithPrefix(Buffer, &GV, false);
369 if (GV.isDeclaration())
371 if (_mustPreserveSymbols.count(Buffer))
372 mustPreserveList.push_back(GV.getName().data());
373 if (_asmUndefinedRefs.count(Buffer))
377 static void findUsedValues(GlobalVariable *LLVMUsed,
378 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
379 if (LLVMUsed == 0) return;
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);
388 void LTOCodeGenerator::applyScopeRestrictions() {
389 if (_scopeRestrictionsDone) return;
390 Module *mergedModule = _linker.getModule();
392 // Start off with a verification pass.
394 passes.add(createVerifierPass());
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;
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);
412 GlobalVariable *LLVMCompilerUsed =
413 mergedModule->getGlobalVariable("llvm.compiler.used");
414 findUsedValues(LLVMCompilerUsed, asmUsed);
415 if (LLVMCompilerUsed)
416 LLVMCompilerUsed->eraseFromParent();
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);
428 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
430 new llvm::GlobalVariable(*mergedModule, ATy, false,
431 llvm::GlobalValue::AppendingLinkage,
432 llvm::ConstantArray::get(ATy, asmUsed2),
433 "llvm.compiler.used");
435 LLVMCompilerUsed->setSection("llvm.metadata");
438 passes.add(createInternalizePass(mustPreserveList));
440 // apply scope restrictions
441 passes.run(*mergedModule);
443 _scopeRestrictionsDone = true;
446 void LTOCodeGenerator::performIPO(bool ToPartition, std::string &errMsg) {
447 // Mark which symbols can not be internalized
448 applyScopeRestrictions();
450 // Instantiate the pass manager to organize the passes.
453 // Start off with a verification pass.
454 Passes.add(createVerifierPass());
456 // Add an appropriate DataLayout instance for this module...
457 Passes.add(new DataLayout(*_target->getDataLayout()));
458 _target->addAnalysisPasses(Passes);
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.
464 PassManagerBuilder().populateLTOPassManager(Passes,
465 /*Internalize=*/false,
468 // Make sure everything is still good.
469 Passes.add(createVerifierPass());
471 Module* M = _linker.getModule();
473 assert(false && "TBD");
477 // Create a partition for the merged module.
478 PartitionMgr.createIPOPart(M);
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".
487 bool LTOCodeGenerator::performPostIPO(std::string &ErrMsg,
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;
496 DrvTy = PostIPODriver::PIDV_Invalid;
497 assert(false && "TBD");
500 PostIPODriver D(DrvTy, _target, PartitionMgr, FileMgr, MergeObjs);
501 if (D.Compile(ErrMsg)) {
503 *MergObjPath = D.getSingleObjFile()->getPath().c_str();
510 /// Optimize merged modules using various IPO passes
511 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
512 std::string &errMsg) {
513 if (!this->determineTarget(errMsg))
516 Module* mergedModule = _linker.getModule();
518 // Mark which symbols can not be internalized
519 this->applyScopeRestrictions();
521 // Instantiate the pass manager to organize the passes.
524 // Start off with a verification pass.
525 passes.add(createVerifierPass());
527 // Add an appropriate DataLayout instance for this module...
528 passes.add(new DataLayout(*_target->getDataLayout()));
529 _target->addAnalysisPasses(passes);
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.
535 PassManagerBuilder().populateLTOPassManager(passes,
536 /*Internalize=*/false,
540 // Make sure everything is still good.
541 passes.add(createVerifierPass());
543 PassManager codeGenPasses;
545 codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
546 _target->addAnalysisPasses(codeGenPasses);
548 formatted_raw_ostream Out(out);
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());
554 if (_target->addPassesToEmitFile(codeGenPasses, Out,
555 TargetMachine::CGFT_ObjectFile)) {
556 errMsg = "target file type not supported";
560 // Run our queue of passes all at once now, efficiently.
561 passes.run(*mergedModule);
563 // Run the code generator, and write assembly file
564 codeGenPasses.run(*mergedModule);
569 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
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
576 if (_codegenOptions.empty())
577 _codegenOptions.push_back(strdup("libLTO"));
578 _codegenOptions.push_back(strdup(o.first.str().c_str()));