1 //===- LTO.cpp ------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "LTO.h" 10 #include "Config.h" 11 #include "InputFiles.h" 12 13 #include "lld/Common/ErrorHandler.h" 14 #include "lld/Common/Strings.h" 15 #include "lld/Common/TargetOptionsCommandFlags.h" 16 #include "llvm/LTO/LTO.h" 17 #include "llvm/Support/raw_ostream.h" 18 19 using namespace lld; 20 using namespace lld::macho; 21 using namespace llvm; 22 createConfig()23static lto::Config createConfig() { 24 lto::Config c; 25 c.Options = initTargetOptionsFromCodeGenFlags(); 26 return c; 27 } 28 BitcodeCompiler()29BitcodeCompiler::BitcodeCompiler() { 30 auto backend = 31 lto::createInProcessThinBackend(llvm::heavyweight_hardware_concurrency()); 32 ltoObj = std::make_unique<lto::LTO>(createConfig(), backend); 33 } 34 add(BitcodeFile & f)35void BitcodeCompiler::add(BitcodeFile &f) { 36 ArrayRef<lto::InputFile::Symbol> objSyms = f.obj->symbols(); 37 std::vector<lto::SymbolResolution> resols; 38 resols.reserve(objSyms.size()); 39 40 // Provide a resolution to the LTO API for each symbol. 41 for (const lto::InputFile::Symbol &objSym : objSyms) { 42 resols.emplace_back(); 43 lto::SymbolResolution &r = resols.back(); 44 45 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile 46 // reports two symbols for module ASM defined. Without this check, lld 47 // flags an undefined in IR with a definition in ASM as prevailing. 48 // Once IRObjectFile is fixed to report only one symbol this hack can 49 // be removed. 50 r.Prevailing = !objSym.isUndefined(); 51 52 // TODO: set the other resolution configs properly 53 r.VisibleToRegularObj = true; 54 } 55 checkError(ltoObj->add(std::move(f.obj), resols)); 56 } 57 58 // Merge all the bitcode files we have seen, codegen the result 59 // and return the resulting ObjectFile(s). compile()60std::vector<ObjFile *> BitcodeCompiler::compile() { 61 unsigned maxTasks = ltoObj->getMaxTasks(); 62 buf.resize(maxTasks); 63 64 checkError(ltoObj->run([&](size_t task) { 65 return std::make_unique<lto::NativeObjectStream>( 66 std::make_unique<raw_svector_ostream>(buf[task])); 67 })); 68 69 if (config->saveTemps) { 70 if (!buf[0].empty()) 71 saveBuffer(buf[0], config->outputFile + ".lto.o"); 72 for (unsigned i = 1; i != maxTasks; ++i) 73 saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o"); 74 } 75 76 std::vector<ObjFile *> ret; 77 for (unsigned i = 0; i != maxTasks; ++i) 78 if (!buf[i].empty()) 79 ret.push_back(make<ObjFile>(MemoryBufferRef(buf[i], "lto.tmp"))); 80 81 return ret; 82 } 83