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(),
206 /* ShouldPreserveUseListOrder */ true);
209 if (Out.os().has_error()) {
210 errMsg = "could not write bitcode file: ";
212 Out.os().clear_error();
220 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
221 std::string &errMsg) {
222 // make unique temp .o file to put generated object file
223 SmallString<128> Filename;
226 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
228 errMsg = EC.message();
232 // generate object file
233 tool_output_file objFile(Filename.c_str(), FD);
235 bool genResult = compileOptimized(objFile.os(), errMsg);
236 objFile.os().close();
237 if (objFile.os().has_error()) {
238 objFile.os().clear_error();
239 sys::fs::remove(Twine(Filename));
245 sys::fs::remove(Twine(Filename));
249 NativeObjectPath = Filename.c_str();
250 *name = NativeObjectPath.c_str();
254 const void *LTOCodeGenerator::compileOptimized(size_t *length,
255 std::string &errMsg) {
257 if (!compileOptimizedToFile(&name, errMsg))
260 // read .o file into memory buffer
261 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
262 MemoryBuffer::getFile(name, -1, false);
263 if (std::error_code EC = BufferOrErr.getError()) {
264 errMsg = EC.message();
265 sys::fs::remove(NativeObjectPath);
268 NativeObjectFile = std::move(*BufferOrErr);
271 sys::fs::remove(NativeObjectPath);
273 // return buffer, unless error
274 if (!NativeObjectFile)
276 *length = NativeObjectFile->getBufferSize();
277 return NativeObjectFile->getBufferStart();
281 bool LTOCodeGenerator::compile_to_file(const char **name,
283 bool disableGVNLoadPRE,
284 bool disableVectorization,
285 std::string &errMsg) {
286 if (!optimize(disableInline, disableGVNLoadPRE,
287 disableVectorization, errMsg))
290 return compileOptimizedToFile(name, errMsg);
293 const void* LTOCodeGenerator::compile(size_t *length,
295 bool disableGVNLoadPRE,
296 bool disableVectorization,
297 std::string &errMsg) {
298 if (!optimize(disableInline, disableGVNLoadPRE,
299 disableVectorization, errMsg))
302 return compileOptimized(length, errMsg);
305 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
309 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
310 if (TripleStr.empty())
311 TripleStr = sys::getDefaultTargetTriple();
312 llvm::Triple Triple(TripleStr);
314 // create target machine from info for merged modules
315 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
319 // The relocation model is actually a static member of TargetMachine and
320 // needs to be set before the TargetMachine is instantiated.
321 Reloc::Model RelocModel = Reloc::Default;
323 case LTO_CODEGEN_PIC_MODEL_STATIC:
324 RelocModel = Reloc::Static;
326 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
327 RelocModel = Reloc::PIC_;
329 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
330 RelocModel = Reloc::DynamicNoPIC;
332 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
333 // RelocModel is already the default, so leave it that way.
337 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
338 // the default set of features.
339 SubtargetFeatures Features(MAttr);
340 Features.getDefaultSubtargetFeatures(Triple);
341 std::string FeatureStr = Features.getString();
342 // Set a default CPU for Darwin triples.
343 if (MCpu.empty() && Triple.isOSDarwin()) {
344 if (Triple.getArch() == llvm::Triple::x86_64)
346 else if (Triple.getArch() == llvm::Triple::x86)
348 else if (Triple.getArch() == llvm::Triple::aarch64)
352 CodeGenOpt::Level CGOptLevel;
355 CGOptLevel = CodeGenOpt::None;
358 CGOptLevel = CodeGenOpt::Less;
361 CGOptLevel = CodeGenOpt::Default;
364 CGOptLevel = CodeGenOpt::Aggressive;
368 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
369 RelocModel, CodeModel::Default,
374 void LTOCodeGenerator::
375 applyRestriction(GlobalValue &GV,
376 ArrayRef<StringRef> Libcalls,
377 std::vector<const char*> &MustPreserveList,
378 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
380 // There are no restrictions to apply to declarations.
381 if (GV.isDeclaration())
384 // There is nothing more restrictive than private linkage.
385 if (GV.hasPrivateLinkage())
388 SmallString<64> Buffer;
389 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
391 if (MustPreserveSymbols.count(Buffer))
392 MustPreserveList.push_back(GV.getName().data());
393 if (AsmUndefinedRefs.count(Buffer))
396 // Conservatively append user-supplied runtime library functions to
397 // llvm.compiler.used. These could be internalized and deleted by
398 // optimizations like -globalopt, causing problems when later optimizations
399 // add new library calls (e.g., llvm.memset => memset and printf => puts).
400 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
401 if (isa<Function>(GV) &&
402 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
406 static void findUsedValues(GlobalVariable *LLVMUsed,
407 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
408 if (!LLVMUsed) return;
410 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
411 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
412 if (GlobalValue *GV =
413 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
414 UsedValues.insert(GV);
417 // Collect names of runtime library functions. User-defined functions with the
418 // same names are added to llvm.compiler.used to prevent them from being
419 // deleted by optimizations.
420 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
421 const TargetLibraryInfo& TLI,
423 const TargetMachine &TM) {
424 // TargetLibraryInfo has info on C runtime library calls on the current
426 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
428 LibFunc::Func F = static_cast<LibFunc::Func>(I);
430 Libcalls.push_back(TLI.getName(F));
433 SmallPtrSet<const TargetLowering *, 1> TLSet;
435 for (const Function &F : Mod) {
436 const TargetLowering *Lowering =
437 TM.getSubtargetImpl(F)->getTargetLowering();
439 if (Lowering && TLSet.insert(Lowering).second)
440 // TargetLowering has info on library calls that CodeGen expects to be
441 // available, both from the C runtime and compiler-rt.
442 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
444 if (const char *Name =
445 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
446 Libcalls.push_back(Name);
449 array_pod_sort(Libcalls.begin(), Libcalls.end());
450 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
454 void LTOCodeGenerator::applyScopeRestrictions() {
455 if (ScopeRestrictionsDone || !ShouldInternalize)
457 Module *mergedModule = IRLinker.getModule();
459 // Start off with a verification pass.
460 legacy::PassManager passes;
461 passes.add(createVerifierPass());
463 // mark which symbols can not be internalized
464 Mangler Mangler(TargetMach->getDataLayout());
465 std::vector<const char*> MustPreserveList;
466 SmallPtrSet<GlobalValue*, 8> AsmUsed;
467 std::vector<StringRef> Libcalls;
468 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
469 TargetLibraryInfo TLI(TLII);
471 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
473 for (Module::iterator f = mergedModule->begin(),
474 e = mergedModule->end(); f != e; ++f)
475 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
476 for (Module::global_iterator v = mergedModule->global_begin(),
477 e = mergedModule->global_end(); v != e; ++v)
478 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
479 for (Module::alias_iterator a = mergedModule->alias_begin(),
480 e = mergedModule->alias_end(); a != e; ++a)
481 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
483 GlobalVariable *LLVMCompilerUsed =
484 mergedModule->getGlobalVariable("llvm.compiler.used");
485 findUsedValues(LLVMCompilerUsed, AsmUsed);
486 if (LLVMCompilerUsed)
487 LLVMCompilerUsed->eraseFromParent();
489 if (!AsmUsed.empty()) {
490 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
491 std::vector<Constant*> asmUsed2;
492 for (auto *GV : AsmUsed) {
493 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
494 asmUsed2.push_back(c);
497 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
499 new llvm::GlobalVariable(*mergedModule, ATy, false,
500 llvm::GlobalValue::AppendingLinkage,
501 llvm::ConstantArray::get(ATy, asmUsed2),
502 "llvm.compiler.used");
504 LLVMCompilerUsed->setSection("llvm.metadata");
507 passes.add(createInternalizePass(MustPreserveList));
509 // apply scope restrictions
510 passes.run(*mergedModule);
512 ScopeRestrictionsDone = true;
515 /// Optimize merged modules using various IPO passes
516 bool LTOCodeGenerator::optimize(bool DisableInline,
517 bool DisableGVNLoadPRE,
518 bool DisableVectorization,
519 std::string &errMsg) {
520 if (!this->determineTarget(errMsg))
523 Module *mergedModule = IRLinker.getModule();
525 // Mark which symbols can not be internalized
526 this->applyScopeRestrictions();
528 // Instantiate the pass manager to organize the passes.
529 legacy::PassManager passes;
531 // Add an appropriate DataLayout instance for this module...
532 mergedModule->setDataLayout(*TargetMach->getDataLayout());
535 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
537 Triple TargetTriple(TargetMach->getTargetTriple());
538 PassManagerBuilder PMB;
539 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
540 PMB.LoopVectorize = !DisableVectorization;
541 PMB.SLPVectorize = !DisableVectorization;
543 PMB.Inliner = createFunctionInliningPass();
544 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
545 PMB.OptLevel = OptLevel;
546 PMB.VerifyInput = true;
547 PMB.VerifyOutput = true;
549 PMB.populateLTOPassManager(passes);
551 // Run our queue of passes all at once now, efficiently.
552 passes.run(*mergedModule);
557 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
558 std::string &errMsg) {
559 if (!this->determineTarget(errMsg))
562 Module *mergedModule = IRLinker.getModule();
564 legacy::PassManager codeGenPasses;
566 // If the bitcode files contain ARC code and were compiled with optimization,
567 // the ObjCARCContractPass must be run, so do it unconditionally here.
568 codeGenPasses.add(createObjCARCContractPass());
570 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
571 TargetMachine::CGFT_ObjectFile)) {
572 errMsg = "target file type not supported";
576 // Run the code generator, and write assembly file
577 codeGenPasses.run(*mergedModule);
582 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
584 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
585 for (std::pair<StringRef, StringRef> o = getToken(options);
586 !o.first.empty(); o = getToken(o.second)) {
587 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
589 if (CodegenOptions.empty())
590 CodegenOptions.push_back(strdup("libLLVMLTO"));
591 CodegenOptions.push_back(strdup(o.first.str().c_str()));
595 void LTOCodeGenerator::parseCodeGenDebugOptions() {
596 // if options were requested, set them
597 if (!CodegenOptions.empty())
598 cl::ParseCommandLineOptions(CodegenOptions.size(),
599 const_cast<char **>(&CodegenOptions[0]));
602 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
604 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
607 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
608 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
609 lto_codegen_diagnostic_severity_t Severity;
610 switch (DI.getSeverity()) {
612 Severity = LTO_DS_ERROR;
615 Severity = LTO_DS_WARNING;
618 Severity = LTO_DS_REMARK;
621 Severity = LTO_DS_NOTE;
624 // Create the string that will be reported to the external diagnostic handler.
625 std::string MsgStorage;
626 raw_string_ostream Stream(MsgStorage);
627 DiagnosticPrinterRawOStream DP(Stream);
631 // If this method has been called it means someone has set up an external
632 // diagnostic handler. Assert on that.
633 assert(DiagHandler && "Invalid diagnostic handler");
634 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
638 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
640 this->DiagHandler = DiagHandler;
641 this->DiagContext = Ctxt;
643 return Context.setDiagnosticHandler(nullptr, nullptr);
644 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
645 // diagnostic to the external DiagHandler.
646 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
647 /* RespectFilters */ true);