2017-03-03 01:07:34 +00:00
|
|
|
//===- InstrProf.cpp - Instrumented profiling format support --------------===//
|
2014-03-21 17:24:48 +00:00
|
|
|
//
|
2019-01-19 08:50:56 +00:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2014-03-21 17:24:48 +00:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This file contains support for clang's instrumentation based PGO and
|
|
|
|
// coverage.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2017-06-06 11:49:48 +00:00
|
|
|
#include "llvm/ProfileData/InstrProf.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/ADT/ArrayRef.h"
|
2023-06-06 11:43:36 -07:00
|
|
|
#include "llvm/ADT/SetVector.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/ADT/SmallVector.h"
|
2016-01-04 21:31:09 +00:00
|
|
|
#include "llvm/ADT/StringExtras.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/ADT/StringRef.h"
|
2021-01-14 15:31:32 -08:00
|
|
|
#include "llvm/Config/config.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/IR/Constant.h"
|
2015-11-09 00:01:22 +00:00
|
|
|
#include "llvm/IR/Constants.h"
|
|
|
|
#include "llvm/IR/Function.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/IR/GlobalValue.h"
|
2015-11-09 00:01:22 +00:00
|
|
|
#include "llvm/IR/GlobalVariable.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/IR/Instruction.h"
|
|
|
|
#include "llvm/IR/LLVMContext.h"
|
2016-02-04 19:11:43 +00:00
|
|
|
#include "llvm/IR/MDBuilder.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/IR/Metadata.h"
|
2015-12-31 07:57:16 +00:00
|
|
|
#include "llvm/IR/Module.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/IR/Type.h"
|
2019-04-30 21:19:12 +00:00
|
|
|
#include "llvm/ProfileData/InstrProfReader.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/Support/Casting.h"
|
|
|
|
#include "llvm/Support/CommandLine.h"
|
|
|
|
#include "llvm/Support/Compiler.h"
|
2015-12-31 07:57:16 +00:00
|
|
|
#include "llvm/Support/Compression.h"
|
2024-04-01 08:52:35 -07:00
|
|
|
#include "llvm/Support/Debug.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/Support/Endian.h"
|
|
|
|
#include "llvm/Support/Error.h"
|
2014-03-21 17:24:48 +00:00
|
|
|
#include "llvm/Support/ErrorHandling.h"
|
2015-12-31 07:57:16 +00:00
|
|
|
#include "llvm/Support/LEB128.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/Support/MathExtras.h"
|
2016-07-12 17:14:51 +00:00
|
|
|
#include "llvm/Support/Path.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include "llvm/Support/SwapByteOrder.h"
|
2023-02-01 09:24:44 -08:00
|
|
|
#include "llvm/Support/VirtualFileSystem.h"
|
2023-02-07 12:21:51 +00:00
|
|
|
#include "llvm/TargetParser/Triple.h"
|
2017-03-03 01:07:34 +00:00
|
|
|
#include <algorithm>
|
|
|
|
#include <cassert>
|
|
|
|
#include <cstddef>
|
|
|
|
#include <cstdint>
|
2017-06-06 11:49:48 +00:00
|
|
|
#include <cstring>
|
2017-03-03 01:07:34 +00:00
|
|
|
#include <memory>
|
|
|
|
#include <string>
|
|
|
|
#include <system_error>
|
2022-02-14 11:52:40 -08:00
|
|
|
#include <type_traits>
|
2017-03-03 01:07:34 +00:00
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
2014-03-21 17:24:48 +00:00
|
|
|
|
|
|
|
using namespace llvm;
|
|
|
|
|
2024-04-01 08:52:35 -07:00
|
|
|
#define DEBUG_TYPE "instrprof"
|
|
|
|
|
2016-07-12 17:14:51 +00:00
|
|
|
static cl::opt<bool> StaticFuncFullModulePrefix(
|
2017-12-01 00:53:10 +00:00
|
|
|
"static-func-full-module-prefix", cl::init(true), cl::Hidden,
|
2016-07-12 17:14:51 +00:00
|
|
|
cl::desc("Use full module build paths in the profile counter names for "
|
|
|
|
"static functions."));
|
|
|
|
|
2017-02-25 00:00:36 +00:00
|
|
|
// This option is tailored to users that have different top-level directory in
|
|
|
|
// profile-gen and profile-use compilation. Users need to specific the number
|
|
|
|
// of levels to strip. A value larger than the number of directories in the
|
|
|
|
// source file will strip all the directory names and only leave the basename.
|
|
|
|
//
|
2017-02-27 17:59:01 +00:00
|
|
|
// Note current ThinLTO module importing for the indirect-calls assumes
|
2017-02-25 00:00:36 +00:00
|
|
|
// the source directory name not being stripped. A non-zero option value here
|
|
|
|
// can potentially prevent some inter-module indirect-call-promotions.
|
|
|
|
static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
|
2017-12-01 00:53:10 +00:00
|
|
|
"static-func-strip-dirname-prefix", cl::init(0), cl::Hidden,
|
2017-02-25 00:00:36 +00:00
|
|
|
cl::desc("Strip specified level of directory name from source path in "
|
|
|
|
"the profile counter name for static functions."));
|
|
|
|
|
2021-08-30 19:12:16 +00:00
|
|
|
static std::string getInstrProfErrString(instrprof_error Err,
|
|
|
|
const std::string &ErrMsg = "") {
|
|
|
|
std::string Msg;
|
|
|
|
raw_string_ostream OS(Msg);
|
|
|
|
|
2016-05-19 03:54:45 +00:00
|
|
|
switch (Err) {
|
|
|
|
case instrprof_error::success:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "success";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::eof:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "end of File";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::unrecognized_format:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "unrecognized instrumentation profile encoding format";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::bad_magic:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "invalid instrumentation profile data (bad magic)";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::bad_header:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "invalid instrumentation profile data (file header is corrupt)";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::unsupported_version:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "unsupported instrumentation profile format version";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::unsupported_hash_type:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "unsupported instrumentation profile hash type";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::too_large:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "too much profile data";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::truncated:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "truncated profile data";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::malformed:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "malformed instrumentation profile data";
|
|
|
|
break;
|
[Profile] Add binary profile correlation for code coverage. (#69493)
## Motivation
Since we don't need the metadata sections at runtime, we can somehow
offload them from memory at runtime. Initially, I explored [debug info
correlation](https://discourse.llvm.org/t/instrprofiling-lightweight-instrumentation/59113),
which is used for PGO with value profiling disabled. However, it
currently only works with DWARF and it's be hard to add such artificial
debug info for every function in to CodeView which is used on Windows.
So, offloading profile metadata sections at runtime seems to be a
platform independent option.
## Design
The idea is to use new section names for profile name and data sections
and mark them as metadata sections. Under this mode, the new sections
are non-SHF_ALLOC in ELF. So, they are not loaded into memory at runtime
and can be stripped away as a post-linking step. After the process
exits, the generated raw profiles will contains only headers + counters.
llvm-profdata can be used correlate raw profiles with the unstripped
binary to generate indexed profile.
## Data
For chromium base_unittests with code coverage on linux, the binary size
overhead due to instrumentation reduced from 64M to 38.8M (39.4%) and
the raw profile files size reduce from 128M to 68M (46.9%)
```
$ bloaty out/cov/base_unittests.stripped -- out/no-cov/base_unittests.stripped
FILE SIZE VM SIZE
-------------- --------------
+121% +30.4Mi +121% +30.4Mi .text
[NEW] +14.6Mi [NEW] +14.6Mi __llvm_prf_data
[NEW] +10.6Mi [NEW] +10.6Mi __llvm_prf_names
[NEW] +5.86Mi [NEW] +5.86Mi __llvm_prf_cnts
+95% +1.75Mi +95% +1.75Mi .eh_frame
+108% +400Ki +108% +400Ki .eh_frame_hdr
+9.5% +211Ki +9.5% +211Ki .rela.dyn
+9.2% +95.0Ki +9.2% +95.0Ki .data.rel.ro
+5.0% +87.3Ki +5.0% +87.3Ki .rodata
[ = ] 0 +13% +47.0Ki .bss
+40% +1.78Ki +40% +1.78Ki .got
+12% +1.49Ki +12% +1.49Ki .gcc_except_table
[ = ] 0 +65% +1.23Ki .relro_padding
+62% +1.20Ki [ = ] 0 [Unmapped]
+13% +448 +19% +448 .init_array
+8.8% +192 [ = ] 0 [ELF Section Headers]
+0.0% +136 +0.0% +80 [7 Others]
+0.1% +96 +0.1% +96 .dynsym
+1.2% +96 +1.2% +96 .rela.plt
+1.5% +80 +1.2% +64 .plt
[ = ] 0 -99.2% -3.68Ki [LOAD #5 [RW]]
+195% +64.0Mi +194% +64.0Mi TOTAL
$ bloaty out/cov-cor/base_unittests.stripped -- out/no-cov/base_unittests.stripped
FILE SIZE VM SIZE
-------------- --------------
+121% +30.4Mi +121% +30.4Mi .text
[NEW] +5.86Mi [NEW] +5.86Mi __llvm_prf_cnts
+95% +1.75Mi +95% +1.75Mi .eh_frame
+108% +400Ki +108% +400Ki .eh_frame_hdr
+9.5% +211Ki +9.5% +211Ki .rela.dyn
+9.2% +95.0Ki +9.2% +95.0Ki .data.rel.ro
+5.0% +87.3Ki +5.0% +87.3Ki .rodata
[ = ] 0 +13% +47.0Ki .bss
+40% +1.78Ki +40% +1.78Ki .got
+12% +1.49Ki +12% +1.49Ki .gcc_except_table
+13% +448 +19% +448 .init_array
+0.1% +96 +0.1% +96 .dynsym
+1.2% +96 +1.2% +96 .rela.plt
+1.2% +64 +1.2% +64 .plt
+2.9% +64 [ = ] 0 [ELF Section Headers]
+0.0% +40 +0.0% +40 .data
+1.2% +32 +1.2% +32 .got.plt
+0.0% +24 +0.0% +8 [5 Others]
[ = ] 0 -22.9% -872 [LOAD #5 [RW]]
-74.5% -1.44Ki [ = ] 0 [Unmapped]
[ = ] 0 -76.5% -1.45Ki .relro_padding
+118% +38.8Mi +117% +38.8Mi TOTAL
```
A few things to note:
1. llvm-profdata doesn't support filter raw profiles by binary id yet,
so when a raw profile doesn't belongs to the binary being digested by
llvm-profdata, merging will fail. Once this is implemented,
llvm-profdata should be able to only merge raw profiles with the same
binary id as the binary and discard the rest (with mismatched/missing
binary id). The workflow I have in mind is to have scripts invoke
llvm-profdata to get all binary ids for all raw profiles, and
selectively choose the raw pnrofiles with matching binary id and the
binary to llvm-profdata for merging.
2. Note: In COFF, currently they are still loaded into memory but not
used. I didn't do it in this patch because I noticed that `.lcovmap` and
`.lcovfunc` are loaded into memory. A separate patch will address it.
3. This should works with PGO when value profiling is disabled as debug
info correlation currently doing, though I haven't tested this yet.
2023-12-14 14:16:38 -05:00
|
|
|
case instrprof_error::missing_correlation_info:
|
|
|
|
OS << "debug info/binary for correlation is required";
|
2021-12-16 14:45:54 -08:00
|
|
|
break;
|
[Profile] Add binary profile correlation for code coverage. (#69493)
## Motivation
Since we don't need the metadata sections at runtime, we can somehow
offload them from memory at runtime. Initially, I explored [debug info
correlation](https://discourse.llvm.org/t/instrprofiling-lightweight-instrumentation/59113),
which is used for PGO with value profiling disabled. However, it
currently only works with DWARF and it's be hard to add such artificial
debug info for every function in to CodeView which is used on Windows.
So, offloading profile metadata sections at runtime seems to be a
platform independent option.
## Design
The idea is to use new section names for profile name and data sections
and mark them as metadata sections. Under this mode, the new sections
are non-SHF_ALLOC in ELF. So, they are not loaded into memory at runtime
and can be stripped away as a post-linking step. After the process
exits, the generated raw profiles will contains only headers + counters.
llvm-profdata can be used correlate raw profiles with the unstripped
binary to generate indexed profile.
## Data
For chromium base_unittests with code coverage on linux, the binary size
overhead due to instrumentation reduced from 64M to 38.8M (39.4%) and
the raw profile files size reduce from 128M to 68M (46.9%)
```
$ bloaty out/cov/base_unittests.stripped -- out/no-cov/base_unittests.stripped
FILE SIZE VM SIZE
-------------- --------------
+121% +30.4Mi +121% +30.4Mi .text
[NEW] +14.6Mi [NEW] +14.6Mi __llvm_prf_data
[NEW] +10.6Mi [NEW] +10.6Mi __llvm_prf_names
[NEW] +5.86Mi [NEW] +5.86Mi __llvm_prf_cnts
+95% +1.75Mi +95% +1.75Mi .eh_frame
+108% +400Ki +108% +400Ki .eh_frame_hdr
+9.5% +211Ki +9.5% +211Ki .rela.dyn
+9.2% +95.0Ki +9.2% +95.0Ki .data.rel.ro
+5.0% +87.3Ki +5.0% +87.3Ki .rodata
[ = ] 0 +13% +47.0Ki .bss
+40% +1.78Ki +40% +1.78Ki .got
+12% +1.49Ki +12% +1.49Ki .gcc_except_table
[ = ] 0 +65% +1.23Ki .relro_padding
+62% +1.20Ki [ = ] 0 [Unmapped]
+13% +448 +19% +448 .init_array
+8.8% +192 [ = ] 0 [ELF Section Headers]
+0.0% +136 +0.0% +80 [7 Others]
+0.1% +96 +0.1% +96 .dynsym
+1.2% +96 +1.2% +96 .rela.plt
+1.5% +80 +1.2% +64 .plt
[ = ] 0 -99.2% -3.68Ki [LOAD #5 [RW]]
+195% +64.0Mi +194% +64.0Mi TOTAL
$ bloaty out/cov-cor/base_unittests.stripped -- out/no-cov/base_unittests.stripped
FILE SIZE VM SIZE
-------------- --------------
+121% +30.4Mi +121% +30.4Mi .text
[NEW] +5.86Mi [NEW] +5.86Mi __llvm_prf_cnts
+95% +1.75Mi +95% +1.75Mi .eh_frame
+108% +400Ki +108% +400Ki .eh_frame_hdr
+9.5% +211Ki +9.5% +211Ki .rela.dyn
+9.2% +95.0Ki +9.2% +95.0Ki .data.rel.ro
+5.0% +87.3Ki +5.0% +87.3Ki .rodata
[ = ] 0 +13% +47.0Ki .bss
+40% +1.78Ki +40% +1.78Ki .got
+12% +1.49Ki +12% +1.49Ki .gcc_except_table
+13% +448 +19% +448 .init_array
+0.1% +96 +0.1% +96 .dynsym
+1.2% +96 +1.2% +96 .rela.plt
+1.2% +64 +1.2% +64 .plt
+2.9% +64 [ = ] 0 [ELF Section Headers]
+0.0% +40 +0.0% +40 .data
+1.2% +32 +1.2% +32 .got.plt
+0.0% +24 +0.0% +8 [5 Others]
[ = ] 0 -22.9% -872 [LOAD #5 [RW]]
-74.5% -1.44Ki [ = ] 0 [Unmapped]
[ = ] 0 -76.5% -1.45Ki .relro_padding
+118% +38.8Mi +117% +38.8Mi TOTAL
```
A few things to note:
1. llvm-profdata doesn't support filter raw profiles by binary id yet,
so when a raw profile doesn't belongs to the binary being digested by
llvm-profdata, merging will fail. Once this is implemented,
llvm-profdata should be able to only merge raw profiles with the same
binary id as the binary and discard the rest (with mismatched/missing
binary id). The workflow I have in mind is to have scripts invoke
llvm-profdata to get all binary ids for all raw profiles, and
selectively choose the raw pnrofiles with matching binary id and the
binary to llvm-profdata for merging.
2. Note: In COFF, currently they are still loaded into memory but not
used. I didn't do it in this patch because I noticed that `.lcovmap` and
`.lcovfunc` are loaded into memory. A separate patch will address it.
3. This should works with PGO when value profiling is disabled as debug
info correlation currently doing, though I haven't tested this yet.
2023-12-14 14:16:38 -05:00
|
|
|
case instrprof_error::unexpected_correlation_info:
|
|
|
|
OS << "debug info/binary for correlation is not necessary";
|
2021-12-16 14:45:54 -08:00
|
|
|
break;
|
|
|
|
case instrprof_error::unable_to_correlate_profile:
|
|
|
|
OS << "unable to correlate profile";
|
|
|
|
break;
|
2021-01-14 15:31:32 -08:00
|
|
|
case instrprof_error::invalid_prof:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "invalid profile created. Please file a bug "
|
|
|
|
"at: " BUG_REPORT_URL
|
|
|
|
" and include the profraw files that caused this error.";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::unknown_function:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "no profile data available for function";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::hash_mismatch:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "function control flow change detected (hash mismatch)";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::count_mismatch:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "function basic block count change detected (counter mismatch)";
|
|
|
|
break;
|
2023-09-21 13:07:31 -05:00
|
|
|
case instrprof_error::bitmap_mismatch:
|
|
|
|
OS << "function bitmap size change detected (bitmap size mismatch)";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::counter_overflow:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "counter overflow";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::value_site_count_mismatch:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "function value site count change detected (counter mismatch)";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::compress_failed:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "failed to compress data (zlib)";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
case instrprof_error::uncompress_failed:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "failed to uncompress data (zlib)";
|
|
|
|
break;
|
2016-10-19 22:51:17 +00:00
|
|
|
case instrprof_error::empty_raw_profile:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "empty raw profile file";
|
|
|
|
break;
|
2017-07-21 21:41:15 +00:00
|
|
|
case instrprof_error::zlib_unavailable:
|
2021-08-30 19:12:16 +00:00
|
|
|
OS << "profile uses zlib compression but the profile reader was built "
|
|
|
|
"without zlib support";
|
|
|
|
break;
|
2023-04-27 10:32:36 -07:00
|
|
|
case instrprof_error::raw_profile_version_mismatch:
|
|
|
|
OS << "raw profile version mismatch";
|
|
|
|
break;
|
2023-10-31 16:40:51 -04:00
|
|
|
case instrprof_error::counter_value_too_large:
|
|
|
|
OS << "excessively large counter value suggests corrupted profile data";
|
|
|
|
break;
|
2016-05-19 03:54:45 +00:00
|
|
|
}
|
2021-08-30 19:12:16 +00:00
|
|
|
|
|
|
|
// If optional error message is not empty, append it to the message.
|
|
|
|
if (!ErrMsg.empty())
|
2021-11-09 20:21:49 +00:00
|
|
|
OS << ": " << ErrMsg;
|
2021-08-30 19:12:16 +00:00
|
|
|
|
|
|
|
return OS.str();
|
2016-05-19 03:54:45 +00:00
|
|
|
}
|
|
|
|
|
2017-03-03 01:07:34 +00:00
|
|
|
namespace {
|
|
|
|
|
2016-05-24 20:13:46 +00:00
|
|
|
// FIXME: This class is only here to support the transition to llvm::Error. It
|
|
|
|
// will be removed once this transition is complete. Clients should prefer to
|
|
|
|
// deal with the Error value directly, rather than converting to error_code.
|
2014-06-12 01:45:43 +00:00
|
|
|
class InstrProfErrorCategoryType : public std::error_category {
|
2016-10-19 23:52:38 +00:00
|
|
|
const char *name() const noexcept override { return "llvm.instrprof"; }
|
2017-03-03 01:07:34 +00:00
|
|
|
|
2014-03-21 17:24:48 +00:00
|
|
|
std::string message(int IE) const override {
|
2016-05-19 03:54:45 +00:00
|
|
|
return getInstrProfErrString(static_cast<instrprof_error>(IE));
|
2014-03-21 17:24:48 +00:00
|
|
|
}
|
|
|
|
};
|
2017-03-03 01:07:34 +00:00
|
|
|
|
2016-01-26 18:48:36 +00:00
|
|
|
} // end anonymous namespace
|
2014-03-21 17:24:48 +00:00
|
|
|
|
2014-06-12 01:45:43 +00:00
|
|
|
const std::error_category &llvm::instrprof_category() {
|
2022-06-29 14:29:33 +02:00
|
|
|
static InstrProfErrorCategoryType ErrorCategory;
|
|
|
|
return ErrorCategory;
|
2014-03-21 17:24:48 +00:00
|
|
|
}
|
2015-11-09 00:01:22 +00:00
|
|
|
|
2017-04-13 23:37:12 +00:00
|
|
|
namespace {
|
|
|
|
|
|
|
|
const char *InstrProfSectNameCommon[] = {
|
2017-04-15 00:09:57 +00:00
|
|
|
#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
|
2017-04-13 23:37:12 +00:00
|
|
|
SectNameCommon,
|
|
|
|
#include "llvm/ProfileData/InstrProfData.inc"
|
|
|
|
};
|
|
|
|
|
|
|
|
const char *InstrProfSectNameCoff[] = {
|
2017-04-15 00:09:57 +00:00
|
|
|
#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
|
2017-04-13 23:37:12 +00:00
|
|
|
SectNameCoff,
|
|
|
|
#include "llvm/ProfileData/InstrProfData.inc"
|
|
|
|
};
|
|
|
|
|
|
|
|
const char *InstrProfSectNamePrefix[] = {
|
2017-04-15 00:09:57 +00:00
|
|
|
#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
|
2017-04-13 23:37:12 +00:00
|
|
|
Prefix,
|
|
|
|
#include "llvm/ProfileData/InstrProfData.inc"
|
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace
|
|
|
|
|
2015-11-09 00:01:22 +00:00
|
|
|
namespace llvm {
|
|
|
|
|
2019-10-21 11:48:38 -07:00
|
|
|
cl::opt<bool> DoInstrProfNameCompression(
|
|
|
|
"enable-name-compression",
|
|
|
|
cl::desc("Enable name/filename string compression"), cl::init(true));
|
|
|
|
|
2024-04-01 08:52:35 -07:00
|
|
|
cl::opt<bool> EnableVTableValueProfiling(
|
|
|
|
"enable-vtable-value-profiling", cl::init(false),
|
|
|
|
cl::desc("If true, the virtual table address will be instrumented to know "
|
|
|
|
"the types of a C++ pointer. The information is used in indirect "
|
|
|
|
"call promotion to do selective vtable-based comparison."));
|
|
|
|
|
[TypeProf][InstrFDO]Implement more efficient comparison sequence for indirect-call-promotion with vtable profiles. (#81442)
Clang's `-fwhole-program-vtables` is required for this optimization to
take place. If `-fwhole-program-vtables` is not enabled, this change is
no-op.
* Function-comparison (before):
```
%vtable = load ptr, ptr %obj
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
%cond = icmp eq ptr %func, @callee
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
call %func
```
* VTable-comparison (after):
```
%vtable = load ptr, ptr %obj
%cond = icmp eq ptr %vtable, @vtable-address-point
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
call %func
```
Key changes:
1. Find out virtual calls and the vtables they come from.
- The ICP relies on type intrinsic `llvm.type.test` to find out virtual
calls and the
compatible vtables, and relies on type metadata to find the address
point for comparison.
2. ICP pass does cost-benefit analysis and compares vtable only when the
number of vtables for a function candidate is within (option specified)
threshold.
3. Sink the function addressing and vtable load instruction to indirect
fallback.
- The sink helper functions are simplified versions of
`InstCombinerImpl::tryToSinkInstruction`. Currently debug intrinsics are
not handled. Ideally `InstCombinerImpl::tryToSinkInstructionDbgValues`
and `InstCombinerImpl::tryToSinkInstructionDbgVariableRecords` could be
moved into Transforms/Utils/Local.cpp (or another util cpp file) to
handle debug intrinsics when moving instructions across basic blocks.
4. Keep value profiles updated
1) Update vtable value profiles after inline
2) For either function-based comparison or vtable-based comparison,
update both vtable and indirect call value profiles.
2024-06-29 23:21:33 -07:00
|
|
|
cl::opt<bool> EnableVTableProfileUse(
|
|
|
|
"enable-vtable-profile-use", cl::init(false),
|
|
|
|
cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable "
|
|
|
|
"profiles will be used by ICP pass for more efficient indirect "
|
|
|
|
"call sequence. If false, type profiles won't be used."));
|
|
|
|
|
2017-04-15 00:09:57 +00:00
|
|
|
std::string getInstrProfSectionName(InstrProfSectKind IPSK,
|
|
|
|
Triple::ObjectFormatType OF,
|
|
|
|
bool AddSegmentInfo) {
|
|
|
|
std::string SectName;
|
2017-04-14 17:48:40 +00:00
|
|
|
|
2017-04-15 00:09:57 +00:00
|
|
|
if (OF == Triple::MachO && AddSegmentInfo)
|
|
|
|
SectName = InstrProfSectNamePrefix[IPSK];
|
2017-04-13 23:37:12 +00:00
|
|
|
|
2017-04-15 00:09:57 +00:00
|
|
|
if (OF == Triple::COFF)
|
|
|
|
SectName += InstrProfSectNameCoff[IPSK];
|
|
|
|
else
|
|
|
|
SectName += InstrProfSectNameCommon[IPSK];
|
2017-04-13 23:37:12 +00:00
|
|
|
|
2017-04-15 00:09:57 +00:00
|
|
|
if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
|
|
|
|
SectName += ",regular,live_support";
|
2017-04-13 23:37:12 +00:00
|
|
|
|
2017-04-15 00:09:57 +00:00
|
|
|
return SectName;
|
2017-04-14 17:48:40 +00:00
|
|
|
}
|
|
|
|
|
2016-05-19 03:54:45 +00:00
|
|
|
std::string InstrProfError::message() const {
|
2021-08-30 19:12:16 +00:00
|
|
|
return getInstrProfErrString(Err, Msg);
|
2016-05-19 03:54:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
char InstrProfError::ID = 0;
|
|
|
|
|
2023-12-19 12:25:56 -08:00
|
|
|
std::string getPGOFuncName(StringRef Name, GlobalValue::LinkageTypes Linkage,
|
2015-12-11 20:23:22 +00:00
|
|
|
StringRef FileName,
|
|
|
|
uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
|
2023-12-19 12:25:56 -08:00
|
|
|
// Value names may be prefixed with a binary '1' to indicate
|
|
|
|
// that the backend should not modify the symbols due to any platform
|
|
|
|
// naming convention. Do not include that '1' in the PGO profile name.
|
|
|
|
if (Name[0] == '\1')
|
|
|
|
Name = Name.substr(1);
|
|
|
|
|
|
|
|
std::string NewName = std::string(Name);
|
|
|
|
if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
|
|
|
|
// For local symbols, prepend the main file name to distinguish them.
|
|
|
|
// Do not include the full path in the file name since there's no guarantee
|
|
|
|
// that it will stay the same, e.g., if the files are checked out from
|
|
|
|
// version control in different locations.
|
|
|
|
if (FileName.empty())
|
|
|
|
NewName = NewName.insert(0, "<unknown>:");
|
|
|
|
else
|
|
|
|
NewName = NewName.insert(0, FileName.str() + ":");
|
|
|
|
}
|
|
|
|
return NewName;
|
2015-11-09 00:01:22 +00:00
|
|
|
}
|
|
|
|
|
2017-02-25 00:00:36 +00:00
|
|
|
// Strip NumPrefix level of directory name from PathNameStr. If the number of
|
|
|
|
// directory separators is less than NumPrefix, strip all the directories and
|
|
|
|
// leave base file name only.
|
|
|
|
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
|
|
|
|
uint32_t Count = NumPrefix;
|
|
|
|
uint32_t Pos = 0, LastPos = 0;
|
2024-06-07 15:06:04 -07:00
|
|
|
for (const auto &CI : PathNameStr) {
|
2017-02-25 00:00:36 +00:00
|
|
|
++Pos;
|
|
|
|
if (llvm::sys::path::is_separator(CI)) {
|
|
|
|
LastPos = Pos;
|
|
|
|
--Count;
|
|
|
|
}
|
|
|
|
if (Count == 0)
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
return PathNameStr.substr(LastPos);
|
|
|
|
}
|
|
|
|
|
2023-10-26 14:48:36 -07:00
|
|
|
static StringRef getStrippedSourceFileName(const GlobalObject &GO) {
|
|
|
|
StringRef FileName(GO.getParent()->getSourceFileName());
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
|
|
|
|
if (StripLevel < StaticFuncStripDirNamePrefix)
|
|
|
|
StripLevel = StaticFuncStripDirNamePrefix;
|
|
|
|
if (StripLevel)
|
|
|
|
FileName = stripDirPrefix(FileName, StripLevel);
|
|
|
|
return FileName;
|
|
|
|
}
|
|
|
|
|
2024-01-04 16:13:57 -08:00
|
|
|
// The PGO name has the format [<filepath>;]<mangled-name> where <filepath>; is
|
|
|
|
// provided if linkage is local and is used to discriminate possibly identical
|
|
|
|
// mangled names. ";" is used because it is unlikely to be found in either
|
|
|
|
// <filepath> or <mangled-name>.
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
//
|
|
|
|
// Older compilers used getPGOFuncName() which has the format
|
2024-01-04 16:13:57 -08:00
|
|
|
// [<filepath>:]<mangled-name>. This caused trouble for Objective-C functions
|
|
|
|
// which commonly have :'s in their names. We still need to compute this name to
|
|
|
|
// lookup functions from profiles built by older compilers.
|
2023-10-26 14:48:36 -07:00
|
|
|
static std::string
|
|
|
|
getIRPGONameForGlobalObject(const GlobalObject &GO,
|
|
|
|
GlobalValue::LinkageTypes Linkage,
|
|
|
|
StringRef FileName) {
|
2024-01-04 16:13:57 -08:00
|
|
|
return GlobalValue::getGlobalIdentifier(GO.getName(), Linkage, FileName);
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
}
|
|
|
|
|
2023-10-26 14:48:36 -07:00
|
|
|
static std::optional<std::string> lookupPGONameFromMetadata(MDNode *MD) {
|
|
|
|
if (MD != nullptr) {
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
StringRef S = cast<MDString>(MD->getOperand(0))->getString();
|
|
|
|
return S.str();
|
|
|
|
}
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
2023-10-26 14:48:36 -07:00
|
|
|
// Returns the PGO object name. This function has some special handling
|
|
|
|
// when called in LTO optimization. The following only applies when calling in
|
|
|
|
// LTO passes (when \c InLTO is true): LTO's internalization privatizes many
|
|
|
|
// global linkage symbols. This happens after value profile annotation, but
|
|
|
|
// those internal linkage functions should not have a source prefix.
|
|
|
|
// Additionally, for ThinLTO mode, exported internal functions are promoted
|
|
|
|
// and renamed. We need to ensure that the original internal PGO name is
|
|
|
|
// used when computing the GUID that is compared against the profiled GUIDs.
|
|
|
|
// To differentiate compiler generated internal symbols from original ones,
|
|
|
|
// PGOFuncName meta data are created and attached to the original internal
|
|
|
|
// symbols in the value profile annotation step
|
|
|
|
// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
|
|
|
|
// data, its original linkage must be non-internal.
|
|
|
|
static std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO,
|
|
|
|
MDNode *PGONameMetadata) {
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
if (!InLTO) {
|
2023-10-26 14:48:36 -07:00
|
|
|
auto FileName = getStrippedSourceFileName(GO);
|
|
|
|
return getIRPGONameForGlobalObject(GO, GO.getLinkage(), FileName);
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// In LTO mode (when InLTO is true), first check if there is a meta data.
|
2023-10-26 14:48:36 -07:00
|
|
|
if (auto IRPGOFuncName = lookupPGONameFromMetadata(PGONameMetadata))
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
return *IRPGOFuncName;
|
|
|
|
|
|
|
|
// If there is no meta data, the function must be a global before the value
|
|
|
|
// profile annotation pass. Its current linkage may be internal if it is
|
|
|
|
// internalized in LTO mode.
|
2023-10-26 14:48:36 -07:00
|
|
|
return getIRPGONameForGlobalObject(GO, GlobalValue::ExternalLinkage, "");
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
}
|
|
|
|
|
2023-10-26 14:48:36 -07:00
|
|
|
// Returns the IRPGO function name and does special handling when called
|
|
|
|
// in LTO optimization. See the comments of `getIRPGOObjectName` for details.
|
|
|
|
std::string getIRPGOFuncName(const Function &F, bool InLTO) {
|
|
|
|
return getIRPGOObjectName(F, InLTO, getPGOFuncNameMetadata(F));
|
|
|
|
}
|
|
|
|
|
2023-12-19 12:25:56 -08:00
|
|
|
// Please use getIRPGOFuncName for LLVM IR instrumentation. This function is
|
|
|
|
// for front-end (Clang, etc) instrumentation.
|
|
|
|
// The implementation is kept for profile matching from older profiles.
|
2023-10-26 14:48:36 -07:00
|
|
|
// This is similar to `getIRPGOFuncName` except that this function calls
|
|
|
|
// 'getPGOFuncName' to get a name and `getIRPGOFuncName` calls
|
|
|
|
// 'getIRPGONameForGlobalObject'. See the difference between two callees in the
|
|
|
|
// comments of `getIRPGONameForGlobalObject`.
|
2016-03-30 18:37:52 +00:00
|
|
|
std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
|
2016-07-12 17:14:51 +00:00
|
|
|
if (!InLTO) {
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
auto FileName = getStrippedSourceFileName(F);
|
2016-07-12 17:14:51 +00:00
|
|
|
return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
|
|
|
|
}
|
2016-03-30 18:37:52 +00:00
|
|
|
|
2016-04-01 16:43:30 +00:00
|
|
|
// In LTO mode (when InLTO is true), first check if there is a meta data.
|
2023-10-26 14:48:36 -07:00
|
|
|
if (auto PGOFuncName = lookupPGONameFromMetadata(getPGOFuncNameMetadata(F)))
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
return *PGOFuncName;
|
2016-03-30 18:37:52 +00:00
|
|
|
|
|
|
|
// If there is no meta data, the function must be a global before the value
|
|
|
|
// profile annotation pass. Its current linkage may be internal if it is
|
|
|
|
// internalized in LTO mode.
|
2016-04-01 16:43:30 +00:00
|
|
|
return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
|
2015-11-09 00:01:22 +00:00
|
|
|
}
|
|
|
|
|
2024-04-01 08:52:35 -07:00
|
|
|
std::string getPGOName(const GlobalVariable &V, bool InLTO) {
|
|
|
|
// PGONameMetadata should be set by compiler at profile use time
|
|
|
|
// and read by symtab creation to look up symbols corresponding to
|
|
|
|
// a MD5 hash.
|
[TypeProf][InstrFDO]Implement more efficient comparison sequence for indirect-call-promotion with vtable profiles. (#81442)
Clang's `-fwhole-program-vtables` is required for this optimization to
take place. If `-fwhole-program-vtables` is not enabled, this change is
no-op.
* Function-comparison (before):
```
%vtable = load ptr, ptr %obj
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
%cond = icmp eq ptr %func, @callee
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
call %func
```
* VTable-comparison (after):
```
%vtable = load ptr, ptr %obj
%cond = icmp eq ptr %vtable, @vtable-address-point
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
call %func
```
Key changes:
1. Find out virtual calls and the vtables they come from.
- The ICP relies on type intrinsic `llvm.type.test` to find out virtual
calls and the
compatible vtables, and relies on type metadata to find the address
point for comparison.
2. ICP pass does cost-benefit analysis and compares vtable only when the
number of vtables for a function candidate is within (option specified)
threshold.
3. Sink the function addressing and vtable load instruction to indirect
fallback.
- The sink helper functions are simplified versions of
`InstCombinerImpl::tryToSinkInstruction`. Currently debug intrinsics are
not handled. Ideally `InstCombinerImpl::tryToSinkInstructionDbgValues`
and `InstCombinerImpl::tryToSinkInstructionDbgVariableRecords` could be
moved into Transforms/Utils/Local.cpp (or another util cpp file) to
handle debug intrinsics when moving instructions across basic blocks.
4. Keep value profiles updated
1) Update vtable value profiles after inline
2) For either function-based comparison or vtable-based comparison,
update both vtable and indirect call value profiles.
2024-06-29 23:21:33 -07:00
|
|
|
return getIRPGOObjectName(V, InLTO, V.getMetadata(getPGONameMetadataName()));
|
2024-04-01 08:52:35 -07:00
|
|
|
}
|
|
|
|
|
2024-02-07 20:03:44 -08:00
|
|
|
// See getIRPGOObjectName() for a discription of the format.
|
|
|
|
std::pair<StringRef, StringRef> getParsedIRPGOName(StringRef IRPGOName) {
|
|
|
|
auto [FileName, MangledName] = IRPGOName.split(kGlobalIdentifierDelimiter);
|
|
|
|
if (MangledName.empty())
|
|
|
|
return std::make_pair(StringRef(), IRPGOName);
|
|
|
|
return std::make_pair(FileName, MangledName);
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
}
|
|
|
|
|
2015-12-15 19:44:45 +00:00
|
|
|
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
|
|
|
|
if (FileName.empty())
|
2016-03-28 15:49:08 +00:00
|
|
|
return PGOFuncName;
|
2023-12-19 12:25:56 -08:00
|
|
|
// Drop the file name including ':' or ';'. See getIRPGONameForGlobalObject as
|
|
|
|
// well.
|
2023-12-18 09:39:55 -08:00
|
|
|
if (PGOFuncName.starts_with(FileName))
|
2015-12-15 19:44:45 +00:00
|
|
|
PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
|
|
|
|
return PGOFuncName;
|
|
|
|
}
|
|
|
|
|
2015-12-12 17:28:03 +00:00
|
|
|
// \p FuncName is the string used as profile lookup key for the function. A
|
|
|
|
// symbol is created to hold the name. Return the legalized symbol name.
|
2016-03-16 20:49:26 +00:00
|
|
|
std::string getPGOFuncNameVarName(StringRef FuncName,
|
|
|
|
GlobalValue::LinkageTypes Linkage) {
|
2020-01-28 20:23:46 +01:00
|
|
|
std::string VarName = std::string(getInstrProfNameVarPrefix());
|
2015-12-12 17:28:03 +00:00
|
|
|
VarName += FuncName;
|
|
|
|
|
|
|
|
if (!GlobalValue::isLocalLinkage(Linkage))
|
|
|
|
return VarName;
|
|
|
|
|
|
|
|
// Now fix up illegal chars in local VarName that may upset the assembler.
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
const char InvalidChars[] = "-:;<>/\"'";
|
2015-12-12 17:28:03 +00:00
|
|
|
size_t found = VarName.find_first_of(InvalidChars);
|
|
|
|
while (found != std::string::npos) {
|
|
|
|
VarName[found] = '_';
|
|
|
|
found = VarName.find_first_of(InvalidChars, found + 1);
|
|
|
|
}
|
|
|
|
return VarName;
|
|
|
|
}
|
|
|
|
|
2015-11-09 00:01:22 +00:00
|
|
|
GlobalVariable *createPGOFuncNameVar(Module &M,
|
|
|
|
GlobalValue::LinkageTypes Linkage,
|
2016-03-16 22:13:41 +00:00
|
|
|
StringRef PGOFuncName) {
|
2015-11-09 00:01:22 +00:00
|
|
|
// We generally want to match the function's linkage, but available_externally
|
|
|
|
// and extern_weak both have the wrong semantics, and anything that doesn't
|
|
|
|
// need to link across compilation units doesn't need to be visible at all.
|
2024-06-28 12:30:45 -05:00
|
|
|
if (Linkage == GlobalValue::ExternalWeakLinkage)
|
2015-11-09 00:01:22 +00:00
|
|
|
Linkage = GlobalValue::LinkOnceAnyLinkage;
|
|
|
|
else if (Linkage == GlobalValue::AvailableExternallyLinkage)
|
|
|
|
Linkage = GlobalValue::LinkOnceODRLinkage;
|
|
|
|
else if (Linkage == GlobalValue::InternalLinkage ||
|
|
|
|
Linkage == GlobalValue::ExternalLinkage)
|
|
|
|
Linkage = GlobalValue::PrivateLinkage;
|
|
|
|
|
2016-03-16 22:13:41 +00:00
|
|
|
auto *Value =
|
|
|
|
ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
|
2015-11-09 00:01:22 +00:00
|
|
|
auto FuncNameVar =
|
|
|
|
new GlobalVariable(M, Value->getType(), true, Linkage, Value,
|
2016-03-16 22:13:41 +00:00
|
|
|
getPGOFuncNameVarName(PGOFuncName, Linkage));
|
2015-11-09 00:01:22 +00:00
|
|
|
|
2024-06-28 12:30:45 -05:00
|
|
|
// Hide the symbol so that we correctly get a copy for each executable.
|
|
|
|
if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
|
|
|
|
FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
|
|
|
|
|
2015-11-09 00:01:22 +00:00
|
|
|
return FuncNameVar;
|
|
|
|
}
|
|
|
|
|
2016-03-16 22:13:41 +00:00
|
|
|
GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
|
|
|
|
return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
|
2015-11-09 00:01:22 +00:00
|
|
|
}
|
2015-11-10 00:24:45 +00:00
|
|
|
|
2017-06-20 01:38:56 +00:00
|
|
|
Error InstrProfSymtab::create(Module &M, bool InLTO) {
|
2016-03-30 18:37:52 +00:00
|
|
|
for (Function &F : M) {
|
|
|
|
// Function may not have a name: like using asm("") to overwrite the name.
|
|
|
|
// Ignore in this case.
|
|
|
|
if (!F.hasName())
|
|
|
|
continue;
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
if (Error E = addFuncWithName(F, getIRPGOFuncName(F, InLTO)))
|
|
|
|
return E;
|
|
|
|
// Also use getPGOFuncName() so that we can find records from older profiles
|
|
|
|
if (Error E = addFuncWithName(F, getPGOFuncName(F, InLTO)))
|
2017-06-20 01:38:56 +00:00
|
|
|
return E;
|
2016-03-30 18:37:52 +00:00
|
|
|
}
|
2024-04-01 08:52:35 -07:00
|
|
|
|
2024-05-09 10:41:23 -07:00
|
|
|
SmallVector<MDNode *, 2> Types;
|
|
|
|
for (GlobalVariable &G : M.globals()) {
|
|
|
|
if (!G.hasName() || !G.hasMetadata(LLVMContext::MD_type))
|
|
|
|
continue;
|
[TypeProf][InstrFDO]Implement more efficient comparison sequence for indirect-call-promotion with vtable profiles. (#81442)
Clang's `-fwhole-program-vtables` is required for this optimization to
take place. If `-fwhole-program-vtables` is not enabled, this change is
no-op.
* Function-comparison (before):
```
%vtable = load ptr, ptr %obj
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
%cond = icmp eq ptr %func, @callee
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
call %func
```
* VTable-comparison (after):
```
%vtable = load ptr, ptr %obj
%cond = icmp eq ptr %vtable, @vtable-address-point
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
call %func
```
Key changes:
1. Find out virtual calls and the vtables they come from.
- The ICP relies on type intrinsic `llvm.type.test` to find out virtual
calls and the
compatible vtables, and relies on type metadata to find the address
point for comparison.
2. ICP pass does cost-benefit analysis and compares vtable only when the
number of vtables for a function candidate is within (option specified)
threshold.
3. Sink the function addressing and vtable load instruction to indirect
fallback.
- The sink helper functions are simplified versions of
`InstCombinerImpl::tryToSinkInstruction`. Currently debug intrinsics are
not handled. Ideally `InstCombinerImpl::tryToSinkInstructionDbgValues`
and `InstCombinerImpl::tryToSinkInstructionDbgVariableRecords` could be
moved into Transforms/Utils/Local.cpp (or another util cpp file) to
handle debug intrinsics when moving instructions across basic blocks.
4. Keep value profiles updated
1) Update vtable value profiles after inline
2) For either function-based comparison or vtable-based comparison,
update both vtable and indirect call value profiles.
2024-06-29 23:21:33 -07:00
|
|
|
if (Error E = addVTableWithName(G, getPGOName(G, InLTO)))
|
2024-05-09 10:41:23 -07:00
|
|
|
return E;
|
|
|
|
}
|
|
|
|
|
2018-03-22 21:26:52 +00:00
|
|
|
Sorted = false;
|
2016-01-20 01:26:34 +00:00
|
|
|
finalizeSymtab();
|
2017-06-20 01:38:56 +00:00
|
|
|
return Error::success();
|
2016-01-20 01:26:34 +00:00
|
|
|
}
|
|
|
|
|
2024-05-09 10:41:23 -07:00
|
|
|
Error InstrProfSymtab::addVTableWithName(GlobalVariable &VTable,
|
|
|
|
StringRef VTablePGOName) {
|
|
|
|
auto mapName = [&](StringRef Name) -> Error {
|
|
|
|
if (Error E = addSymbolName(Name))
|
|
|
|
return E;
|
|
|
|
|
|
|
|
bool Inserted = true;
|
|
|
|
std::tie(std::ignore, Inserted) =
|
|
|
|
MD5VTableMap.try_emplace(GlobalValue::getGUID(Name), &VTable);
|
|
|
|
if (!Inserted)
|
|
|
|
LLVM_DEBUG(dbgs() << "GUID conflict within one module");
|
|
|
|
return Error::success();
|
|
|
|
};
|
|
|
|
if (Error E = mapName(VTablePGOName))
|
|
|
|
return E;
|
|
|
|
|
|
|
|
StringRef CanonicalName = getCanonicalName(VTablePGOName);
|
|
|
|
if (CanonicalName != VTablePGOName)
|
|
|
|
return mapName(CanonicalName);
|
|
|
|
|
|
|
|
return Error::success();
|
|
|
|
}
|
|
|
|
|
2023-11-09 10:47:44 -08:00
|
|
|
/// \c NameStrings is a string composed of one of more possibly encoded
|
|
|
|
/// sub-strings. The substrings are separated by 0 or more zero bytes. This
|
|
|
|
/// method decodes the string and calls `NameCallback` for each substring.
|
|
|
|
static Error
|
|
|
|
readAndDecodeStrings(StringRef NameStrings,
|
|
|
|
std::function<Error(StringRef)> NameCallback) {
|
|
|
|
const uint8_t *P = NameStrings.bytes_begin();
|
|
|
|
const uint8_t *EndP = NameStrings.bytes_end();
|
|
|
|
while (P < EndP) {
|
|
|
|
uint32_t N;
|
|
|
|
uint64_t UncompressedSize = decodeULEB128(P, &N);
|
|
|
|
P += N;
|
|
|
|
uint64_t CompressedSize = decodeULEB128(P, &N);
|
|
|
|
P += N;
|
|
|
|
bool isCompressed = (CompressedSize != 0);
|
|
|
|
SmallVector<uint8_t, 128> UncompressedNameStrings;
|
|
|
|
StringRef NameStrings;
|
|
|
|
if (isCompressed) {
|
|
|
|
if (!llvm::compression::zlib::isAvailable())
|
|
|
|
return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
|
|
|
|
|
|
|
|
if (Error E = compression::zlib::decompress(ArrayRef(P, CompressedSize),
|
|
|
|
UncompressedNameStrings,
|
|
|
|
UncompressedSize)) {
|
|
|
|
consumeError(std::move(E));
|
|
|
|
return make_error<InstrProfError>(instrprof_error::uncompress_failed);
|
|
|
|
}
|
|
|
|
P += CompressedSize;
|
|
|
|
NameStrings = toStringRef(UncompressedNameStrings);
|
|
|
|
} else {
|
|
|
|
NameStrings =
|
|
|
|
StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
|
|
|
|
P += UncompressedSize;
|
|
|
|
}
|
|
|
|
// Now parse the name strings.
|
|
|
|
SmallVector<StringRef, 0> Names;
|
|
|
|
NameStrings.split(Names, getInstrProfNameSeparator());
|
|
|
|
for (StringRef &Name : Names)
|
|
|
|
if (Error E = NameCallback(Name))
|
|
|
|
return E;
|
|
|
|
|
|
|
|
while (P < EndP && *P == 0)
|
|
|
|
P++;
|
|
|
|
}
|
|
|
|
return Error::success();
|
|
|
|
}
|
|
|
|
|
|
|
|
Error InstrProfSymtab::create(StringRef NameStrings) {
|
|
|
|
return readAndDecodeStrings(
|
|
|
|
NameStrings,
|
|
|
|
std::bind(&InstrProfSymtab::addFuncName, this, std::placeholders::_1));
|
|
|
|
}
|
|
|
|
|
2024-04-01 08:52:35 -07:00
|
|
|
Error InstrProfSymtab::create(StringRef FuncNameStrings,
|
|
|
|
StringRef VTableNameStrings) {
|
|
|
|
if (Error E = readAndDecodeStrings(FuncNameStrings,
|
|
|
|
std::bind(&InstrProfSymtab::addFuncName,
|
|
|
|
this, std::placeholders::_1)))
|
|
|
|
return E;
|
|
|
|
|
|
|
|
return readAndDecodeStrings(
|
|
|
|
VTableNameStrings,
|
|
|
|
std::bind(&InstrProfSymtab::addVTableName, this, std::placeholders::_1));
|
|
|
|
}
|
|
|
|
|
|
|
|
Error InstrProfSymtab::initVTableNamesFromCompressedStrings(
|
|
|
|
StringRef CompressedVTableStrings) {
|
|
|
|
return readAndDecodeStrings(
|
|
|
|
CompressedVTableStrings,
|
|
|
|
std::bind(&InstrProfSymtab::addVTableName, this, std::placeholders::_1));
|
|
|
|
}
|
|
|
|
|
2024-02-13 10:49:35 -08:00
|
|
|
StringRef InstrProfSymtab::getCanonicalName(StringRef PGOName) {
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
// In ThinLTO, local function may have been promoted to global and have
|
|
|
|
// suffix ".llvm." added to the function name. We need to add the
|
|
|
|
// stripped function name to the symbol table so that we can find a match
|
|
|
|
// from profile.
|
|
|
|
//
|
2024-02-13 10:49:35 -08:00
|
|
|
// ".__uniq." suffix is used to differentiate internal linkage functions in
|
|
|
|
// different modules and should be kept. This is the only suffix with the
|
|
|
|
// pattern ".xxx" which is kept before matching, other suffixes similar as
|
|
|
|
// ".llvm." will be stripped.
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
const std::string UniqSuffix = ".__uniq.";
|
2024-02-13 10:49:35 -08:00
|
|
|
size_t pos = PGOName.find(UniqSuffix);
|
|
|
|
if (pos != StringRef::npos)
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
pos += UniqSuffix.length();
|
|
|
|
else
|
|
|
|
pos = 0;
|
2024-02-13 10:49:35 -08:00
|
|
|
|
|
|
|
// Search '.' after ".__uniq." if ".__uniq." exists, otherwise search '.' from
|
|
|
|
// the beginning.
|
|
|
|
pos = PGOName.find('.', pos);
|
|
|
|
if (pos != StringRef::npos && pos != 0)
|
|
|
|
return PGOName.substr(0, pos);
|
|
|
|
|
|
|
|
return PGOName;
|
|
|
|
}
|
|
|
|
|
|
|
|
Error InstrProfSymtab::addFuncWithName(Function &F, StringRef PGOFuncName) {
|
|
|
|
auto mapName = [&](StringRef Name) -> Error {
|
|
|
|
if (Error E = addFuncName(Name))
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
return E;
|
2024-02-13 10:49:35 -08:00
|
|
|
MD5FuncMap.emplace_back(Function::getGUID(Name), &F);
|
|
|
|
return Error::success();
|
|
|
|
};
|
|
|
|
if (Error E = mapName(PGOFuncName))
|
|
|
|
return E;
|
|
|
|
|
|
|
|
StringRef CanonicalFuncName = getCanonicalName(PGOFuncName);
|
|
|
|
if (CanonicalFuncName != PGOFuncName)
|
|
|
|
return mapName(CanonicalFuncName);
|
|
|
|
|
[InstrProf] Encode linkage names in IRPGO counter names
Prior to this diff, names in the `__llvm_prf_names` section had the format `[<filepath>:]<function-name>`, e.g., `main.cpp:foo`, `bar`. `<filepath>` is used to discriminate between possibly identical function names when linkage is local and `<function-name>` simply comes from `F.getName()`. This has two problems:
* `:` is commonly found in Objective-C functions so that names like `main.mm:-[C foo::]` and `-[C bar::]` are difficult to parse
* `<function-name>` might be different from the linkage name, so it cannot be used to pass a function order to the linker via `-symbol-ordering-file` or `-order_file` (see https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068)
Instead, this diff changes the format to `[<filepath>;]<linkage-name>`, e.g., `main.cpp;_foo`, `_bar`. The hope is that `;` won't realistically be found in either `<filepath>` or `<linkage-name>`.
To prevent invalidating all prior IRPGO profiles, we also lookup the prior name format when a record is not found (see `InstrProfSymtab::create()`, `readMemprof()`, and `getInstrProfRecord()`). It seems that Swift and Clang FE-PGO rely on the original `getPGOFuncName()`, so we cannot simply replace it.
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D156569
2023-08-04 11:26:14 -07:00
|
|
|
return Error::success();
|
|
|
|
}
|
|
|
|
|
2024-04-01 08:52:35 -07:00
|
|
|
uint64_t InstrProfSymtab::getVTableHashFromAddress(uint64_t Address) {
|
|
|
|
// Given a runtime address, look up the hash value in the interval map, and
|
|
|
|
// fallback to value 0 if a hash value is not found.
|
|
|
|
return VTableAddrMap.lookup(Address, 0);
|
|
|
|
}
|
|
|
|
|
2018-03-21 22:27:31 +00:00
|
|
|
uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) {
|
|
|
|
finalizeSymtab();
|
2019-06-30 11:19:56 +00:00
|
|
|
auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
|
|
|
|
return A.first < Address;
|
|
|
|
});
|
2018-03-21 22:27:31 +00:00
|
|
|
// Raw function pointer collected by value profiler may be from
|
|
|
|
// external functions that are not instrumented. They won't have
|
|
|
|
// mapping data to be used by the deserializer. Force the value to
|
|
|
|
// be 0 in this case.
|
2019-06-30 11:19:56 +00:00
|
|
|
if (It != AddrToMD5Map.end() && It->first == Address)
|
|
|
|
return (uint64_t)It->second;
|
2018-03-21 22:27:31 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2023-07-22 15:47:44 -07:00
|
|
|
void InstrProfSymtab::dumpNames(raw_ostream &OS) const {
|
|
|
|
SmallVector<StringRef, 0> Sorted(NameTab.keys());
|
|
|
|
llvm::sort(Sorted);
|
|
|
|
for (StringRef S : Sorted)
|
|
|
|
OS << S << '\n';
|
|
|
|
}
|
|
|
|
|
2023-10-26 14:48:36 -07:00
|
|
|
Error collectGlobalObjectNameStrings(ArrayRef<std::string> NameStrs,
|
|
|
|
bool doCompression, std::string &Result) {
|
2017-03-03 01:07:34 +00:00
|
|
|
assert(!NameStrs.empty() && "No name data to emit");
|
2016-03-28 21:06:42 +00:00
|
|
|
|
2023-09-26 10:16:01 +09:00
|
|
|
uint8_t Header[20], *P = Header;
|
2016-01-04 21:31:09 +00:00
|
|
|
std::string UncompressedNameStrings =
|
2016-03-28 21:06:42 +00:00
|
|
|
join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
|
|
|
|
|
|
|
|
assert(StringRef(UncompressedNameStrings)
|
|
|
|
.count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
|
|
|
|
"PGO name is invalid (contains separator token)");
|
2016-01-04 20:26:05 +00:00
|
|
|
|
2015-12-31 07:57:16 +00:00
|
|
|
unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
|
|
|
|
P += EncLen;
|
2016-01-04 22:01:02 +00:00
|
|
|
|
2016-05-29 10:31:00 +00:00
|
|
|
auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
|
2016-01-04 22:01:02 +00:00
|
|
|
EncLen = encodeULEB128(CompressedLen, P);
|
2015-12-31 07:57:16 +00:00
|
|
|
P += EncLen;
|
2016-01-04 22:01:02 +00:00
|
|
|
char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
|
|
|
|
unsigned HeaderLen = P - &Header[0];
|
|
|
|
Result.append(HeaderStr, HeaderLen);
|
|
|
|
Result += InputStr;
|
2016-05-19 03:54:45 +00:00
|
|
|
return Error::success();
|
2016-01-04 22:01:02 +00:00
|
|
|
};
|
|
|
|
|
2016-05-19 03:54:45 +00:00
|
|
|
if (!doCompression) {
|
2016-01-04 22:01:02 +00:00
|
|
|
return WriteStringToResult(0, UncompressedNameStrings);
|
2016-05-19 03:54:45 +00:00
|
|
|
}
|
2016-01-04 22:01:02 +00:00
|
|
|
|
2022-07-13 16:26:54 -07:00
|
|
|
SmallVector<uint8_t, 128> CompressedNameStrings;
|
|
|
|
compression::zlib::compress(arrayRefFromStringRef(UncompressedNameStrings),
|
2022-07-08 11:19:05 -07:00
|
|
|
CompressedNameStrings,
|
|
|
|
compression::zlib::BestSizeCompression);
|
2016-01-04 22:01:02 +00:00
|
|
|
|
2016-05-29 10:31:00 +00:00
|
|
|
return WriteStringToResult(CompressedNameStrings.size(),
|
2022-07-13 16:26:54 -07:00
|
|
|
toStringRef(CompressedNameStrings));
|
2015-12-31 07:57:16 +00:00
|
|
|
}
|
|
|
|
|
2016-02-04 23:59:09 +00:00
|
|
|
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
|
2016-01-03 04:38:13 +00:00
|
|
|
auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
|
|
|
|
StringRef NameStr =
|
|
|
|
Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
|
|
|
|
return NameStr;
|
|
|
|
}
|
|
|
|
|
2017-05-28 13:23:02 +00:00
|
|
|
Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
|
2016-05-19 03:54:45 +00:00
|
|
|
std::string &Result, bool doCompression) {
|
2015-12-31 07:57:16 +00:00
|
|
|
std::vector<std::string> NameStrs;
|
|
|
|
for (auto *NameVar : NameVars) {
|
2020-01-28 20:23:46 +01:00
|
|
|
NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar)));
|
2015-12-31 07:57:16 +00:00
|
|
|
}
|
2023-10-26 14:48:36 -07:00
|
|
|
return collectGlobalObjectNameStrings(
|
2022-07-08 11:19:05 -07:00
|
|
|
NameStrs, compression::zlib::isAvailable() && doCompression, Result);
|
2015-12-31 07:57:16 +00:00
|
|
|
}
|
|
|
|
|
2024-04-01 08:52:35 -07:00
|
|
|
Error collectVTableStrings(ArrayRef<GlobalVariable *> VTables,
|
|
|
|
std::string &Result, bool doCompression) {
|
|
|
|
std::vector<std::string> VTableNameStrs;
|
|
|
|
for (auto *VTable : VTables)
|
|
|
|
VTableNameStrs.push_back(getPGOName(*VTable));
|
|
|
|
return collectGlobalObjectNameStrings(
|
|
|
|
VTableNameStrs, compression::zlib::isAvailable() && doCompression,
|
|
|
|
Result);
|
|
|
|
}
|
|
|
|
|
2019-10-01 18:06:50 +00:00
|
|
|
void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const {
|
2019-04-30 21:19:12 +00:00
|
|
|
uint64_t FuncSum = 0;
|
|
|
|
Sum.NumEntries += Counts.size();
|
2021-12-09 09:37:29 -08:00
|
|
|
for (uint64_t Count : Counts)
|
|
|
|
FuncSum += Count;
|
2019-04-30 21:19:12 +00:00
|
|
|
Sum.CountSum += FuncSum;
|
|
|
|
|
|
|
|
for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
|
|
|
|
uint64_t KindSum = 0;
|
|
|
|
uint32_t NumValueSites = getNumValueSites(VK);
|
|
|
|
for (size_t I = 0; I < NumValueSites; ++I) {
|
2024-06-14 06:38:48 -07:00
|
|
|
for (const auto &V : getValueArrayForSite(VK, I))
|
|
|
|
KindSum += V.Count;
|
2019-04-30 21:19:12 +00:00
|
|
|
}
|
|
|
|
Sum.ValueCounts[VK] += KindSum;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
|
|
|
|
uint32_t ValueKind,
|
|
|
|
OverlapStats &Overlap,
|
|
|
|
OverlapStats &FuncLevelOverlap) {
|
|
|
|
this->sortByTargetValues();
|
|
|
|
Input.sortByTargetValues();
|
|
|
|
double Score = 0.0f, FuncLevelScore = 0.0f;
|
|
|
|
auto I = ValueData.begin();
|
|
|
|
auto IE = ValueData.end();
|
|
|
|
auto J = Input.ValueData.begin();
|
|
|
|
auto JE = Input.ValueData.end();
|
|
|
|
while (I != IE && J != JE) {
|
|
|
|
if (I->Value == J->Value) {
|
|
|
|
Score += OverlapStats::score(I->Count, J->Count,
|
|
|
|
Overlap.Base.ValueCounts[ValueKind],
|
|
|
|
Overlap.Test.ValueCounts[ValueKind]);
|
|
|
|
FuncLevelScore += OverlapStats::score(
|
|
|
|
I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
|
|
|
|
FuncLevelOverlap.Test.ValueCounts[ValueKind]);
|
|
|
|
++I;
|
|
|
|
} else if (I->Value < J->Value) {
|
|
|
|
++I;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
++J;
|
|
|
|
}
|
|
|
|
Overlap.Overlap.ValueCounts[ValueKind] += Score;
|
|
|
|
FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return false on mismatch.
|
|
|
|
void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
|
|
|
|
InstrProfRecord &Other,
|
|
|
|
OverlapStats &Overlap,
|
|
|
|
OverlapStats &FuncLevelOverlap) {
|
|
|
|
uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
|
2019-04-30 21:44:21 +00:00
|
|
|
assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
|
2019-04-30 21:19:12 +00:00
|
|
|
if (!ThisNumValueSites)
|
|
|
|
return;
|
|
|
|
|
|
|
|
std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
|
|
|
|
getOrCreateValueSitesForKind(ValueKind);
|
|
|
|
MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
|
|
|
|
Other.getValueSitesForKind(ValueKind);
|
|
|
|
for (uint32_t I = 0; I < ThisNumValueSites; I++)
|
|
|
|
ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
|
|
|
|
FuncLevelOverlap);
|
|
|
|
}
|
|
|
|
|
|
|
|
void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
|
|
|
|
OverlapStats &FuncLevelOverlap,
|
|
|
|
uint64_t ValueCutoff) {
|
|
|
|
// FuncLevel CountSum for other should already computed and nonzero.
|
|
|
|
assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
|
2019-10-01 18:06:50 +00:00
|
|
|
accumulateCounts(FuncLevelOverlap.Base);
|
2019-04-30 21:19:12 +00:00
|
|
|
bool Mismatch = (Counts.size() != Other.Counts.size());
|
|
|
|
|
|
|
|
// Check if the value profiles mismatch.
|
|
|
|
if (!Mismatch) {
|
|
|
|
for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
|
|
|
|
uint32_t ThisNumValueSites = getNumValueSites(Kind);
|
|
|
|
uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
|
|
|
|
if (ThisNumValueSites != OtherNumValueSites) {
|
|
|
|
Mismatch = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (Mismatch) {
|
|
|
|
Overlap.addOneMismatch(FuncLevelOverlap.Test);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Compute overlap for value counts.
|
|
|
|
for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
|
|
|
|
overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
|
|
|
|
|
|
|
|
double Score = 0.0;
|
|
|
|
uint64_t MaxCount = 0;
|
|
|
|
// Compute overlap for edge counts.
|
|
|
|
for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
|
|
|
|
Score += OverlapStats::score(Counts[I], Other.Counts[I],
|
|
|
|
Overlap.Base.CountSum, Overlap.Test.CountSum);
|
|
|
|
MaxCount = std::max(Other.Counts[I], MaxCount);
|
|
|
|
}
|
|
|
|
Overlap.Overlap.CountSum += Score;
|
|
|
|
Overlap.Overlap.NumEntries += 1;
|
|
|
|
|
|
|
|
if (MaxCount >= ValueCutoff) {
|
|
|
|
double FuncScore = 0.0;
|
|
|
|
for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
|
|
|
|
FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
|
|
|
|
FuncLevelOverlap.Base.CountSum,
|
|
|
|
FuncLevelOverlap.Test.CountSum);
|
|
|
|
FuncLevelOverlap.Overlap.CountSum = FuncScore;
|
|
|
|
FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
|
|
|
|
FuncLevelOverlap.Valid = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-07-10 03:04:59 +00:00
|
|
|
void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
|
|
|
|
uint64_t Weight,
|
|
|
|
function_ref<void(instrprof_error)> Warn) {
|
2015-12-20 05:15:45 +00:00
|
|
|
this->sortByTargetValues();
|
|
|
|
Input.sortByTargetValues();
|
|
|
|
auto I = ValueData.begin();
|
|
|
|
auto IE = ValueData.end();
|
2024-06-12 11:22:49 -07:00
|
|
|
std::vector<InstrProfValueData> Merged;
|
|
|
|
Merged.reserve(std::max(ValueData.size(), Input.ValueData.size()));
|
2021-11-29 09:04:44 -08:00
|
|
|
for (const InstrProfValueData &J : Input.ValueData) {
|
2024-06-12 11:22:49 -07:00
|
|
|
while (I != IE && I->Value < J.Value) {
|
|
|
|
Merged.push_back(*I);
|
2015-12-20 05:15:45 +00:00
|
|
|
++I;
|
2024-06-12 11:22:49 -07:00
|
|
|
}
|
2021-11-29 09:04:44 -08:00
|
|
|
if (I != IE && I->Value == J.Value) {
|
2015-12-20 05:15:45 +00:00
|
|
|
bool Overflowed;
|
2021-11-29 09:04:44 -08:00
|
|
|
I->Count = SaturatingMultiplyAdd(J.Count, Weight, I->Count, &Overflowed);
|
2015-12-20 05:15:45 +00:00
|
|
|
if (Overflowed)
|
2017-07-10 03:04:59 +00:00
|
|
|
Warn(instrprof_error::counter_overflow);
|
2024-06-12 11:22:49 -07:00
|
|
|
Merged.push_back(*I);
|
2015-12-20 05:15:45 +00:00
|
|
|
++I;
|
|
|
|
continue;
|
|
|
|
}
|
2024-06-12 11:22:49 -07:00
|
|
|
Merged.push_back(J);
|
2015-12-20 05:15:45 +00:00
|
|
|
}
|
2024-06-12 11:22:49 -07:00
|
|
|
Merged.insert(Merged.end(), I, IE);
|
|
|
|
ValueData = std::move(Merged);
|
2015-12-20 05:15:45 +00:00
|
|
|
}
|
|
|
|
|
Supplement instr profile with sample profile.
PGO profile is usually more precise than sample profile. However, PGO profile
needs to be collected from loadtest and loadtest may not be representative
enough to the production workload. Sample profile collected from production
can be used as a supplement -- for functions cold in loadtest but warm/hot
in production, we can scale up the related function in PGO profile if the
function is warm or hot in sample profile.
The implementation contains changes in compiler side and llvm-profdata side.
Given an instr profile and a sample profile, for a function cold in PGO
profile but warm/hot in sample profile, llvm-profdata will either mark
all the counters in the profile to be -1 or scale up the max count in the
function to be above hot threshold, depending on the zero counter ratio in
the profile. The assumption is if there are too many counters being zero
in the function profile, the profile is more likely to cause harm than good,
then llvm-profdata will mark all the counters to be -1 indicating the
function is hot but the profile is unaccountable. In compiler side, if a
function profile with all -1 counters is seen, the function entry count will
be set to be above hot threshold but its internal profile will be dropped.
In the long run, it may be useful to let compiler support using PGO profile
and sample profile at the same time, but that requires more careful design
and more substantial changes to make two profiles work seamlessly. The patch
here serves as a simple intermediate solution.
Differential Revision: https://reviews.llvm.org/D81981
2020-07-08 15:19:44 -07:00
|
|
|
void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D,
|
2017-07-10 03:04:59 +00:00
|
|
|
function_ref<void(instrprof_error)> Warn) {
|
2021-12-09 09:37:29 -08:00
|
|
|
for (InstrProfValueData &I : ValueData) {
|
2016-01-08 03:49:59 +00:00
|
|
|
bool Overflowed;
|
2021-12-09 09:37:29 -08:00
|
|
|
I.Count = SaturatingMultiply(I.Count, N, &Overflowed) / D;
|
2016-01-08 03:49:59 +00:00
|
|
|
if (Overflowed)
|
2017-07-10 03:04:59 +00:00
|
|
|
Warn(instrprof_error::counter_overflow);
|
2016-01-08 03:49:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-18 23:06:37 +00:00
|
|
|
// Merge Value Profile data from Src record to this record for ValueKind.
|
|
|
|
// Scale merged value counts by \p Weight.
|
2017-07-10 03:04:59 +00:00
|
|
|
void InstrProfRecord::mergeValueProfData(
|
|
|
|
uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
|
|
|
|
function_ref<void(instrprof_error)> Warn) {
|
2015-12-18 23:06:37 +00:00
|
|
|
uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
|
|
|
|
uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
|
2016-05-11 19:42:19 +00:00
|
|
|
if (ThisNumValueSites != OtherNumValueSites) {
|
2017-07-10 03:04:59 +00:00
|
|
|
Warn(instrprof_error::value_site_count_mismatch);
|
2016-05-11 19:42:19 +00:00
|
|
|
return;
|
|
|
|
}
|
llvm-profdata: Indirect infrequently used fields to reduce memory usage
Examining a large profile example, it seems relatively few records have
non-empty IndirectCall and MemOP data, so indirecting these through a
unique_ptr (non-null only when they are non-empty) Reduces memory usage
on this particular example from 14GB to 10GB according to valgrind's
massif.
I suspect it'd still be worth moving InstrProfWriter to its own data
structure that had Counts and the indirected IndirectCall+MemOP, and did
not include the Name, Hash, or Error fields. This would reduce the size
of this dominant data structure by half of this new, lower amount.
(Name(2), Hash(1), Error(1) ~= Counts(vector, 3), ValueProfData
(unique_ptr, 1))
-> From code review feedback, might actually refactor InstrProfRecord
itself to have a sub-struct with all the counts, and use that from
InstrProfWriter, rather than InstrProfWriter owning its own data
structure for this.
Reviewers: davidxl
Differential Revision: https://reviews.llvm.org/D34694
llvm-svn: 306631
2017-06-29 02:51:58 +00:00
|
|
|
if (!ThisNumValueSites)
|
|
|
|
return;
|
2015-12-18 23:06:37 +00:00
|
|
|
std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
|
llvm-profdata: Indirect infrequently used fields to reduce memory usage
Examining a large profile example, it seems relatively few records have
non-empty IndirectCall and MemOP data, so indirecting these through a
unique_ptr (non-null only when they are non-empty) Reduces memory usage
on this particular example from 14GB to 10GB according to valgrind's
massif.
I suspect it'd still be worth moving InstrProfWriter to its own data
structure that had Counts and the indirected IndirectCall+MemOP, and did
not include the Name, Hash, or Error fields. This would reduce the size
of this dominant data structure by half of this new, lower amount.
(Name(2), Hash(1), Error(1) ~= Counts(vector, 3), ValueProfData
(unique_ptr, 1))
-> From code review feedback, might actually refactor InstrProfRecord
itself to have a sub-struct with all the counts, and use that from
InstrProfWriter, rather than InstrProfWriter owning its own data
structure for this.
Reviewers: davidxl
Differential Revision: https://reviews.llvm.org/D34694
llvm-svn: 306631
2017-06-29 02:51:58 +00:00
|
|
|
getOrCreateValueSitesForKind(ValueKind);
|
|
|
|
MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
|
2015-12-18 23:06:37 +00:00
|
|
|
Src.getValueSitesForKind(ValueKind);
|
|
|
|
for (uint32_t I = 0; I < ThisNumValueSites; I++)
|
2017-07-10 03:04:59 +00:00
|
|
|
ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
|
2015-12-18 23:06:37 +00:00
|
|
|
}
|
|
|
|
|
2017-07-10 03:04:59 +00:00
|
|
|
void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
|
|
|
|
function_ref<void(instrprof_error)> Warn) {
|
2015-12-18 23:06:37 +00:00
|
|
|
// If the number of counters doesn't match we either have bad data
|
|
|
|
// or a hash collision.
|
2016-05-11 19:42:19 +00:00
|
|
|
if (Counts.size() != Other.Counts.size()) {
|
2017-07-10 03:04:59 +00:00
|
|
|
Warn(instrprof_error::count_mismatch);
|
2016-05-11 19:42:19 +00:00
|
|
|
return;
|
|
|
|
}
|
2015-12-18 23:06:37 +00:00
|
|
|
|
2022-08-24 11:54:06 -07:00
|
|
|
// Special handling of the first count as the PseudoCount.
|
|
|
|
CountPseudoKind OtherKind = Other.getCountPseudoKind();
|
|
|
|
CountPseudoKind ThisKind = getCountPseudoKind();
|
|
|
|
if (OtherKind != NotPseudo || ThisKind != NotPseudo) {
|
|
|
|
// We don't allow the merge of a profile with pseudo counts and
|
|
|
|
// a normal profile (i.e. without pesudo counts).
|
|
|
|
// Profile supplimenation should be done after the profile merge.
|
|
|
|
if (OtherKind == NotPseudo || ThisKind == NotPseudo) {
|
|
|
|
Warn(instrprof_error::count_mismatch);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (OtherKind == PseudoHot || ThisKind == PseudoHot)
|
|
|
|
setPseudoCount(PseudoHot);
|
|
|
|
else
|
|
|
|
setPseudoCount(PseudoWarm);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2015-12-18 23:06:37 +00:00
|
|
|
for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
|
|
|
|
bool Overflowed;
|
2022-08-24 11:54:06 -07:00
|
|
|
uint64_t Value =
|
2016-01-12 22:34:00 +00:00
|
|
|
SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
|
2022-08-24 11:54:06 -07:00
|
|
|
if (Value > getInstrMaxCountValue()) {
|
|
|
|
Value = getInstrMaxCountValue();
|
|
|
|
Overflowed = true;
|
|
|
|
}
|
|
|
|
Counts[I] = Value;
|
2015-12-18 23:06:37 +00:00
|
|
|
if (Overflowed)
|
2017-07-10 03:04:59 +00:00
|
|
|
Warn(instrprof_error::counter_overflow);
|
2015-12-18 23:06:37 +00:00
|
|
|
}
|
|
|
|
|
2023-09-21 13:07:31 -05:00
|
|
|
// If the number of bitmap bytes doesn't match we either have bad data
|
|
|
|
// or a hash collision.
|
|
|
|
if (BitmapBytes.size() != Other.BitmapBytes.size()) {
|
|
|
|
Warn(instrprof_error::bitmap_mismatch);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bitmap bytes are merged by simply ORing them together.
|
|
|
|
for (size_t I = 0, E = Other.BitmapBytes.size(); I < E; ++I) {
|
|
|
|
BitmapBytes[I] = Other.BitmapBytes[I] | BitmapBytes[I];
|
|
|
|
}
|
|
|
|
|
2015-12-18 23:06:37 +00:00
|
|
|
for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
|
2017-07-10 03:04:59 +00:00
|
|
|
mergeValueProfData(Kind, Other, Weight, Warn);
|
2015-12-18 23:06:37 +00:00
|
|
|
}
|
2015-12-20 06:22:13 +00:00
|
|
|
|
2017-07-10 03:04:59 +00:00
|
|
|
void InstrProfRecord::scaleValueProfData(
|
Supplement instr profile with sample profile.
PGO profile is usually more precise than sample profile. However, PGO profile
needs to be collected from loadtest and loadtest may not be representative
enough to the production workload. Sample profile collected from production
can be used as a supplement -- for functions cold in loadtest but warm/hot
in production, we can scale up the related function in PGO profile if the
function is warm or hot in sample profile.
The implementation contains changes in compiler side and llvm-profdata side.
Given an instr profile and a sample profile, for a function cold in PGO
profile but warm/hot in sample profile, llvm-profdata will either mark
all the counters in the profile to be -1 or scale up the max count in the
function to be above hot threshold, depending on the zero counter ratio in
the profile. The assumption is if there are too many counters being zero
in the function profile, the profile is more likely to cause harm than good,
then llvm-profdata will mark all the counters to be -1 indicating the
function is hot but the profile is unaccountable. In compiler side, if a
function profile with all -1 counters is seen, the function entry count will
be set to be above hot threshold but its internal profile will be dropped.
In the long run, it may be useful to let compiler support using PGO profile
and sample profile at the same time, but that requires more careful design
and more substantial changes to make two profiles work seamlessly. The patch
here serves as a simple intermediate solution.
Differential Revision: https://reviews.llvm.org/D81981
2020-07-08 15:19:44 -07:00
|
|
|
uint32_t ValueKind, uint64_t N, uint64_t D,
|
2017-07-10 03:04:59 +00:00
|
|
|
function_ref<void(instrprof_error)> Warn) {
|
llvm-profdata: Indirect infrequently used fields to reduce memory usage
Examining a large profile example, it seems relatively few records have
non-empty IndirectCall and MemOP data, so indirecting these through a
unique_ptr (non-null only when they are non-empty) Reduces memory usage
on this particular example from 14GB to 10GB according to valgrind's
massif.
I suspect it'd still be worth moving InstrProfWriter to its own data
structure that had Counts and the indirected IndirectCall+MemOP, and did
not include the Name, Hash, or Error fields. This would reduce the size
of this dominant data structure by half of this new, lower amount.
(Name(2), Hash(1), Error(1) ~= Counts(vector, 3), ValueProfData
(unique_ptr, 1))
-> From code review feedback, might actually refactor InstrProfRecord
itself to have a sub-struct with all the counts, and use that from
InstrProfWriter, rather than InstrProfWriter owning its own data
structure for this.
Reviewers: davidxl
Differential Revision: https://reviews.llvm.org/D34694
llvm-svn: 306631
2017-06-29 02:51:58 +00:00
|
|
|
for (auto &R : getValueSitesForKind(ValueKind))
|
Supplement instr profile with sample profile.
PGO profile is usually more precise than sample profile. However, PGO profile
needs to be collected from loadtest and loadtest may not be representative
enough to the production workload. Sample profile collected from production
can be used as a supplement -- for functions cold in loadtest but warm/hot
in production, we can scale up the related function in PGO profile if the
function is warm or hot in sample profile.
The implementation contains changes in compiler side and llvm-profdata side.
Given an instr profile and a sample profile, for a function cold in PGO
profile but warm/hot in sample profile, llvm-profdata will either mark
all the counters in the profile to be -1 or scale up the max count in the
function to be above hot threshold, depending on the zero counter ratio in
the profile. The assumption is if there are too many counters being zero
in the function profile, the profile is more likely to cause harm than good,
then llvm-profdata will mark all the counters to be -1 indicating the
function is hot but the profile is unaccountable. In compiler side, if a
function profile with all -1 counters is seen, the function entry count will
be set to be above hot threshold but its internal profile will be dropped.
In the long run, it may be useful to let compiler support using PGO profile
and sample profile at the same time, but that requires more careful design
and more substantial changes to make two profiles work seamlessly. The patch
here serves as a simple intermediate solution.
Differential Revision: https://reviews.llvm.org/D81981
2020-07-08 15:19:44 -07:00
|
|
|
R.scale(N, D, Warn);
|
2016-01-08 03:49:59 +00:00
|
|
|
}
|
|
|
|
|
Supplement instr profile with sample profile.
PGO profile is usually more precise than sample profile. However, PGO profile
needs to be collected from loadtest and loadtest may not be representative
enough to the production workload. Sample profile collected from production
can be used as a supplement -- for functions cold in loadtest but warm/hot
in production, we can scale up the related function in PGO profile if the
function is warm or hot in sample profile.
The implementation contains changes in compiler side and llvm-profdata side.
Given an instr profile and a sample profile, for a function cold in PGO
profile but warm/hot in sample profile, llvm-profdata will either mark
all the counters in the profile to be -1 or scale up the max count in the
function to be above hot threshold, depending on the zero counter ratio in
the profile. The assumption is if there are too many counters being zero
in the function profile, the profile is more likely to cause harm than good,
then llvm-profdata will mark all the counters to be -1 indicating the
function is hot but the profile is unaccountable. In compiler side, if a
function profile with all -1 counters is seen, the function entry count will
be set to be above hot threshold but its internal profile will be dropped.
In the long run, it may be useful to let compiler support using PGO profile
and sample profile at the same time, but that requires more careful design
and more substantial changes to make two profiles work seamlessly. The patch
here serves as a simple intermediate solution.
Differential Revision: https://reviews.llvm.org/D81981
2020-07-08 15:19:44 -07:00
|
|
|
void InstrProfRecord::scale(uint64_t N, uint64_t D,
|
2017-07-10 03:04:59 +00:00
|
|
|
function_ref<void(instrprof_error)> Warn) {
|
Supplement instr profile with sample profile.
PGO profile is usually more precise than sample profile. However, PGO profile
needs to be collected from loadtest and loadtest may not be representative
enough to the production workload. Sample profile collected from production
can be used as a supplement -- for functions cold in loadtest but warm/hot
in production, we can scale up the related function in PGO profile if the
function is warm or hot in sample profile.
The implementation contains changes in compiler side and llvm-profdata side.
Given an instr profile and a sample profile, for a function cold in PGO
profile but warm/hot in sample profile, llvm-profdata will either mark
all the counters in the profile to be -1 or scale up the max count in the
function to be above hot threshold, depending on the zero counter ratio in
the profile. The assumption is if there are too many counters being zero
in the function profile, the profile is more likely to cause harm than good,
then llvm-profdata will mark all the counters to be -1 indicating the
function is hot but the profile is unaccountable. In compiler side, if a
function profile with all -1 counters is seen, the function entry count will
be set to be above hot threshold but its internal profile will be dropped.
In the long run, it may be useful to let compiler support using PGO profile
and sample profile at the same time, but that requires more careful design
and more substantial changes to make two profiles work seamlessly. The patch
here serves as a simple intermediate solution.
Differential Revision: https://reviews.llvm.org/D81981
2020-07-08 15:19:44 -07:00
|
|
|
assert(D != 0 && "D cannot be 0");
|
2016-01-08 03:49:59 +00:00
|
|
|
for (auto &Count : this->Counts) {
|
|
|
|
bool Overflowed;
|
Supplement instr profile with sample profile.
PGO profile is usually more precise than sample profile. However, PGO profile
needs to be collected from loadtest and loadtest may not be representative
enough to the production workload. Sample profile collected from production
can be used as a supplement -- for functions cold in loadtest but warm/hot
in production, we can scale up the related function in PGO profile if the
function is warm or hot in sample profile.
The implementation contains changes in compiler side and llvm-profdata side.
Given an instr profile and a sample profile, for a function cold in PGO
profile but warm/hot in sample profile, llvm-profdata will either mark
all the counters in the profile to be -1 or scale up the max count in the
function to be above hot threshold, depending on the zero counter ratio in
the profile. The assumption is if there are too many counters being zero
in the function profile, the profile is more likely to cause harm than good,
then llvm-profdata will mark all the counters to be -1 indicating the
function is hot but the profile is unaccountable. In compiler side, if a
function profile with all -1 counters is seen, the function entry count will
be set to be above hot threshold but its internal profile will be dropped.
In the long run, it may be useful to let compiler support using PGO profile
and sample profile at the same time, but that requires more careful design
and more substantial changes to make two profiles work seamlessly. The patch
here serves as a simple intermediate solution.
Differential Revision: https://reviews.llvm.org/D81981
2020-07-08 15:19:44 -07:00
|
|
|
Count = SaturatingMultiply(Count, N, &Overflowed) / D;
|
2022-08-24 11:54:06 -07:00
|
|
|
if (Count > getInstrMaxCountValue()) {
|
|
|
|
Count = getInstrMaxCountValue();
|
|
|
|
Overflowed = true;
|
|
|
|
}
|
2016-05-11 19:42:19 +00:00
|
|
|
if (Overflowed)
|
2017-07-10 03:04:59 +00:00
|
|
|
Warn(instrprof_error::counter_overflow);
|
2016-01-08 03:49:59 +00:00
|
|
|
}
|
|
|
|
for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
|
Supplement instr profile with sample profile.
PGO profile is usually more precise than sample profile. However, PGO profile
needs to be collected from loadtest and loadtest may not be representative
enough to the production workload. Sample profile collected from production
can be used as a supplement -- for functions cold in loadtest but warm/hot
in production, we can scale up the related function in PGO profile if the
function is warm or hot in sample profile.
The implementation contains changes in compiler side and llvm-profdata side.
Given an instr profile and a sample profile, for a function cold in PGO
profile but warm/hot in sample profile, llvm-profdata will either mark
all the counters in the profile to be -1 or scale up the max count in the
function to be above hot threshold, depending on the zero counter ratio in
the profile. The assumption is if there are too many counters being zero
in the function profile, the profile is more likely to cause harm than good,
then llvm-profdata will mark all the counters to be -1 indicating the
function is hot but the profile is unaccountable. In compiler side, if a
function profile with all -1 counters is seen, the function entry count will
be set to be above hot threshold but its internal profile will be dropped.
In the long run, it may be useful to let compiler support using PGO profile
and sample profile at the same time, but that requires more careful design
and more substantial changes to make two profiles work seamlessly. The patch
here serves as a simple intermediate solution.
Differential Revision: https://reviews.llvm.org/D81981
2020-07-08 15:19:44 -07:00
|
|
|
scaleValueProfData(Kind, N, D, Warn);
|
2016-01-08 03:49:59 +00:00
|
|
|
}
|
|
|
|
|
2015-12-18 23:06:37 +00:00
|
|
|
// Map indirect call target name hash to name string.
|
|
|
|
uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
|
2018-03-21 22:27:31 +00:00
|
|
|
InstrProfSymtab *SymTab) {
|
|
|
|
if (!SymTab)
|
2015-12-18 23:06:37 +00:00
|
|
|
return Value;
|
2018-03-21 22:27:31 +00:00
|
|
|
|
|
|
|
if (ValueKind == IPVK_IndirectCallTarget)
|
|
|
|
return SymTab->getFunctionHashFromAddress(Value);
|
|
|
|
|
2024-04-01 08:52:35 -07:00
|
|
|
if (ValueKind == IPVK_VTableTarget)
|
|
|
|
return SymTab->getVTableHashFromAddress(Value);
|
|
|
|
|
2015-12-18 23:06:37 +00:00
|
|
|
return Value;
|
|
|
|
}
|
|
|
|
|
|
|
|
void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
|
|
|
|
InstrProfValueData *VData, uint32_t N,
|
2018-03-21 22:27:31 +00:00
|
|
|
InstrProfSymtab *ValueMap) {
|
2015-12-18 23:06:37 +00:00
|
|
|
for (uint32_t I = 0; I < N; I++) {
|
2015-12-20 06:22:13 +00:00
|
|
|
VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
|
2015-12-18 23:06:37 +00:00
|
|
|
}
|
|
|
|
std::vector<InstrProfValueSiteRecord> &ValueSites =
|
llvm-profdata: Indirect infrequently used fields to reduce memory usage
Examining a large profile example, it seems relatively few records have
non-empty IndirectCall and MemOP data, so indirecting these through a
unique_ptr (non-null only when they are non-empty) Reduces memory usage
on this particular example from 14GB to 10GB according to valgrind's
massif.
I suspect it'd still be worth moving InstrProfWriter to its own data
structure that had Counts and the indirected IndirectCall+MemOP, and did
not include the Name, Hash, or Error fields. This would reduce the size
of this dominant data structure by half of this new, lower amount.
(Name(2), Hash(1), Error(1) ~= Counts(vector, 3), ValueProfData
(unique_ptr, 1))
-> From code review feedback, might actually refactor InstrProfRecord
itself to have a sub-struct with all the counts, and use that from
InstrProfWriter, rather than InstrProfWriter owning its own data
structure for this.
Reviewers: davidxl
Differential Revision: https://reviews.llvm.org/D34694
llvm-svn: 306631
2017-06-29 02:51:58 +00:00
|
|
|
getOrCreateValueSitesForKind(ValueKind);
|
2024-06-20 22:25:19 -07:00
|
|
|
assert(ValueSites.size() == Site);
|
2015-12-18 23:06:37 +00:00
|
|
|
if (N == 0)
|
2016-05-11 16:03:02 +00:00
|
|
|
ValueSites.emplace_back();
|
2015-12-18 23:06:37 +00:00
|
|
|
else
|
|
|
|
ValueSites.emplace_back(VData, VData + N);
|
|
|
|
}
|
|
|
|
|
2024-05-23 11:19:29 -07:00
|
|
|
void TemporalProfTraceTy::createBPFunctionNodes(
|
|
|
|
ArrayRef<TemporalProfTraceTy> Traces, std::vector<BPFunctionNode> &Nodes,
|
|
|
|
bool RemoveOutlierUNs) {
|
2023-06-06 11:43:36 -07:00
|
|
|
using IDT = BPFunctionNode::IDT;
|
|
|
|
using UtilityNodeT = BPFunctionNode::UtilityNodeT;
|
2024-05-23 11:19:29 -07:00
|
|
|
UtilityNodeT MaxUN = 0;
|
|
|
|
DenseMap<IDT, size_t> IdToFirstTimestamp;
|
|
|
|
DenseMap<IDT, UtilityNodeT> IdToFirstUN;
|
|
|
|
DenseMap<IDT, SmallVector<UtilityNodeT>> IdToUNs;
|
2024-01-19 15:01:43 -08:00
|
|
|
// TODO: We need to use the Trace.Weight field to give more weight to more
|
2023-06-06 11:43:36 -07:00
|
|
|
// important utilities
|
2024-05-23 11:19:29 -07:00
|
|
|
for (auto &Trace : Traces) {
|
|
|
|
size_t CutoffTimestamp = 1;
|
|
|
|
for (size_t Timestamp = 0; Timestamp < Trace.FunctionNameRefs.size();
|
|
|
|
Timestamp++) {
|
|
|
|
IDT Id = Trace.FunctionNameRefs[Timestamp];
|
|
|
|
auto [It, WasInserted] = IdToFirstTimestamp.try_emplace(Id, Timestamp);
|
|
|
|
if (!WasInserted)
|
|
|
|
It->getSecond() = std::min<size_t>(It->getSecond(), Timestamp);
|
|
|
|
if (Timestamp >= CutoffTimestamp) {
|
|
|
|
++MaxUN;
|
|
|
|
CutoffTimestamp = 2 * Timestamp;
|
2023-06-06 11:43:36 -07:00
|
|
|
}
|
2024-05-23 11:19:29 -07:00
|
|
|
IdToFirstUN.try_emplace(Id, MaxUN);
|
2023-06-06 11:43:36 -07:00
|
|
|
}
|
2024-05-23 11:19:29 -07:00
|
|
|
for (auto &[Id, FirstUN] : IdToFirstUN)
|
|
|
|
for (auto UN = FirstUN; UN <= MaxUN; ++UN)
|
|
|
|
IdToUNs[Id].push_back(UN);
|
|
|
|
++MaxUN;
|
|
|
|
IdToFirstUN.clear();
|
2023-06-06 11:43:36 -07:00
|
|
|
}
|
|
|
|
|
2024-05-23 11:19:29 -07:00
|
|
|
if (RemoveOutlierUNs) {
|
|
|
|
DenseMap<UtilityNodeT, unsigned> UNFrequency;
|
|
|
|
for (auto &[Id, UNs] : IdToUNs)
|
|
|
|
for (auto &UN : UNs)
|
|
|
|
++UNFrequency[UN];
|
|
|
|
// Filter out utility nodes that are too infrequent or too prevalent to make
|
|
|
|
// BalancedPartitioning more effective.
|
|
|
|
for (auto &[Id, UNs] : IdToUNs)
|
|
|
|
llvm::erase_if(UNs, [&](auto &UN) {
|
|
|
|
return UNFrequency[UN] <= 1 || 2 * UNFrequency[UN] > IdToUNs.size();
|
|
|
|
});
|
2023-06-06 11:43:36 -07:00
|
|
|
}
|
2024-05-23 11:19:29 -07:00
|
|
|
|
|
|
|
for (auto &[Id, UNs] : IdToUNs)
|
|
|
|
Nodes.emplace_back(Id, UNs);
|
|
|
|
|
|
|
|
// Since BalancedPartitioning is sensitive to the initial order, we explicitly
|
|
|
|
// order nodes by their earliest timestamp.
|
|
|
|
llvm::sort(Nodes, [&](auto &L, auto &R) {
|
|
|
|
return std::make_pair(IdToFirstTimestamp[L.Id], L.Id) <
|
|
|
|
std::make_pair(IdToFirstTimestamp[R.Id], R.Id);
|
|
|
|
});
|
2023-06-06 11:43:36 -07:00
|
|
|
}
|
|
|
|
|
2015-11-28 19:07:09 +00:00
|
|
|
#define INSTR_PROF_COMMON_API_IMPL
|
|
|
|
#include "llvm/ProfileData/InstrProfData.inc"
|
2015-11-10 00:24:45 +00:00
|
|
|
|
2015-12-18 23:06:37 +00:00
|
|
|
/*!
|
2018-05-01 15:54:18 +00:00
|
|
|
* ValueProfRecordClosure Interface implementation for InstrProfRecord
|
2015-11-25 23:31:18 +00:00
|
|
|
* class. These C wrappers are used as adaptors so that C++ code can be
|
|
|
|
* invoked as callbacks.
|
|
|
|
*/
|
2015-11-25 06:23:38 +00:00
|
|
|
uint32_t getNumValueKindsInstrProf(const void *Record) {
|
|
|
|
return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
|
|
|
|
}
|
|
|
|
|
|
|
|
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
|
|
|
|
return reinterpret_cast<const InstrProfRecord *>(Record)
|
|
|
|
->getNumValueSites(VKind);
|
|
|
|
}
|
|
|
|
|
|
|
|
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
|
|
|
|
return reinterpret_cast<const InstrProfRecord *>(Record)
|
|
|
|
->getNumValueData(VKind);
|
|
|
|
}
|
|
|
|
|
|
|
|
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
|
|
|
|
uint32_t S) {
|
2024-06-14 06:38:48 -07:00
|
|
|
const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
|
|
|
|
return IPR->getValueArrayForSite(VK, S).size();
|
2015-11-25 06:23:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
|
2016-02-04 05:29:51 +00:00
|
|
|
uint32_t K, uint32_t S) {
|
2024-06-14 06:38:48 -07:00
|
|
|
const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
|
|
|
|
llvm::copy(IPR->getValueArrayForSite(K, S), Dst);
|
2015-11-25 19:13:00 +00:00
|
|
|
}
|
|
|
|
|
2015-11-25 06:23:38 +00:00
|
|
|
ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
|
2015-12-15 21:57:08 +00:00
|
|
|
ValueProfData *VD =
|
|
|
|
(ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
|
|
|
|
memset(VD, 0, TotalSizeInBytes);
|
|
|
|
return VD;
|
2015-11-25 06:23:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
static ValueProfRecordClosure InstrProfRecordClosure = {
|
2016-01-26 18:48:36 +00:00
|
|
|
nullptr,
|
2015-11-25 06:23:38 +00:00
|
|
|
getNumValueKindsInstrProf,
|
|
|
|
getNumValueSitesInstrProf,
|
|
|
|
getNumValueDataInstrProf,
|
|
|
|
getNumValueDataForSiteInstrProf,
|
2016-01-26 18:48:36 +00:00
|
|
|
nullptr,
|
2015-11-25 06:23:38 +00:00
|
|
|
getValueForSiteInstrProf,
|
2015-12-15 21:57:08 +00:00
|
|
|
allocValueProfDataInstrProf};
|
2015-11-25 06:23:38 +00:00
|
|
|
|
2015-11-25 19:13:00 +00:00
|
|
|
// Wrapper implementation using the closure mechanism.
|
2015-11-25 06:23:38 +00:00
|
|
|
uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
|
2017-06-27 17:21:51 +00:00
|
|
|
auto Closure = InstrProfRecordClosure;
|
|
|
|
Closure.Record = &Record;
|
|
|
|
return getValueProfDataSize(&Closure);
|
2015-11-25 06:23:38 +00:00
|
|
|
}
|
|
|
|
|
2015-11-25 19:13:00 +00:00
|
|
|
// Wrapper implementation using the closure mechanism.
|
2015-11-25 06:23:38 +00:00
|
|
|
std::unique_ptr<ValueProfData>
|
|
|
|
ValueProfData::serializeFrom(const InstrProfRecord &Record) {
|
|
|
|
InstrProfRecordClosure.Record = &Record;
|
|
|
|
|
|
|
|
std::unique_ptr<ValueProfData> VPD(
|
2015-12-01 19:47:32 +00:00
|
|
|
serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
|
2015-11-25 06:23:38 +00:00
|
|
|
return VPD;
|
|
|
|
}
|
|
|
|
|
2015-11-25 19:13:00 +00:00
|
|
|
void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
|
2018-03-21 22:27:31 +00:00
|
|
|
InstrProfSymtab *SymTab) {
|
2015-11-25 19:13:00 +00:00
|
|
|
Record.reserveSites(Kind, NumValueSites);
|
|
|
|
|
|
|
|
InstrProfValueData *ValueData = getValueProfRecordValueData(this);
|
|
|
|
for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
|
|
|
|
uint8_t ValueDataCount = this->SiteCountArray[VSite];
|
2018-03-21 22:27:31 +00:00
|
|
|
Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
|
2015-11-25 19:13:00 +00:00
|
|
|
ValueData += ValueDataCount;
|
|
|
|
}
|
|
|
|
}
|
2015-11-25 23:31:18 +00:00
|
|
|
|
2015-11-25 19:13:00 +00:00
|
|
|
// For writing/serializing, Old is the host endianness, and New is
|
|
|
|
// byte order intended on disk. For Reading/deserialization, Old
|
|
|
|
// is the on-disk source endianness, and New is the host endianness.
|
2023-10-10 21:54:15 -07:00
|
|
|
void ValueProfRecord::swapBytes(llvm::endianness Old, llvm::endianness New) {
|
2015-11-25 19:13:00 +00:00
|
|
|
using namespace support;
|
2017-03-03 01:07:34 +00:00
|
|
|
|
2015-11-25 19:13:00 +00:00
|
|
|
if (Old == New)
|
|
|
|
return;
|
|
|
|
|
2023-10-05 21:30:48 -07:00
|
|
|
if (llvm::endianness::native != Old) {
|
2015-11-25 19:13:00 +00:00
|
|
|
sys::swapByteOrder<uint32_t>(NumValueSites);
|
|
|
|
sys::swapByteOrder<uint32_t>(Kind);
|
|
|
|
}
|
|
|
|
uint32_t ND = getValueProfRecordNumValueData(this);
|
|
|
|
InstrProfValueData *VD = getValueProfRecordValueData(this);
|
|
|
|
|
|
|
|
// No need to swap byte array: SiteCountArrray.
|
|
|
|
for (uint32_t I = 0; I < ND; I++) {
|
|
|
|
sys::swapByteOrder<uint64_t>(VD[I].Value);
|
|
|
|
sys::swapByteOrder<uint64_t>(VD[I].Count);
|
|
|
|
}
|
2023-10-05 21:30:48 -07:00
|
|
|
if (llvm::endianness::native == Old) {
|
2015-11-25 19:13:00 +00:00
|
|
|
sys::swapByteOrder<uint32_t>(NumValueSites);
|
|
|
|
sys::swapByteOrder<uint32_t>(Kind);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void ValueProfData::deserializeTo(InstrProfRecord &Record,
|
2018-03-21 22:27:31 +00:00
|
|
|
InstrProfSymtab *SymTab) {
|
2015-11-25 19:13:00 +00:00
|
|
|
if (NumValueKinds == 0)
|
|
|
|
return;
|
|
|
|
|
|
|
|
ValueProfRecord *VR = getFirstValueProfRecord(this);
|
|
|
|
for (uint32_t K = 0; K < NumValueKinds; K++) {
|
2018-03-21 22:27:31 +00:00
|
|
|
VR->deserializeTo(Record, SymTab);
|
2015-11-25 19:13:00 +00:00
|
|
|
VR = getValueProfRecordNext(VR);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
|
|
|
|
return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
|
|
|
|
ValueProfData());
|
|
|
|
}
|
|
|
|
|
2016-05-19 03:54:45 +00:00
|
|
|
Error ValueProfData::checkIntegrity() {
|
2015-11-28 04:56:07 +00:00
|
|
|
if (NumValueKinds > IPVK_Last + 1)
|
2021-08-30 19:12:16 +00:00
|
|
|
return make_error<InstrProfError>(
|
|
|
|
instrprof_error::malformed, "number of value profile kinds is invalid");
|
|
|
|
// Total size needs to be multiple of quadword size.
|
2015-11-28 04:56:07 +00:00
|
|
|
if (TotalSize % sizeof(uint64_t))
|
2021-08-30 19:12:16 +00:00
|
|
|
return make_error<InstrProfError>(
|
|
|
|
instrprof_error::malformed, "total size is not multiples of quardword");
|
2015-11-28 04:56:07 +00:00
|
|
|
|
|
|
|
ValueProfRecord *VR = getFirstValueProfRecord(this);
|
|
|
|
for (uint32_t K = 0; K < this->NumValueKinds; K++) {
|
|
|
|
if (VR->Kind > IPVK_Last)
|
2021-08-30 19:12:16 +00:00
|
|
|
return make_error<InstrProfError>(instrprof_error::malformed,
|
|
|
|
"value kind is invalid");
|
2015-11-28 04:56:07 +00:00
|
|
|
VR = getValueProfRecordNext(VR);
|
|
|
|
if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
|
2021-08-30 19:12:16 +00:00
|
|
|
return make_error<InstrProfError>(
|
|
|
|
instrprof_error::malformed,
|
|
|
|
"value profile address is greater than total size");
|
2015-11-28 04:56:07 +00:00
|
|
|
}
|
2016-05-19 03:54:45 +00:00
|
|
|
return Error::success();
|
2015-11-28 04:56:07 +00:00
|
|
|
}
|
|
|
|
|
2016-05-19 03:54:45 +00:00
|
|
|
Expected<std::unique_ptr<ValueProfData>>
|
2015-11-10 00:24:45 +00:00
|
|
|
ValueProfData::getValueProfData(const unsigned char *D,
|
|
|
|
const unsigned char *const BufferEnd,
|
2023-10-10 21:54:15 -07:00
|
|
|
llvm::endianness Endianness) {
|
2015-11-10 00:24:45 +00:00
|
|
|
using namespace support;
|
2017-03-03 01:07:34 +00:00
|
|
|
|
2015-11-10 00:24:45 +00:00
|
|
|
if (D + sizeof(ValueProfData) > BufferEnd)
|
2016-05-19 03:54:45 +00:00
|
|
|
return make_error<InstrProfError>(instrprof_error::truncated);
|
2015-11-10 00:24:45 +00:00
|
|
|
|
2015-11-17 03:47:21 +00:00
|
|
|
const unsigned char *Header = D;
|
2024-06-06 13:25:52 -07:00
|
|
|
uint32_t TotalSize = endian::readNext<uint32_t>(Header, Endianness);
|
|
|
|
|
2015-11-10 00:24:45 +00:00
|
|
|
if (D + TotalSize > BufferEnd)
|
2016-05-19 03:54:45 +00:00
|
|
|
return make_error<InstrProfError>(instrprof_error::too_large);
|
2015-11-10 00:24:45 +00:00
|
|
|
|
2015-11-25 06:23:38 +00:00
|
|
|
std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
|
2015-11-10 00:24:45 +00:00
|
|
|
memcpy(VPD.get(), D, TotalSize);
|
|
|
|
// Byte swap.
|
|
|
|
VPD->swapBytesToHost(Endianness);
|
|
|
|
|
2016-05-19 03:54:45 +00:00
|
|
|
Error E = VPD->checkIntegrity();
|
|
|
|
if (E)
|
2020-02-10 07:06:45 -08:00
|
|
|
return std::move(E);
|
2015-11-10 00:24:45 +00:00
|
|
|
|
2020-02-10 07:06:45 -08:00
|
|
|
return std::move(VPD);
|
2015-11-10 00:24:45 +00:00
|
|
|
}
|
|
|
|
|
2023-10-10 21:54:15 -07:00
|
|
|
void ValueProfData::swapBytesToHost(llvm::endianness Endianness) {
|
2015-11-10 00:24:45 +00:00
|
|
|
using namespace support;
|
2017-03-03 01:07:34 +00:00
|
|
|
|
2023-10-05 21:30:48 -07:00
|
|
|
if (Endianness == llvm::endianness::native)
|
2015-11-10 00:24:45 +00:00
|
|
|
return;
|
|
|
|
|
|
|
|
sys::swapByteOrder<uint32_t>(TotalSize);
|
|
|
|
sys::swapByteOrder<uint32_t>(NumValueKinds);
|
|
|
|
|
2015-11-25 06:23:38 +00:00
|
|
|
ValueProfRecord *VR = getFirstValueProfRecord(this);
|
2015-11-10 00:24:45 +00:00
|
|
|
for (uint32_t K = 0; K < NumValueKinds; K++) {
|
2023-10-05 21:30:48 -07:00
|
|
|
VR->swapBytes(Endianness, llvm::endianness::native);
|
2015-11-25 04:29:24 +00:00
|
|
|
VR = getValueProfRecordNext(VR);
|
2015-11-10 00:24:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-10 21:54:15 -07:00
|
|
|
void ValueProfData::swapBytesFromHost(llvm::endianness Endianness) {
|
2015-11-10 00:24:45 +00:00
|
|
|
using namespace support;
|
2017-03-03 01:07:34 +00:00
|
|
|
|
2023-10-05 21:30:48 -07:00
|
|
|
if (Endianness == llvm::endianness::native)
|
2015-11-10 00:24:45 +00:00
|
|
|
return;
|
|
|
|
|
2015-11-25 06:23:38 +00:00
|
|
|
ValueProfRecord *VR = getFirstValueProfRecord(this);
|
2015-11-10 00:24:45 +00:00
|
|
|
for (uint32_t K = 0; K < NumValueKinds; K++) {
|
2015-11-25 04:29:24 +00:00
|
|
|
ValueProfRecord *NVR = getValueProfRecordNext(VR);
|
2023-10-05 21:30:48 -07:00
|
|
|
VR->swapBytes(llvm::endianness::native, Endianness);
|
2015-11-10 00:24:45 +00:00
|
|
|
VR = NVR;
|
|
|
|
}
|
|
|
|
sys::swapByteOrder<uint32_t>(TotalSize);
|
|
|
|
sys::swapByteOrder<uint32_t>(NumValueKinds);
|
|
|
|
}
|
2015-11-25 19:13:00 +00:00
|
|
|
|
2016-02-04 19:11:43 +00:00
|
|
|
void annotateValueSite(Module &M, Instruction &Inst,
|
|
|
|
const InstrProfRecord &InstrProfR,
|
2016-02-10 22:19:43 +00:00
|
|
|
InstrProfValueKind ValueKind, uint32_t SiteIdx,
|
|
|
|
uint32_t MaxMDCount) {
|
2024-06-14 06:38:48 -07:00
|
|
|
auto VDs = InstrProfR.getValueArrayForSite(ValueKind, SiteIdx);
|
|
|
|
if (VDs.empty())
|
2016-04-14 16:25:45 +00:00
|
|
|
return;
|
2024-06-12 10:14:33 -07:00
|
|
|
uint64_t Sum = 0;
|
|
|
|
for (const InstrProfValueData &V : VDs)
|
|
|
|
Sum = SaturatingAdd(Sum, V.Count);
|
2016-03-30 16:56:31 +00:00
|
|
|
annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
|
2016-02-12 21:36:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void annotateValueSite(Module &M, Instruction &Inst,
|
2016-03-30 16:56:31 +00:00
|
|
|
ArrayRef<InstrProfValueData> VDs,
|
2016-02-12 21:36:17 +00:00
|
|
|
uint64_t Sum, InstrProfValueKind ValueKind,
|
|
|
|
uint32_t MaxMDCount) {
|
2024-04-11 13:28:20 -07:00
|
|
|
if (VDs.empty())
|
|
|
|
return;
|
2016-02-04 19:11:43 +00:00
|
|
|
LLVMContext &Ctx = M.getContext();
|
|
|
|
MDBuilder MDHelper(Ctx);
|
|
|
|
SmallVector<Metadata *, 3> Vals;
|
|
|
|
// Tag
|
|
|
|
Vals.push_back(MDHelper.createString("VP"));
|
|
|
|
// Value Kind
|
|
|
|
Vals.push_back(MDHelper.createConstant(
|
|
|
|
ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
|
|
|
|
// Total Count
|
|
|
|
Vals.push_back(
|
|
|
|
MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
|
|
|
|
|
|
|
|
// Value Profile Data
|
2016-02-10 22:19:43 +00:00
|
|
|
uint32_t MDCount = MaxMDCount;
|
2024-06-07 15:06:04 -07:00
|
|
|
for (const auto &VD : VDs) {
|
2016-02-04 19:11:43 +00:00
|
|
|
Vals.push_back(MDHelper.createConstant(
|
2016-03-30 16:56:31 +00:00
|
|
|
ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
|
2016-02-04 19:11:43 +00:00
|
|
|
Vals.push_back(MDHelper.createConstant(
|
2016-03-30 16:56:31 +00:00
|
|
|
ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
|
2016-02-04 19:11:43 +00:00
|
|
|
if (--MDCount == 0)
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
|
|
|
|
}
|
|
|
|
|
2024-04-01 15:14:49 -07:00
|
|
|
MDNode *mayHaveValueProfileOfKind(const Instruction &Inst,
|
|
|
|
InstrProfValueKind ValueKind) {
|
2016-02-04 19:11:43 +00:00
|
|
|
MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
|
|
|
|
if (!MD)
|
2024-04-01 15:14:49 -07:00
|
|
|
return nullptr;
|
2016-02-04 19:11:43 +00:00
|
|
|
|
2024-04-01 15:14:49 -07:00
|
|
|
if (MD->getNumOperands() < 5)
|
|
|
|
return nullptr;
|
2016-02-04 19:11:43 +00:00
|
|
|
|
|
|
|
MDString *Tag = cast<MDString>(MD->getOperand(0));
|
2024-05-08 10:33:53 -07:00
|
|
|
if (!Tag || Tag->getString() != "VP")
|
2024-04-01 15:14:49 -07:00
|
|
|
return nullptr;
|
2016-02-04 19:11:43 +00:00
|
|
|
|
|
|
|
// Now check kind:
|
|
|
|
ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
|
|
|
|
if (!KindInt)
|
2024-04-01 15:14:49 -07:00
|
|
|
return nullptr;
|
2016-02-04 19:11:43 +00:00
|
|
|
if (KindInt->getZExtValue() != ValueKind)
|
2024-04-01 15:14:49 -07:00
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
return MD;
|
|
|
|
}
|
2016-02-04 19:11:43 +00:00
|
|
|
|
2024-06-22 00:40:36 -07:00
|
|
|
SmallVector<InstrProfValueData, 4>
|
|
|
|
getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind,
|
|
|
|
uint32_t MaxNumValueData, uint64_t &TotalC,
|
|
|
|
bool GetNoICPValue) {
|
|
|
|
// Four inline elements seem to work well in practice. With MaxNumValueData,
|
|
|
|
// this array won't grow very big anyway.
|
|
|
|
SmallVector<InstrProfValueData, 4> ValueData;
|
|
|
|
MDNode *MD = mayHaveValueProfileOfKind(Inst, ValueKind);
|
|
|
|
if (!MD)
|
|
|
|
return ValueData;
|
|
|
|
const unsigned NOps = MD->getNumOperands();
|
|
|
|
// Get total count
|
|
|
|
ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
|
|
|
|
if (!TotalCInt)
|
|
|
|
return ValueData;
|
|
|
|
TotalC = TotalCInt->getZExtValue();
|
|
|
|
|
|
|
|
ValueData.reserve((NOps - 3) / 2);
|
|
|
|
for (unsigned I = 3; I < NOps; I += 2) {
|
|
|
|
if (ValueData.size() >= MaxNumValueData)
|
|
|
|
break;
|
|
|
|
ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
|
|
|
|
ConstantInt *Count =
|
|
|
|
mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
|
|
|
|
if (!Value || !Count) {
|
|
|
|
ValueData.clear();
|
|
|
|
return ValueData;
|
|
|
|
}
|
|
|
|
uint64_t CntValue = Count->getZExtValue();
|
|
|
|
if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM))
|
|
|
|
continue;
|
|
|
|
InstrProfValueData V;
|
|
|
|
V.Value = Value->getZExtValue();
|
|
|
|
V.Count = CntValue;
|
|
|
|
ValueData.push_back(V);
|
|
|
|
}
|
|
|
|
return ValueData;
|
|
|
|
}
|
|
|
|
|
2016-04-01 20:15:04 +00:00
|
|
|
MDNode *getPGOFuncNameMetadata(const Function &F) {
|
|
|
|
return F.getMetadata(getPGOFuncNameMetadataName());
|
|
|
|
}
|
|
|
|
|
[TypeProf][InstrFDO]Implement more efficient comparison sequence for indirect-call-promotion with vtable profiles. (#81442)
Clang's `-fwhole-program-vtables` is required for this optimization to
take place. If `-fwhole-program-vtables` is not enabled, this change is
no-op.
* Function-comparison (before):
```
%vtable = load ptr, ptr %obj
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
%cond = icmp eq ptr %func, @callee
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
call %func
```
* VTable-comparison (after):
```
%vtable = load ptr, ptr %obj
%cond = icmp eq ptr %vtable, @vtable-address-point
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
call %func
```
Key changes:
1. Find out virtual calls and the vtables they come from.
- The ICP relies on type intrinsic `llvm.type.test` to find out virtual
calls and the
compatible vtables, and relies on type metadata to find the address
point for comparison.
2. ICP pass does cost-benefit analysis and compares vtable only when the
number of vtables for a function candidate is within (option specified)
threshold.
3. Sink the function addressing and vtable load instruction to indirect
fallback.
- The sink helper functions are simplified versions of
`InstCombinerImpl::tryToSinkInstruction`. Currently debug intrinsics are
not handled. Ideally `InstCombinerImpl::tryToSinkInstructionDbgValues`
and `InstCombinerImpl::tryToSinkInstructionDbgVariableRecords` could be
moved into Transforms/Utils/Local.cpp (or another util cpp file) to
handle debug intrinsics when moving instructions across basic blocks.
4. Keep value profiles updated
1) Update vtable value profiles after inline
2) For either function-based comparison or vtable-based comparison,
update both vtable and indirect call value profiles.
2024-06-29 23:21:33 -07:00
|
|
|
static void createPGONameMetadata(GlobalObject &GO, StringRef MetadataName,
|
|
|
|
StringRef PGOName) {
|
|
|
|
// Only for internal linkage functions or global variables. The name is not
|
|
|
|
// the same as PGO name for these global objects.
|
|
|
|
if (GO.getName() == PGOName)
|
2016-04-01 16:43:30 +00:00
|
|
|
return;
|
[TypeProf][InstrFDO]Implement more efficient comparison sequence for indirect-call-promotion with vtable profiles. (#81442)
Clang's `-fwhole-program-vtables` is required for this optimization to
take place. If `-fwhole-program-vtables` is not enabled, this change is
no-op.
* Function-comparison (before):
```
%vtable = load ptr, ptr %obj
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
%cond = icmp eq ptr %func, @callee
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
call %func
```
* VTable-comparison (after):
```
%vtable = load ptr, ptr %obj
%cond = icmp eq ptr %vtable, @vtable-address-point
br i1 %cond, label bb1, label bb2:
bb1:
call @callee
bb2:
%vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
%func = load ptr, ptr %vfn
call %func
```
Key changes:
1. Find out virtual calls and the vtables they come from.
- The ICP relies on type intrinsic `llvm.type.test` to find out virtual
calls and the
compatible vtables, and relies on type metadata to find the address
point for comparison.
2. ICP pass does cost-benefit analysis and compares vtable only when the
number of vtables for a function candidate is within (option specified)
threshold.
3. Sink the function addressing and vtable load instruction to indirect
fallback.
- The sink helper functions are simplified versions of
`InstCombinerImpl::tryToSinkInstruction`. Currently debug intrinsics are
not handled. Ideally `InstCombinerImpl::tryToSinkInstructionDbgValues`
and `InstCombinerImpl::tryToSinkInstructionDbgVariableRecords` could be
moved into Transforms/Utils/Local.cpp (or another util cpp file) to
handle debug intrinsics when moving instructions across basic blocks.
4. Keep value profiles updated
1) Update vtable value profiles after inline
2) For either function-based comparison or vtable-based comparison,
update both vtable and indirect call value profiles.
2024-06-29 23:21:33 -07:00
|
|
|
|
|
|
|
// Don't create duplicated metadata.
|
|
|
|
if (GO.getMetadata(MetadataName))
|
|
|
|
return;
|
|
|
|
|
|
|
|
LLVMContext &C = GO.getContext();
|
|
|
|
MDNode *N = MDNode::get(C, MDString::get(C, PGOName));
|
|
|
|
GO.setMetadata(MetadataName, N);
|
|
|
|
}
|
|
|
|
|
|
|
|
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
|
|
|
|
return createPGONameMetadata(F, getPGOFuncNameMetadataName(), PGOFuncName);
|
|
|
|
}
|
|
|
|
|
|
|
|
void createPGONameMetadata(GlobalObject &GO, StringRef PGOName) {
|
|
|
|
return createPGONameMetadata(GO, getPGONameMetadataName(), PGOName);
|
2016-04-01 16:43:30 +00:00
|
|
|
}
|
|
|
|
|
2024-04-01 08:52:35 -07:00
|
|
|
bool needsComdatForCounter(const GlobalObject &GO, const Module &M) {
|
|
|
|
if (GO.hasComdat())
|
2016-07-21 20:50:02 +00:00
|
|
|
return true;
|
|
|
|
|
2018-07-26 22:59:17 +00:00
|
|
|
if (!Triple(M.getTargetTriple()).supportsCOMDAT())
|
2016-07-21 20:50:02 +00:00
|
|
|
return false;
|
|
|
|
|
|
|
|
// See createPGOFuncNameVar for more details. To avoid link errors, profile
|
|
|
|
// counters for function with available_externally linkage needs to be changed
|
|
|
|
// to linkonce linkage. On ELF based systems, this leads to weak symbols to be
|
|
|
|
// created. Without using comdat, duplicate entries won't be removed by the
|
|
|
|
// linker leading to increased data segement size and raw profile size. Even
|
|
|
|
// worse, since the referenced counter from profile per-function data object
|
|
|
|
// will be resolved to the common strong definition, the profile counts for
|
|
|
|
// available_externally functions will end up being duplicated in raw profile
|
|
|
|
// data. This can result in distorted profile as the counts of those dups
|
|
|
|
// will be accumulated by the profile merger.
|
2024-04-01 08:52:35 -07:00
|
|
|
GlobalValue::LinkageTypes Linkage = GO.getLinkage();
|
2016-07-21 20:50:02 +00:00
|
|
|
if (Linkage != GlobalValue::ExternalWeakLinkage &&
|
|
|
|
Linkage != GlobalValue::AvailableExternallyLinkage)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
2017-01-11 20:19:41 +00:00
|
|
|
|
|
|
|
// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
|
|
|
|
bool isIRPGOFlagSet(const Module *M) {
|
|
|
|
auto IRInstrVar =
|
|
|
|
M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
|
2021-08-24 09:04:37 -07:00
|
|
|
if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
|
2017-01-11 20:19:41 +00:00
|
|
|
return false;
|
|
|
|
|
2021-08-24 09:04:37 -07:00
|
|
|
// For CSPGO+LTO, this variable might be marked as non-prevailing and we only
|
|
|
|
// have the decl.
|
|
|
|
if (IRInstrVar->isDeclaration())
|
|
|
|
return true;
|
|
|
|
|
2017-01-11 20:19:41 +00:00
|
|
|
// Check if the flag is set.
|
|
|
|
if (!IRInstrVar->hasInitializer())
|
|
|
|
return false;
|
|
|
|
|
2019-10-01 10:38:30 +00:00
|
|
|
auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
|
2017-01-11 20:19:41 +00:00
|
|
|
if (!InitVal)
|
|
|
|
return false;
|
2019-10-01 10:38:30 +00:00
|
|
|
return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
|
2017-01-11 20:19:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check if we can safely rename this Comdat function.
|
|
|
|
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
|
|
|
|
if (F.getName().empty())
|
|
|
|
return false;
|
|
|
|
if (!needsComdatForCounter(F, *(F.getParent())))
|
|
|
|
return false;
|
|
|
|
// Unsafe to rename the address-taken function (which can be used in
|
|
|
|
// function comparison).
|
|
|
|
if (CheckAddressTaken && F.hasAddressTaken())
|
|
|
|
return false;
|
|
|
|
// Only safe to do if this function may be discarded if it is not used
|
|
|
|
// in the compilation unit.
|
|
|
|
if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// For AvailableExternallyLinkage functions.
|
|
|
|
if (!F.hasComdat()) {
|
|
|
|
assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
2017-03-03 01:07:34 +00:00
|
|
|
|
2019-02-05 22:34:45 +00:00
|
|
|
// Create the variable for the profile file name.
|
|
|
|
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
|
|
|
|
if (InstrProfileOutput.empty())
|
|
|
|
return;
|
|
|
|
Constant *ProfileNameConst =
|
|
|
|
ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
|
|
|
|
GlobalVariable *ProfileNameVar = new GlobalVariable(
|
|
|
|
M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
|
|
|
|
ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
|
2022-10-26 17:13:05 +00:00
|
|
|
ProfileNameVar->setVisibility(GlobalValue::HiddenVisibility);
|
2019-02-05 22:34:45 +00:00
|
|
|
Triple TT(M.getTargetTriple());
|
|
|
|
if (TT.supportsCOMDAT()) {
|
|
|
|
ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
|
|
|
|
ProfileNameVar->setComdat(M.getOrInsertComdat(
|
|
|
|
StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-01 18:06:50 +00:00
|
|
|
Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
|
|
|
|
const std::string &TestFilename,
|
|
|
|
bool IsCS) {
|
2019-04-30 21:19:12 +00:00
|
|
|
auto getProfileSum = [IsCS](const std::string &Filename,
|
|
|
|
CountSumOrPercent &Sum) -> Error {
|
2023-02-01 09:24:44 -08:00
|
|
|
// This function is only used from llvm-profdata that doesn't use any kind
|
|
|
|
// of VFS. Just create a default RealFileSystem to read profiles.
|
|
|
|
auto FS = vfs::getRealFileSystem();
|
|
|
|
auto ReaderOrErr = InstrProfReader::create(Filename, *FS);
|
2019-04-30 21:19:12 +00:00
|
|
|
if (Error E = ReaderOrErr.takeError()) {
|
|
|
|
return E;
|
|
|
|
}
|
|
|
|
auto Reader = std::move(ReaderOrErr.get());
|
2019-10-01 18:06:50 +00:00
|
|
|
Reader->accumulateCounts(Sum, IsCS);
|
2019-04-30 21:19:12 +00:00
|
|
|
return Error::success();
|
|
|
|
};
|
|
|
|
auto Ret = getProfileSum(BaseFilename, Base);
|
|
|
|
if (Ret)
|
2019-04-30 21:44:21 +00:00
|
|
|
return Ret;
|
2019-04-30 21:19:12 +00:00
|
|
|
Ret = getProfileSum(TestFilename, Test);
|
|
|
|
if (Ret)
|
2019-04-30 21:44:21 +00:00
|
|
|
return Ret;
|
2019-04-30 21:19:12 +00:00
|
|
|
this->BaseFilename = &BaseFilename;
|
|
|
|
this->TestFilename = &TestFilename;
|
|
|
|
Valid = true;
|
|
|
|
return Error::success();
|
|
|
|
}
|
|
|
|
|
|
|
|
void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
|
|
|
|
Mismatch.NumEntries += 1;
|
|
|
|
Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
|
|
|
|
for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
|
|
|
|
if (Test.ValueCounts[I] >= 1.0f)
|
|
|
|
Mismatch.ValueCounts[I] +=
|
|
|
|
MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
|
|
|
|
Unique.NumEntries += 1;
|
|
|
|
Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
|
|
|
|
for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
|
|
|
|
if (Test.ValueCounts[I] >= 1.0f)
|
|
|
|
Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void OverlapStats::dump(raw_fd_ostream &OS) const {
|
|
|
|
if (!Valid)
|
|
|
|
return;
|
|
|
|
|
|
|
|
const char *EntryName =
|
|
|
|
(Level == ProgramLevel ? "functions" : "edge counters");
|
|
|
|
if (Level == ProgramLevel) {
|
|
|
|
OS << "Profile overlap infomation for base_profile: " << *BaseFilename
|
|
|
|
<< " and test_profile: " << *TestFilename << "\nProgram level:\n";
|
|
|
|
} else {
|
|
|
|
OS << "Function level:\n"
|
|
|
|
<< " Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
|
|
|
|
if (Mismatch.NumEntries)
|
|
|
|
OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries
|
|
|
|
<< "\n";
|
|
|
|
if (Unique.NumEntries)
|
|
|
|
OS << " # of " << EntryName
|
|
|
|
<< " only in test_profile: " << Unique.NumEntries << "\n";
|
|
|
|
|
|
|
|
OS << " Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
|
|
|
|
<< "\n";
|
|
|
|
if (Mismatch.NumEntries)
|
|
|
|
OS << " Mismatched count percentage (Edge): "
|
|
|
|
<< format("%.3f%%", Mismatch.CountSum * 100) << "\n";
|
|
|
|
if (Unique.NumEntries)
|
|
|
|
OS << " Percentage of Edge profile only in test_profile: "
|
|
|
|
<< format("%.3f%%", Unique.CountSum * 100) << "\n";
|
|
|
|
OS << " Edge profile base count sum: " << format("%.0f", Base.CountSum)
|
|
|
|
<< "\n"
|
|
|
|
<< " Edge profile test count sum: " << format("%.0f", Test.CountSum)
|
|
|
|
<< "\n";
|
|
|
|
|
|
|
|
for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
|
|
|
|
if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
|
|
|
|
continue;
|
2024-04-01 08:52:35 -07:00
|
|
|
char ProfileKindName[20] = {0};
|
2019-04-30 21:19:12 +00:00
|
|
|
switch (I) {
|
|
|
|
case IPVK_IndirectCallTarget:
|
|
|
|
strncpy(ProfileKindName, "IndirectCall", 19);
|
|
|
|
break;
|
|
|
|
case IPVK_MemOPSize:
|
|
|
|
strncpy(ProfileKindName, "MemOP", 19);
|
|
|
|
break;
|
2024-04-01 08:52:35 -07:00
|
|
|
case IPVK_VTableTarget:
|
|
|
|
strncpy(ProfileKindName, "VTable", 19);
|
|
|
|
break;
|
2019-04-30 21:19:12 +00:00
|
|
|
default:
|
|
|
|
snprintf(ProfileKindName, 19, "VP[%d]", I);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
OS << " " << ProfileKindName
|
|
|
|
<< " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
|
|
|
|
<< "\n";
|
|
|
|
if (Mismatch.NumEntries)
|
|
|
|
OS << " Mismatched count percentage (" << ProfileKindName
|
|
|
|
<< "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
|
|
|
|
if (Unique.NumEntries)
|
|
|
|
OS << " Percentage of " << ProfileKindName
|
|
|
|
<< " profile only in test_profile: "
|
|
|
|
<< format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
|
|
|
|
OS << " " << ProfileKindName
|
|
|
|
<< " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
|
|
|
|
<< "\n"
|
|
|
|
<< " " << ProfileKindName
|
|
|
|
<< " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
|
|
|
|
<< "\n";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-14 11:52:40 -08:00
|
|
|
namespace IndexedInstrProf {
|
|
|
|
Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
|
|
|
|
using namespace support;
|
2022-11-08 14:15:04 +00:00
|
|
|
static_assert(std::is_standard_layout_v<Header>,
|
2024-05-30 12:44:29 -07:00
|
|
|
"Use standard layout for Header for simplicity");
|
2022-02-14 11:52:40 -08:00
|
|
|
Header H;
|
|
|
|
|
2024-05-30 12:44:29 -07:00
|
|
|
H.Magic = endian::readNext<uint64_t, llvm::endianness::little>(Buffer);
|
2022-02-14 11:52:40 -08:00
|
|
|
// Check the magic number.
|
2024-05-21 21:25:12 -07:00
|
|
|
if (H.Magic != IndexedInstrProf::Magic)
|
2022-02-14 11:52:40 -08:00
|
|
|
return make_error<InstrProfError>(instrprof_error::bad_magic);
|
|
|
|
|
|
|
|
// Read the version.
|
2024-05-30 12:44:29 -07:00
|
|
|
H.Version = endian::readNext<uint64_t, llvm::endianness::little>(Buffer);
|
2024-05-29 10:15:17 -07:00
|
|
|
if (H.getIndexedProfileVersion() >
|
|
|
|
IndexedInstrProf::ProfVersion::CurrentVersion)
|
2022-02-14 11:52:40 -08:00
|
|
|
return make_error<InstrProfError>(instrprof_error::unsupported_version);
|
|
|
|
|
2024-05-30 12:44:29 -07:00
|
|
|
static_assert(IndexedInstrProf::ProfVersion::CurrentVersion == Version12,
|
|
|
|
"Please update the reader as needed when a new field is added "
|
|
|
|
"or when indexed profile version gets bumped.");
|
|
|
|
|
|
|
|
Buffer += sizeof(uint64_t); // Skip Header.Unused field.
|
|
|
|
H.HashType = endian::readNext<uint64_t, llvm::endianness::little>(Buffer);
|
|
|
|
H.HashOffset = endian::readNext<uint64_t, llvm::endianness::little>(Buffer);
|
|
|
|
if (H.getIndexedProfileVersion() >= 8)
|
|
|
|
H.MemProfOffset =
|
|
|
|
endian::readNext<uint64_t, llvm::endianness::little>(Buffer);
|
|
|
|
if (H.getIndexedProfileVersion() >= 9)
|
|
|
|
H.BinaryIdOffset =
|
|
|
|
endian::readNext<uint64_t, llvm::endianness::little>(Buffer);
|
|
|
|
// Version 11 is handled by this condition.
|
|
|
|
if (H.getIndexedProfileVersion() >= 10)
|
2023-04-11 07:58:47 -07:00
|
|
|
H.TemporalProfTracesOffset =
|
2024-05-30 12:44:29 -07:00
|
|
|
endian::readNext<uint64_t, llvm::endianness::little>(Buffer);
|
|
|
|
if (H.getIndexedProfileVersion() >= 12)
|
|
|
|
H.VTableNamesOffset =
|
|
|
|
endian::readNext<uint64_t, llvm::endianness::little>(Buffer);
|
2022-02-14 11:52:40 -08:00
|
|
|
return H;
|
|
|
|
}
|
|
|
|
|
2024-05-29 10:15:17 -07:00
|
|
|
uint64_t Header::getIndexedProfileVersion() const {
|
|
|
|
return GET_VERSION(Version);
|
|
|
|
}
|
|
|
|
|
2022-02-14 11:52:40 -08:00
|
|
|
size_t Header::size() const {
|
2024-05-29 10:15:17 -07:00
|
|
|
switch (getIndexedProfileVersion()) {
|
2024-05-30 12:44:29 -07:00
|
|
|
// To retain backward compatibility, new fields must be appended to the end
|
|
|
|
// of the header, and byte offset of existing fields shouldn't change when
|
|
|
|
// indexed profile version gets incremented.
|
|
|
|
static_assert(
|
|
|
|
IndexedInstrProf::ProfVersion::CurrentVersion == Version12,
|
|
|
|
"Please update the size computation below if a new field has "
|
|
|
|
"been added to the header; for a version bump without new "
|
|
|
|
"fields, add a case statement to fall through to the latest version.");
|
Reland "[TypeProf][InstrPGO] Introduce raw and instr profile format change for type profiling." (#82711)
New change on top of [reviewed
patch](https://github.com/llvm/llvm-project/pull/81691) are [in commits
after this
one](https://github.com/llvm/llvm-project/pull/82711/commits/d0757f46b3e3865b5f7c552bc0744309a363e0ac).
Previous commits are restored from the remote branch with timestamps.
1. Fix build breakage for non-ELF platforms, by defining the missing
functions {`__llvm_profile_begin_vtables`, `__llvm_profile_end_vtables`,
`__llvm_profile_begin_vtabnames `, `__llvm_profile_end_vtabnames`}
everywhere.
* Tested on mac laptop (for darwins) and Windows. Specifically,
functions in `InstrProfilingPlatformWindows.c` returns `NULL` to make it
more explicit that type prof isn't supported; see comments for the
reason.
* For the rest (AIX, other), mostly follow existing examples (like this
[one](https://github.com/llvm/llvm-project/commit/f95b2f1acf1171abb0d00089fd4c9238753847e3))
2. Rename `__llvm_prf_vtabnames` -> `__llvm_prf_vns` for shorter section
name, and make returned pointers
[const](https://github.com/llvm/llvm-project/pull/82711/commits/a825d2a4ec00f07772a373091a702f149c3b0c34#diff-4de780ce726d76b7abc9d3353aef95013e7b21e7bda01be8940cc6574fb0b5ffR120-R121)
**Original Description**
* Raw profile format
- Header: records the byte size of compressed vtable names, and the
number of profiled vtable entries (call it `VTableProfData`). Header
also records padded bytes of each section.
- Payload: adds a section for compressed vtable names, and a section to
store `VTableProfData`. Both sections are padded so the size is a
multiple of 8.
* Indexed profile format
- Header: records the byte offset of compressed vtable names.
- Payload: adds a section to store compressed vtable names. This section
is used by `llvm-profdata` to show the list of vtables profiled for an
instrumented site.
[The originally reviewed
patch](https://github.com/llvm/llvm-project/pull/66825) will have
profile reader/write change and llvm-profdata change.
- To ensure this PR has all the necessary profile format change along
with profile version bump, created a copy of the originally reviewed
patch in https://github.com/llvm/llvm-project/pull/80761. The copy
doesn't have profile format change, but it has the set of tests which
covers type profile generation, profile read and profile merge. Tests
pass there.
rfc in
https://discourse.llvm.org/t/rfc-dynamic-type-profiling-and-optimizations-in-llvm/74600
---------
Co-authored-by: modiking <modiking213@gmail.com>
2024-02-27 11:07:40 -08:00
|
|
|
case 12ull:
|
2024-05-30 12:44:29 -07:00
|
|
|
return 72;
|
2023-09-21 13:07:31 -05:00
|
|
|
case 11ull:
|
|
|
|
[[fallthrough]];
|
2023-04-11 07:58:47 -07:00
|
|
|
case 10ull:
|
2024-05-30 12:44:29 -07:00
|
|
|
return 64;
|
2022-10-13 00:50:10 +00:00
|
|
|
case 9ull:
|
2024-05-30 12:44:29 -07:00
|
|
|
return 56;
|
2022-02-17 16:01:31 -08:00
|
|
|
case 8ull:
|
2024-05-30 12:44:29 -07:00
|
|
|
return 48;
|
2022-02-14 11:52:40 -08:00
|
|
|
default: // Version7 (when the backwards compatible header was introduced).
|
2024-05-30 12:44:29 -07:00
|
|
|
return 40;
|
2022-02-14 11:52:40 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace IndexedInstrProf
|
|
|
|
|
2016-01-26 18:48:36 +00:00
|
|
|
} // end namespace llvm
|