]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/ICF.cpp
Merge ^/head r339670 through r339812.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / COFF / ICF.cpp
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 "ICF.h"
22 #include "Chunks.h"
23 #include "Symbols.h"
24 #include "lld/Common/ErrorHandler.h"
25 #include "lld/Common/Timer.h"
26 #include "llvm/ADT/Hashing.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Parallel.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/xxhash.h"
31 #include <algorithm>
32 #include <atomic>
33 #include <vector>
34
35 using namespace llvm;
36
37 namespace lld {
38 namespace coff {
39
40 static Timer ICFTimer("ICF", Timer::root());
41
42 class ICF {
43 public:
44   void run(ArrayRef<Chunk *> V);
45
46 private:
47   void segregate(size_t Begin, size_t End, bool Constant);
48
49   bool assocEquals(const SectionChunk *A, const SectionChunk *B);
50
51   bool equalsConstant(const SectionChunk *A, const SectionChunk *B);
52   bool equalsVariable(const SectionChunk *A, const SectionChunk *B);
53
54   uint32_t getHash(SectionChunk *C);
55   bool isEligible(SectionChunk *C);
56
57   size_t findBoundary(size_t Begin, size_t End);
58
59   void forEachClassRange(size_t Begin, size_t End,
60                          std::function<void(size_t, size_t)> Fn);
61
62   void forEachClass(std::function<void(size_t, size_t)> Fn);
63
64   std::vector<SectionChunk *> Chunks;
65   int Cnt = 0;
66   std::atomic<bool> Repeat = {false};
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. However, we also
77 // merge read-only sections in a couple of cases where the address of the
78 // section is insignificant to the user program and the behaviour matches that
79 // of the Visual C++ linker.
80 bool ICF::isEligible(SectionChunk *C) {
81   // Non-comdat chunks, dead chunks, and writable chunks are not elegible.
82   bool Writable = C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
83   if (!C->isCOMDAT() || !C->isLive() || Writable)
84     return false;
85
86   // Code sections are eligible.
87   if (C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
88     return true;
89
90   // .pdata and .xdata unwind info sections are eligible.
91   StringRef OutSecName = C->getSectionName().split('$').first;
92   if (OutSecName == ".pdata" || OutSecName == ".xdata")
93     return true;
94
95   // So are vtables.
96   return C->Sym && C->Sym->getName().startswith("??_7");
97 }
98
99 // Split an equivalence class into smaller classes.
100 void ICF::segregate(size_t Begin, size_t End, bool Constant) {
101   while (Begin < End) {
102     // Divide [Begin, End) into two. Let Mid be the start index of the
103     // second group.
104     auto Bound = std::stable_partition(
105         Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) {
106           if (Constant)
107             return equalsConstant(Chunks[Begin], S);
108           return equalsVariable(Chunks[Begin], S);
109         });
110     size_t Mid = Bound - Chunks.begin();
111
112     // Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an
113     // equivalence class ID because every group ends with a unique index.
114     for (size_t I = Begin; I < Mid; ++I)
115       Chunks[I]->Class[(Cnt + 1) % 2] = Mid;
116
117     // If we created a group, we need to iterate the main loop again.
118     if (Mid != End)
119       Repeat = true;
120
121     Begin = Mid;
122   }
123 }
124
125 // Returns true if two sections' associative children are equal.
126 bool ICF::assocEquals(const SectionChunk *A, const SectionChunk *B) {
127   auto ChildClasses = [&](const SectionChunk *SC) {
128     std::vector<uint32_t> Classes;
129     for (const SectionChunk *C : SC->children())
130       if (!C->SectionName.startswith(".debug") &&
131           C->SectionName != ".gfids$y" && C->SectionName != ".gljmp$y")
132         Classes.push_back(C->Class[Cnt % 2]);
133     return Classes;
134   };
135   return ChildClasses(A) == ChildClasses(B);
136 }
137
138 // Compare "non-moving" part of two sections, namely everything
139 // except relocation targets.
140 bool ICF::equalsConstant(const SectionChunk *A, const SectionChunk *B) {
141   if (A->Relocs.size() != B->Relocs.size())
142     return false;
143
144   // Compare relocations.
145   auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
146     if (R1.Type != R2.Type ||
147         R1.VirtualAddress != R2.VirtualAddress) {
148       return false;
149     }
150     Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
151     Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
152     if (B1 == B2)
153       return true;
154     if (auto *D1 = dyn_cast<DefinedRegular>(B1))
155       if (auto *D2 = dyn_cast<DefinedRegular>(B2))
156         return D1->getValue() == D2->getValue() &&
157                D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
158     return false;
159   };
160   if (!std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq))
161     return false;
162
163   // Compare section attributes and contents.
164   return A->getOutputCharacteristics() == B->getOutputCharacteristics() &&
165          A->SectionName == B->SectionName &&
166          A->Header->SizeOfRawData == B->Header->SizeOfRawData &&
167          A->Checksum == B->Checksum && A->getContents() == B->getContents() &&
168          assocEquals(A, B);
169 }
170
171 // Compare "moving" part of two sections, namely relocation targets.
172 bool ICF::equalsVariable(const SectionChunk *A, const SectionChunk *B) {
173   // Compare relocations.
174   auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
175     Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
176     Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
177     if (B1 == B2)
178       return true;
179     if (auto *D1 = dyn_cast<DefinedRegular>(B1))
180       if (auto *D2 = dyn_cast<DefinedRegular>(B2))
181         return D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
182     return false;
183   };
184   return std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(),
185                     Eq) &&
186          assocEquals(A, B);
187 }
188
189 // Find the first Chunk after Begin that has a different class from Begin.
190 size_t ICF::findBoundary(size_t Begin, size_t End) {
191   for (size_t I = Begin + 1; I < End; ++I)
192     if (Chunks[Begin]->Class[Cnt % 2] != Chunks[I]->Class[Cnt % 2])
193       return I;
194   return End;
195 }
196
197 void ICF::forEachClassRange(size_t Begin, size_t End,
198                             std::function<void(size_t, size_t)> Fn) {
199   while (Begin < End) {
200     size_t Mid = findBoundary(Begin, End);
201     Fn(Begin, Mid);
202     Begin = Mid;
203   }
204 }
205
206 // Call Fn on each class group.
207 void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) {
208   // If the number of sections are too small to use threading,
209   // call Fn sequentially.
210   if (Chunks.size() < 1024) {
211     forEachClassRange(0, Chunks.size(), Fn);
212     ++Cnt;
213     return;
214   }
215
216   // Shard into non-overlapping intervals, and call Fn in parallel.
217   // The sharding must be completed before any calls to Fn are made
218   // so that Fn can modify the Chunks in its shard without causing data
219   // races.
220   const size_t NumShards = 256;
221   size_t Step = Chunks.size() / NumShards;
222   size_t Boundaries[NumShards + 1];
223   Boundaries[0] = 0;
224   Boundaries[NumShards] = Chunks.size();
225   for_each_n(parallel::par, size_t(1), NumShards, [&](size_t I) {
226     Boundaries[I] = findBoundary((I - 1) * Step, Chunks.size());
227   });
228   for_each_n(parallel::par, size_t(1), NumShards + 1, [&](size_t I) {
229     if (Boundaries[I - 1] < Boundaries[I]) {
230       forEachClassRange(Boundaries[I - 1], Boundaries[I], Fn);
231     }
232   });
233   ++Cnt;
234 }
235
236 // Merge identical COMDAT sections.
237 // Two sections are considered the same if their section headers,
238 // contents and relocations are all the same.
239 void ICF::run(ArrayRef<Chunk *> Vec) {
240   ScopedTimer T(ICFTimer);
241
242   // Collect only mergeable sections and group by hash value.
243   uint32_t NextId = 1;
244   for (Chunk *C : Vec) {
245     if (auto *SC = dyn_cast<SectionChunk>(C)) {
246       if (isEligible(SC))
247         Chunks.push_back(SC);
248       else
249         SC->Class[0] = NextId++;
250     }
251   }
252
253   // Make sure that ICF doesn't merge sections that are being handled by string
254   // tail merging.
255   for (auto &P : MergeChunk::Instances)
256     for (SectionChunk *SC : P.second->Sections)
257       SC->Class[0] = NextId++;
258
259   // Initially, we use hash values to partition sections.
260   for_each(parallel::par, Chunks.begin(), Chunks.end(), [&](SectionChunk *SC) {
261     // Set MSB to 1 to avoid collisions with non-hash classs.
262     SC->Class[0] = xxHash64(SC->getContents()) | (1 << 31);
263   });
264
265   // From now on, sections in Chunks are ordered so that sections in
266   // the same group are consecutive in the vector.
267   std::stable_sort(Chunks.begin(), Chunks.end(),
268                    [](SectionChunk *A, SectionChunk *B) {
269                      return A->Class[0] < B->Class[0];
270                    });
271
272   // Compare static contents and assign unique IDs for each static content.
273   forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); });
274
275   // Split groups by comparing relocations until convergence is obtained.
276   do {
277     Repeat = false;
278     forEachClass(
279         [&](size_t Begin, size_t End) { segregate(Begin, End, false); });
280   } while (Repeat);
281
282   log("ICF needed " + Twine(Cnt) + " iterations");
283
284   // Merge sections in the same classs.
285   forEachClass([&](size_t Begin, size_t End) {
286     if (End - Begin == 1)
287       return;
288
289     log("Selected " + Chunks[Begin]->getDebugName());
290     for (size_t I = Begin + 1; I < End; ++I) {
291       log("  Removed " + Chunks[I]->getDebugName());
292       Chunks[Begin]->replace(Chunks[I]);
293     }
294   });
295 }
296
297 // Entry point to ICF.
298 void doICF(ArrayRef<Chunk *> Chunks) { ICF().run(Chunks); }
299
300 } // namespace coff
301 } // namespace lld