xref: /freebsd/contrib/llvm-project/lld/ELF/ICF.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===- ICF.cpp ------------------------------------------------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // ICF is short for Identical Code Folding. This is a size optimization to
10*0b57cec5SDimitry Andric // identify and merge two or more read-only sections (typically functions)
11*0b57cec5SDimitry Andric // that happened to have the same contents. It usually reduces output size
12*0b57cec5SDimitry Andric // by a few percent.
13*0b57cec5SDimitry Andric //
14*0b57cec5SDimitry Andric // In ICF, two sections are considered identical if they have the same
15*0b57cec5SDimitry Andric // section flags, section data, and relocations. Relocations are tricky,
16*0b57cec5SDimitry Andric // because two relocations are considered the same if they have the same
17*0b57cec5SDimitry Andric // relocation types, values, and if they point to the same sections *in
18*0b57cec5SDimitry Andric // terms of ICF*.
19*0b57cec5SDimitry Andric //
20*0b57cec5SDimitry Andric // Here is an example. If foo and bar defined below are compiled to the
21*0b57cec5SDimitry Andric // same machine instructions, ICF can and should merge the two, although
22*0b57cec5SDimitry Andric // their relocations point to each other.
23*0b57cec5SDimitry Andric //
24*0b57cec5SDimitry Andric //   void foo() { bar(); }
25*0b57cec5SDimitry Andric //   void bar() { foo(); }
26*0b57cec5SDimitry Andric //
27*0b57cec5SDimitry Andric // If you merge the two, their relocations point to the same section and
28*0b57cec5SDimitry Andric // thus you know they are mergeable, but how do you know they are
29*0b57cec5SDimitry Andric // mergeable in the first place? This is not an easy problem to solve.
30*0b57cec5SDimitry Andric //
31*0b57cec5SDimitry Andric // What we are doing in LLD is to partition sections into equivalence
32*0b57cec5SDimitry Andric // classes. Sections in the same equivalence class when the algorithm
33*0b57cec5SDimitry Andric // terminates are considered identical. Here are details:
34*0b57cec5SDimitry Andric //
35*0b57cec5SDimitry Andric // 1. First, we partition sections using their hash values as keys. Hash
36*0b57cec5SDimitry Andric //    values contain section types, section contents and numbers of
37*0b57cec5SDimitry Andric //    relocations. During this step, relocation targets are not taken into
38*0b57cec5SDimitry Andric //    account. We just put sections that apparently differ into different
39*0b57cec5SDimitry Andric //    equivalence classes.
40*0b57cec5SDimitry Andric //
41*0b57cec5SDimitry Andric // 2. Next, for each equivalence class, we visit sections to compare
42*0b57cec5SDimitry Andric //    relocation targets. Relocation targets are considered equivalent if
43*0b57cec5SDimitry Andric //    their targets are in the same equivalence class. Sections with
44*0b57cec5SDimitry Andric //    different relocation targets are put into different equivalence
45*0b57cec5SDimitry Andric //    clases.
46*0b57cec5SDimitry Andric //
47*0b57cec5SDimitry Andric // 3. If we split an equivalence class in step 2, two relocations
48*0b57cec5SDimitry Andric //    previously target the same equivalence class may now target
49*0b57cec5SDimitry Andric //    different equivalence classes. Therefore, we repeat step 2 until a
50*0b57cec5SDimitry Andric //    convergence is obtained.
51*0b57cec5SDimitry Andric //
52*0b57cec5SDimitry Andric // 4. For each equivalence class C, pick an arbitrary section in C, and
53*0b57cec5SDimitry Andric //    merge all the other sections in C with it.
54*0b57cec5SDimitry Andric //
55*0b57cec5SDimitry Andric // For small programs, this algorithm needs 3-5 iterations. For large
56*0b57cec5SDimitry Andric // programs such as Chromium, it takes more than 20 iterations.
57*0b57cec5SDimitry Andric //
58*0b57cec5SDimitry Andric // This algorithm was mentioned as an "optimistic algorithm" in [1],
59*0b57cec5SDimitry Andric // though gold implements a different algorithm than this.
60*0b57cec5SDimitry Andric //
61*0b57cec5SDimitry Andric // We parallelize each step so that multiple threads can work on different
62*0b57cec5SDimitry Andric // equivalence classes concurrently. That gave us a large performance
63*0b57cec5SDimitry Andric // boost when applying ICF on large programs. For example, MSVC link.exe
64*0b57cec5SDimitry Andric // or GNU gold takes 10-20 seconds to apply ICF on Chromium, whose output
65*0b57cec5SDimitry Andric // size is about 1.5 GB, but LLD can finish it in less than 2 seconds on a
66*0b57cec5SDimitry Andric // 2.8 GHz 40 core machine. Even without threading, LLD's ICF is still
67*0b57cec5SDimitry Andric // faster than MSVC or gold though.
68*0b57cec5SDimitry Andric //
69*0b57cec5SDimitry Andric // [1] Safe ICF: Pointer Safe and Unwinding aware Identical Code Folding
70*0b57cec5SDimitry Andric // in the Gold Linker
71*0b57cec5SDimitry Andric // http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/36912.pdf
72*0b57cec5SDimitry Andric //
73*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
74*0b57cec5SDimitry Andric 
75*0b57cec5SDimitry Andric #include "ICF.h"
76*0b57cec5SDimitry Andric #include "Config.h"
77*0b57cec5SDimitry Andric #include "SymbolTable.h"
78*0b57cec5SDimitry Andric #include "Symbols.h"
79*0b57cec5SDimitry Andric #include "SyntheticSections.h"
80*0b57cec5SDimitry Andric #include "Writer.h"
81*0b57cec5SDimitry Andric #include "lld/Common/Threads.h"
82*0b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
83*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
84*0b57cec5SDimitry Andric #include "llvm/Object/ELF.h"
85*0b57cec5SDimitry Andric #include "llvm/Support/xxhash.h"
86*0b57cec5SDimitry Andric #include <algorithm>
87*0b57cec5SDimitry Andric #include <atomic>
88*0b57cec5SDimitry Andric 
89*0b57cec5SDimitry Andric using namespace lld;
90*0b57cec5SDimitry Andric using namespace lld::elf;
91*0b57cec5SDimitry Andric using namespace llvm;
92*0b57cec5SDimitry Andric using namespace llvm::ELF;
93*0b57cec5SDimitry Andric using namespace llvm::object;
94*0b57cec5SDimitry Andric 
95*0b57cec5SDimitry Andric namespace {
96*0b57cec5SDimitry Andric template <class ELFT> class ICF {
97*0b57cec5SDimitry Andric public:
98*0b57cec5SDimitry Andric   void run();
99*0b57cec5SDimitry Andric 
100*0b57cec5SDimitry Andric private:
101*0b57cec5SDimitry Andric   void segregate(size_t begin, size_t end, bool constant);
102*0b57cec5SDimitry Andric 
103*0b57cec5SDimitry Andric   template <class RelTy>
104*0b57cec5SDimitry Andric   bool constantEq(const InputSection *a, ArrayRef<RelTy> relsA,
105*0b57cec5SDimitry Andric                   const InputSection *b, ArrayRef<RelTy> relsB);
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric   template <class RelTy>
108*0b57cec5SDimitry Andric   bool variableEq(const InputSection *a, ArrayRef<RelTy> relsA,
109*0b57cec5SDimitry Andric                   const InputSection *b, ArrayRef<RelTy> relsB);
110*0b57cec5SDimitry Andric 
111*0b57cec5SDimitry Andric   bool equalsConstant(const InputSection *a, const InputSection *b);
112*0b57cec5SDimitry Andric   bool equalsVariable(const InputSection *a, const InputSection *b);
113*0b57cec5SDimitry Andric 
114*0b57cec5SDimitry Andric   size_t findBoundary(size_t begin, size_t end);
115*0b57cec5SDimitry Andric 
116*0b57cec5SDimitry Andric   void forEachClassRange(size_t begin, size_t end,
117*0b57cec5SDimitry Andric                          llvm::function_ref<void(size_t, size_t)> fn);
118*0b57cec5SDimitry Andric 
119*0b57cec5SDimitry Andric   void forEachClass(llvm::function_ref<void(size_t, size_t)> fn);
120*0b57cec5SDimitry Andric 
121*0b57cec5SDimitry Andric   std::vector<InputSection *> sections;
122*0b57cec5SDimitry Andric 
123*0b57cec5SDimitry Andric   // We repeat the main loop while `Repeat` is true.
124*0b57cec5SDimitry Andric   std::atomic<bool> repeat;
125*0b57cec5SDimitry Andric 
126*0b57cec5SDimitry Andric   // The main loop counter.
127*0b57cec5SDimitry Andric   int cnt = 0;
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric   // We have two locations for equivalence classes. On the first iteration
130*0b57cec5SDimitry Andric   // of the main loop, Class[0] has a valid value, and Class[1] contains
131*0b57cec5SDimitry Andric   // garbage. We read equivalence classes from slot 0 and write to slot 1.
132*0b57cec5SDimitry Andric   // So, Class[0] represents the current class, and Class[1] represents
133*0b57cec5SDimitry Andric   // the next class. On each iteration, we switch their roles and use them
134*0b57cec5SDimitry Andric   // alternately.
135*0b57cec5SDimitry Andric   //
136*0b57cec5SDimitry Andric   // Why are we doing this? Recall that other threads may be working on
137*0b57cec5SDimitry Andric   // other equivalence classes in parallel. They may read sections that we
138*0b57cec5SDimitry Andric   // are updating. We cannot update equivalence classes in place because
139*0b57cec5SDimitry Andric   // it breaks the invariance that all possibly-identical sections must be
140*0b57cec5SDimitry Andric   // in the same equivalence class at any moment. In other words, the for
141*0b57cec5SDimitry Andric   // loop to update equivalence classes is not atomic, and that is
142*0b57cec5SDimitry Andric   // observable from other threads. By writing new classes to other
143*0b57cec5SDimitry Andric   // places, we can keep the invariance.
144*0b57cec5SDimitry Andric   //
145*0b57cec5SDimitry Andric   // Below, `Current` has the index of the current class, and `Next` has
146*0b57cec5SDimitry Andric   // the index of the next class. If threading is enabled, they are either
147*0b57cec5SDimitry Andric   // (0, 1) or (1, 0).
148*0b57cec5SDimitry Andric   //
149*0b57cec5SDimitry Andric   // Note on single-thread: if that's the case, they are always (0, 0)
150*0b57cec5SDimitry Andric   // because we can safely read the next class without worrying about race
151*0b57cec5SDimitry Andric   // conditions. Using the same location makes this algorithm converge
152*0b57cec5SDimitry Andric   // faster because it uses results of the same iteration earlier.
153*0b57cec5SDimitry Andric   int current = 0;
154*0b57cec5SDimitry Andric   int next = 0;
155*0b57cec5SDimitry Andric };
156*0b57cec5SDimitry Andric }
157*0b57cec5SDimitry Andric 
158*0b57cec5SDimitry Andric // Returns true if section S is subject of ICF.
159*0b57cec5SDimitry Andric static bool isEligible(InputSection *s) {
160*0b57cec5SDimitry Andric   if (!s->isLive() || s->keepUnique || !(s->flags & SHF_ALLOC))
161*0b57cec5SDimitry Andric     return false;
162*0b57cec5SDimitry Andric 
163*0b57cec5SDimitry Andric   // Don't merge writable sections. .data.rel.ro sections are marked as writable
164*0b57cec5SDimitry Andric   // but are semantically read-only.
165*0b57cec5SDimitry Andric   if ((s->flags & SHF_WRITE) && s->name != ".data.rel.ro" &&
166*0b57cec5SDimitry Andric       !s->name.startswith(".data.rel.ro."))
167*0b57cec5SDimitry Andric     return false;
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric   // SHF_LINK_ORDER sections are ICF'd as a unit with their dependent sections,
170*0b57cec5SDimitry Andric   // so we don't consider them for ICF individually.
171*0b57cec5SDimitry Andric   if (s->flags & SHF_LINK_ORDER)
172*0b57cec5SDimitry Andric     return false;
173*0b57cec5SDimitry Andric 
174*0b57cec5SDimitry Andric   // Don't merge synthetic sections as their Data member is not valid and empty.
175*0b57cec5SDimitry Andric   // The Data member needs to be valid for ICF as it is used by ICF to determine
176*0b57cec5SDimitry Andric   // the equality of section contents.
177*0b57cec5SDimitry Andric   if (isa<SyntheticSection>(s))
178*0b57cec5SDimitry Andric     return false;
179*0b57cec5SDimitry Andric 
180*0b57cec5SDimitry Andric   // .init and .fini contains instructions that must be executed to initialize
181*0b57cec5SDimitry Andric   // and finalize the process. They cannot and should not be merged.
182*0b57cec5SDimitry Andric   if (s->name == ".init" || s->name == ".fini")
183*0b57cec5SDimitry Andric     return false;
184*0b57cec5SDimitry Andric 
185*0b57cec5SDimitry Andric   // A user program may enumerate sections named with a C identifier using
186*0b57cec5SDimitry Andric   // __start_* and __stop_* symbols. We cannot ICF any such sections because
187*0b57cec5SDimitry Andric   // that could change program semantics.
188*0b57cec5SDimitry Andric   if (isValidCIdentifier(s->name))
189*0b57cec5SDimitry Andric     return false;
190*0b57cec5SDimitry Andric 
191*0b57cec5SDimitry Andric   return true;
192*0b57cec5SDimitry Andric }
193*0b57cec5SDimitry Andric 
194*0b57cec5SDimitry Andric // Split an equivalence class into smaller classes.
195*0b57cec5SDimitry Andric template <class ELFT>
196*0b57cec5SDimitry Andric void ICF<ELFT>::segregate(size_t begin, size_t end, bool constant) {
197*0b57cec5SDimitry Andric   // This loop rearranges sections in [Begin, End) so that all sections
198*0b57cec5SDimitry Andric   // that are equal in terms of equals{Constant,Variable} are contiguous
199*0b57cec5SDimitry Andric   // in [Begin, End).
200*0b57cec5SDimitry Andric   //
201*0b57cec5SDimitry Andric   // The algorithm is quadratic in the worst case, but that is not an
202*0b57cec5SDimitry Andric   // issue in practice because the number of the distinct sections in
203*0b57cec5SDimitry Andric   // each range is usually very small.
204*0b57cec5SDimitry Andric 
205*0b57cec5SDimitry Andric   while (begin < end) {
206*0b57cec5SDimitry Andric     // Divide [Begin, End) into two. Let Mid be the start index of the
207*0b57cec5SDimitry Andric     // second group.
208*0b57cec5SDimitry Andric     auto bound =
209*0b57cec5SDimitry Andric         std::stable_partition(sections.begin() + begin + 1,
210*0b57cec5SDimitry Andric                               sections.begin() + end, [&](InputSection *s) {
211*0b57cec5SDimitry Andric                                 if (constant)
212*0b57cec5SDimitry Andric                                   return equalsConstant(sections[begin], s);
213*0b57cec5SDimitry Andric                                 return equalsVariable(sections[begin], s);
214*0b57cec5SDimitry Andric                               });
215*0b57cec5SDimitry Andric     size_t mid = bound - sections.begin();
216*0b57cec5SDimitry Andric 
217*0b57cec5SDimitry Andric     // Now we split [Begin, End) into [Begin, Mid) and [Mid, End) by
218*0b57cec5SDimitry Andric     // updating the sections in [Begin, Mid). We use Mid as an equivalence
219*0b57cec5SDimitry Andric     // class ID because every group ends with a unique index.
220*0b57cec5SDimitry Andric     for (size_t i = begin; i < mid; ++i)
221*0b57cec5SDimitry Andric       sections[i]->eqClass[next] = mid;
222*0b57cec5SDimitry Andric 
223*0b57cec5SDimitry Andric     // If we created a group, we need to iterate the main loop again.
224*0b57cec5SDimitry Andric     if (mid != end)
225*0b57cec5SDimitry Andric       repeat = true;
226*0b57cec5SDimitry Andric 
227*0b57cec5SDimitry Andric     begin = mid;
228*0b57cec5SDimitry Andric   }
229*0b57cec5SDimitry Andric }
230*0b57cec5SDimitry Andric 
231*0b57cec5SDimitry Andric // Compare two lists of relocations.
232*0b57cec5SDimitry Andric template <class ELFT>
233*0b57cec5SDimitry Andric template <class RelTy>
234*0b57cec5SDimitry Andric bool ICF<ELFT>::constantEq(const InputSection *secA, ArrayRef<RelTy> ra,
235*0b57cec5SDimitry Andric                            const InputSection *secB, ArrayRef<RelTy> rb) {
236*0b57cec5SDimitry Andric   for (size_t i = 0; i < ra.size(); ++i) {
237*0b57cec5SDimitry Andric     if (ra[i].r_offset != rb[i].r_offset ||
238*0b57cec5SDimitry Andric         ra[i].getType(config->isMips64EL) != rb[i].getType(config->isMips64EL))
239*0b57cec5SDimitry Andric       return false;
240*0b57cec5SDimitry Andric 
241*0b57cec5SDimitry Andric     uint64_t addA = getAddend<ELFT>(ra[i]);
242*0b57cec5SDimitry Andric     uint64_t addB = getAddend<ELFT>(rb[i]);
243*0b57cec5SDimitry Andric 
244*0b57cec5SDimitry Andric     Symbol &sa = secA->template getFile<ELFT>()->getRelocTargetSym(ra[i]);
245*0b57cec5SDimitry Andric     Symbol &sb = secB->template getFile<ELFT>()->getRelocTargetSym(rb[i]);
246*0b57cec5SDimitry Andric     if (&sa == &sb) {
247*0b57cec5SDimitry Andric       if (addA == addB)
248*0b57cec5SDimitry Andric         continue;
249*0b57cec5SDimitry Andric       return false;
250*0b57cec5SDimitry Andric     }
251*0b57cec5SDimitry Andric 
252*0b57cec5SDimitry Andric     auto *da = dyn_cast<Defined>(&sa);
253*0b57cec5SDimitry Andric     auto *db = dyn_cast<Defined>(&sb);
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric     // Placeholder symbols generated by linker scripts look the same now but
256*0b57cec5SDimitry Andric     // may have different values later.
257*0b57cec5SDimitry Andric     if (!da || !db || da->scriptDefined || db->scriptDefined)
258*0b57cec5SDimitry Andric       return false;
259*0b57cec5SDimitry Andric 
260*0b57cec5SDimitry Andric     // Relocations referring to absolute symbols are constant-equal if their
261*0b57cec5SDimitry Andric     // values are equal.
262*0b57cec5SDimitry Andric     if (!da->section && !db->section && da->value + addA == db->value + addB)
263*0b57cec5SDimitry Andric       continue;
264*0b57cec5SDimitry Andric     if (!da->section || !db->section)
265*0b57cec5SDimitry Andric       return false;
266*0b57cec5SDimitry Andric 
267*0b57cec5SDimitry Andric     if (da->section->kind() != db->section->kind())
268*0b57cec5SDimitry Andric       return false;
269*0b57cec5SDimitry Andric 
270*0b57cec5SDimitry Andric     // Relocations referring to InputSections are constant-equal if their
271*0b57cec5SDimitry Andric     // section offsets are equal.
272*0b57cec5SDimitry Andric     if (isa<InputSection>(da->section)) {
273*0b57cec5SDimitry Andric       if (da->value + addA == db->value + addB)
274*0b57cec5SDimitry Andric         continue;
275*0b57cec5SDimitry Andric       return false;
276*0b57cec5SDimitry Andric     }
277*0b57cec5SDimitry Andric 
278*0b57cec5SDimitry Andric     // Relocations referring to MergeInputSections are constant-equal if their
279*0b57cec5SDimitry Andric     // offsets in the output section are equal.
280*0b57cec5SDimitry Andric     auto *x = dyn_cast<MergeInputSection>(da->section);
281*0b57cec5SDimitry Andric     if (!x)
282*0b57cec5SDimitry Andric       return false;
283*0b57cec5SDimitry Andric     auto *y = cast<MergeInputSection>(db->section);
284*0b57cec5SDimitry Andric     if (x->getParent() != y->getParent())
285*0b57cec5SDimitry Andric       return false;
286*0b57cec5SDimitry Andric 
287*0b57cec5SDimitry Andric     uint64_t offsetA =
288*0b57cec5SDimitry Andric         sa.isSection() ? x->getOffset(addA) : x->getOffset(da->value) + addA;
289*0b57cec5SDimitry Andric     uint64_t offsetB =
290*0b57cec5SDimitry Andric         sb.isSection() ? y->getOffset(addB) : y->getOffset(db->value) + addB;
291*0b57cec5SDimitry Andric     if (offsetA != offsetB)
292*0b57cec5SDimitry Andric       return false;
293*0b57cec5SDimitry Andric   }
294*0b57cec5SDimitry Andric 
295*0b57cec5SDimitry Andric   return true;
296*0b57cec5SDimitry Andric }
297*0b57cec5SDimitry Andric 
298*0b57cec5SDimitry Andric // Compare "non-moving" part of two InputSections, namely everything
299*0b57cec5SDimitry Andric // except relocation targets.
300*0b57cec5SDimitry Andric template <class ELFT>
301*0b57cec5SDimitry Andric bool ICF<ELFT>::equalsConstant(const InputSection *a, const InputSection *b) {
302*0b57cec5SDimitry Andric   if (a->numRelocations != b->numRelocations || a->flags != b->flags ||
303*0b57cec5SDimitry Andric       a->getSize() != b->getSize() || a->data() != b->data())
304*0b57cec5SDimitry Andric     return false;
305*0b57cec5SDimitry Andric 
306*0b57cec5SDimitry Andric   // If two sections have different output sections, we cannot merge them.
307*0b57cec5SDimitry Andric   // FIXME: This doesn't do the right thing in the case where there is a linker
308*0b57cec5SDimitry Andric   // script. We probably need to move output section assignment before ICF to
309*0b57cec5SDimitry Andric   // get the correct behaviour here.
310*0b57cec5SDimitry Andric   if (getOutputSectionName(a) != getOutputSectionName(b))
311*0b57cec5SDimitry Andric     return false;
312*0b57cec5SDimitry Andric 
313*0b57cec5SDimitry Andric   if (a->areRelocsRela)
314*0b57cec5SDimitry Andric     return constantEq(a, a->template relas<ELFT>(), b,
315*0b57cec5SDimitry Andric                       b->template relas<ELFT>());
316*0b57cec5SDimitry Andric   return constantEq(a, a->template rels<ELFT>(), b, b->template rels<ELFT>());
317*0b57cec5SDimitry Andric }
318*0b57cec5SDimitry Andric 
319*0b57cec5SDimitry Andric // Compare two lists of relocations. Returns true if all pairs of
320*0b57cec5SDimitry Andric // relocations point to the same section in terms of ICF.
321*0b57cec5SDimitry Andric template <class ELFT>
322*0b57cec5SDimitry Andric template <class RelTy>
323*0b57cec5SDimitry Andric bool ICF<ELFT>::variableEq(const InputSection *secA, ArrayRef<RelTy> ra,
324*0b57cec5SDimitry Andric                            const InputSection *secB, ArrayRef<RelTy> rb) {
325*0b57cec5SDimitry Andric   assert(ra.size() == rb.size());
326*0b57cec5SDimitry Andric 
327*0b57cec5SDimitry Andric   for (size_t i = 0; i < ra.size(); ++i) {
328*0b57cec5SDimitry Andric     // The two sections must be identical.
329*0b57cec5SDimitry Andric     Symbol &sa = secA->template getFile<ELFT>()->getRelocTargetSym(ra[i]);
330*0b57cec5SDimitry Andric     Symbol &sb = secB->template getFile<ELFT>()->getRelocTargetSym(rb[i]);
331*0b57cec5SDimitry Andric     if (&sa == &sb)
332*0b57cec5SDimitry Andric       continue;
333*0b57cec5SDimitry Andric 
334*0b57cec5SDimitry Andric     auto *da = cast<Defined>(&sa);
335*0b57cec5SDimitry Andric     auto *db = cast<Defined>(&sb);
336*0b57cec5SDimitry Andric 
337*0b57cec5SDimitry Andric     // We already dealt with absolute and non-InputSection symbols in
338*0b57cec5SDimitry Andric     // constantEq, and for InputSections we have already checked everything
339*0b57cec5SDimitry Andric     // except the equivalence class.
340*0b57cec5SDimitry Andric     if (!da->section)
341*0b57cec5SDimitry Andric       continue;
342*0b57cec5SDimitry Andric     auto *x = dyn_cast<InputSection>(da->section);
343*0b57cec5SDimitry Andric     if (!x)
344*0b57cec5SDimitry Andric       continue;
345*0b57cec5SDimitry Andric     auto *y = cast<InputSection>(db->section);
346*0b57cec5SDimitry Andric 
347*0b57cec5SDimitry Andric     // Ineligible sections are in the special equivalence class 0.
348*0b57cec5SDimitry Andric     // They can never be the same in terms of the equivalence class.
349*0b57cec5SDimitry Andric     if (x->eqClass[current] == 0)
350*0b57cec5SDimitry Andric       return false;
351*0b57cec5SDimitry Andric     if (x->eqClass[current] != y->eqClass[current])
352*0b57cec5SDimitry Andric       return false;
353*0b57cec5SDimitry Andric   };
354*0b57cec5SDimitry Andric 
355*0b57cec5SDimitry Andric   return true;
356*0b57cec5SDimitry Andric }
357*0b57cec5SDimitry Andric 
358*0b57cec5SDimitry Andric // Compare "moving" part of two InputSections, namely relocation targets.
359*0b57cec5SDimitry Andric template <class ELFT>
360*0b57cec5SDimitry Andric bool ICF<ELFT>::equalsVariable(const InputSection *a, const InputSection *b) {
361*0b57cec5SDimitry Andric   if (a->areRelocsRela)
362*0b57cec5SDimitry Andric     return variableEq(a, a->template relas<ELFT>(), b,
363*0b57cec5SDimitry Andric                       b->template relas<ELFT>());
364*0b57cec5SDimitry Andric   return variableEq(a, a->template rels<ELFT>(), b, b->template rels<ELFT>());
365*0b57cec5SDimitry Andric }
366*0b57cec5SDimitry Andric 
367*0b57cec5SDimitry Andric template <class ELFT> size_t ICF<ELFT>::findBoundary(size_t begin, size_t end) {
368*0b57cec5SDimitry Andric   uint32_t eqClass = sections[begin]->eqClass[current];
369*0b57cec5SDimitry Andric   for (size_t i = begin + 1; i < end; ++i)
370*0b57cec5SDimitry Andric     if (eqClass != sections[i]->eqClass[current])
371*0b57cec5SDimitry Andric       return i;
372*0b57cec5SDimitry Andric   return end;
373*0b57cec5SDimitry Andric }
374*0b57cec5SDimitry Andric 
375*0b57cec5SDimitry Andric // Sections in the same equivalence class are contiguous in Sections
376*0b57cec5SDimitry Andric // vector. Therefore, Sections vector can be considered as contiguous
377*0b57cec5SDimitry Andric // groups of sections, grouped by the class.
378*0b57cec5SDimitry Andric //
379*0b57cec5SDimitry Andric // This function calls Fn on every group within [Begin, End).
380*0b57cec5SDimitry Andric template <class ELFT>
381*0b57cec5SDimitry Andric void ICF<ELFT>::forEachClassRange(size_t begin, size_t end,
382*0b57cec5SDimitry Andric                                   llvm::function_ref<void(size_t, size_t)> fn) {
383*0b57cec5SDimitry Andric   while (begin < end) {
384*0b57cec5SDimitry Andric     size_t mid = findBoundary(begin, end);
385*0b57cec5SDimitry Andric     fn(begin, mid);
386*0b57cec5SDimitry Andric     begin = mid;
387*0b57cec5SDimitry Andric   }
388*0b57cec5SDimitry Andric }
389*0b57cec5SDimitry Andric 
390*0b57cec5SDimitry Andric // Call Fn on each equivalence class.
391*0b57cec5SDimitry Andric template <class ELFT>
392*0b57cec5SDimitry Andric void ICF<ELFT>::forEachClass(llvm::function_ref<void(size_t, size_t)> fn) {
393*0b57cec5SDimitry Andric   // If threading is disabled or the number of sections are
394*0b57cec5SDimitry Andric   // too small to use threading, call Fn sequentially.
395*0b57cec5SDimitry Andric   if (!threadsEnabled || sections.size() < 1024) {
396*0b57cec5SDimitry Andric     forEachClassRange(0, sections.size(), fn);
397*0b57cec5SDimitry Andric     ++cnt;
398*0b57cec5SDimitry Andric     return;
399*0b57cec5SDimitry Andric   }
400*0b57cec5SDimitry Andric 
401*0b57cec5SDimitry Andric   current = cnt % 2;
402*0b57cec5SDimitry Andric   next = (cnt + 1) % 2;
403*0b57cec5SDimitry Andric 
404*0b57cec5SDimitry Andric   // Shard into non-overlapping intervals, and call Fn in parallel.
405*0b57cec5SDimitry Andric   // The sharding must be completed before any calls to Fn are made
406*0b57cec5SDimitry Andric   // so that Fn can modify the Chunks in its shard without causing data
407*0b57cec5SDimitry Andric   // races.
408*0b57cec5SDimitry Andric   const size_t numShards = 256;
409*0b57cec5SDimitry Andric   size_t step = sections.size() / numShards;
410*0b57cec5SDimitry Andric   size_t boundaries[numShards + 1];
411*0b57cec5SDimitry Andric   boundaries[0] = 0;
412*0b57cec5SDimitry Andric   boundaries[numShards] = sections.size();
413*0b57cec5SDimitry Andric 
414*0b57cec5SDimitry Andric   parallelForEachN(1, numShards, [&](size_t i) {
415*0b57cec5SDimitry Andric     boundaries[i] = findBoundary((i - 1) * step, sections.size());
416*0b57cec5SDimitry Andric   });
417*0b57cec5SDimitry Andric 
418*0b57cec5SDimitry Andric   parallelForEachN(1, numShards + 1, [&](size_t i) {
419*0b57cec5SDimitry Andric     if (boundaries[i - 1] < boundaries[i])
420*0b57cec5SDimitry Andric       forEachClassRange(boundaries[i - 1], boundaries[i], fn);
421*0b57cec5SDimitry Andric   });
422*0b57cec5SDimitry Andric   ++cnt;
423*0b57cec5SDimitry Andric }
424*0b57cec5SDimitry Andric 
425*0b57cec5SDimitry Andric // Combine the hashes of the sections referenced by the given section into its
426*0b57cec5SDimitry Andric // hash.
427*0b57cec5SDimitry Andric template <class ELFT, class RelTy>
428*0b57cec5SDimitry Andric static void combineRelocHashes(unsigned cnt, InputSection *isec,
429*0b57cec5SDimitry Andric                                ArrayRef<RelTy> rels) {
430*0b57cec5SDimitry Andric   uint32_t hash = isec->eqClass[cnt % 2];
431*0b57cec5SDimitry Andric   for (RelTy rel : rels) {
432*0b57cec5SDimitry Andric     Symbol &s = isec->template getFile<ELFT>()->getRelocTargetSym(rel);
433*0b57cec5SDimitry Andric     if (auto *d = dyn_cast<Defined>(&s))
434*0b57cec5SDimitry Andric       if (auto *relSec = dyn_cast_or_null<InputSection>(d->section))
435*0b57cec5SDimitry Andric         hash += relSec->eqClass[cnt % 2];
436*0b57cec5SDimitry Andric   }
437*0b57cec5SDimitry Andric   // Set MSB to 1 to avoid collisions with non-hash IDs.
438*0b57cec5SDimitry Andric   isec->eqClass[(cnt + 1) % 2] = hash | (1U << 31);
439*0b57cec5SDimitry Andric }
440*0b57cec5SDimitry Andric 
441*0b57cec5SDimitry Andric static void print(const Twine &s) {
442*0b57cec5SDimitry Andric   if (config->printIcfSections)
443*0b57cec5SDimitry Andric     message(s);
444*0b57cec5SDimitry Andric }
445*0b57cec5SDimitry Andric 
446*0b57cec5SDimitry Andric // The main function of ICF.
447*0b57cec5SDimitry Andric template <class ELFT> void ICF<ELFT>::run() {
448*0b57cec5SDimitry Andric   // Collect sections to merge.
449*0b57cec5SDimitry Andric   for (InputSectionBase *sec : inputSections)
450*0b57cec5SDimitry Andric     if (auto *s = dyn_cast<InputSection>(sec))
451*0b57cec5SDimitry Andric       if (isEligible(s))
452*0b57cec5SDimitry Andric         sections.push_back(s);
453*0b57cec5SDimitry Andric 
454*0b57cec5SDimitry Andric   // Initially, we use hash values to partition sections.
455*0b57cec5SDimitry Andric   parallelForEach(sections, [&](InputSection *s) {
456*0b57cec5SDimitry Andric     s->eqClass[0] = xxHash64(s->data());
457*0b57cec5SDimitry Andric   });
458*0b57cec5SDimitry Andric 
459*0b57cec5SDimitry Andric   for (unsigned cnt = 0; cnt != 2; ++cnt) {
460*0b57cec5SDimitry Andric     parallelForEach(sections, [&](InputSection *s) {
461*0b57cec5SDimitry Andric       if (s->areRelocsRela)
462*0b57cec5SDimitry Andric         combineRelocHashes<ELFT>(cnt, s, s->template relas<ELFT>());
463*0b57cec5SDimitry Andric       else
464*0b57cec5SDimitry Andric         combineRelocHashes<ELFT>(cnt, s, s->template rels<ELFT>());
465*0b57cec5SDimitry Andric     });
466*0b57cec5SDimitry Andric   }
467*0b57cec5SDimitry Andric 
468*0b57cec5SDimitry Andric   // From now on, sections in Sections vector are ordered so that sections
469*0b57cec5SDimitry Andric   // in the same equivalence class are consecutive in the vector.
470*0b57cec5SDimitry Andric   llvm::stable_sort(sections, [](const InputSection *a, const InputSection *b) {
471*0b57cec5SDimitry Andric     return a->eqClass[0] < b->eqClass[0];
472*0b57cec5SDimitry Andric   });
473*0b57cec5SDimitry Andric 
474*0b57cec5SDimitry Andric   // Compare static contents and assign unique IDs for each static content.
475*0b57cec5SDimitry Andric   forEachClass([&](size_t begin, size_t end) { segregate(begin, end, true); });
476*0b57cec5SDimitry Andric 
477*0b57cec5SDimitry Andric   // Split groups by comparing relocations until convergence is obtained.
478*0b57cec5SDimitry Andric   do {
479*0b57cec5SDimitry Andric     repeat = false;
480*0b57cec5SDimitry Andric     forEachClass(
481*0b57cec5SDimitry Andric         [&](size_t begin, size_t end) { segregate(begin, end, false); });
482*0b57cec5SDimitry Andric   } while (repeat);
483*0b57cec5SDimitry Andric 
484*0b57cec5SDimitry Andric   log("ICF needed " + Twine(cnt) + " iterations");
485*0b57cec5SDimitry Andric 
486*0b57cec5SDimitry Andric   // Merge sections by the equivalence class.
487*0b57cec5SDimitry Andric   forEachClassRange(0, sections.size(), [&](size_t begin, size_t end) {
488*0b57cec5SDimitry Andric     if (end - begin == 1)
489*0b57cec5SDimitry Andric       return;
490*0b57cec5SDimitry Andric     print("selected section " + toString(sections[begin]));
491*0b57cec5SDimitry Andric     for (size_t i = begin + 1; i < end; ++i) {
492*0b57cec5SDimitry Andric       print("  removing identical section " + toString(sections[i]));
493*0b57cec5SDimitry Andric       sections[begin]->replace(sections[i]);
494*0b57cec5SDimitry Andric 
495*0b57cec5SDimitry Andric       // At this point we know sections merged are fully identical and hence
496*0b57cec5SDimitry Andric       // we want to remove duplicate implicit dependencies such as link order
497*0b57cec5SDimitry Andric       // and relocation sections.
498*0b57cec5SDimitry Andric       for (InputSection *isec : sections[i]->dependentSections)
499*0b57cec5SDimitry Andric         isec->markDead();
500*0b57cec5SDimitry Andric     }
501*0b57cec5SDimitry Andric   });
502*0b57cec5SDimitry Andric }
503*0b57cec5SDimitry Andric 
504*0b57cec5SDimitry Andric // ICF entry point function.
505*0b57cec5SDimitry Andric template <class ELFT> void elf::doIcf() { ICF<ELFT>().run(); }
506*0b57cec5SDimitry Andric 
507*0b57cec5SDimitry Andric template void elf::doIcf<ELF32LE>();
508*0b57cec5SDimitry Andric template void elf::doIcf<ELF32BE>();
509*0b57cec5SDimitry Andric template void elf::doIcf<ELF64LE>();
510*0b57cec5SDimitry Andric template void elf::doIcf<ELF64BE>();
511