xref: /freebsd/contrib/llvm-project/lld/ELF/ICF.cpp (revision 6e516c87b6d779911edde7481d8aef165b837a03)
10b57cec5SDimitry Andric //===- ICF.cpp ------------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // ICF is short for Identical Code Folding. This is a size optimization to
100b57cec5SDimitry Andric // identify and merge two or more read-only sections (typically functions)
110b57cec5SDimitry Andric // that happened to have the same contents. It usually reduces output size
120b57cec5SDimitry Andric // by a few percent.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric // In ICF, two sections are considered identical if they have the same
150b57cec5SDimitry Andric // section flags, section data, and relocations. Relocations are tricky,
160b57cec5SDimitry Andric // because two relocations are considered the same if they have the same
170b57cec5SDimitry Andric // relocation types, values, and if they point to the same sections *in
180b57cec5SDimitry Andric // terms of ICF*.
190b57cec5SDimitry Andric //
200b57cec5SDimitry Andric // Here is an example. If foo and bar defined below are compiled to the
210b57cec5SDimitry Andric // same machine instructions, ICF can and should merge the two, although
220b57cec5SDimitry Andric // their relocations point to each other.
230b57cec5SDimitry Andric //
240b57cec5SDimitry Andric //   void foo() { bar(); }
250b57cec5SDimitry Andric //   void bar() { foo(); }
260b57cec5SDimitry Andric //
270b57cec5SDimitry Andric // If you merge the two, their relocations point to the same section and
280b57cec5SDimitry Andric // thus you know they are mergeable, but how do you know they are
290b57cec5SDimitry Andric // mergeable in the first place? This is not an easy problem to solve.
300b57cec5SDimitry Andric //
310b57cec5SDimitry Andric // What we are doing in LLD is to partition sections into equivalence
320b57cec5SDimitry Andric // classes. Sections in the same equivalence class when the algorithm
330b57cec5SDimitry Andric // terminates are considered identical. Here are details:
340b57cec5SDimitry Andric //
350b57cec5SDimitry Andric // 1. First, we partition sections using their hash values as keys. Hash
360b57cec5SDimitry Andric //    values contain section types, section contents and numbers of
370b57cec5SDimitry Andric //    relocations. During this step, relocation targets are not taken into
380b57cec5SDimitry Andric //    account. We just put sections that apparently differ into different
390b57cec5SDimitry Andric //    equivalence classes.
400b57cec5SDimitry Andric //
410b57cec5SDimitry Andric // 2. Next, for each equivalence class, we visit sections to compare
420b57cec5SDimitry Andric //    relocation targets. Relocation targets are considered equivalent if
430b57cec5SDimitry Andric //    their targets are in the same equivalence class. Sections with
440b57cec5SDimitry Andric //    different relocation targets are put into different equivalence
45480093f4SDimitry Andric //    classes.
460b57cec5SDimitry Andric //
470b57cec5SDimitry Andric // 3. If we split an equivalence class in step 2, two relocations
480b57cec5SDimitry Andric //    previously target the same equivalence class may now target
490b57cec5SDimitry Andric //    different equivalence classes. Therefore, we repeat step 2 until a
500b57cec5SDimitry Andric //    convergence is obtained.
510b57cec5SDimitry Andric //
520b57cec5SDimitry Andric // 4. For each equivalence class C, pick an arbitrary section in C, and
530b57cec5SDimitry Andric //    merge all the other sections in C with it.
540b57cec5SDimitry Andric //
550b57cec5SDimitry Andric // For small programs, this algorithm needs 3-5 iterations. For large
560b57cec5SDimitry Andric // programs such as Chromium, it takes more than 20 iterations.
570b57cec5SDimitry Andric //
580b57cec5SDimitry Andric // This algorithm was mentioned as an "optimistic algorithm" in [1],
590b57cec5SDimitry Andric // though gold implements a different algorithm than this.
600b57cec5SDimitry Andric //
610b57cec5SDimitry Andric // We parallelize each step so that multiple threads can work on different
620b57cec5SDimitry Andric // equivalence classes concurrently. That gave us a large performance
630b57cec5SDimitry Andric // boost when applying ICF on large programs. For example, MSVC link.exe
640b57cec5SDimitry Andric // or GNU gold takes 10-20 seconds to apply ICF on Chromium, whose output
650b57cec5SDimitry Andric // size is about 1.5 GB, but LLD can finish it in less than 2 seconds on a
660b57cec5SDimitry Andric // 2.8 GHz 40 core machine. Even without threading, LLD's ICF is still
670b57cec5SDimitry Andric // faster than MSVC or gold though.
680b57cec5SDimitry Andric //
690b57cec5SDimitry Andric // [1] Safe ICF: Pointer Safe and Unwinding aware Identical Code Folding
700b57cec5SDimitry Andric // in the Gold Linker
710b57cec5SDimitry Andric // http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/36912.pdf
720b57cec5SDimitry Andric //
730b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric #include "ICF.h"
760b57cec5SDimitry Andric #include "Config.h"
7781ad6265SDimitry Andric #include "InputFiles.h"
7885868e8aSDimitry Andric #include "LinkerScript.h"
7985868e8aSDimitry Andric #include "OutputSections.h"
800b57cec5SDimitry Andric #include "SymbolTable.h"
810b57cec5SDimitry Andric #include "Symbols.h"
820b57cec5SDimitry Andric #include "SyntheticSections.h"
830b57cec5SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
840b57cec5SDimitry Andric #include "llvm/Object/ELF.h"
855ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
865ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h"
870b57cec5SDimitry Andric #include "llvm/Support/xxhash.h"
880b57cec5SDimitry Andric #include <algorithm>
890b57cec5SDimitry Andric #include <atomic>
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric using namespace llvm;
920b57cec5SDimitry Andric using namespace llvm::ELF;
930b57cec5SDimitry Andric using namespace llvm::object;
945ffd83dbSDimitry Andric using namespace lld;
955ffd83dbSDimitry Andric using namespace lld::elf;
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric namespace {
980b57cec5SDimitry Andric template <class ELFT> class ICF {
990b57cec5SDimitry Andric public:
1000b57cec5SDimitry Andric   void run();
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric private:
103e8d8bef9SDimitry Andric   void segregate(size_t begin, size_t end, uint32_t eqClassBase, bool constant);
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   template <class RelTy>
10652418fc2SDimitry Andric   bool constantEq(const InputSection *a, Relocs<RelTy> relsA,
10752418fc2SDimitry Andric                   const InputSection *b, Relocs<RelTy> relsB);
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   template <class RelTy>
11052418fc2SDimitry Andric   bool variableEq(const InputSection *a, Relocs<RelTy> relsA,
11152418fc2SDimitry Andric                   const InputSection *b, Relocs<RelTy> relsB);
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric   bool equalsConstant(const InputSection *a, const InputSection *b);
1140b57cec5SDimitry Andric   bool equalsVariable(const InputSection *a, const InputSection *b);
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric   size_t findBoundary(size_t begin, size_t end);
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   void forEachClassRange(size_t begin, size_t end,
1190b57cec5SDimitry Andric                          llvm::function_ref<void(size_t, size_t)> fn);
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   void forEachClass(llvm::function_ref<void(size_t, size_t)> fn);
1220b57cec5SDimitry Andric 
1231fd87a68SDimitry Andric   SmallVector<InputSection *, 0> sections;
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // We repeat the main loop while `Repeat` is true.
1260b57cec5SDimitry Andric   std::atomic<bool> repeat;
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   // The main loop counter.
1290b57cec5SDimitry Andric   int cnt = 0;
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   // We have two locations for equivalence classes. On the first iteration
1320b57cec5SDimitry Andric   // of the main loop, Class[0] has a valid value, and Class[1] contains
1330b57cec5SDimitry Andric   // garbage. We read equivalence classes from slot 0 and write to slot 1.
1340b57cec5SDimitry Andric   // So, Class[0] represents the current class, and Class[1] represents
1350b57cec5SDimitry Andric   // the next class. On each iteration, we switch their roles and use them
1360b57cec5SDimitry Andric   // alternately.
1370b57cec5SDimitry Andric   //
1380b57cec5SDimitry Andric   // Why are we doing this? Recall that other threads may be working on
1390b57cec5SDimitry Andric   // other equivalence classes in parallel. They may read sections that we
1400b57cec5SDimitry Andric   // are updating. We cannot update equivalence classes in place because
1410b57cec5SDimitry Andric   // it breaks the invariance that all possibly-identical sections must be
1420b57cec5SDimitry Andric   // in the same equivalence class at any moment. In other words, the for
1430b57cec5SDimitry Andric   // loop to update equivalence classes is not atomic, and that is
1440b57cec5SDimitry Andric   // observable from other threads. By writing new classes to other
1450b57cec5SDimitry Andric   // places, we can keep the invariance.
1460b57cec5SDimitry Andric   //
1470b57cec5SDimitry Andric   // Below, `Current` has the index of the current class, and `Next` has
1480b57cec5SDimitry Andric   // the index of the next class. If threading is enabled, they are either
1490b57cec5SDimitry Andric   // (0, 1) or (1, 0).
1500b57cec5SDimitry Andric   //
1510b57cec5SDimitry Andric   // Note on single-thread: if that's the case, they are always (0, 0)
1520b57cec5SDimitry Andric   // because we can safely read the next class without worrying about race
1530b57cec5SDimitry Andric   // conditions. Using the same location makes this algorithm converge
1540b57cec5SDimitry Andric   // faster because it uses results of the same iteration earlier.
1550b57cec5SDimitry Andric   int current = 0;
1560b57cec5SDimitry Andric   int next = 0;
1570b57cec5SDimitry Andric };
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric // Returns true if section S is subject of ICF.
isEligible(InputSection * s)1610b57cec5SDimitry Andric static bool isEligible(InputSection *s) {
1620b57cec5SDimitry Andric   if (!s->isLive() || s->keepUnique || !(s->flags & SHF_ALLOC))
1630b57cec5SDimitry Andric     return false;
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   // Don't merge writable sections. .data.rel.ro sections are marked as writable
1660b57cec5SDimitry Andric   // but are semantically read-only.
1670b57cec5SDimitry Andric   if ((s->flags & SHF_WRITE) && s->name != ".data.rel.ro" &&
16806c3fb27SDimitry Andric       !s->name.starts_with(".data.rel.ro."))
1690b57cec5SDimitry Andric     return false;
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   // SHF_LINK_ORDER sections are ICF'd as a unit with their dependent sections,
1720b57cec5SDimitry Andric   // so we don't consider them for ICF individually.
1730b57cec5SDimitry Andric   if (s->flags & SHF_LINK_ORDER)
1740b57cec5SDimitry Andric     return false;
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   // Don't merge synthetic sections as their Data member is not valid and empty.
1770b57cec5SDimitry Andric   // The Data member needs to be valid for ICF as it is used by ICF to determine
1780b57cec5SDimitry Andric   // the equality of section contents.
1790b57cec5SDimitry Andric   if (isa<SyntheticSection>(s))
1800b57cec5SDimitry Andric     return false;
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   // .init and .fini contains instructions that must be executed to initialize
1830b57cec5SDimitry Andric   // and finalize the process. They cannot and should not be merged.
1840b57cec5SDimitry Andric   if (s->name == ".init" || s->name == ".fini")
1850b57cec5SDimitry Andric     return false;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   // A user program may enumerate sections named with a C identifier using
1880b57cec5SDimitry Andric   // __start_* and __stop_* symbols. We cannot ICF any such sections because
1890b57cec5SDimitry Andric   // that could change program semantics.
1900b57cec5SDimitry Andric   if (isValidCIdentifier(s->name))
1910b57cec5SDimitry Andric     return false;
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   return true;
1940b57cec5SDimitry Andric }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric // Split an equivalence class into smaller classes.
1970b57cec5SDimitry Andric template <class ELFT>
segregate(size_t begin,size_t end,uint32_t eqClassBase,bool constant)198e8d8bef9SDimitry Andric void ICF<ELFT>::segregate(size_t begin, size_t end, uint32_t eqClassBase,
199e8d8bef9SDimitry Andric                           bool constant) {
2000b57cec5SDimitry Andric   // This loop rearranges sections in [Begin, End) so that all sections
2010b57cec5SDimitry Andric   // that are equal in terms of equals{Constant,Variable} are contiguous
2020b57cec5SDimitry Andric   // in [Begin, End).
2030b57cec5SDimitry Andric   //
2040b57cec5SDimitry Andric   // The algorithm is quadratic in the worst case, but that is not an
2050b57cec5SDimitry Andric   // issue in practice because the number of the distinct sections in
2060b57cec5SDimitry Andric   // each range is usually very small.
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   while (begin < end) {
2090b57cec5SDimitry Andric     // Divide [Begin, End) into two. Let Mid be the start index of the
2100b57cec5SDimitry Andric     // second group.
2110b57cec5SDimitry Andric     auto bound =
2120b57cec5SDimitry Andric         std::stable_partition(sections.begin() + begin + 1,
2130b57cec5SDimitry Andric                               sections.begin() + end, [&](InputSection *s) {
2140b57cec5SDimitry Andric                                 if (constant)
2150b57cec5SDimitry Andric                                   return equalsConstant(sections[begin], s);
2160b57cec5SDimitry Andric                                 return equalsVariable(sections[begin], s);
2170b57cec5SDimitry Andric                               });
2180b57cec5SDimitry Andric     size_t mid = bound - sections.begin();
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric     // Now we split [Begin, End) into [Begin, Mid) and [Mid, End) by
221e8d8bef9SDimitry Andric     // updating the sections in [Begin, Mid). We use Mid as the basis for
222e8d8bef9SDimitry Andric     // the equivalence class ID because every group ends with a unique index.
223e8d8bef9SDimitry Andric     // Add this to eqClassBase to avoid equality with unique IDs.
2240b57cec5SDimitry Andric     for (size_t i = begin; i < mid; ++i)
225e8d8bef9SDimitry Andric       sections[i]->eqClass[next] = eqClassBase + mid;
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric     // If we created a group, we need to iterate the main loop again.
2280b57cec5SDimitry Andric     if (mid != end)
2290b57cec5SDimitry Andric       repeat = true;
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric     begin = mid;
2320b57cec5SDimitry Andric   }
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric // Compare two lists of relocations.
2360b57cec5SDimitry Andric template <class ELFT>
2370b57cec5SDimitry Andric template <class RelTy>
constantEq(const InputSection * secA,Relocs<RelTy> ra,const InputSection * secB,Relocs<RelTy> rb)23852418fc2SDimitry Andric bool ICF<ELFT>::constantEq(const InputSection *secA, Relocs<RelTy> ra,
23952418fc2SDimitry Andric                            const InputSection *secB, Relocs<RelTy> rb) {
240349cc55cSDimitry Andric   if (ra.size() != rb.size())
241349cc55cSDimitry Andric     return false;
2420fca6ea1SDimitry Andric   auto rai = ra.begin(), rae = ra.end(), rbi = rb.begin();
2430fca6ea1SDimitry Andric   for (; rai != rae; ++rai, ++rbi) {
2440fca6ea1SDimitry Andric     if (rai->r_offset != rbi->r_offset ||
2450fca6ea1SDimitry Andric         rai->getType(config->isMips64EL) != rbi->getType(config->isMips64EL))
2460b57cec5SDimitry Andric       return false;
2470b57cec5SDimitry Andric 
2480fca6ea1SDimitry Andric     uint64_t addA = getAddend<ELFT>(*rai);
2490fca6ea1SDimitry Andric     uint64_t addB = getAddend<ELFT>(*rbi);
2500b57cec5SDimitry Andric 
2510fca6ea1SDimitry Andric     Symbol &sa = secA->file->getRelocTargetSym(*rai);
2520fca6ea1SDimitry Andric     Symbol &sb = secB->file->getRelocTargetSym(*rbi);
2530b57cec5SDimitry Andric     if (&sa == &sb) {
2540b57cec5SDimitry Andric       if (addA == addB)
2550b57cec5SDimitry Andric         continue;
2560b57cec5SDimitry Andric       return false;
2570b57cec5SDimitry Andric     }
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric     auto *da = dyn_cast<Defined>(&sa);
2600b57cec5SDimitry Andric     auto *db = dyn_cast<Defined>(&sb);
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric     // Placeholder symbols generated by linker scripts look the same now but
2630b57cec5SDimitry Andric     // may have different values later.
2640b57cec5SDimitry Andric     if (!da || !db || da->scriptDefined || db->scriptDefined)
2650b57cec5SDimitry Andric       return false;
2660b57cec5SDimitry Andric 
267480093f4SDimitry Andric     // When comparing a pair of relocations, if they refer to different symbols,
268480093f4SDimitry Andric     // and either symbol is preemptible, the containing sections should be
269480093f4SDimitry Andric     // considered different. This is because even if the sections are identical
270480093f4SDimitry Andric     // in this DSO, they may not be after preemption.
271480093f4SDimitry Andric     if (da->isPreemptible || db->isPreemptible)
272480093f4SDimitry Andric       return false;
273480093f4SDimitry Andric 
2740b57cec5SDimitry Andric     // Relocations referring to absolute symbols are constant-equal if their
2750b57cec5SDimitry Andric     // values are equal.
2760b57cec5SDimitry Andric     if (!da->section && !db->section && da->value + addA == db->value + addB)
2770b57cec5SDimitry Andric       continue;
2780b57cec5SDimitry Andric     if (!da->section || !db->section)
2790b57cec5SDimitry Andric       return false;
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric     if (da->section->kind() != db->section->kind())
2820b57cec5SDimitry Andric       return false;
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric     // Relocations referring to InputSections are constant-equal if their
2850b57cec5SDimitry Andric     // section offsets are equal.
2860b57cec5SDimitry Andric     if (isa<InputSection>(da->section)) {
2870b57cec5SDimitry Andric       if (da->value + addA == db->value + addB)
2880b57cec5SDimitry Andric         continue;
2890b57cec5SDimitry Andric       return false;
2900b57cec5SDimitry Andric     }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric     // Relocations referring to MergeInputSections are constant-equal if their
2930b57cec5SDimitry Andric     // offsets in the output section are equal.
2940b57cec5SDimitry Andric     auto *x = dyn_cast<MergeInputSection>(da->section);
2950b57cec5SDimitry Andric     if (!x)
2960b57cec5SDimitry Andric       return false;
2970b57cec5SDimitry Andric     auto *y = cast<MergeInputSection>(db->section);
2980b57cec5SDimitry Andric     if (x->getParent() != y->getParent())
2990b57cec5SDimitry Andric       return false;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric     uint64_t offsetA =
3020b57cec5SDimitry Andric         sa.isSection() ? x->getOffset(addA) : x->getOffset(da->value) + addA;
3030b57cec5SDimitry Andric     uint64_t offsetB =
3040b57cec5SDimitry Andric         sb.isSection() ? y->getOffset(addB) : y->getOffset(db->value) + addB;
3050b57cec5SDimitry Andric     if (offsetA != offsetB)
3060b57cec5SDimitry Andric       return false;
3070b57cec5SDimitry Andric   }
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   return true;
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric // Compare "non-moving" part of two InputSections, namely everything
3130b57cec5SDimitry Andric // except relocation targets.
3140b57cec5SDimitry Andric template <class ELFT>
equalsConstant(const InputSection * a,const InputSection * b)3150b57cec5SDimitry Andric bool ICF<ELFT>::equalsConstant(const InputSection *a, const InputSection *b) {
316349cc55cSDimitry Andric   if (a->flags != b->flags || a->getSize() != b->getSize() ||
317bdd1243dSDimitry Andric       a->content() != b->content())
3180b57cec5SDimitry Andric     return false;
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric   // If two sections have different output sections, we cannot merge them.
32185868e8aSDimitry Andric   assert(a->getParent() && b->getParent());
32285868e8aSDimitry Andric   if (a->getParent() != b->getParent())
3230b57cec5SDimitry Andric     return false;
3240b57cec5SDimitry Andric 
325349cc55cSDimitry Andric   const RelsOrRelas<ELFT> ra = a->template relsOrRelas<ELFT>();
326349cc55cSDimitry Andric   const RelsOrRelas<ELFT> rb = b->template relsOrRelas<ELFT>();
327*6e516c87SDimitry Andric   if (ra.areRelocsCrel() || rb.areRelocsCrel())
32852418fc2SDimitry Andric     return constantEq(a, ra.crels, b, rb.crels);
3291ac55f4cSDimitry Andric   return ra.areRelocsRel() || rb.areRelocsRel()
3301ac55f4cSDimitry Andric              ? constantEq(a, ra.rels, b, rb.rels)
331349cc55cSDimitry Andric              : constantEq(a, ra.relas, b, rb.relas);
3320b57cec5SDimitry Andric }
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric // Compare two lists of relocations. Returns true if all pairs of
3350b57cec5SDimitry Andric // relocations point to the same section in terms of ICF.
3360b57cec5SDimitry Andric template <class ELFT>
3370b57cec5SDimitry Andric template <class RelTy>
variableEq(const InputSection * secA,Relocs<RelTy> ra,const InputSection * secB,Relocs<RelTy> rb)33852418fc2SDimitry Andric bool ICF<ELFT>::variableEq(const InputSection *secA, Relocs<RelTy> ra,
33952418fc2SDimitry Andric                            const InputSection *secB, Relocs<RelTy> rb) {
3400b57cec5SDimitry Andric   assert(ra.size() == rb.size());
3410b57cec5SDimitry Andric 
3420fca6ea1SDimitry Andric   auto rai = ra.begin(), rae = ra.end(), rbi = rb.begin();
3430fca6ea1SDimitry Andric   for (; rai != rae; ++rai, ++rbi) {
3440b57cec5SDimitry Andric     // The two sections must be identical.
3450fca6ea1SDimitry Andric     Symbol &sa = secA->file->getRelocTargetSym(*rai);
3460fca6ea1SDimitry Andric     Symbol &sb = secB->file->getRelocTargetSym(*rbi);
3470b57cec5SDimitry Andric     if (&sa == &sb)
3480b57cec5SDimitry Andric       continue;
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric     auto *da = cast<Defined>(&sa);
3510b57cec5SDimitry Andric     auto *db = cast<Defined>(&sb);
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric     // We already dealt with absolute and non-InputSection symbols in
3540b57cec5SDimitry Andric     // constantEq, and for InputSections we have already checked everything
3550b57cec5SDimitry Andric     // except the equivalence class.
3560b57cec5SDimitry Andric     if (!da->section)
3570b57cec5SDimitry Andric       continue;
3580b57cec5SDimitry Andric     auto *x = dyn_cast<InputSection>(da->section);
3590b57cec5SDimitry Andric     if (!x)
3600b57cec5SDimitry Andric       continue;
3610b57cec5SDimitry Andric     auto *y = cast<InputSection>(db->section);
3620b57cec5SDimitry Andric 
363e8d8bef9SDimitry Andric     // Sections that are in the special equivalence class 0, can never be the
364e8d8bef9SDimitry Andric     // same in terms of the equivalence class.
3650b57cec5SDimitry Andric     if (x->eqClass[current] == 0)
3660b57cec5SDimitry Andric       return false;
3670b57cec5SDimitry Andric     if (x->eqClass[current] != y->eqClass[current])
3680b57cec5SDimitry Andric       return false;
3690b57cec5SDimitry Andric   };
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   return true;
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric // Compare "moving" part of two InputSections, namely relocation targets.
3750b57cec5SDimitry Andric template <class ELFT>
equalsVariable(const InputSection * a,const InputSection * b)3760b57cec5SDimitry Andric bool ICF<ELFT>::equalsVariable(const InputSection *a, const InputSection *b) {
377349cc55cSDimitry Andric   const RelsOrRelas<ELFT> ra = a->template relsOrRelas<ELFT>();
378349cc55cSDimitry Andric   const RelsOrRelas<ELFT> rb = b->template relsOrRelas<ELFT>();
379*6e516c87SDimitry Andric   if (ra.areRelocsCrel() || rb.areRelocsCrel())
38052418fc2SDimitry Andric     return variableEq(a, ra.crels, b, rb.crels);
3811ac55f4cSDimitry Andric   return ra.areRelocsRel() || rb.areRelocsRel()
3821ac55f4cSDimitry Andric              ? variableEq(a, ra.rels, b, rb.rels)
383349cc55cSDimitry Andric              : variableEq(a, ra.relas, b, rb.relas);
3840b57cec5SDimitry Andric }
3850b57cec5SDimitry Andric 
findBoundary(size_t begin,size_t end)3860b57cec5SDimitry Andric template <class ELFT> size_t ICF<ELFT>::findBoundary(size_t begin, size_t end) {
3870b57cec5SDimitry Andric   uint32_t eqClass = sections[begin]->eqClass[current];
3880b57cec5SDimitry Andric   for (size_t i = begin + 1; i < end; ++i)
3890b57cec5SDimitry Andric     if (eqClass != sections[i]->eqClass[current])
3900b57cec5SDimitry Andric       return i;
3910b57cec5SDimitry Andric   return end;
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric // Sections in the same equivalence class are contiguous in Sections
3950b57cec5SDimitry Andric // vector. Therefore, Sections vector can be considered as contiguous
3960b57cec5SDimitry Andric // groups of sections, grouped by the class.
3970b57cec5SDimitry Andric //
3980b57cec5SDimitry Andric // This function calls Fn on every group within [Begin, End).
3990b57cec5SDimitry Andric template <class ELFT>
forEachClassRange(size_t begin,size_t end,llvm::function_ref<void (size_t,size_t)> fn)4000b57cec5SDimitry Andric void ICF<ELFT>::forEachClassRange(size_t begin, size_t end,
4010b57cec5SDimitry Andric                                   llvm::function_ref<void(size_t, size_t)> fn) {
4020b57cec5SDimitry Andric   while (begin < end) {
4030b57cec5SDimitry Andric     size_t mid = findBoundary(begin, end);
4040b57cec5SDimitry Andric     fn(begin, mid);
4050b57cec5SDimitry Andric     begin = mid;
4060b57cec5SDimitry Andric   }
4070b57cec5SDimitry Andric }
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric // Call Fn on each equivalence class.
4100b57cec5SDimitry Andric template <class ELFT>
forEachClass(llvm::function_ref<void (size_t,size_t)> fn)4110b57cec5SDimitry Andric void ICF<ELFT>::forEachClass(llvm::function_ref<void(size_t, size_t)> fn) {
4120b57cec5SDimitry Andric   // If threading is disabled or the number of sections are
4130b57cec5SDimitry Andric   // too small to use threading, call Fn sequentially.
4145ffd83dbSDimitry Andric   if (parallel::strategy.ThreadsRequested == 1 || sections.size() < 1024) {
4150b57cec5SDimitry Andric     forEachClassRange(0, sections.size(), fn);
4160b57cec5SDimitry Andric     ++cnt;
4170b57cec5SDimitry Andric     return;
4180b57cec5SDimitry Andric   }
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   current = cnt % 2;
4210b57cec5SDimitry Andric   next = (cnt + 1) % 2;
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // Shard into non-overlapping intervals, and call Fn in parallel.
4240b57cec5SDimitry Andric   // The sharding must be completed before any calls to Fn are made
4250b57cec5SDimitry Andric   // so that Fn can modify the Chunks in its shard without causing data
4260b57cec5SDimitry Andric   // races.
4270b57cec5SDimitry Andric   const size_t numShards = 256;
4280b57cec5SDimitry Andric   size_t step = sections.size() / numShards;
4290b57cec5SDimitry Andric   size_t boundaries[numShards + 1];
4300b57cec5SDimitry Andric   boundaries[0] = 0;
4310b57cec5SDimitry Andric   boundaries[numShards] = sections.size();
4320b57cec5SDimitry Andric 
43381ad6265SDimitry Andric   parallelFor(1, numShards, [&](size_t i) {
4340b57cec5SDimitry Andric     boundaries[i] = findBoundary((i - 1) * step, sections.size());
4350b57cec5SDimitry Andric   });
4360b57cec5SDimitry Andric 
43781ad6265SDimitry Andric   parallelFor(1, numShards + 1, [&](size_t i) {
4380b57cec5SDimitry Andric     if (boundaries[i - 1] < boundaries[i])
4390b57cec5SDimitry Andric       forEachClassRange(boundaries[i - 1], boundaries[i], fn);
4400b57cec5SDimitry Andric   });
4410b57cec5SDimitry Andric   ++cnt;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric // Combine the hashes of the sections referenced by the given section into its
4450b57cec5SDimitry Andric // hash.
4460fca6ea1SDimitry Andric template <class RelTy>
combineRelocHashes(unsigned cnt,InputSection * isec,Relocs<RelTy> rels)4470b57cec5SDimitry Andric static void combineRelocHashes(unsigned cnt, InputSection *isec,
44852418fc2SDimitry Andric                                Relocs<RelTy> rels) {
4490b57cec5SDimitry Andric   uint32_t hash = isec->eqClass[cnt % 2];
4500b57cec5SDimitry Andric   for (RelTy rel : rels) {
4510fca6ea1SDimitry Andric     Symbol &s = isec->file->getRelocTargetSym(rel);
4520b57cec5SDimitry Andric     if (auto *d = dyn_cast<Defined>(&s))
4530b57cec5SDimitry Andric       if (auto *relSec = dyn_cast_or_null<InputSection>(d->section))
4540b57cec5SDimitry Andric         hash += relSec->eqClass[cnt % 2];
4550b57cec5SDimitry Andric   }
456e8d8bef9SDimitry Andric   // Set MSB to 1 to avoid collisions with unique IDs.
4570b57cec5SDimitry Andric   isec->eqClass[(cnt + 1) % 2] = hash | (1U << 31);
4580b57cec5SDimitry Andric }
4590b57cec5SDimitry Andric 
print(const Twine & s)4600b57cec5SDimitry Andric static void print(const Twine &s) {
4610b57cec5SDimitry Andric   if (config->printIcfSections)
4620b57cec5SDimitry Andric     message(s);
4630b57cec5SDimitry Andric }
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric // The main function of ICF.
run()4660b57cec5SDimitry Andric template <class ELFT> void ICF<ELFT>::run() {
467480093f4SDimitry Andric   // Compute isPreemptible early. We may add more symbols later, so this loop
468480093f4SDimitry Andric   // cannot be merged with the later computeIsPreemptible() pass which is used
469480093f4SDimitry Andric   // by scanRelocations().
47004eeddc0SDimitry Andric   if (config->hasDynSymTab)
471bdd1243dSDimitry Andric     for (Symbol *sym : symtab.getSymbols())
472480093f4SDimitry Andric       sym->isPreemptible = computeIsPreemptible(*sym);
473480093f4SDimitry Andric 
474e8d8bef9SDimitry Andric   // Two text sections may have identical content and relocations but different
475e8d8bef9SDimitry Andric   // LSDA, e.g. the two functions may have catch blocks of different types. If a
476e8d8bef9SDimitry Andric   // text section is referenced by a .eh_frame FDE with LSDA, it is not
477e8d8bef9SDimitry Andric   // eligible. This is implemented by iterating over CIE/FDE and setting
478e8d8bef9SDimitry Andric   // eqClass[0] to the referenced text section from a live FDE.
479e8d8bef9SDimitry Andric   //
480e8d8bef9SDimitry Andric   // If two .gcc_except_table have identical semantics (usually identical
481e8d8bef9SDimitry Andric   // content with PC-relative encoding), we will lose folding opportunity.
482e8d8bef9SDimitry Andric   uint32_t uniqueId = 0;
483e8d8bef9SDimitry Andric   for (Partition &part : partitions)
484e8d8bef9SDimitry Andric     part.ehFrame->iterateFDEWithLSDA<ELFT>(
485e8d8bef9SDimitry Andric         [&](InputSection &s) { s.eqClass[0] = s.eqClass[1] = ++uniqueId; });
486e8d8bef9SDimitry Andric 
4870b57cec5SDimitry Andric   // Collect sections to merge.
488bdd1243dSDimitry Andric   for (InputSectionBase *sec : ctx.inputSections) {
489bdd1243dSDimitry Andric     auto *s = dyn_cast<InputSection>(sec);
490bdd1243dSDimitry Andric     if (s && s->eqClass[0] == 0) {
4910b57cec5SDimitry Andric       if (isEligible(s))
4920b57cec5SDimitry Andric         sections.push_back(s);
493e8d8bef9SDimitry Andric       else
494e8d8bef9SDimitry Andric         // Ineligible sections are assigned unique IDs, i.e. each section
495e8d8bef9SDimitry Andric         // belongs to an equivalence class of its own.
496e8d8bef9SDimitry Andric         s->eqClass[0] = s->eqClass[1] = ++uniqueId;
497e8d8bef9SDimitry Andric     }
49885868e8aSDimitry Andric   }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   // Initially, we use hash values to partition sections.
501e8d8bef9SDimitry Andric   parallelForEach(sections, [&](InputSection *s) {
502e8d8bef9SDimitry Andric     // Set MSB to 1 to avoid collisions with unique IDs.
50306c3fb27SDimitry Andric     s->eqClass[0] = xxh3_64bits(s->content()) | (1U << 31);
504e8d8bef9SDimitry Andric   });
5050b57cec5SDimitry Andric 
506e8d8bef9SDimitry Andric   // Perform 2 rounds of relocation hash propagation. 2 is an empirical value to
507e8d8bef9SDimitry Andric   // reduce the average sizes of equivalence classes, i.e. segregate() which has
508e8d8bef9SDimitry Andric   // a large time complexity will have less work to do.
5090b57cec5SDimitry Andric   for (unsigned cnt = 0; cnt != 2; ++cnt) {
5100b57cec5SDimitry Andric     parallelForEach(sections, [&](InputSection *s) {
511349cc55cSDimitry Andric       const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
51252418fc2SDimitry Andric       if (rels.areRelocsCrel())
51352418fc2SDimitry Andric         combineRelocHashes(cnt, s, rels.crels);
51452418fc2SDimitry Andric       else if (rels.areRelocsRel())
5150fca6ea1SDimitry Andric         combineRelocHashes(cnt, s, rels.rels);
5160b57cec5SDimitry Andric       else
5170fca6ea1SDimitry Andric         combineRelocHashes(cnt, s, rels.relas);
5180b57cec5SDimitry Andric     });
5190b57cec5SDimitry Andric   }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   // From now on, sections in Sections vector are ordered so that sections
5220b57cec5SDimitry Andric   // in the same equivalence class are consecutive in the vector.
5230b57cec5SDimitry Andric   llvm::stable_sort(sections, [](const InputSection *a, const InputSection *b) {
5240b57cec5SDimitry Andric     return a->eqClass[0] < b->eqClass[0];
5250b57cec5SDimitry Andric   });
5260b57cec5SDimitry Andric 
527e8d8bef9SDimitry Andric   // Compare static contents and assign unique equivalence class IDs for each
528e8d8bef9SDimitry Andric   // static content. Use a base offset for these IDs to ensure no overlap with
529e8d8bef9SDimitry Andric   // the unique IDs already assigned.
530e8d8bef9SDimitry Andric   uint32_t eqClassBase = ++uniqueId;
531e8d8bef9SDimitry Andric   forEachClass([&](size_t begin, size_t end) {
532e8d8bef9SDimitry Andric     segregate(begin, end, eqClassBase, true);
533e8d8bef9SDimitry Andric   });
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   // Split groups by comparing relocations until convergence is obtained.
5360b57cec5SDimitry Andric   do {
5370b57cec5SDimitry Andric     repeat = false;
538e8d8bef9SDimitry Andric     forEachClass([&](size_t begin, size_t end) {
539e8d8bef9SDimitry Andric       segregate(begin, end, eqClassBase, false);
540e8d8bef9SDimitry Andric     });
5410b57cec5SDimitry Andric   } while (repeat);
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric   log("ICF needed " + Twine(cnt) + " iterations");
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   // Merge sections by the equivalence class.
5460b57cec5SDimitry Andric   forEachClassRange(0, sections.size(), [&](size_t begin, size_t end) {
5470b57cec5SDimitry Andric     if (end - begin == 1)
5480b57cec5SDimitry Andric       return;
5490b57cec5SDimitry Andric     print("selected section " + toString(sections[begin]));
5500b57cec5SDimitry Andric     for (size_t i = begin + 1; i < end; ++i) {
5510b57cec5SDimitry Andric       print("  removing identical section " + toString(sections[i]));
5520b57cec5SDimitry Andric       sections[begin]->replace(sections[i]);
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric       // At this point we know sections merged are fully identical and hence
5550b57cec5SDimitry Andric       // we want to remove duplicate implicit dependencies such as link order
5560b57cec5SDimitry Andric       // and relocation sections.
5570b57cec5SDimitry Andric       for (InputSection *isec : sections[i]->dependentSections)
5580b57cec5SDimitry Andric         isec->markDead();
5590b57cec5SDimitry Andric     }
5600b57cec5SDimitry Andric   });
56185868e8aSDimitry Andric 
5620eae32dcSDimitry Andric   // Change Defined symbol's section field to the canonical one.
5630eae32dcSDimitry Andric   auto fold = [](Symbol *sym) {
5640eae32dcSDimitry Andric     if (auto *d = dyn_cast<Defined>(sym))
5650eae32dcSDimitry Andric       if (auto *sec = dyn_cast_or_null<InputSection>(d->section))
5660eae32dcSDimitry Andric         if (sec->repl != d->section) {
5670eae32dcSDimitry Andric           d->section = sec->repl;
5680eae32dcSDimitry Andric           d->folded = true;
5690eae32dcSDimitry Andric         }
5700eae32dcSDimitry Andric   };
571bdd1243dSDimitry Andric   for (Symbol *sym : symtab.getSymbols())
5720eae32dcSDimitry Andric     fold(sym);
573bdd1243dSDimitry Andric   parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) {
5740eae32dcSDimitry Andric     for (Symbol *sym : file->getLocalSymbols())
5750eae32dcSDimitry Andric       fold(sym);
5760eae32dcSDimitry Andric   });
5770eae32dcSDimitry Andric 
57885868e8aSDimitry Andric   // InputSectionDescription::sections is populated by processSectionCommands().
57985868e8aSDimitry Andric   // ICF may fold some input sections assigned to output sections. Remove them.
5804824e7fdSDimitry Andric   for (SectionCommand *cmd : script->sectionCommands)
58181ad6265SDimitry Andric     if (auto *osd = dyn_cast<OutputDesc>(cmd))
58281ad6265SDimitry Andric       for (SectionCommand *subCmd : osd->osec.commands)
5834824e7fdSDimitry Andric         if (auto *isd = dyn_cast<InputSectionDescription>(subCmd))
58485868e8aSDimitry Andric           llvm::erase_if(isd->sections,
58585868e8aSDimitry Andric                          [](InputSection *isec) { return !isec->isLive(); });
5860b57cec5SDimitry Andric }
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric // ICF entry point function.
doIcf()5895ffd83dbSDimitry Andric template <class ELFT> void elf::doIcf() {
5905ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("ICF");
5915ffd83dbSDimitry Andric   ICF<ELFT>().run();
5925ffd83dbSDimitry Andric }
5930b57cec5SDimitry Andric 
5945ffd83dbSDimitry Andric template void elf::doIcf<ELF32LE>();
5955ffd83dbSDimitry Andric template void elf::doIcf<ELF32BE>();
5965ffd83dbSDimitry Andric template void elf::doIcf<ELF64LE>();
5975ffd83dbSDimitry Andric template void elf::doIcf<ELF64BE>();
598