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 "Driver.h" 12 #include "InputFiles.h" 13 #include "Symbols.h" 14 #include "Target.h" 15 16 #include "lld/Common/Args.h" 17 #include "lld/Common/CommonLinkerContext.h" 18 #include "lld/Common/Strings.h" 19 #include "lld/Common/TargetOptionsCommandFlags.h" 20 #include "llvm/LTO/Config.h" 21 #include "llvm/LTO/LTO.h" 22 #include "llvm/Support/Caching.h" 23 #include "llvm/Support/FileSystem.h" 24 #include "llvm/Support/Path.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Transforms/ObjCARC.h" 27 28 using namespace lld; 29 using namespace lld::macho; 30 using namespace llvm; 31 using namespace llvm::MachO; 32 using namespace llvm::sys; 33 34 static lto::Config createConfig() { 35 lto::Config c; 36 c.Options = initTargetOptionsFromCodeGenFlags(); 37 c.CodeModel = getCodeModelFromCMModel(); 38 c.CPU = getCPUStr(); 39 c.MAttrs = getMAttrs(); 40 c.DiagHandler = diagnosticHandler; 41 c.PreCodeGenPassesHook = [](legacy::PassManager &pm) { 42 pm.add(createObjCARCContractPass()); 43 }; 44 c.TimeTraceEnabled = config->timeTraceEnabled; 45 c.TimeTraceGranularity = config->timeTraceGranularity; 46 c.OptLevel = config->ltoo; 47 c.CGOptLevel = args::getCGOptLevel(config->ltoo); 48 if (config->saveTemps) 49 checkError(c.addSaveTemps(config->outputFile.str() + ".", 50 /*UseInputModulePath=*/true)); 51 return c; 52 } 53 54 BitcodeCompiler::BitcodeCompiler() { 55 lto::ThinBackend backend = lto::createInProcessThinBackend( 56 heavyweight_hardware_concurrency(config->thinLTOJobs)); 57 ltoObj = std::make_unique<lto::LTO>(createConfig(), backend); 58 } 59 60 void BitcodeCompiler::add(BitcodeFile &f) { 61 ArrayRef<lto::InputFile::Symbol> objSyms = f.obj->symbols(); 62 std::vector<lto::SymbolResolution> resols; 63 resols.reserve(objSyms.size()); 64 65 // Provide a resolution to the LTO API for each symbol. 66 bool exportDynamic = 67 config->outputType != MH_EXECUTE || config->exportDynamic; 68 auto symIt = f.symbols.begin(); 69 for (const lto::InputFile::Symbol &objSym : objSyms) { 70 resols.emplace_back(); 71 lto::SymbolResolution &r = resols.back(); 72 Symbol *sym = *symIt++; 73 74 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile 75 // reports two symbols for module ASM defined. Without this check, lld 76 // flags an undefined in IR with a definition in ASM as prevailing. 77 // Once IRObjectFile is fixed to report only one symbol this hack can 78 // be removed. 79 r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f; 80 81 if (const auto *defined = dyn_cast<Defined>(sym)) { 82 r.ExportDynamic = 83 defined->isExternal() && !defined->privateExtern && exportDynamic; 84 r.FinalDefinitionInLinkageUnit = 85 !defined->isExternalWeakDef() && !defined->interposable; 86 } else if (const auto *common = dyn_cast<CommonSymbol>(sym)) { 87 r.ExportDynamic = !common->privateExtern && exportDynamic; 88 r.FinalDefinitionInLinkageUnit = true; 89 } 90 91 r.VisibleToRegularObj = 92 sym->isUsedInRegularObj || (r.Prevailing && r.ExportDynamic); 93 94 // Un-define the symbol so that we don't get duplicate symbol errors when we 95 // load the ObjFile emitted by LTO compilation. 96 if (r.Prevailing) 97 replaceSymbol<Undefined>(sym, sym->getName(), sym->getFile(), 98 RefState::Strong); 99 100 // TODO: set the other resolution configs properly 101 } 102 checkError(ltoObj->add(std::move(f.obj), resols)); 103 } 104 105 // Merge all the bitcode files we have seen, codegen the result 106 // and return the resulting ObjectFile(s). 107 std::vector<ObjFile *> BitcodeCompiler::compile() { 108 unsigned maxTasks = ltoObj->getMaxTasks(); 109 buf.resize(maxTasks); 110 files.resize(maxTasks); 111 112 // The -cache_path_lto option specifies the path to a directory in which 113 // to cache native object files for ThinLTO incremental builds. If a path was 114 // specified, configure LTO to use it as the cache directory. 115 FileCache cache; 116 if (!config->thinLTOCacheDir.empty()) 117 cache = 118 check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir, 119 [&](size_t task, std::unique_ptr<MemoryBuffer> mb) { 120 files[task] = std::move(mb); 121 })); 122 123 checkError(ltoObj->run( 124 [&](size_t task) { 125 return std::make_unique<CachedFileStream>( 126 std::make_unique<raw_svector_ostream>(buf[task])); 127 }, 128 cache)); 129 130 if (!config->thinLTOCacheDir.empty()) 131 pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy); 132 133 if (config->saveTemps) { 134 if (!buf[0].empty()) 135 saveBuffer(buf[0], config->outputFile + ".lto.o"); 136 for (unsigned i = 1; i != maxTasks; ++i) 137 saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o"); 138 } 139 140 if (!config->ltoObjPath.empty()) 141 fs::create_directories(config->ltoObjPath); 142 143 std::vector<ObjFile *> ret; 144 for (unsigned i = 0; i != maxTasks; ++i) { 145 if (buf[i].empty()) 146 continue; 147 SmallString<261> filePath("/tmp/lto.tmp"); 148 uint32_t modTime = 0; 149 if (!config->ltoObjPath.empty()) { 150 filePath = config->ltoObjPath; 151 path::append(filePath, Twine(i) + "." + 152 getArchitectureName(config->arch()) + 153 ".lto.o"); 154 saveBuffer(buf[i], filePath); 155 modTime = getModTime(filePath); 156 } 157 ret.push_back(make<ObjFile>( 158 MemoryBufferRef(buf[i], saver().save(filePath.str())), modTime, "")); 159 } 160 for (std::unique_ptr<MemoryBuffer> &file : files) 161 if (file) 162 ret.push_back(make<ObjFile>(*file, 0, "")); 163 return ret; 164 } 165