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 const void *LTOCodeGenerator::compileOptimized(size_t *length,
254 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);
267 NativeObjectFile = std::move(*BufferOrErr);
270 sys::fs::remove(NativeObjectPath);
272 // return buffer, unless error
273 if (!NativeObjectFile)
275 *length = NativeObjectFile->getBufferSize();
276 return NativeObjectFile->getBufferStart();
280 bool LTOCodeGenerator::compile_to_file(const char **name,
282 bool disableGVNLoadPRE,
283 bool disableVectorization,
284 std::string &errMsg) {
285 if (!optimize(disableInline, disableGVNLoadPRE,
286 disableVectorization, errMsg))
289 return compileOptimizedToFile(name, errMsg);
292 const void* LTOCodeGenerator::compile(size_t *length,
294 bool disableGVNLoadPRE,
295 bool disableVectorization,
296 std::string &errMsg) {
297 if (!optimize(disableInline, disableGVNLoadPRE,
298 disableVectorization, errMsg))
301 return compileOptimized(length, errMsg);
304 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
308 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
309 if (TripleStr.empty())
310 TripleStr = sys::getDefaultTargetTriple();
311 llvm::Triple Triple(TripleStr);
313 // create target machine from info for merged modules
314 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
318 // The relocation model is actually a static member of TargetMachine and
319 // needs to be set before the TargetMachine is instantiated.
320 Reloc::Model RelocModel = Reloc::Default;
322 case LTO_CODEGEN_PIC_MODEL_STATIC:
323 RelocModel = Reloc::Static;
325 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
326 RelocModel = Reloc::PIC_;
328 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
329 RelocModel = Reloc::DynamicNoPIC;
331 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
332 // RelocModel is already the default, so leave it that way.
336 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
337 // the default set of features.
338 SubtargetFeatures Features(MAttr);
339 Features.getDefaultSubtargetFeatures(Triple);
340 std::string FeatureStr = Features.getString();
341 // Set a default CPU for Darwin triples.
342 if (MCpu.empty() && Triple.isOSDarwin()) {
343 if (Triple.getArch() == llvm::Triple::x86_64)
345 else if (Triple.getArch() == llvm::Triple::x86)
347 else if (Triple.getArch() == llvm::Triple::aarch64)
351 CodeGenOpt::Level CGOptLevel;
354 CGOptLevel = CodeGenOpt::None;
357 CGOptLevel = CodeGenOpt::Less;
360 CGOptLevel = CodeGenOpt::Default;
363 CGOptLevel = CodeGenOpt::Aggressive;
367 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
368 RelocModel, CodeModel::Default,
373 void LTOCodeGenerator::
374 applyRestriction(GlobalValue &GV,
375 ArrayRef<StringRef> Libcalls,
376 std::vector<const char*> &MustPreserveList,
377 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
379 // There are no restrictions to apply to declarations.
380 if (GV.isDeclaration())
383 // There is nothing more restrictive than private linkage.
384 if (GV.hasPrivateLinkage())
387 SmallString<64> Buffer;
388 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
390 if (MustPreserveSymbols.count(Buffer))
391 MustPreserveList.push_back(GV.getName().data());
392 if (AsmUndefinedRefs.count(Buffer))
395 // Conservatively append user-supplied runtime library functions to
396 // llvm.compiler.used. These could be internalized and deleted by
397 // optimizations like -globalopt, causing problems when later optimizations
398 // add new library calls (e.g., llvm.memset => memset and printf => puts).
399 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
400 if (isa<Function>(GV) &&
401 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
405 static void findUsedValues(GlobalVariable *LLVMUsed,
406 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
407 if (!LLVMUsed) return;
409 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
410 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
411 if (GlobalValue *GV =
412 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
413 UsedValues.insert(GV);
416 // Collect names of runtime library functions. User-defined functions with the
417 // same names are added to llvm.compiler.used to prevent them from being
418 // deleted by optimizations.
419 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
420 const TargetLibraryInfo& TLI,
422 const TargetMachine &TM) {
423 // TargetLibraryInfo has info on C runtime library calls on the current
425 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
427 LibFunc::Func F = static_cast<LibFunc::Func>(I);
429 Libcalls.push_back(TLI.getName(F));
432 SmallPtrSet<const TargetLowering *, 1> TLSet;
434 for (const Function &F : Mod) {
435 const TargetLowering *Lowering =
436 TM.getSubtargetImpl(F)->getTargetLowering();
438 if (Lowering && TLSet.insert(Lowering).second)
439 // TargetLowering has info on library calls that CodeGen expects to be
440 // available, both from the C runtime and compiler-rt.
441 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
443 if (const char *Name =
444 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
445 Libcalls.push_back(Name);
448 array_pod_sort(Libcalls.begin(), Libcalls.end());
449 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
453 void LTOCodeGenerator::applyScopeRestrictions() {
454 if (ScopeRestrictionsDone || !ShouldInternalize)
456 Module *mergedModule = IRLinker.getModule();
458 // Start off with a verification pass.
459 legacy::PassManager passes;
460 passes.add(createVerifierPass());
462 // mark which symbols can not be internalized
463 Mangler Mangler(TargetMach->getDataLayout());
464 std::vector<const char*> MustPreserveList;
465 SmallPtrSet<GlobalValue*, 8> AsmUsed;
466 std::vector<StringRef> Libcalls;
467 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
468 TargetLibraryInfo TLI(TLII);
470 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
472 for (Module::iterator f = mergedModule->begin(),
473 e = mergedModule->end(); f != e; ++f)
474 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
475 for (Module::global_iterator v = mergedModule->global_begin(),
476 e = mergedModule->global_end(); v != e; ++v)
477 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
478 for (Module::alias_iterator a = mergedModule->alias_begin(),
479 e = mergedModule->alias_end(); a != e; ++a)
480 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
482 GlobalVariable *LLVMCompilerUsed =
483 mergedModule->getGlobalVariable("llvm.compiler.used");
484 findUsedValues(LLVMCompilerUsed, AsmUsed);
485 if (LLVMCompilerUsed)
486 LLVMCompilerUsed->eraseFromParent();
488 if (!AsmUsed.empty()) {
489 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
490 std::vector<Constant*> asmUsed2;
491 for (auto *GV : AsmUsed) {
492 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
493 asmUsed2.push_back(c);
496 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
498 new llvm::GlobalVariable(*mergedModule, ATy, false,
499 llvm::GlobalValue::AppendingLinkage,
500 llvm::ConstantArray::get(ATy, asmUsed2),
501 "llvm.compiler.used");
503 LLVMCompilerUsed->setSection("llvm.metadata");
506 passes.add(createInternalizePass(MustPreserveList));
508 // apply scope restrictions
509 passes.run(*mergedModule);
511 ScopeRestrictionsDone = true;
514 /// Optimize merged modules using various IPO passes
515 bool LTOCodeGenerator::optimize(bool DisableInline,
516 bool DisableGVNLoadPRE,
517 bool DisableVectorization,
518 std::string &errMsg) {
519 if (!this->determineTarget(errMsg))
522 Module *mergedModule = IRLinker.getModule();
524 // Mark which symbols can not be internalized
525 this->applyScopeRestrictions();
527 // Instantiate the pass manager to organize the passes.
528 legacy::PassManager passes;
530 // Add an appropriate DataLayout instance for this module...
531 mergedModule->setDataLayout(*TargetMach->getDataLayout());
534 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
536 Triple TargetTriple(TargetMach->getTargetTriple());
537 PassManagerBuilder PMB;
538 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
539 PMB.LoopVectorize = !DisableVectorization;
540 PMB.SLPVectorize = !DisableVectorization;
542 PMB.Inliner = createFunctionInliningPass();
543 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
544 PMB.OptLevel = OptLevel;
545 PMB.VerifyInput = true;
546 PMB.VerifyOutput = true;
548 PMB.populateLTOPassManager(passes);
550 // Run our queue of passes all at once now, efficiently.
551 passes.run(*mergedModule);
556 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
557 std::string &errMsg) {
558 if (!this->determineTarget(errMsg))
561 Module *mergedModule = IRLinker.getModule();
563 legacy::PassManager codeGenPasses;
565 // If the bitcode files contain ARC code and were compiled with optimization,
566 // the ObjCARCContractPass must be run, so do it unconditionally here.
567 codeGenPasses.add(createObjCARCContractPass());
569 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
570 TargetMachine::CGFT_ObjectFile)) {
571 errMsg = "target file type not supported";
575 // Run the code generator, and write assembly file
576 codeGenPasses.run(*mergedModule);
581 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
583 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
584 for (std::pair<StringRef, StringRef> o = getToken(options);
585 !o.first.empty(); o = getToken(o.second)) {
586 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
588 if (CodegenOptions.empty())
589 CodegenOptions.push_back(strdup("libLLVMLTO"));
590 CodegenOptions.push_back(strdup(o.first.str().c_str()));
594 void LTOCodeGenerator::parseCodeGenDebugOptions() {
595 // if options were requested, set them
596 if (!CodegenOptions.empty())
597 cl::ParseCommandLineOptions(CodegenOptions.size(),
598 const_cast<char **>(&CodegenOptions[0]));
601 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
603 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
606 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
607 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
608 lto_codegen_diagnostic_severity_t Severity;
609 switch (DI.getSeverity()) {
611 Severity = LTO_DS_ERROR;
614 Severity = LTO_DS_WARNING;
617 Severity = LTO_DS_REMARK;
620 Severity = LTO_DS_NOTE;
623 // Create the string that will be reported to the external diagnostic handler.
624 std::string MsgStorage;
625 raw_string_ostream Stream(MsgStorage);
626 DiagnosticPrinterRawOStream DP(Stream);
630 // If this method has been called it means someone has set up an external
631 // diagnostic handler. Assert on that.
632 assert(DiagHandler && "Invalid diagnostic handler");
633 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
637 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
639 this->DiagHandler = DiagHandler;
640 this->DiagContext = Ctxt;
642 return Context.setDiagnosticHandler(nullptr, nullptr);
643 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
644 // diagnostic to the external DiagHandler.
645 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
646 /* RespectFilters */ true);