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)) {
68 initializeLTOPasses();
71 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72 : OwnedContext(std::move(Context)), Context(*OwnedContext),
73 IRLinker(new Module("ld-temp.o", *OwnedContext)) {
74 initializeLTOPasses();
77 void LTOCodeGenerator::destroyMergedModule() {
79 assert(IRLinker.getModule() == &OwnedModule->getModule() &&
80 "The linker's module should be the same as the owned module");
82 OwnedModule = nullptr;
83 } else if (IRLinker.getModule())
84 IRLinker.deleteModule();
87 LTOCodeGenerator::~LTOCodeGenerator() {
88 destroyMergedModule();
93 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
94 E = CodegenOptions.end();
99 // Initialize LTO passes. Please keep this funciton in sync with
100 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
101 // passes are initialized.
102 void LTOCodeGenerator::initializeLTOPasses() {
103 PassRegistry &R = *PassRegistry::getPassRegistry();
105 initializeInternalizePassPass(R);
106 initializeIPSCCPPass(R);
107 initializeGlobalOptPass(R);
108 initializeConstantMergePass(R);
109 initializeDAHPass(R);
110 initializeInstructionCombiningPassPass(R);
111 initializeSimpleInlinerPass(R);
112 initializePruneEHPass(R);
113 initializeGlobalDCEPass(R);
114 initializeArgPromotionPass(R);
115 initializeJumpThreadingPass(R);
116 initializeSROAPass(R);
117 initializeSROA_DTPass(R);
118 initializeSROA_SSAUpPass(R);
119 initializeFunctionAttrsPass(R);
120 initializeGlobalsModRefPass(R);
121 initializeLICMPass(R);
122 initializeMergedLoadStoreMotionPass(R);
123 initializeGVNPass(R);
124 initializeMemCpyOptPass(R);
125 initializeDCEPass(R);
126 initializeCFGSimplifyPassPass(R);
129 bool LTOCodeGenerator::addModule(LTOModule *mod) {
130 assert(&mod->getModule().getContext() == &Context &&
131 "Expected module in same context");
133 bool ret = IRLinker.linkInModule(&mod->getModule());
135 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
136 for (int i = 0, e = undefs.size(); i != e; ++i)
137 AsmUndefinedRefs[undefs[i]] = 1;
142 void LTOCodeGenerator::setModule(LTOModule *Mod) {
143 assert(&Mod->getModule().getContext() == &Context &&
144 "Expected module in same context");
146 // Delete the old merged module.
147 destroyMergedModule();
148 AsmUndefinedRefs.clear();
151 IRLinker.setModule(&Mod->getModule());
153 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
154 for (int I = 0, E = Undefs.size(); I != E; ++I)
155 AsmUndefinedRefs[Undefs[I]] = 1;
158 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
162 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
164 case LTO_DEBUG_MODEL_NONE:
165 EmitDwarfDebugInfo = false;
168 case LTO_DEBUG_MODEL_DWARF:
169 EmitDwarfDebugInfo = true;
172 llvm_unreachable("Unknown debug format!");
175 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
177 case LTO_CODEGEN_PIC_MODEL_STATIC:
178 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
179 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
180 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
184 llvm_unreachable("Unknown PIC model!");
187 bool LTOCodeGenerator::writeMergedModules(const char *path,
188 std::string &errMsg) {
189 if (!determineTarget(errMsg))
192 // mark which symbols can not be internalized
193 applyScopeRestrictions();
195 // create output file
197 tool_output_file Out(path, EC, sys::fs::F_None);
199 errMsg = "could not open bitcode file for writing: ";
204 // write bitcode to it
205 WriteBitcodeToFile(IRLinker.getModule(), Out.os(), ShouldEmbedUselists);
208 if (Out.os().has_error()) {
209 errMsg = "could not write bitcode file: ";
211 Out.os().clear_error();
219 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
220 std::string &errMsg) {
221 // make unique temp .o file to put generated object file
222 SmallString<128> Filename;
225 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
227 errMsg = EC.message();
231 // generate object file
232 tool_output_file objFile(Filename.c_str(), FD);
234 bool genResult = compileOptimized(objFile.os(), errMsg);
235 objFile.os().close();
236 if (objFile.os().has_error()) {
237 objFile.os().clear_error();
238 sys::fs::remove(Twine(Filename));
244 sys::fs::remove(Twine(Filename));
248 NativeObjectPath = Filename.c_str();
249 *name = NativeObjectPath.c_str();
253 std::unique_ptr<MemoryBuffer>
254 LTOCodeGenerator::compileOptimized(std::string &errMsg) {
256 if (!compileOptimizedToFile(&name, errMsg))
259 // read .o file into memory buffer
260 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
261 MemoryBuffer::getFile(name, -1, false);
262 if (std::error_code EC = BufferOrErr.getError()) {
263 errMsg = EC.message();
264 sys::fs::remove(NativeObjectPath);
269 sys::fs::remove(NativeObjectPath);
271 return std::move(*BufferOrErr);
275 bool LTOCodeGenerator::compile_to_file(const char **name,
277 bool disableGVNLoadPRE,
278 bool disableVectorization,
279 std::string &errMsg) {
280 if (!optimize(disableInline, disableGVNLoadPRE,
281 disableVectorization, errMsg))
284 return compileOptimizedToFile(name, errMsg);
287 std::unique_ptr<MemoryBuffer>
288 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
289 bool disableVectorization, std::string &errMsg) {
290 if (!optimize(disableInline, disableGVNLoadPRE,
291 disableVectorization, errMsg))
294 return compileOptimized(errMsg);
297 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
301 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
302 if (TripleStr.empty())
303 TripleStr = sys::getDefaultTargetTriple();
304 llvm::Triple Triple(TripleStr);
306 // create target machine from info for merged modules
307 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
311 // The relocation model is actually a static member of TargetMachine and
312 // needs to be set before the TargetMachine is instantiated.
313 Reloc::Model RelocModel = Reloc::Default;
315 case LTO_CODEGEN_PIC_MODEL_STATIC:
316 RelocModel = Reloc::Static;
318 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
319 RelocModel = Reloc::PIC_;
321 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
322 RelocModel = Reloc::DynamicNoPIC;
324 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
325 // RelocModel is already the default, so leave it that way.
329 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
330 // the default set of features.
331 SubtargetFeatures Features(MAttr);
332 Features.getDefaultSubtargetFeatures(Triple);
333 std::string FeatureStr = Features.getString();
334 // Set a default CPU for Darwin triples.
335 if (MCpu.empty() && Triple.isOSDarwin()) {
336 if (Triple.getArch() == llvm::Triple::x86_64)
338 else if (Triple.getArch() == llvm::Triple::x86)
340 else if (Triple.getArch() == llvm::Triple::aarch64)
344 CodeGenOpt::Level CGOptLevel;
347 CGOptLevel = CodeGenOpt::None;
350 CGOptLevel = CodeGenOpt::Less;
353 CGOptLevel = CodeGenOpt::Default;
356 CGOptLevel = CodeGenOpt::Aggressive;
360 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
361 RelocModel, CodeModel::Default,
366 void LTOCodeGenerator::
367 applyRestriction(GlobalValue &GV,
368 ArrayRef<StringRef> Libcalls,
369 std::vector<const char*> &MustPreserveList,
370 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
372 // There are no restrictions to apply to declarations.
373 if (GV.isDeclaration())
376 // There is nothing more restrictive than private linkage.
377 if (GV.hasPrivateLinkage())
380 SmallString<64> Buffer;
381 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
383 if (MustPreserveSymbols.count(Buffer))
384 MustPreserveList.push_back(GV.getName().data());
385 if (AsmUndefinedRefs.count(Buffer))
388 // Conservatively append user-supplied runtime library functions to
389 // llvm.compiler.used. These could be internalized and deleted by
390 // optimizations like -globalopt, causing problems when later optimizations
391 // add new library calls (e.g., llvm.memset => memset and printf => puts).
392 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
393 if (isa<Function>(GV) &&
394 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
398 static void findUsedValues(GlobalVariable *LLVMUsed,
399 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
400 if (!LLVMUsed) return;
402 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
403 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
404 if (GlobalValue *GV =
405 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
406 UsedValues.insert(GV);
409 // Collect names of runtime library functions. User-defined functions with the
410 // same names are added to llvm.compiler.used to prevent them from being
411 // deleted by optimizations.
412 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
413 const TargetLibraryInfo& TLI,
415 const TargetMachine &TM) {
416 // TargetLibraryInfo has info on C runtime library calls on the current
418 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
420 LibFunc::Func F = static_cast<LibFunc::Func>(I);
422 Libcalls.push_back(TLI.getName(F));
425 SmallPtrSet<const TargetLowering *, 1> TLSet;
427 for (const Function &F : Mod) {
428 const TargetLowering *Lowering =
429 TM.getSubtargetImpl(F)->getTargetLowering();
431 if (Lowering && TLSet.insert(Lowering).second)
432 // TargetLowering has info on library calls that CodeGen expects to be
433 // available, both from the C runtime and compiler-rt.
434 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
436 if (const char *Name =
437 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
438 Libcalls.push_back(Name);
441 array_pod_sort(Libcalls.begin(), Libcalls.end());
442 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
446 void LTOCodeGenerator::applyScopeRestrictions() {
447 if (ScopeRestrictionsDone || !ShouldInternalize)
449 Module *mergedModule = IRLinker.getModule();
451 // Start off with a verification pass.
452 legacy::PassManager passes;
453 passes.add(createVerifierPass());
455 // mark which symbols can not be internalized
457 std::vector<const char*> MustPreserveList;
458 SmallPtrSet<GlobalValue*, 8> AsmUsed;
459 std::vector<StringRef> Libcalls;
460 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
461 TargetLibraryInfo TLI(TLII);
463 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
465 for (Module::iterator f = mergedModule->begin(),
466 e = mergedModule->end(); f != e; ++f)
467 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
468 for (Module::global_iterator v = mergedModule->global_begin(),
469 e = mergedModule->global_end(); v != e; ++v)
470 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
471 for (Module::alias_iterator a = mergedModule->alias_begin(),
472 e = mergedModule->alias_end(); a != e; ++a)
473 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
475 GlobalVariable *LLVMCompilerUsed =
476 mergedModule->getGlobalVariable("llvm.compiler.used");
477 findUsedValues(LLVMCompilerUsed, AsmUsed);
478 if (LLVMCompilerUsed)
479 LLVMCompilerUsed->eraseFromParent();
481 if (!AsmUsed.empty()) {
482 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
483 std::vector<Constant*> asmUsed2;
484 for (auto *GV : AsmUsed) {
485 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
486 asmUsed2.push_back(c);
489 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
491 new llvm::GlobalVariable(*mergedModule, ATy, false,
492 llvm::GlobalValue::AppendingLinkage,
493 llvm::ConstantArray::get(ATy, asmUsed2),
494 "llvm.compiler.used");
496 LLVMCompilerUsed->setSection("llvm.metadata");
499 passes.add(createInternalizePass(MustPreserveList));
501 // apply scope restrictions
502 passes.run(*mergedModule);
504 ScopeRestrictionsDone = true;
507 /// Optimize merged modules using various IPO passes
508 bool LTOCodeGenerator::optimize(bool DisableInline,
509 bool DisableGVNLoadPRE,
510 bool DisableVectorization,
511 std::string &errMsg) {
512 if (!this->determineTarget(errMsg))
515 Module *mergedModule = IRLinker.getModule();
517 // Mark which symbols can not be internalized
518 this->applyScopeRestrictions();
520 // Instantiate the pass manager to organize the passes.
521 legacy::PassManager passes;
523 // Add an appropriate DataLayout instance for this module...
524 mergedModule->setDataLayout(*TargetMach->getDataLayout());
527 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
529 Triple TargetTriple(TargetMach->getTargetTriple());
530 PassManagerBuilder PMB;
531 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
532 PMB.LoopVectorize = !DisableVectorization;
533 PMB.SLPVectorize = !DisableVectorization;
535 PMB.Inliner = createFunctionInliningPass();
536 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
537 PMB.OptLevel = OptLevel;
538 PMB.VerifyInput = true;
539 PMB.VerifyOutput = true;
541 PMB.populateLTOPassManager(passes);
543 // Run our queue of passes all at once now, efficiently.
544 passes.run(*mergedModule);
549 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
550 std::string &errMsg) {
551 if (!this->determineTarget(errMsg))
554 Module *mergedModule = IRLinker.getModule();
556 legacy::PassManager codeGenPasses;
558 // If the bitcode files contain ARC code and were compiled with optimization,
559 // the ObjCARCContractPass must be run, so do it unconditionally here.
560 codeGenPasses.add(createObjCARCContractPass());
562 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
563 TargetMachine::CGFT_ObjectFile)) {
564 errMsg = "target file type not supported";
568 // Run the code generator, and write assembly file
569 codeGenPasses.run(*mergedModule);
574 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
576 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
577 for (std::pair<StringRef, StringRef> o = getToken(options);
578 !o.first.empty(); o = getToken(o.second)) {
579 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
581 if (CodegenOptions.empty())
582 CodegenOptions.push_back(strdup("libLLVMLTO"));
583 CodegenOptions.push_back(strdup(o.first.str().c_str()));
587 void LTOCodeGenerator::parseCodeGenDebugOptions() {
588 // if options were requested, set them
589 if (!CodegenOptions.empty())
590 cl::ParseCommandLineOptions(CodegenOptions.size(),
591 const_cast<char **>(&CodegenOptions[0]));
594 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
596 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
599 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
600 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
601 lto_codegen_diagnostic_severity_t Severity;
602 switch (DI.getSeverity()) {
604 Severity = LTO_DS_ERROR;
607 Severity = LTO_DS_WARNING;
610 Severity = LTO_DS_REMARK;
613 Severity = LTO_DS_NOTE;
616 // Create the string that will be reported to the external diagnostic handler.
617 std::string MsgStorage;
618 raw_string_ostream Stream(MsgStorage);
619 DiagnosticPrinterRawOStream DP(Stream);
623 // If this method has been called it means someone has set up an external
624 // diagnostic handler. Assert on that.
625 assert(DiagHandler && "Invalid diagnostic handler");
626 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
630 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
632 this->DiagHandler = DiagHandler;
633 this->DiagContext = Ctxt;
635 return Context.setDiagnosticHandler(nullptr, nullptr);
636 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
637 // diagnostic to the external DiagHandler.
638 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
639 /* RespectFilters */ true);