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();
91 // Initialize LTO passes. Please keep this funciton in sync with
92 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
93 // passes are initialized.
94 void LTOCodeGenerator::initializeLTOPasses() {
95 PassRegistry &R = *PassRegistry::getPassRegistry();
97 initializeInternalizePassPass(R);
98 initializeIPSCCPPass(R);
99 initializeGlobalOptPass(R);
100 initializeConstantMergePass(R);
101 initializeDAHPass(R);
102 initializeInstructionCombiningPassPass(R);
103 initializeSimpleInlinerPass(R);
104 initializePruneEHPass(R);
105 initializeGlobalDCEPass(R);
106 initializeArgPromotionPass(R);
107 initializeJumpThreadingPass(R);
108 initializeSROAPass(R);
109 initializeSROA_DTPass(R);
110 initializeSROA_SSAUpPass(R);
111 initializeFunctionAttrsPass(R);
112 initializeGlobalsModRefPass(R);
113 initializeLICMPass(R);
114 initializeMergedLoadStoreMotionPass(R);
115 initializeGVNPass(R);
116 initializeMemCpyOptPass(R);
117 initializeDCEPass(R);
118 initializeCFGSimplifyPassPass(R);
121 bool LTOCodeGenerator::addModule(LTOModule *mod) {
122 assert(&mod->getModule().getContext() == &Context &&
123 "Expected module in same context");
125 bool ret = IRLinker.linkInModule(&mod->getModule());
127 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
128 for (int i = 0, e = undefs.size(); i != e; ++i)
129 AsmUndefinedRefs[undefs[i]] = 1;
134 void LTOCodeGenerator::setModule(LTOModule *Mod) {
135 assert(&Mod->getModule().getContext() == &Context &&
136 "Expected module in same context");
138 // Delete the old merged module.
139 destroyMergedModule();
140 AsmUndefinedRefs.clear();
143 IRLinker.setModule(&Mod->getModule());
145 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
146 for (int I = 0, E = Undefs.size(); I != E; ++I)
147 AsmUndefinedRefs[Undefs[I]] = 1;
150 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
154 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
156 case LTO_DEBUG_MODEL_NONE:
157 EmitDwarfDebugInfo = false;
160 case LTO_DEBUG_MODEL_DWARF:
161 EmitDwarfDebugInfo = true;
164 llvm_unreachable("Unknown debug format!");
167 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
169 case LTO_CODEGEN_PIC_MODEL_STATIC:
170 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
171 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
172 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
176 llvm_unreachable("Unknown PIC model!");
179 bool LTOCodeGenerator::writeMergedModules(const char *path,
180 std::string &errMsg) {
181 if (!determineTarget(errMsg))
184 // mark which symbols can not be internalized
185 applyScopeRestrictions();
187 // create output file
189 tool_output_file Out(path, EC, sys::fs::F_None);
191 errMsg = "could not open bitcode file for writing: ";
196 // write bitcode to it
197 WriteBitcodeToFile(IRLinker.getModule(), Out.os(), ShouldEmbedUselists);
200 if (Out.os().has_error()) {
201 errMsg = "could not write bitcode file: ";
203 Out.os().clear_error();
211 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
212 std::string &errMsg) {
213 // make unique temp .o file to put generated object file
214 SmallString<128> Filename;
217 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
219 errMsg = EC.message();
223 // generate object file
224 tool_output_file objFile(Filename.c_str(), FD);
226 bool genResult = compileOptimized(objFile.os(), errMsg);
227 objFile.os().close();
228 if (objFile.os().has_error()) {
229 objFile.os().clear_error();
230 sys::fs::remove(Twine(Filename));
236 sys::fs::remove(Twine(Filename));
240 NativeObjectPath = Filename.c_str();
241 *name = NativeObjectPath.c_str();
245 std::unique_ptr<MemoryBuffer>
246 LTOCodeGenerator::compileOptimized(std::string &errMsg) {
248 if (!compileOptimizedToFile(&name, errMsg))
251 // read .o file into memory buffer
252 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
253 MemoryBuffer::getFile(name, -1, false);
254 if (std::error_code EC = BufferOrErr.getError()) {
255 errMsg = EC.message();
256 sys::fs::remove(NativeObjectPath);
261 sys::fs::remove(NativeObjectPath);
263 return std::move(*BufferOrErr);
267 bool LTOCodeGenerator::compile_to_file(const char **name,
269 bool disableGVNLoadPRE,
270 bool disableVectorization,
271 std::string &errMsg) {
272 if (!optimize(disableInline, disableGVNLoadPRE,
273 disableVectorization, errMsg))
276 return compileOptimizedToFile(name, errMsg);
279 std::unique_ptr<MemoryBuffer>
280 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
281 bool disableVectorization, std::string &errMsg) {
282 if (!optimize(disableInline, disableGVNLoadPRE,
283 disableVectorization, errMsg))
286 return compileOptimized(errMsg);
289 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
293 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
294 if (TripleStr.empty())
295 TripleStr = sys::getDefaultTargetTriple();
296 llvm::Triple Triple(TripleStr);
298 // create target machine from info for merged modules
299 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
303 // The relocation model is actually a static member of TargetMachine and
304 // needs to be set before the TargetMachine is instantiated.
305 Reloc::Model RelocModel = Reloc::Default;
307 case LTO_CODEGEN_PIC_MODEL_STATIC:
308 RelocModel = Reloc::Static;
310 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
311 RelocModel = Reloc::PIC_;
313 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
314 RelocModel = Reloc::DynamicNoPIC;
316 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
317 // RelocModel is already the default, so leave it that way.
321 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
322 // the default set of features.
323 SubtargetFeatures Features(MAttr);
324 Features.getDefaultSubtargetFeatures(Triple);
325 std::string FeatureStr = Features.getString();
326 // Set a default CPU for Darwin triples.
327 if (MCpu.empty() && Triple.isOSDarwin()) {
328 if (Triple.getArch() == llvm::Triple::x86_64)
330 else if (Triple.getArch() == llvm::Triple::x86)
332 else if (Triple.getArch() == llvm::Triple::aarch64)
336 CodeGenOpt::Level CGOptLevel;
339 CGOptLevel = CodeGenOpt::None;
342 CGOptLevel = CodeGenOpt::Less;
345 CGOptLevel = CodeGenOpt::Default;
348 CGOptLevel = CodeGenOpt::Aggressive;
352 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
354 CodeModel::Default, CGOptLevel));
358 void LTOCodeGenerator::
359 applyRestriction(GlobalValue &GV,
360 ArrayRef<StringRef> Libcalls,
361 std::vector<const char*> &MustPreserveList,
362 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
364 // There are no restrictions to apply to declarations.
365 if (GV.isDeclaration())
368 // There is nothing more restrictive than private linkage.
369 if (GV.hasPrivateLinkage())
372 SmallString<64> Buffer;
373 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
375 if (MustPreserveSymbols.count(Buffer))
376 MustPreserveList.push_back(GV.getName().data());
377 if (AsmUndefinedRefs.count(Buffer))
380 // Conservatively append user-supplied runtime library functions to
381 // llvm.compiler.used. These could be internalized and deleted by
382 // optimizations like -globalopt, causing problems when later optimizations
383 // add new library calls (e.g., llvm.memset => memset and printf => puts).
384 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
385 if (isa<Function>(GV) &&
386 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
390 static void findUsedValues(GlobalVariable *LLVMUsed,
391 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
392 if (!LLVMUsed) return;
394 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
395 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
396 if (GlobalValue *GV =
397 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
398 UsedValues.insert(GV);
401 // Collect names of runtime library functions. User-defined functions with the
402 // same names are added to llvm.compiler.used to prevent them from being
403 // deleted by optimizations.
404 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
405 const TargetLibraryInfo& TLI,
407 const TargetMachine &TM) {
408 // TargetLibraryInfo has info on C runtime library calls on the current
410 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
412 LibFunc::Func F = static_cast<LibFunc::Func>(I);
414 Libcalls.push_back(TLI.getName(F));
417 SmallPtrSet<const TargetLowering *, 1> TLSet;
419 for (const Function &F : Mod) {
420 const TargetLowering *Lowering =
421 TM.getSubtargetImpl(F)->getTargetLowering();
423 if (Lowering && TLSet.insert(Lowering).second)
424 // TargetLowering has info on library calls that CodeGen expects to be
425 // available, both from the C runtime and compiler-rt.
426 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
428 if (const char *Name =
429 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
430 Libcalls.push_back(Name);
433 array_pod_sort(Libcalls.begin(), Libcalls.end());
434 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
438 void LTOCodeGenerator::applyScopeRestrictions() {
439 if (ScopeRestrictionsDone || !ShouldInternalize)
441 Module *mergedModule = IRLinker.getModule();
443 // Start off with a verification pass.
444 legacy::PassManager passes;
445 passes.add(createVerifierPass());
447 // mark which symbols can not be internalized
449 std::vector<const char*> MustPreserveList;
450 SmallPtrSet<GlobalValue*, 8> AsmUsed;
451 std::vector<StringRef> Libcalls;
452 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
453 TargetLibraryInfo TLI(TLII);
455 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
457 for (Module::iterator f = mergedModule->begin(),
458 e = mergedModule->end(); f != e; ++f)
459 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
460 for (Module::global_iterator v = mergedModule->global_begin(),
461 e = mergedModule->global_end(); v != e; ++v)
462 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
463 for (Module::alias_iterator a = mergedModule->alias_begin(),
464 e = mergedModule->alias_end(); a != e; ++a)
465 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
467 GlobalVariable *LLVMCompilerUsed =
468 mergedModule->getGlobalVariable("llvm.compiler.used");
469 findUsedValues(LLVMCompilerUsed, AsmUsed);
470 if (LLVMCompilerUsed)
471 LLVMCompilerUsed->eraseFromParent();
473 if (!AsmUsed.empty()) {
474 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
475 std::vector<Constant*> asmUsed2;
476 for (auto *GV : AsmUsed) {
477 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
478 asmUsed2.push_back(c);
481 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
483 new llvm::GlobalVariable(*mergedModule, ATy, false,
484 llvm::GlobalValue::AppendingLinkage,
485 llvm::ConstantArray::get(ATy, asmUsed2),
486 "llvm.compiler.used");
488 LLVMCompilerUsed->setSection("llvm.metadata");
491 passes.add(createInternalizePass(MustPreserveList));
493 // apply scope restrictions
494 passes.run(*mergedModule);
496 ScopeRestrictionsDone = true;
499 /// Optimize merged modules using various IPO passes
500 bool LTOCodeGenerator::optimize(bool DisableInline,
501 bool DisableGVNLoadPRE,
502 bool DisableVectorization,
503 std::string &errMsg) {
504 if (!this->determineTarget(errMsg))
507 Module *mergedModule = IRLinker.getModule();
509 // Mark which symbols can not be internalized
510 this->applyScopeRestrictions();
512 // Instantiate the pass manager to organize the passes.
513 legacy::PassManager passes;
515 // Add an appropriate DataLayout instance for this module...
516 mergedModule->setDataLayout(TargetMach->createDataLayout());
519 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
521 Triple TargetTriple(TargetMach->getTargetTriple());
522 PassManagerBuilder PMB;
523 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
524 PMB.LoopVectorize = !DisableVectorization;
525 PMB.SLPVectorize = !DisableVectorization;
527 PMB.Inliner = createFunctionInliningPass();
528 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
529 PMB.OptLevel = OptLevel;
530 PMB.VerifyInput = true;
531 PMB.VerifyOutput = true;
533 PMB.populateLTOPassManager(passes);
535 // Run our queue of passes all at once now, efficiently.
536 passes.run(*mergedModule);
541 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
542 std::string &errMsg) {
543 if (!this->determineTarget(errMsg))
546 Module *mergedModule = IRLinker.getModule();
548 legacy::PassManager codeGenPasses;
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 (TargetMach->addPassesToEmitFile(codeGenPasses, out,
555 TargetMachine::CGFT_ObjectFile)) {
556 errMsg = "target file type not supported";
560 // Run the code generator, and write assembly file
561 codeGenPasses.run(*mergedModule);
566 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
568 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
569 for (std::pair<StringRef, StringRef> o = getToken(options);
570 !o.first.empty(); o = getToken(o.second))
571 CodegenOptions.push_back(o.first);
574 void LTOCodeGenerator::parseCodeGenDebugOptions() {
575 // if options were requested, set them
576 if (!CodegenOptions.empty()) {
577 // ParseCommandLineOptions() expects argv[0] to be program name.
578 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
579 for (std::string &Arg : CodegenOptions)
580 CodegenArgv.push_back(Arg.c_str());
581 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
585 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
587 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
590 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
591 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
592 lto_codegen_diagnostic_severity_t Severity;
593 switch (DI.getSeverity()) {
595 Severity = LTO_DS_ERROR;
598 Severity = LTO_DS_WARNING;
601 Severity = LTO_DS_REMARK;
604 Severity = LTO_DS_NOTE;
607 // Create the string that will be reported to the external diagnostic handler.
608 std::string MsgStorage;
609 raw_string_ostream Stream(MsgStorage);
610 DiagnosticPrinterRawOStream DP(Stream);
614 // If this method has been called it means someone has set up an external
615 // diagnostic handler. Assert on that.
616 assert(DiagHandler && "Invalid diagnostic handler");
617 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
621 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
623 this->DiagHandler = DiagHandler;
624 this->DiagContext = Ctxt;
626 return Context.setDiagnosticHandler(nullptr, nullptr);
627 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
628 // diagnostic to the external DiagHandler.
629 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
630 /* RespectFilters */ true);