LmCast :: Stay tuned in

PGO or not PGO this is the dilemma. Step 2

Recorded: Oct. 16, 2026, 10:11 p.m.

Original Summarized

PGO or not PGO this is the dilemma. Step 2 - Percona

Download the New 2026 State of Open Source Database Management Report

Database Technology

PostgreSQL

PostgreSQL
Enterprise-ready open source PostgreSQL

Percona Software for PostgreSQL
Open source PostgreSQL software for production workloads

Calculator
Model infrastructure requirements for PostgreSQL deployments.

Downloads
Download PostgreSQL software and tools

Enterprise Support and Services
Expert help to run PostgreSQL in production

MySQL

Vision
The Future of MySQL

MySQL
Open source MySQL for enterprise use

Percona Software for MySQL
Production-ready open source MySQL software

Calculator
Compare DBaaS vs MySQL on Kubernetes cloud costs

Downloads
Download MySQL software and tools

Enterprise Support and Services
Expert help to run MySQL in production

MariaDB

MongoDB®

Technology Overview
Enterprise-grade value for MongoDB®

Percona Software for MongoDB®
Source-available, enterprise-grade compatible software for MongoDB®

Calculator
Compare MongoDB® deployment options, costs, and trade-offs.

Downloads
Download MongoDB® software and tools

Enterprise Support and Services
Expert help to run MongoDB® in production

Valkey / Redis

Valkey / Redis
Run and manage Redis or Valkey

Calculator
Discover the benefits of migrating from Redis to Valkey

Downloads
Download Valkey software and tools

Enterprise Support and Services
Expert help to run Redis and Valkey in production

Databases on Kubernetes

Observability

Monitoring & Management (PMM)

Coroot Percona Edition

Percona Toolkit

Services

Solutions Bundles

Database Support

Expert Support

ExpertOps

Expert Consulting and Services

Migrations
Health Audit
Architecture and Design
Performance Tuning
Security Assessment
Monitoring Quickstart
Training

Use Cases

Use Cases

Database solutions aligned to your needs

Learn More

Cost Optimization

Reduce licensing waste and optimize database cost and performance

Performance and Reliability

Maintain consistent performance and availability as workloads grow

Sovereignty, Security, and Compliance

Keep data secure, compliant, and under your control

AI and Future Readiness

Prepare for AI and new workloads without lock-in or replatforming

Resources

Resources

Guides, reports, and tools to help you run open source databases in production

Docs

Downloads

Resource Hub

Blog

Customer Stories

Webinars

Community

Forum

Ask questions, share knowledge, and learn from the community.

Community Hub

Join the Percona Community

Events

Connect with us via talks, workshops, and meetups.

Company

About Percona

Learn about Percona, our mission, and our open source roots.

Learn More

News

Press Releases

Partners

Careers

Contact

Brand Resources

×

Main site
Percona Blog
Community Blog
Documentation

See all results →

Downloads

Blog

Contact Us

Database Technology

MySQL

Vision
The Future of MySQL

MySQL

Percona Software for MySQL

Calculator

Downloads

Enterprise Support and Services

MongoDB

MongoDB

Percona Software for MongoDB

Calculator

Downloads

Enterprise Support and Services

PostgreSQL

PostgreSQL

Percona Software for PostgreSQL

Calculator

Downloads

Enterprise Support and Services

Valkey / Redis

Valkey / Redis

Calculator

Downloads

Enterprise Support and Services

Operations

Monitoring

Percona Toolkit

Services

Support & Operations

Expert Support

ExpertOps

Training

Advisory & Solutions

Support & Services

Expert Consulting

Solution Bundles

Use Cases

Overview

Use Cases

Operational Outcomes

Cost Optimization

Performance and Reliability

Sovereignty, Security, and Compliance

Future Readiness

AI and Future Readiness

Resources

Developers

Docs

Downloads

Hub

Resource Hub

Blog

Customer Stories

Webinars

Percona

Community

Forum

PMM Contributions

Events

Company

About Percona

News and Press

Partners

Careers

Contact Us

PGO or not PGO this is the dilemma. Step 2

October 9, 2026

Author

Marco Tusa

Marco Tusa

Insight for DBAs

Insight for Developers

MySQL

Share this Post:

Step 2: How it works
Given the topic complexity and the length of this article I have split it in 3 three different blog-post:

What is PGO
How PGO it works
Why my sysbench-trained build loses and how to do it right.

How PGO works: PGO is a two-pass build. First pass compiles with instrumentation (-fprofile-generate): every basic block and branch gets a counter.
You run a training workload, counters are dumped to profraw files.
Second pass recompiles using those counts to drive inlining decisions, branch layout (hot path falls through, cold path jumps away), hot/cold function splitting, code ordering for icache/iTLB locality, loop unrolling, and indirect-call promotion.
Crucially, PGO is not “make the trained workload fast” it’s “tell the compiler which code is hot and which is cold, and let it reshape the whole binary accordingly.”
 
