1 //===- SectionPriorities.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 /// This is based on the ELF port, see ELF/CallGraphSort.cpp for the details 10 /// about the algorithm. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "SectionPriorities.h" 15 #include "BPSectionOrderer.h" 16 #include "Config.h" 17 #include "InputFiles.h" 18 #include "Symbols.h" 19 #include "Target.h" 20 21 #include "lld/Common/Args.h" 22 #include "lld/Common/CommonLinkerContext.h" 23 #include "lld/Common/ErrorHandler.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/MapVector.h" 26 #include "llvm/Support/Path.h" 27 #include "llvm/Support/TimeProfiler.h" 28 #include "llvm/Support/raw_ostream.h" 29 30 #include <numeric> 31 32 using namespace llvm; 33 using namespace llvm::MachO; 34 using namespace llvm::sys; 35 using namespace lld; 36 using namespace lld::macho; 37 38 PriorityBuilder macho::priorityBuilder; 39 40 namespace { 41 struct Edge { 42 int from; 43 uint64_t weight; 44 }; 45 46 struct Cluster { 47 Cluster(int sec, size_t s) : next(sec), prev(sec), size(s) {} 48 49 double getDensity() const { 50 if (size == 0) 51 return 0; 52 return double(weight) / double(size); 53 } 54 55 int next; 56 int prev; 57 uint64_t size; 58 uint64_t weight = 0; 59 uint64_t initialWeight = 0; 60 Edge bestPred = {-1, 0}; 61 }; 62 63 class CallGraphSort { 64 public: 65 CallGraphSort(const MapVector<SectionPair, uint64_t> &profile); 66 67 DenseMap<const InputSection *, int> run(); 68 69 private: 70 std::vector<Cluster> clusters; 71 std::vector<const InputSection *> sections; 72 }; 73 // Maximum amount the combined cluster density can be worse than the original 74 // cluster to consider merging. 75 constexpr int MAX_DENSITY_DEGRADATION = 8; 76 } // end anonymous namespace 77 78 // Take the edge list in callGraphProfile, resolve symbol names to Symbols, and 79 // generate a graph between InputSections with the provided weights. 80 CallGraphSort::CallGraphSort(const MapVector<SectionPair, uint64_t> &profile) { 81 DenseMap<const InputSection *, int> secToCluster; 82 83 auto getOrCreateCluster = [&](const InputSection *isec) -> int { 84 auto res = secToCluster.try_emplace(isec, clusters.size()); 85 if (res.second) { 86 sections.push_back(isec); 87 clusters.emplace_back(clusters.size(), isec->getSize()); 88 } 89 return res.first->second; 90 }; 91 92 // Create the graph 93 for (const std::pair<SectionPair, uint64_t> &c : profile) { 94 const auto fromSec = c.first.first->canonical(); 95 const auto toSec = c.first.second->canonical(); 96 uint64_t weight = c.second; 97 // Ignore edges between input sections belonging to different output 98 // sections. This is done because otherwise we would end up with clusters 99 // containing input sections that can't actually be placed adjacently in the 100 // output. This messes with the cluster size and density calculations. We 101 // would also end up moving input sections in other output sections without 102 // moving them closer to what calls them. 103 if (fromSec->parent != toSec->parent) 104 continue; 105 106 int from = getOrCreateCluster(fromSec); 107 int to = getOrCreateCluster(toSec); 108 109 clusters[to].weight += weight; 110 111 if (from == to) 112 continue; 113 114 // Remember the best edge. 115 Cluster &toC = clusters[to]; 116 if (toC.bestPred.from == -1 || toC.bestPred.weight < weight) { 117 toC.bestPred.from = from; 118 toC.bestPred.weight = weight; 119 } 120 } 121 for (Cluster &c : clusters) 122 c.initialWeight = c.weight; 123 } 124 125 // It's bad to merge clusters which would degrade the density too much. 126 static bool isNewDensityBad(Cluster &a, Cluster &b) { 127 double newDensity = double(a.weight + b.weight) / double(a.size + b.size); 128 return newDensity < a.getDensity() / MAX_DENSITY_DEGRADATION; 129 } 130 131 // Find the leader of V's belonged cluster (represented as an equivalence 132 // class). We apply union-find path-halving technique (simple to implement) in 133 // the meantime as it decreases depths and the time complexity. 134 static int getLeader(std::vector<int> &leaders, int v) { 135 while (leaders[v] != v) { 136 leaders[v] = leaders[leaders[v]]; 137 v = leaders[v]; 138 } 139 return v; 140 } 141 142 static void mergeClusters(std::vector<Cluster> &cs, Cluster &into, int intoIdx, 143 Cluster &from, int fromIdx) { 144 int tail1 = into.prev, tail2 = from.prev; 145 into.prev = tail2; 146 cs[tail2].next = intoIdx; 147 from.prev = tail1; 148 cs[tail1].next = fromIdx; 149 into.size += from.size; 150 into.weight += from.weight; 151 from.size = 0; 152 from.weight = 0; 153 } 154 155 // Group InputSections into clusters using the Call-Chain Clustering heuristic 156 // then sort the clusters by density. 157 DenseMap<const InputSection *, int> CallGraphSort::run() { 158 const uint64_t maxClusterSize = target->getPageSize(); 159 160 // Cluster indices sorted by density. 161 std::vector<int> sorted(clusters.size()); 162 // For union-find. 163 std::vector<int> leaders(clusters.size()); 164 165 std::iota(leaders.begin(), leaders.end(), 0); 166 std::iota(sorted.begin(), sorted.end(), 0); 167 168 llvm::stable_sort(sorted, [&](int a, int b) { 169 return clusters[a].getDensity() > clusters[b].getDensity(); 170 }); 171 172 for (int l : sorted) { 173 // The cluster index is the same as the index of its leader here because 174 // clusters[L] has not been merged into another cluster yet. 175 Cluster &c = clusters[l]; 176 177 // Don't consider merging if the edge is unlikely. 178 if (c.bestPred.from == -1 || c.bestPred.weight * 10 <= c.initialWeight) 179 continue; 180 181 int predL = getLeader(leaders, c.bestPred.from); 182 // Already in the same cluster. 183 if (l == predL) 184 continue; 185 186 Cluster *predC = &clusters[predL]; 187 if (c.size + predC->size > maxClusterSize) 188 continue; 189 190 if (isNewDensityBad(*predC, c)) 191 continue; 192 193 leaders[l] = predL; 194 mergeClusters(clusters, *predC, predL, c, l); 195 } 196 // Sort remaining non-empty clusters by density. 197 sorted.clear(); 198 for (int i = 0, e = (int)clusters.size(); i != e; ++i) 199 if (clusters[i].size > 0) 200 sorted.push_back(i); 201 llvm::stable_sort(sorted, [&](int a, int b) { 202 return clusters[a].getDensity() > clusters[b].getDensity(); 203 }); 204 205 DenseMap<const InputSection *, int> orderMap; 206 207 // Sections will be sorted by decreasing order. Absent sections will have 208 // priority 0 and be placed at the end of sections. 209 int curOrder = -clusters.size(); 210 for (int leader : sorted) { 211 for (int i = leader;;) { 212 orderMap[sections[i]] = curOrder++; 213 i = clusters[i].next; 214 if (i == leader) 215 break; 216 } 217 } 218 if (!config->printSymbolOrder.empty()) { 219 std::error_code ec; 220 raw_fd_ostream os(config->printSymbolOrder, ec, sys::fs::OF_None); 221 if (ec) { 222 error("cannot open " + config->printSymbolOrder + ": " + ec.message()); 223 return orderMap; 224 } 225 // Print the symbols ordered by C3, in the order of decreasing curOrder 226 // Instead of sorting all the orderMap, just repeat the loops above. 227 for (int leader : sorted) 228 for (int i = leader;;) { 229 const InputSection *isec = sections[i]; 230 // Search all the symbols in the file of the section 231 // and find out a Defined symbol with name that is within the 232 // section. 233 for (Symbol *sym : isec->getFile()->symbols) { 234 if (auto *d = dyn_cast_or_null<Defined>(sym)) { 235 if (d->isec() == isec) 236 os << sym->getName() << "\n"; 237 } 238 } 239 i = clusters[i].next; 240 if (i == leader) 241 break; 242 } 243 } 244 245 return orderMap; 246 } 247 248 std::optional<int> 249 macho::PriorityBuilder::getSymbolPriority(const Defined *sym) { 250 if (sym->isAbsolute()) 251 return std::nullopt; 252 253 auto it = priorities.find(sym->getName()); 254 if (it == priorities.end()) 255 return std::nullopt; 256 const SymbolPriorityEntry &entry = it->second; 257 const InputFile *f = sym->isec()->getFile(); 258 if (!f) 259 return entry.anyObjectFile; 260 // We don't use toString(InputFile *) here because it returns the full path 261 // for object files, and we only want the basename. 262 StringRef filename; 263 if (f->archiveName.empty()) 264 filename = path::filename(f->getName()); 265 else 266 filename = saver().save(path::filename(f->archiveName) + "(" + 267 path::filename(f->getName()) + ")"); 268 return std::min(entry.objectFiles.lookup(filename), entry.anyObjectFile); 269 } 270 271 void macho::PriorityBuilder::extractCallGraphProfile() { 272 TimeTraceScope timeScope("Extract call graph profile"); 273 bool hasOrderFile = !priorities.empty(); 274 for (const InputFile *file : inputFiles) { 275 auto *obj = dyn_cast_or_null<ObjFile>(file); 276 if (!obj) 277 continue; 278 for (const CallGraphEntry &entry : obj->callGraph) { 279 assert(entry.fromIndex < obj->symbols.size() && 280 entry.toIndex < obj->symbols.size()); 281 auto *fromSym = dyn_cast_or_null<Defined>(obj->symbols[entry.fromIndex]); 282 auto *toSym = dyn_cast_or_null<Defined>(obj->symbols[entry.toIndex]); 283 if (fromSym && toSym && 284 (!hasOrderFile || 285 (!getSymbolPriority(fromSym) && !getSymbolPriority(toSym)))) 286 callGraphProfile[{fromSym->isec(), toSym->isec()}] += entry.count; 287 } 288 } 289 } 290 291 void macho::PriorityBuilder::parseOrderFile(StringRef path) { 292 assert(callGraphProfile.empty() && 293 "Order file must be parsed before call graph profile is processed"); 294 std::optional<MemoryBufferRef> buffer = readFile(path); 295 if (!buffer) { 296 error("Could not read order file at " + path); 297 return; 298 } 299 300 int prio = std::numeric_limits<int>::min(); 301 MemoryBufferRef mbref = *buffer; 302 for (StringRef line : args::getLines(mbref)) { 303 StringRef objectFile, symbol; 304 line = line.take_until([](char c) { return c == '#'; }); // ignore comments 305 line = line.ltrim(); 306 307 CPUType cpuType = StringSwitch<CPUType>(line) 308 .StartsWith("i386:", CPU_TYPE_I386) 309 .StartsWith("x86_64:", CPU_TYPE_X86_64) 310 .StartsWith("arm:", CPU_TYPE_ARM) 311 .StartsWith("arm64:", CPU_TYPE_ARM64) 312 .StartsWith("ppc:", CPU_TYPE_POWERPC) 313 .StartsWith("ppc64:", CPU_TYPE_POWERPC64) 314 .Default(CPU_TYPE_ANY); 315 316 if (cpuType != CPU_TYPE_ANY && cpuType != target->cpuType) 317 continue; 318 319 // Drop the CPU type as well as the colon 320 if (cpuType != CPU_TYPE_ANY) 321 line = line.drop_until([](char c) { return c == ':'; }).drop_front(); 322 323 constexpr std::array<StringRef, 2> fileEnds = {".o:", ".o):"}; 324 for (StringRef fileEnd : fileEnds) { 325 size_t pos = line.find(fileEnd); 326 if (pos != StringRef::npos) { 327 // Split the string around the colon 328 objectFile = line.take_front(pos + fileEnd.size() - 1); 329 line = line.drop_front(pos + fileEnd.size()); 330 break; 331 } 332 } 333 symbol = line.trim(); 334 335 if (!symbol.empty()) { 336 SymbolPriorityEntry &entry = priorities[symbol]; 337 if (!objectFile.empty()) 338 entry.objectFiles.insert(std::make_pair(objectFile, prio)); 339 else 340 entry.anyObjectFile = std::min(entry.anyObjectFile, prio); 341 } 342 343 ++prio; 344 } 345 } 346 347 DenseMap<const InputSection *, int> 348 macho::PriorityBuilder::buildInputSectionPriorities() { 349 DenseMap<const InputSection *, int> sectionPriorities; 350 if (config->bpStartupFunctionSort || config->bpFunctionOrderForCompression || 351 config->bpDataOrderForCompression) { 352 TimeTraceScope timeScope("Balanced Partitioning Section Orderer"); 353 sectionPriorities = runBalancedPartitioning( 354 config->bpStartupFunctionSort ? config->irpgoProfilePath : "", 355 config->bpFunctionOrderForCompression, 356 config->bpDataOrderForCompression, 357 config->bpCompressionSortStartupFunctions, 358 config->bpVerboseSectionOrderer); 359 } else if (config->callGraphProfileSort) { 360 // Sort sections by the profile data provided by __LLVM,__cg_profile 361 // sections. 362 // 363 // This first builds a call graph based on the profile data then merges 364 // sections according to the C³ heuristic. All clusters are then sorted by a 365 // density metric to further improve locality. 366 TimeTraceScope timeScope("Call graph profile sort"); 367 sectionPriorities = CallGraphSort(callGraphProfile).run(); 368 } 369 370 if (priorities.empty()) 371 return sectionPriorities; 372 373 auto addSym = [&](const Defined *sym) { 374 std::optional<int> symbolPriority = getSymbolPriority(sym); 375 if (!symbolPriority) 376 return; 377 int &priority = sectionPriorities[sym->isec()]; 378 priority = std::min(priority, *symbolPriority); 379 }; 380 381 // TODO: Make sure this handles weak symbols correctly. 382 for (const InputFile *file : inputFiles) { 383 if (isa<ObjFile>(file)) 384 for (Symbol *sym : file->symbols) 385 if (auto *d = dyn_cast_or_null<Defined>(sym)) 386 addSym(d); 387 } 388 389 return sectionPriorities; 390 } 391