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