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 "llvm/LTO/LTOCodeGenerator.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/RuntimeLibcalls.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/LTO/LTOModule.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include <system_error>
58 const char* LTOCodeGenerator::getVersionString() {
59 #ifdef LLVM_VERSION_INFO
60 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62 return PACKAGE_NAME " version " PACKAGE_VERSION;
66 LTOCodeGenerator::LTOCodeGenerator()
67 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
71 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72 : OwnedContext(std::move(Context)), Context(*OwnedContext),
73 IRLinker(new Module("ld-temp.o", *OwnedContext)), OptLevel(2) {
77 void LTOCodeGenerator::initialize() {
79 EmitDwarfDebugInfo = false;
80 ScopeRestrictionsDone = false;
81 CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
82 DiagHandler = nullptr;
83 DiagContext = nullptr;
84 OwnedModule = nullptr;
86 initializeLTOPasses();
89 void LTOCodeGenerator::destroyMergedModule() {
91 assert(IRLinker.getModule() == &OwnedModule->getModule() &&
92 "The linker's module should be the same as the owned module");
94 OwnedModule = nullptr;
95 } else if (IRLinker.getModule())
96 IRLinker.deleteModule();
99 LTOCodeGenerator::~LTOCodeGenerator() {
100 destroyMergedModule();
103 TargetMach = nullptr;
105 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
106 E = CodegenOptions.end();
111 // Initialize LTO passes. Please keep this funciton in sync with
112 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
113 // passes are initialized.
114 void LTOCodeGenerator::initializeLTOPasses() {
115 PassRegistry &R = *PassRegistry::getPassRegistry();
117 initializeInternalizePassPass(R);
118 initializeIPSCCPPass(R);
119 initializeGlobalOptPass(R);
120 initializeConstantMergePass(R);
121 initializeDAHPass(R);
122 initializeInstructionCombiningPassPass(R);
123 initializeSimpleInlinerPass(R);
124 initializePruneEHPass(R);
125 initializeGlobalDCEPass(R);
126 initializeArgPromotionPass(R);
127 initializeJumpThreadingPass(R);
128 initializeSROAPass(R);
129 initializeSROA_DTPass(R);
130 initializeSROA_SSAUpPass(R);
131 initializeFunctionAttrsPass(R);
132 initializeGlobalsModRefPass(R);
133 initializeLICMPass(R);
134 initializeMergedLoadStoreMotionPass(R);
135 initializeGVNPass(R);
136 initializeMemCpyOptPass(R);
137 initializeDCEPass(R);
138 initializeCFGSimplifyPassPass(R);
141 bool LTOCodeGenerator::addModule(LTOModule *mod) {
142 assert(&mod->getModule().getContext() == &Context &&
143 "Expected module in same context");
145 bool ret = IRLinker.linkInModule(&mod->getModule());
147 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
148 for (int i = 0, e = undefs.size(); i != e; ++i)
149 AsmUndefinedRefs[undefs[i]] = 1;
154 void LTOCodeGenerator::setModule(LTOModule *Mod) {
155 assert(&Mod->getModule().getContext() == &Context &&
156 "Expected module in same context");
158 // Delete the old merged module.
159 destroyMergedModule();
160 AsmUndefinedRefs.clear();
163 IRLinker.setModule(&Mod->getModule());
165 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
166 for (int I = 0, E = Undefs.size(); I != E; ++I)
167 AsmUndefinedRefs[Undefs[I]] = 1;
170 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
174 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
176 case LTO_DEBUG_MODEL_NONE:
177 EmitDwarfDebugInfo = false;
180 case LTO_DEBUG_MODEL_DWARF:
181 EmitDwarfDebugInfo = true;
184 llvm_unreachable("Unknown debug format!");
187 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
189 case LTO_CODEGEN_PIC_MODEL_STATIC:
190 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
191 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
192 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
196 llvm_unreachable("Unknown PIC model!");
199 bool LTOCodeGenerator::writeMergedModules(const char *path,
200 std::string &errMsg) {
201 if (!determineTarget(errMsg))
204 // mark which symbols can not be internalized
205 applyScopeRestrictions();
207 // create output file
209 tool_output_file Out(path, EC, sys::fs::F_None);
211 errMsg = "could not open bitcode file for writing: ";
216 // write bitcode to it
217 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
220 if (Out.os().has_error()) {
221 errMsg = "could not write bitcode file: ";
223 Out.os().clear_error();
231 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
232 std::string &errMsg) {
233 // make unique temp .o file to put generated object file
234 SmallString<128> Filename;
237 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
239 errMsg = EC.message();
243 // generate object file
244 tool_output_file objFile(Filename.c_str(), FD);
246 bool genResult = compileOptimized(objFile.os(), errMsg);
247 objFile.os().close();
248 if (objFile.os().has_error()) {
249 objFile.os().clear_error();
250 sys::fs::remove(Twine(Filename));
256 sys::fs::remove(Twine(Filename));
260 NativeObjectPath = Filename.c_str();
261 *name = NativeObjectPath.c_str();
265 const void *LTOCodeGenerator::compileOptimized(size_t *length,
266 std::string &errMsg) {
268 if (!compileOptimizedToFile(&name, errMsg))
271 // read .o file into memory buffer
272 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
273 MemoryBuffer::getFile(name, -1, false);
274 if (std::error_code EC = BufferOrErr.getError()) {
275 errMsg = EC.message();
276 sys::fs::remove(NativeObjectPath);
279 NativeObjectFile = std::move(*BufferOrErr);
282 sys::fs::remove(NativeObjectPath);
284 // return buffer, unless error
285 if (!NativeObjectFile)
287 *length = NativeObjectFile->getBufferSize();
288 return NativeObjectFile->getBufferStart();
292 bool LTOCodeGenerator::compile_to_file(const char **name,
294 bool disableGVNLoadPRE,
295 bool disableVectorization,
296 std::string &errMsg) {
297 if (!optimize(disableInline, disableGVNLoadPRE,
298 disableVectorization, errMsg))
301 return compileOptimizedToFile(name, errMsg);
304 const void* LTOCodeGenerator::compile(size_t *length,
306 bool disableGVNLoadPRE,
307 bool disableVectorization,
308 std::string &errMsg) {
309 if (!optimize(disableInline, disableGVNLoadPRE,
310 disableVectorization, errMsg))
313 return compileOptimized(length, errMsg);
316 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
320 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
321 if (TripleStr.empty())
322 TripleStr = sys::getDefaultTargetTriple();
323 llvm::Triple Triple(TripleStr);
325 // create target machine from info for merged modules
326 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
330 // The relocation model is actually a static member of TargetMachine and
331 // needs to be set before the TargetMachine is instantiated.
332 Reloc::Model RelocModel = Reloc::Default;
334 case LTO_CODEGEN_PIC_MODEL_STATIC:
335 RelocModel = Reloc::Static;
337 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
338 RelocModel = Reloc::PIC_;
340 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
341 RelocModel = Reloc::DynamicNoPIC;
343 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
344 // RelocModel is already the default, so leave it that way.
348 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
349 // the default set of features.
350 SubtargetFeatures Features(MAttr);
351 Features.getDefaultSubtargetFeatures(Triple);
352 std::string FeatureStr = Features.getString();
353 // Set a default CPU for Darwin triples.
354 if (MCpu.empty() && Triple.isOSDarwin()) {
355 if (Triple.getArch() == llvm::Triple::x86_64)
357 else if (Triple.getArch() == llvm::Triple::x86)
359 else if (Triple.getArch() == llvm::Triple::aarch64)
363 CodeGenOpt::Level CGOptLevel;
366 CGOptLevel = CodeGenOpt::None;
369 CGOptLevel = CodeGenOpt::Less;
372 CGOptLevel = CodeGenOpt::Default;
375 CGOptLevel = CodeGenOpt::Aggressive;
379 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
380 RelocModel, CodeModel::Default,
385 void LTOCodeGenerator::
386 applyRestriction(GlobalValue &GV,
387 ArrayRef<StringRef> Libcalls,
388 std::vector<const char*> &MustPreserveList,
389 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
391 // There are no restrictions to apply to declarations.
392 if (GV.isDeclaration())
395 // There is nothing more restrictive than private linkage.
396 if (GV.hasPrivateLinkage())
399 SmallString<64> Buffer;
400 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
402 if (MustPreserveSymbols.count(Buffer))
403 MustPreserveList.push_back(GV.getName().data());
404 if (AsmUndefinedRefs.count(Buffer))
407 // Conservatively append user-supplied runtime library functions to
408 // llvm.compiler.used. These could be internalized and deleted by
409 // optimizations like -globalopt, causing problems when later optimizations
410 // add new library calls (e.g., llvm.memset => memset and printf => puts).
411 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
412 if (isa<Function>(GV) &&
413 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
417 static void findUsedValues(GlobalVariable *LLVMUsed,
418 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
419 if (!LLVMUsed) return;
421 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
422 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
423 if (GlobalValue *GV =
424 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
425 UsedValues.insert(GV);
428 // Collect names of runtime library functions. User-defined functions with the
429 // same names are added to llvm.compiler.used to prevent them from being
430 // deleted by optimizations.
431 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
432 const TargetLibraryInfo& TLI,
434 const TargetMachine &TM) {
435 // TargetLibraryInfo has info on C runtime library calls on the current
437 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
439 LibFunc::Func F = static_cast<LibFunc::Func>(I);
441 Libcalls.push_back(TLI.getName(F));
444 SmallPtrSet<const TargetLowering *, 1> TLSet;
446 for (const Function &F : Mod) {
447 const TargetLowering *Lowering =
448 TM.getSubtargetImpl(F)->getTargetLowering();
450 if (Lowering && TLSet.insert(Lowering).second)
451 // TargetLowering has info on library calls that CodeGen expects to be
452 // available, both from the C runtime and compiler-rt.
453 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
455 if (const char *Name =
456 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
457 Libcalls.push_back(Name);
460 array_pod_sort(Libcalls.begin(), Libcalls.end());
461 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
465 void LTOCodeGenerator::applyScopeRestrictions() {
466 if (ScopeRestrictionsDone)
468 Module *mergedModule = IRLinker.getModule();
470 // Start off with a verification pass.
471 legacy::PassManager passes;
472 passes.add(createVerifierPass());
474 // mark which symbols can not be internalized
475 Mangler Mangler(TargetMach->getDataLayout());
476 std::vector<const char*> MustPreserveList;
477 SmallPtrSet<GlobalValue*, 8> AsmUsed;
478 std::vector<StringRef> Libcalls;
479 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
480 TargetLibraryInfo TLI(TLII);
482 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
484 for (Module::iterator f = mergedModule->begin(),
485 e = mergedModule->end(); f != e; ++f)
486 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
487 for (Module::global_iterator v = mergedModule->global_begin(),
488 e = mergedModule->global_end(); v != e; ++v)
489 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
490 for (Module::alias_iterator a = mergedModule->alias_begin(),
491 e = mergedModule->alias_end(); a != e; ++a)
492 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
494 GlobalVariable *LLVMCompilerUsed =
495 mergedModule->getGlobalVariable("llvm.compiler.used");
496 findUsedValues(LLVMCompilerUsed, AsmUsed);
497 if (LLVMCompilerUsed)
498 LLVMCompilerUsed->eraseFromParent();
500 if (!AsmUsed.empty()) {
501 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
502 std::vector<Constant*> asmUsed2;
503 for (auto *GV : AsmUsed) {
504 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
505 asmUsed2.push_back(c);
508 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
510 new llvm::GlobalVariable(*mergedModule, ATy, false,
511 llvm::GlobalValue::AppendingLinkage,
512 llvm::ConstantArray::get(ATy, asmUsed2),
513 "llvm.compiler.used");
515 LLVMCompilerUsed->setSection("llvm.metadata");
518 passes.add(createInternalizePass(MustPreserveList));
520 // apply scope restrictions
521 passes.run(*mergedModule);
523 ScopeRestrictionsDone = true;
526 /// Optimize merged modules using various IPO passes
527 bool LTOCodeGenerator::optimize(bool DisableInline,
528 bool DisableGVNLoadPRE,
529 bool DisableVectorization,
530 std::string &errMsg) {
531 if (!this->determineTarget(errMsg))
534 Module *mergedModule = IRLinker.getModule();
536 // Mark which symbols can not be internalized
537 this->applyScopeRestrictions();
539 // Instantiate the pass manager to organize the passes.
540 legacy::PassManager passes;
542 // Add an appropriate DataLayout instance for this module...
543 mergedModule->setDataLayout(*TargetMach->getDataLayout());
546 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
548 Triple TargetTriple(TargetMach->getTargetTriple());
549 PassManagerBuilder PMB;
550 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
551 PMB.LoopVectorize = !DisableVectorization;
552 PMB.SLPVectorize = !DisableVectorization;
554 PMB.Inliner = createFunctionInliningPass();
555 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
556 PMB.OptLevel = OptLevel;
557 PMB.VerifyInput = true;
558 PMB.VerifyOutput = true;
560 PMB.populateLTOPassManager(passes);
562 // Run our queue of passes all at once now, efficiently.
563 passes.run(*mergedModule);
568 bool LTOCodeGenerator::compileOptimized(raw_ostream &out, std::string &errMsg) {
569 if (!this->determineTarget(errMsg))
572 Module *mergedModule = IRLinker.getModule();
574 legacy::PassManager codeGenPasses;
576 // If the bitcode files contain ARC code and were compiled with optimization,
577 // the ObjCARCContractPass must be run, so do it unconditionally here.
578 codeGenPasses.add(createObjCARCContractPass());
580 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
581 TargetMachine::CGFT_ObjectFile)) {
582 errMsg = "target file type not supported";
586 // Run the code generator, and write assembly file
587 codeGenPasses.run(*mergedModule);
592 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
594 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
595 for (std::pair<StringRef, StringRef> o = getToken(options);
596 !o.first.empty(); o = getToken(o.second)) {
597 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
599 if (CodegenOptions.empty())
600 CodegenOptions.push_back(strdup("libLLVMLTO"));
601 CodegenOptions.push_back(strdup(o.first.str().c_str()));
605 void LTOCodeGenerator::parseCodeGenDebugOptions() {
606 // if options were requested, set them
607 if (!CodegenOptions.empty())
608 cl::ParseCommandLineOptions(CodegenOptions.size(),
609 const_cast<char **>(&CodegenOptions[0]));
612 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
614 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
617 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
618 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
619 lto_codegen_diagnostic_severity_t Severity;
620 switch (DI.getSeverity()) {
622 Severity = LTO_DS_ERROR;
625 Severity = LTO_DS_WARNING;
628 Severity = LTO_DS_REMARK;
631 Severity = LTO_DS_NOTE;
634 // Create the string that will be reported to the external diagnostic handler.
635 std::string MsgStorage;
636 raw_string_ostream Stream(MsgStorage);
637 DiagnosticPrinterRawOStream DP(Stream);
641 // If this method has been called it means someone has set up an external
642 // diagnostic handler. Assert on that.
643 assert(DiagHandler && "Invalid diagnostic handler");
644 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
648 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
650 this->DiagHandler = DiagHandler;
651 this->DiagContext = Ctxt;
653 return Context.setDiagnosticHandler(nullptr, nullptr);
654 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
655 // diagnostic to the external DiagHandler.
656 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
657 /* RespectFilters */ true);