But how does it work?
Phase 1: what actually gets recorded. The instrumented binary has counters injected at compile time one per edge in the control-flow graph, not just per function.
So for every branch, every loop back-edge, every call site, there’s a counter that increments each time execution takes that path.
This is finer-grained than “function X was called N times” it’s “when we reached this branch, we went left 950,000 times and right 50 times.”
That per-edge granularity is what lets the second phase make surgical decisions rather than just “function X is hot, function Y is cold.”
Phase 2: what the compiler does with those counts. Several distinct transformations, all driven by the same counter data:
Inlining.
Normally the compiler inlines based on static heuristics:

function size call-site count
estimated cost/benefit. 

With profile data it can override those heuristics: a call site executed millions of times gets inlined even if it looks “too expensive” by static cost rules, because the runtime benefit clearly outweighs the code-size cost. 
A call site that’s technically inlinable but sits in dead-cold code gets left as a real call inlining it would only bloat the binary for no benefit.
Branch layout.
Every “if” in our code compiles down to a branch instruction with two possible outcomes: 

continue straight to the next instruction
jump somewhere else. 

Continuing straight is basically free; the CPU is already fetching instructions in order, so there’s no extra cost.
Jumping is not free: the CPU has to guess in advance which way a branch will go so it can keep fetching ahead of time, and if it guesses wrong, it has to throw away the work it already queued up and start over from the right place.
That is the “pipeline bubble,” a small stall. So the “straight through” path is cheap and the “jump elsewhere” path carries a penalty when the guess is wrong. 
The compiler arranges the hot path as the fall-through and pushes the cold path out of line; literally relocated to a separate location in the binary, often into a .text.unlikely section.
So an if (unlikely_error_condition) { …rare handling… } block doesn’t sit inline interrupting the hot path anymore; it is moved somewhere else entirely, and the hot path becomes a straight run of instructions with no diversion.
To be clear, reordering our if/else in the source code usually doesn’t change how the compiler lays out the machine code. Optimizing compilers decide branch layout themselves based on either profile data (PGO) or static heuristics, not on which branch we happened to write first in the source. So swapping the order of our if blocks by hand generally has little to no effect on the compiled result.
Hot/cold function splitting.
This is the same idea applied within a single function.
A function might have a hot core loop and a rarely-hit error-handling tail.
The compiler physically splits the function into two pieces: 

the hot part stays in .text.hot
the cold part moves to .text.unlikely. 

The function still works identically (a jump connects them when needed), but now the hot part is smaller and denser, so more of it fits in an instruction-cache line, and cold code that’s almost never touched isn’t wasting icache space sitting next to it.
Whole-binary function reordering.
This is where “reshape the whole binary” becomes literal.
At link time (especially with LTO, which MySQL’s PGO build enables), functions get physically reordered in the final executable so that functions which call each other frequently, or execute in sequence during a hot workload, are placed near each other in memory.
This maximizes instruction-cache and iTLB locality; the CPU’s fetch unit is pulling in a tight cluster of hot functions instead of jumping all over a 100+MB binary.
For something the size of mysqld, this is often the single biggest win, because normal builds place functions in whatever order the source files happen to be compiled, which has no relationship to runtime call patterns.
Indirect-call promotion.
If profile data shows a virtual call or function-pointer call resolves to the same target the overwhelming majority of the time (common in C++ with vtables, e.g. a storage-engine interface with basically only InnoDB registered), the compiler inserts a guarded direct call: “if target == this specific address, call it directly and skip the indirect jump; otherwise fall back to the indirect call.”
Direct calls are cheaper and more predictable for the branch predictor than an indirect jump through a table.
Register allocation and code density trade-offs.
Hot code gets compiled favoring speed, more aggressive unrolling, more registers dedicated to hot-path values.
Cold code, especially with -fprofile-partial-training and cold-path treatment, gets compiled favoring size, fewer registers, less unrolling because it barely executes. So runtime cost there is irrelevant but its footprint in the binary is not free (it still occupies disk/page-cache space and can evict hot lines from cache if placed carelessly, which is exactly why it gets segregated into .text.unlikely rather than just left unoptimized in place).
Switch/jump-table lowering.
A switch statement with many cases can be compiled as a jump table (fast, O(1), but requires a full table load and indirect jump) or as a cascade of compares (slower per-case but better branch prediction if one case dominates).
Profile data tells the compiler which case actually dominates in practice and picks accordingly.
Given the above,  “reshape the whole binary” is not metaphorical. The compiler is redrawing the physical layout of machine code in the executable: which instructions are adjacent to which, which code sections are hot and packed tightly versus cold and shoved to the side, which calls are direct versus indirect, and where the CPU’s fetch/prediction effort gets spent.
None of this requires the values processed during training to resemble production traffic. It only requires the shape of control flow.
Which branches, functions, and paths are frequently exercised to resemble production traffic.
That’s the core reason MTR’s broad-but-different-data coverage transfers well: it walks nearly every code path in mysqld even though the actual queries and data are nothing like a TPCC workload, and control-flow shape is exactly what PGO optimizes for.
 
