xref: /llvm-project-15.0.7/lld/MachO/LTO.cpp (revision 2ea7fb7b)
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/ErrorHandler.h"
17 #include "lld/Common/Strings.h"
18 #include "lld/Common/TargetOptionsCommandFlags.h"
19 #include "llvm/LTO/LTO.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Transforms/ObjCARC.h"
24 
25 using namespace lld;
26 using namespace lld::macho;
27 using namespace llvm;
28 using namespace llvm::MachO;
29 using namespace llvm::sys;
30 
31 static lto::Config createConfig() {
32   lto::Config c;
33   c.Options = initTargetOptionsFromCodeGenFlags();
34   c.CodeModel = getCodeModelFromCMModel();
35   c.CPU = getCPUStr();
36   c.MAttrs = getMAttrs();
37   c.UseNewPM = config->ltoNewPassManager;
38   c.PreCodeGenPassesHook = [](legacy::PassManager &pm) {
39     pm.add(createObjCARCContractPass());
40   };
41   c.TimeTraceEnabled = config->timeTraceEnabled;
42   c.TimeTraceGranularity = config->timeTraceGranularity;
43   if (config->saveTemps)
44     checkError(c.addSaveTemps(config->outputFile.str() + ".",
45                               /*UseInputModulePath=*/true));
46   return c;
47 }
48 
49 BitcodeCompiler::BitcodeCompiler() {
50   lto::ThinBackend backend = lto::createInProcessThinBackend(
51       heavyweight_hardware_concurrency(config->thinLTOJobs));
52   ltoObj = std::make_unique<lto::LTO>(createConfig(), backend);
53 }
54 
55 void BitcodeCompiler::add(BitcodeFile &f) {
56   ArrayRef<lto::InputFile::Symbol> objSyms = f.obj->symbols();
57   std::vector<lto::SymbolResolution> resols;
58   resols.reserve(objSyms.size());
59 
60   // Provide a resolution to the LTO API for each symbol.
61   auto symIt = f.symbols.begin();
62   for (const lto::InputFile::Symbol &objSym : objSyms) {
63     resols.emplace_back();
64     lto::SymbolResolution &r = resols.back();
65     Symbol *sym = *symIt++;
66 
67     // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
68     // reports two symbols for module ASM defined. Without this check, lld
69     // flags an undefined in IR with a definition in ASM as prevailing.
70     // Once IRObjectFile is fixed to report only one symbol this hack can
71     // be removed.
72     r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;
73 
74     // FIXME: What about other output types? And we can probably be less
75     // restrictive with -flat_namespace, but it's an infrequent use case.
76     r.VisibleToRegularObj = config->outputType != MH_EXECUTE ||
77                             config->namespaceKind == NamespaceKind::flat ||
78                             sym->isUsedInRegularObj;
79 
80     // Un-define the symbol so that we don't get duplicate symbol errors when we
81     // load the ObjFile emitted by LTO compilation.
82     if (r.Prevailing)
83       replaceSymbol<Undefined>(sym, sym->getName(), sym->getFile(),
84                                RefState::Strong);
85 
86     // TODO: set the other resolution configs properly
87   }
88   checkError(ltoObj->add(std::move(f.obj), resols));
89 }
90 
91 // Merge all the bitcode files we have seen, codegen the result
92 // and return the resulting ObjectFile(s).
93 std::vector<ObjFile *> BitcodeCompiler::compile() {
94   unsigned maxTasks = ltoObj->getMaxTasks();
95   buf.resize(maxTasks);
96 
97   checkError(ltoObj->run([&](size_t task) {
98     return std::make_unique<lto::NativeObjectStream>(
99         std::make_unique<raw_svector_ostream>(buf[task]));
100   }));
101 
102   if (config->saveTemps) {
103     if (!buf[0].empty())
104       saveBuffer(buf[0], config->outputFile + ".lto.o");
105     for (unsigned i = 1; i != maxTasks; ++i)
106       saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o");
107   }
108 
109   if (!config->ltoObjPath.empty())
110     fs::create_directories(config->ltoObjPath);
111 
112   std::vector<ObjFile *> ret;
113   for (unsigned i = 0; i != maxTasks; ++i) {
114     if (buf[i].empty())
115       continue;
116     SmallString<261> filePath("/tmp/lto.tmp");
117     uint32_t modTime = 0;
118     if (!config->ltoObjPath.empty()) {
119       filePath = config->ltoObjPath;
120       path::append(filePath, Twine(i) + "." +
121                                  getArchitectureName(config->arch()) +
122                                  ".lto.o");
123       saveBuffer(buf[i], filePath);
124       modTime = getModTime(filePath);
125     }
126     ret.push_back(make<ObjFile>(
127         MemoryBufferRef(buf[i], saver.save(filePath.str())), modTime, ""));
128   }
129 
130   return ret;
131 }
132