xref: /freebsd/contrib/llvm-project/lld/MachO/ICF.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1fe6060f1SDimitry Andric //===- ICF.cpp ------------------------------------------------------------===//
2fe6060f1SDimitry Andric //
3fe6060f1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4fe6060f1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5fe6060f1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fe6060f1SDimitry Andric //
7fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
8fe6060f1SDimitry Andric 
9fe6060f1SDimitry Andric #include "ICF.h"
10fe6060f1SDimitry Andric #include "ConcatOutputSection.h"
11*81ad6265SDimitry Andric #include "Config.h"
12fe6060f1SDimitry Andric #include "InputSection.h"
13*81ad6265SDimitry Andric #include "SymbolTable.h"
14fe6060f1SDimitry Andric #include "Symbols.h"
15fe6060f1SDimitry Andric #include "UnwindInfoSection.h"
16fe6060f1SDimitry Andric 
17*81ad6265SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
18*81ad6265SDimitry Andric #include "llvm/Support/LEB128.h"
19fe6060f1SDimitry Andric #include "llvm/Support/Parallel.h"
20fe6060f1SDimitry Andric #include "llvm/Support/TimeProfiler.h"
21*81ad6265SDimitry Andric #include "llvm/Support/xxhash.h"
22fe6060f1SDimitry Andric 
23fe6060f1SDimitry Andric #include <atomic>
24fe6060f1SDimitry Andric 
25fe6060f1SDimitry Andric using namespace llvm;
26fe6060f1SDimitry Andric using namespace lld;
27fe6060f1SDimitry Andric using namespace lld::macho;
28fe6060f1SDimitry Andric 
29*81ad6265SDimitry Andric static constexpr bool verboseDiagnostics = false;
30*81ad6265SDimitry Andric 
31fe6060f1SDimitry Andric class ICF {
32fe6060f1SDimitry Andric public:
33fe6060f1SDimitry Andric   ICF(std::vector<ConcatInputSection *> &inputs);
34fe6060f1SDimitry Andric   void run();
35*81ad6265SDimitry Andric 
36*81ad6265SDimitry Andric   using EqualsFn = bool (ICF::*)(const ConcatInputSection *,
37*81ad6265SDimitry Andric                                  const ConcatInputSection *);
38*81ad6265SDimitry Andric   void segregate(size_t begin, size_t end, EqualsFn);
39fe6060f1SDimitry Andric   size_t findBoundary(size_t begin, size_t end);
40fe6060f1SDimitry Andric   void forEachClassRange(size_t begin, size_t end,
41*81ad6265SDimitry Andric                          llvm::function_ref<void(size_t, size_t)> func);
42*81ad6265SDimitry Andric   void forEachClass(llvm::function_ref<void(size_t, size_t)> func);
43*81ad6265SDimitry Andric 
44*81ad6265SDimitry Andric   bool equalsConstant(const ConcatInputSection *ia,
45*81ad6265SDimitry Andric                       const ConcatInputSection *ib);
46*81ad6265SDimitry Andric   bool equalsVariable(const ConcatInputSection *ia,
47*81ad6265SDimitry Andric                       const ConcatInputSection *ib);
48fe6060f1SDimitry Andric 
49fe6060f1SDimitry Andric   // ICF needs a copy of the inputs vector because its equivalence-class
50fe6060f1SDimitry Andric   // segregation algorithm destroys the proper sequence.
51fe6060f1SDimitry Andric   std::vector<ConcatInputSection *> icfInputs;
52*81ad6265SDimitry Andric 
53*81ad6265SDimitry Andric   unsigned icfPass = 0;
54*81ad6265SDimitry Andric   std::atomic<bool> icfRepeat{false};
55*81ad6265SDimitry Andric   std::atomic<uint64_t> equalsConstantCount{0};
56*81ad6265SDimitry Andric   std::atomic<uint64_t> equalsVariableCount{0};
57fe6060f1SDimitry Andric };
58fe6060f1SDimitry Andric 
59fe6060f1SDimitry Andric ICF::ICF(std::vector<ConcatInputSection *> &inputs) {
60fe6060f1SDimitry Andric   icfInputs.assign(inputs.begin(), inputs.end());
61fe6060f1SDimitry Andric }
62fe6060f1SDimitry Andric 
63fe6060f1SDimitry Andric // ICF = Identical Code Folding
64fe6060f1SDimitry Andric //
65fe6060f1SDimitry Andric // We only fold __TEXT,__text, so this is really "code" folding, and not
66fe6060f1SDimitry Andric // "COMDAT" folding. String and scalar constant literals are deduplicated
67fe6060f1SDimitry Andric // elsewhere.
68fe6060f1SDimitry Andric //
69fe6060f1SDimitry Andric // Summary of segments & sections:
70fe6060f1SDimitry Andric //
71fe6060f1SDimitry Andric // The __TEXT segment is readonly at the MMU. Some sections are already
72fe6060f1SDimitry Andric // deduplicated elsewhere (__TEXT,__cstring & __TEXT,__literal*) and some are
73fe6060f1SDimitry Andric // synthetic and inherently free of duplicates (__TEXT,__stubs &
74fe6060f1SDimitry Andric // __TEXT,__unwind_info). Note that we don't yet run ICF on __TEXT,__const,
75fe6060f1SDimitry Andric // because doing so induces many test failures.
76fe6060f1SDimitry Andric //
77fe6060f1SDimitry Andric // The __LINKEDIT segment is readonly at the MMU, yet entirely synthetic, and
78fe6060f1SDimitry Andric // thus ineligible for ICF.
79fe6060f1SDimitry Andric //
80fe6060f1SDimitry Andric // The __DATA_CONST segment is read/write at the MMU, but is logically const to
81fe6060f1SDimitry Andric // the application after dyld applies fixups to pointer data. We currently
82fe6060f1SDimitry Andric // fold only the __DATA_CONST,__cfstring section.
83fe6060f1SDimitry Andric //
84fe6060f1SDimitry Andric // The __DATA segment is read/write at the MMU, and as application-writeable
85fe6060f1SDimitry Andric // data, none of its sections are eligible for ICF.
86fe6060f1SDimitry Andric //
87fe6060f1SDimitry Andric // Please see the large block comment in lld/ELF/ICF.cpp for an explanation
88fe6060f1SDimitry Andric // of the segregation algorithm.
89fe6060f1SDimitry Andric //
90fe6060f1SDimitry Andric // FIXME(gkm): implement keep-unique attributes
91fe6060f1SDimitry Andric // FIXME(gkm): implement address-significance tables for MachO object files
92fe6060f1SDimitry Andric 
93fe6060f1SDimitry Andric // Compare "non-moving" parts of two ConcatInputSections, namely everything
94fe6060f1SDimitry Andric // except references to other ConcatInputSections.
95*81ad6265SDimitry Andric bool ICF::equalsConstant(const ConcatInputSection *ia,
96fe6060f1SDimitry Andric                          const ConcatInputSection *ib) {
97*81ad6265SDimitry Andric   if (verboseDiagnostics)
98*81ad6265SDimitry Andric     ++equalsConstantCount;
99fe6060f1SDimitry Andric   // We can only fold within the same OutputSection.
100fe6060f1SDimitry Andric   if (ia->parent != ib->parent)
101fe6060f1SDimitry Andric     return false;
102fe6060f1SDimitry Andric   if (ia->data.size() != ib->data.size())
103fe6060f1SDimitry Andric     return false;
104fe6060f1SDimitry Andric   if (ia->data != ib->data)
105fe6060f1SDimitry Andric     return false;
106fe6060f1SDimitry Andric   if (ia->relocs.size() != ib->relocs.size())
107fe6060f1SDimitry Andric     return false;
108fe6060f1SDimitry Andric   auto f = [](const Reloc &ra, const Reloc &rb) {
109fe6060f1SDimitry Andric     if (ra.type != rb.type)
110fe6060f1SDimitry Andric       return false;
111fe6060f1SDimitry Andric     if (ra.pcrel != rb.pcrel)
112fe6060f1SDimitry Andric       return false;
113fe6060f1SDimitry Andric     if (ra.length != rb.length)
114fe6060f1SDimitry Andric       return false;
115fe6060f1SDimitry Andric     if (ra.offset != rb.offset)
116fe6060f1SDimitry Andric       return false;
117fe6060f1SDimitry Andric     if (ra.referent.is<Symbol *>() != rb.referent.is<Symbol *>())
118fe6060f1SDimitry Andric       return false;
119fe6060f1SDimitry Andric 
120fe6060f1SDimitry Andric     InputSection *isecA, *isecB;
121349cc55cSDimitry Andric 
122349cc55cSDimitry Andric     uint64_t valueA = 0;
123349cc55cSDimitry Andric     uint64_t valueB = 0;
124fe6060f1SDimitry Andric     if (ra.referent.is<Symbol *>()) {
125fe6060f1SDimitry Andric       const auto *sa = ra.referent.get<Symbol *>();
126fe6060f1SDimitry Andric       const auto *sb = rb.referent.get<Symbol *>();
127fe6060f1SDimitry Andric       if (sa->kind() != sb->kind())
128fe6060f1SDimitry Andric         return false;
129*81ad6265SDimitry Andric       // ICF runs before Undefineds are treated (and potentially converted into
130*81ad6265SDimitry Andric       // DylibSymbols).
131*81ad6265SDimitry Andric       if (isa<DylibSymbol>(sa) || isa<Undefined>(sa))
132*81ad6265SDimitry Andric         return sa == sb && ra.addend == rb.addend;
133*81ad6265SDimitry Andric       assert(isa<Defined>(sa));
134fe6060f1SDimitry Andric       const auto *da = cast<Defined>(sa);
135fe6060f1SDimitry Andric       const auto *db = cast<Defined>(sb);
136349cc55cSDimitry Andric       if (!da->isec || !db->isec) {
137fe6060f1SDimitry Andric         assert(da->isAbsolute() && db->isAbsolute());
138*81ad6265SDimitry Andric         return da->value + ra.addend == db->value + rb.addend;
139fe6060f1SDimitry Andric       }
140349cc55cSDimitry Andric       isecA = da->isec;
141349cc55cSDimitry Andric       valueA = da->value;
142349cc55cSDimitry Andric       isecB = db->isec;
143349cc55cSDimitry Andric       valueB = db->value;
144fe6060f1SDimitry Andric     } else {
145fe6060f1SDimitry Andric       isecA = ra.referent.get<InputSection *>();
146fe6060f1SDimitry Andric       isecB = rb.referent.get<InputSection *>();
147fe6060f1SDimitry Andric     }
148fe6060f1SDimitry Andric 
149fe6060f1SDimitry Andric     if (isecA->parent != isecB->parent)
150fe6060f1SDimitry Andric       return false;
151fe6060f1SDimitry Andric     // Sections with identical parents should be of the same kind.
152fe6060f1SDimitry Andric     assert(isecA->kind() == isecB->kind());
153fe6060f1SDimitry Andric     // We will compare ConcatInputSection contents in equalsVariable.
154fe6060f1SDimitry Andric     if (isa<ConcatInputSection>(isecA))
155*81ad6265SDimitry Andric       return ra.addend == rb.addend;
156fe6060f1SDimitry Andric     // Else we have two literal sections. References to them are equal iff their
157fe6060f1SDimitry Andric     // offsets in the output section are equal.
158*81ad6265SDimitry Andric     if (ra.referent.is<Symbol *>())
159*81ad6265SDimitry Andric       // For symbol relocs, we compare the contents at the symbol address. We
160*81ad6265SDimitry Andric       // don't do `getOffset(value + addend)` because value + addend may not be
161*81ad6265SDimitry Andric       // a valid offset in the literal section.
162*81ad6265SDimitry Andric       return isecA->getOffset(valueA) == isecB->getOffset(valueB) &&
163*81ad6265SDimitry Andric              ra.addend == rb.addend;
164*81ad6265SDimitry Andric     else {
165*81ad6265SDimitry Andric       assert(valueA == 0 && valueB == 0);
166*81ad6265SDimitry Andric       // For section relocs, we compare the content at the section offset.
167*81ad6265SDimitry Andric       return isecA->getOffset(ra.addend) == isecB->getOffset(rb.addend);
168*81ad6265SDimitry Andric     }
169fe6060f1SDimitry Andric   };
170fe6060f1SDimitry Andric   return std::equal(ia->relocs.begin(), ia->relocs.end(), ib->relocs.begin(),
171fe6060f1SDimitry Andric                     f);
172fe6060f1SDimitry Andric }
173fe6060f1SDimitry Andric 
174fe6060f1SDimitry Andric // Compare the "moving" parts of two ConcatInputSections -- i.e. everything not
175fe6060f1SDimitry Andric // handled by equalsConstant().
176*81ad6265SDimitry Andric bool ICF::equalsVariable(const ConcatInputSection *ia,
177fe6060f1SDimitry Andric                          const ConcatInputSection *ib) {
178*81ad6265SDimitry Andric   if (verboseDiagnostics)
179*81ad6265SDimitry Andric     ++equalsVariableCount;
180fe6060f1SDimitry Andric   assert(ia->relocs.size() == ib->relocs.size());
181*81ad6265SDimitry Andric   auto f = [this](const Reloc &ra, const Reloc &rb) {
182fe6060f1SDimitry Andric     // We already filtered out mismatching values/addends in equalsConstant.
183fe6060f1SDimitry Andric     if (ra.referent == rb.referent)
184fe6060f1SDimitry Andric       return true;
185fe6060f1SDimitry Andric     const ConcatInputSection *isecA, *isecB;
186fe6060f1SDimitry Andric     if (ra.referent.is<Symbol *>()) {
187fe6060f1SDimitry Andric       // Matching DylibSymbols are already filtered out by the
188fe6060f1SDimitry Andric       // identical-referent check above. Non-matching DylibSymbols were filtered
189fe6060f1SDimitry Andric       // out in equalsConstant(). So we can safely cast to Defined here.
190fe6060f1SDimitry Andric       const auto *da = cast<Defined>(ra.referent.get<Symbol *>());
191fe6060f1SDimitry Andric       const auto *db = cast<Defined>(rb.referent.get<Symbol *>());
192fe6060f1SDimitry Andric       if (da->isAbsolute())
193fe6060f1SDimitry Andric         return true;
194fe6060f1SDimitry Andric       isecA = dyn_cast<ConcatInputSection>(da->isec);
195fe6060f1SDimitry Andric       if (!isecA)
196fe6060f1SDimitry Andric         return true; // literal sections were checked in equalsConstant.
197fe6060f1SDimitry Andric       isecB = cast<ConcatInputSection>(db->isec);
198fe6060f1SDimitry Andric     } else {
199fe6060f1SDimitry Andric       const auto *sa = ra.referent.get<InputSection *>();
200fe6060f1SDimitry Andric       const auto *sb = rb.referent.get<InputSection *>();
201fe6060f1SDimitry Andric       isecA = dyn_cast<ConcatInputSection>(sa);
202fe6060f1SDimitry Andric       if (!isecA)
203fe6060f1SDimitry Andric         return true;
204fe6060f1SDimitry Andric       isecB = cast<ConcatInputSection>(sb);
205fe6060f1SDimitry Andric     }
206fe6060f1SDimitry Andric     return isecA->icfEqClass[icfPass % 2] == isecB->icfEqClass[icfPass % 2];
207fe6060f1SDimitry Andric   };
208349cc55cSDimitry Andric   if (!std::equal(ia->relocs.begin(), ia->relocs.end(), ib->relocs.begin(), f))
209349cc55cSDimitry Andric     return false;
210349cc55cSDimitry Andric 
211349cc55cSDimitry Andric   // If there are symbols with associated unwind info, check that the unwind
212349cc55cSDimitry Andric   // info matches. For simplicity, we only handle the case where there are only
213349cc55cSDimitry Andric   // symbols at offset zero within the section (which is typically the case with
214349cc55cSDimitry Andric   // .subsections_via_symbols.)
215*81ad6265SDimitry Andric   auto hasUnwind = [](Defined *d) { return d->unwindEntry != nullptr; };
216*81ad6265SDimitry Andric   auto itA = std::find_if(ia->symbols.begin(), ia->symbols.end(), hasUnwind);
217*81ad6265SDimitry Andric   auto itB = std::find_if(ib->symbols.begin(), ib->symbols.end(), hasUnwind);
218349cc55cSDimitry Andric   if (itA == ia->symbols.end())
219349cc55cSDimitry Andric     return itB == ib->symbols.end();
220349cc55cSDimitry Andric   if (itB == ib->symbols.end())
221349cc55cSDimitry Andric     return false;
222349cc55cSDimitry Andric   const Defined *da = *itA;
223349cc55cSDimitry Andric   const Defined *db = *itB;
224349cc55cSDimitry Andric   if (da->unwindEntry->icfEqClass[icfPass % 2] !=
225349cc55cSDimitry Andric           db->unwindEntry->icfEqClass[icfPass % 2] ||
226349cc55cSDimitry Andric       da->value != 0 || db->value != 0)
227349cc55cSDimitry Andric     return false;
228349cc55cSDimitry Andric   auto isZero = [](Defined *d) { return d->value == 0; };
229349cc55cSDimitry Andric   return std::find_if_not(std::next(itA), ia->symbols.end(), isZero) ==
230349cc55cSDimitry Andric              ia->symbols.end() &&
231349cc55cSDimitry Andric          std::find_if_not(std::next(itB), ib->symbols.end(), isZero) ==
232349cc55cSDimitry Andric              ib->symbols.end();
233fe6060f1SDimitry Andric }
234fe6060f1SDimitry Andric 
235fe6060f1SDimitry Andric // Find the first InputSection after BEGIN whose equivalence class differs
236fe6060f1SDimitry Andric size_t ICF::findBoundary(size_t begin, size_t end) {
237fe6060f1SDimitry Andric   uint64_t beginHash = icfInputs[begin]->icfEqClass[icfPass % 2];
238fe6060f1SDimitry Andric   for (size_t i = begin + 1; i < end; ++i)
239fe6060f1SDimitry Andric     if (beginHash != icfInputs[i]->icfEqClass[icfPass % 2])
240fe6060f1SDimitry Andric       return i;
241fe6060f1SDimitry Andric   return end;
242fe6060f1SDimitry Andric }
243fe6060f1SDimitry Andric 
244fe6060f1SDimitry Andric // Invoke FUNC on subranges with matching equivalence class
245fe6060f1SDimitry Andric void ICF::forEachClassRange(size_t begin, size_t end,
246*81ad6265SDimitry Andric                             llvm::function_ref<void(size_t, size_t)> func) {
247fe6060f1SDimitry Andric   while (begin < end) {
248fe6060f1SDimitry Andric     size_t mid = findBoundary(begin, end);
249fe6060f1SDimitry Andric     func(begin, mid);
250fe6060f1SDimitry Andric     begin = mid;
251fe6060f1SDimitry Andric   }
252fe6060f1SDimitry Andric }
253fe6060f1SDimitry Andric 
254fe6060f1SDimitry Andric // Split icfInputs into shards, then parallelize invocation of FUNC on subranges
255fe6060f1SDimitry Andric // with matching equivalence class
256*81ad6265SDimitry Andric void ICF::forEachClass(llvm::function_ref<void(size_t, size_t)> func) {
257fe6060f1SDimitry Andric   // Only use threads when the benefits outweigh the overhead.
258fe6060f1SDimitry Andric   const size_t threadingThreshold = 1024;
259fe6060f1SDimitry Andric   if (icfInputs.size() < threadingThreshold) {
260fe6060f1SDimitry Andric     forEachClassRange(0, icfInputs.size(), func);
261fe6060f1SDimitry Andric     ++icfPass;
262fe6060f1SDimitry Andric     return;
263fe6060f1SDimitry Andric   }
264fe6060f1SDimitry Andric 
265fe6060f1SDimitry Andric   // Shard into non-overlapping intervals, and call FUNC in parallel.  The
266fe6060f1SDimitry Andric   // sharding must be completed before any calls to FUNC are made so that FUNC
267fe6060f1SDimitry Andric   // can modify the InputSection in its shard without causing data races.
268fe6060f1SDimitry Andric   const size_t shards = 256;
269fe6060f1SDimitry Andric   size_t step = icfInputs.size() / shards;
270fe6060f1SDimitry Andric   size_t boundaries[shards + 1];
271fe6060f1SDimitry Andric   boundaries[0] = 0;
272fe6060f1SDimitry Andric   boundaries[shards] = icfInputs.size();
273*81ad6265SDimitry Andric   parallelFor(1, shards, [&](size_t i) {
274fe6060f1SDimitry Andric     boundaries[i] = findBoundary((i - 1) * step, icfInputs.size());
275fe6060f1SDimitry Andric   });
276*81ad6265SDimitry Andric   parallelFor(1, shards + 1, [&](size_t i) {
277fe6060f1SDimitry Andric     if (boundaries[i - 1] < boundaries[i]) {
278fe6060f1SDimitry Andric       forEachClassRange(boundaries[i - 1], boundaries[i], func);
279fe6060f1SDimitry Andric     }
280fe6060f1SDimitry Andric   });
281fe6060f1SDimitry Andric   ++icfPass;
282fe6060f1SDimitry Andric }
283fe6060f1SDimitry Andric 
284fe6060f1SDimitry Andric void ICF::run() {
285fe6060f1SDimitry Andric   // Into each origin-section hash, combine all reloc referent section hashes.
286fe6060f1SDimitry Andric   for (icfPass = 0; icfPass < 2; ++icfPass) {
287fe6060f1SDimitry Andric     parallelForEach(icfInputs, [&](ConcatInputSection *isec) {
288*81ad6265SDimitry Andric       uint32_t hash = isec->icfEqClass[icfPass % 2];
289fe6060f1SDimitry Andric       for (const Reloc &r : isec->relocs) {
290fe6060f1SDimitry Andric         if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
291*81ad6265SDimitry Andric           if (auto *defined = dyn_cast<Defined>(sym)) {
292fe6060f1SDimitry Andric             if (defined->isec) {
293*81ad6265SDimitry Andric               if (auto referentIsec =
294*81ad6265SDimitry Andric                       dyn_cast<ConcatInputSection>(defined->isec))
295*81ad6265SDimitry Andric                 hash += defined->value + referentIsec->icfEqClass[icfPass % 2];
296fe6060f1SDimitry Andric               else
297fe6060f1SDimitry Andric                 hash += defined->isec->kind() +
298fe6060f1SDimitry Andric                         defined->isec->getOffset(defined->value);
299fe6060f1SDimitry Andric             } else {
300fe6060f1SDimitry Andric               hash += defined->value;
301fe6060f1SDimitry Andric             }
302*81ad6265SDimitry Andric           } else {
303*81ad6265SDimitry Andric             // ICF runs before Undefined diags
304*81ad6265SDimitry Andric             assert(isa<Undefined>(sym) || isa<DylibSymbol>(sym));
305*81ad6265SDimitry Andric           }
306fe6060f1SDimitry Andric         }
307fe6060f1SDimitry Andric       }
308fe6060f1SDimitry Andric       // Set MSB to 1 to avoid collisions with non-hashed classes.
309*81ad6265SDimitry Andric       isec->icfEqClass[(icfPass + 1) % 2] = hash | (1ull << 31);
310fe6060f1SDimitry Andric     });
311fe6060f1SDimitry Andric   }
312fe6060f1SDimitry Andric 
313fe6060f1SDimitry Andric   llvm::stable_sort(
314fe6060f1SDimitry Andric       icfInputs, [](const ConcatInputSection *a, const ConcatInputSection *b) {
315fe6060f1SDimitry Andric         return a->icfEqClass[0] < b->icfEqClass[0];
316fe6060f1SDimitry Andric       });
317*81ad6265SDimitry Andric   forEachClass([&](size_t begin, size_t end) {
318*81ad6265SDimitry Andric     segregate(begin, end, &ICF::equalsConstant);
319*81ad6265SDimitry Andric   });
320fe6060f1SDimitry Andric 
321fe6060f1SDimitry Andric   // Split equivalence groups by comparing relocations until convergence
322fe6060f1SDimitry Andric   do {
323fe6060f1SDimitry Andric     icfRepeat = false;
324fe6060f1SDimitry Andric     forEachClass([&](size_t begin, size_t end) {
325*81ad6265SDimitry Andric       segregate(begin, end, &ICF::equalsVariable);
326fe6060f1SDimitry Andric     });
327fe6060f1SDimitry Andric   } while (icfRepeat);
328fe6060f1SDimitry Andric   log("ICF needed " + Twine(icfPass) + " iterations");
329*81ad6265SDimitry Andric   if (verboseDiagnostics) {
330*81ad6265SDimitry Andric     log("equalsConstant() called " + Twine(equalsConstantCount) + " times");
331*81ad6265SDimitry Andric     log("equalsVariable() called " + Twine(equalsVariableCount) + " times");
332*81ad6265SDimitry Andric   }
333fe6060f1SDimitry Andric 
334fe6060f1SDimitry Andric   // Fold sections within equivalence classes
335fe6060f1SDimitry Andric   forEachClass([&](size_t begin, size_t end) {
336fe6060f1SDimitry Andric     if (end - begin < 2)
337fe6060f1SDimitry Andric       return;
338fe6060f1SDimitry Andric     ConcatInputSection *beginIsec = icfInputs[begin];
339fe6060f1SDimitry Andric     for (size_t i = begin + 1; i < end; ++i)
340fe6060f1SDimitry Andric       beginIsec->foldIdentical(icfInputs[i]);
341fe6060f1SDimitry Andric   });
342fe6060f1SDimitry Andric }
343fe6060f1SDimitry Andric 
344fe6060f1SDimitry Andric // Split an equivalence class into smaller classes.
345*81ad6265SDimitry Andric void ICF::segregate(size_t begin, size_t end, EqualsFn equals) {
346fe6060f1SDimitry Andric   while (begin < end) {
347fe6060f1SDimitry Andric     // Divide [begin, end) into two. Let mid be the start index of the
348fe6060f1SDimitry Andric     // second group.
349*81ad6265SDimitry Andric     auto bound = std::stable_partition(
350*81ad6265SDimitry Andric         icfInputs.begin() + begin + 1, icfInputs.begin() + end,
351fe6060f1SDimitry Andric         [&](ConcatInputSection *isec) {
352*81ad6265SDimitry Andric           return (this->*equals)(icfInputs[begin], isec);
353fe6060f1SDimitry Andric         });
354fe6060f1SDimitry Andric     size_t mid = bound - icfInputs.begin();
355fe6060f1SDimitry Andric 
356fe6060f1SDimitry Andric     // Split [begin, end) into [begin, mid) and [mid, end). We use mid as an
357fe6060f1SDimitry Andric     // equivalence class ID because every group ends with a unique index.
358fe6060f1SDimitry Andric     for (size_t i = begin; i < mid; ++i)
359fe6060f1SDimitry Andric       icfInputs[i]->icfEqClass[(icfPass + 1) % 2] = mid;
360fe6060f1SDimitry Andric 
361fe6060f1SDimitry Andric     // If we created a group, we need to iterate the main loop again.
362fe6060f1SDimitry Andric     if (mid != end)
363fe6060f1SDimitry Andric       icfRepeat = true;
364fe6060f1SDimitry Andric 
365fe6060f1SDimitry Andric     begin = mid;
366fe6060f1SDimitry Andric   }
367fe6060f1SDimitry Andric }
368fe6060f1SDimitry Andric 
369*81ad6265SDimitry Andric void macho::markSymAsAddrSig(Symbol *s) {
370*81ad6265SDimitry Andric   if (auto *d = dyn_cast_or_null<Defined>(s))
371*81ad6265SDimitry Andric     if (d->isec)
372*81ad6265SDimitry Andric       d->isec->keepUnique = true;
373*81ad6265SDimitry Andric }
374*81ad6265SDimitry Andric 
375*81ad6265SDimitry Andric void macho::markAddrSigSymbols() {
376*81ad6265SDimitry Andric   TimeTraceScope timeScope("Mark addrsig symbols");
377*81ad6265SDimitry Andric   for (InputFile *file : inputFiles) {
378*81ad6265SDimitry Andric     ObjFile *obj = dyn_cast<ObjFile>(file);
379*81ad6265SDimitry Andric     if (!obj)
380*81ad6265SDimitry Andric       continue;
381*81ad6265SDimitry Andric 
382*81ad6265SDimitry Andric     Section *addrSigSection = obj->addrSigSection;
383*81ad6265SDimitry Andric     if (!addrSigSection)
384*81ad6265SDimitry Andric       continue;
385*81ad6265SDimitry Andric     assert(addrSigSection->subsections.size() == 1);
386*81ad6265SDimitry Andric 
387*81ad6265SDimitry Andric     Subsection *subSection = &addrSigSection->subsections[0];
388*81ad6265SDimitry Andric     ArrayRef<unsigned char> &contents = subSection->isec->data;
389*81ad6265SDimitry Andric 
390*81ad6265SDimitry Andric     const uint8_t *pData = contents.begin();
391*81ad6265SDimitry Andric     while (pData != contents.end()) {
392*81ad6265SDimitry Andric       unsigned size;
393*81ad6265SDimitry Andric       const char *err;
394*81ad6265SDimitry Andric       uint32_t symIndex = decodeULEB128(pData, &size, contents.end(), &err);
395*81ad6265SDimitry Andric       if (err)
396*81ad6265SDimitry Andric         fatal(toString(file) + ": could not decode addrsig section: " + err);
397*81ad6265SDimitry Andric       markSymAsAddrSig(obj->symbols[symIndex]);
398*81ad6265SDimitry Andric       pData += size;
399*81ad6265SDimitry Andric     }
400*81ad6265SDimitry Andric   }
401*81ad6265SDimitry Andric }
402*81ad6265SDimitry Andric 
403fe6060f1SDimitry Andric void macho::foldIdenticalSections() {
404fe6060f1SDimitry Andric   TimeTraceScope timeScope("Fold Identical Code Sections");
405fe6060f1SDimitry Andric   // The ICF equivalence-class segregation algorithm relies on pre-computed
406fe6060f1SDimitry Andric   // hashes of InputSection::data for the ConcatOutputSection::inputs and all
407fe6060f1SDimitry Andric   // sections referenced by their relocs. We could recursively traverse the
408fe6060f1SDimitry Andric   // relocs to find every referenced InputSection, but that precludes easy
409fe6060f1SDimitry Andric   // parallelization. Therefore, we hash every InputSection here where we have
410fe6060f1SDimitry Andric   // them all accessible as simple vectors.
411fe6060f1SDimitry Andric 
412fe6060f1SDimitry Andric   // If an InputSection is ineligible for ICF, we give it a unique ID to force
413fe6060f1SDimitry Andric   // it into an unfoldable singleton equivalence class.  Begin the unique-ID
414fe6060f1SDimitry Andric   // space at inputSections.size(), so that it will never intersect with
415fe6060f1SDimitry Andric   // equivalence-class IDs which begin at 0. Since hashes & unique IDs never
416fe6060f1SDimitry Andric   // coexist with equivalence-class IDs, this is not necessary, but might help
417fe6060f1SDimitry Andric   // someone keep the numbers straight in case we ever need to debug the
418fe6060f1SDimitry Andric   // ICF::segregate()
419fe6060f1SDimitry Andric   std::vector<ConcatInputSection *> hashable;
420fe6060f1SDimitry Andric   uint64_t icfUniqueID = inputSections.size();
421fe6060f1SDimitry Andric   for (ConcatInputSection *isec : inputSections) {
422fe6060f1SDimitry Andric     // FIXME: consider non-code __text sections as hashable?
423*81ad6265SDimitry Andric     bool isHashable = (isCodeSection(isec) || isCfStringSection(isec) ||
424*81ad6265SDimitry Andric                        isClassRefsSection(isec)) &&
425*81ad6265SDimitry Andric                       !isec->keepUnique && !isec->shouldOmitFromOutput() &&
426*81ad6265SDimitry Andric                       sectionType(isec->getFlags()) == MachO::S_REGULAR;
427349cc55cSDimitry Andric     if (isHashable) {
428fe6060f1SDimitry Andric       hashable.push_back(isec);
429349cc55cSDimitry Andric       for (Defined *d : isec->symbols)
430349cc55cSDimitry Andric         if (d->unwindEntry)
431349cc55cSDimitry Andric           hashable.push_back(d->unwindEntry);
432*81ad6265SDimitry Andric 
433*81ad6265SDimitry Andric       // __cfstring has embedded addends that foil ICF's hashing / equality
434*81ad6265SDimitry Andric       // checks. (We can ignore embedded addends when doing ICF because the same
435*81ad6265SDimitry Andric       // information gets recorded in our Reloc structs.) We therefore create a
436*81ad6265SDimitry Andric       // mutable copy of the CFString and zero out the embedded addends before
437*81ad6265SDimitry Andric       // performing any hashing / equality checks.
438*81ad6265SDimitry Andric       if (isCfStringSection(isec) || isClassRefsSection(isec)) {
439*81ad6265SDimitry Andric         // We have to do this copying serially as the BumpPtrAllocator is not
440*81ad6265SDimitry Andric         // thread-safe. FIXME: Make a thread-safe allocator.
441*81ad6265SDimitry Andric         MutableArrayRef<uint8_t> copy = isec->data.copy(bAlloc());
442*81ad6265SDimitry Andric         for (const Reloc &r : isec->relocs)
443*81ad6265SDimitry Andric           target->relocateOne(copy.data() + r.offset, r, /*va=*/0,
444*81ad6265SDimitry Andric                               /*relocVA=*/0);
445*81ad6265SDimitry Andric         isec->data = copy;
446*81ad6265SDimitry Andric       }
447*81ad6265SDimitry Andric     } else if (!isEhFrameSection(isec)) {
448*81ad6265SDimitry Andric       // EH frames are gathered as hashables from unwindEntry above; give a
449*81ad6265SDimitry Andric       // unique ID to everything else.
450fe6060f1SDimitry Andric       isec->icfEqClass[0] = ++icfUniqueID;
451fe6060f1SDimitry Andric     }
452349cc55cSDimitry Andric   }
453*81ad6265SDimitry Andric   parallelForEach(hashable, [](ConcatInputSection *isec) {
454*81ad6265SDimitry Andric     assert(isec->icfEqClass[0] == 0); // don't overwrite a unique ID!
455*81ad6265SDimitry Andric     // Turn-on the top bit to guarantee that valid hashes have no collisions
456*81ad6265SDimitry Andric     // with the small-integer unique IDs for ICF-ineligible sections
457*81ad6265SDimitry Andric     isec->icfEqClass[0] = xxHash64(isec->data) | (1ull << 31);
458*81ad6265SDimitry Andric   });
459fe6060f1SDimitry Andric   // Now that every input section is either hashed or marked as unique, run the
460fe6060f1SDimitry Andric   // segregation algorithm to detect foldable subsections.
461fe6060f1SDimitry Andric   ICF(hashable).run();
462fe6060f1SDimitry Andric }
463