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/legacy/LTOCodeGenerator.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeWriter.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassTimingInfo.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/LTO/LTO.h"
40 #include "llvm/LTO/legacy/LTOModule.h"
41 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
42 #include "llvm/Linker/Linker.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/SubtargetFeature.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/ToolOutputFile.h"
54 #include "llvm/Support/YAMLTraits.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetOptions.h"
57 #include "llvm/Transforms/IPO.h"
58 #include "llvm/Transforms/IPO/Internalize.h"
59 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
60 #include "llvm/Transforms/ObjCARC.h"
61 #include "llvm/Transforms/Utils/ModuleUtils.h"
62 #include <system_error>
65 const char* LTOCodeGenerator::getVersionString() {
66 #ifdef LLVM_VERSION_INFO
67 return PACKAGE_NAME
" version " PACKAGE_VERSION
", " LLVM_VERSION_INFO
;
69 return PACKAGE_NAME
" version " PACKAGE_VERSION
;
74 cl::opt
<bool> LTODiscardValueNames(
75 "lto-discard-value-names",
76 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
85 LTORemarksFilename("lto-pass-remarks-output",
86 cl::desc("Output filename for pass remarks"),
87 cl::value_desc("filename"));
89 cl::opt
<bool> LTOPassRemarksWithHotness(
90 "lto-pass-remarks-with-hotness",
91 cl::desc("With PGO, include profile count in optimization remarks"),
95 LTOCodeGenerator::LTOCodeGenerator(LLVMContext
&Context
)
96 : Context(Context
), MergedModule(new Module("ld-temp.o", Context
)),
97 TheLinker(new Linker(*MergedModule
)) {
98 Context
.setDiscardValueNames(LTODiscardValueNames
);
99 Context
.enableDebugTypeODRUniquing();
100 initializeLTOPasses();
103 LTOCodeGenerator::~LTOCodeGenerator() {}
105 // Initialize LTO passes. Please keep this function in sync with
106 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
107 // passes are initialized.
108 void LTOCodeGenerator::initializeLTOPasses() {
109 PassRegistry
&R
= *PassRegistry::getPassRegistry();
111 initializeInternalizeLegacyPassPass(R
);
112 initializeIPSCCPLegacyPassPass(R
);
113 initializeGlobalOptLegacyPassPass(R
);
114 initializeConstantMergeLegacyPassPass(R
);
115 initializeDAHPass(R
);
116 initializeInstructionCombiningPassPass(R
);
117 initializeSimpleInlinerPass(R
);
118 initializePruneEHPass(R
);
119 initializeGlobalDCELegacyPassPass(R
);
120 initializeArgPromotionPass(R
);
121 initializeJumpThreadingPass(R
);
122 initializeSROALegacyPassPass(R
);
123 initializePostOrderFunctionAttrsLegacyPassPass(R
);
124 initializeReversePostOrderFunctionAttrsLegacyPassPass(R
);
125 initializeGlobalsAAWrapperPassPass(R
);
126 initializeLegacyLICMPassPass(R
);
127 initializeMergedLoadStoreMotionLegacyPassPass(R
);
128 initializeGVNLegacyPassPass(R
);
129 initializeMemCpyOptLegacyPassPass(R
);
130 initializeDCELegacyPassPass(R
);
131 initializeCFGSimplifyPassPass(R
);
134 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule
*Mod
) {
135 const std::vector
<StringRef
> &undefs
= Mod
->getAsmUndefinedRefs();
136 for (int i
= 0, e
= undefs
.size(); i
!= e
; ++i
)
137 AsmUndefinedRefs
[undefs
[i
]] = 1;
140 bool LTOCodeGenerator::addModule(LTOModule
*Mod
) {
141 assert(&Mod
->getModule().getContext() == &Context
&&
142 "Expected module in same context");
144 bool ret
= TheLinker
->linkInModule(Mod
->takeModule());
145 setAsmUndefinedRefs(Mod
);
147 // We've just changed the input, so let's make sure we verify it.
148 HasVerifiedInput
= false;
153 void LTOCodeGenerator::setModule(std::unique_ptr
<LTOModule
> Mod
) {
154 assert(&Mod
->getModule().getContext() == &Context
&&
155 "Expected module in same context");
157 AsmUndefinedRefs
.clear();
159 MergedModule
= Mod
->takeModule();
160 TheLinker
= make_unique
<Linker
>(*MergedModule
);
161 setAsmUndefinedRefs(&*Mod
);
163 // We've just changed the input, so let's make sure we verify it.
164 HasVerifiedInput
= false;
167 void LTOCodeGenerator::setTargetOptions(const TargetOptions
&Options
) {
168 this->Options
= Options
;
171 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug
) {
173 case LTO_DEBUG_MODEL_NONE
:
174 EmitDwarfDebugInfo
= false;
177 case LTO_DEBUG_MODEL_DWARF
:
178 EmitDwarfDebugInfo
= true;
181 llvm_unreachable("Unknown debug format!");
184 void LTOCodeGenerator::setOptLevel(unsigned Level
) {
188 CGOptLevel
= CodeGenOpt::None
;
191 CGOptLevel
= CodeGenOpt::Less
;
194 CGOptLevel
= CodeGenOpt::Default
;
197 CGOptLevel
= CodeGenOpt::Aggressive
;
200 llvm_unreachable("Unknown optimization level!");
203 bool LTOCodeGenerator::writeMergedModules(StringRef Path
) {
204 if (!determineTarget())
207 // We always run the verifier once on the merged module.
208 verifyMergedModuleOnce();
210 // mark which symbols can not be internalized
211 applyScopeRestrictions();
213 // create output file
215 ToolOutputFile
Out(Path
, EC
, sys::fs::F_None
);
217 std::string ErrMsg
= "could not open bitcode file for writing: ";
218 ErrMsg
+= Path
.str() + ": " + EC
.message();
223 // write bitcode to it
224 WriteBitcodeToFile(*MergedModule
, Out
.os(), ShouldEmbedUselists
);
227 if (Out
.os().has_error()) {
228 std::string ErrMsg
= "could not write bitcode file: ";
229 ErrMsg
+= Path
.str() + ": " + Out
.os().error().message();
231 Out
.os().clear_error();
239 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name
) {
240 // make unique temp output file to put generated code
241 SmallString
<128> Filename
;
245 (FileType
== TargetMachine::CGFT_AssemblyFile
? "s" : "o");
248 sys::fs::createTemporaryFile("lto-llvm", Extension
, FD
, Filename
);
250 emitError(EC
.message());
254 // generate object file
255 ToolOutputFile
objFile(Filename
, FD
);
257 bool genResult
= compileOptimized(&objFile
.os());
258 objFile
.os().close();
259 if (objFile
.os().has_error()) {
260 emitError((Twine("could not write object file: ") + Filename
+ ": " +
261 objFile
.os().error().message())
263 objFile
.os().clear_error();
264 sys::fs::remove(Twine(Filename
));
270 sys::fs::remove(Twine(Filename
));
274 NativeObjectPath
= Filename
.c_str();
275 *Name
= NativeObjectPath
.c_str();
279 std::unique_ptr
<MemoryBuffer
>
280 LTOCodeGenerator::compileOptimized() {
282 if (!compileOptimizedToFile(&name
))
285 // read .o file into memory buffer
286 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferOrErr
=
287 MemoryBuffer::getFile(name
, -1, false);
288 if (std::error_code EC
= BufferOrErr
.getError()) {
289 emitError(EC
.message());
290 sys::fs::remove(NativeObjectPath
);
295 sys::fs::remove(NativeObjectPath
);
297 return std::move(*BufferOrErr
);
300 bool LTOCodeGenerator::compile_to_file(const char **Name
, bool DisableVerify
,
302 bool DisableGVNLoadPRE
,
303 bool DisableVectorization
) {
304 if (!optimize(DisableVerify
, DisableInline
, DisableGVNLoadPRE
,
305 DisableVectorization
))
308 return compileOptimizedToFile(Name
);
311 std::unique_ptr
<MemoryBuffer
>
312 LTOCodeGenerator::compile(bool DisableVerify
, bool DisableInline
,
313 bool DisableGVNLoadPRE
, bool DisableVectorization
) {
314 if (!optimize(DisableVerify
, DisableInline
, DisableGVNLoadPRE
,
315 DisableVectorization
))
318 return compileOptimized();
321 bool LTOCodeGenerator::determineTarget() {
325 TripleStr
= MergedModule
->getTargetTriple();
326 if (TripleStr
.empty()) {
327 TripleStr
= sys::getDefaultTargetTriple();
328 MergedModule
->setTargetTriple(TripleStr
);
330 llvm::Triple
Triple(TripleStr
);
332 // create target machine from info for merged modules
334 MArch
= TargetRegistry::lookupTarget(TripleStr
, ErrMsg
);
340 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
341 // the default set of features.
342 SubtargetFeatures
Features(MAttr
);
343 Features
.getDefaultSubtargetFeatures(Triple
);
344 FeatureStr
= Features
.getString();
345 // Set a default CPU for Darwin triples.
346 if (MCpu
.empty() && Triple
.isOSDarwin()) {
347 if (Triple
.getArch() == llvm::Triple::x86_64
)
349 else if (Triple
.getArch() == llvm::Triple::x86
)
351 else if (Triple
.getArch() == llvm::Triple::aarch64
)
355 TargetMach
= createTargetMachine();
359 std::unique_ptr
<TargetMachine
> LTOCodeGenerator::createTargetMachine() {
360 return std::unique_ptr
<TargetMachine
>(MArch
->createTargetMachine(
361 TripleStr
, MCpu
, FeatureStr
, Options
, RelocModel
, None
, CGOptLevel
));
364 // If a linkonce global is present in the MustPreserveSymbols, we need to make
365 // sure we honor this. To force the compiler to not drop it, we add it to the
366 // "llvm.compiler.used" global.
367 void LTOCodeGenerator::preserveDiscardableGVs(
369 llvm::function_ref
<bool(const GlobalValue
&)> mustPreserveGV
) {
370 std::vector
<GlobalValue
*> Used
;
371 auto mayPreserveGlobal
= [&](GlobalValue
&GV
) {
372 if (!GV
.isDiscardableIfUnused() || GV
.isDeclaration() ||
375 if (GV
.hasAvailableExternallyLinkage())
377 (Twine("Linker asked to preserve available_externally global: '") +
378 GV
.getName() + "'").str());
379 if (GV
.hasInternalLinkage())
380 return emitWarning((Twine("Linker asked to preserve internal global: '") +
381 GV
.getName() + "'").str());
384 for (auto &GV
: TheModule
)
385 mayPreserveGlobal(GV
);
386 for (auto &GV
: TheModule
.globals())
387 mayPreserveGlobal(GV
);
388 for (auto &GV
: TheModule
.aliases())
389 mayPreserveGlobal(GV
);
394 appendToCompilerUsed(TheModule
, Used
);
397 void LTOCodeGenerator::applyScopeRestrictions() {
398 if (ScopeRestrictionsDone
)
401 // Declare a callback for the internalize pass that will ask for every
402 // candidate GlobalValue if it can be internalized or not.
404 SmallString
<64> MangledName
;
405 auto mustPreserveGV
= [&](const GlobalValue
&GV
) -> bool {
406 // Unnamed globals can't be mangled, but they can't be preserved either.
410 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
411 // with the linker supplied name, which on Darwin includes a leading
414 MangledName
.reserve(GV
.getName().size() + 1);
415 Mang
.getNameWithPrefix(MangledName
, &GV
, /*CannotUsePrivateLabel=*/false);
416 return MustPreserveSymbols
.count(MangledName
);
419 // Preserve linkonce value on linker request
420 preserveDiscardableGVs(*MergedModule
, mustPreserveGV
);
422 if (!ShouldInternalize
)
425 if (ShouldRestoreGlobalsLinkage
) {
426 // Record the linkage type of non-local symbols so they can be restored
428 // to module splitting.
429 auto RecordLinkage
= [&](const GlobalValue
&GV
) {
430 if (!GV
.hasAvailableExternallyLinkage() && !GV
.hasLocalLinkage() &&
432 ExternalSymbols
.insert(std::make_pair(GV
.getName(), GV
.getLinkage()));
434 for (auto &GV
: *MergedModule
)
436 for (auto &GV
: MergedModule
->globals())
438 for (auto &GV
: MergedModule
->aliases())
442 // Update the llvm.compiler_used globals to force preserving libcalls and
443 // symbols referenced from asm
444 updateCompilerUsed(*MergedModule
, *TargetMach
, AsmUndefinedRefs
);
446 internalizeModule(*MergedModule
, mustPreserveGV
);
448 ScopeRestrictionsDone
= true;
451 /// Restore original linkage for symbols that may have been internalized
452 void LTOCodeGenerator::restoreLinkageForExternals() {
453 if (!ShouldInternalize
|| !ShouldRestoreGlobalsLinkage
)
456 assert(ScopeRestrictionsDone
&&
457 "Cannot externalize without internalization!");
459 if (ExternalSymbols
.empty())
462 auto externalize
= [this](GlobalValue
&GV
) {
463 if (!GV
.hasLocalLinkage() || !GV
.hasName())
466 auto I
= ExternalSymbols
.find(GV
.getName());
467 if (I
== ExternalSymbols
.end())
470 GV
.setLinkage(I
->second
);
473 llvm::for_each(MergedModule
->functions(), externalize
);
474 llvm::for_each(MergedModule
->globals(), externalize
);
475 llvm::for_each(MergedModule
->aliases(), externalize
);
478 void LTOCodeGenerator::verifyMergedModuleOnce() {
479 // Only run on the first call.
480 if (HasVerifiedInput
)
482 HasVerifiedInput
= true;
484 bool BrokenDebugInfo
= false;
485 if (verifyModule(*MergedModule
, &dbgs(), &BrokenDebugInfo
))
486 report_fatal_error("Broken module found, compilation aborted!");
487 if (BrokenDebugInfo
) {
488 emitWarning("Invalid debug info found, debug info will be stripped");
489 StripDebugInfo(*MergedModule
);
493 void LTOCodeGenerator::finishOptimizationRemarks() {
494 if (DiagnosticOutputFile
) {
495 DiagnosticOutputFile
->keep();
496 // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
497 DiagnosticOutputFile
->os().flush();
501 /// Optimize merged modules using various IPO passes
502 bool LTOCodeGenerator::optimize(bool DisableVerify
, bool DisableInline
,
503 bool DisableGVNLoadPRE
,
504 bool DisableVectorization
) {
505 if (!this->determineTarget())
508 auto DiagFileOrErr
= lto::setupOptimizationRemarks(
509 Context
, LTORemarksFilename
, LTOPassRemarksWithHotness
);
510 if (!DiagFileOrErr
) {
511 errs() << "Error: " << toString(DiagFileOrErr
.takeError()) << "\n";
512 report_fatal_error("Can't get an output file for the remarks");
514 DiagnosticOutputFile
= std::move(*DiagFileOrErr
);
516 // We always run the verifier once on the merged module, the `DisableVerify`
517 // parameter only applies to subsequent verify.
518 verifyMergedModuleOnce();
520 // Mark which symbols can not be internalized
521 this->applyScopeRestrictions();
523 // Instantiate the pass manager to organize the passes.
524 legacy::PassManager passes
;
526 // Add an appropriate DataLayout instance for this module...
527 MergedModule
->setDataLayout(TargetMach
->createDataLayout());
530 createTargetTransformInfoWrapperPass(TargetMach
->getTargetIRAnalysis()));
532 Triple
TargetTriple(TargetMach
->getTargetTriple());
533 PassManagerBuilder PMB
;
534 PMB
.DisableGVNLoadPRE
= DisableGVNLoadPRE
;
535 PMB
.LoopVectorize
= !DisableVectorization
;
536 PMB
.SLPVectorize
= !DisableVectorization
;
538 PMB
.Inliner
= createFunctionInliningPass();
539 PMB
.LibraryInfo
= new TargetLibraryInfoImpl(TargetTriple
);
541 PMB
.LibraryInfo
->disableAllFunctions();
542 PMB
.OptLevel
= OptLevel
;
543 PMB
.VerifyInput
= !DisableVerify
;
544 PMB
.VerifyOutput
= !DisableVerify
;
546 PMB
.populateLTOPassManager(passes
);
548 // Run our queue of passes all at once now, efficiently.
549 passes
.run(*MergedModule
);
554 bool LTOCodeGenerator::compileOptimized(ArrayRef
<raw_pwrite_stream
*> Out
) {
555 if (!this->determineTarget())
558 // We always run the verifier once on the merged module. If it has already
559 // been called in optimize(), this call will return early.
560 verifyMergedModuleOnce();
562 legacy::PassManager preCodeGenPasses
;
564 // If the bitcode files contain ARC code and were compiled with optimization,
565 // the ObjCARCContractPass must be run, so do it unconditionally here.
566 preCodeGenPasses
.add(createObjCARCContractPass());
567 preCodeGenPasses
.run(*MergedModule
);
569 // Re-externalize globals that may have been internalized to increase scope
571 restoreLinkageForExternals();
573 // Do code generation. We need to preserve the module in case the client calls
574 // writeMergedModules() after compilation, but we only need to allow this at
575 // parallelism level 1. This is achieved by having splitCodeGen return the
576 // original module at parallelism level 1 which we then assign back to
578 MergedModule
= splitCodeGen(std::move(MergedModule
), Out
, {},
579 [&]() { return createTargetMachine(); }, FileType
,
580 ShouldRestoreGlobalsLinkage
);
582 // If statistics were requested, print them out after codegen.
583 if (llvm::AreStatisticsEnabled())
584 llvm::PrintStatistics();
585 reportAndResetTimings();
587 finishOptimizationRemarks();
592 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
594 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options
) {
595 for (std::pair
<StringRef
, StringRef
> o
= getToken(Options
); !o
.first
.empty();
596 o
= getToken(o
.second
))
597 CodegenOptions
.push_back(o
.first
);
600 void LTOCodeGenerator::parseCodeGenDebugOptions() {
601 // if options were requested, set them
602 if (!CodegenOptions
.empty()) {
603 // ParseCommandLineOptions() expects argv[0] to be program name.
604 std::vector
<const char *> CodegenArgv(1, "libLLVMLTO");
605 for (std::string
&Arg
: CodegenOptions
)
606 CodegenArgv
.push_back(Arg
.c_str());
607 cl::ParseCommandLineOptions(CodegenArgv
.size(), CodegenArgv
.data());
612 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo
&DI
) {
613 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
614 lto_codegen_diagnostic_severity_t Severity
;
615 switch (DI
.getSeverity()) {
617 Severity
= LTO_DS_ERROR
;
620 Severity
= LTO_DS_WARNING
;
623 Severity
= LTO_DS_REMARK
;
626 Severity
= LTO_DS_NOTE
;
629 // Create the string that will be reported to the external diagnostic handler.
630 std::string MsgStorage
;
631 raw_string_ostream
Stream(MsgStorage
);
632 DiagnosticPrinterRawOStream
DP(Stream
);
636 // If this method has been called it means someone has set up an external
637 // diagnostic handler. Assert on that.
638 assert(DiagHandler
&& "Invalid diagnostic handler");
639 (*DiagHandler
)(Severity
, MsgStorage
.c_str(), DiagContext
);
643 struct LTODiagnosticHandler
: public DiagnosticHandler
{
644 LTOCodeGenerator
*CodeGenerator
;
645 LTODiagnosticHandler(LTOCodeGenerator
*CodeGenPtr
)
646 : CodeGenerator(CodeGenPtr
) {}
647 bool handleDiagnostics(const DiagnosticInfo
&DI
) override
{
648 CodeGenerator
->DiagnosticHandler(DI
);
655 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler
,
657 this->DiagHandler
= DiagHandler
;
658 this->DiagContext
= Ctxt
;
660 return Context
.setDiagnosticHandler(nullptr);
661 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
662 // diagnostic to the external DiagHandler.
663 Context
.setDiagnosticHandler(llvm::make_unique
<LTODiagnosticHandler
>(this),
668 class LTODiagnosticInfo
: public DiagnosticInfo
{
671 LTODiagnosticInfo(const Twine
&DiagMsg
, DiagnosticSeverity Severity
=DS_Error
)
672 : DiagnosticInfo(DK_Linker
, Severity
), Msg(DiagMsg
) {}
673 void print(DiagnosticPrinter
&DP
) const override
{ DP
<< Msg
; }
677 void LTOCodeGenerator::emitError(const std::string
&ErrMsg
) {
679 (*DiagHandler
)(LTO_DS_ERROR
, ErrMsg
.c_str(), DiagContext
);
681 Context
.diagnose(LTODiagnosticInfo(ErrMsg
));
684 void LTOCodeGenerator::emitWarning(const std::string
&ErrMsg
) {
686 (*DiagHandler
)(LTO_DS_WARNING
, ErrMsg
.c_str(), DiagContext
);
688 Context
.diagnose(LTODiagnosticInfo(ErrMsg
, DS_Warning
));