xref: /llvm-project-15.0.7/lld/COFF/ICF.cpp (revision f4bf4227)
1 //===- ICF.cpp ------------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // ICF is short for Identical Code Folding. That is a size optimization to
11 // identify and merge two or more read-only sections (typically functions)
12 // that happened to have the same contents. It usually reduces output size
13 // by a few percent.
14 //
15 // On Windows, ICF is enabled by default.
16 //
17 // See ELF/ICF.cpp for the details about the algortihm.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "Chunks.h"
22 #include "Symbols.h"
23 #include "lld/Common/ErrorHandler.h"
24 #include "llvm/ADT/Hashing.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Parallel.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 #include <atomic>
30 #include <vector>
31 
32 using namespace llvm;
33 
34 namespace lld {
35 namespace coff {
36 
37 class ICF {
38 public:
39   void run(const std::vector<Chunk *> &V);
40 
41 private:
42   void segregate(size_t Begin, size_t End, bool Constant);
43 
44   bool equalsConstant(const SectionChunk *A, const SectionChunk *B);
45   bool equalsVariable(const SectionChunk *A, const SectionChunk *B);
46 
47   uint32_t getHash(SectionChunk *C);
48   bool isEligible(SectionChunk *C);
49 
50   size_t findBoundary(size_t Begin, size_t End);
51 
52   void forEachClassRange(size_t Begin, size_t End,
53                          std::function<void(size_t, size_t)> Fn);
54 
55   void forEachClass(std::function<void(size_t, size_t)> Fn);
56 
57   std::vector<SectionChunk *> Chunks;
58   int Cnt = 0;
59   std::atomic<bool> Repeat = {false};
60 };
61 
62 // Returns a hash value for S.
63 uint32_t ICF::getHash(SectionChunk *C) {
64   return hash_combine(C->getPermissions(), C->SectionName, C->NumRelocs,
65                       C->Alignment, uint32_t(C->Header->SizeOfRawData),
66                       C->Checksum, C->getContents());
67 }
68 
69 // Returns true if section S is subject of ICF.
70 //
71 // Microsoft's documentation
72 // (https://msdn.microsoft.com/en-us/library/bxwfs976.aspx; visited April
73 // 2017) says that /opt:icf folds both functions and read-only data.
74 // Despite that, the MSVC linker folds only functions. We found
75 // a few instances of programs that are not safe for data merging.
76 // Therefore, we merge only functions just like the MSVC tool.
77 bool ICF::isEligible(SectionChunk *C) {
78   bool Global = C->Sym && C->Sym->isExternal();
79   bool Executable = C->getPermissions() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE;
80   bool Writable = C->getPermissions() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
81   return C->isCOMDAT() && C->isLive() && Global && Executable && !Writable;
82 }
83 
84 // Split an equivalence class into smaller classes.
85 void ICF::segregate(size_t Begin, size_t End, bool Constant) {
86   while (Begin < End) {
87     // Divide [Begin, End) into two. Let Mid be the start index of the
88     // second group.
89     auto Bound = std::stable_partition(
90         Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) {
91           if (Constant)
92             return equalsConstant(Chunks[Begin], S);
93           return equalsVariable(Chunks[Begin], S);
94         });
95     size_t Mid = Bound - Chunks.begin();
96 
97     // Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an
98     // equivalence class ID because every group ends with a unique index.
99     for (size_t I = Begin; I < Mid; ++I)
100       Chunks[I]->Class[(Cnt + 1) % 2] = Mid;
101 
102     // If we created a group, we need to iterate the main loop again.
103     if (Mid != End)
104       Repeat = true;
105 
106     Begin = Mid;
107   }
108 }
109 
110 // Compare "non-moving" part of two sections, namely everything
111 // except relocation targets.
112 bool ICF::equalsConstant(const SectionChunk *A, const SectionChunk *B) {
113   if (A->NumRelocs != B->NumRelocs)
114     return false;
115 
116   // Compare relocations.
117   auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
118     if (R1.Type != R2.Type ||
119         R1.VirtualAddress != R2.VirtualAddress) {
120       return false;
121     }
122     Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
123     Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
124     if (B1 == B2)
125       return true;
126     if (auto *D1 = dyn_cast<DefinedRegular>(B1))
127       if (auto *D2 = dyn_cast<DefinedRegular>(B2))
128         return D1->getValue() == D2->getValue() &&
129                D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
130     return false;
131   };
132   if (!std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq))
133     return false;
134 
135   // Compare section attributes and contents.
136   return A->getPermissions() == B->getPermissions() &&
137          A->SectionName == B->SectionName && A->Alignment == B->Alignment &&
138          A->Header->SizeOfRawData == B->Header->SizeOfRawData &&
139          A->Checksum == B->Checksum && A->getContents() == B->getContents();
140 }
141 
142 // Compare "moving" part of two sections, namely relocation targets.
143 bool ICF::equalsVariable(const SectionChunk *A, const SectionChunk *B) {
144   // Compare relocations.
145   auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
146     Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
147     Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
148     if (B1 == B2)
149       return true;
150     if (auto *D1 = dyn_cast<DefinedRegular>(B1))
151       if (auto *D2 = dyn_cast<DefinedRegular>(B2))
152         return D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
153     return false;
154   };
155   return std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq);
156 }
157 
158 size_t ICF::findBoundary(size_t Begin, size_t End) {
159   for (size_t I = Begin + 1; I < End; ++I)
160     if (Chunks[Begin]->Class[Cnt % 2] != Chunks[I]->Class[Cnt % 2])
161       return I;
162   return End;
163 }
164 
165 void ICF::forEachClassRange(size_t Begin, size_t End,
166                             std::function<void(size_t, size_t)> Fn) {
167   if (Begin > 0)
168     Begin = findBoundary(Begin - 1, End);
169 
170   while (Begin < End) {
171     size_t Mid = findBoundary(Begin, Chunks.size());
172     Fn(Begin, Mid);
173     Begin = Mid;
174   }
175 }
176 
177 // Call Fn on each class group.
178 void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) {
179   // If the number of sections are too small to use threading,
180   // call Fn sequentially.
181   if (Chunks.size() < 1024) {
182     forEachClassRange(0, Chunks.size(), Fn);
183     ++Cnt;
184     return;
185   }
186 
187   // Split sections into 256 shards and call Fn in parallel.
188   size_t NumShards = 256;
189   size_t Step = Chunks.size() / NumShards;
190   for_each_n(parallel::par, size_t(0), NumShards, [&](size_t I) {
191     size_t End = (I == NumShards - 1) ? Chunks.size() : (I + 1) * Step;
192     forEachClassRange(I * Step, End, Fn);
193   });
194   ++Cnt;
195 }
196 
197 // Merge identical COMDAT sections.
198 // Two sections are considered the same if their section headers,
199 // contents and relocations are all the same.
200 void ICF::run(const std::vector<Chunk *> &Vec) {
201   // Collect only mergeable sections and group by hash value.
202   uint32_t NextId = 1;
203   for (Chunk *C : Vec) {
204     if (auto *SC = dyn_cast<SectionChunk>(C)) {
205       if (isEligible(SC))
206         Chunks.push_back(SC);
207       else
208         SC->Class[0] = NextId++;
209     }
210   }
211 
212   // Initially, we use hash values to partition sections.
213   for_each(parallel::par, Chunks.begin(), Chunks.end(), [&](SectionChunk *SC) {
214     // Set MSB to 1 to avoid collisions with non-hash classs.
215     SC->Class[0] = getHash(SC) | (1 << 31);
216   });
217 
218   // From now on, sections in Chunks are ordered so that sections in
219   // the same group are consecutive in the vector.
220   std::stable_sort(Chunks.begin(), Chunks.end(),
221                    [](SectionChunk *A, SectionChunk *B) {
222                      return A->Class[0] < B->Class[0];
223                    });
224 
225   // Compare static contents and assign unique IDs for each static content.
226   forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); });
227 
228   // Split groups by comparing relocations until convergence is obtained.
229   do {
230     Repeat = false;
231     forEachClass(
232         [&](size_t Begin, size_t End) { segregate(Begin, End, false); });
233   } while (Repeat);
234 
235   log("ICF needed " + Twine(Cnt) + " iterations");
236 
237   // Merge sections in the same classs.
238   forEachClass([&](size_t Begin, size_t End) {
239     if (End - Begin == 1)
240       return;
241 
242     log("Selected " + Chunks[Begin]->getDebugName());
243     for (size_t I = Begin + 1; I < End; ++I) {
244       log("  Removed " + Chunks[I]->getDebugName());
245       Chunks[Begin]->replace(Chunks[I]);
246     }
247   });
248 }
249 
250 // Entry point to ICF.
251 void doICF(const std::vector<Chunk *> &Chunks) { ICF().run(Chunks); }
252 
253 } // namespace coff
254 } // namespace lld
255