File: GenerateFrequencyData.cpp

package info (click to toggle)
intel-graphics-compiler2 2.20.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 107,552 kB
  • sloc: cpp: 807,012; lisp: 287,936; ansic: 16,397; python: 4,010; yacc: 2,588; lex: 1,666; pascal: 313; sh: 186; makefile: 37
file content (201 lines) | stat: -rw-r--r-- 7,669 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/*========================== begin_copyright_notice ============================

Copyright (C) 2022 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#include "GenerateFrequencyData.hpp"
#include "Compiler/IGCPassSupport.h"
#include "common/igc_regkeys.hpp"
#include "Probe/Assertion.h"

#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/InstVisitor.h>

#include "llvmWrapper/ADT/Optional.h"

#include <llvm/Analysis/BlockFrequencyInfo.h>
#include <llvm/Analysis/BranchProbabilityInfo.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/SyntheticCountsUtils.h>
#include <llvm/ADT/Optional.h>

#include <llvm/Support/ScaledNumber.h>
#include <unordered_map>
#include <string>

using namespace llvm;
using Scaled64 = ScaledNumber<uint64_t>;

class GenerateFrequencyData : public ModulePass {
  typedef enum {
    PGSS_IGC_DUMP_BLK = 0x1,
    PGSS_IGC_DUMP_FUNC = 0x2,
  } PGSS_DUMP_t;

public:
  static char ID;

  GenerateFrequencyData() : ModulePass(ID), M(nullptr) {
    IGC::initializeGenerateFrequencyDataPass(*PassRegistry::getPassRegistry());
  }

  bool runOnModule(Module &) override;
  void runStaticAnalysis();
  void updateStaticFuncFreq(DenseMap<Function *, ScaledNumber<uint64_t>> &Counts);

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.setPreservesCFG();
    AU.addRequired<LoopInfoWrapperPass>();
    AU.addRequired<BranchProbabilityInfoWrapperPass>();
    AU.addRequired<BlockFrequencyInfoWrapperPass>();
  }

  Module *getModule() { return M; };
  void setModule(Module *m) { M = m; };

private:
  Module *M;
};

char GenerateFrequencyData::ID = 0;

#define PASS_FLAG "igc-generate-frequency-data"
#define PASS_DESC "Generate frequency data"
#define PASS_CFG_ONLY false
#define PASS_ANALYSIS false

namespace IGC {
IGC_INITIALIZE_PASS_BEGIN(GenerateFrequencyData, PASS_FLAG, PASS_DESC, PASS_CFG_ONLY, PASS_ANALYSIS)
IGC_INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
IGC_INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
IGC_INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
IGC_INITIALIZE_PASS_END(GenerateFrequencyData, PASS_FLAG, PASS_DESC, PASS_CFG_ONLY, PASS_ANALYSIS)
} // namespace IGC

llvm::ModulePass *IGC::createGenerateFrequencyDataPass() { return new GenerateFrequencyData(); }

bool GenerateFrequencyData::runOnModule(Module &M) {
  setModule(&M);
  runStaticAnalysis();
  return false;
}

void GenerateFrequencyData::runStaticAnalysis() {
  // Analyze function frequencies from SyntheticCountsPropagation
  // PrintStaticProfilingForKernelSizeReduction(0x1, "------------------Static analysis start------------------")
  DenseMap<Function *, ScaledNumber<uint64_t>> F_freqs;
  DenseMap<BasicBlock *, ScaledNumber<uint64_t>> B_freqs;
  LLVMContext &C = M->getContext();
  updateStaticFuncFreq(F_freqs);
  for (auto &F : M->getFunctionList()) {
    if (F.empty() || F_freqs.find(&F) == F_freqs.end())
      continue;
    auto &BFI = getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
    Scaled64 EntryFreq(BFI.getEntryFreq(), 0);

    if ((IGC_GET_FLAG_VALUE(PrintStaticProfileGuidedSpillCostAnalysis) & PGSS_IGC_DUMP_BLK) != 0)
      dbgs() << "Function frequency of " << F.getName().str() << ": " << F_freqs[&F].toString() << "\n";

    for (auto &B : F) {
      Scaled64 BBCount(BFI.getBlockFreq(&B).getFrequency(), 0);
      BBCount /= EntryFreq;
      BBCount *= F_freqs[&F];
      B_freqs[&B] = BBCount;
      if ((IGC_GET_FLAG_VALUE(PrintStaticProfileGuidedSpillCostAnalysis) & PGSS_IGC_DUMP_BLK) != 0)
        dbgs() << "Block frequency of " << B.getName().str() << " " << &B << ": " << BBCount.toString() << "\n";

      Instruction *last_inst = B.getTerminator();
      if (last_inst) {
        // llvm::dbgs() << "Digits: " <<  BBCount.getDigits() << "\n";
        // llvm::dbgs() << "Scale: " << BBCount.getScale() << "\n";
        MDNode *m_node = MDNode::get(C, MDString::get(C, std::to_string(BBCount.getDigits())));
        last_inst->setMetadata("stats.blockFrequency.digits", m_node);
        m_node = MDNode::get(C, MDString::get(C, std::to_string(BBCount.getScale())));
        last_inst->setMetadata("stats.blockFrequency.scale", m_node);
      }
    }
  }
  return;
}

void GenerateFrequencyData::updateStaticFuncFreq(DenseMap<Function *, ScaledNumber<uint64_t>> &Counts) {
  auto MayHaveIndirectCalls = [](Function &F) {
    for (auto *U : F.users()) {
      if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
        return true;
    }
    return false;
  };
  uint64_t InitialSyntheticCount = 10;
  uint64_t InlineSyntheticCount = 15;
  uint64_t ColdSyntheticCount = 5;
  std::unordered_map<llvm::BasicBlock *, Scaled64> blockFreqs;
  std::unordered_map<llvm::Function *, Scaled64> entryFreqs;
  for (Function &F : getModule()->getFunctionList()) {
    uint64_t InitialCount = InitialSyntheticCount;
    if (!F.empty()) {
      auto &BFI = getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
      entryFreqs[&F] = Scaled64(BFI.getEntryFreq(), 0);
      for (auto &B : F)
        blockFreqs[&B] = Scaled64(BFI.getBlockFreq(&B).getFrequency(), 0);
    }
    if (F.isDeclaration())
      continue;
    if (F.hasFnAttribute(llvm::Attribute::AlwaysInline) || F.hasFnAttribute(llvm::Attribute::InlineHint)) {
      // Use a higher value for inline functions to account for the fact that
      // these are usually beneficial to inline.
      InitialCount = InlineSyntheticCount;
    } else if (F.hasLocalLinkage() && !MayHaveIndirectCalls(F)) {
      // Local functions without inline hints get counts only through
      // propagation.
      InitialCount = 0;
    } else if (F.hasFnAttribute(llvm::Attribute::Cold) || F.hasFnAttribute(llvm::Attribute::NoInline)) {
      // Use a lower value for noinline and cold functions.
      InitialCount = ColdSyntheticCount;
    }
    Counts[&F] = Scaled64(InitialCount, 0);
  }
  // Edge includes information about the source. Hence ignore the first
  // parameter.
  auto GetCallSiteProfCount = [&](const CallGraphNode *, const CallGraphNode::CallRecord &Edge) {
    std::optional<Scaled64> Res = std::nullopt;
    if (!Edge.first)
      return IGCLLVM::makeLLVMOptional(Res);
    CallBase &CB = *cast<CallBase>(*Edge.first);
    Function *Caller = CB.getCaller();
    BasicBlock *CSBB = CB.getParent();

    // Now compute the callsite count from relative frequency and
    // entry count:
    Scaled64 EntryFreq = entryFreqs[Caller];
    Scaled64 BBCount = blockFreqs[CSBB];
    IGC_ASSERT(EntryFreq != 0);
    BBCount /= EntryFreq;
    BBCount *= Counts[Caller];
    return IGCLLVM::makeLLVMOptional(std::optional<Scaled64>(BBCount));
  };
  CallGraph CG(*M);
  // Propgate the entry counts on the callgraph.
  SyntheticCountsUtils<const CallGraph *>::propagate(&CG, GetCallSiteProfCount,
                                                     [&](const CallGraphNode *N, Scaled64 New) {
                                                       auto F = N->getFunction();
                                                       if (!F || F->isDeclaration())
                                                         return;
                                                       Counts[F] += New;
                                                     });

  for (auto &F : M->getFunctionList()) {
    if (F.empty())
      continue;
    if (Counts.find(&F) != Counts.end()) {
      if ((IGC_GET_FLAG_VALUE(PrintStaticProfileGuidedSpillCostAnalysis) & PGSS_IGC_DUMP_FUNC) != 0)
        dbgs() << F.getName().str() << " Freq: " << Counts[&F].toString() << "\n";
    }
  }
  return;
}