<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Talha Semerci on Medium]]></title>
        <description><![CDATA[Stories by Talha Semerci on Medium]]></description>
        <link>https://medium.com/@alexzakarov?source=rss-399438fa3156------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RYjbReKGiHmMBxRZ</url>
            <title>Stories by Talha Semerci on Medium</title>
            <link>https://medium.com/@alexzakarov?source=rss-399438fa3156------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:46:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexzakarov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Anatomy of a Hyper-Optimized Binary: Perf, BOLT, and LLVM]]></title>
            <link>https://medium.com/@alexzakarov/anatomy-of-a-hyper-optimized-binary-perf-bolt-and-llvm-056d98c515ae?source=rss-399438fa3156------2</link>
            <guid isPermaLink="false">https://medium.com/p/056d98c515ae</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[llvm-ir]]></category>
            <category><![CDATA[llvm-bolt]]></category>
            <category><![CDATA[perf]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Talha Semerci]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 16:54:17 GMT</pubDate>
            <atom:updated>2026-09-06T11:16:43.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGzF4fT2EWciWm4468X0UQ.png" /></figure><h3>What is Perf?</h3><p><strong>perf</strong> (often referred to as <em>perf_events</em>) is the official, Linux-native performance profiling subsystem and command-line utility. Built directly into the Linux kernel source tree, it provides direct access to CPU hardware performance counters, kernel tracepoints, software events, and dynamic probes—making it the industry standard for low-overhead performance analysis on Linux systems. It categorizes performance events into four primary types:</p><p><strong>Hardware Events:</strong> Sourced directly from CPU hardware Performance Monitoring Units (PMUs), such as cycles, instructions, cache-misses, and branch-misses.</p><p><strong>Software Events:</strong> Kernel-level software abstractions, including page-faults, context-switches, and cpu-migrations.</p><p><strong>Tracepoints:</strong> Static measurement hooks embedded in Linux kernel subsystems (e.g., sched:sched_switch, syscalls:sys_enter_read).</p><p><strong>Dynamic Probes (</strong><strong>kprobes / </strong><strong>uprobes):</strong> Custom hooks dynamically inserted at runtime into arbitrary kernel or user-space function boundaries.</p><h4>Primary Subcommands &amp; Workflow</h4><p>perf utilizes a Git-like CLI structure with subcommands tailored to different performance investigation scopes:</p><h4>1. perf list — Discovering Available Events</h4><p>Displays all hardware, software, tracepoint, and PMU events supported by your specific CPU architecture and kernel version.</p><h4>2. perf stat — Macro-Level Counting</h4><p>Executes a target application and counts total performance events throughout its lifetime. It provides immediate, high-level metrics without collecting fine-grained call stacks.</p><h4>3. perf record &amp; perf report — Statistical Sampling</h4><p>Captures detailed stack traces and event locations by sampling CPU states at specified frequencies or event thresholds.</p><h4>4. perf top — Real-Time Profiling</h4><p>Functions similarly to the standard Linux top utility, but displays system-wide CPU cycles and function hotspots in real time across all running processes.</p><h4>5. perf annotate — Source &amp; Assembly Hotspot Inspection</h4><p>Disassembles hotspot functions from recorded profile data, annotating exact assembly instructions with percentages of CPU time, memory stalls, or cache misses spent on each instruction.</p><h3>Types of Optimization Techniques</h3><p><strong>LTO (Link-Time Optimization):</strong> LTO defers optimization decisions until the linking phase, providing whole-program visibility across separate translation units to enable aggressive cross-module inlining and dead code elimination.</p><p><strong>IPGO (Instrumentation Profile-Guided Optimization):</strong> IPGO injects explicit counters into the code during compilation to record exact execution counts with maximum accuracy, though at the cost of high runtime overhead.</p><p><strong>S-PGO (Sample-Profile Guided Optimization / AutoFDO):</strong> S-PGO uses external profilers like Linux perf to statistically sample production execution without modifying the binary, achieving near-zero runtime overhead.</p><p><strong>CSS-PGO (Context-Sensitive Sampling PGO):</strong> CSS-PGO embeds lightweight pseudo-probes during compilation to ensure hardware sampling traces accurately map back to complex, inlined call-stack contexts.</p><p><strong>HW-PGO (Hardware-Assisted / Memory-Profile PGO):</strong> HW-PGO leverages advanced hardware performance counters to analyze memory access patterns and optimize virtual table (v-table) lookups to reduce CPU cache misses.</p><p><strong>Temporal PGO:</strong> Temporal PGO reorganizes code based on the chronological sequence of application startup to minimize page faults and drastically reduce initial loading times.</p><p><strong>High-Level PGO (IR-PGO):</strong> High-Level PGO operates on the compiler’s Intermediate Representation (IR) to make semantic optimization decisions like function inlining and loop unrolling.</p><p><strong>Low-Level PGO (Binary-Level / Post-Link PGO):</strong> Low-Level PGO optimizes raw compiled machine code after linking by reordering basic blocks and instruction layouts to maximize CPU instruction cache efficiency.</p><h3>Speeding Up Your Binary with LLVM BOLT</h3><p><strong>BOLT (Binary Optimization and Layout Tool)</strong> is a static post-link binary optimizer developed by Meta (Facebook). It leverages Linux <strong>perf</strong> to capture low-overhead hardware profiling data—such as Intel Last Branch Records (LBR)—directly from production environments, converting those execution traces to rewrite binary layouts and eliminate hardware-level CPU front-end bottlenecks like I-cache misses, I-TLB stalls, and branch mispredictions.</p><h4><strong>1. Basic Block Reordering:</strong></h4><p>Arranges frequently executed (hot) basic blocks sequentially to maximize fall-through branch prediction and pipeline efficiency.</p><h4>2. <strong>Hot/Cold Splitting:</strong></h4><p>Separates rarely executed (cold) blocks from the main function body and relocates them to distant memory regions.</p><h4>3. <strong>Function Placement (HFSort):</strong></h4><p>Reorders hot functions across the binary based on Call Graph topology to minimize L1 I-cache and I-TLB misses.</p><h4>4. <strong>Indirect Call Promotion (ICP):</strong></h4><p>Uses profile data to transform runtime indirect calls into direct conditional jumps, reducing branch mispredictions.</p><h4><strong>5. PLT Optimization:</strong></h4><p>Reduces dynamic linker resolution overhead and optimizes calls going through the Procedure Linkage Table.</p><h4><strong>6. Identical Code Folding (ICF):</strong></h4><p>Detects and merges identical functions and code blocks at the binary level beyond standard linker capabilities.</p><h4><strong>7. Sample-Based Profile Aggregation:</strong></h4><p>Accurately maps low-overhead hardware performance counter data (Intel LBR) directly to disassembled machine code.</p><h4><strong>8. Metadata &amp; Debug Info Preservation:</strong></h4><p>Consistently updates C++ exception handling tables (.eh_frame) and DWARF debug symbol offsets during code transformation.</p><h4><strong>9. Relocations Mode Support:</strong></h4><p>Allows unrestricted function re-ordering, splitting, and expansion for binaries built with relocation metadata.</p><h3>Let’s Start to Optimize!</h3><h4>Prerequisites</h4><ul><li>LLVM 15+ with BOLT enabled (llvm-bolt, merge-fdata, perf2bolt)</li><li>A Linux environment (BOLT works with ELF binaries; Windows PE/COFF is not yet supported)</li><li>Your project compiled with Clang</li></ul><p>We will use an example code to check if we can optimize it by using IPGO:</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;cstdlib&gt;<br><br>// Heavy function forced out-of-line to demonstrate layout splitting<br>__attribute__((noinline)) void cold_path() {<br>    std::cout &lt;&lt; &quot;This is a cold path, rarely executed.\n&quot;;<br>}<br><br>__attribute__((noinline)) void hot_path(int value) {<br>    // Highly predictable math loop<br>    volatile int x = 0;<br>    for (int i = 0; i &lt; 1000; ++i) {<br>        x += value * i;<br>    }<br>}<br><br>int main(int argc, char* argv[]) {<br>    // Use an argument to simulate real-world data variation<br>    int iterations = (argc &gt; 1) ? std::atoi(argv[1]) : 500000;<br><br>    for (int i = 0; i &lt; iterations; ++i) {<br>        if (i % 100 == 0) {<br>            cold_path();<br>        } else {<br>            hot_path(i);<br>        }<br>    }<br>    return 0;<br>}<br></pre><h4>Step 1: Build with Relocation Info</h4><p>BOLT needs linker-inserted relocations to be able to disassemble and reassemble the binary. Pass “— emit-relocs” to the linker:</p><pre>cmake -B build -G Ninja \<br>  -DCMAKE_BUILD_TYPE=Release \<br>  -DCMAKE_C_COMPILER=clang \<br>  -DCMAKE_CXX_COMPILER=clang++ \<br>  -DCMAKE_EXE_LINKER_FLAGS=&quot;-Wl,--emit-relocs&quot;</pre><pre>cmake --build build --target app</pre><p>Why “— emit-relocs”? Normally the linker resolves all relocations and discards them. This flag tells it to keep them in a special .rela.text section so BOLT can later remap every instruction to its original symbol.</p><h4>Step 2: Create an Instrumented Binary</h4><p>Instrumentation mode injects profiling counters into every basic block of the binary:</p><pre>llvm-bolt app<br>  -o app.inst<br>  -instrument<br>  -instrumentation-file=./bolt_prof.fdata</pre><p>This produces app.inst — a copy of your binary with built-in profiling. The -instrumentation-file flag tells it where to dump the profile data at runtime.</p><h4>Step 3: Run Your Workload</h4><pre>./app.inst input1.mod<br>./app.inst input2.mod<br>./app.inst input3.mod</pre><p>Each run appends profile data to bolt_prof.fdata. For long-running services, you can use “— instrumentation-sleep-time” to periodically flush profiles without stopping the process:</p><pre>llvm-bolt app -o app.inst -instrument \<br>  -instrumentation-sleep-time=60 \<br>  -instrumentation-file=./bolt_prof.fdata</pre><p><strong>Tip:</strong> The profile file can grow large. Point it to a location with sufficient disk space.</p><h4>Step 4: Merge Profile Data (Optional)</h4><p>If you ran the instrumented binary multiple times, merge the profiles into a single file:</p><pre>merge-fdata ./bolt_prof.fdata &gt; prof.fdata</pre><h4>Step 5: Optimize Using the Profile</h4><p>Feed the profile back into BOLT to optimize the original binary (not the instrumented one):</p><pre>llvm-bolt build/app<br>  -o app.bolt<br>  -data=prof.fdata<br>  -reorder-blocks=ext-tsp<br>  -reorder-functions=hfsort<br>  -split-functions<br>  -split-all-cold<br>  -dyno-stats</pre><h4>Step 6: Check The Performans and CPU Metrics</h4><pre>perf stat -e task-clock,cycles,instructions,branches,branch-misses ./app</pre><h4>Original Executable Metrics</h4><pre> Performance counter stats for &#39;./test_llvm_bolt&#39;:<br><br>         359931300      task-clock                       #    0.927 CPUs utilized             <br>     &lt;not counted&gt;      cycles                                                                  (0.00%)<br>     &lt;not counted&gt;      instructions                                                            (0.00%)<br>     &lt;not counted&gt;      branches                                                                (0.00%)<br>     &lt;not counted&gt;      branch-misses                                                           (0.00%)<br><br>       0.388449584 seconds time elapsed<br><br>       0.314409000 seconds user<br>       0.073362000 seconds sys</pre><h4>Optimized Executable Metrics</h4><pre> Performance counter stats for &#39;./optimized.bolt&#39;:<br><br>         343672900      task-clock                       #    0.970 CPUs utilized             <br>     &lt;not counted&gt;      cycles                                                                  (0.00%)<br>     &lt;not counted&gt;      instructions                                                            (0.00%)<br>     &lt;not counted&gt;      branches                                                                (0.00%)<br>     &lt;not counted&gt;      branch-misses                                                           (0.00%)<br><br>       0.354181836 seconds time elapsed<br><br>       0.265924000 seconds user<br>       0.078792000 seconds sys</pre><p>You can see, we have reduced task clocks and achived<strong> 7.89%</strong> optimized binary.</p><p>Reaching peak hardware performance requires going beyond traditional compilers. By feeding production <strong>perf</strong> traces into <strong>LLVM BOLT</strong>, you can restructure fully compiled binaries, eliminate CPU front-end bottlenecks, and unlock performance gains that standard compilation leaves on the table.</p><p><strong><em>Thank you for reading! If you enjoyed this deep dive into binary optimization, feel free to give it a clap, leave a comment with your own benchmark experiences, and share it with fellow low-level enthusiasts. Happy optimizing!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*-8lbHykF-RrX1f__PajaSw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=056d98c515ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>