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 bool LTOCodeGenerator::writeMergedModules(const char *path,
168 std::string &errMsg) {
169 if (!determineTarget(errMsg))
172 // mark which symbols can not be internalized
173 applyScopeRestrictions();
175 // create output file
177 tool_output_file Out(path, EC, sys::fs::F_None);
179 errMsg = "could not open bitcode file for writing: ";
184 // write bitcode to it
185 WriteBitcodeToFile(IRLinker.getModule(), Out.os(), ShouldEmbedUselists);
188 if (Out.os().has_error()) {
189 errMsg = "could not write bitcode file: ";
191 Out.os().clear_error();
199 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
200 std::string &errMsg) {
201 // make unique temp .o file to put generated object file
202 SmallString<128> Filename;
205 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
207 errMsg = EC.message();
211 // generate object file
212 tool_output_file objFile(Filename.c_str(), FD);
214 bool genResult = compileOptimized(objFile.os(), errMsg);
215 objFile.os().close();
216 if (objFile.os().has_error()) {
217 objFile.os().clear_error();
218 sys::fs::remove(Twine(Filename));
224 sys::fs::remove(Twine(Filename));
228 NativeObjectPath = Filename.c_str();
229 *name = NativeObjectPath.c_str();
233 std::unique_ptr<MemoryBuffer>
234 LTOCodeGenerator::compileOptimized(std::string &errMsg) {
236 if (!compileOptimizedToFile(&name, errMsg))
239 // read .o file into memory buffer
240 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
241 MemoryBuffer::getFile(name, -1, false);
242 if (std::error_code EC = BufferOrErr.getError()) {
243 errMsg = EC.message();
244 sys::fs::remove(NativeObjectPath);
249 sys::fs::remove(NativeObjectPath);
251 return std::move(*BufferOrErr);
255 bool LTOCodeGenerator::compile_to_file(const char **name,
257 bool disableGVNLoadPRE,
258 bool disableVectorization,
259 std::string &errMsg) {
260 if (!optimize(disableInline, disableGVNLoadPRE,
261 disableVectorization, errMsg))
264 return compileOptimizedToFile(name, errMsg);
267 std::unique_ptr<MemoryBuffer>
268 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
269 bool disableVectorization, std::string &errMsg) {
270 if (!optimize(disableInline, disableGVNLoadPRE,
271 disableVectorization, errMsg))
274 return compileOptimized(errMsg);
277 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
281 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
282 if (TripleStr.empty())
283 TripleStr = sys::getDefaultTargetTriple();
284 llvm::Triple Triple(TripleStr);
286 // create target machine from info for merged modules
287 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
291 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
292 // the default set of features.
293 SubtargetFeatures Features(MAttr);
294 Features.getDefaultSubtargetFeatures(Triple);
295 std::string FeatureStr = Features.getString();
296 // Set a default CPU for Darwin triples.
297 if (MCpu.empty() && Triple.isOSDarwin()) {
298 if (Triple.getArch() == llvm::Triple::x86_64)
300 else if (Triple.getArch() == llvm::Triple::x86)
302 else if (Triple.getArch() == llvm::Triple::aarch64)
306 CodeGenOpt::Level CGOptLevel;
309 CGOptLevel = CodeGenOpt::None;
312 CGOptLevel = CodeGenOpt::Less;
315 CGOptLevel = CodeGenOpt::Default;
318 CGOptLevel = CodeGenOpt::Aggressive;
322 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
324 CodeModel::Default, CGOptLevel));
328 void LTOCodeGenerator::
329 applyRestriction(GlobalValue &GV,
330 ArrayRef<StringRef> Libcalls,
331 std::vector<const char*> &MustPreserveList,
332 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
334 // There are no restrictions to apply to declarations.
335 if (GV.isDeclaration())
338 // There is nothing more restrictive than private linkage.
339 if (GV.hasPrivateLinkage())
342 SmallString<64> Buffer;
343 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
345 if (MustPreserveSymbols.count(Buffer))
346 MustPreserveList.push_back(GV.getName().data());
347 if (AsmUndefinedRefs.count(Buffer))
350 // Conservatively append user-supplied runtime library functions to
351 // llvm.compiler.used. These could be internalized and deleted by
352 // optimizations like -globalopt, causing problems when later optimizations
353 // add new library calls (e.g., llvm.memset => memset and printf => puts).
354 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
355 if (isa<Function>(GV) &&
356 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
360 static void findUsedValues(GlobalVariable *LLVMUsed,
361 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
362 if (!LLVMUsed) return;
364 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
365 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
366 if (GlobalValue *GV =
367 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
368 UsedValues.insert(GV);
371 // Collect names of runtime library functions. User-defined functions with the
372 // same names are added to llvm.compiler.used to prevent them from being
373 // deleted by optimizations.
374 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
375 const TargetLibraryInfo& TLI,
377 const TargetMachine &TM) {
378 // TargetLibraryInfo has info on C runtime library calls on the current
380 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
382 LibFunc::Func F = static_cast<LibFunc::Func>(I);
384 Libcalls.push_back(TLI.getName(F));
387 SmallPtrSet<const TargetLowering *, 1> TLSet;
389 for (const Function &F : Mod) {
390 const TargetLowering *Lowering =
391 TM.getSubtargetImpl(F)->getTargetLowering();
393 if (Lowering && TLSet.insert(Lowering).second)
394 // TargetLowering has info on library calls that CodeGen expects to be
395 // available, both from the C runtime and compiler-rt.
396 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
398 if (const char *Name =
399 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
400 Libcalls.push_back(Name);
403 array_pod_sort(Libcalls.begin(), Libcalls.end());
404 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
408 void LTOCodeGenerator::applyScopeRestrictions() {
409 if (ScopeRestrictionsDone || !ShouldInternalize)
411 Module *mergedModule = IRLinker.getModule();
413 // Start off with a verification pass.
414 legacy::PassManager passes;
415 passes.add(createVerifierPass());
417 // mark which symbols can not be internalized
419 std::vector<const char*> MustPreserveList;
420 SmallPtrSet<GlobalValue*, 8> AsmUsed;
421 std::vector<StringRef> Libcalls;
422 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
423 TargetLibraryInfo TLI(TLII);
425 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
427 for (Module::iterator f = mergedModule->begin(),
428 e = mergedModule->end(); f != e; ++f)
429 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
430 for (Module::global_iterator v = mergedModule->global_begin(),
431 e = mergedModule->global_end(); v != e; ++v)
432 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
433 for (Module::alias_iterator a = mergedModule->alias_begin(),
434 e = mergedModule->alias_end(); a != e; ++a)
435 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
437 GlobalVariable *LLVMCompilerUsed =
438 mergedModule->getGlobalVariable("llvm.compiler.used");
439 findUsedValues(LLVMCompilerUsed, AsmUsed);
440 if (LLVMCompilerUsed)
441 LLVMCompilerUsed->eraseFromParent();
443 if (!AsmUsed.empty()) {
444 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
445 std::vector<Constant*> asmUsed2;
446 for (auto *GV : AsmUsed) {
447 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
448 asmUsed2.push_back(c);
451 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
453 new llvm::GlobalVariable(*mergedModule, ATy, false,
454 llvm::GlobalValue::AppendingLinkage,
455 llvm::ConstantArray::get(ATy, asmUsed2),
456 "llvm.compiler.used");
458 LLVMCompilerUsed->setSection("llvm.metadata");
461 passes.add(createInternalizePass(MustPreserveList));
463 // apply scope restrictions
464 passes.run(*mergedModule);
466 ScopeRestrictionsDone = true;
469 /// Optimize merged modules using various IPO passes
470 bool LTOCodeGenerator::optimize(bool DisableInline,
471 bool DisableGVNLoadPRE,
472 bool DisableVectorization,
473 std::string &errMsg) {
474 if (!this->determineTarget(errMsg))
477 Module *mergedModule = IRLinker.getModule();
479 // Mark which symbols can not be internalized
480 this->applyScopeRestrictions();
482 // Instantiate the pass manager to organize the passes.
483 legacy::PassManager passes;
485 // Add an appropriate DataLayout instance for this module...
486 mergedModule->setDataLayout(TargetMach->createDataLayout());
489 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
491 Triple TargetTriple(TargetMach->getTargetTriple());
492 PassManagerBuilder PMB;
493 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
494 PMB.LoopVectorize = !DisableVectorization;
495 PMB.SLPVectorize = !DisableVectorization;
497 PMB.Inliner = createFunctionInliningPass();
498 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
499 PMB.OptLevel = OptLevel;
500 PMB.VerifyInput = true;
501 PMB.VerifyOutput = true;
503 PMB.populateLTOPassManager(passes);
505 // Run our queue of passes all at once now, efficiently.
506 passes.run(*mergedModule);
511 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
512 std::string &errMsg) {
513 if (!this->determineTarget(errMsg))
516 Module *mergedModule = IRLinker.getModule();
518 legacy::PassManager codeGenPasses;
520 // If the bitcode files contain ARC code and were compiled with optimization,
521 // the ObjCARCContractPass must be run, so do it unconditionally here.
522 codeGenPasses.add(createObjCARCContractPass());
524 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
525 TargetMachine::CGFT_ObjectFile)) {
526 errMsg = "target file type not supported";
530 // Run the code generator, and write assembly file
531 codeGenPasses.run(*mergedModule);
536 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
538 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
539 for (std::pair<StringRef, StringRef> o = getToken(options);
540 !o.first.empty(); o = getToken(o.second))
541 CodegenOptions.push_back(o.first);
544 void LTOCodeGenerator::parseCodeGenDebugOptions() {
545 // if options were requested, set them
546 if (!CodegenOptions.empty()) {
547 // ParseCommandLineOptions() expects argv[0] to be program name.
548 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
549 for (std::string &Arg : CodegenOptions)
550 CodegenArgv.push_back(Arg.c_str());
551 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
555 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
557 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
560 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
561 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
562 lto_codegen_diagnostic_severity_t Severity;
563 switch (DI.getSeverity()) {
565 Severity = LTO_DS_ERROR;
568 Severity = LTO_DS_WARNING;
571 Severity = LTO_DS_REMARK;
574 Severity = LTO_DS_NOTE;
577 // Create the string that will be reported to the external diagnostic handler.
578 std::string MsgStorage;
579 raw_string_ostream Stream(MsgStorage);
580 DiagnosticPrinterRawOStream DP(Stream);
584 // If this method has been called it means someone has set up an external
585 // diagnostic handler. Assert on that.
586 assert(DiagHandler && "Invalid diagnostic handler");
587 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
591 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
593 this->DiagHandler = DiagHandler;
594 this->DiagContext = Ctxt;
596 return Context.setDiagnosticHandler(nullptr, nullptr);
597 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
598 // diagnostic to the external DiagHandler.
599 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
600 /* RespectFilters */ true);