llvm-project
335 строк · 11.5 Кб
1//===- ICF.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// ICF is short for Identical Code Folding. That is a size optimization to
10// identify and merge two or more read-only sections (typically functions)
11// that happened to have the same contents. It usually reduces output size
12// by a few percent.
13//
14// On Windows, ICF is enabled by default.
15//
16// See ELF/ICF.cpp for the details about the algorithm.
17//
18//===----------------------------------------------------------------------===//
19
20#include "ICF.h"
21#include "COFFLinkerContext.h"
22#include "Chunks.h"
23#include "Symbols.h"
24#include "lld/Common/ErrorHandler.h"
25#include "lld/Common/Timer.h"
26#include "llvm/ADT/Hashing.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/Parallel.h"
29#include "llvm/Support/TimeProfiler.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Support/xxhash.h"
32#include <algorithm>
33#include <atomic>
34#include <vector>
35
36using namespace llvm;
37
38namespace lld::coff {
39
40class ICF {
41public:
42ICF(COFFLinkerContext &c) : ctx(c){};
43void run();
44
45private:
46void segregate(size_t begin, size_t end, bool constant);
47
48bool assocEquals(const SectionChunk *a, const SectionChunk *b);
49
50bool equalsConstant(const SectionChunk *a, const SectionChunk *b);
51bool equalsVariable(const SectionChunk *a, const SectionChunk *b);
52
53bool isEligible(SectionChunk *c);
54
55size_t findBoundary(size_t begin, size_t end);
56
57void forEachClassRange(size_t begin, size_t end,
58std::function<void(size_t, size_t)> fn);
59
60void forEachClass(std::function<void(size_t, size_t)> fn);
61
62std::vector<SectionChunk *> chunks;
63int cnt = 0;
64std::atomic<bool> repeat = {false};
65
66COFFLinkerContext &ctx;
67};
68
69// Returns true if section S is subject of ICF.
70//
71// Microsoft's documentation
72// (https://msdn.microsoft.com/en-us/library/bxwfs976.aspx; visited April
73// 2017) says that /opt:icf folds both functions and read-only data.
74// Despite that, the MSVC linker folds only functions. We found
75// a few instances of programs that are not safe for data merging.
76// Therefore, we merge only functions just like the MSVC tool. However, we also
77// merge read-only sections in a couple of cases where the address of the
78// section is insignificant to the user program and the behaviour matches that
79// of the Visual C++ linker.
80bool ICF::isEligible(SectionChunk *c) {
81// Non-comdat chunks, dead chunks, and writable chunks are not eligible.
82bool writable = c->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
83if (!c->isCOMDAT() || !c->live || writable)
84return false;
85
86// Under regular (not safe) ICF, all code sections are eligible.
87if ((ctx.config.doICF == ICFLevel::All) &&
88c->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
89return true;
90
91// .pdata and .xdata unwind info sections are eligible.
92StringRef outSecName = c->getSectionName().split('$').first;
93if (outSecName == ".pdata" || outSecName == ".xdata")
94return true;
95
96// So are vtables.
97const char *itaniumVtablePrefix =
98ctx.config.machine == I386 ? "__ZTV" : "_ZTV";
99if (c->sym && (c->sym->getName().starts_with("??_7") ||
100c->sym->getName().starts_with(itaniumVtablePrefix)))
101return true;
102
103// Anything else not in an address-significance table is eligible.
104return !c->keepUnique;
105}
106
107// Split an equivalence class into smaller classes.
108void ICF::segregate(size_t begin, size_t end, bool constant) {
109while (begin < end) {
110// Divide [Begin, End) into two. Let Mid be the start index of the
111// second group.
112auto bound = std::stable_partition(
113chunks.begin() + begin + 1, chunks.begin() + end, [&](SectionChunk *s) {
114if (constant)
115return equalsConstant(chunks[begin], s);
116return equalsVariable(chunks[begin], s);
117});
118size_t mid = bound - chunks.begin();
119
120// Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an
121// equivalence class ID because every group ends with a unique index.
122for (size_t i = begin; i < mid; ++i)
123chunks[i]->eqClass[(cnt + 1) % 2] = mid;
124
125// If we created a group, we need to iterate the main loop again.
126if (mid != end)
127repeat = true;
128
129begin = mid;
130}
131}
132
133// Returns true if two sections' associative children are equal.
134bool ICF::assocEquals(const SectionChunk *a, const SectionChunk *b) {
135// Ignore associated metadata sections that don't participate in ICF, such as
136// debug info and CFGuard metadata.
137auto considerForICF = [](const SectionChunk &assoc) {
138StringRef Name = assoc.getSectionName();
139return !(Name.starts_with(".debug") || Name == ".gfids$y" ||
140Name == ".giats$y" || Name == ".gljmp$y");
141};
142auto ra = make_filter_range(a->children(), considerForICF);
143auto rb = make_filter_range(b->children(), considerForICF);
144return std::equal(ra.begin(), ra.end(), rb.begin(), rb.end(),
145[&](const SectionChunk &ia, const SectionChunk &ib) {
146return ia.eqClass[cnt % 2] == ib.eqClass[cnt % 2];
147});
148}
149
150// Compare "non-moving" part of two sections, namely everything
151// except relocation targets.
152bool ICF::equalsConstant(const SectionChunk *a, const SectionChunk *b) {
153if (a->relocsSize != b->relocsSize)
154return false;
155
156// Compare relocations.
157auto eq = [&](const coff_relocation &r1, const coff_relocation &r2) {
158if (r1.Type != r2.Type ||
159r1.VirtualAddress != r2.VirtualAddress) {
160return false;
161}
162Symbol *b1 = a->file->getSymbol(r1.SymbolTableIndex);
163Symbol *b2 = b->file->getSymbol(r2.SymbolTableIndex);
164if (b1 == b2)
165return true;
166if (auto *d1 = dyn_cast<DefinedRegular>(b1))
167if (auto *d2 = dyn_cast<DefinedRegular>(b2))
168return d1->getValue() == d2->getValue() &&
169d1->getChunk()->eqClass[cnt % 2] == d2->getChunk()->eqClass[cnt % 2];
170return false;
171};
172if (!std::equal(a->getRelocs().begin(), a->getRelocs().end(),
173b->getRelocs().begin(), eq))
174return false;
175
176// Compare section attributes and contents.
177return a->getOutputCharacteristics() == b->getOutputCharacteristics() &&
178a->getSectionName() == b->getSectionName() &&
179a->header->SizeOfRawData == b->header->SizeOfRawData &&
180a->checksum == b->checksum && a->getContents() == b->getContents() &&
181a->getMachine() == b->getMachine() && assocEquals(a, b);
182}
183
184// Compare "moving" part of two sections, namely relocation targets.
185bool ICF::equalsVariable(const SectionChunk *a, const SectionChunk *b) {
186// Compare relocations.
187auto eqSym = [&](Symbol *b1, Symbol *b2) {
188if (b1 == b2)
189return true;
190if (auto *d1 = dyn_cast<DefinedRegular>(b1))
191if (auto *d2 = dyn_cast<DefinedRegular>(b2))
192return d1->getChunk()->eqClass[cnt % 2] == d2->getChunk()->eqClass[cnt % 2];
193return false;
194};
195auto eq = [&](const coff_relocation &r1, const coff_relocation &r2) {
196Symbol *b1 = a->file->getSymbol(r1.SymbolTableIndex);
197Symbol *b2 = b->file->getSymbol(r2.SymbolTableIndex);
198return eqSym(b1, b2);
199};
200
201Symbol *e1 = a->getEntryThunk();
202Symbol *e2 = b->getEntryThunk();
203if ((e1 || e2) && (!e1 || !e2 || !eqSym(e1, e2)))
204return false;
205
206return std::equal(a->getRelocs().begin(), a->getRelocs().end(),
207b->getRelocs().begin(), eq) &&
208assocEquals(a, b);
209}
210
211// Find the first Chunk after Begin that has a different class from Begin.
212size_t ICF::findBoundary(size_t begin, size_t end) {
213for (size_t i = begin + 1; i < end; ++i)
214if (chunks[begin]->eqClass[cnt % 2] != chunks[i]->eqClass[cnt % 2])
215return i;
216return end;
217}
218
219void ICF::forEachClassRange(size_t begin, size_t end,
220std::function<void(size_t, size_t)> fn) {
221while (begin < end) {
222size_t mid = findBoundary(begin, end);
223fn(begin, mid);
224begin = mid;
225}
226}
227
228// Call Fn on each class group.
229void ICF::forEachClass(std::function<void(size_t, size_t)> fn) {
230// If the number of sections are too small to use threading,
231// call Fn sequentially.
232if (chunks.size() < 1024) {
233forEachClassRange(0, chunks.size(), fn);
234++cnt;
235return;
236}
237
238// Shard into non-overlapping intervals, and call Fn in parallel.
239// The sharding must be completed before any calls to Fn are made
240// so that Fn can modify the Chunks in its shard without causing data
241// races.
242const size_t numShards = 256;
243size_t step = chunks.size() / numShards;
244size_t boundaries[numShards + 1];
245boundaries[0] = 0;
246boundaries[numShards] = chunks.size();
247parallelFor(1, numShards, [&](size_t i) {
248boundaries[i] = findBoundary((i - 1) * step, chunks.size());
249});
250parallelFor(1, numShards + 1, [&](size_t i) {
251if (boundaries[i - 1] < boundaries[i]) {
252forEachClassRange(boundaries[i - 1], boundaries[i], fn);
253}
254});
255++cnt;
256}
257
258// Merge identical COMDAT sections.
259// Two sections are considered the same if their section headers,
260// contents and relocations are all the same.
261void ICF::run() {
262llvm::TimeTraceScope timeScope("ICF");
263ScopedTimer t(ctx.icfTimer);
264
265// Collect only mergeable sections and group by hash value.
266uint32_t nextId = 1;
267for (Chunk *c : ctx.symtab.getChunks()) {
268if (auto *sc = dyn_cast<SectionChunk>(c)) {
269if (isEligible(sc))
270chunks.push_back(sc);
271else
272sc->eqClass[0] = nextId++;
273}
274}
275
276// Make sure that ICF doesn't merge sections that are being handled by string
277// tail merging.
278for (MergeChunk *mc : ctx.mergeChunkInstances)
279if (mc)
280for (SectionChunk *sc : mc->sections)
281sc->eqClass[0] = nextId++;
282
283// Initially, we use hash values to partition sections.
284parallelForEach(chunks, [&](SectionChunk *sc) {
285sc->eqClass[0] = xxh3_64bits(sc->getContents());
286});
287
288// Combine the hashes of the sections referenced by each section into its
289// hash.
290for (unsigned cnt = 0; cnt != 2; ++cnt) {
291parallelForEach(chunks, [&](SectionChunk *sc) {
292uint32_t hash = sc->eqClass[cnt % 2];
293for (Symbol *b : sc->symbols())
294if (auto *sym = dyn_cast_or_null<DefinedRegular>(b))
295hash += sym->getChunk()->eqClass[cnt % 2];
296// Set MSB to 1 to avoid collisions with non-hash classes.
297sc->eqClass[(cnt + 1) % 2] = hash | (1U << 31);
298});
299}
300
301// From now on, sections in Chunks are ordered so that sections in
302// the same group are consecutive in the vector.
303llvm::stable_sort(chunks, [](const SectionChunk *a, const SectionChunk *b) {
304return a->eqClass[0] < b->eqClass[0];
305});
306
307// Compare static contents and assign unique IDs for each static content.
308forEachClass([&](size_t begin, size_t end) { segregate(begin, end, true); });
309
310// Split groups by comparing relocations until convergence is obtained.
311do {
312repeat = false;
313forEachClass(
314[&](size_t begin, size_t end) { segregate(begin, end, false); });
315} while (repeat);
316
317log("ICF needed " + Twine(cnt) + " iterations");
318
319// Merge sections in the same classes.
320forEachClass([&](size_t begin, size_t end) {
321if (end - begin == 1)
322return;
323
324log("Selected " + chunks[begin]->getDebugName());
325for (size_t i = begin + 1; i < end; ++i) {
326log(" Removed " + chunks[i]->getDebugName());
327chunks[begin]->replace(chunks[i]);
328}
329});
330}
331
332// Entry point to ICF.
333void doICF(COFFLinkerContext &ctx) { ICF(ctx).run(); }
334
335} // namespace lld::coff
336