xref: /openbsd-src/gnu/llvm/lld/ELF/ICF.cpp (revision dfe94b169149f14cc1aee2cf6dad58a8d9a1860c)
1ece8a530Spatrick //===- ICF.cpp ------------------------------------------------------------===//
2ece8a530Spatrick //
3ece8a530Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ece8a530Spatrick // See https://llvm.org/LICENSE.txt for license information.
5ece8a530Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ece8a530Spatrick //
7ece8a530Spatrick //===----------------------------------------------------------------------===//
8ece8a530Spatrick //
9ece8a530Spatrick // ICF is short for Identical Code Folding. This is a size optimization to
10ece8a530Spatrick // identify and merge two or more read-only sections (typically functions)
11ece8a530Spatrick // that happened to have the same contents. It usually reduces output size
12ece8a530Spatrick // by a few percent.
13ece8a530Spatrick //
14ece8a530Spatrick // In ICF, two sections are considered identical if they have the same
15ece8a530Spatrick // section flags, section data, and relocations. Relocations are tricky,
16ece8a530Spatrick // because two relocations are considered the same if they have the same
17ece8a530Spatrick // relocation types, values, and if they point to the same sections *in
18ece8a530Spatrick // terms of ICF*.
19ece8a530Spatrick //
20ece8a530Spatrick // Here is an example. If foo and bar defined below are compiled to the
21ece8a530Spatrick // same machine instructions, ICF can and should merge the two, although
22ece8a530Spatrick // their relocations point to each other.
23ece8a530Spatrick //
24ece8a530Spatrick //   void foo() { bar(); }
25ece8a530Spatrick //   void bar() { foo(); }
26ece8a530Spatrick //
27ece8a530Spatrick // If you merge the two, their relocations point to the same section and
28ece8a530Spatrick // thus you know they are mergeable, but how do you know they are
29ece8a530Spatrick // mergeable in the first place? This is not an easy problem to solve.
30ece8a530Spatrick //
31ece8a530Spatrick // What we are doing in LLD is to partition sections into equivalence
32ece8a530Spatrick // classes. Sections in the same equivalence class when the algorithm
33ece8a530Spatrick // terminates are considered identical. Here are details:
34ece8a530Spatrick //
35ece8a530Spatrick // 1. First, we partition sections using their hash values as keys. Hash
36ece8a530Spatrick //    values contain section types, section contents and numbers of
37ece8a530Spatrick //    relocations. During this step, relocation targets are not taken into
38ece8a530Spatrick //    account. We just put sections that apparently differ into different
39ece8a530Spatrick //    equivalence classes.
40ece8a530Spatrick //
41ece8a530Spatrick // 2. Next, for each equivalence class, we visit sections to compare
42ece8a530Spatrick //    relocation targets. Relocation targets are considered equivalent if
43ece8a530Spatrick //    their targets are in the same equivalence class. Sections with
44ece8a530Spatrick //    different relocation targets are put into different equivalence
45ece8a530Spatrick //    classes.
46ece8a530Spatrick //
47ece8a530Spatrick // 3. If we split an equivalence class in step 2, two relocations
48ece8a530Spatrick //    previously target the same equivalence class may now target
49ece8a530Spatrick //    different equivalence classes. Therefore, we repeat step 2 until a
50ece8a530Spatrick //    convergence is obtained.
51ece8a530Spatrick //
52ece8a530Spatrick // 4. For each equivalence class C, pick an arbitrary section in C, and
53ece8a530Spatrick //    merge all the other sections in C with it.
54ece8a530Spatrick //
55ece8a530Spatrick // For small programs, this algorithm needs 3-5 iterations. For large
56ece8a530Spatrick // programs such as Chromium, it takes more than 20 iterations.
57ece8a530Spatrick //
58ece8a530Spatrick // This algorithm was mentioned as an "optimistic algorithm" in [1],
59ece8a530Spatrick // though gold implements a different algorithm than this.
60ece8a530Spatrick //
61ece8a530Spatrick // We parallelize each step so that multiple threads can work on different
62ece8a530Spatrick // equivalence classes concurrently. That gave us a large performance
63ece8a530Spatrick // boost when applying ICF on large programs. For example, MSVC link.exe
64ece8a530Spatrick // or GNU gold takes 10-20 seconds to apply ICF on Chromium, whose output
65ece8a530Spatrick // size is about 1.5 GB, but LLD can finish it in less than 2 seconds on a
66ece8a530Spatrick // 2.8 GHz 40 core machine. Even without threading, LLD's ICF is still
67ece8a530Spatrick // faster than MSVC or gold though.
68ece8a530Spatrick //
69ece8a530Spatrick // [1] Safe ICF: Pointer Safe and Unwinding aware Identical Code Folding
70ece8a530Spatrick // in the Gold Linker
71ece8a530Spatrick // http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/36912.pdf
72ece8a530Spatrick //
73ece8a530Spatrick //===----------------------------------------------------------------------===//
74ece8a530Spatrick 
75ece8a530Spatrick #include "ICF.h"
76ece8a530Spatrick #include "Config.h"
77*dfe94b16Srobert #include "InputFiles.h"
78ece8a530Spatrick #include "LinkerScript.h"
79ece8a530Spatrick #include "OutputSections.h"
80ece8a530Spatrick #include "SymbolTable.h"
81ece8a530Spatrick #include "Symbols.h"
82ece8a530Spatrick #include "SyntheticSections.h"
83ece8a530Spatrick #include "llvm/BinaryFormat/ELF.h"
84ece8a530Spatrick #include "llvm/Object/ELF.h"
85bb684c34Spatrick #include "llvm/Support/Parallel.h"
86bb684c34Spatrick #include "llvm/Support/TimeProfiler.h"
87ece8a530Spatrick #include "llvm/Support/xxhash.h"
88ece8a530Spatrick #include <algorithm>
89ece8a530Spatrick #include <atomic>
90ece8a530Spatrick 
91ece8a530Spatrick using namespace llvm;
92ece8a530Spatrick using namespace llvm::ELF;
93ece8a530Spatrick using namespace llvm::object;
94bb684c34Spatrick using namespace lld;
95bb684c34Spatrick using namespace lld::elf;
96ece8a530Spatrick 
97ece8a530Spatrick namespace {
98ece8a530Spatrick template <class ELFT> class ICF {
99ece8a530Spatrick public:
100ece8a530Spatrick   void run();
101ece8a530Spatrick 
102ece8a530Spatrick private:
1031cf9926bSpatrick   void segregate(size_t begin, size_t end, uint32_t eqClassBase, bool constant);
104ece8a530Spatrick 
105ece8a530Spatrick   template <class RelTy>
106ece8a530Spatrick   bool constantEq(const InputSection *a, ArrayRef<RelTy> relsA,
107ece8a530Spatrick                   const InputSection *b, ArrayRef<RelTy> relsB);
108ece8a530Spatrick 
109ece8a530Spatrick   template <class RelTy>
110ece8a530Spatrick   bool variableEq(const InputSection *a, ArrayRef<RelTy> relsA,
111ece8a530Spatrick                   const InputSection *b, ArrayRef<RelTy> relsB);
112ece8a530Spatrick 
113ece8a530Spatrick   bool equalsConstant(const InputSection *a, const InputSection *b);
114ece8a530Spatrick   bool equalsVariable(const InputSection *a, const InputSection *b);
115ece8a530Spatrick 
116ece8a530Spatrick   size_t findBoundary(size_t begin, size_t end);
117ece8a530Spatrick 
118ece8a530Spatrick   void forEachClassRange(size_t begin, size_t end,
119ece8a530Spatrick                          llvm::function_ref<void(size_t, size_t)> fn);
120ece8a530Spatrick 
121ece8a530Spatrick   void forEachClass(llvm::function_ref<void(size_t, size_t)> fn);
122ece8a530Spatrick 
123*dfe94b16Srobert   SmallVector<InputSection *, 0> sections;
124ece8a530Spatrick 
125ece8a530Spatrick   // We repeat the main loop while `Repeat` is true.
126ece8a530Spatrick   std::atomic<bool> repeat;
127ece8a530Spatrick 
128ece8a530Spatrick   // The main loop counter.
129ece8a530Spatrick   int cnt = 0;
130ece8a530Spatrick 
131ece8a530Spatrick   // We have two locations for equivalence classes. On the first iteration
132ece8a530Spatrick   // of the main loop, Class[0] has a valid value, and Class[1] contains
133ece8a530Spatrick   // garbage. We read equivalence classes from slot 0 and write to slot 1.
134ece8a530Spatrick   // So, Class[0] represents the current class, and Class[1] represents
135ece8a530Spatrick   // the next class. On each iteration, we switch their roles and use them
136ece8a530Spatrick   // alternately.
137ece8a530Spatrick   //
138ece8a530Spatrick   // Why are we doing this? Recall that other threads may be working on
139ece8a530Spatrick   // other equivalence classes in parallel. They may read sections that we
140ece8a530Spatrick   // are updating. We cannot update equivalence classes in place because
141ece8a530Spatrick   // it breaks the invariance that all possibly-identical sections must be
142ece8a530Spatrick   // in the same equivalence class at any moment. In other words, the for
143ece8a530Spatrick   // loop to update equivalence classes is not atomic, and that is
144ece8a530Spatrick   // observable from other threads. By writing new classes to other
145ece8a530Spatrick   // places, we can keep the invariance.
146ece8a530Spatrick   //
147ece8a530Spatrick   // Below, `Current` has the index of the current class, and `Next` has
148ece8a530Spatrick   // the index of the next class. If threading is enabled, they are either
149ece8a530Spatrick   // (0, 1) or (1, 0).
150ece8a530Spatrick   //
151ece8a530Spatrick   // Note on single-thread: if that's the case, they are always (0, 0)
152ece8a530Spatrick   // because we can safely read the next class without worrying about race
153ece8a530Spatrick   // conditions. Using the same location makes this algorithm converge
154ece8a530Spatrick   // faster because it uses results of the same iteration earlier.
155ece8a530Spatrick   int current = 0;
156ece8a530Spatrick   int next = 0;
157ece8a530Spatrick };
158ece8a530Spatrick }
159ece8a530Spatrick 
160ece8a530Spatrick // Returns true if section S is subject of ICF.
isEligible(InputSection * s)161ece8a530Spatrick static bool isEligible(InputSection *s) {
162ece8a530Spatrick   if (!s->isLive() || s->keepUnique || !(s->flags & SHF_ALLOC))
163ece8a530Spatrick     return false;
164ece8a530Spatrick 
165ece8a530Spatrick   // Don't merge writable sections. .data.rel.ro sections are marked as writable
166ece8a530Spatrick   // but are semantically read-only.
167ece8a530Spatrick   if ((s->flags & SHF_WRITE) && s->name != ".data.rel.ro" &&
168ece8a530Spatrick       !s->name.startswith(".data.rel.ro."))
169ece8a530Spatrick     return false;
170ece8a530Spatrick 
171ece8a530Spatrick   // SHF_LINK_ORDER sections are ICF'd as a unit with their dependent sections,
172ece8a530Spatrick   // so we don't consider them for ICF individually.
173ece8a530Spatrick   if (s->flags & SHF_LINK_ORDER)
174ece8a530Spatrick     return false;
175ece8a530Spatrick 
176ece8a530Spatrick   // Don't merge synthetic sections as their Data member is not valid and empty.
177ece8a530Spatrick   // The Data member needs to be valid for ICF as it is used by ICF to determine
178ece8a530Spatrick   // the equality of section contents.
179ece8a530Spatrick   if (isa<SyntheticSection>(s))
180ece8a530Spatrick     return false;
181ece8a530Spatrick 
182ece8a530Spatrick   // .init and .fini contains instructions that must be executed to initialize
183ece8a530Spatrick   // and finalize the process. They cannot and should not be merged.
184ece8a530Spatrick   if (s->name == ".init" || s->name == ".fini")
185ece8a530Spatrick     return false;
186ece8a530Spatrick 
187ece8a530Spatrick   // A user program may enumerate sections named with a C identifier using
188ece8a530Spatrick   // __start_* and __stop_* symbols. We cannot ICF any such sections because
189ece8a530Spatrick   // that could change program semantics.
190ece8a530Spatrick   if (isValidCIdentifier(s->name))
191ece8a530Spatrick     return false;
192ece8a530Spatrick 
193ece8a530Spatrick   return true;
194ece8a530Spatrick }
195ece8a530Spatrick 
196ece8a530Spatrick // Split an equivalence class into smaller classes.
197ece8a530Spatrick template <class ELFT>
segregate(size_t begin,size_t end,uint32_t eqClassBase,bool constant)1981cf9926bSpatrick void ICF<ELFT>::segregate(size_t begin, size_t end, uint32_t eqClassBase,
1991cf9926bSpatrick                           bool constant) {
200ece8a530Spatrick   // This loop rearranges sections in [Begin, End) so that all sections
201ece8a530Spatrick   // that are equal in terms of equals{Constant,Variable} are contiguous
202ece8a530Spatrick   // in [Begin, End).
203ece8a530Spatrick   //
204ece8a530Spatrick   // The algorithm is quadratic in the worst case, but that is not an
205ece8a530Spatrick   // issue in practice because the number of the distinct sections in
206ece8a530Spatrick   // each range is usually very small.
207ece8a530Spatrick 
208ece8a530Spatrick   while (begin < end) {
209ece8a530Spatrick     // Divide [Begin, End) into two. Let Mid be the start index of the
210ece8a530Spatrick     // second group.
211ece8a530Spatrick     auto bound =
212ece8a530Spatrick         std::stable_partition(sections.begin() + begin + 1,
213ece8a530Spatrick                               sections.begin() + end, [&](InputSection *s) {
214ece8a530Spatrick                                 if (constant)
215ece8a530Spatrick                                   return equalsConstant(sections[begin], s);
216ece8a530Spatrick                                 return equalsVariable(sections[begin], s);
217ece8a530Spatrick                               });
218ece8a530Spatrick     size_t mid = bound - sections.begin();
219ece8a530Spatrick 
220ece8a530Spatrick     // Now we split [Begin, End) into [Begin, Mid) and [Mid, End) by
2211cf9926bSpatrick     // updating the sections in [Begin, Mid). We use Mid as the basis for
2221cf9926bSpatrick     // the equivalence class ID because every group ends with a unique index.
2231cf9926bSpatrick     // Add this to eqClassBase to avoid equality with unique IDs.
224ece8a530Spatrick     for (size_t i = begin; i < mid; ++i)
2251cf9926bSpatrick       sections[i]->eqClass[next] = eqClassBase + mid;
226ece8a530Spatrick 
227ece8a530Spatrick     // If we created a group, we need to iterate the main loop again.
228ece8a530Spatrick     if (mid != end)
229ece8a530Spatrick       repeat = true;
230ece8a530Spatrick 
231ece8a530Spatrick     begin = mid;
232ece8a530Spatrick   }
233ece8a530Spatrick }
234ece8a530Spatrick 
235ece8a530Spatrick // Compare two lists of relocations.
236ece8a530Spatrick template <class ELFT>
237ece8a530Spatrick template <class RelTy>
constantEq(const InputSection * secA,ArrayRef<RelTy> ra,const InputSection * secB,ArrayRef<RelTy> rb)238ece8a530Spatrick bool ICF<ELFT>::constantEq(const InputSection *secA, ArrayRef<RelTy> ra,
239ece8a530Spatrick                            const InputSection *secB, ArrayRef<RelTy> rb) {
240*dfe94b16Srobert   if (ra.size() != rb.size())
241*dfe94b16Srobert     return false;
242ece8a530Spatrick   for (size_t i = 0; i < ra.size(); ++i) {
243ece8a530Spatrick     if (ra[i].r_offset != rb[i].r_offset ||
244ece8a530Spatrick         ra[i].getType(config->isMips64EL) != rb[i].getType(config->isMips64EL))
245ece8a530Spatrick       return false;
246ece8a530Spatrick 
247ece8a530Spatrick     uint64_t addA = getAddend<ELFT>(ra[i]);
248ece8a530Spatrick     uint64_t addB = getAddend<ELFT>(rb[i]);
249ece8a530Spatrick 
250ece8a530Spatrick     Symbol &sa = secA->template getFile<ELFT>()->getRelocTargetSym(ra[i]);
251ece8a530Spatrick     Symbol &sb = secB->template getFile<ELFT>()->getRelocTargetSym(rb[i]);
252ece8a530Spatrick     if (&sa == &sb) {
253ece8a530Spatrick       if (addA == addB)
254ece8a530Spatrick         continue;
255ece8a530Spatrick       return false;
256ece8a530Spatrick     }
257ece8a530Spatrick 
258ece8a530Spatrick     auto *da = dyn_cast<Defined>(&sa);
259ece8a530Spatrick     auto *db = dyn_cast<Defined>(&sb);
260ece8a530Spatrick 
261ece8a530Spatrick     // Placeholder symbols generated by linker scripts look the same now but
262ece8a530Spatrick     // may have different values later.
263ece8a530Spatrick     if (!da || !db || da->scriptDefined || db->scriptDefined)
264ece8a530Spatrick       return false;
265ece8a530Spatrick 
266ece8a530Spatrick     // When comparing a pair of relocations, if they refer to different symbols,
267ece8a530Spatrick     // and either symbol is preemptible, the containing sections should be
268ece8a530Spatrick     // considered different. This is because even if the sections are identical
269ece8a530Spatrick     // in this DSO, they may not be after preemption.
270ece8a530Spatrick     if (da->isPreemptible || db->isPreemptible)
271ece8a530Spatrick       return false;
272ece8a530Spatrick 
273ece8a530Spatrick     // Relocations referring to absolute symbols are constant-equal if their
274ece8a530Spatrick     // values are equal.
275ece8a530Spatrick     if (!da->section && !db->section && da->value + addA == db->value + addB)
276ece8a530Spatrick       continue;
277ece8a530Spatrick     if (!da->section || !db->section)
278ece8a530Spatrick       return false;
279ece8a530Spatrick 
280ece8a530Spatrick     if (da->section->kind() != db->section->kind())
281ece8a530Spatrick       return false;
282ece8a530Spatrick 
283ece8a530Spatrick     // Relocations referring to InputSections are constant-equal if their
284ece8a530Spatrick     // section offsets are equal.
285ece8a530Spatrick     if (isa<InputSection>(da->section)) {
286ece8a530Spatrick       if (da->value + addA == db->value + addB)
287ece8a530Spatrick         continue;
288ece8a530Spatrick       return false;
289ece8a530Spatrick     }
290ece8a530Spatrick 
291ece8a530Spatrick     // Relocations referring to MergeInputSections are constant-equal if their
292ece8a530Spatrick     // offsets in the output section are equal.
293ece8a530Spatrick     auto *x = dyn_cast<MergeInputSection>(da->section);
294ece8a530Spatrick     if (!x)
295ece8a530Spatrick       return false;
296ece8a530Spatrick     auto *y = cast<MergeInputSection>(db->section);
297ece8a530Spatrick     if (x->getParent() != y->getParent())
298ece8a530Spatrick       return false;
299ece8a530Spatrick 
300ece8a530Spatrick     uint64_t offsetA =
301ece8a530Spatrick         sa.isSection() ? x->getOffset(addA) : x->getOffset(da->value) + addA;
302ece8a530Spatrick     uint64_t offsetB =
303ece8a530Spatrick         sb.isSection() ? y->getOffset(addB) : y->getOffset(db->value) + addB;
304ece8a530Spatrick     if (offsetA != offsetB)
305ece8a530Spatrick       return false;
306ece8a530Spatrick   }
307ece8a530Spatrick 
308ece8a530Spatrick   return true;
309ece8a530Spatrick }
310ece8a530Spatrick 
311ece8a530Spatrick // Compare "non-moving" part of two InputSections, namely everything
312ece8a530Spatrick // except relocation targets.
313ece8a530Spatrick template <class ELFT>
equalsConstant(const InputSection * a,const InputSection * b)314ece8a530Spatrick bool ICF<ELFT>::equalsConstant(const InputSection *a, const InputSection *b) {
315*dfe94b16Srobert   if (a->flags != b->flags || a->getSize() != b->getSize() ||
316*dfe94b16Srobert       a->content() != b->content())
317ece8a530Spatrick     return false;
318ece8a530Spatrick 
319ece8a530Spatrick   // If two sections have different output sections, we cannot merge them.
320ece8a530Spatrick   assert(a->getParent() && b->getParent());
321ece8a530Spatrick   if (a->getParent() != b->getParent())
322ece8a530Spatrick     return false;
323ece8a530Spatrick 
324*dfe94b16Srobert   const RelsOrRelas<ELFT> ra = a->template relsOrRelas<ELFT>();
325*dfe94b16Srobert   const RelsOrRelas<ELFT> rb = b->template relsOrRelas<ELFT>();
326*dfe94b16Srobert   return ra.areRelocsRel() || rb.areRelocsRel()
327*dfe94b16Srobert              ? constantEq(a, ra.rels, b, rb.rels)
328*dfe94b16Srobert              : constantEq(a, ra.relas, b, rb.relas);
329ece8a530Spatrick }
330ece8a530Spatrick 
331ece8a530Spatrick // Compare two lists of relocations. Returns true if all pairs of
332ece8a530Spatrick // relocations point to the same section in terms of ICF.
333ece8a530Spatrick template <class ELFT>
334ece8a530Spatrick template <class RelTy>
variableEq(const InputSection * secA,ArrayRef<RelTy> ra,const InputSection * secB,ArrayRef<RelTy> rb)335ece8a530Spatrick bool ICF<ELFT>::variableEq(const InputSection *secA, ArrayRef<RelTy> ra,
336ece8a530Spatrick                            const InputSection *secB, ArrayRef<RelTy> rb) {
337ece8a530Spatrick   assert(ra.size() == rb.size());
338ece8a530Spatrick 
339ece8a530Spatrick   for (size_t i = 0; i < ra.size(); ++i) {
340ece8a530Spatrick     // The two sections must be identical.
341ece8a530Spatrick     Symbol &sa = secA->template getFile<ELFT>()->getRelocTargetSym(ra[i]);
342ece8a530Spatrick     Symbol &sb = secB->template getFile<ELFT>()->getRelocTargetSym(rb[i]);
343ece8a530Spatrick     if (&sa == &sb)
344ece8a530Spatrick       continue;
345ece8a530Spatrick 
346ece8a530Spatrick     auto *da = cast<Defined>(&sa);
347ece8a530Spatrick     auto *db = cast<Defined>(&sb);
348ece8a530Spatrick 
349ece8a530Spatrick     // We already dealt with absolute and non-InputSection symbols in
350ece8a530Spatrick     // constantEq, and for InputSections we have already checked everything
351ece8a530Spatrick     // except the equivalence class.
352ece8a530Spatrick     if (!da->section)
353ece8a530Spatrick       continue;
354ece8a530Spatrick     auto *x = dyn_cast<InputSection>(da->section);
355ece8a530Spatrick     if (!x)
356ece8a530Spatrick       continue;
357ece8a530Spatrick     auto *y = cast<InputSection>(db->section);
358ece8a530Spatrick 
3591cf9926bSpatrick     // Sections that are in the special equivalence class 0, can never be the
3601cf9926bSpatrick     // same in terms of the equivalence class.
361ece8a530Spatrick     if (x->eqClass[current] == 0)
362ece8a530Spatrick       return false;
363ece8a530Spatrick     if (x->eqClass[current] != y->eqClass[current])
364ece8a530Spatrick       return false;
365ece8a530Spatrick   };
366ece8a530Spatrick 
367ece8a530Spatrick   return true;
368ece8a530Spatrick }
369ece8a530Spatrick 
370ece8a530Spatrick // Compare "moving" part of two InputSections, namely relocation targets.
371ece8a530Spatrick template <class ELFT>
equalsVariable(const InputSection * a,const InputSection * b)372ece8a530Spatrick bool ICF<ELFT>::equalsVariable(const InputSection *a, const InputSection *b) {
373*dfe94b16Srobert   const RelsOrRelas<ELFT> ra = a->template relsOrRelas<ELFT>();
374*dfe94b16Srobert   const RelsOrRelas<ELFT> rb = b->template relsOrRelas<ELFT>();
375*dfe94b16Srobert   return ra.areRelocsRel() || rb.areRelocsRel()
376*dfe94b16Srobert              ? variableEq(a, ra.rels, b, rb.rels)
377*dfe94b16Srobert              : variableEq(a, ra.relas, b, rb.relas);
378ece8a530Spatrick }
379ece8a530Spatrick 
findBoundary(size_t begin,size_t end)380ece8a530Spatrick template <class ELFT> size_t ICF<ELFT>::findBoundary(size_t begin, size_t end) {
381ece8a530Spatrick   uint32_t eqClass = sections[begin]->eqClass[current];
382ece8a530Spatrick   for (size_t i = begin + 1; i < end; ++i)
383ece8a530Spatrick     if (eqClass != sections[i]->eqClass[current])
384ece8a530Spatrick       return i;
385ece8a530Spatrick   return end;
386ece8a530Spatrick }
387ece8a530Spatrick 
388ece8a530Spatrick // Sections in the same equivalence class are contiguous in Sections
389ece8a530Spatrick // vector. Therefore, Sections vector can be considered as contiguous
390ece8a530Spatrick // groups of sections, grouped by the class.
391ece8a530Spatrick //
392ece8a530Spatrick // This function calls Fn on every group within [Begin, End).
393ece8a530Spatrick template <class ELFT>
forEachClassRange(size_t begin,size_t end,llvm::function_ref<void (size_t,size_t)> fn)394ece8a530Spatrick void ICF<ELFT>::forEachClassRange(size_t begin, size_t end,
395ece8a530Spatrick                                   llvm::function_ref<void(size_t, size_t)> fn) {
396ece8a530Spatrick   while (begin < end) {
397ece8a530Spatrick     size_t mid = findBoundary(begin, end);
398ece8a530Spatrick     fn(begin, mid);
399ece8a530Spatrick     begin = mid;
400ece8a530Spatrick   }
401ece8a530Spatrick }
402ece8a530Spatrick 
403ece8a530Spatrick // Call Fn on each equivalence class.
404ece8a530Spatrick template <class ELFT>
forEachClass(llvm::function_ref<void (size_t,size_t)> fn)405ece8a530Spatrick void ICF<ELFT>::forEachClass(llvm::function_ref<void(size_t, size_t)> fn) {
406ece8a530Spatrick   // If threading is disabled or the number of sections are
407ece8a530Spatrick   // too small to use threading, call Fn sequentially.
408bb684c34Spatrick   if (parallel::strategy.ThreadsRequested == 1 || sections.size() < 1024) {
409ece8a530Spatrick     forEachClassRange(0, sections.size(), fn);
410ece8a530Spatrick     ++cnt;
411ece8a530Spatrick     return;
412ece8a530Spatrick   }
413ece8a530Spatrick 
414ece8a530Spatrick   current = cnt % 2;
415ece8a530Spatrick   next = (cnt + 1) % 2;
416ece8a530Spatrick 
417ece8a530Spatrick   // Shard into non-overlapping intervals, and call Fn in parallel.
418ece8a530Spatrick   // The sharding must be completed before any calls to Fn are made
419ece8a530Spatrick   // so that Fn can modify the Chunks in its shard without causing data
420ece8a530Spatrick   // races.
421ece8a530Spatrick   const size_t numShards = 256;
422ece8a530Spatrick   size_t step = sections.size() / numShards;
423ece8a530Spatrick   size_t boundaries[numShards + 1];
424ece8a530Spatrick   boundaries[0] = 0;
425ece8a530Spatrick   boundaries[numShards] = sections.size();
426ece8a530Spatrick 
427*dfe94b16Srobert   parallelFor(1, numShards, [&](size_t i) {
428ece8a530Spatrick     boundaries[i] = findBoundary((i - 1) * step, sections.size());
429ece8a530Spatrick   });
430ece8a530Spatrick 
431*dfe94b16Srobert   parallelFor(1, numShards + 1, [&](size_t i) {
432ece8a530Spatrick     if (boundaries[i - 1] < boundaries[i])
433ece8a530Spatrick       forEachClassRange(boundaries[i - 1], boundaries[i], fn);
434ece8a530Spatrick   });
435ece8a530Spatrick   ++cnt;
436ece8a530Spatrick }
437ece8a530Spatrick 
438ece8a530Spatrick // Combine the hashes of the sections referenced by the given section into its
439ece8a530Spatrick // hash.
440ece8a530Spatrick template <class ELFT, class RelTy>
combineRelocHashes(unsigned cnt,InputSection * isec,ArrayRef<RelTy> rels)441ece8a530Spatrick static void combineRelocHashes(unsigned cnt, InputSection *isec,
442ece8a530Spatrick                                ArrayRef<RelTy> rels) {
443ece8a530Spatrick   uint32_t hash = isec->eqClass[cnt % 2];
444ece8a530Spatrick   for (RelTy rel : rels) {
445ece8a530Spatrick     Symbol &s = isec->template getFile<ELFT>()->getRelocTargetSym(rel);
446ece8a530Spatrick     if (auto *d = dyn_cast<Defined>(&s))
447ece8a530Spatrick       if (auto *relSec = dyn_cast_or_null<InputSection>(d->section))
448ece8a530Spatrick         hash += relSec->eqClass[cnt % 2];
449ece8a530Spatrick   }
4501cf9926bSpatrick   // Set MSB to 1 to avoid collisions with unique IDs.
451ece8a530Spatrick   isec->eqClass[(cnt + 1) % 2] = hash | (1U << 31);
452ece8a530Spatrick }
453ece8a530Spatrick 
print(const Twine & s)454ece8a530Spatrick static void print(const Twine &s) {
455ece8a530Spatrick   if (config->printIcfSections)
456ece8a530Spatrick     message(s);
457ece8a530Spatrick }
458ece8a530Spatrick 
459ece8a530Spatrick // The main function of ICF.
run()460ece8a530Spatrick template <class ELFT> void ICF<ELFT>::run() {
461ece8a530Spatrick   // Compute isPreemptible early. We may add more symbols later, so this loop
462ece8a530Spatrick   // cannot be merged with the later computeIsPreemptible() pass which is used
463ece8a530Spatrick   // by scanRelocations().
464*dfe94b16Srobert   if (config->hasDynSymTab)
465*dfe94b16Srobert     for (Symbol *sym : symtab.getSymbols())
466ece8a530Spatrick       sym->isPreemptible = computeIsPreemptible(*sym);
467ece8a530Spatrick 
4681cf9926bSpatrick   // Two text sections may have identical content and relocations but different
4691cf9926bSpatrick   // LSDA, e.g. the two functions may have catch blocks of different types. If a
4701cf9926bSpatrick   // text section is referenced by a .eh_frame FDE with LSDA, it is not
4711cf9926bSpatrick   // eligible. This is implemented by iterating over CIE/FDE and setting
4721cf9926bSpatrick   // eqClass[0] to the referenced text section from a live FDE.
4731cf9926bSpatrick   //
4741cf9926bSpatrick   // If two .gcc_except_table have identical semantics (usually identical
4751cf9926bSpatrick   // content with PC-relative encoding), we will lose folding opportunity.
4761cf9926bSpatrick   uint32_t uniqueId = 0;
4771cf9926bSpatrick   for (Partition &part : partitions)
4781cf9926bSpatrick     part.ehFrame->iterateFDEWithLSDA<ELFT>(
4791cf9926bSpatrick         [&](InputSection &s) { s.eqClass[0] = s.eqClass[1] = ++uniqueId; });
4801cf9926bSpatrick 
481ece8a530Spatrick   // Collect sections to merge.
482*dfe94b16Srobert   for (InputSectionBase *sec : ctx.inputSections) {
483*dfe94b16Srobert     auto *s = dyn_cast<InputSection>(sec);
484*dfe94b16Srobert     if (s && s->eqClass[0] == 0) {
485ece8a530Spatrick       if (isEligible(s))
486ece8a530Spatrick         sections.push_back(s);
4871cf9926bSpatrick       else
4881cf9926bSpatrick         // Ineligible sections are assigned unique IDs, i.e. each section
4891cf9926bSpatrick         // belongs to an equivalence class of its own.
4901cf9926bSpatrick         s->eqClass[0] = s->eqClass[1] = ++uniqueId;
4911cf9926bSpatrick     }
492ece8a530Spatrick   }
493ece8a530Spatrick 
494ece8a530Spatrick   // Initially, we use hash values to partition sections.
4951cf9926bSpatrick   parallelForEach(sections, [&](InputSection *s) {
4961cf9926bSpatrick     // Set MSB to 1 to avoid collisions with unique IDs.
497*dfe94b16Srobert     s->eqClass[0] = xxHash64(s->content()) | (1U << 31);
4981cf9926bSpatrick   });
499ece8a530Spatrick 
5001cf9926bSpatrick   // Perform 2 rounds of relocation hash propagation. 2 is an empirical value to
5011cf9926bSpatrick   // reduce the average sizes of equivalence classes, i.e. segregate() which has
5021cf9926bSpatrick   // a large time complexity will have less work to do.
503ece8a530Spatrick   for (unsigned cnt = 0; cnt != 2; ++cnt) {
504ece8a530Spatrick     parallelForEach(sections, [&](InputSection *s) {
505*dfe94b16Srobert       const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
506*dfe94b16Srobert       if (rels.areRelocsRel())
507*dfe94b16Srobert         combineRelocHashes<ELFT>(cnt, s, rels.rels);
508ece8a530Spatrick       else
509*dfe94b16Srobert         combineRelocHashes<ELFT>(cnt, s, rels.relas);
510ece8a530Spatrick     });
511ece8a530Spatrick   }
512ece8a530Spatrick 
513ece8a530Spatrick   // From now on, sections in Sections vector are ordered so that sections
514ece8a530Spatrick   // in the same equivalence class are consecutive in the vector.
515ece8a530Spatrick   llvm::stable_sort(sections, [](const InputSection *a, const InputSection *b) {
516ece8a530Spatrick     return a->eqClass[0] < b->eqClass[0];
517ece8a530Spatrick   });
518ece8a530Spatrick 
5191cf9926bSpatrick   // Compare static contents and assign unique equivalence class IDs for each
5201cf9926bSpatrick   // static content. Use a base offset for these IDs to ensure no overlap with
5211cf9926bSpatrick   // the unique IDs already assigned.
5221cf9926bSpatrick   uint32_t eqClassBase = ++uniqueId;
5231cf9926bSpatrick   forEachClass([&](size_t begin, size_t end) {
5241cf9926bSpatrick     segregate(begin, end, eqClassBase, true);
5251cf9926bSpatrick   });
526ece8a530Spatrick 
527ece8a530Spatrick   // Split groups by comparing relocations until convergence is obtained.
528ece8a530Spatrick   do {
529ece8a530Spatrick     repeat = false;
5301cf9926bSpatrick     forEachClass([&](size_t begin, size_t end) {
5311cf9926bSpatrick       segregate(begin, end, eqClassBase, false);
5321cf9926bSpatrick     });
533ece8a530Spatrick   } while (repeat);
534ece8a530Spatrick 
535ece8a530Spatrick   log("ICF needed " + Twine(cnt) + " iterations");
536ece8a530Spatrick 
537ece8a530Spatrick   // Merge sections by the equivalence class.
538ece8a530Spatrick   forEachClassRange(0, sections.size(), [&](size_t begin, size_t end) {
539ece8a530Spatrick     if (end - begin == 1)
540ece8a530Spatrick       return;
541ece8a530Spatrick     print("selected section " + toString(sections[begin]));
542ece8a530Spatrick     for (size_t i = begin + 1; i < end; ++i) {
543ece8a530Spatrick       print("  removing identical section " + toString(sections[i]));
544ece8a530Spatrick       sections[begin]->replace(sections[i]);
545ece8a530Spatrick 
546ece8a530Spatrick       // At this point we know sections merged are fully identical and hence
547ece8a530Spatrick       // we want to remove duplicate implicit dependencies such as link order
548ece8a530Spatrick       // and relocation sections.
549ece8a530Spatrick       for (InputSection *isec : sections[i]->dependentSections)
550ece8a530Spatrick         isec->markDead();
551ece8a530Spatrick     }
552ece8a530Spatrick   });
553ece8a530Spatrick 
554*dfe94b16Srobert   // Change Defined symbol's section field to the canonical one.
555*dfe94b16Srobert   auto fold = [](Symbol *sym) {
556*dfe94b16Srobert     if (auto *d = dyn_cast<Defined>(sym))
557*dfe94b16Srobert       if (auto *sec = dyn_cast_or_null<InputSection>(d->section))
558*dfe94b16Srobert         if (sec->repl != d->section) {
559*dfe94b16Srobert           d->section = sec->repl;
560*dfe94b16Srobert           d->folded = true;
561*dfe94b16Srobert         }
562*dfe94b16Srobert   };
563*dfe94b16Srobert   for (Symbol *sym : symtab.getSymbols())
564*dfe94b16Srobert     fold(sym);
565*dfe94b16Srobert   parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) {
566*dfe94b16Srobert     for (Symbol *sym : file->getLocalSymbols())
567*dfe94b16Srobert       fold(sym);
568*dfe94b16Srobert   });
569*dfe94b16Srobert 
570ece8a530Spatrick   // InputSectionDescription::sections is populated by processSectionCommands().
571ece8a530Spatrick   // ICF may fold some input sections assigned to output sections. Remove them.
572*dfe94b16Srobert   for (SectionCommand *cmd : script->sectionCommands)
573*dfe94b16Srobert     if (auto *osd = dyn_cast<OutputDesc>(cmd))
574*dfe94b16Srobert       for (SectionCommand *subCmd : osd->osec.commands)
575*dfe94b16Srobert         if (auto *isd = dyn_cast<InputSectionDescription>(subCmd))
576ece8a530Spatrick           llvm::erase_if(isd->sections,
577ece8a530Spatrick                          [](InputSection *isec) { return !isec->isLive(); });
578ece8a530Spatrick }
579ece8a530Spatrick 
580ece8a530Spatrick // ICF entry point function.
doIcf()581bb684c34Spatrick template <class ELFT> void elf::doIcf() {
582bb684c34Spatrick   llvm::TimeTraceScope timeScope("ICF");
583bb684c34Spatrick   ICF<ELFT>().run();
584bb684c34Spatrick }
585ece8a530Spatrick 
586bb684c34Spatrick template void elf::doIcf<ELF32LE>();
587bb684c34Spatrick template void elf::doIcf<ELF32BE>();
588bb684c34Spatrick template void elf::doIcf<ELF64LE>();
589bb684c34Spatrick template void elf::doIcf<ELF64BE>();
590