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 "llvm/Support/Parallel.h" 16 #include "llvm/Support/TimeProfiler.h" 17 18 #include <atomic> 19 20 using namespace llvm; 21 using namespace lld; 22 using namespace lld::macho; 23 24 class ICF { 25 public: 26 ICF(std::vector<ConcatInputSection *> &inputs); 27 28 void run(); 29 void segregate(size_t begin, size_t end, 30 std::function<bool(const ConcatInputSection *, 31 const ConcatInputSection *)> 32 equals); 33 size_t findBoundary(size_t begin, size_t end); 34 void forEachClassRange(size_t begin, size_t end, 35 std::function<void(size_t, size_t)> func); 36 void forEachClass(std::function<void(size_t, size_t)> func); 37 38 // ICF needs a copy of the inputs vector because its equivalence-class 39 // segregation algorithm destroys the proper sequence. 40 std::vector<ConcatInputSection *> icfInputs; 41 }; 42 43 ICF::ICF(std::vector<ConcatInputSection *> &inputs) { 44 icfInputs.assign(inputs.begin(), inputs.end()); 45 } 46 47 // ICF = Identical Code Folding 48 // 49 // We only fold __TEXT,__text, so this is really "code" folding, and not 50 // "COMDAT" folding. String and scalar constant literals are deduplicated 51 // elsewhere. 52 // 53 // Summary of segments & sections: 54 // 55 // The __TEXT segment is readonly at the MMU. Some sections are already 56 // deduplicated elsewhere (__TEXT,__cstring & __TEXT,__literal*) and some are 57 // synthetic and inherently free of duplicates (__TEXT,__stubs & 58 // __TEXT,__unwind_info). Note that we don't yet run ICF on __TEXT,__const, 59 // because doing so induces many test failures. 60 // 61 // The __LINKEDIT segment is readonly at the MMU, yet entirely synthetic, and 62 // thus ineligible for ICF. 63 // 64 // The __DATA_CONST segment is read/write at the MMU, but is logically const to 65 // the application after dyld applies fixups to pointer data. We currently 66 // fold only the __DATA_CONST,__cfstring section. 67 // 68 // The __DATA segment is read/write at the MMU, and as application-writeable 69 // data, none of its sections are eligible for ICF. 70 // 71 // Please see the large block comment in lld/ELF/ICF.cpp for an explanation 72 // of the segregation algorithm. 73 // 74 // FIXME(gkm): implement keep-unique attributes 75 // FIXME(gkm): implement address-significance tables for MachO object files 76 77 static unsigned icfPass = 0; 78 static std::atomic<bool> icfRepeat{false}; 79 80 // Compare "non-moving" parts of two ConcatInputSections, namely everything 81 // except references to other ConcatInputSections. 82 static bool equalsConstant(const ConcatInputSection *ia, 83 const ConcatInputSection *ib) { 84 // We can only fold within the same OutputSection. 85 if (ia->parent != ib->parent) 86 return false; 87 if (ia->data.size() != ib->data.size()) 88 return false; 89 if (ia->data != ib->data) 90 return false; 91 if (ia->relocs.size() != ib->relocs.size()) 92 return false; 93 auto f = [](const Reloc &ra, const Reloc &rb) { 94 if (ra.type != rb.type) 95 return false; 96 if (ra.pcrel != rb.pcrel) 97 return false; 98 if (ra.length != rb.length) 99 return false; 100 if (ra.offset != rb.offset) 101 return false; 102 if (ra.addend != rb.addend) 103 return false; 104 if (ra.referent.is<Symbol *>() != rb.referent.is<Symbol *>()) 105 return false; 106 107 InputSection *isecA, *isecB; 108 if (ra.referent.is<Symbol *>()) { 109 const auto *sa = ra.referent.get<Symbol *>(); 110 const auto *sb = rb.referent.get<Symbol *>(); 111 if (sa->kind() != sb->kind()) 112 return false; 113 if (!isa<Defined>(sa)) { 114 assert(isa<DylibSymbol>(sa)); 115 return sa == sb; 116 } 117 const auto *da = cast<Defined>(sa); 118 const auto *db = cast<Defined>(sb); 119 if (!da->isec || !db->isec) { 120 assert(da->isAbsolute() && db->isAbsolute()); 121 return da->value == db->value; 122 } 123 isecA = da->isec; 124 isecB = db->isec; 125 } else { 126 isecA = ra.referent.get<InputSection *>(); 127 isecB = rb.referent.get<InputSection *>(); 128 } 129 130 if (isecA->parent != isecB->parent) 131 return false; 132 // Sections with identical parents should be of the same kind. 133 assert(isecA->kind() == isecB->kind()); 134 // We will compare ConcatInputSection contents in equalsVariable. 135 if (isa<ConcatInputSection>(isecA)) 136 return true; 137 // Else we have two literal sections. References to them are equal iff their 138 // offsets in the output section are equal. 139 return isecA->getOffset(ra.addend) == isecB->getOffset(rb.addend); 140 }; 141 return std::equal(ia->relocs.begin(), ia->relocs.end(), ib->relocs.begin(), 142 f); 143 } 144 145 // Compare the "moving" parts of two ConcatInputSections -- i.e. everything not 146 // handled by equalsConstant(). 147 static bool equalsVariable(const ConcatInputSection *ia, 148 const ConcatInputSection *ib) { 149 assert(ia->relocs.size() == ib->relocs.size()); 150 auto f = [](const Reloc &ra, const Reloc &rb) { 151 // We already filtered out mismatching values/addends in equalsConstant. 152 if (ra.referent == rb.referent) 153 return true; 154 const ConcatInputSection *isecA, *isecB; 155 if (ra.referent.is<Symbol *>()) { 156 // Matching DylibSymbols are already filtered out by the 157 // identical-referent check above. Non-matching DylibSymbols were filtered 158 // out in equalsConstant(). So we can safely cast to Defined here. 159 const auto *da = cast<Defined>(ra.referent.get<Symbol *>()); 160 const auto *db = cast<Defined>(rb.referent.get<Symbol *>()); 161 if (da->isAbsolute()) 162 return true; 163 isecA = dyn_cast<ConcatInputSection>(da->isec); 164 if (!isecA) 165 return true; // literal sections were checked in equalsConstant. 166 isecB = cast<ConcatInputSection>(db->isec); 167 } else { 168 const auto *sa = ra.referent.get<InputSection *>(); 169 const auto *sb = rb.referent.get<InputSection *>(); 170 isecA = dyn_cast<ConcatInputSection>(sa); 171 if (!isecA) 172 return true; 173 isecB = cast<ConcatInputSection>(sb); 174 } 175 return isecA->icfEqClass[icfPass % 2] == isecB->icfEqClass[icfPass % 2]; 176 }; 177 return std::equal(ia->relocs.begin(), ia->relocs.end(), ib->relocs.begin(), 178 f); 179 } 180 181 // Find the first InputSection after BEGIN whose equivalence class differs 182 size_t ICF::findBoundary(size_t begin, size_t end) { 183 uint64_t beginHash = icfInputs[begin]->icfEqClass[icfPass % 2]; 184 for (size_t i = begin + 1; i < end; ++i) 185 if (beginHash != icfInputs[i]->icfEqClass[icfPass % 2]) 186 return i; 187 return end; 188 } 189 190 // Invoke FUNC on subranges with matching equivalence class 191 void ICF::forEachClassRange(size_t begin, size_t end, 192 std::function<void(size_t, size_t)> func) { 193 while (begin < end) { 194 size_t mid = findBoundary(begin, end); 195 func(begin, mid); 196 begin = mid; 197 } 198 } 199 200 // Split icfInputs into shards, then parallelize invocation of FUNC on subranges 201 // with matching equivalence class 202 void ICF::forEachClass(std::function<void(size_t, size_t)> func) { 203 // Only use threads when the benefits outweigh the overhead. 204 const size_t threadingThreshold = 1024; 205 if (icfInputs.size() < threadingThreshold) { 206 forEachClassRange(0, icfInputs.size(), func); 207 ++icfPass; 208 return; 209 } 210 211 // Shard into non-overlapping intervals, and call FUNC in parallel. The 212 // sharding must be completed before any calls to FUNC are made so that FUNC 213 // can modify the InputSection in its shard without causing data races. 214 const size_t shards = 256; 215 size_t step = icfInputs.size() / shards; 216 size_t boundaries[shards + 1]; 217 boundaries[0] = 0; 218 boundaries[shards] = icfInputs.size(); 219 parallelForEachN(1, shards, [&](size_t i) { 220 boundaries[i] = findBoundary((i - 1) * step, icfInputs.size()); 221 }); 222 parallelForEachN(1, shards + 1, [&](size_t i) { 223 if (boundaries[i - 1] < boundaries[i]) { 224 forEachClassRange(boundaries[i - 1], boundaries[i], func); 225 } 226 }); 227 ++icfPass; 228 } 229 230 void ICF::run() { 231 // Into each origin-section hash, combine all reloc referent section hashes. 232 for (icfPass = 0; icfPass < 2; ++icfPass) { 233 parallelForEach(icfInputs, [&](ConcatInputSection *isec) { 234 uint64_t hash = isec->icfEqClass[icfPass % 2]; 235 for (const Reloc &r : isec->relocs) { 236 if (auto *sym = r.referent.dyn_cast<Symbol *>()) { 237 if (auto *dylibSym = dyn_cast<DylibSymbol>(sym)) 238 hash += dylibSym->stubsHelperIndex; 239 else if (auto *defined = dyn_cast<Defined>(sym)) { 240 if (defined->isec) { 241 if (auto isec = dyn_cast<ConcatInputSection>(defined->isec)) 242 hash += defined->value + isec->icfEqClass[icfPass % 2]; 243 else 244 hash += defined->isec->kind() + 245 defined->isec->getOffset(defined->value); 246 } else { 247 hash += defined->value; 248 } 249 } else 250 llvm_unreachable("foldIdenticalSections symbol kind"); 251 } 252 } 253 // Set MSB to 1 to avoid collisions with non-hashed classes. 254 isec->icfEqClass[(icfPass + 1) % 2] = hash | (1ull << 63); 255 }); 256 } 257 258 llvm::stable_sort( 259 icfInputs, [](const ConcatInputSection *a, const ConcatInputSection *b) { 260 return a->icfEqClass[0] < b->icfEqClass[0]; 261 }); 262 forEachClass( 263 [&](size_t begin, size_t end) { segregate(begin, end, equalsConstant); }); 264 265 // Split equivalence groups by comparing relocations until convergence 266 do { 267 icfRepeat = false; 268 forEachClass([&](size_t begin, size_t end) { 269 segregate(begin, end, equalsVariable); 270 }); 271 } while (icfRepeat); 272 log("ICF needed " + Twine(icfPass) + " iterations"); 273 274 // Fold sections within equivalence classes 275 forEachClass([&](size_t begin, size_t end) { 276 if (end - begin < 2) 277 return; 278 ConcatInputSection *beginIsec = icfInputs[begin]; 279 for (size_t i = begin + 1; i < end; ++i) 280 beginIsec->foldIdentical(icfInputs[i]); 281 }); 282 } 283 284 // Split an equivalence class into smaller classes. 285 void ICF::segregate( 286 size_t begin, size_t end, 287 std::function<bool(const ConcatInputSection *, const ConcatInputSection *)> 288 equals) { 289 while (begin < end) { 290 // Divide [begin, end) into two. Let mid be the start index of the 291 // second group. 292 auto bound = std::stable_partition(icfInputs.begin() + begin + 1, 293 icfInputs.begin() + end, 294 [&](ConcatInputSection *isec) { 295 return equals(icfInputs[begin], isec); 296 }); 297 size_t mid = bound - icfInputs.begin(); 298 299 // Split [begin, end) into [begin, mid) and [mid, end). We use mid as an 300 // equivalence class ID because every group ends with a unique index. 301 for (size_t i = begin; i < mid; ++i) 302 icfInputs[i]->icfEqClass[(icfPass + 1) % 2] = mid; 303 304 // If we created a group, we need to iterate the main loop again. 305 if (mid != end) 306 icfRepeat = true; 307 308 begin = mid; 309 } 310 } 311 312 template <class Ptr> 313 DenseSet<const InputSection *> findFunctionsWithUnwindInfo() { 314 DenseSet<const InputSection *> result; 315 for (ConcatInputSection *isec : in.unwindInfo->getInputs()) { 316 for (size_t i = 0; i < isec->relocs.size(); ++i) { 317 Reloc &r = isec->relocs[i]; 318 assert(target->hasAttr(r.type, RelocAttrBits::UNSIGNED)); 319 if (r.offset % sizeof(CompactUnwindEntry<Ptr>) != 320 offsetof(CompactUnwindEntry<Ptr>, functionAddress)) 321 continue; 322 result.insert(r.referent.get<InputSection *>()); 323 } 324 } 325 return result; 326 } 327 328 void macho::foldIdenticalSections() { 329 TimeTraceScope timeScope("Fold Identical Code Sections"); 330 // The ICF equivalence-class segregation algorithm relies on pre-computed 331 // hashes of InputSection::data for the ConcatOutputSection::inputs and all 332 // sections referenced by their relocs. We could recursively traverse the 333 // relocs to find every referenced InputSection, but that precludes easy 334 // parallelization. Therefore, we hash every InputSection here where we have 335 // them all accessible as simple vectors. 336 337 // ICF can't fold functions with unwind info 338 DenseSet<const InputSection *> functionsWithUnwindInfo = 339 target->wordSize == 8 ? findFunctionsWithUnwindInfo<uint64_t>() 340 : findFunctionsWithUnwindInfo<uint32_t>(); 341 342 // If an InputSection is ineligible for ICF, we give it a unique ID to force 343 // it into an unfoldable singleton equivalence class. Begin the unique-ID 344 // space at inputSections.size(), so that it will never intersect with 345 // equivalence-class IDs which begin at 0. Since hashes & unique IDs never 346 // coexist with equivalence-class IDs, this is not necessary, but might help 347 // someone keep the numbers straight in case we ever need to debug the 348 // ICF::segregate() 349 std::vector<ConcatInputSection *> hashable; 350 uint64_t icfUniqueID = inputSections.size(); 351 for (ConcatInputSection *isec : inputSections) { 352 // FIXME: consider non-code __text sections as hashable? 353 bool isHashable = (isCodeSection(isec) || isCfStringSection(isec)) && 354 !isec->shouldOmitFromOutput() && 355 !functionsWithUnwindInfo.contains(isec) && 356 isec->isHashableForICF(); 357 if (isHashable) 358 hashable.push_back(isec); 359 else 360 isec->icfEqClass[0] = ++icfUniqueID; 361 } 362 parallelForEach(hashable, 363 [](ConcatInputSection *isec) { isec->hashForICF(); }); 364 // Now that every input section is either hashed or marked as unique, run the 365 // segregation algorithm to detect foldable subsections. 366 ICF(hashable).run(); 367 } 368