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 "Config.h"
12#include "InputSection.h"
13#include "SymbolTable.h"
14#include "Symbols.h"
15
16#include "lld/Common/CommonLinkerContext.h"
17#include "llvm/Support/Parallel.h"
18#include "llvm/Support/TimeProfiler.h"
19#include "llvm/Support/xxhash.h"
20
21#include <atomic>
22
23using namespace llvm;
24using namespace lld;
25using namespace lld::macho;
26
27static constexpr bool verboseDiagnostics = false;
28// This counter is used to generate unique thunk names.
29static uint64_t icfThunkCounter = 0;
30
31class ICF {
32public:
33 ICF(std::vector<ConcatInputSection *> &inputs);
34 void run();
35
36 using EqualsFn = bool (ICF::*)(const ConcatInputSection *,
37 const ConcatInputSection *);
38 void segregate(size_t begin, size_t end, EqualsFn);
39 size_t findBoundary(size_t begin, size_t end);
40 void forEachClassRange(size_t begin, size_t end,
41 llvm::function_ref<void(size_t, size_t)> func);
42 void forEachClass(llvm::function_ref<void(size_t, size_t)> func);
43
44 bool equalsConstant(const ConcatInputSection *ia,
45 const ConcatInputSection *ib);
46 bool equalsVariable(const ConcatInputSection *ia,
47 const ConcatInputSection *ib);
48 void applySafeThunksToRange(size_t begin, size_t end);
49
50 // ICF needs a copy of the inputs vector because its equivalence-class
51 // segregation algorithm destroys the proper sequence.
52 std::vector<ConcatInputSection *> icfInputs;
53
54 unsigned icfPass = 0;
55 std::atomic<bool> icfRepeat{false};
56 std::atomic<uint64_t> equalsConstantCount{0};
57 std::atomic<uint64_t> equalsVariableCount{0};
58};
59
60ICF::ICF(std::vector<ConcatInputSection *> &inputs) {
61 icfInputs.assign(first: inputs.begin(), last: inputs.end());
62}
63
64// ICF = Identical Code Folding
65//
66// We only fold __TEXT,__text, so this is really "code" folding, and not
67// "COMDAT" folding. String and scalar constant literals are deduplicated
68// elsewhere.
69//
70// Summary of segments & sections:
71//
72// The __TEXT segment is readonly at the MMU. Some sections are already
73// deduplicated elsewhere (__TEXT,__cstring & __TEXT,__literal*) and some are
74// synthetic and inherently free of duplicates (__TEXT,__stubs &
75// __TEXT,__unwind_info). Note that we don't yet run ICF on __TEXT,__const,
76// because doing so induces many test failures.
77//
78// The __LINKEDIT segment is readonly at the MMU, yet entirely synthetic, and
79// thus ineligible for ICF.
80//
81// The __DATA_CONST segment is read/write at the MMU, but is logically const to
82// the application after dyld applies fixups to pointer data. We currently
83// fold only the __DATA_CONST,__cfstring section.
84//
85// The __DATA segment is read/write at the MMU, and as application-writeable
86// data, none of its sections are eligible for ICF.
87//
88// Please see the large block comment in lld/ELF/ICF.cpp for an explanation
89// of the segregation algorithm.
90//
91// FIXME(gkm): implement keep-unique attributes
92// FIXME(gkm): implement address-significance tables for MachO object files
93
94static bool isFoldableWithAddendsRemoved(const ConcatInputSection *isec) {
95 return isCfStringSection(isec) || isClassRefsSection(isec) ||
96 isSelRefsSection(isec) || isEhFrameSection(isec);
97}
98
99// Make a normalized copy of a section's bytes by zeroing out the embedded
100// relocs. Return it in the given &buf
101static void getNormalizedData(const ConcatInputSection *isec,
102 SmallVectorImpl<uint8_t> &buf) {
103 buf.assign(in_start: isec->data.begin(), in_end: isec->data.end());
104 for (size_t i = 0; i < isec->relocs.size(); ++i) {
105 const Relocation &r = isec->relocs[i];
106 size_t size = 1ULL << r.length;
107 if (r.offset + size <= buf.size())
108 memset(s: buf.data() + r.offset, c: 0, n: size);
109 if (target->hasAttr(type: r.type, bit: RelocAttrBits::SUBTRAHEND))
110 ++i; // Skip the paired minuend relocation
111 }
112}
113
114static bool compareData(const ConcatInputSection *ia,
115 const ConcatInputSection *ib) {
116 if (ia->data.size() != ib->data.size())
117 return false;
118 if (ia->data == ib->data)
119 return true;
120 if (!isFoldableWithAddendsRemoved(isec: ia))
121 return false;
122 assert(isFoldableWithAddendsRemoved(ib));
123
124 SmallVector<uint8_t, 64> bufA, bufB;
125 getNormalizedData(isec: ia, buf&: bufA);
126 getNormalizedData(isec: ib, buf&: bufB);
127 return bufA == bufB;
128}
129
130// Compare "non-moving" parts of two ConcatInputSections, namely everything
131// except references to other ConcatInputSections.
132bool ICF::equalsConstant(const ConcatInputSection *ia,
133 const ConcatInputSection *ib) {
134 if (verboseDiagnostics)
135 ++equalsConstantCount;
136 // We can only fold within the same OutputSection.
137 if (ia->parent != ib->parent)
138 return false;
139 if (!compareData(ia, ib))
140 return false;
141 auto f = [](const Relocation &ra, const Relocation &rb) {
142 if (ra.type != rb.type)
143 return false;
144 if (ra.pcrel != rb.pcrel)
145 return false;
146 if (ra.length != rb.length)
147 return false;
148 if (ra.offset != rb.offset)
149 return false;
150 if (isa<Symbol *>(Val: ra.referent) != isa<Symbol *>(Val: rb.referent))
151 return false;
152
153 InputSection *isecA, *isecB;
154
155 uint64_t valueA = 0;
156 uint64_t valueB = 0;
157 if (isa<Symbol *>(Val: ra.referent)) {
158 const auto *sa = cast<Symbol *>(Val: ra.referent);
159 const auto *sb = cast<Symbol *>(Val: rb.referent);
160 if (sa->kind() != sb->kind())
161 return false;
162 // ICF runs before Undefineds are treated (and potentially converted into
163 // DylibSymbols).
164 if (isa<DylibSymbol>(Val: sa) || isa<Undefined>(Val: sa))
165 return sa == sb && ra.addend == rb.addend;
166 assert(isa<Defined>(sa));
167 const auto *da = cast<Defined>(Val: sa);
168 const auto *db = cast<Defined>(Val: sb);
169 if (!da->isec() || !db->isec()) {
170 assert(da->isAbsolute() && db->isAbsolute());
171 return da->value + ra.addend == db->value + rb.addend;
172 }
173 isecA = da->isec();
174 valueA = da->value;
175 isecB = db->isec();
176 valueB = db->value;
177 } else {
178 isecA = cast<InputSection *>(Val: ra.referent);
179 isecB = cast<InputSection *>(Val: rb.referent);
180 }
181
182 // Typically, we should not encounter sections marked with `keepUnique` at
183 // this point as they would have resulted in different hashes and therefore
184 // no need for a full comparison.
185 // However, in `safe_thunks` mode, it's possible for two different
186 // relocations to reference identical `keepUnique` functions that will be
187 // distinguished later via thunks - so we need to handle this case
188 // explicitly.
189 if ((isecA != isecB) && ((isecA->keepUnique && isCodeSection(isecA)) ||
190 (isecB->keepUnique && isCodeSection(isecB))))
191 return false;
192
193 if (isecA->parent != isecB->parent)
194 return false;
195 // Sections with identical parents should be of the same kind.
196 assert(isecA->kind() == isecB->kind());
197 // We will compare ConcatInputSection contents in equalsVariable.
198 if (isa<ConcatInputSection>(Val: isecA))
199 return ra.addend == rb.addend;
200 // Else we have two literal sections. References to them are equal iff their
201 // offsets in the output section are equal.
202 if (isa<Symbol *>(Val: ra.referent))
203 // For symbol relocs, we compare the contents at the symbol address. We
204 // don't do `getOffset(value + addend)` because value + addend may not be
205 // a valid offset in the literal section.
206 return isecA->getOffset(off: valueA) == isecB->getOffset(off: valueB) &&
207 ra.addend == rb.addend;
208 assert(valueA == 0 && valueB == 0);
209 // For section relocs, we compare the content at the section offset.
210 return isecA->getOffset(off: ra.addend) == isecB->getOffset(off: rb.addend);
211 };
212 if (!llvm::equal(LRange: ia->relocs, RRange: ib->relocs, P: f))
213 return false;
214
215 // Check unwind info structural compatibility: if there are symbols with
216 // associated unwind info, check that both sections have compatible symbol
217 // layouts. For simplicity, we only attempt folding when all symbols are at
218 // offset zero within the section (which is typically the case with
219 // .subsections_via_symbols.)
220 auto hasUnwind = [](Defined *d) { return d->unwindEntry() != nullptr; };
221 const auto *itA = llvm::find_if(Range: ia->symbols, P: hasUnwind);
222 const auto *itB = llvm::find_if(Range: ib->symbols, P: hasUnwind);
223 if (itA == ia->symbols.end())
224 return itB == ib->symbols.end();
225 if (itB == ib->symbols.end())
226 return false;
227 const Defined *da = *itA;
228 const Defined *db = *itB;
229 if (da->value != 0 || db->value != 0)
230 return false;
231 auto isZero = [](Defined *d) { return d->value == 0; };
232 // Since symbols are stored in order of value, and since we have already
233 // checked that da/db have value zero, we just need to do the isZero check on
234 // the subsequent symbols.
235 return std::find_if_not(first: std::next(x: itA), last: ia->symbols.end(), pred: isZero) ==
236 ia->symbols.end() &&
237 std::find_if_not(first: std::next(x: itB), last: ib->symbols.end(), pred: isZero) ==
238 ib->symbols.end();
239}
240
241// Compare the "moving" parts of two ConcatInputSections -- i.e. everything not
242// handled by equalsConstant().
243bool ICF::equalsVariable(const ConcatInputSection *ia,
244 const ConcatInputSection *ib) {
245 if (verboseDiagnostics)
246 ++equalsVariableCount;
247 assert(ia->relocs.size() == ib->relocs.size());
248 auto f = [this](const Relocation &ra, const Relocation &rb) {
249 // We already filtered out mismatching values/addends in equalsConstant.
250 if (ra.referent == rb.referent)
251 return true;
252 const ConcatInputSection *isecA, *isecB;
253 if (isa<Symbol *>(Val: ra.referent)) {
254 // Matching DylibSymbols are already filtered out by the
255 // identical-referent check above. Non-matching DylibSymbols were filtered
256 // out in equalsConstant(). So we can safely cast to Defined here.
257 const auto *da = cast<Defined>(Val: cast<Symbol *>(Val: ra.referent));
258 const auto *db = cast<Defined>(Val: cast<Symbol *>(Val: rb.referent));
259 if (da->isAbsolute())
260 return true;
261 isecA = dyn_cast<ConcatInputSection>(Val: da->isec());
262 if (!isecA)
263 return true; // literal sections were checked in equalsConstant.
264 isecB = cast<ConcatInputSection>(Val: db->isec());
265 } else {
266 const auto *sa = cast<InputSection *>(Val: ra.referent);
267 const auto *sb = cast<InputSection *>(Val: rb.referent);
268 isecA = dyn_cast<ConcatInputSection>(Val: sa);
269 if (!isecA)
270 return true;
271 isecB = cast<ConcatInputSection>(Val: sb);
272 }
273 return isecA->icfEqClass[icfPass % 2] == isecB->icfEqClass[icfPass % 2];
274 };
275 if (!llvm::equal(LRange: ia->relocs, RRange: ib->relocs, P: f))
276 return false;
277
278 // Compare unwind info equivalence classes.
279 auto hasUnwind = [](Defined *d) { return d->unwindEntry() != nullptr; };
280 const auto *itA = llvm::find_if(Range: ia->symbols, P: hasUnwind);
281 if (itA == ia->symbols.end())
282 return true;
283 const Defined *da = *itA;
284 // equalsConstant() guarantees that both sections have unwind info.
285 const Defined *db = *llvm::find_if(Range: ib->symbols, P: hasUnwind);
286 return da->unwindEntry()->icfEqClass[icfPass % 2] ==
287 db->unwindEntry()->icfEqClass[icfPass % 2];
288}
289
290// Find the first InputSection after BEGIN whose equivalence class differs
291size_t ICF::findBoundary(size_t begin, size_t end) {
292 uint64_t beginHash = icfInputs[begin]->icfEqClass[icfPass % 2];
293 for (size_t i = begin + 1; i < end; ++i)
294 if (beginHash != icfInputs[i]->icfEqClass[icfPass % 2])
295 return i;
296 return end;
297}
298
299// Invoke FUNC on subranges with matching equivalence class
300void ICF::forEachClassRange(size_t begin, size_t end,
301 llvm::function_ref<void(size_t, size_t)> func) {
302 while (begin < end) {
303 size_t mid = findBoundary(begin, end);
304 func(begin, mid);
305 begin = mid;
306 }
307}
308
309// Find or create a symbol at offset 0 in the given section
310static Symbol *getThunkTargetSymbol(ConcatInputSection *isec) {
311 for (Symbol *sym : isec->symbols)
312 if (auto *d = dyn_cast<Defined>(Val: sym))
313 if (d->value == 0)
314 return sym;
315
316 std::string thunkName;
317 if (isec->symbols.size() == 0)
318 thunkName = isec->getName().str() + ".icf.0";
319 else
320 thunkName = isec->getName().str() + "icf.thunk.target" +
321 std::to_string(val: icfThunkCounter++);
322
323 // If no symbol found at offset 0, create one
324 auto *sym = make<Defined>(args&: thunkName, /*file=*/args: nullptr, args&: isec,
325 /*value=*/args: 0, /*size=*/args: isec->getSize(),
326 /*isWeakDef=*/args: false, /*isExternal=*/args: false,
327 /*isPrivateExtern=*/args: false, /*isThumb=*/args: false,
328 /*isReferencedDynamically=*/args: false,
329 /*noDeadStrip=*/args: false);
330 isec->symbols.push_back(NewVal: sym);
331 return sym;
332}
333
334// Given a range of identical icfInputs, replace address significant functions
335// with a thunk that is just a direct branch to the first function in the
336// series. This way we keep only one main body of the function but we still
337// retain the address uniqueness of relevant functions by having them be a
338// direct branch thunk rather than containing a full copy of the actual function
339// body.
340void ICF::applySafeThunksToRange(size_t begin, size_t end) {
341 // When creating a unique ICF thunk, use the first section as the section that
342 // all thunks will branch to.
343 ConcatInputSection *masterIsec = icfInputs[begin];
344
345 // If the first section is not address significant, sorting guarantees that
346 // there are no address significant functions. So we can skip this range.
347 if (!masterIsec->keepUnique)
348 return;
349
350 // Skip anything that is not a code section.
351 if (!isCodeSection(masterIsec))
352 return;
353
354 // If the functions we're dealing with are smaller than the thunk size, then
355 // just leave them all as-is - creating thunks would be a net loss.
356 uint32_t thunkSize = target->getICFSafeThunkSize();
357 if (masterIsec->data.size() <= thunkSize)
358 return;
359
360 // Get the symbol that all thunks will branch to.
361 Symbol *masterSym = getThunkTargetSymbol(isec: masterIsec);
362
363 for (size_t i = begin + 1; i < end; ++i) {
364 ConcatInputSection *isec = icfInputs[i];
365 // When we're done processing keepUnique entries, we can stop. Sorting
366 // guaratees that all keepUnique will be at the front.
367 if (!isec->keepUnique)
368 break;
369
370 ConcatInputSection *thunk =
371 makeSyntheticInputSection(segName: isec->getSegName(), sectName: isec->getName());
372 // A thunk-folded cold function has a cold thunk.
373 thunk->isCold = isec->isCold;
374 addInputSection(inputSection: thunk);
375
376 target->initICFSafeThunkBody(thunk, targetSym: masterSym);
377 thunk->foldIdentical(redundant: isec, foldKind: Symbol::ICFFoldKind::Thunk);
378
379 // Since we're folding the target function into a thunk, we need to adjust
380 // the symbols that now got relocated from the target function to the thunk.
381 // Since the thunk is only one branch, we move all symbols to offset 0 and
382 // make sure that the size of all non-zero-size symbols is equal to the size
383 // of the branch.
384 for (auto *sym : thunk->symbols) {
385 sym->value = 0;
386 if (sym->size != 0)
387 sym->size = thunkSize;
388 }
389 }
390}
391
392// Split icfInputs into shards, then parallelize invocation of FUNC on subranges
393// with matching equivalence class
394void ICF::forEachClass(llvm::function_ref<void(size_t, size_t)> func) {
395 // Only use threads when the benefits outweigh the overhead.
396 const size_t threadingThreshold = 1024;
397 if (icfInputs.size() < threadingThreshold) {
398 forEachClassRange(begin: 0, end: icfInputs.size(), func);
399 ++icfPass;
400 return;
401 }
402
403 // Shard into non-overlapping intervals, and call FUNC in parallel. The
404 // sharding must be completed before any calls to FUNC are made so that FUNC
405 // can modify the InputSection in its shard without causing data races.
406 const size_t shards = 256;
407 size_t step = icfInputs.size() / shards;
408 size_t boundaries[shards + 1];
409 boundaries[0] = 0;
410 boundaries[shards] = icfInputs.size();
411 parallelFor(Begin: 1, End: shards, Fn: [&](size_t i) {
412 boundaries[i] = findBoundary(begin: (i - 1) * step, end: icfInputs.size());
413 });
414 parallelFor(Begin: 1, End: shards + 1, Fn: [&](size_t i) {
415 if (boundaries[i - 1] < boundaries[i]) {
416 forEachClassRange(begin: boundaries[i - 1], end: boundaries[i], func);
417 }
418 });
419 ++icfPass;
420}
421
422void ICF::run() {
423 // Into each origin-section hash, combine all reloc referent section hashes.
424 for (icfPass = 0; icfPass < 2; ++icfPass) {
425 parallelForEach(R&: icfInputs, Fn: [&](ConcatInputSection *isec) {
426 uint32_t hash = isec->icfEqClass[icfPass % 2];
427 for (const Relocation &r : isec->relocs) {
428 if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
429 if (auto *defined = dyn_cast<Defined>(Val: sym)) {
430 if (defined->isec()) {
431 if (auto *referentIsec =
432 dyn_cast<ConcatInputSection>(Val: defined->isec()))
433 hash += defined->value + referentIsec->icfEqClass[icfPass % 2];
434 else
435 hash += defined->isec()->kind() +
436 defined->isec()->getOffset(off: defined->value);
437 } else {
438 hash += defined->value;
439 }
440 } else {
441 // ICF runs before Undefined diags
442 assert(isa<Undefined>(sym) || isa<DylibSymbol>(sym));
443 }
444 }
445 }
446 // Set MSB to 1 to avoid collisions with non-hashed classes.
447 isec->icfEqClass[(icfPass + 1) % 2] = hash | (1ull << 31);
448 });
449 }
450 const bool useSafeThunks = config->icfLevel == ICFLevel::safe_thunks;
451 llvm::stable_sort(
452 Range&: icfInputs, C: [&](const ConcatInputSection *a, const ConcatInputSection *b) {
453 // When using safe_thunks, ensure that we first sort by icfEqClass and
454 // then by keepUnique (descending). This guarantees that within an
455 // equivalence class, the keepUnique inputs are always first.
456 if (useSafeThunks)
457 if (a->icfEqClass[0] == b->icfEqClass[0])
458 return a->keepUnique > b->keepUnique;
459 return a->icfEqClass[0] < b->icfEqClass[0];
460 });
461 forEachClass(func: [&](size_t begin, size_t end) {
462 segregate(begin, end, &ICF::equalsConstant);
463 });
464
465 // Split equivalence groups by comparing relocations until convergence
466 do {
467 icfRepeat = false;
468 forEachClass(func: [&](size_t begin, size_t end) {
469 segregate(begin, end, &ICF::equalsVariable);
470 });
471 } while (icfRepeat);
472 log(msg: "ICF needed " + Twine(icfPass) + " iterations");
473 if (verboseDiagnostics) {
474 log(msg: "equalsConstant() called " + Twine(equalsConstantCount) + " times");
475 log(msg: "equalsVariable() called " + Twine(equalsVariableCount) + " times");
476 }
477
478 // When using safe_thunks, we need to create thunks for all keepUnique
479 // functions that can be deduplicated. Since we're creating / adding new
480 // InputSections, we can't paralellize this.
481 if (useSafeThunks)
482 forEachClassRange(begin: 0, end: icfInputs.size(), func: [&](size_t begin, size_t end) {
483 applySafeThunksToRange(begin, end);
484 });
485
486 // Fold sections within equivalence classes
487 forEachClass(func: [&](size_t begin, size_t end) {
488 if (end - begin < 2)
489 return;
490 // For ICF level safe_thunks, replace keepUnique function bodies with
491 // thunks. For all other ICF levels, directly merge the functions.
492
493 ConcatInputSection *beginIsec = icfInputs[begin];
494 for (size_t i = begin + 1; i < end; ++i) {
495 // Skip keepUnique inputs when using safe_thunks (already handled above)
496 if (useSafeThunks && isCodeSection(beginIsec) &&
497 icfInputs[i]->keepUnique) {
498 // Assert keepUnique sections are either small or replaced with thunks.
499 assert(!icfInputs[i]->live ||
500 icfInputs[i]->data.size() <= target->getICFSafeThunkSize());
501 assert(!icfInputs[i]->replacement ||
502 icfInputs[i]->replacement->data.size() ==
503 target->getICFSafeThunkSize());
504 continue;
505 }
506 beginIsec->foldIdentical(redundant: icfInputs[i]);
507 // Make sure we don't fold hot code into cold regions.
508 if (!icfInputs[i]->isCold)
509 beginIsec->isCold = false;
510 }
511 });
512}
513
514// Split an equivalence class into smaller classes.
515void ICF::segregate(size_t begin, size_t end, EqualsFn equals) {
516 while (begin < end) {
517 // Divide [begin, end) into two. Let mid be the start index of the
518 // second group.
519 auto bound = std::stable_partition(
520 first: icfInputs.begin() + begin + 1, last: icfInputs.begin() + end,
521 pred: [&](ConcatInputSection *isec) {
522 return (this->*equals)(icfInputs[begin], isec);
523 });
524 size_t mid = bound - icfInputs.begin();
525
526 // Split [begin, end) into [begin, mid) and [mid, end). We use mid as an
527 // equivalence class ID because every group ends with a unique index.
528 for (size_t i = begin; i < mid; ++i)
529 icfInputs[i]->icfEqClass[(icfPass + 1) % 2] = mid;
530
531 // If we created a group, we need to iterate the main loop again.
532 if (mid != end)
533 icfRepeat = true;
534
535 begin = mid;
536 }
537}
538
539void macho::markSymAsAddrSig(Symbol *s) {
540 if (auto *d = dyn_cast_or_null<Defined>(Val: s))
541 if (d->isec())
542 d->isec()->keepUnique = true;
543}
544
545void macho::markAddrSigSymbols() {
546 TimeTraceScope timeScope("Mark addrsig symbols");
547 for (InputFile *file : inputFiles) {
548 ObjFile *obj = dyn_cast<ObjFile>(Val: file);
549 if (!obj)
550 continue;
551
552 Section *addrSigSection = obj->addrSigSection;
553 if (!addrSigSection) {
554 for (Symbol *sym : obj->symbols)
555 markSymAsAddrSig(s: sym);
556 continue;
557 }
558 assert(addrSigSection->subsections.size() == 1);
559
560 const InputSection *isec = addrSigSection->subsections[0].isec;
561
562 for (const Relocation &r : isec->relocs) {
563 if (auto *sym = r.referent.dyn_cast<Symbol *>())
564 markSymAsAddrSig(s: sym);
565 else
566 error(msg: toString(isec) + ": unexpected section relocation");
567 }
568 }
569}
570
571// Given a symbol that was folded into a thunk, return the symbol pointing to
572// the actual body of the function. We use this approach rather than storing the
573// needed info in the Defined itself in order to minimize memory usage.
574Defined *macho::getBodyForThunkFoldedSym(Defined *foldedSym) {
575 assert(isa<ConcatInputSection>(foldedSym->originalIsec) &&
576 "thunk-folded ICF symbol expected to be on a ConcatInputSection");
577 // foldedSec is the InputSection that was marked as deleted upon fold
578 ConcatInputSection *foldedSec =
579 cast<ConcatInputSection>(Val: foldedSym->originalIsec);
580
581 // thunkBody is the actual live thunk, containing the code that branches to
582 // the actual body of the function.
583 InputSection *thunkBody = foldedSec->replacement;
584
585 // The symbol of the merged body of the function that the thunk jumps to. This
586 // will end up in the final binary.
587 Symbol *targetSym = target->getThunkBranchTarget(thunk: thunkBody);
588
589 return cast<Defined>(Val: targetSym);
590}
591void macho::foldIdenticalSections(bool onlyCfStrings) {
592 TimeTraceScope timeScope("Fold Identical Code Sections");
593 // The ICF equivalence-class segregation algorithm relies on pre-computed
594 // hashes of InputSection::data for the ConcatOutputSection::inputs and all
595 // sections referenced by their relocs. We could recursively traverse the
596 // relocs to find every referenced InputSection, but that precludes easy
597 // parallelization. Therefore, we hash every InputSection here where we have
598 // them all accessible as simple vectors.
599
600 // If an InputSection is ineligible for ICF, we give it a unique ID to force
601 // it into an unfoldable singleton equivalence class. Begin the unique-ID
602 // space at inputSections.size(), so that it will never intersect with
603 // equivalence-class IDs which begin at 0. Since hashes & unique IDs never
604 // coexist with equivalence-class IDs, this is not necessary, but might help
605 // someone keep the numbers straight in case we ever need to debug the
606 // ICF::segregate()
607 std::vector<ConcatInputSection *> foldable;
608 uint64_t icfUniqueID = inputSections.size();
609 // Reset the thunk counter for each run of ICF.
610 icfThunkCounter = 0;
611 for (ConcatInputSection *isec : inputSections) {
612 bool isUnconditionallyCoalescedData = isCfStringSection(isec) ||
613 isClassRefsSection(isec) ||
614 isSelRefsSection(isec);
615 // NOTE: __objc_selrefs is typically marked as no_dead_strip by MC, but we
616 // can still fold it.
617 bool hasFoldableFlags = (isSelRefsSection(isec) ||
618 sectionType(flags: isec->getFlags()) == MachO::S_REGULAR);
619
620 bool isCodeSec = isCodeSection(isec);
621
622 // Determine whether keepUnique forbids folding this section.
623 // - __cfstring / __objc_classrefs / __objc_selrefs always fold
624 // regardless of keepUnique. Compilers currently emit over-broad
625 // __llvm_addrsig entries that can cover non-address-significant data
626 // symbols in these sections; ld64 coalesces them unconditionally, and
627 // we match that behavior.
628 // - Under safe_thunks, keepUnique code sections still fold; the
629 // safe_thunks logic is applied later at merge time based on the
630 // keepUnique flag.
631 // - Otherwise, keepUnique sections are not foldable.
632 // Happens to match isFoldableWithAddendsRemoved today, but expresses a
633 // different intent (ld64's coalescing semantics, not addend stripping),
634 // so the two may diverge as either list grows.
635 bool isSafeThunksCode =
636 config->icfLevel == ICFLevel::safe_thunks && isCodeSec;
637 bool keepUniqueAllowsFolding =
638 !isec->keepUnique || isUnconditionallyCoalescedData || isSafeThunksCode;
639
640 // FIXME: consider non-code __text sections as foldable?
641 bool isFoldable = (!onlyCfStrings || isCfStringSection(isec)) &&
642 (isCodeSec || isFoldableWithAddendsRemoved(isec) ||
643 isGccExceptTabSection(isec)) &&
644 keepUniqueAllowsFolding && !isec->hasAltEntry &&
645 !isec->shouldOmitFromOutput() && hasFoldableFlags;
646 if (isFoldable) {
647 foldable.push_back(x: isec);
648 for (Defined *d : isec->symbols)
649 if (d->unwindEntry())
650 foldable.push_back(x: d->unwindEntry());
651 } else if (isEhFrameSection(isec)) {
652 // __eh_frame contains two types of records: FDEs and CIEs.
653 // Functions point to FDEs, which are already collected above via
654 // unwindEntry(). CIEs are shared headers and are not attached to
655 // individual functions. Collect only CIEs here so they can also be hashed
656 // and deduplicated.
657 auto *obj = dyn_cast_or_null<ObjFile>(Val: isec->getFile());
658 if (!onlyCfStrings && obj && !obj->fdes.contains(Val: isec) &&
659 !isec->shouldOmitFromOutput())
660 foldable.push_back(x: isec);
661 } else {
662 // Give a unique ID to everything else.
663 isec->icfEqClass[0] = ++icfUniqueID;
664 }
665 }
666 parallelForEach(R&: foldable, Fn: [](ConcatInputSection *isec) {
667 assert(isec->icfEqClass[0] == 0); // don't overwrite a unique ID!
668 uint64_t hash;
669 if (isFoldableWithAddendsRemoved(isec)) {
670 SmallVector<uint8_t, 64> stackBuf;
671 getNormalizedData(isec, buf&: stackBuf);
672 hash = xxh3_64bits(data: stackBuf);
673 } else {
674 hash = xxh3_64bits(data: isec->data);
675 }
676 // Turn-on the top bit to guarantee that valid hashes have no collisions
677 // with the small-integer unique IDs for ICF-ineligible sections
678 isec->icfEqClass[0] = hash | (1ull << 31);
679 });
680 // Now that every input section is either hashed or marked as unique, run the
681 // segregation algorithm to detect foldable subsections.
682 ICF(foldable).run();
683}
684