Path: blob/main/contrib/llvm-project/lld/ELF/CallGraphSort.cpp
34869 views
//===- CallGraphSort.cpp --------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// The file is responsible for sorting sections using LLVM call graph profile9/// data by placing frequently executed code sections together. The goal of the10/// placement is to improve the runtime performance of the final executable by11/// arranging code sections so that i-TLB misses and i-cache misses are reduced.12///13/// The algorithm first builds a call graph based on the profile data and then14/// iteratively merges "chains" (ordered lists) of input sections which will be15/// laid out as a unit. There are two implementations for deciding how to16/// merge a pair of chains:17/// - a simpler one, referred to as Call-Chain Clustering (C^3), that follows18/// "Optimizing Function Placement for Large-Scale Data-Center Applications"19/// https://research.fb.com/wp-content/uploads/2017/01/cgo2017-hfsort-final1.pdf20/// - a more advanced one, referred to as Cache-Directed-Sort (CDSort), which21/// typically produces layouts with higher locality, and hence, yields fewer22/// instruction cache misses on large binaries.23//===----------------------------------------------------------------------===//2425#include "CallGraphSort.h"26#include "InputFiles.h"27#include "InputSection.h"28#include "Symbols.h"29#include "llvm/Support/FileSystem.h"30#include "llvm/Transforms/Utils/CodeLayout.h"3132#include <numeric>3334using namespace llvm;35using namespace lld;36using namespace lld::elf;3738namespace {39struct Edge {40int from;41uint64_t weight;42};4344struct Cluster {45Cluster(int sec, size_t s) : next(sec), prev(sec), size(s) {}4647double getDensity() const {48if (size == 0)49return 0;50return double(weight) / double(size);51}5253int next;54int prev;55uint64_t size;56uint64_t weight = 0;57uint64_t initialWeight = 0;58Edge bestPred = {-1, 0};59};6061/// Implementation of the Call-Chain Clustering (C^3). The goal of this62/// algorithm is to improve runtime performance of the executable by arranging63/// code sections such that page table and i-cache misses are minimized.64///65/// Definitions:66/// * Cluster67/// * An ordered list of input sections which are laid out as a unit. At the68/// beginning of the algorithm each input section has its own cluster and69/// the weight of the cluster is the sum of the weight of all incoming70/// edges.71/// * Call-Chain Clustering (C³) Heuristic72/// * Defines when and how clusters are combined. Pick the highest weighted73/// input section then add it to its most likely predecessor if it wouldn't74/// penalize it too much.75/// * Density76/// * The weight of the cluster divided by the size of the cluster. This is a77/// proxy for the amount of execution time spent per byte of the cluster.78///79/// It does so given a call graph profile by the following:80/// * Build a weighted call graph from the call graph profile81/// * Sort input sections by weight82/// * For each input section starting with the highest weight83/// * Find its most likely predecessor cluster84/// * Check if the combined cluster would be too large, or would have too low85/// a density.86/// * If not, then combine the clusters.87/// * Sort non-empty clusters by density88class CallGraphSort {89public:90CallGraphSort();9192DenseMap<const InputSectionBase *, int> run();9394private:95std::vector<Cluster> clusters;96std::vector<const InputSectionBase *> sections;97};9899// Maximum amount the combined cluster density can be worse than the original100// cluster to consider merging.101constexpr int MAX_DENSITY_DEGRADATION = 8;102103// Maximum cluster size in bytes.104constexpr uint64_t MAX_CLUSTER_SIZE = 1024 * 1024;105} // end anonymous namespace106107using SectionPair =108std::pair<const InputSectionBase *, const InputSectionBase *>;109110// Take the edge list in Config->CallGraphProfile, resolve symbol names to111// Symbols, and generate a graph between InputSections with the provided112// weights.113CallGraphSort::CallGraphSort() {114MapVector<SectionPair, uint64_t> &profile = config->callGraphProfile;115DenseMap<const InputSectionBase *, int> secToCluster;116117auto getOrCreateNode = [&](const InputSectionBase *isec) -> int {118auto res = secToCluster.try_emplace(isec, clusters.size());119if (res.second) {120sections.push_back(isec);121clusters.emplace_back(clusters.size(), isec->getSize());122}123return res.first->second;124};125126// Create the graph.127for (std::pair<SectionPair, uint64_t> &c : profile) {128const auto *fromSB = cast<InputSectionBase>(c.first.first);129const auto *toSB = cast<InputSectionBase>(c.first.second);130uint64_t weight = c.second;131132// Ignore edges between input sections belonging to different output133// sections. This is done because otherwise we would end up with clusters134// containing input sections that can't actually be placed adjacently in the135// output. This messes with the cluster size and density calculations. We136// would also end up moving input sections in other output sections without137// moving them closer to what calls them.138if (fromSB->getOutputSection() != toSB->getOutputSection())139continue;140141int from = getOrCreateNode(fromSB);142int to = getOrCreateNode(toSB);143144clusters[to].weight += weight;145146if (from == to)147continue;148149// Remember the best edge.150Cluster &toC = clusters[to];151if (toC.bestPred.from == -1 || toC.bestPred.weight < weight) {152toC.bestPred.from = from;153toC.bestPred.weight = weight;154}155}156for (Cluster &c : clusters)157c.initialWeight = c.weight;158}159160// It's bad to merge clusters which would degrade the density too much.161static bool isNewDensityBad(Cluster &a, Cluster &b) {162double newDensity = double(a.weight + b.weight) / double(a.size + b.size);163return newDensity < a.getDensity() / MAX_DENSITY_DEGRADATION;164}165166// Find the leader of V's belonged cluster (represented as an equivalence167// class). We apply union-find path-halving technique (simple to implement) in168// the meantime as it decreases depths and the time complexity.169static int getLeader(int *leaders, int v) {170while (leaders[v] != v) {171leaders[v] = leaders[leaders[v]];172v = leaders[v];173}174return v;175}176177static void mergeClusters(std::vector<Cluster> &cs, Cluster &into, int intoIdx,178Cluster &from, int fromIdx) {179int tail1 = into.prev, tail2 = from.prev;180into.prev = tail2;181cs[tail2].next = intoIdx;182from.prev = tail1;183cs[tail1].next = fromIdx;184into.size += from.size;185into.weight += from.weight;186from.size = 0;187from.weight = 0;188}189190// Group InputSections into clusters using the Call-Chain Clustering heuristic191// then sort the clusters by density.192DenseMap<const InputSectionBase *, int> CallGraphSort::run() {193std::vector<int> sorted(clusters.size());194std::unique_ptr<int[]> leaders(new int[clusters.size()]);195196std::iota(leaders.get(), leaders.get() + clusters.size(), 0);197std::iota(sorted.begin(), sorted.end(), 0);198llvm::stable_sort(sorted, [&](int a, int b) {199return clusters[a].getDensity() > clusters[b].getDensity();200});201202for (int l : sorted) {203// The cluster index is the same as the index of its leader here because204// clusters[L] has not been merged into another cluster yet.205Cluster &c = clusters[l];206207// Don't consider merging if the edge is unlikely.208if (c.bestPred.from == -1 || c.bestPred.weight * 10 <= c.initialWeight)209continue;210211int predL = getLeader(leaders.get(), c.bestPred.from);212if (l == predL)213continue;214215Cluster *predC = &clusters[predL];216if (c.size + predC->size > MAX_CLUSTER_SIZE)217continue;218219if (isNewDensityBad(*predC, c))220continue;221222leaders[l] = predL;223mergeClusters(clusters, *predC, predL, c, l);224}225226// Sort remaining non-empty clusters by density.227sorted.clear();228for (int i = 0, e = (int)clusters.size(); i != e; ++i)229if (clusters[i].size > 0)230sorted.push_back(i);231llvm::stable_sort(sorted, [&](int a, int b) {232return clusters[a].getDensity() > clusters[b].getDensity();233});234235DenseMap<const InputSectionBase *, int> orderMap;236int curOrder = 1;237for (int leader : sorted) {238for (int i = leader;;) {239orderMap[sections[i]] = curOrder++;240i = clusters[i].next;241if (i == leader)242break;243}244}245if (!config->printSymbolOrder.empty()) {246std::error_code ec;247raw_fd_ostream os(config->printSymbolOrder, ec, sys::fs::OF_None);248if (ec) {249error("cannot open " + config->printSymbolOrder + ": " + ec.message());250return orderMap;251}252253// Print the symbols ordered by C3, in the order of increasing curOrder254// Instead of sorting all the orderMap, just repeat the loops above.255for (int leader : sorted)256for (int i = leader;;) {257// Search all the symbols in the file of the section258// and find out a Defined symbol with name that is within the section.259for (Symbol *sym : sections[i]->file->getSymbols())260if (!sym->isSection()) // Filter out section-type symbols here.261if (auto *d = dyn_cast<Defined>(sym))262if (sections[i] == d->section)263os << sym->getName() << "\n";264i = clusters[i].next;265if (i == leader)266break;267}268}269270return orderMap;271}272273// Sort sections by the profile data using the Cache-Directed Sort algorithm.274// The placement is done by optimizing the locality by co-locating frequently275// executed code sections together.276DenseMap<const InputSectionBase *, int> elf::computeCacheDirectedSortOrder() {277SmallVector<uint64_t, 0> funcSizes;278SmallVector<uint64_t, 0> funcCounts;279SmallVector<codelayout::EdgeCount, 0> callCounts;280SmallVector<uint64_t, 0> callOffsets;281SmallVector<const InputSectionBase *, 0> sections;282DenseMap<const InputSectionBase *, size_t> secToTargetId;283284auto getOrCreateNode = [&](const InputSectionBase *inSec) -> size_t {285auto res = secToTargetId.try_emplace(inSec, sections.size());286if (res.second) {287// inSec does not appear before in the graph.288sections.push_back(inSec);289funcSizes.push_back(inSec->getSize());290funcCounts.push_back(0);291}292return res.first->second;293};294295// Create the graph.296for (std::pair<SectionPair, uint64_t> &c : config->callGraphProfile) {297const InputSectionBase *fromSB = cast<InputSectionBase>(c.first.first);298const InputSectionBase *toSB = cast<InputSectionBase>(c.first.second);299// Ignore edges between input sections belonging to different sections.300if (fromSB->getOutputSection() != toSB->getOutputSection())301continue;302303uint64_t weight = c.second;304// Ignore edges with zero weight.305if (weight == 0)306continue;307308size_t from = getOrCreateNode(fromSB);309size_t to = getOrCreateNode(toSB);310// Ignore self-edges (recursive calls).311if (from == to)312continue;313314callCounts.push_back({from, to, weight});315// Assume that the jump is at the middle of the input section. The profile316// data does not contain jump offsets.317callOffsets.push_back((funcSizes[from] + 1) / 2);318funcCounts[to] += weight;319}320321// Run the layout algorithm.322std::vector<uint64_t> sortedSections = codelayout::computeCacheDirectedLayout(323funcSizes, funcCounts, callCounts, callOffsets);324325// Create the final order.326DenseMap<const InputSectionBase *, int> orderMap;327int curOrder = 1;328for (uint64_t secIdx : sortedSections)329orderMap[sections[secIdx]] = curOrder++;330331return orderMap;332}333334// Sort sections by the profile data provided by --callgraph-profile-file.335//336// This first builds a call graph based on the profile data then merges sections337// according either to the C³ or Cache-Directed-Sort ordering algorithm.338DenseMap<const InputSectionBase *, int> elf::computeCallGraphProfileOrder() {339if (config->callGraphProfileSort == CGProfileSortKind::Cdsort)340return computeCacheDirectedSortOrder();341return CallGraphSort().run();342}343344345