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/ParallelCG.h"
22 #include "llvm/CodeGen/RuntimeLibcalls.h"
23 #include "llvm/Config/config.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/LTO/LTOModule.h"
36 #include "llvm/Linker/Linker.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/IPO.h"
54 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 #include "llvm/Transforms/ObjCARC.h"
56 #include <system_error>
59 const char* LTOCodeGenerator::getVersionString() {
60 #ifdef LLVM_VERSION_INFO
61 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
63 return PACKAGE_NAME " version " PACKAGE_VERSION;
67 LTOCodeGenerator::LTOCodeGenerator()
68 : Context(getGlobalContext()),
69 MergedModule(new Module("ld-temp.o", Context)),
70 IRLinker(MergedModule.get()) {
71 initializeLTOPasses();
74 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
75 : OwnedContext(std::move(Context)), Context(*OwnedContext),
76 MergedModule(new Module("ld-temp.o", *OwnedContext)),
77 IRLinker(MergedModule.get()) {
78 initializeLTOPasses();
81 LTOCodeGenerator::~LTOCodeGenerator() {}
83 // Initialize LTO passes. Please keep this function in sync with
84 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
85 // passes are initialized.
86 void LTOCodeGenerator::initializeLTOPasses() {
87 PassRegistry &R = *PassRegistry::getPassRegistry();
89 initializeInternalizePassPass(R);
90 initializeIPSCCPPass(R);
91 initializeGlobalOptPass(R);
92 initializeConstantMergePass(R);
94 initializeInstructionCombiningPassPass(R);
95 initializeSimpleInlinerPass(R);
96 initializePruneEHPass(R);
97 initializeGlobalDCEPass(R);
98 initializeArgPromotionPass(R);
99 initializeJumpThreadingPass(R);
100 initializeSROALegacyPassPass(R);
101 initializeSROA_DTPass(R);
102 initializeSROA_SSAUpPass(R);
103 initializeFunctionAttrsPass(R);
104 initializeGlobalsAAWrapperPassPass(R);
105 initializeLICMPass(R);
106 initializeMergedLoadStoreMotionPass(R);
107 initializeGVNPass(R);
108 initializeMemCpyOptPass(R);
109 initializeDCEPass(R);
110 initializeCFGSimplifyPassPass(R);
113 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
114 assert(&Mod->getModule().getContext() == &Context &&
115 "Expected module in same context");
117 bool ret = IRLinker.linkInModule(&Mod->getModule());
119 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
120 for (int i = 0, e = undefs.size(); i != e; ++i)
121 AsmUndefinedRefs[undefs[i]] = 1;
126 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
127 assert(&Mod->getModule().getContext() == &Context &&
128 "Expected module in same context");
130 AsmUndefinedRefs.clear();
132 MergedModule = Mod->takeModule();
133 IRLinker.setModule(MergedModule.get());
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;
140 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
141 this->Options = Options;
144 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
146 case LTO_DEBUG_MODEL_NONE:
147 EmitDwarfDebugInfo = false;
150 case LTO_DEBUG_MODEL_DWARF:
151 EmitDwarfDebugInfo = true;
154 llvm_unreachable("Unknown debug format!");
157 void LTOCodeGenerator::setOptLevel(unsigned Level) {
161 CGOptLevel = CodeGenOpt::None;
164 CGOptLevel = CodeGenOpt::Less;
167 CGOptLevel = CodeGenOpt::Default;
170 CGOptLevel = CodeGenOpt::Aggressive;
175 bool LTOCodeGenerator::writeMergedModules(const char *Path,
176 std::string &ErrMsg) {
177 if (!determineTarget(ErrMsg))
180 // mark which symbols can not be internalized
181 applyScopeRestrictions();
183 // create output file
185 tool_output_file Out(Path, EC, sys::fs::F_None);
187 ErrMsg = "could not open bitcode file for writing: ";
192 // write bitcode to it
193 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
196 if (Out.os().has_error()) {
197 ErrMsg = "could not write bitcode file: ";
199 Out.os().clear_error();
207 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name,
208 std::string &ErrMsg) {
209 // make unique temp .o file to put generated object file
210 SmallString<128> Filename;
213 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
215 ErrMsg = EC.message();
219 // generate object file
220 tool_output_file objFile(Filename.c_str(), FD);
222 bool genResult = compileOptimized(&objFile.os(), ErrMsg);
223 objFile.os().close();
224 if (objFile.os().has_error()) {
225 objFile.os().clear_error();
226 sys::fs::remove(Twine(Filename));
232 sys::fs::remove(Twine(Filename));
236 NativeObjectPath = Filename.c_str();
237 *Name = NativeObjectPath.c_str();
241 std::unique_ptr<MemoryBuffer>
242 LTOCodeGenerator::compileOptimized(std::string &ErrMsg) {
244 if (!compileOptimizedToFile(&name, ErrMsg))
247 // read .o file into memory buffer
248 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
249 MemoryBuffer::getFile(name, -1, false);
250 if (std::error_code EC = BufferOrErr.getError()) {
251 ErrMsg = EC.message();
252 sys::fs::remove(NativeObjectPath);
257 sys::fs::remove(NativeObjectPath);
259 return std::move(*BufferOrErr);
262 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
264 bool DisableGVNLoadPRE,
265 bool DisableVectorization,
266 std::string &ErrMsg) {
267 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
268 DisableVectorization, ErrMsg))
271 return compileOptimizedToFile(Name, ErrMsg);
274 std::unique_ptr<MemoryBuffer>
275 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
276 bool DisableGVNLoadPRE, bool DisableVectorization,
277 std::string &ErrMsg) {
278 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
279 DisableVectorization, ErrMsg))
282 return compileOptimized(ErrMsg);
285 bool LTOCodeGenerator::determineTarget(std::string &ErrMsg) {
289 std::string TripleStr = MergedModule->getTargetTriple();
290 if (TripleStr.empty()) {
291 TripleStr = sys::getDefaultTargetTriple();
292 MergedModule->setTargetTriple(TripleStr);
294 llvm::Triple Triple(TripleStr);
296 // create target machine from info for merged modules
297 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
301 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
302 // the default set of features.
303 SubtargetFeatures Features(MAttr);
304 Features.getDefaultSubtargetFeatures(Triple);
305 FeatureStr = Features.getString();
306 // Set a default CPU for Darwin triples.
307 if (MCpu.empty() && Triple.isOSDarwin()) {
308 if (Triple.getArch() == llvm::Triple::x86_64)
310 else if (Triple.getArch() == llvm::Triple::x86)
312 else if (Triple.getArch() == llvm::Triple::aarch64)
316 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
318 CodeModel::Default, CGOptLevel));
322 void LTOCodeGenerator::
323 applyRestriction(GlobalValue &GV,
324 ArrayRef<StringRef> Libcalls,
325 std::vector<const char*> &MustPreserveList,
326 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
328 // There are no restrictions to apply to declarations.
329 if (GV.isDeclaration())
332 // There is nothing more restrictive than private linkage.
333 if (GV.hasPrivateLinkage())
336 SmallString<64> Buffer;
337 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
339 if (MustPreserveSymbols.count(Buffer))
340 MustPreserveList.push_back(GV.getName().data());
341 if (AsmUndefinedRefs.count(Buffer))
344 // Conservatively append user-supplied runtime library functions to
345 // llvm.compiler.used. These could be internalized and deleted by
346 // optimizations like -globalopt, causing problems when later optimizations
347 // add new library calls (e.g., llvm.memset => memset and printf => puts).
348 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
349 if (isa<Function>(GV) &&
350 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
354 static void findUsedValues(GlobalVariable *LLVMUsed,
355 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
356 if (!LLVMUsed) return;
358 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
359 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
360 if (GlobalValue *GV =
361 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
362 UsedValues.insert(GV);
365 // Collect names of runtime library functions. User-defined functions with the
366 // same names are added to llvm.compiler.used to prevent them from being
367 // deleted by optimizations.
368 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
369 const TargetLibraryInfo& TLI,
371 const TargetMachine &TM) {
372 // TargetLibraryInfo has info on C runtime library calls on the current
374 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
376 LibFunc::Func F = static_cast<LibFunc::Func>(I);
378 Libcalls.push_back(TLI.getName(F));
381 SmallPtrSet<const TargetLowering *, 1> TLSet;
383 for (const Function &F : Mod) {
384 const TargetLowering *Lowering =
385 TM.getSubtargetImpl(F)->getTargetLowering();
387 if (Lowering && TLSet.insert(Lowering).second)
388 // TargetLowering has info on library calls that CodeGen expects to be
389 // available, both from the C runtime and compiler-rt.
390 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
392 if (const char *Name =
393 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
394 Libcalls.push_back(Name);
397 array_pod_sort(Libcalls.begin(), Libcalls.end());
398 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
402 void LTOCodeGenerator::applyScopeRestrictions() {
403 if (ScopeRestrictionsDone || !ShouldInternalize)
406 // Start off with a verification pass.
407 legacy::PassManager passes;
408 passes.add(createVerifierPass());
410 // mark which symbols can not be internalized
412 std::vector<const char*> MustPreserveList;
413 SmallPtrSet<GlobalValue*, 8> AsmUsed;
414 std::vector<StringRef> Libcalls;
415 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
416 TargetLibraryInfo TLI(TLII);
418 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
420 for (Function &f : *MergedModule)
421 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
422 for (GlobalVariable &v : MergedModule->globals())
423 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
424 for (GlobalAlias &a : MergedModule->aliases())
425 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
427 GlobalVariable *LLVMCompilerUsed =
428 MergedModule->getGlobalVariable("llvm.compiler.used");
429 findUsedValues(LLVMCompilerUsed, AsmUsed);
430 if (LLVMCompilerUsed)
431 LLVMCompilerUsed->eraseFromParent();
433 if (!AsmUsed.empty()) {
434 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
435 std::vector<Constant*> asmUsed2;
436 for (auto *GV : AsmUsed) {
437 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
438 asmUsed2.push_back(c);
441 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
443 new llvm::GlobalVariable(*MergedModule, ATy, false,
444 llvm::GlobalValue::AppendingLinkage,
445 llvm::ConstantArray::get(ATy, asmUsed2),
446 "llvm.compiler.used");
448 LLVMCompilerUsed->setSection("llvm.metadata");
451 passes.add(createInternalizePass(MustPreserveList));
453 // apply scope restrictions
454 passes.run(*MergedModule);
456 ScopeRestrictionsDone = true;
459 /// Optimize merged modules using various IPO passes
460 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
461 bool DisableGVNLoadPRE,
462 bool DisableVectorization,
463 std::string &ErrMsg) {
464 if (!this->determineTarget(ErrMsg))
467 // Mark which symbols can not be internalized
468 this->applyScopeRestrictions();
470 // Instantiate the pass manager to organize the passes.
471 legacy::PassManager passes;
473 // Add an appropriate DataLayout instance for this module...
474 MergedModule->setDataLayout(TargetMach->createDataLayout());
477 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
479 Triple TargetTriple(TargetMach->getTargetTriple());
480 PassManagerBuilder PMB;
481 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
482 PMB.LoopVectorize = !DisableVectorization;
483 PMB.SLPVectorize = !DisableVectorization;
485 PMB.Inliner = createFunctionInliningPass();
486 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
487 PMB.OptLevel = OptLevel;
488 PMB.VerifyInput = !DisableVerify;
489 PMB.VerifyOutput = !DisableVerify;
491 PMB.populateLTOPassManager(passes);
493 // Run our queue of passes all at once now, efficiently.
494 passes.run(*MergedModule);
499 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out,
500 std::string &ErrMsg) {
501 if (!this->determineTarget(ErrMsg))
504 legacy::PassManager preCodeGenPasses;
506 // If the bitcode files contain ARC code and were compiled with optimization,
507 // the ObjCARCContractPass must be run, so do it unconditionally here.
508 preCodeGenPasses.add(createObjCARCContractPass());
509 preCodeGenPasses.run(*MergedModule);
511 // Do code generation. We need to preserve the module in case the client calls
512 // writeMergedModules() after compilation, but we only need to allow this at
513 // parallelism level 1. This is achieved by having splitCodeGen return the
514 // original module at parallelism level 1 which we then assign back to
517 splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
518 RelocModel, CodeModel::Default, CGOptLevel);
523 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
525 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
526 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
527 o = getToken(o.second))
528 CodegenOptions.push_back(o.first);
531 void LTOCodeGenerator::parseCodeGenDebugOptions() {
532 // if options were requested, set them
533 if (!CodegenOptions.empty()) {
534 // ParseCommandLineOptions() expects argv[0] to be program name.
535 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
536 for (std::string &Arg : CodegenOptions)
537 CodegenArgv.push_back(Arg.c_str());
538 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
542 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
544 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
547 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
548 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
549 lto_codegen_diagnostic_severity_t Severity;
550 switch (DI.getSeverity()) {
552 Severity = LTO_DS_ERROR;
555 Severity = LTO_DS_WARNING;
558 Severity = LTO_DS_REMARK;
561 Severity = LTO_DS_NOTE;
564 // Create the string that will be reported to the external diagnostic handler.
565 std::string MsgStorage;
566 raw_string_ostream Stream(MsgStorage);
567 DiagnosticPrinterRawOStream DP(Stream);
571 // If this method has been called it means someone has set up an external
572 // diagnostic handler. Assert on that.
573 assert(DiagHandler && "Invalid diagnostic handler");
574 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
578 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
580 this->DiagHandler = DiagHandler;
581 this->DiagContext = Ctxt;
583 return Context.setDiagnosticHandler(nullptr, nullptr);
584 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
585 // diagnostic to the external DiagHandler.
586 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
587 /* RespectFilters */ true);