Why my sysbench-trained build loses and how to do it right.

0
0
votes
Article Rating

Subscribe

Notify of

new follow-up comments
new replies to my comments

Label

{}
[+]

Name*

Email*

Website

Δ

Label

{}
[+]

Name*

Email*

Website

Δ

0 Comments

Oldest

Newest
Most Voted

Resources

RELATED POSTS

October 16, 2026

|

Zelmar Michelini

“MongoDB was slow on Thursday”: answering the app team with mongo-health

PXC

|

October 16, 2026

|

Przemysław Malkowski

When a Small Change Writes Too Much – How A Linux Kernel Improvement Can Strike You in PXC/Galera Workloads

MySQL

|

October 15, 2026

|

Marco Tusa

JavaScript in MySQL: Extending SQL, Not Moving the Application

Far Enough.

Said no pioneer ever.

Get Started

Open source database software from experts who stand with you in production. Forever free from lock-in and other corporate BS.

Connect

© 2026 Percona All Rights Reserved

Database Technology

PostgreSQL

MySQL

MariaDB

MongoDB

Valkey / Redis

Databases on Kubernetes

Monitoring & Management (PMM)

Percona Toolkit

Services

Expert Support

ExpertOps

Expert Consulting

Training

Solution Bundles

Subscription Policies

Use Cases

Cost Optimization

Performance and Reliability

Sovereignty, Security, and Compliance

AI and Future Readiness

Company

About Percona

Partners

Careers

Events

Press Releases

News

Terms of Use

|

Privacy

|

Copyright

|

Legal

|

Security Center

MySQL, PostgreSQL, InnoDB, MariaDB, MongoDB and Kubernetes are trademarks for their respective owners.

© 2026 Percona All Rights Reserved


wpDiscuzInsert

The discussion centers on the dilemma of implementing Profile-Guided Optimization (PGO), focusing on how it fundamentally reshapes compiled binaries rather than simply optimizing a specific workload. PGO is executed in a two-pass build process. The first pass involves compiling with instrumentation using the flag -fprofile-generate, which injects counters for every basic block and branch, accumulating execution counts for every path taken during a training workload. The second pass uses this collected profile data to drive advanced optimization decisions. This process is not aimed at making the training workload faster but rather at allowing the compiler to determine which parts of the code are hot and which are cold, enabling the compiler to restructure the entire binary accordingly.

In the first phase of data collection, the instrumentation records finely grained counters for every edge in the control-flow graph, providing information on the frequency of execution for every branch, loop back-edge, and call site. This per-edge granularity is crucial, as it allows the subsequent phase to make surgical decisions based on actual execution patterns rather than aggregate function call counts.

During the second phase, the compiler utilizes this profile data to perform several transformative optimizations. For function inlining, PGO can override static cost heuristics; a call site executed millions of times can be inlined even if it appears statically expensive, because the runtime benefit necessitates it. It prevents the inclusion of cold code in the binary, ensuring that only frequently executed paths are tightly integrated.

Regarding branch layout, PGO guides the compiler to arrange the machine code such that the hot path serves as a straight line of execution, while cold paths are relocated and pushed out of line, often into separate sections of the binary. This strategy aims to eliminate pipeline bubbles caused by mispredictions, as the highly probable execution path flows continuously while unlikely alternatives are physically segregated. While source code ordering does not dictate machine code layout, the optimization ensures that the resulting binary layout significantly improves execution flow predictability.

Hot and cold function splitting is also achieved by physically separating functions within the binary. A function may be split into a hot part residing in a highly cache-friendly section, such as .text.hot, and a rarely executed error-handling tail placed in a separate section, such as .text.unlikely. This segregation reduces the footprint of cold code, improving instruction cache locality for the dominant execution path.

The concept of whole-binary function reordering becomes literal when leveraging Link-Time Optimization, which PGO facilitates. Functions that frequently execute sequentially during a hot workload are physically reordered in the final executable. This repositions frequently called functions to be adjacent in memory, which maximizes instruction cache and translation lookaside buffer locality by ensuring the CPU's fetch unit retrieves a tight cluster of relevant instructions rather than jumping across a large binary space.

Further optimizations include indirect-call promotion, where if profile data indicates a virtual call or function pointer resolution overwhelmingly favors a single target, the compiler inserts a guarded direct call. This makes the branch predictor more efficient by favoring direct execution. Furthermore, trade-offs are managed between register allocation and code density. Hot code is compiled with aggressive unrolling and more dedicated registers, whereas cold code is compiled to minimize its physical footprint, as its runtime cost is irrelevant.

PGO also influences switch and jump-table lowering by favoring the practical dominant case identified in the profile data, leading to more streamlined branching logic. Ultimately, the core principle is that PGO optimizes the physical layout of machine code—instruction adjacency, code section segregation, and call mechanisms—based solely on the shape of the control flow, which is exactly what is frequently exercised in production traffic. This optimization is effective regardless of whether the training data perfectly mirrors actual production traffic, as what matters is the distribution of control flow.