<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="/feed.xml" rel="self" type="application/atom+xml" /><link href="/" rel="alternate" type="text/html" /><updated>2026-11-26T06:21:17+00:00</updated><id>/feed.xml</id><title type="html">Compiler Research</title><subtitle>Write an awesome description for your new site here. You can edit this line in _config.yml. It will appear in your document head meta (for Google search results) and in your feed.xml site description.
</subtitle><entry><title type="html">One copy is enough: deduplicating source locations in Clang modules</title><link href="/blogs/cppalliance26_ayokunle_amodu_sloc_dedup_final/" rel="alternate" type="text/html" title="One copy is enough: deduplicating source locations in Clang modules" /><published>2026-11-26T00:00:00+00:00</published><updated>2026-11-26T00:00:00+00:00</updated><id>/blogs/cppalliance26-ayokunle-amodu-sloc-dedup-final</id><content type="html" xml:base="/blogs/cppalliance26_ayokunle_amodu_sloc_dedup_final/"><![CDATA[<div class="custom-banner-wrapper" role="img" aria-label="">
  <div class="custom-banner-flex">
    <div class="banner-logo">
      <img src="/images/cppalliance-logo.svg" alt="Left Logo" />
    </div>

    <div class="banner-separator" aria-hidden="true">
      @
    </div>

    <div class="banner-logo logo-right-bg">
      <img src="/images/cr-logo.png" alt="Right Logo" />
    </div>
  </div>

  
  <div class="banner-caption" role="heading" aria-level="2">
    
  </div>
  
</div>

<style>
  .custom-banner-wrapper {
    --b-height: 20vh;
    width: 100%;
    max-width: 95%;
    margin: 0 auto;
    padding: 1.5rem 0;
  }

  .custom-banner-flex {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 3rem;
  }

  .banner-logo img {
    height: calc(var(--b-height) * 0.85);
    width: auto;
    max-width: 30vw;
    min-height: 50px;
    object-fit: contain;
  }

  /* Keep the white background for the right logo badge if needed */
  .logo-right-bg img {
    padding: 8px;
    background: #fff;
    border-radius: 4px;
  }

  .banner-separator {
    font-size: calc(var(--b-height) * 0.5);
    font-weight: 700;
    color: #000;
  }

  .banner-caption {
    text-align: center;
    margin-top: 1rem;
    font-family: Georgia, serif;
    font-size: calc(var(--b-height) * 0.25);
    color: #111;
  }

  @media (max-width: 768px) {
    .custom-banner-wrapper { --b-height: 15vh; }
    .custom-banner-flex { gap: 1.5rem; }
  }

  @media (max-width: 480px) {
    .custom-banner-flex { flex-direction: column; gap: 1rem; }
  }
</style>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fatal error: ran out of source locations
</code></pre></div></div>

<p>That is how a large modular build can end. Clang gives every byte of source it
sees a number, and those numbers live in a single 32-bit space, about two
billion addresses for the whole compilation. When the space is full, the build
stops. I spent my CppAlliance Fellowship with Vassil Vassilev working on one of
the biggest reasons modular builds fill it: the same header being paid for over
and over. My <a href="/blogs/optimize_source_locations_clang_modules_Ayokunle_Amodu_blog/">first post</a>
introduced the project; this one covers how it turned out.</p>

<h2 id="where-the-space-goes">Where the space goes</h2>

<p>When a module is built, Clang saves it as a PCM, and each file the module saw
gets its own range of source locations inside it. Now take two modules that
both textually include the same header:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// module A           // module B</span>
<span class="cp">#include</span> <span class="cpf">"shared.h"</span><span class="c1">   #include "shared.h"</span><span class="cp">
</span><span class="kt">int</span> <span class="nf">a_fn</span><span class="p">();</span>           <span class="kt">int</span> <span class="nf">b_fn</span><span class="p">();</span>
</code></pre></div></div>

<p>Each PCM carries its own copy of <code class="language-plaintext highlighter-rouge">shared.h</code>. Import both and the translation
unit pays for <code class="language-plaintext highlighter-rouge">shared.h</code> twice. Import fifty modules and it pays fifty times,
even though every copy is byte-for-byte identical.</p>

<p>The clean answer is to make <code class="language-plaintext highlighter-rouge">shared.h</code> a module of its own, so everyone shares
one copy. But the headers that hurt most are system and third-party headers you
don’t own, or config headers that have to stay textual. That is where the
duplication lives.</p>

<p>The other answer on the table was to widen source locations to 64 bits. There
are <a href="https://discourse.llvm.org/t/revisiting-64-bit-source-locations/86556">RFCs</a>
for it, but it touches a type that is used everywhere in Clang. Removing the
duplicates goes after the same pressure without that change.</p>

<h2 id="first-try-catch-it-on-load">First try: catch it on load</h2>

<p>Duplicates only meet when modules are loaded together, so that is where I
started. As each module loads, the patch remembers where every file first
landed. When a later module brings the same file, it reserves no new space for
it and points that copy’s locations at the first one.</p>

<p>It worked. At the <a href="/assets/presentations/Ayokunle_Amodu_CppAlliance_Fellowship2026_midterm_presentation.pdf">midterm</a>,
a Boost build pulling in asio, beast, spirit and hana dropped from 47.5 MB to
28.4 MB of loaded source-location space. On <a href="https://root.cern">ROOT</a>, it
reclaimed about a third.</p>

<p>The cost showed up when I measured properly. A module’s space is reserved
before any of its files are placed, so the duplicates have to be known first.
That meant scanning every file entry of every module at load time. Clang
normally loads these lazily, and most are never touched. On ROOT, module
writing went up 6.1% in instructions and peak memory went up 5.1%. On top of
that, a single base offset per module became a piecewise map that had to work
in both directions. It was too much machinery for what it bought.</p>

<h2 id="second-try-never-write-the-copy">Second try: never write the copy</h2>

<p>So after the midterm I moved the work to the other end. Modules are built in
dependency order, so when module B is being written, the module that already
owns <code class="language-plaintext highlighter-rouge">shared.h</code> is usually loaded. If it is, B doesn’t write its own copy at
all. Every location that would have pointed into B’s copy is rewritten to point
into the owner’s copy instead.</p>

<p>Nothing is scanned at load, and there are no gaps to remap. The reader just
follows the location to the owner.</p>

<p>On ROOT, with 88 dictionaries and runtime C++ modules:</p>

<ul>
  <li>loaded source-location space went from <strong>75.33 MB to 61.02 MB</strong>, a <strong>19%</strong> saving</li>
  <li>peak memory went down <strong>3.7%</strong></li>
  <li>PCM size went down <strong>4.4%</strong></li>
  <li>compile time stayed flat</li>
</ul>

<p>The biggest savings came from headers like <code class="language-plaintext highlighter-rouge">c++config.h</code>, <code class="language-plaintext highlighter-rouge">features.h</code> and
<code class="language-plaintext highlighter-rouge">sys/cdefs.h</code>. These are exactly the system headers nobody can turn into
modules, so every PCM used to carry its own copy.</p>

<p>This is <a href="https://github.com/llvm/llvm-project/pull/209795">#209795</a>.</p>

<h2 id="what-review-found">What review found</h2>

<p>Getting numbers is one thing. Getting a serialization change into Clang is
another, and review is where most of the real work happened.</p>

<p>Jonas Hahnfeld tested it on ROOT and Qiongsi Wu on Apple SDK workloads, and
their reports kept me honest. A crash, a dependency-scanning slowdown that
turned out to be path canonicalization on every input file, and two
location-ordering bugs all got fixed at the root, and reproducers from
reviewers became regression tests.</p>

<p>One problem didn’t go away. Two copies of a header can be byte-for-byte
identical and still not mean the same thing, because they were compiled under
different preprocessor state. A declaration behind an <code class="language-plaintext highlighter-rouge">#ifdef</code>, or a
<code class="language-plaintext highlighter-rouge">#pragma diagnostic</code>, can differ between the two. Sharing their locations
doesn’t capture that. Every fix I tried ended up as another band-aid, and I
didn’t want to land something I couldn’t fully stand behind.</p>

<h2 id="narrowing-it-down-module-maps">Narrowing it down: module maps</h2>

<p>While working through that, I was looking at
<a href="https://github.com/llvm/llvm-project/pull/116374">#116374</a>, which already
drops module maps that nothing references. Module maps are duplicated the same
way: every PCM built from a shared map carries its own copy. The ones that are
referenced can’t be dropped, but they can be redirected to a single copy, the
same idea as before.</p>

<p>A module map is a much easier thing to share than a header. It has no
declarations, no macros and no preprocessor state, so there is far less to
prove equivalent. It also doesn’t depend on how bottom-up a codebase is
modularized. If anything, the more you modularize, the more copies there are.</p>

<p>On ROOT it reclaims about <strong>12%</strong> of loaded source-location space, and all 88
dictionaries build with assertions on. It is up for review as
<a href="https://github.com/llvm/llvm-project/pull/240442">#240442</a>.</p>

<h2 id="where-it-stands">Where it stands</h2>

<ul>
  <li><a href="https://github.com/llvm/llvm-project/pull/240442">#240442</a>, module map
deduplication, is open and under review.</li>
  <li><a href="https://github.com/llvm/llvm-project/pull/209795">#209795</a>, header
deduplication, is open with one question left around preprocessor state.</li>
</ul>

<p>The header work isn’t abandoned. The module map patch stands on its own, and if
per-copy preprocessor state can be handled cleanly, the header saving can stack
on top of it. The work was also featured as a poster at CppCon 2026.</p>

<h2 id="related-links">Related links</h2>

<ul>
  <li><a href="/blogs/optimize_source_locations_clang_modules_Ayokunle_Amodu_blog/">Announcement blog post</a></li>
  <li><a href="/assets/docs/Ayokunle_Amodu_Proposal_2026.pdf">Project proposal</a></li>
  <li><a href="/assets/presentations/Ayokunle_Amodu_CppAlliance_Fellowship2026_initial_presentation.pdf">Fellowship initial presentation</a></li>
  <li><a href="/assets/presentations/Ayokunle_Amodu_CppAlliance_Fellowship2026_midterm_presentation.pdf">Fellowship midterm presentation</a></li>
  <li><a href="/assets/presentations/Ayokunle_Amodu_CppAlliance_Fellowship2026_final_presentation.html">Fellowship final presentation</a></li>
  <li><a href="/assets/presentations/Ayokunle_Amodu-CRCon26_One_Copy_Is_Enough.html">CRCon26 slides</a></li>
</ul>

<h2 id="thanks">Thanks</h2>

<p>Thank you to Vassil Vassilev for his guidance throughout, to Haojian Wu, Jan
Svoboda, Corentin Jabot, Chuanqi Xu and Reid Kleckner for their careful review,
to Jonas Hahnfeld and Qiongsi Wu for testing, and to the C++ Alliance for
supporting the fellowship.</p>]]></content><author><name>Ayokunle Amodu</name></author><category term="cppalliance" /><category term="clang" /><category term="llvm" /><category term="modules" /><category term="serialization" /><category term="source-locations" /><summary type="html"><![CDATA[A CppAlliance Fellowship 2026 wrap-up: why modular builds run out of source locations, two ways to stop paying for the same header twice, and the 19% of address space we got back on ROOT.]]></summary></entry><entry><title type="html">Process High-Impact clang-tidy and Clang Static Analyzer Requests: Final Results</title><link href="/blogs/cppalliance26_peiqi_li_clang_tidy_wrapup/" rel="alternate" type="text/html" title="Process High-Impact clang-tidy and Clang Static Analyzer Requests: Final Results" /><published>2026-11-24T00:00:00+00:00</published><updated>2026-11-24T00:00:00+00:00</updated><id>/blogs/cppalliance26-peiqi-li-wrapup</id><content type="html" xml:base="/blogs/cppalliance26_peiqi_li_clang_tidy_wrapup/"><![CDATA[<div class="custom-banner-wrapper" role="img" aria-label="">
  <div class="custom-banner-flex">
    <div class="banner-logo">
      <img src="/images/cppalliance-logo.svg" alt="Left Logo" />
    </div>

    <div class="banner-separator" aria-hidden="true">
      @
    </div>

    <div class="banner-logo logo-right-bg">
      <img src="/images/cr-logo.png" alt="Right Logo" />
    </div>
  </div>

  
  <div class="banner-caption" role="heading" aria-level="2">
    
  </div>
  
</div>

<style>
  .custom-banner-wrapper {
    --b-height: 20vh;
    width: 100%;
    max-width: 95%;
    margin: 0 auto;
    padding: 1.5rem 0;
  }

  .custom-banner-flex {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 3rem;
  }

  .banner-logo img {
    height: calc(var(--b-height) * 0.85);
    width: auto;
    max-width: 30vw;
    min-height: 50px;
    object-fit: contain;
  }

  /* Keep the white background for the right logo badge if needed */
  .logo-right-bg img {
    padding: 8px;
    background: #fff;
    border-radius: 4px;
  }

  .banner-separator {
    font-size: calc(var(--b-height) * 0.5);
    font-weight: 700;
    color: #000;
  }

  .banner-caption {
    text-align: center;
    margin-top: 1rem;
    font-family: Georgia, serif;
    font-size: calc(var(--b-height) * 0.25);
    color: #111;
  }

  @media (max-width: 768px) {
    .custom-banner-wrapper { --b-height: 15vh; }
    .custom-banner-flex { gap: 1.5rem; }
  }

  @media (max-width: 480px) {
    .custom-banner-flex { flex-direction: column; gap: 1rem; }
  }
</style>

<p>Over the past six months I worked on clang-tidy and the Clang Static Analyzer as
a CppAlliance Fellow. The project started from a simple problem: both tools have
a long backlog of diagnostics that are wrong in practice — false positives,
missed bugs, and fix-its that break code. When a check is noisy, people add
<code class="language-plaintext highlighter-rouge">NOLINT</code> or turn it off, and the tool stops being useful. I spent the fellowship
fixing the cases that caused the most friction and getting the fixes merged
upstream.</p>

<h2 id="clang-tidy">clang-tidy</h2>

<p>Most of the merged work is in clang-tidy. The first group was about false
positives. <a href="https://github.com/llvm/llvm-project/pull/199189"><code class="language-plaintext highlighter-rouge">modernize-use-using</code> #199189</a>
was rewriting typedefs inside <code class="language-plaintext highlighter-rouge">extern "C"</code> into <code class="language-plaintext highlighter-rouge">using</code>, which is invalid C in
mixed-language headers. <a href="https://github.com/llvm/llvm-project/pull/199905"><code class="language-plaintext highlighter-rouge">bugprone-use-after-move</code> #199905</a>
missed the <code class="language-plaintext highlighter-rouge">DerivedToBase</code> cast hidden inside <code class="language-plaintext highlighter-rouge">std::forward</code> and reported a
partial move as a full move. <a href="https://github.com/llvm/llvm-project/pull/198085"><code class="language-plaintext highlighter-rouge">misc-redundant-expression</code> #198085</a>
compared distinct aliases after desugaring and called them redundant.
<a href="https://github.com/llvm/llvm-project/pull/220548"><code class="language-plaintext highlighter-rouge">readability-trailing-comma</code> #220548</a>
looked at the semantic form of empty initializer lists instead of what the user
wrote. And <a href="https://github.com/llvm/llvm-project/pull/225585"><code class="language-plaintext highlighter-rouge">modernize-use-nullptr</code> #225585</a>
started warning on every C++20 spaceship comparison after libstdc++ 16 renamed
an internal type.</p>

<p>The second group was fix-its. <a href="https://github.com/llvm/llvm-project/pull/208682">clangd #208682</a>
used to apply clang-tidy edits naively, so two adjacent removals could glue
tokens together:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">return</span> <span class="p">(</span><span class="mi">0</span><span class="p">);</span>   <span class="c1">// two removals</span>
<span class="n">return0</span><span class="p">;</span>      <span class="c1">// what clangd applied before</span>
</code></pre></div></div>

<p>I moved <code class="language-plaintext highlighter-rouge">mergeFixits()</code> from <code class="language-plaintext highlighter-rouge">DiagnosticRenderer</code> into <code class="language-plaintext highlighter-rouge">clang::edit</code>, and clangd
now uses the same merge logic as the compiler. The other fix-it issue was
<a href="https://github.com/llvm/llvm-project/pull/227984">#227984</a>: a fix-it on a
one-character string from a macro replaced the macro with a raw literal. The
check now keeps the warning and drops the fix-it. In both cases the diagnostic
is still useful; only the unsafe edit is gone.</p>

<h2 id="clangd">clangd</h2>

<p>Most people don’t run clang-tidy from the command line; they see it through
clangd. Query-based custom checks let projects write their own rules as
clang-query matchers in <code class="language-plaintext highlighter-rouge">.clang-tidy</code>, but they only ran in the CLI. In
<a href="https://github.com/llvm/llvm-project/pull/216336">#216336</a> I wired them into
clangd. The feature is off by default and only runs when <code class="language-plaintext highlighter-rouge">FastCheckFilter</code> is
<code class="language-plaintext highlighter-rouge">Loose</code> or <code class="language-plaintext highlighter-rouge">None</code>, so a slow matcher cannot slow down a session that has not
opted in. The option is documented on the clangd website
(<a href="https://github.com/llvm/clangd-www/pull/146">clangd-www #146</a>).</p>

<p>LineFilter (<a href="https://github.com/llvm/llvm-project/pull/202575">#202575</a>) did
not end as a patch. I implemented the requested option, but review showed that
the request was a workaround. What users actually need is filtering by where a
macro is defined. That is new configuration surface, so the next step is an RFC
for <code class="language-plaintext highlighter-rouge">ExcludeMacroExpansionRegex</code>, not a narrow feature hidden in a config file.</p>

<h2 id="the-analyzer">The analyzer</h2>

<p>The second half was the Clang Static Analyzer, where the bug is usually in how a
checker models program state, not in a matcher. I have three patches in review:
<a href="https://github.com/llvm/llvm-project/pull/221587">NewDeleteLeaks #221587</a> was a
false negative — pointers stored in heap fields were treated as escaped, so real
leaks were not reported. <a href="https://github.com/llvm/llvm-project/pull/225048">unix.Malloc #225048</a>
was a false positive — <code class="language-plaintext highlighter-rouge">LocAsInteger</code> was lost through identity operations, so
the allocation looked leaked. <a href="https://github.com/llvm/llvm-project/pull/231736">CStringChecker #231736</a>
is the one I want to explain.</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="nc">container</span> <span class="p">{</span> <span class="kt">int</span> <span class="o">*</span><span class="n">head</span><span class="p">;</span> <span class="p">};</span>

<span class="kt">void</span> <span class="n">test</span><span class="p">(</span><span class="k">struct</span> <span class="nc">container</span> <span class="o">*</span><span class="n">c</span><span class="p">)</span> <span class="p">{</span>
  <span class="kt">int</span> <span class="o">*</span><span class="n">tail</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="n">memset</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="o">*</span><span class="n">c</span><span class="p">));</span>
  <span class="n">clang_analyzer_eval</span><span class="p">(</span><span class="n">c</span><span class="o">-&gt;</span><span class="n">head</span> <span class="o">==</span> <span class="mi">0</span><span class="p">);</span>
  <span class="c1">// before: TRUE and FALSE</span>
  <span class="c1">// after:  TRUE</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">c</span><span class="o">-&gt;</span><span class="n">head</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
    <span class="o">*</span><span class="n">tail</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>   <span class="c1">// null-dereference false positive</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Before the fix, the analyzer says both TRUE and FALSE. Both paths stay alive, so
it reports a null dereference on code that cannot run. <code class="language-plaintext highlighter-rouge">c</code> is a pointer
parameter, so the extent is only known to be at least <code class="language-plaintext highlighter-rouge">sizeof(*c)</code>, not exactly
that size. The checker cannot model the zeroing, falls back to invalidation, and
throws away everything it knew about <code class="language-plaintext highlighter-rouge">*c</code>. The fix binds a zeroed value whenever
the length provably covers the pointee; non-zero fills and symbolic extents keep
the old behavior.</p>

<h2 id="what-changed">What changed</h2>

<p>Nine PRs are merged: eight in <code class="language-plaintext highlighter-rouge">llvm/llvm-project</code> and one in <code class="language-plaintext highlighter-rouge">llvm/clangd-www</code>.
Six widely used clang-tidy checks are corrected, two cases that were breaking
builds or upgrades are fixed, and clangd now applies fix-its safely and can show
custom checks in the editor. The merged fixes reach users through tools they
already run; no new tool or configuration is required.</p>

<p>The three analyzer patches are still in review. When they land, they will report
heap-field leaks that used to be silent and remove some false leak and
null-dereference reports. I also presented the work at
<a href="https://compiler-research.org/crcon2026/">CompilerResearchCon 2026</a>; the
<a href="https://compiler-research.org/assets/presentations/Peiqi_Li-CRCon26_Process_High-Impact_clang-tidy_and_Clang_Static_Analyzer.pdf">slides</a>
are a shorter overview of the same work.</p>

<h2 id="next">Next</h2>

<p>Next is landing the three analyzer patches and writing the
<code class="language-plaintext highlighter-rouge">ExcludeMacroExpansionRegex</code> RFC that came out of the LineFilter review. After
that I would like to keep contributing upstream.</p>

<p>Thanks to my mentors, Vassil Vassilev, Aaron Jomy, and Martin Vassilev, for their
guidance, and to the LLVM reviewers for their careful feedback.</p>]]></content><author><name>Peiqi Li</name></author><category term="cppalliance" /><category term="clang-tidy" /><category term="clang" /><category term="llvm" /><category term="static-analyzer" /><category term="clangd" /><summary type="html"><![CDATA[A CppAlliance Fellowship 2026 wrap-up: nine merged PRs in clang-tidy and clangd, three Clang Static Analyzer patches in review, and the cases behind them.]]></summary></entry><entry><title type="html">Implementing Missing C and C++ Language Features in Clang: Final Report</title><link href="/blogs/Implement_missing_C++26_features_in_Clang_Muhammad_Bassiouni_final_blog/" rel="alternate" type="text/html" title="Implementing Missing C and C++ Language Features in Clang: Final Report" /><published>2026-11-23T00:00:00+00:00</published><updated>2026-11-23T00:00:00+00:00</updated><id>/blogs/Implement-missing-C-and-C++-features-in-Clang-final</id><content type="html" xml:base="/blogs/Implement_missing_C++26_features_in_Clang_Muhammad_Bassiouni_final_blog/"><![CDATA[<div class="custom-banner-wrapper" role="img" aria-label="">
  <div class="custom-banner-flex">
    <div class="banner-logo">
      <img src="/images/cppalliance-logo.svg" alt="Left Logo" />
    </div>

    <div class="banner-separator" aria-hidden="true">
      @
    </div>

    <div class="banner-logo logo-right-bg">
      <img src="/images/cr-logo_old.png" alt="Right Logo" />
    </div>
  </div>

  
  <div class="banner-caption" role="heading" aria-level="2">
    
  </div>
  
</div>

<style>
  .custom-banner-wrapper {
    --b-height: 20vh;
    width: 100%;
    max-width: 95%;
    margin: 0 auto;
    padding: 1.5rem 0;
  }

  .custom-banner-flex {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 3rem;
  }

  .banner-logo img {
    height: calc(var(--b-height) * 0.85);
    width: auto;
    max-width: 30vw;
    min-height: 50px;
    object-fit: contain;
  }

  /* Keep the white background for the right logo badge if needed */
  .logo-right-bg img {
    padding: 8px;
    background: #fff;
    border-radius: 4px;
  }

  .banner-separator {
    font-size: calc(var(--b-height) * 0.5);
    font-weight: 700;
    color: #000;
  }

  .banner-caption {
    text-align: center;
    margin-top: 1rem;
    font-family: Georgia, serif;
    font-size: calc(var(--b-height) * 0.25);
    color: #111;
  }

  @media (max-width: 768px) {
    .custom-banner-wrapper { --b-height: 15vh; }
    .custom-banner-flex { gap: 1.5rem; }
  }

  @media (max-width: 480px) {
    .custom-banner-flex { flex-direction: column; gap: 1rem; }
  }
</style>

<h2 id="introduction">Introduction</h2>

<p>I am Muhammad Bassiouni, a maintainer of <a href="https://libc.llvm.org/">LLVM libc</a>
and a C++ Alliance Fellowship 2026 contributor. During the fellowship I worked
on implementing standards papers that <code class="language-plaintext highlighter-rouge">Clang</code> was still missing. This post
wraps up the project that I introduced in my
<a href="/blogs/Implement_missing_C++26_features_in_Clang_Muhammad_Bassiouni_blog/">announcement blog post</a>,
and follows the talk I gave at
<a href="/crcon2026/">CompilerResearchCon 2026</a>
(<a href="/assets/presentations/Muhammad_Bassiouni-CRCon26_Missing_C_and_CXX_Features_in_Clang.pdf">slides</a>).</p>

<p><strong>Mentors</strong>: Vassil Vassilev, Aaron Jomy</p>

<h2 id="the-fellowship-at-a-glance">The Fellowship at a Glance</h2>

<p>The project was candidate-driven: I proposed the papers to implement, and
adjusted the plan as the upstream situation of each paper became clear. In the
end I worked on four papers:</p>

<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Paper</th>
      <th>Feature</th>
      <th>Outcome</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td><a href="https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3356.htm">C2y N3356</a></td>
      <td>Declarations in <code class="language-plaintext highlighter-rouge">if</code> / <code class="language-plaintext highlighter-rouge">switch</code> conditions</td>
      <td><strong>Landed upstream</strong></td>
    </tr>
    <tr>
      <td>2</td>
      <td><a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1814r0.html">C++20 P1814R0</a></td>
      <td>CTAD for alias templates</td>
      <td>Blocked: open core issue</td>
    </tr>
    <tr>
      <td>3</td>
      <td>C++23/26 constexpr <code class="language-plaintext highlighter-rouge">&lt;cmath&gt;</code></td>
      <td>constexpr math in <code class="language-plaintext highlighter-rouge">Clang</code></td>
      <td>Blocked: pending design</td>
    </tr>
    <tr>
      <td>4</td>
      <td><a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p3668r4.html">C++2d P3668R4</a></td>
      <td>Defaulted postfix <code class="language-plaintext highlighter-rouge">++</code> / <code class="language-plaintext highlighter-rouge">--</code></td>
      <td><strong>Landed upstream</strong></td>
    </tr>
  </tbody>
</table>

<p>Two papers landed, and two were blocked for reasons outside of the
fellowship’s control. When I presented the work at CRCon, the P3668R4 PR was
still under review; it has been merged since.</p>

<h2 id="c2y-n3356-declarations-in-if-and-switch-conditions">C2y N3356: Declarations in <code class="language-plaintext highlighter-rouge">if</code> and <code class="language-plaintext highlighter-rouge">switch</code> Conditions</h2>

<h3 id="what-the-paper-adds">What the paper adds</h3>

<p>N3356 allows a declaration in the condition of <code class="language-plaintext highlighter-rouge">if</code> and <code class="language-plaintext highlighter-rouge">switch</code> statements in
<code class="language-plaintext highlighter-rouge">C</code>. It looks similar to the <code class="language-plaintext highlighter-rouge">C++17</code> feature, but it is not the same: the first
clause must be a declaration and can’t be empty, and the second clause can only
be an expression. Because the first clause is a declaration, attributes and
declaration specifiers come along with it:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">bool</span> <span class="n">x</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span> <span class="n">x</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">if</span> <span class="p">(</span><span class="n">bool</span> <span class="n">x</span> <span class="o">=</span> <span class="nb">false</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span><span class="p">;</span>
<span class="k">if</span> <span class="p">([[</span><span class="n">maybe_unused</span><span class="p">]]</span> <span class="n">bool</span> <span class="n">x</span> <span class="o">=</span> <span class="nb">true</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">if</span> <span class="p">(</span><span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">3</span><span class="p">;</span> <span class="n">x</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">if</span> <span class="p">(</span><span class="k">struct</span> <span class="n">A</span> <span class="p">{</span> <span class="kt">int</span> <span class="n">x</span><span class="p">;</span> <span class="p">}</span> <span class="n">a</span> <span class="o">=</span> <span class="p">{.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="p">};</span> <span class="n">a</span><span class="p">.</span><span class="n">x</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">if</span> <span class="p">(</span><span class="kt">int</span> <span class="n">arr</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">};</span> <span class="n">arr</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="p">{}</span>
<span class="k">if</span> <span class="p">(</span><span class="n">static_assert</span><span class="p">(</span><span class="nb">true</span><span class="p">);</span> <span class="nb">true</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">if</span> <span class="p">([[]];</span> <span class="nb">true</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">if</span> <span class="p">(</span><span class="k">auto</span> <span class="n">x</span> <span class="nf">__attribute__</span><span class="p">((</span><span class="n">deprecated</span><span class="p">))</span> <span class="o">=</span> <span class="mi">3</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">if</span> <span class="p">(</span><span class="n">__extension__</span> <span class="p">[[</span><span class="n">maybe_unused</span><span class="p">]]</span> <span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">3</span><span class="p">;</span>
    <span class="n">x</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{}</span>

<span class="k">switch</span> <span class="p">(</span><span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{}</span>
<span class="k">switch</span> <span class="p">(</span><span class="k">auto</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">3</span><span class="p">)</span> <span class="p">{</span> <span class="k">default</span><span class="o">:</span> <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span><span class="p">;</span> <span class="p">}</span>
</code></pre></div></div>

<h3 id="how-it-was-built">How it was built</h3>

<p>Rather than writing a new parser path, I reused the existing <code class="language-plaintext highlighter-rouge">C++17</code>
<code class="language-plaintext highlighter-rouge">if (init; cond)</code> and <code class="language-plaintext highlighter-rouge">switch (init; cond)</code> code paths in <code class="language-plaintext highlighter-rouge">Clang</code> and then
specialized them for <code class="language-plaintext highlighter-rouge">C</code>:</p>

<ul>
  <li>the first clause must be a declaration, so expression statements are
rejected there with dedicated diagnostics;</li>
  <li>the second clause is an expression only;</li>
  <li><code class="language-plaintext highlighter-rouge">C</code> attributes, declaration specifiers and <code class="language-plaintext highlighter-rouge">__extension__</code> are supported.</li>
</ul>

<h3 id="what-landed-in-clang">What landed in Clang</h3>

<ul>
  <li><strong>Merged upstream</strong> in <a href="https://github.com/llvm/llvm-project/pull/198244">#198244</a>
(commit <code class="language-plaintext highlighter-rouge">226b0b5</code>) and <a href="https://github.com/llvm/llvm-project/pull/209920">#209920</a>
(commit <code class="language-plaintext highlighter-rouge">1387002</code>). The feature is complete per the paper wording and is part
of <code class="language-plaintext highlighter-rouge">Clang</code> 24.</li>
  <li><strong>Available back to C89</strong>: the new syntax works in every <code class="language-plaintext highlighter-rouge">C</code> mode <code class="language-plaintext highlighter-rouge">Clang</code>
supports, with the appropriate compatibility warnings and extension
diagnostics in modes older than <code class="language-plaintext highlighter-rouge">C2y</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">__extension__</code> in C and C++ conditions</strong>: it silences the extension
diagnostics for the rest of the condition. This wasn’t available in <code class="language-plaintext highlighter-rouge">C++</code>
conditions before.</li>
  <li><strong>A new way to handle compatibility diagnostics</strong>: the follow-up commit
<code class="language-plaintext highlighter-rouge">1387002</code> introduced a new approach to emitting compatibility diagnostics in
the parser.</li>
</ul>

<p>One thing did not make it: GNU attribute declarations such as
<code class="language-plaintext highlighter-rouge">if (__attribute__((...)); true)</code>. <code class="language-plaintext highlighter-rouge">GCC</code> doesn’t follow the paper wording here
yet, so we couldn’t decide on the right behavior. <code class="language-plaintext highlighter-rouge">C23</code>-style attribute
declarations (<code class="language-plaintext highlighter-rouge">[[...]];</code>) did make it.</p>

<h3 id="impact-and-follow-ups">Impact and follow-ups</h3>

<p>Despite the heavy parser changes, the feature has held up well:</p>

<ul>
  <li><strong>C89 to C2y</strong>: the new syntax works in every <code class="language-plaintext highlighter-rouge">C</code> mode <code class="language-plaintext highlighter-rouge">Clang</code> supports.</li>
  <li><strong>No performance regressions</strong>: Ezzeldin Ibrahim, who tracked <code class="language-plaintext highlighter-rouge">Clang</code>
compile-time regressions during
<a href="/blogs/cppalliance26_ezzeldin_ibrahim_improve_clang_performance/">his fellowship</a>,
found that the new code performs as well as the old one.</li>
  <li><strong>Few user issues</strong>: the first one,
<a href="https://github.com/llvm/llvm-project/issues/233839">#233839</a>, pointed out
that the shared condition parsing also accepted declarations in <code class="language-plaintext highlighter-rouge">while</code>
loops, which N3356 does not allow. I fixed it in
<a href="https://github.com/llvm/llvm-project/pull/233908">#233908</a>. Recently a
second one, <a href="https://github.com/llvm/llvm-project/issues/243727">#243727</a>,
reported a crash on <code class="language-plaintext highlighter-rouge">if (::0);</code> in <code class="language-plaintext highlighter-rouge">C</code>, because <code class="language-plaintext highlighter-rouge">C</code> conditions now reach a
<code class="language-plaintext highlighter-rouge">C++</code>-only code path. The fix is under review in
<a href="https://github.com/llvm/llvm-project/pull/244055">#244055</a>.</li>
</ul>

<h2 id="what-got-blocked-and-why">What Got Blocked, and Why</h2>

<h3 id="c20-p1814r0-ctad-for-alias-templates">C++20 P1814R0: CTAD for alias templates</h3>

<p>Class template argument deduction (CTAD), introduced in <code class="language-plaintext highlighter-rouge">C++17</code>, lets the
compiler work out a class template’s arguments from its initializer, as it
already did for function templates:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">pair</span> <span class="nf">p</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">);</span>       <span class="c1">// std::pair&lt;int, double&gt;</span>
<span class="n">std</span><span class="o">::</span><span class="n">vector</span> <span class="n">v</span> <span class="o">=</span> <span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">};</span> <span class="c1">// std::vector&lt;int&gt;</span>
<span class="n">std</span><span class="o">::</span><span class="n">lock_guard</span> <span class="n">lk</span><span class="p">(</span><span class="n">m</span><span class="p">);</span>     <span class="c1">// std::lock_guard&lt;std::mutex&gt;</span>
</code></pre></div></div>

<p>Each constructor becomes an implicit deduction guide, the initializer goes
through overload resolution against those guides, and libraries can add
user-written guides for rules that constructors can’t express.</p>

<p>P1814R0 extends CTAD to alias templates in <code class="language-plaintext highlighter-rouge">C++20</code>:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">template</span> <span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span> <span class="k">struct</span> <span class="nc">A</span> <span class="p">{</span> <span class="n">A</span><span class="p">(</span><span class="n">T</span><span class="p">)</span> <span class="p">{}</span> <span class="p">};</span>
<span class="k">template</span> <span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span> <span class="k">using</span> <span class="n">Proxy</span> <span class="o">=</span> <span class="n">T</span><span class="p">;</span>
<span class="k">template</span> <span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span> <span class="k">using</span> <span class="n">C</span> <span class="o">=</span> <span class="n">Proxy</span><span class="o">&lt;</span><span class="n">A</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;&gt;</span><span class="p">;</span>

<span class="n">C</span> <span class="n">test</span><span class="p">{</span><span class="mi">42</span><span class="p">};</span> <span class="c1">// deduce C&lt;int&gt;</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">Clang</code> had a basic implementation that was not stable: it rejected valid code
or crashed in some cases, and there were many reported issues that needed
triage. I opened <a href="https://github.com/llvm/llvm-project/pull/193056">#193056</a> to
close the gap with <code class="language-plaintext highlighter-rouge">GCC</code> and set the <code class="language-plaintext highlighter-rouge">__cpp_deduction_guides</code> feature test
macro accordingly, and <a href="https://github.com/llvm/llvm-project/pull/222215">#222215</a>
to handle alias templates with nested aliases such as the example above.</p>

<p>The work got blocked for three reasons:</p>

<ol>
  <li><strong>The PR got blocked</strong>: there was a debate on the equivalence of alias
templates, and only <code class="language-plaintext highlighter-rouge">GCC</code> implements it.</li>
  <li><strong>An open core issue, <a href="https://cplusplus.github.io/CWG/issues/2186.html">CWG2186</a></strong>:
fixing it needs new wording from the committee.</li>
  <li><strong>Not a priority</strong>: the wording wouldn’t be discussed soon, so it didn’t fit
the fellowship schedule.</li>
</ol>

<h3 id="pivot-c2326-constexpr-math">Pivot: C++23/26 constexpr math</h3>

<p>Making <code class="language-plaintext highlighter-rouge">&lt;cmath&gt;</code> constexpr was a natural next step for me, since half of the
work is in <code class="language-plaintext highlighter-rouge">Clang</code> built-ins and I had already done the <code class="language-plaintext highlighter-rouge">LLVM libc</code> side.</p>

<p>This work is part of <strong>Hand-in-Hand++</strong>. Hand-in-Hand started by
sharing <code class="language-plaintext highlighter-rouge">LLVM libc</code> internals with <code class="language-plaintext highlighter-rouge">libc++</code>; Hand-in-Hand++ extends this to the
whole LLVM tree. <code class="language-plaintext highlighter-rouge">libc/shared/</code> exposes header-only, correctly rounded math
that <code class="language-plaintext highlighter-rouge">LLVM</code>, <code class="language-plaintext highlighter-rouge">Clang</code> and <code class="language-plaintext highlighter-rouge">libc++</code> can include, so every layer uses one
implementation instead of rewriting it. Implementing constexpr math spans four
LLVM projects:</p>

<table>
  <thead>
    <tr>
      <th>Layer</th>
      <th>Component</th>
      <th>Role</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">LLVM libc</code></td>
      <td><code class="language-plaintext highlighter-rouge">libc/shared/math.h</code></td>
      <td>Header-only, correctly rounded math, written once</td>
      <td>Done</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">LLVM APFloat</code></td>
      <td><code class="language-plaintext highlighter-rouge">llvm/Support</code></td>
      <td>Reuses the shared libc math for software floating point</td>
      <td>-</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Clang</code></td>
      <td>constant evaluator</td>
      <td>Folds <code class="language-plaintext highlighter-rouge">__builtin_exp</code> and friends at compile time via <code class="language-plaintext highlighter-rouge">APFloat</code></td>
      <td>Waiting</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">LLVM libc++</code></td>
      <td><code class="language-plaintext highlighter-rouge">&lt;cmath&gt;</code></td>
      <td>constexpr <code class="language-plaintext highlighter-rouge">std::exp</code>, <code class="language-plaintext highlighter-rouge">std::log</code>, … on top of the built-ins</td>
      <td>-</td>
    </tr>
  </tbody>
</table>

<p>On the <code class="language-plaintext highlighter-rouge">libc</code> side, the math functions are qualified to be usable in constant
evaluation (for example <a href="https://github.com/llvm/llvm-project/pull/184745">#184745</a>
and <a href="https://github.com/llvm/llvm-project/pull/184948">#184948</a>).</p>

<p>However, the chain is held up at <code class="language-plaintext highlighter-rouge">Clang</code>: an open PR,
<a href="https://github.com/llvm/llvm-project/pull/199808">#199808</a>, makes
<code class="language-plaintext highlighter-rouge">__builtin_exp</code> constexpr, but the maintainers first need to agree on the
approach. With the design still open, this was too slow for the fellowship, so
I picked another paper to implement.</p>

<h2 id="c2d-p3668r4-defaulted-postfix--and---">C++2d P3668R4: Defaulted Postfix <code class="language-plaintext highlighter-rouge">++</code> and <code class="language-plaintext highlighter-rouge">--</code></h2>

<p>P3668R4 allows the postfix increment and decrement operators to be explicitly
defaulted. The postfix form is generated from the prefix one:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="nc">Counter</span> <span class="p">{</span>
  <span class="kt">int</span> <span class="n">v</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="n">Counter</span> <span class="o">&amp;</span><span class="k">operator</span><span class="o">++</span><span class="p">()</span> <span class="p">{</span> <span class="o">++</span><span class="n">v</span><span class="p">;</span> <span class="k">return</span> <span class="o">*</span><span class="k">this</span><span class="p">;</span> <span class="p">}</span>
  <span class="n">Counter</span> <span class="k">operator</span><span class="o">++</span><span class="p">(</span><span class="kt">int</span><span class="p">)</span> <span class="o">=</span> <span class="k">default</span><span class="p">;</span>
  <span class="c1">// same as:</span>
  <span class="c1">//   Counter tmp = *this;</span>
  <span class="c1">//   ++*this; return tmp;</span>
<span class="p">};</span>
</code></pre></div></div>

<p>I implemented the paper wording in
<a href="https://github.com/llvm/llvm-project/pull/229560">#229560</a>, which was
<strong>merged upstream</strong> after several rounds of review with the <code class="language-plaintext highlighter-rouge">Clang</code>
maintainers. The implementation:</p>

<ul>
  <li>checks the declaration requirements of <code class="language-plaintext highlighter-rouge">[over.inc.default]</code>, such as the
parameter and return types, and defines the operator as deleted, with notes
explaining why, when the class has no usable copy constructor, destructor or
prefix operator;</li>
  <li>computes the exception specification from the implicit definition, and
makes the operator implicitly <code class="language-plaintext highlighter-rouge">constexpr</code> when it is suitable, following the
rules for other defaulted functions;</li>
  <li>performs the lookup of the prefix operator from the context of the function
body, also for <code class="language-plaintext highlighter-rouge">= default</code> at namespace scope;</li>
  <li>is available in all <code class="language-plaintext highlighter-rouge">C++</code> language modes as an extension, down to <code class="language-plaintext highlighter-rouge">C++03</code>.
Porting it down required accounting for language features like <code class="language-plaintext highlighter-rouge">constexpr</code>
and other qualifiers not being available in older modes.</li>
</ul>

<p>After it landed, a crash was reported when instantiating functions defaulted
outside class templates under non-default floating-point features
(<a href="https://github.com/llvm/llvm-project/issues/240351">#240351</a>). I fixed it in
<a href="https://github.com/llvm/llvm-project/pull/240376">#240376</a>, which also fixed
the same problem for a defaulted postfix operator.</p>

<h2 id="how-i-used-ai">How I Used AI</h2>

<p>I used AI as an assistant in two areas:</p>

<ol>
  <li><strong>Navigating Clang’s code</strong>: explaining unfamiliar parser and <code class="language-plaintext highlighter-rouge">Sema</code> code
paths, and finding where a change should go in a large codebase.</li>
  <li><strong>Writing tests</strong>: drafting test cases and listing the edge cases to cover,
such as attributes, <code class="language-plaintext highlighter-rouge">__extension__</code> and the different <code class="language-plaintext highlighter-rouge">C</code> modes.</li>
</ol>

<h2 id="summary-of-contributions">Summary of Contributions</h2>

<table>
  <thead>
    <tr>
      <th>PR</th>
      <th>Description</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><a href="https://github.com/llvm/llvm-project/pull/198244">#198244</a></td>
      <td><code class="language-plaintext highlighter-rouge">[Clang][C2y]</code> Add support for if declarations (N3356)</td>
      <td>Merged</td>
    </tr>
    <tr>
      <td><a href="https://github.com/llvm/llvm-project/pull/209920">#209920</a></td>
      <td><code class="language-plaintext highlighter-rouge">[Clang][NFC]</code> Update diagnostic handling for C2y compatibility in parser</td>
      <td>Merged</td>
    </tr>
    <tr>
      <td><a href="https://github.com/llvm/llvm-project/pull/233908">#233908</a></td>
      <td><code class="language-plaintext highlighter-rouge">[Clang][C2y]</code> Reject declarations in the condition of a while loop</td>
      <td>Merged</td>
    </tr>
    <tr>
      <td><a href="https://github.com/llvm/llvm-project/pull/244055">#244055</a></td>
      <td><code class="language-plaintext highlighter-rouge">[Clang][Parse]</code> Do not treat <code class="language-plaintext highlighter-rouge">::</code> as a decl-specifier outside C++</td>
      <td>In review</td>
    </tr>
    <tr>
      <td><a href="https://github.com/llvm/llvm-project/pull/229560">#229560</a></td>
      <td><code class="language-plaintext highlighter-rouge">[Clang][C++2d]</code> Implement defaulted postfix increment and decrement operators (P3668R4)</td>
      <td>Merged</td>
    </tr>
    <tr>
      <td><a href="https://github.com/llvm/llvm-project/pull/240376">#240376</a></td>
      <td><code class="language-plaintext highlighter-rouge">[Clang]</code> Fix crash instantiating functions defaulted outside class templates</td>
      <td>Merged</td>
    </tr>
    <tr>
      <td><a href="https://github.com/llvm/llvm-project/pull/193056">#193056</a></td>
      <td><code class="language-plaintext highlighter-rouge">[Clang][C++17/20]</code> Add full support to deduction guides and CTAD alias templates</td>
      <td>Blocked</td>
    </tr>
    <tr>
      <td><a href="https://github.com/llvm/llvm-project/pull/222215">#222215</a></td>
      <td><code class="language-plaintext highlighter-rouge">[Clang][CTAD]</code> Implement deduction guides for alias templates with nested aliases</td>
      <td>Blocked</td>
    </tr>
  </tbody>
</table>

<h2 id="whats-next">What’s Next</h2>

<ul>
  <li>Land the fix for <a href="https://github.com/llvm/llvm-project/issues/243727">#243727</a>
in <a href="https://github.com/llvm/llvm-project/pull/244055">#244055</a>.</li>
  <li>Pick CTAD for alias templates back up once CWG2186 gets new wording.</li>
  <li>Continue the constexpr math chain once the <code class="language-plaintext highlighter-rouge">__builtin_exp</code> approach is
agreed on in <code class="language-plaintext highlighter-rouge">Clang</code>.</li>
</ul>

<h2 id="acknowledgments">Acknowledgments</h2>

<p>I would like to thank my mentors, Vassil Vassilev and Aaron Jomy, for their
guidance throughout the fellowship, the <code class="language-plaintext highlighter-rouge">Clang</code> maintainers and reviewers for
their time and feedback, and the C++ Alliance for supporting this work.</p>

<h2 id="related-links">Related Links</h2>

<ul>
  <li><a href="https://github.com/llvm/llvm-project">LLVM project</a></li>
  <li><a href="/blogs/Implement_missing_C++26_features_in_Clang_Muhammad_Bassiouni_blog/">Announcement blog post</a></li>
  <li><a href="/assets/presentations/Muhammad_Bassiouni-CRCon26_Missing_C_and_CXX_Features_in_Clang.pdf">CRCon26 slides</a></li>
  <li><a href="/assets/presentations/Muhammad_Bassiouni_CppAlliance_Fellowship2026_midterm_presentation.pdf">Fellowship midterm presentation</a></li>
  <li><a href="/assets/presentations/Muhammad_Bassiouni_CppAlliance_Fellowship2026_final_presentation.pdf">Fellowship final presentation</a></li>
  <li><a href="https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3356.htm">N3356: if declarations in C2y</a></li>
  <li><a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1814r0.html">P1814R0: CTAD for alias templates</a></li>
  <li><a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p3668r4.html">P3668R4: Defaulted postfix operators</a></li>
  <li><a href="https://github.com/bassiounix">My GitHub profile</a></li>
</ul>]]></content><author><name>Muhammad Bassiouni</name></author><category term="cppalliance" /><category term="Clang" /><category term="LLVM" /><category term="C" /><category term="C++" /><category term="C2y" /><category term="C++20" /><category term="C++2d" /><category term="if-declaration" /><category term="CTAD-alias-templates" /><category term="constexpr-math" /><category term="defaulted-postfix-operators" /><summary type="html"><![CDATA[A wrap-up of my C++ Alliance Fellowship 2026: what landed in Clang (C2y if/switch declarations and C++2d defaulted postfix operators), what got blocked (CTAD for alias templates and constexpr math) and why, and how the work impacted Clang.]]></summary></entry><entry><title type="html">Where Clang spends its compile time</title><link href="/blogs/cppalliance26_ezzeldin_ibrahim_improve_clang_performance_final/" rel="alternate" type="text/html" title="Where Clang spends its compile time" /><published>2026-11-23T00:00:00+00:00</published><updated>2026-11-23T00:00:00+00:00</updated><id>/blogs/improve-clang-performance-final</id><content type="html" xml:base="/blogs/cppalliance26_ezzeldin_ibrahim_improve_clang_performance_final/"><![CDATA[<div class="custom-banner-wrapper" role="img" aria-label="">
  <div class="custom-banner-flex">
    <div class="banner-logo">
      <img src="/images/cppalliance-logo.svg" alt="Left Logo" />
    </div>

    <div class="banner-separator" aria-hidden="true">
      @
    </div>

    <div class="banner-logo logo-right-bg">
      <img src="/images/cr-logo_old.png" alt="Right Logo" />
    </div>
  </div>

  
  <div class="banner-caption" role="heading" aria-level="2">
    
  </div>
  
</div>

<style>
  .custom-banner-wrapper {
    --b-height: 20vh;
    width: 100%;
    max-width: 95%;
    margin: 0 auto;
    padding: 1.5rem 0;
  }

  .custom-banner-flex {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 3rem;
  }

  .banner-logo img {
    height: calc(var(--b-height) * 0.85);
    width: auto;
    max-width: 30vw;
    min-height: 50px;
    object-fit: contain;
  }

  /* Keep the white background for the right logo badge if needed */
  .logo-right-bg img {
    padding: 8px;
    background: #fff;
    border-radius: 4px;
  }

  .banner-separator {
    font-size: calc(var(--b-height) * 0.5);
    font-weight: 700;
    color: #000;
  }

  .banner-caption {
    text-align: center;
    margin-top: 1rem;
    font-family: Georgia, serif;
    font-size: calc(var(--b-height) * 0.25);
    color: #111;
  }

  @media (max-width: 768px) {
    .custom-banner-wrapper { --b-height: 15vh; }
    .custom-banner-flex { gap: 1.5rem; }
  }

  @media (max-width: 480px) {
    .custom-banner-flex { flex-direction: column; gap: 1rem; }
  }
</style>

<p>My first attempt to pin down a Clang regression took about 19 hours and pointed
to the wrong commit. I had been timing SQLite compilations on my laptop. Each
step of the bisect built a fresh Clang, then immediately used it to compile
SQLite. Depending on how hot the laptop was, the same compiler could give me
times several percent apart. That was enough to send the bisect down the wrong
half of the history.</p>

<p>I spent my C++ Alliance Fellowship investigating changes like this with Vassil
Vassilev and Aaron Jomy. By the time I finished on 2 November, I had compared
Clang 18 through 23 on ten C and C++ codebases and identified 20 regressions.
I found practical fixes for eight of them. My <a href="/blogs/cppalliance26_ezzeldin_ibrahim_improve_clang_performance/">earlier post</a>
describes how the project started.</p>

<h2 id="finding-the-commit-that-changed-the-cost">Finding the commit that changed the cost</h2>

<p>I switched to counting the instructions Clang executed under Callgrind. I could
compile the same source file with two revisions, keep the flags and environment
fixed, and see a small change even while the machine was busy. I also measured
the frontend on its own. A full SQLite build had become faster overall, but
improvements in code generation hid an increase in the cost of parsing and
checking the source.</p>

<p>Building a compiler for every revision was the next bottleneck.
<a href="https://github.com/elfshaker/manyclangs">manyclangs</a> let me sample prebuilt
compilers across a release and plot the instruction count against the commit.
On Boost.MPL, several small steps added up to the release-level slowdown. A
single first-bad commit would have told only part of that story. I used the
prebuilt compilers to locate the steps, then checked individual changes with
native builds before reporting them.</p>

<h2 id="when-a-faster-patch-made-debug-builds-slower">When a faster patch made debug builds slower</h2>

<p>Clang was collecting documentation comments even in compilations that had no
use for them. My first patch checked whether a feature or warning needed the
comments before adding them to the syntax tree. It helped on comment-heavy
files. After it merged, the LLVM Compile Time Tracker showed a <strong>7.6% increase</strong>
in instructions at <code class="language-plaintext highlighter-rouge">-O0 -g</code>, and the patch was reverted. The check I had added
was itself expensive enough to erase the savings. <a href="https://github.com/llvm/llvm-project/pull/206363#issuecomment-5479204717">Original patch and regression report</a></p>

<p>For the second version I cached whether the documentation warnings were
enabled. The cache had to respect changes in diagnostic settings within a
file, including changes made by pragmas. With that in place, Clang could skip
the comment work without repeatedly looking up the warning policy. The reland
reduced compiler instructions by <strong>0.31%</strong> on the tracker at <code class="language-plaintext highlighter-rouge">-O0 -g</code>. <a href="https://github.com/llvm/llvm-project/pull/221605">Merged fix</a></p>

<h2 id="what-the-instruction-counter-missed">What the instruction counter missed</h2>

<p>Compiling CTRE, a library that processes regular expressions at compile time,
used almost 9 GB on my test. I added peak-heap measurements with Massif and
traced one source of growth to the key Clang stored in its table of deduced
<code class="language-plaintext highlighter-rouge">auto</code> types. A small saving per entry mattered because the compiler kept so
many entries alive at once. Shrinking that key reduced peak resident memory
from <strong>8,928 MB to 8,347 MB</strong> on the same compilation, a <strong>6.5%</strong> reduction.
<a href="https://github.com/llvm/llvm-project/pull/218278">Merged fix and measurements</a></p>

<h2 id="the-last-two-weeks">The last two weeks</h2>

<p>On 31 October my DWARF 5 checksum patch merged. Clang had already hashed the
main source file when it created the debug compile unit. Later, when it needed
a debug file entry for that same file, it read and hashed the contents again.
Reusing the first checksum saved <strong>0.72%</strong> of compiler instructions on SQLite
in the reported debug build. <a href="https://github.com/llvm/llvm-project/pull/228926">DWARF checksum fix</a></p>

<p>On 2 November I opened two smaller patches after looking for source-location
lookups on common paths. When parsing a GNU attribute, Clang can check whether
it came from a macro before looking up the presumed filename. When identifying
a language-defined builtin macro, it can check the macro name first. Measured
independently at <code class="language-plaintext highlighter-rouge">-O0 -g</code>, those changes reduced tracker instruction counts by
<strong>0.08%</strong> and <strong>0.13%</strong>, respectively. <a href="https://github.com/llvm/llvm-project/pull/237803">GNU attribute patch</a> · <a href="https://github.com/llvm/llvm-project/pull/237805">Builtin macro patch</a></p>

<h2 id="upstream-results">Upstream results</h2>

<p>I opened 18 performance PRs. Twelve merged, including the documentation change
that I subsequently reworked, five remained open, and I closed one initial
approach. A few other results illustrate how much the workload matters.</p>

<ul>
  <li>Clang could spend time finding a spelling correction even when the diagnostic
that would show it was disabled. Skipping that search saved <strong>1.2%</strong> of
compiler instructions on Boost.MPL. <a href="https://github.com/llvm/llvm-project/pull/209694">Merged typo-correction fix</a></li>
  <li>A user reported a compilation that spent minutes in LLVM’s loop optimizer.
I traced it to repeated invalidation of cached analysis results. Batching
that work brought the reproducer from <strong>3 min 46 s to 3.9 s</strong>. <a href="https://github.com/llvm/llvm-project/issues/194308">Issue investigation</a> · <a href="https://github.com/llvm/llvm-project/pull/219025">Merged optimizer fix</a></li>
  <li>Two patches under review remove quadratic work. Selecting an element from an
8,000-element template pack went from <strong>11.9 s to 0.69 s</strong> on the test case.
Checking a designated initializer with 40,000 fields went from <strong>8.87 s to
0.07 s</strong>. <a href="https://github.com/llvm/llvm-project/pull/213790">Pack indexing</a> · <a href="https://github.com/llvm/llvm-project/pull/225573">Designated initializers</a></li>
</ul>

<p>Thank you to Vassil Vassilev and Aaron Jomy for their guidance, to the LLVM
reviewers who helped work through these changes, and to the C++ Alliance for
supporting the fellowship. I presented the benchmarking method and the results
at CompilerResearchCon 2026. <a href="/assets/presentations/Ezzeldin_Ibrahim-CRCon26_Improving_Clang_Performance.pdf">Talk slides</a></p>]]></content><author><name>Ezzeldin Ibrahim</name></author><category term="cppalliance" /><category term="clang" /><category term="performance" /><category term="benchmarking" /><category term="memory-optimization" /><summary type="html"><![CDATA[A 19-hour bisect pointed me to the wrong Clang commit. I explain how counting instructions changed the way I investigated slow builds, and how measuring memory led to a 581 MB saving on one compilation.]]></summary></entry><entry><title type="html">Clad as a First-Class Gradient Engine in LibTorch: GSoC 2026 Final Report</title><link href="/blogs/gsoc26_kacent_final_blog/" rel="alternate" type="text/html" title="Clad as a First-Class Gradient Engine in LibTorch: GSoC 2026 Final Report" /><published>2026-11-05T00:00:00+00:00</published><updated>2026-11-05T00:00:00+00:00</updated><id>/blogs/gsoc26-kacent-final-blog</id><content type="html" xml:base="/blogs/gsoc26_kacent_final_blog/"><![CDATA[<p>At the beginning of GSoC, I wanted to make Clad-generated derivatives usable
inside a LibTorch C++ training loop. LibTorch already provides Tensor storage,
optimized kernels, and an autograd engine. Clad can generate derivative code
while compiling C++. My project explored how these two systems could work
together for a supported subset of Tensor operations.</p>

<p>The result includes a Tensor derivative backend, a compiler frontend that
connects generated pullbacks to <code class="language-plaintext highlighter-rouge">torch::autograd::Function</code>, and an MNIST
training example with correctness tests and reproducible benchmarks. Several
compiler improvements developed along the way have been merged into Clad;
others remain under review.</p>

<p>Performance became a substantial part of the work. In our CPU MNIST experiment,
the optimized direct Clad path reduced measured training time by 15.4% relative
to native LibTorch autograd, but still used 26.0% more peak Tensor storage.
Investigating that remaining gap led to a useful finding: some generated
Tensor handles kept storage alive after its last use. A manual early-release
experiment brought the peak close to the native reference.</p>

<p>This report follows the implementation and the experiments behind those
results. It continues my <a href="https://compiler-research.org/blogs/gsoc26_kacent_introduction_blog/">initial project introduction</a>.</p>

<h2 id="making-tensor-derivatives-work">Making Tensor derivatives work</h2>

<p>The first challenge was representing derivatives of Tensor values correctly.
In reverse-mode AD, an <em>adjoint</em> accumulates contributions to a value’s
derivative. A scalar adjoint can start at <code class="language-plaintext highlighter-rouge">0</code>. A Tensor adjoint also needs the
right shape, dtype, and device, with storage independent of the original value.</p>

<p>Copying a Tensor copies its handle and shares the underlying storage. Clearing
that copy can therefore overwrite the original data. Default construction has
a different problem: it creates an undefined Tensor, without the runtime shape
needed by a pullback that writes into it.</p>

<p>I introduced <code class="language-plaintext highlighter-rouge">clad::zero_like</code> to express construction of a zero adjoint from an
existing value. For a defined floating-point CPU Tensor, the essential rule is:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">namespace</span> <span class="n">clad</span> <span class="p">{</span>
<span class="n">at</span><span class="o">::</span><span class="n">Tensor</span> <span class="n">zero_like</span><span class="p">(</span><span class="k">const</span> <span class="n">at</span><span class="o">::</span><span class="n">Tensor</span><span class="o">&amp;</span> <span class="n">value</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">at</span><span class="o">::</span><span class="n">NoGradGuard</span> <span class="n">guard</span><span class="p">;</span>
  <span class="k">return</span> <span class="n">at</span><span class="o">::</span><span class="n">zeros_like</span><span class="p">(</span><span class="n">value</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This also separates construction from <code class="language-plaintext highlighter-rouge">zero_init</code>, which resets an existing
adjoint. Subsequent changes let Clad reuse the type-level rule when constructing
default reverse-forward results and centralize its use in adjoint generation.
An ordinary function returning a Tensor by value no longer needs its own
<code class="language-plaintext highlighter-rouge">reverse_forw</code> helper just to repeat the same initialization rule. Explicit
helpers still serve cases involving aliasing or additional saved state.</p>

<p>The operator derivatives are a separate layer. I implemented custom pullbacks
for the supported Tensor operations, including arithmetic, reductions, ReLU,
matrix multiplication, and views. Clad composes these rules into the derivative
of the user’s C++ function. LibTorch executes the underlying kernels; Clad does
not need to differentiate their implementations.</p>

<p>Broadcasting and strided views made this more than a collection of scalar
formulas. For example, a broadcast bias receives the sum of contributions over
the expanded dimensions. Tensor copies and moves also require care because
shared primal storage does not imply that independent local adjoints should
share storage. Tests cover these cases alongside the simpler contiguous path.</p>

<h2 id="separating-entry-discovery-from-derivative-planning">Separating entry discovery from derivative planning</h2>

<p>Clad traditionally discovers differentiation requests through calls such as
<code class="language-plaintext highlighter-rouge">clad::gradient</code>. The Torch integration needs to request a derivative from a
different entry point, while retaining Clad’s dependency planning and analyses.</p>

<p>I separated ordinary Clad invocation discovery into <code class="language-plaintext highlighter-rouge">CladInvocationVisitor</code>.
The Torch frontend has its own visitor, and both describe the required work
with a <code class="language-plaintext highlighter-rouge">DiffRequest</code>. A shared <code class="language-plaintext highlighter-rouge">DiffScheduler::PlanRoot</code> submits those requests
to the planner. The scheduler checks the invocation’s <code class="language-plaintext highlighter-rouge">#pragma clad</code> interval
and queues roots discovered while another request is being planned.</p>

<p><img src="/images/blog/gsoc26-kacent-final/frontend-integration.svg" alt="Compile-time entry discovery shares a differentiation planner; at runtime a Torch Function connects the generated pullback to autograd." /></p>

<p>This keeps frontend-specific recognition separate from derivative generation.
Adding a Torch entry point does not require a second AD engine, and ordinary
Clad calls continue through the same planning infrastructure. The refactor is
tracked in <a href="https://github.com/vgvassilev/clad/pull/2376">PR #2376</a>.</p>

<h2 id="connecting-a-pullback-to-torch-autograd">Connecting a pullback to Torch autograd</h2>

<p>For a supported function, the explicit entry point looks like this:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">using</span> <span class="n">Tensor</span> <span class="o">=</span> <span class="n">at</span><span class="o">::</span><span class="n">Tensor</span><span class="p">;</span>

<span class="n">Tensor</span> <span class="nf">block</span><span class="p">(</span><span class="k">const</span> <span class="n">Tensor</span><span class="o">&amp;</span> <span class="n">x</span><span class="p">,</span> <span class="k">const</span> <span class="n">Tensor</span><span class="o">&amp;</span> <span class="n">weight</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">*</span> <span class="n">weight</span><span class="p">).</span><span class="n">relu</span><span class="p">();</span>
<span class="p">}</span>

<span class="c1">// x and weight are CPU floating-point Tensors requiring gradients.</span>
<span class="k">auto</span> <span class="n">y</span> <span class="o">=</span> <span class="n">clad</span><span class="o">::</span><span class="n">torch</span><span class="o">::</span><span class="n">autograd</span><span class="p">(</span><span class="n">block</span><span class="p">,</span> <span class="s">"x,weight"</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">weight</span><span class="p">);</span>
<span class="n">y</span><span class="p">.</span><span class="n">sum</span><span class="p">().</span><span class="n">backward</span><span class="p">();</span>
</code></pre></div></div>

<p>The frontend identifies <code class="language-plaintext highlighter-rouge">block</code>, requests a pullback, and replaces the entry
call with an adapter based on <code class="language-plaintext highlighter-rouge">torch::autograd::Function</code>. Conceptually, the
replacement is:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">using</span> <span class="n">Node</span> <span class="o">=</span> <span class="n">clad</span><span class="o">::</span><span class="n">torch</span><span class="o">::</span><span class="n">detail</span><span class="o">::</span><span class="n">AutogradFunction</span><span class="o">&lt;</span><span class="n">block</span><span class="p">,</span> <span class="n">block_pullback</span><span class="o">&gt;</span><span class="p">;</span>
<span class="k">auto</span> <span class="n">y</span> <span class="o">=</span> <span class="n">Node</span><span class="o">::</span><span class="n">apply</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">weight</span><span class="p">);</span>
</code></pre></div></div>

<p>The adapter’s forward method runs the original function and saves its inputs.
During backward, Torch supplies the output’s upstream gradient, and the adapter
passes it to the generated pullback. The returned input gradients then continue
through the surrounding Torch graph. A <code class="language-plaintext highlighter-rouge">CLAD_TORCH_AUTOGRAD</code> annotation also
allows supported direct calls to request this integration.</p>

<p>A pullback is the appropriate interface here because its output seed can be
arbitrary. A scalar-loss gradient entry normally starts the reverse pass with
a seed of one; a function embedded in a larger computation must receive the
contribution from that computation instead. PyTorch’s <a href="https://docs.pytorch.org/tutorials/advanced/cpp_autograd.html">C++ autograd interface</a>
provides this forward/backward boundary.</p>

<p>The prototype targets first-order derivatives of supported CPU Tensor
functions. Torch still manages the surrounding graph. Within a Clad-backed
region, the generated pullback supplies the backward program. Separate
integration tests check this boundary, including composition with native
autograd and upstream gradients that are not simply one.</p>

<h2 id="validating-a-complete-training-workload">Validating a complete training workload</h2>

<p>I used MNIST to move beyond individual operator tests. The model has a
784-to-64 hidden layer with ReLU and a 64-to-10 output layer. Its loss is the
sum of squared differences from one-hot targets, divided by twice the batch
size. Training uses mini-batch SGD with batch size 128 and learning rate 0.05.</p>

<p><img src="/images/blog/gsoc26-kacent-final/mnist-model.svg" alt="The MNIST model maps 784 image pixels to 64 hidden units and 10 scores, using one-hot squared-error loss." /></p>

<p>LibTorch loads the data and executes Tensor kernels. Clad generates the loss
derivative for both weight matrices and both biases. Gradient checks compare
against native autograd and central finite differences, including strided
weights. The training runs use all 60,000 training images and 10,000 test
images for ten epochs.</p>

<p>For the detailed optimization experiments below, I call <code class="language-plaintext highlighter-rouge">clad::gradient</code>
directly under <code class="language-plaintext highlighter-rouge">NoGradGuard</code>. This measures the generated training path without
the Torch Function adapter. The native reference uses the same training loop,
initialization, batches, and SGD updates with LibTorch autograd. Keeping these
paths separate makes the benchmark’s scope explicit.</p>

<p>All stages in the experiment reached 93.9% test accuracy, and their final
parameters had a maximum absolute difference of zero from the native reference
in this run. Correctness checks also run independently of full training, so a
similar accuracy alone is not our test of the derivatives.</p>

<h2 id="removing-work-from-the-generated-backward-pass">Removing work from the generated backward pass</h2>

<p>Before the staged experiment, I put the model’s forward operations directly
inside the differentiated loss. With a separate prediction helper, an ordinary
generated pullback can recompute the helper’s intermediates because its
interface does not receive those values from the earlier forward call. Keeping
the operations in the root function lets its reverse sweep reuse local values.
This is already part of S0, the baseline below.</p>

<p>S0 also uses native ReLU backward kernels and ordinary <code class="language-plaintext highlighter-rouge">zero_like</code> semantics.
The Tensor backend had earlier explored representing zero with an undefined
Tensor. The final backend constructs real zero adjoints, so custom pullbacks
can work with them normally; the later optimizations focus on avoiding work
and reusing storage where the operation permits it.</p>

<h3 id="s1-omits-gradients-for-fixed-data">S1 omits gradients for fixed data</h3>

<p>The loss requests gradients for the model parameters, but the original full
matrix pullback also computes an image gradient. For <code class="language-plaintext highlighter-rouge">Y = XW</code> and upstream
gradient <code class="language-plaintext highlighter-rouge">G</code>, the weight contribution is <code class="language-plaintext highlighter-rouge">XᵀG</code>, while the image contribution is
<code class="language-plaintext highlighter-rouge">GWᵀ</code>. This training loop needs the former. The latter costs another matrix
product and a 128-by-784 buffer.</p>

<p>Selecting gradient outputs alone is not generally permission to omit every
other adjoint. An unselected parameter can be overwritten with an active value
and become an intermediate in the derivative. I added the explicit option
<code class="language-plaintext highlighter-rouge">assume_unselected_inactive</code> for callers who can promise that unselected root
inputs, including their reachable storage, remain inactive. The fixed images
and targets in this workload satisfy that promise.</p>

<p>I also added <code class="language-plaintext highlighter-rouge">clad::no_adjoint</code>, an empty type that preserves an omitted
gradient’s position in a pullback signature. A small scalar example is:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// product(data, weight) = data * weight</span>
<span class="k">namespace</span> <span class="n">clad</span><span class="o">::</span><span class="n">custom_derivatives</span> <span class="p">{</span>
<span class="kt">void</span> <span class="n">product_pullback</span><span class="p">(</span><span class="kt">double</span> <span class="n">data</span><span class="p">,</span> <span class="kt">double</span> <span class="cm">/*weight*/</span><span class="p">,</span> <span class="kt">double</span> <span class="n">seed</span><span class="p">,</span>
                      <span class="n">clad</span><span class="o">::</span><span class="n">no_adjoint</span><span class="p">,</span> <span class="kt">double</span><span class="o">*</span> <span class="n">d_weight</span><span class="p">)</span> <span class="p">{</span>
  <span class="o">*</span><span class="n">d_weight</span> <span class="o">+=</span> <span class="n">data</span> <span class="o">*</span> <span class="n">seed</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Clad can select this overload when only the weight contribution is needed.
The same approach applies to the Tensor matrix pullback. Selection happens
while compiling. Generated pullbacks also retain
omitted positions with the marker, distinguishing output subsets whose
remaining pointer types would otherwise be identical. Existing full custom
pullbacks remain usable through a fallback with real output storage.</p>

<p>Varied Analysis, enabled by <code class="language-plaintext highlighter-rouge">enable_va</code>, is already present in S0. It tracks
which values depend on selected inputs, but a full handwritten custom pullback
still contains its own computations. The partial overload gives Clad an
implementation that actually omits the unwanted output work.</p>

<h3 id="s2-and-s3-reduce-allocation-and-copying">S2 and S3 reduce allocation and copying</h3>

<p>In S2, matrix pullbacks accumulate directly into existing gradient storage with
<code class="language-plaintext highlighter-rouge">addmm_</code>, where dtype and aliasing conditions permit. This avoids materializing
a separate matrix product and then adding it to the destination.</p>

<p>S3 groups further buffer improvements: elementwise accumulating kernels,
copy-adjoint propagation without a redundant temporary, and reuse of a ReLU
seed when ownership permits. Ownership matters because moving a Tensor handle
does not remove other aliases. Borrowed or shared storage must remain protected.</p>

<h3 id="s4-removes-an-unused-default-adjoint">S4 removes an unused default adjoint</h3>

<p>Inspection of the generated code revealed another allocation source. While
processing a temporary member-call receiver, the outer visitor could already
provide its adjoint. Visiting the inner call could nevertheless create a
second default adjoint through <code class="language-plaintext highlighter-rouge">zero_like</code>. The outer visitor then replaced
that returned adjoint reference, leaving the extra initialization unused.</p>

<p>I fixed this specific case in <a href="https://github.com/vgvassilev/clad/pull/2496">PR #2496</a>.
The MNIST derivative loses three allocations per batch. This is compiler-side
work elimination: the extra Tensor never needs to be constructed.</p>

<h2 id="measuring-the-changes">Measuring the changes</h2>

<p>The experiment uses Clang 21.1.3 with <code class="language-plaintext highlighter-rouge">-O3</code>, LibTorch 2.11 CPU, FP32, and one
thread pinned to CPU 0. Each case has six timing runs in rotated order. Timing
includes batch copies, forward, backward, and SGD, and excludes data loading,
shuffle preparation, evaluation, and serialization. The reported ten-epoch
time is the sum of the per-epoch medians across those runs.</p>

<p>Memory instrumentation runs separately. It counts newly allocated CPU Tensor
storage during training, excluding pre-existing datasets and model storage,
allocator reservations, and C++ graph metadata. Allocation volume measures
all bytes allocated during an epoch; peak live storage measures how many of
those bytes coexist.</p>

<table>
  <thead>
    <tr>
      <th>Case</th>
      <th style="text-align: right">Training time (s)</th>
      <th style="text-align: right">Allocated per epoch (MiB)</th>
      <th style="text-align: right">Peak live storage (KiB)</th>
      <th style="text-align: right">Allocations per batch</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>S0 baseline</td>
      <td style="text-align: right">2.065</td>
      <td style="text-align: right">776.3</td>
      <td style="text-align: right">1420.8</td>
      <td style="text-align: right">35</td>
    </tr>
    <tr>
      <td>S1 partial pullbacks</td>
      <td style="text-align: right">1.373</td>
      <td style="text-align: right">412.9</td>
      <td style="text-align: right">827.8</td>
      <td style="text-align: right">29</td>
    </tr>
    <tr>
      <td>S2 direct matrix accumulation</td>
      <td style="text-align: right">1.369</td>
      <td style="text-align: right">398.2</td>
      <td style="text-align: right">827.8</td>
      <td style="text-align: right">28</td>
    </tr>
    <tr>
      <td>S3 buffer improvements</td>
      <td style="text-align: right">1.363</td>
      <td style="text-align: right">395.9</td>
      <td style="text-align: right">827.8</td>
      <td style="text-align: right">27</td>
    </tr>
    <tr>
      <td>S4 unused-adjoint fix</td>
      <td style="text-align: right">1.357</td>
      <td style="text-align: right">379.0</td>
      <td style="text-align: right">790.8</td>
      <td style="text-align: right">24</td>
    </tr>
    <tr>
      <td>Native LibTorch autograd</td>
      <td style="text-align: right">1.603</td>
      <td style="text-align: right">359.8</td>
      <td style="text-align: right">627.8</td>
      <td style="text-align: right">27</td>
    </tr>
  </tbody>
</table>

<p><img src="/images/blog/gsoc26-kacent-final/ablation-all-stages.svg" alt="Cumulative changes in training time, allocation volume, and peak live Tensor storage from S0 through S4." /></p>

<p>The time error bars show the minimum and maximum total training times across
the six runs. The largest improvement is S0 to S1: training time falls by
33.5%, and peak storage by 41.7%. Later stages mainly reduce allocations.</p>

<p>The <a href="/assets/docs/gsoc26-kacent-final/ablation-raw.csv">raw timing and allocation measurements</a>,
<a href="/assets/docs/gsoc26-kacent-final/ablation-summary.json">ablation summary</a>, and
<a href="/assets/docs/gsoc26-kacent-final/lifetime-summary.json">memory lifetime summary</a>
are available alongside this report.</p>

<h2 id="understanding-the-remaining-memory-gap">Understanding the remaining memory gap</h2>

<p>A Tensor’s last numerical use does not necessarily end its lifetime. A local
handle can keep storage alive until the function returns, and another handle
can retain an alias even after the first is moved. Generated code contained
patterns like this:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Tensor</span> <span class="n">saved_adjoint</span> <span class="o">=</span> <span class="n">clad</span><span class="o">::</span><span class="n">zero_like</span><span class="p">(</span><span class="n">hidden</span><span class="p">);</span>
<span class="n">Tensor</span> <span class="n">d_hidden</span> <span class="o">=</span> <span class="n">saved_adjoint</span><span class="p">;</span>  <span class="c1">// Another handle to the same storage.</span>
<span class="c1">// ... backward computations use d_hidden ...</span>
</code></pre></div></div>

<p>Even when the backward computation finishes using <code class="language-plaintext highlighter-rouge">d_hidden</code>, the redundant
<code class="language-plaintext highlighter-rouge">saved_adjoint</code> handle can retain that storage. Forward intermediates also
remain live beyond their last backward use. This explains why eliminating
allocations alone does not necessarily bring the peak down to native autograd.</p>

<p>To test the cause, I edited a copy of the generated derivative and inserted
<code class="language-plaintext highlighter-rouge">Tensor::reset()</code> after the last use of each local handle. The experiment kept
the derivative formulas and real <code class="language-plaintext highlighter-rouge">zero_like</code> initialization. Releasing a
redundant gradient alias also made a ReLU seed uniquely owned, enabling an
existing kernel to reuse it.</p>

<p><img src="/images/blog/gsoc26-kacent-final/mnist-memory-lifetime.svg" alt="Live Tensor storage within one batch for the final Clad version, manually inserted early release, and native autograd." /></p>

<p>The peak fell from 809,772 bytes to 642,856 bytes, a 20.6% reduction. Native
autograd used 642,864 bytes, just eight bytes more. Final parameters still
matched, accuracy remained 93.9%, and newly tracked storage returned to zero
at every batch end.</p>

<h2 id="contributions-to-clad">Contributions to Clad</h2>

<p>The integration exposed issues that also matter to other C++ types and
frontends. The following groups summarize the related compiler contributions.
Statuses are recorded as of November 5, 2026.</p>

<table>
  <thead>
    <tr>
      <th>Contribution</th>
      <th>Pull requests</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Construct zero adjoints from values and reuse the rule across generation paths</td>
      <td><a href="https://github.com/vgvassilev/clad/pull/1932">#1932</a>, <a href="https://github.com/vgvassilev/clad/pull/2068">#2068</a>, <a href="https://github.com/vgvassilev/clad/pull/2336">#2336</a>, <a href="https://github.com/vgvassilev/clad/pull/2353">#2353</a></td>
      <td>Merged</td>
    </tr>
    <tr>
      <td>Correct derivative lookup, temporary cloning, return handling, default initializers, and member calls</td>
      <td><a href="https://github.com/vgvassilev/clad/pull/1832">#1832</a>, <a href="https://github.com/vgvassilev/clad/pull/1926">#1926</a>, <a href="https://github.com/vgvassilev/clad/pull/2066">#2066</a>, <a href="https://github.com/vgvassilev/clad/pull/2067">#2067</a>, <a href="https://github.com/vgvassilev/clad/pull/2165">#2165</a>, <a href="https://github.com/vgvassilev/clad/pull/2168">#2168</a></td>
      <td>Merged</td>
    </tr>
    <tr>
      <td>Respect closed pragma intervals</td>
      <td><a href="https://github.com/vgvassilev/clad/pull/2175">#2175</a></td>
      <td>Merged</td>
    </tr>
    <tr>
      <td>Separate entry discovery from shared request planning</td>
      <td><a href="https://github.com/vgvassilev/clad/pull/2376">#2376</a></td>
      <td>Open</td>
    </tr>
    <tr>
      <td>Support partial pullbacks and the inactive-input assumption</td>
      <td><a href="https://github.com/vgvassilev/clad/pull/2495">#2495</a></td>
      <td>Open</td>
    </tr>
    <tr>
      <td>Avoid unused default adjoints for temporary receivers</td>
      <td><a href="https://github.com/vgvassilev/clad/pull/2496">#2496</a></td>
      <td>Open</td>
    </tr>
  </tbody>
</table>

<p>The LibTorch backend, adapter, tests, and benchmarks are developed in the
<a href="https://github.com/fogsong233/clad">project fork</a>. They build on these compiler
changes. I plan to submit the integration upstream once the supporting mechanisms
have been merged.</p>

<h2 id="next-steps">Next steps</h2>

<p>Two compiler improvements follow directly from the experiments. First,
generated pullbacks should be able to reuse the values produced by a separate
forward helper. Clad already provides <a href="https://github.com/vgvassilev/clad/blob/master/test/Gradient/PullbackState.C"><code class="language-plaintext highlighter-rouge">pullback_state</code></a> for a custom
<code class="language-plaintext highlighter-rouge">reverse_forw</code>/pullback pair to exchange per-call state. The next step is to
automate the selection and transport of saved values for generated functions.</p>

<p>Second, generated code should release Tensor storage once no later operation
needs it. The manual experiment gives a concrete target, but general support
must account for control flow, aliases, escaped references, and the type’s
release semantics. These two directions address complementary costs:
recomputation across function boundaries and excessive lifetimes within a
generated function.</p>

<p>I would like to thank my mentors Aaron Jomy, David Lange, and Vassil Vassilev. Their feedback
helped turn problems encountered in one Tensor backend into improvements that
other Clad users can build on.</p>]]></content><author><name>Kacent Huang</name></author><category term="gsoc" /><category term="c++" /><category term="clang" /><category term="clad" /><category term="libtorch" /><category term="pytorch" /><category term="machine-learning" /><summary type="html"><![CDATA[Integrating Clad-generated derivatives with LibTorch, training an MNIST model, and investigating where compile-time differentiation saves time and where Tensor memory still remains live.]]></summary></entry><entry><title type="html">Wrapping up GSoC 2026: Consolidate and advance the GPU infrastructure in Clad</title><link href="/blogs/gsoc26_vedant_final_blog/" rel="alternate" type="text/html" title="Wrapping up GSoC 2026: Consolidate and advance the GPU infrastructure in Clad" /><published>2026-10-30T00:00:00+00:00</published><updated>2026-10-30T00:00:00+00:00</updated><id>/blogs/consolidate-and-advance-the-gpu-infrastructure-in-Clad</id><content type="html" xml:base="/blogs/gsoc26_vedant_final_blog/"><![CDATA[<h3 id="introduction">Introduction</h3>

<p>When I began Google Summer of Code 2026, the goal was ambitious: to make GPU-based automatic differentiation more practical, reliable, and performant in Clad. The idea was to consolidate fragmented GPU support, extend reverse-mode differentiation for CUDA kernels, and validate the infrastructure against real-world High-Performance Computing (HPC) workloads.</p>

<p>This post takes you through that journey. We explore the main technical decisions, results and lessons learned while working on compiler-driven automatic differentiation.</p>

<p><strong>Mentors:</strong> Aaron Jomy, David Lange, Vassil Vassilev</p>

<h3 id="project-overview">Project Overview</h3>
<p>Clad is a Clang-based automatic differentiation tool for C++. It leverages Clang’s compiler infrastructure to analyze C++ source code and generate derivative computations at compile time.</p>

<p>Although Clad already had CUDA differentiation support, several GPU-related implementations were distributed across different branches and experimental contributions. This made it difficult to maintain consistent functionality and evaluate performance across GPU workloads.</p>

<p>My project focused on strengthening this infrastructure, improving reverse-mode differentiation for CUDA kernels, integrating HPC benchmarks, and addressing correctness issues exposed during development and testing.</p>

<h3 id="project-implementation">Project Implementation</h3>
<h3 id="phase1-strengthening-gpu-infrastructure">Phase1: Strengthening GPU Infrastructure</h3>
<h4 id="cuda-shared-memory-support">CUDA Shared Memory Support</h4>
<p>CUDA shared memory allows threads within a block to cooperate through a low-latency memory region. Supporting shared-memory operations in reverse-mode differentiation is important for differentiating GPU kernels that rely on thread cooperation and block-level computations.</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">__global__</span> <span class="kt">void</span> <span class="nf">sum_shared</span><span class="p">(</span><span class="kt">int</span> <span class="o">*</span><span class="n">input</span><span class="p">,</span> <span class="kt">int</span> <span class="o">*</span><span class="n">output</span><span class="p">,</span> <span class="kt">int</span> <span class="n">N</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">__shared__</span> <span class="kt">int</span> <span class="n">cache</span><span class="p">[</span><span class="mi">256</span><span class="p">];</span>
    <span class="kt">int</span> <span class="n">tid</span> <span class="o">=</span> <span class="n">threadIdx</span><span class="p">.</span><span class="n">x</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">idx</span> <span class="o">=</span> <span class="n">blockIdx</span><span class="p">.</span><span class="n">x</span> <span class="o">*</span> <span class="n">blockDim</span><span class="p">.</span><span class="n">x</span> <span class="o">+</span> <span class="n">tid</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">stride</span> <span class="o">=</span> <span class="n">blockDim</span><span class="p">.</span><span class="n">x</span> <span class="o">*</span> <span class="n">gridDim</span><span class="p">.</span><span class="n">x</span><span class="p">;</span>

    <span class="kt">int</span> <span class="n">local_sum</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">idx</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">N</span><span class="p">;</span> <span class="n">i</span> <span class="o">+=</span> <span class="n">stride</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">local_sum</span> <span class="o">+=</span> <span class="n">input</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
    <span class="p">}</span>
    <span class="n">cache</span><span class="p">[</span><span class="n">tid</span><span class="p">]</span> <span class="o">=</span> <span class="n">local_sum</span><span class="p">;</span>
    <span class="n">__syncthreads</span><span class="p">();</span>
    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">s</span> <span class="o">=</span> <span class="n">blockDim</span><span class="p">.</span><span class="n">x</span> <span class="o">/</span> <span class="mi">2</span><span class="p">;</span> <span class="n">s</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">;</span> <span class="n">s</span> <span class="o">/=</span> <span class="mi">2</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">tid</span> <span class="o">&lt;</span> <span class="n">s</span><span class="p">)</span>
            <span class="n">cache</span><span class="p">[</span><span class="n">tid</span><span class="p">]</span> <span class="o">+=</span> <span class="n">cache</span><span class="p">[</span><span class="n">tid</span> <span class="o">+</span> <span class="n">s</span><span class="p">];</span>
        <span class="n">__syncthreads</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">tid</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
        <span class="n">atomicAdd</span><span class="p">(</span><span class="n">output</span><span class="p">,</span> <span class="n">cache</span><span class="p">[</span><span class="mi">0</span><span class="p">]);</span>
<span class="p">}</span>
</code></pre></div></div>

<h4 id="enabling-restore_tracker-in-gpu-device-kernels">Enabling restore_tracker in GPU Device Kernels</h4>

<p>The restore tracker saves primal values during the forward sweep so they can be restored during reverse-mode differentiation. CUDA device support was introduced by adapting its storage for device execution, then optimized it by consolidating records into a single contiguous buffer to reduce per-value allocation overhead.</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#ifdef __CUDACC__
</span><span class="k">struct</span> <span class="nc">MetaData</span> <span class="p">{</span>
    <span class="kt">char</span><span class="o">*</span> <span class="n">addr</span><span class="p">;</span>
    <span class="kt">size_t</span> <span class="n">size</span><span class="p">;</span>
    <span class="kt">size_t</span> <span class="n">off</span><span class="p">;</span>
<span class="p">};</span>

<span class="n">MetaData</span> <span class="n">m_meta</span><span class="p">[</span><span class="n">Max_Records</span><span class="p">];</span>
<span class="kt">uint8_t</span> <span class="n">m_buf</span><span class="p">[</span><span class="n">Max_Bytes</span><span class="p">];</span>
<span class="kt">size_t</span> <span class="n">m_cnt</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">m_off</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

<span class="nl">public:</span>
    <span class="n">__host__</span> <span class="n">__device__</span> <span class="n">restore_tracker</span><span class="p">()</span> <span class="o">=</span> <span class="k">default</span><span class="p">;</span>

    <span class="k">template</span> <span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span>
    <span class="n">__host__</span> <span class="n">__device__</span> <span class="kt">void</span> <span class="n">store</span><span class="p">(</span><span class="k">const</span> <span class="n">T</span><span class="o">&amp;</span> <span class="n">val</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">for</span> <span class="p">(</span><span class="kt">size_t</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">m_cnt</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">m_meta</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">addr</span> <span class="o">==</span> <span class="p">(</span><span class="kt">char</span><span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">val</span><span class="p">)</span>
                <span class="k">return</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">m_cnt</span> <span class="o">&gt;=</span> <span class="n">Max_Records</span> <span class="o">||</span> <span class="n">m_off</span> <span class="o">+</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">T</span><span class="p">)</span> <span class="o">&gt;</span> <span class="n">Max_Bytes</span><span class="p">)</span> 
            <span class="k">return</span><span class="p">;</span>
        
        <span class="n">m_meta</span><span class="p">[</span><span class="n">m_cnt</span><span class="p">]</span> <span class="o">=</span> <span class="p">{(</span><span class="kt">char</span><span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">val</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">T</span><span class="p">),</span> <span class="n">m_off</span><span class="p">};</span>
        <span class="n">std</span><span class="o">::</span><span class="n">memcpy</span><span class="p">(</span><span class="n">m_buf</span> <span class="o">+</span> <span class="n">m_off</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">val</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">T</span><span class="p">));</span>
        <span class="n">m_off</span> <span class="o">+=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">T</span><span class="p">);</span>
        <span class="n">m_cnt</span><span class="o">++</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">__host__</span> <span class="n">__device__</span> <span class="kt">void</span> <span class="n">restore</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">for</span> <span class="p">(</span><span class="kt">size_t</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">m_cnt</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">std</span><span class="o">::</span><span class="n">memcpy</span><span class="p">(</span><span class="n">m_meta</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">addr</span><span class="p">,</span> <span class="n">m_buf</span> <span class="o">+</span> <span class="n">m_meta</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">off</span><span class="p">,</span>
                        <span class="n">m_meta</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">size</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="n">m_cnt</span> <span class="o">=</span> <span class="n">m_off</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>
<span class="cp">#endif
</span></code></pre></div></div>

<h4 id="cuda-activity-analysis-and-varied-analysis">CUDA Activity Analysis and Varied Analysis</h4>
<p>Activity analysis identifies variables that contribute to the differentiated result. CUDA built-ins such as <code class="language-plaintext highlighter-rouge">threadIdx</code>, <code class="language-plaintext highlighter-rouge">blockIdx</code>, <code class="language-plaintext highlighter-rouge">blockDim</code>, and <code class="language-plaintext highlighter-rouge">gridDim</code> are treated as passive to avoid unnecessary adjoint allocations and tape entries. Kernel-launch handling was also improved to correctly propagate variations through pointer arguments, ensuring that required adjoints and gradient seeds are not missed.</p>

<h3 id="phase2-hpc-benchmark-integration">Phase2: HPC Benchmark Integration</h3>

<p>An important part of the project was moving beyond isolated CUDA examples and evaluating Clad against representative HPC workloads.</p>

<h4 id="lulesh">LULESH</h4>

<p>It is a proxy application used in the HPC proxy application used to evaluate computational performance. In the tested configurations, Clad was <strong>6.4× faster</strong> at grid size 25 and <strong>8.6× faster</strong> at grid size 35.</p>

<p><img src="/images/blog/lulesh_benchmark.png" alt="Benchmarks" width="500px" /></p>

<h3 id="xsbench">XSBench</h3>

<p>XSBench is an HPC proxy application for Monte Carlo neutron transport simulations. In the tested configurations, results showed Clad running <strong>~2× faster</strong> than Enzyme.</p>

<p><img src="/images/blog/xsbench_benchmark.png" alt="Benchmarks" width="500px" /></p>

<h4 id="phase3-integrating-clad-with-gradbench">Phase3: Integrating Clad with GradBench</h4>
<p>GradBench is a benchmarking suite designed to compare automatic differentiation tools across different programming languages and computational domains. The incorporation of Clad into the GradBench benchmarking workflow exposed several edge cases in its differentiation and code-generation pipelines.</p>

<p>Some important bugs fixed:</p>
<ul>
  <li>Correct handling of calls inside Clad-generated derivative functions.</li>
  <li>Preventing duplicated tape-pop operations caused by cloning shared adjoint seeds.</li>
  <li>Correcting gradient accumulation for expressions involving side effects such as a[i++]</li>
</ul>

<p><img src="/images/blog/gradbench.png" alt="Benchmark" width="700px" /></p>

<h3 id="future-work">Future Work</h3>
<ul>
  <li>Further develop activity analysis for CUDA device code.</li>
  <li>Optimize GPU diff performance by improving memory management, synchronization, and tape operations to reduce overhead and improve scalability.</li>
</ul>

<h3 id="related-links">Related Links</h3>
<ul>
  <li><a href="https://hepsoftwarefoundation.org/gsoc/2026/proposal_Clad-GPU.html">Project Description</a></li>
  <li><a href="https://github.com/vgvassilev/clad">Clad Repository</a></li>
  <li><a href="/assets/docs/Vedant_Goyal_Proposal_2026.pdf">GSoC Project Proposal</a></li>
  <li><a href="https://github.com/Vedant2005goyal">My Github Profile</a></li>
</ul>]]></content><author><name>Vedant Goyal</name></author><category term="gsoc" /><category term="clad" /><category term="clang" /><category term="cuda" /><category term="c++" /><summary type="html"><![CDATA[A GSoC 2026 project aimed at consolidating the fragmented GPU work and advancing the GPU infrastructure]]></summary></entry><entry><title type="html">CARTopiaX: Extending a Next-Generation Platform for Computational Cancer Biology; Results</title><link href="/blogs/gsoc26_salvador_wrapup_blog/" rel="alternate" type="text/html" title="CARTopiaX: Extending a Next-Generation Platform for Computational Cancer Biology; Results" /><published>2026-10-27T00:00:00+00:00</published><updated>2026-10-27T00:00:00+00:00</updated><id>/blogs/cartopiax-extension-results</id><content type="html" xml:base="/blogs/gsoc26_salvador_wrapup_blog/"><![CDATA[<h2 id="introduction">Introduction</h2>

<p>This is my <strong>second Google Summer of Code</strong> with the Compiler Research Team. During <a href="https://compiler-research.org/blogs/gsoc25_salvador_wrapup_blog/">GSoC 2025</a> I created <strong>CARTopiaX</strong> from scratch, and this year I have extended it to replicate a new state-of-the-art wet-lab experiment, demonstrating that it can be adapted to study new biological scenarios.</p>

<h2 id="project-overview">Project Overview</h2>

<p><strong>CAR T-cell therapy</strong> is a form of cancer immunotherapy that engineers a patient’s T cells to recognize and destroy malignant cells. While it is <strong>highly effective in hematological cancers</strong> such as leukemia, and is supported by numerous mathematical models, it still <strong>struggles in solid tumors</strong>, where robust simulation models remain scarce despite their importance for optimizing treatment strategies.</p>

<p><strong>CARTopiaX</strong> is an <strong>agent-based model (ABM)</strong> built on <strong>BioDynaMo</strong>, a high-performance, open-source platform for large-scale biological modeling. It implements the mathematical framework described in the <em>Nature Scientific Reports</em> publication <em>“In silico study of heterogeneous tumour-derived organoid response to CAR T-cell therapy”</em> (2024), and provides a platform for simulating <strong>tumor–immune interactions</strong>, testing hypotheses, and evaluating CAR T-cell treatment strategies <em>in silico</em>.</p>

<p><b><u>Goal of this year's project:</u></b> extend and calibrate CARTopiaX to <strong>reproduce a state-of-the-art CAR T-cell experiment</strong>, demonstrating it as a <strong>flexible and robust framework</strong> for <em>in silico</em> hypothesis testing that accelerates research and reduces reliance on costly wet-lab experiments.</p>

<hr />

<h2 id="the-selected-paper-evaluating-car-t-cell-therapy-in-a-hypoxic-3d-tumor-model">The Selected Paper: Evaluating CAR-T Cell Therapy in a Hypoxic 3D Tumor Model</h2>

<p>The replicated study is <em>Ando et al., “Evaluating CAR-T Cell Therapy in a Hypoxic 3D Tumor Model”, Advanced Healthcare Materials (2019)</em>:</p>

<ul>
  <li><strong>Experimental setup:</strong> HER2+ SKOV3 <strong>ovarian cancer cells</strong> are embedded in a cylindrical 3D GelMA hydrogel with a radius of 3000 µm. A <strong>polycarbonate cap</strong> placed on top of the tumor acts as a diffusion barrier, so oxygen can only enter from the edges, creating a <strong>hypoxic environment</strong>. This is compared against <strong>normoxia</strong> (no cap).</li>
  <li><strong>Treatment protocol:</strong> anti-HER2 CAR T-cells are delivered through the channel surrounding the tumor at a <strong>20:1 effector-to-target (E:T) ratio</strong>, over a total experimental duration of <strong>72 hours</strong>.</li>
  <li><strong>Limited T-cell infiltration:</strong> despite high tumor mortality, CAR T-cell infiltration into the hydrogel was <strong>negligible</strong>, with most immune cells remaining at the edges.</li>
  <li><strong>Bystander killing:</strong> cancer cells <strong>died far from the CAR T-cells</strong>, in the core of the tumor. The authors called this <strong>“non-contact mediated” CAR T-cell cytotoxicity</strong> and hypothesized that it is driven by metabolic competition: activated CAR T-cells at the periphery consume nutrients, starving the already stressed cancer cells in the center.</li>
</ul>

<p><img src="/images/blog/cartopiax/paper_device_schematic.png" alt="Experimental device schematic" style="max-width: 70%; height: auto; display: block; margin: 0 auto;" /></p>
<p style="text-align: center;"><i>Experimental setup. Image from Ando et al. (2019).</i></p>

<hr />

<h2 id="the-new-model-a-cylindrical-tumor-mass">The New Model: a Cylindrical Tumor Mass</h2>

<p>To replicate this experiment, CARTopiaX was extended with a <strong>completely new scenario</strong>:</p>

<ul>
  <li><strong>New tumor geometry:</strong> a cylindrical tumor mass, where oxygen enters only from the border of the cylinder when the cap is present.</li>
  <li><strong>Glucose as a new diffusing substance:</strong> both tumor cells and CAR T-cells consume it. Its lack <strong>limits cell proliferation</strong> and can even <strong>starve cells to death</strong> (apoptosis).</li>
  <li><strong>New cell behaviors and mechanics:</strong> CAR T-cells now also <strong>consume oxygen and glucose</strong>, competing metabolically with cancer cells, while still moving by chemotaxis towards the immunostimulatory factor secreted by tumor cells and inducing apoptosis in them.</li>
  <li><strong>New outputs:</strong> radial profiles of all the simulation metrics, and tracking of the <strong>cause of death of each tumor cell</strong> (lack of oxygen, lack of glucose, CAR T-cell killing, or random natural causes).</li>
</ul>

<p><img src="/images/blog/cartopiax/model_outline2026.png" alt="New model diagram" style="max-width: 80%; height: auto; display: block; margin: 0 auto;" /></p>

<hr />

<h2 id="data-extraction-and-processing">Data Extraction and Processing</h2>

<p>The experimental data reported in the paper are <strong>radial profiles of dead tumor cells</strong>: the tumor is divided into concentric rings, and the number of dead cells in each ring is counted. To compare these data with CARTopiaX:</p>

<ol>
  <li>The data points were extracted from the figures of the paper and smoothed with a <strong>spline fit</strong>.</li>
  <li>Since the area of each ring grows with the radius, outer rings naturally contain more cells than inner ones. To study the trends independently of this effect, the absolute numbers were <strong>normalized by the area of each ring</strong>, obtaining a <strong>density of dead cells per µm²</strong>.</li>
</ol>

<p>Points at radii below 150 µm are omitted in the density plots: the innermost rings are so small that they contain very few cells, which results in large variations and a dividing area that tends to zero.</p>

<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">
  <p><img src="/images/blog/cartopiax/data_spline_fit.png" alt="Spline fit of the extracted data" style="width: 48%; min-width: 280px; height: auto;" />
  <img src="/images/blog/cartopiax/data_density_distribution.png" alt="Area-normalized density of dead cells" style="width: 48%; min-width: 280px; height: auto;" /></p>
</div>

<p>All CARTopiaX plots below show the <strong>mean and standard deviation over around five stochastic runs</strong>. We focus on reproducing the <strong>key trends</strong>, since the biological process is highly stochastic and the <strong>error bars in the paper are very large</strong>.</p>

<hr />

<h2 id="results">Results</h2>

<h3 id="oxygen-gradient-10-million-cellsml-with-cap-no-treatment">Oxygen gradient: 10 million cells/mL, with cap, no treatment</h3>

<p>The first step was to verify that the model reproduces the oxygen gradient created by the cap. The paper reports oxygen levels measured with sensors (orange), together with a simple differential equation model developed by the authors (blue), which is unrelated to CARTopiaX.</p>

<p>In CARTopiaX, oxygen flows in from the border of the cylinder (3000 µm) and is consumed by the cells, producing a <strong>decreasing oxygen profile towards the center</strong> that closely matches the experimental measurements after 24 hours.</p>

<p><img src="/images/blog/cartopiax/oxygen_profile_comparison.png" alt="Oxygen profile comparison" style="max-width: 80%; height: auto; display: block; margin: 0 auto;" /></p>
<p style="text-align: center;"><i>Left: oxygen profile reported by Ando et al. (2019). Right: CARTopiaX oxygen profile at minute 1440 (24 hours).</i></p>

<h3 id="no-treatment-without-cap-normoxia">No treatment, without cap (normoxia)</h3>

<p>Without the cap, oxygen can enter the whole tumor, so the environmental conditions are perfectly symmetric and <strong>cell death is uniform</strong> across the tumor. The absolute number of dead cells grows with the radius only because outer rings are larger, as the area-normalized plot shows.</p>

<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">
  <p><img src="/images/blog/cartopiax/no_treatment_no_cap_72h_counts.png" alt="No treatment without cap at 72h, dead cell counts" style="width: 48%; min-width: 280px; height: auto;" />
  <img src="/images/blog/cartopiax/no_treatment_no_cap_72h_density.png" alt="No treatment without cap at 72h, dead cell density" style="width: 48%; min-width: 280px; height: auto;" /></p>
</div>

<h3 id="no-treatment-with-cap-hypoxia">No treatment, with cap (hypoxia)</h3>

<p>Since oxygen now flows in only from the edges, the cap creates a <strong>hypoxic region in the center</strong> of the cylinder, which <strong>increases cell death in the core</strong>, as observed in the experiments.</p>

<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">
  <p><img src="/images/blog/cartopiax/no_treatment_cap_72h_counts.png" alt="No treatment with cap at 72h, dead cell counts" style="width: 48%; min-width: 280px; height: auto;" />
  <img src="/images/blog/cartopiax/no_treatment_cap_72h_density.png" alt="No treatment with cap at 72h, dead cell density" style="width: 48%; min-width: 280px; height: auto;" /></p>
</div>

<h3 id="glucose-starvation-kills-cells">Glucose starvation kills cells</h3>

<p>In the experiments, <strong>many more cells are dead by day 3 than by day 2</strong>. The device used by the researchers contains <strong>medium with glucose</strong> to feed the cells, and since it is <strong>not replaced</strong> during the experiment, glucose is progressively depleted. In CARTopiaX, this depletion explains the sharp increase in cell death during the last day.</p>

<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">
  <p><img src="/images/blog/cartopiax/no_treatment_cap_48h_counts.png" alt="No treatment with cap at 48h" style="width: 48%; min-width: 280px; height: auto;" />
  <img src="/images/blog/cartopiax/no_treatment_cap_72h_counts.png" alt="No treatment with cap at 72h" style="width: 48%; min-width: 280px; height: auto;" /></p>
</div>

<h3 id="car-t-cells-starve-cancer-cells">CAR T-cells starve cancer cells</h3>

<p>The following plots show the average glucose level and the number of dead tumor cells over time, with and without treatment. Without treatment, cells start dying from lack of glucose after around 2.25 days. When treatment is added, <strong>CAR T-cells also consume glucose</strong>, so it is depleted faster: cells start dying from glucose starvation earlier, and the total number of dead tumor cells by day 3 is much higher (around 4,300 instead of 2,400).</p>

<p>This mechanism contributes to what the authors call <strong>“non-contact mediated” CAR T-cell cytotoxicity</strong>: CAR T-cells kill cancer cells that they never touch, simply by competing with them for nutrients.</p>

<p><img src="/images/blog/cartopiax/glucose_and_deaths_over_time.png" alt="Glucose and cell deaths over time" style="max-width: 80%; height: auto; display: block; margin: 0 auto;" /></p>

<h3 id="201-treatment-without-cap-normoxia">20:1 treatment, without cap (normoxia)</h3>

<p>With CAR T-cell treatment and no cap, <strong>cell death is uniform</strong> across the tumor, <strong>except at the edge</strong>, where CAR T-cells target and kill tumor cells.</p>

<p><u>Unexpected emergent behavior:</u> cancer cell deaths <strong>drop at a radius of 3000 µm</strong>. This was not explicitly programmed: a large number of CAR T-cells enter from the edges and <strong>push tumor cells toward the center</strong>, leaving fewer cancer cells at the very border. This drop is also visible in the experimental data.</p>

<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">
  <p><img src="/images/blog/cartopiax/treatment_no_cap_72h_counts.png" alt="Treatment without cap at 72h, dead cell counts" style="width: 48%; min-width: 280px; height: auto;" />
  <img src="/images/blog/cartopiax/treatment_no_cap_72h_density.png" alt="Treatment without cap at 72h, dead cell density" style="width: 48%; min-width: 280px; height: auto;" /></p>
</div>

<h3 id="why-do-cancer-cells-die">Why do cancer cells die?</h3>

<p>One of the main advantages of an ABM is that it provides information that is very hard to measure in the lab, such as the <strong>cause of death of each cell</strong>. The following plots show the deaths by cause and the share of each cause as a function of the radius, after 72 hours:</p>

<ul>
  <li><strong>CAR T-cells barely infiltrate the tumor</strong>, as reported in the paper, so very few cancer cells are killed directly by them, and only near the edge.</li>
  <li><strong>Most cancer cell deaths are caused by glucose deprivation</strong> (around 80% across most of the tumor), which is <strong>exacerbated by glucose consumption by CAR T-cells</strong>.</li>
</ul>

<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">
  <p><img src="/images/blog/cartopiax/treatment_no_cap_death_causes_density.png" alt="Tumor cell deaths by cause vs radius without cap" style="width: 48%; min-width: 280px; height: auto;" />
  <img src="/images/blog/cartopiax/treatment_no_cap_death_causes_percentage.png" alt="Share of tumor cell death causes vs radius without cap" style="width: 48%; min-width: 280px; height: auto;" /></p>
</div>

<h3 id="201-treatment-with-cap-hypoxia">20:1 treatment, with cap (hypoxia)</h3>

<p>When the cap is added to the treated tumor:</p>

<ul>
  <li>Again, <strong>more cells die in the core</strong> due to <strong>oxygen deprivation</strong>, which is the main cause of death within the inner ~1200 µm. <strong>CAR T-cells also consume oxygen</strong>, further exacerbating the situation at the center.</li>
  <li>In the rest of the tumor, <strong>glucose deprivation</strong> remains the main cause of death.</li>
  <li>At the <strong>edges</strong>, CAR T-cells push and kill cancer cells, as before.</li>
</ul>

<p>As a result, cell death increases both at the core and at the edges, producing a <strong>U-shaped profile of dead cells</strong>, with a drop at a radius of 3000 µm due to the CAR T-cells pushing cancer cells inward. CARTopiaX closely reproduces this U-shaped profile observed in the paper.</p>

<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">
  <p><img src="/images/blog/cartopiax/treatment_cap_72h_density.png" alt="Treatment with cap at 72h, dead cell density" style="width: 48%; min-width: 280px; height: auto;" />
  <img src="/images/blog/cartopiax/treatment_cap_death_causes_percentage.png" alt="Share of tumor cell death causes vs radius with cap" style="width: 48%; min-width: 280px; height: auto;" /></p>
</div>

<h3 id="201-treatment-cell-deaths-in-the-middle-region-with-vs-without-the-cap">20:1 treatment: cell deaths in the middle region, with vs. without the cap</h3>

<p>Comparing both treated scenarios reveals another subtle trend, present both in the paper and in CARTopiaX:</p>

<ul>
  <li><strong>More cells die between radii 1400 and 2500 µm when there is no cap.</strong></li>
  <li>Without the cap, <strong>more oxygen is available</strong>, allowing cells to <strong>proliferate more</strong>, which consequently increases the number of cell deaths.</li>
  <li>This <strong>does not happen at the core</strong> because, with the cap, <strong>oxygen levels are so low</strong> that cells not only stop proliferating but also <strong>die much more frequently</strong>.</li>
  <li>At the <strong>edges</strong>, <strong>oxygen levels are sufficiently high</strong> in both cases, so cell death rates remain <strong>similar</strong>.</li>
</ul>

<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">
  <p><img src="/images/blog/cartopiax/treatment_no_cap_72h_counts.png" alt="Treatment without cap at 72h" style="width: 48%; min-width: 280px; height: auto;" />
  <img src="/images/blog/cartopiax/treatment_cap_72h_counts.png" alt="Treatment with cap at 72h" style="width: 48%; min-width: 280px; height: auto;" /></p>
</div>

<h3 id="low-density-1-million-cellsml-no-treatment">Low density: 1 million cells/mL, no treatment</h3>

<p>Finally, the experiment was repeated with a ten times lower cell density. With <strong>very few cells</strong> present, oxygen consumption is low, so both the normoxic (without cap) and hypoxic (with cap) conditions are <strong>effectively normoxic</strong>, resulting in <strong>no significant differences</strong> between them. In addition, since there are far fewer cells, they <strong>do not run out of glucose</strong>, and very few cells die. CARTopiaX reproduces this behavior as well.</p>

<p><img src="/images/blog/cartopiax/low_density_1M_no_treatment.png" alt="Low density without treatment" style="max-width: 80%; height: auto; display: block; margin: 0 auto;" /></p>
<p style="text-align: center;"><i>Left: results reported by Ando et al. (2019). Right: CARTopiaX, without cap (top) and with cap (bottom).</i></p>

<hr />

<h2 id="automated-model-calibration-with-bayesian-optimization">Automated Model Calibration with Bayesian Optimization</h2>

<p>Many parameters of the model <strong>cannot be measured in the lab</strong> or found in the biological literature, and each simulation is <strong>computationally expensive</strong>, so trying every combination of parameters (grid search) is not feasible.</p>

<p>To address this, I added a new <strong>calibration tool</strong> to the repository that automatically estimates the parameters that best reproduce experimental data:</p>

<ul>
  <li><strong>How it works:</strong> it uses <strong>Bayesian optimization</strong> through <strong>Optuna</strong> and its <strong>Tree-structured Parzen Estimator (TPE)</strong>. TPE builds a <strong>probabilistic surrogate</strong> from all previous trials, separating the parameter values that gave good results from the ones that gave bad results. The next trial is sampled where good values are more likely, <strong>balancing exploration and exploitation</strong> to <strong>minimize the number of costly simulations</strong>.</li>
  <li><strong>Robust to noise:</strong> since the model is stochastic, each candidate is evaluated over <strong>multiple Monte Carlo runs</strong> with different random seeds, and the error is averaged.</li>
  <li><strong>Flexible loss functions:</strong> the error can be computed on <strong>whole-tumor time series</strong> (e.g., average oxygen or tumor radius over time), on <strong>radial profiles</strong> at a fixed time, or with a <strong>user-defined</strong> function.</li>
  <li><strong>Ready to use:</strong> results are stored in a persistent study, so optimization runs can be <strong>resumed or extended</strong>.</li>
</ul>

<hr />

<h2 id="conclusion">Conclusion</h2>

<p>During this GSoC, CARTopiaX was extended to <strong>replicate a new wet-lab scenario</strong>, with a completely new tumor geometry, glucose as a new diffusing substance, and new cell behaviors and mechanics, together with a new <strong>Bayesian optimization tool</strong> for model calibration.</p>

<p>The extended model <strong>reproduces the key trends of the paper</strong>, including <strong>emergent behaviors that were not explicitly programmed</strong>, such as CAR T-cells pushing cancer cells inward. Moreover, it offers an <strong>in silico explanation of the “non-contact mediated” CAR T-cell cytotoxicity</strong> observed by the authors: glucose and oxygen competition between CAR T-cells and cancer cells. This explanation relies on data that is very hard to measure in the lab, such as the <strong>causes of death per radius</strong>.</p>

<p>Altogether, this work shows that CARTopiaX is a <strong>flexible platform</strong> for <strong>fast, low-cost hypothesis testing</strong> of CAR T-cell therapies, able to provide insights that cannot always be obtained experimentally.</p>

<hr />

<h2 id="related-links">Related Links</h2>

<ul>
  <li><a href="https://github.com/compiler-research/CARTopiaX">Project Repository</a></li>
  <li><a href="https://compiler-research.org/blogs/gsoc25_salvador_wrapup_blog/">GSoC 2025 Wrap-up Blog Post</a></li>
  <li><a href="https://github.com/BioDynaMo/biodynamo">BioDynaMo Repository</a></li>
  <li>Ando, Y., Siegler, E.L., Ta, H.P. et al. <em>Evaluating CAR-T Cell Therapy in a Hypoxic 3D Tumor Model.</em> Adv Healthc Mater 8(5), e1900001 (2019). <a href="https://doi.org/10.1002/adhm.201900001">DOI</a></li>
  <li>Luque, L.M., Carlevaro, C.M., Rodriguez-Lomba, E. et al. <em>In silico study of heterogeneous tumour-derived organoid response to CAR T-cell therapy.</em> Sci Rep 14, 12307 (2024). <a href="https://doi.org/10.1038/s41598-024-63125-5">DOI</a></li>
  <li><a href="https://github.com/salva24">My GitHub Profile</a></li>
</ul>]]></content><author><name>Salvador de la Torre Gonzalez</name></author><category term="gsoc" /><category term="BioDynaMo" /><category term="c++" /><category term="bayesian-optimization" /><summary type="html"><![CDATA[During GSoC 2026, CARTopiaX was extended to replicate a state-of-the-art wet-lab experiment of CAR T-cell therapy in a hypoxic 3D tumor model. The extended model reproduces the key trends of the study, offers an in silico explanation of the observed non-contact mediated CAR T-cell cytotoxicity, and includes a new Bayesian optimization tool for model calibration.]]></summary></entry><entry><title type="html">Improve Clang Performance</title><link href="/blogs/cppalliance26_ezzeldin_ibrahim_improve_clang_performance/" rel="alternate" type="text/html" title="Improve Clang Performance" /><published>2026-08-09T00:00:00+00:00</published><updated>2026-08-09T00:00:00+00:00</updated><id>/blogs/improve-clang-performance</id><content type="html" xml:base="/blogs/cppalliance26_ezzeldin_ibrahim_improve_clang_performance/"><![CDATA[<div class="custom-banner-wrapper" role="img" aria-label="">
  <div class="custom-banner-flex">
    <div class="banner-logo">
      <img src="/images/cppalliance-logo.svg" alt="Left Logo" />
    </div>

    <div class="banner-separator" aria-hidden="true">
      @
    </div>

    <div class="banner-logo logo-right-bg">
      <img src="/images/cr-logo_old.png" alt="Right Logo" />
    </div>
  </div>

  
  <div class="banner-caption" role="heading" aria-level="2">
    
  </div>
  
</div>

<style>
  .custom-banner-wrapper {
    --b-height: 20vh;
    width: 100%;
    max-width: 95%;
    margin: 0 auto;
    padding: 1.5rem 0;
  }

  .custom-banner-flex {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 3rem;
  }

  .banner-logo img {
    height: calc(var(--b-height) * 0.85);
    width: auto;
    max-width: 30vw;
    min-height: 50px;
    object-fit: contain;
  }

  /* Keep the white background for the right logo badge if needed */
  .logo-right-bg img {
    padding: 8px;
    background: #fff;
    border-radius: 4px;
  }

  .banner-separator {
    font-size: calc(var(--b-height) * 0.5);
    font-weight: 700;
    color: #000;
  }

  .banner-caption {
    text-align: center;
    margin-top: 1rem;
    font-family: Georgia, serif;
    font-size: calc(var(--b-height) * 0.25);
    color: #111;
  }

  @media (max-width: 768px) {
    .custom-banner-wrapper { --b-height: 15vh; }
    .custom-banner-flex { gap: 1.5rem; }
  }

  @media (max-width: 480px) {
    .custom-banner-flex { flex-direction: column; gap: 1rem; }
  }
</style>

<p>So yeah, this summer I am a compiler research fellow with <a href="https://compiler-research.org/blogs/cppalliance_fellowships_2026/">cppalliance</a>, where I need to somehow improve the performance of clang???!!</p>

<p>At first I was very lost on where to actually start.
Diving deep directly into clang to find an area to improve didn’t seem like the best idea. In fact, I did it a few weeks ago and was kinda grilled by the reviewers (:</p>

<p>So another idea was, instead of trying to do something entirely new, let’s look into the gaps between the work of clang maintainers.
Of course, the clang people won’t leave any obvious slowdown, and most PRs are already optimized, and if there are any big regressions they are caught really fast. So we are even looking into more hidden gaps, but I was kinda hopeful with this idea and more scared of the first one.</p>

<h2 id="how-to-actually-find-regressions">How to actually find regressions?</h2>
<p>If we are gonna look for regressions, we need targets. At first I tried SQLite and got good results, but my mentor quickly recommended I use Boost.MPL, and it was one of the best targets.
Out of the 20 regressions I have found during my search, MPL was affected noticeably by 8 of them.</p>

<p>And for clang, I decided to look for regressions within clang 18 up to clang 23.
I don’t exactly know where a regression may be located, so I try a number of commits within each version and measure (At first I used wall clock, which was really stupid, and I quickly switched to using Ir instructions using valgrind.) how much each version of clang costs on the targets,
then focus on that range to try to find what commit exactly caused that slowdown, slowly bisecting each range.</p>

<h2 id="first-fixable-regression-found">First fixable regression found</h2>

<p>So so far I had found a couple of regressions, but they were either intrinsic to how clang works now or already solved in trunk.
But finally, finally, after three weeks of searching, I found an actual fixable one.</p>

<p>Looks like when the Swift team’s fork upstreamed the <a href="https://clang.llvm.org/docs/APINotes.html">API Notes</a> feature, they didn’t notice that it also always runs even when there’s no need for it, for every project. <code class="language-plaintext highlighter-rouge">Sema::ProcessAPINotes</code> was being called on <em>every single declaration</em>, whether or not the file had any API Notes files loaded at all (which, for basically most projects, is never).
And this had remained unnoticed in clang for about two years.</p>

<p>So I filed an issue: <a href="https://github.com/llvm/llvm-project/issues/202214">#202214 — Sema::ProcessAPINotes runs on every decl even when API Notes aren’t used</a>.</p>

<p>And it was fixed quite simply too, instead of running the API-notes lookup multiple times, just run it once and reuse the value, then also cache whether API Notes are needed at all so the per-decl work is skipped entirely.</p>

<p>So together that’s roughly a <strong>−0.2%</strong> improvement in clang.</p>

<p>It seems very minuscule, but like I said, we are looking through the gaps and these very small easy to fix regressions accumulate over time and cause actual slowness.</p>

<h2 id="the-manyclangs-project">The ManyClangs Project!</h2>
<p>The <a href="https://github.com/elfshaker/manyclangs">manyclangs</a> project saved this project a huge amount of time. One of the bottlenecks of the project was that compiling a commit of clang took so long, about 40 minutes for each one even with the help of ccache.
So with the manyclangs, after downloading 5GBs of data, it does some compressing and version-control magic, and I can access the binary of any clang commit in seconds. This lets me do sweeps at much larger scales at incredible speed.</p>

<h2 id="benchmarking-projects">Benchmarking projects</h2>

<table>
  <thead>
    <tr>
      <th>project</th>
      <th>language</th>
      <th>what it stresses in clang</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>SQLite</td>
      <td>C</td>
      <td>the C frontend over one giant amalgamation, parsing and sema on a huge TU</td>
    </tr>
    <tr>
      <td>Boost.MPL</td>
      <td>C++</td>
      <td>heavy template instantiation / template metaprogramming</td>
    </tr>
    <tr>
      <td>Boost.Hana</td>
      <td>C++</td>
      <td>modern metaprogramming, constexpr mixed with templates</td>
    </tr>
    <tr>
      <td>Boost.Spirit</td>
      <td>C++</td>
      <td>expression-template EDSLs and deep template nesting</td>
    </tr>
    <tr>
      <td>range-v3</td>
      <td>C++</td>
      <td>ranges and heavily constrained templates</td>
    </tr>
    <tr>
      <td>fmt</td>
      <td>C++</td>
      <td>templates plus constexpr</td>
    </tr>
    <tr>
      <td>kernel headers</td>
      <td>C</td>
      <td>the preprocessor and parser (tons of macros)</td>
    </tr>
    <tr>
      <td>Eigen</td>
      <td>C++</td>
      <td>expression templates (linear algebra)</td>
    </tr>
    <tr>
      <td>stdexec</td>
      <td>C++20</td>
      <td>concepts and constraint satisfaction</td>
    </tr>
    <tr>
      <td>mp-units</td>
      <td>C++23</td>
      <td>concepts plus non-type template parameters (a units library)</td>
    </tr>
  </tbody>
</table>

<p>I tried, when adding new projects, to make sure they test a new part of clang, and so far each has helped in finding some regressions.</p>

<h2 id="how-is-the-work-so-far">How is the work so far</h2>

<p>So far I’ve landed a bunch of these small fixes upstream. Here’s every PR, what it fixed, and how much it bought:</p>

<table>
  <thead>
    <tr>
      <th>#</th>
      <th>PR</th>
      <th>fix</th>
      <th>local benchmarks</th>
      <th>LLVM tracker</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/202727">#202727</a></td>
      <td>APINotes: early return when no apinotes files are loaded</td>
      <td>-0.4% MPL</td>
      <td><strong>−0.11%</strong></td>
    </tr>
    <tr>
      <td>2</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/203710">#203710</a></td>
      <td>APINotes: skip per-decl work when no notes are active</td>
      <td>(follow-up to above)</td>
      <td><strong>−0.07%</strong></td>
    </tr>
    <tr>
      <td>3</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/204926">#204926</a></td>
      <td>only record lexer check-points when colors are enabled</td>
      <td>part of a +0.3% step</td>
      <td>+0.07%</td>
    </tr>
    <tr>
      <td>4</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/209355">#209355</a></td>
      <td>fix check-point recording under default colors</td>
      <td>fixes a regression <strong>#204926 caused</strong></td>
      <td><strong>−0.20%</strong></td>
    </tr>
    <tr>
      <td>5</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/208862">#208862</a></td>
      <td>skip macro source-location check for names that can’t warn</td>
      <td>−0.7% kernel, −0.3% MPL</td>
      <td>~0%</td>
    </tr>
    <tr>
      <td>6</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/208139">#208139</a></td>
      <td>compute current instantiation less often in <code class="language-plaintext highlighter-rouge">lookupInBases</code></td>
      <td>~99% of a +0.4% step</td>
      <td><strong>−0.03%</strong></td>
    </tr>
    <tr>
      <td>7</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/209694">#209694</a></td>
      <td>no typo-correction suggestions for disabled diagnostics</td>
      <td><strong>−1.2% MPL</strong>, −0.2% kernel</td>
      <td><strong>−0.28%</strong></td>
    </tr>
    <tr>
      <td>8</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/206363">#206363</a></td>
      <td>don’t add doc comments to the AST if not requested</td>
      <td>−5% on comment-heavy TUs</td>
      <td><strong>−0.24%</strong></td>
    </tr>
    <tr>
      <td>9</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/212213">#212213</a></td>
      <td>cache the analysis-based warning policy instead of recomputing it per body</td>
      <td><strong>−0.3% MPL</strong>, −0.5% fmt</td>
      <td><strong>−0.11%</strong></td>
    </tr>
    <tr>
      <td>10</td>
      <td><a href="https://github.com/llvm/llvm-project/pull/213790">#213790</a></td>
      <td>avoid quadratic pack-indexing instantiation</td>
      <td>O(N²)→O(N): <strong>~14.6× faster, ~31× less memory</strong> at N=8k</td>
      <td>~0%</td>
    </tr>
  </tbody>
</table>

<p><em>tracker = llvm-compile-time-tracker.com, geomean <code class="language-plaintext highlighter-rouge">instructions:u</code></em></p>

<p>Overall I made clang faster by a whole 1.25%! All with very small and simple changes.</p>

<p>For context, a 1% improvement in Clang’s compilation speed may seem modest, but its cumulative impact is enormous. Clang is one of the world’s most widely used C and C++ compilers, powering software development across operating systems, browsers, mobile platforms, cloud infrastructure, game engines, and embedded devices. Every day, millions of developers and continuous integration systems invoke Clang countless times. As a result, even a 1% reduction in compilation time translates into millions of CPU-hours saved annually worldwide, reducing energy consumption, lowering infrastructure costs, and enabling developers to receive build feedback more quickly. In a tool used at such global scale, seemingly small performance gains compound into substantial economic and productivity benefits, making a 1% improvement a real achievement.</p>

<p>Most of them were fixed with a few lines consisting of:</p>

<p>A. Caching with a simple boolean so we don’t recalculate a heavy computation <a href="https://github.com/llvm/llvm-project/pull/203710">#203710</a>, <a href="https://github.com/llvm/llvm-project/pull/208139">#208139</a>, <a href="https://github.com/llvm/llvm-project/pull/212213">#212213</a></p>

<p>B. Reorder some conditions so that the heavy computation is stopped early if it’s not needed <a href="https://github.com/llvm/llvm-project/pull/202727">#202727</a>, <a href="https://github.com/llvm/llvm-project/pull/208862">#208862</a></p>

<p>C. Something ran when it shouldn’t, like how the computations for some of the diagnostics ran even though warnings were disabled <a href="https://github.com/llvm/llvm-project/pull/204926">#204926</a>, <a href="https://github.com/llvm/llvm-project/pull/209355">#209355</a>, <a href="https://github.com/llvm/llvm-project/pull/209694">#209694</a>, <a href="https://github.com/llvm/llvm-project/pull/206363">#206363</a></p>

<h2 id="a-few-of-these-up-close">A few of these up close</h2>

<ol>
  <li>
    <p><strong>Skip the macro source-location check for names that can’t warn (<a href="https://github.com/llvm/llvm-project/pull/208862">#208862</a>).</strong> Every time clang sees a macro name it was doing a source-location lookup to decide whether to warn about it, but most macro names can’t ever trigger that warning, so the lookup was pure waste. The fix checks the cheap “can this name even warn?” condition first and skips the lookup otherwise. That’s worth −0.7% on kernel headers (which are basically all macros) and −0.3% on MPL.</p>
  </li>
  <li>
    <p><strong>Don’t add doc comments to the AST if not requested (<a href="https://github.com/llvm/llvm-project/pull/206363">#206363</a>).</strong> clang was collecting doc comments into the AST even when nothing was going to use them, no <code class="language-plaintext highlighter-rouge">-Wdocumentation</code>, nobody asking for them. On comment-heavy files that’s a lot of parsing and allocation for nothing. The fix only keeps the comments when something actually asked for them, which is up to −5% on comment-heavy TUs.</p>
  </li>
  <li>
    <p><strong>Only record lexer check-points when colors are enabled (<a href="https://github.com/llvm/llvm-project/pull/204926">#204926</a>).</strong> clang records “check-points” while lexing that are only needed to render colored diagnostics, so I gated recording them behind the colors-enabled check. Unfortunately, mid-PR another related PR got merged, so after fixing the merge conflicts, merging it caused my first clang regression, and it was quickly fixed with a follow-up.</p>
  </li>
  <li>
    <p><strong>No typo-correction suggestions for disabled diagnostics (<a href="https://github.com/llvm/llvm-project/pull/209694">#209694</a>).</strong> When clang sees something it doesn’t recognize, like an unknown attribute or a misspelled preprocessor directive, it runs an edit-distance search to suggest “did you mean X ?”. The problem is it was doing that search even when the warning that would show the suggestion is turned off. On Boost.MPL and the kernel headers that’s a huge pile of wasted scans, since the system headers trip it constantly, so only running it when the diagnostic is actually enabled is worth −1.2% on MPL and −0.2% on the kernel.</p>
  </li>
</ol>

<h2 id="ai-usage-in-finding-regressions">AI Usage in finding regressions</h2>
<p>AI agents really helped in this project. Here are some points where AI was heavily utilised:</p>
<ol>
  <li>I don’t really care about how MPL is built, or any of the 10 other projects, so agents helped set up the environments, dependencies, etc.</li>
  <li>A lot of utility and helper scripts that are used in the benchmarking and the sweeps were made with the help of agents.</li>
  <li>Agents were always monitoring the bisecting process, documenting interesting results as it goes, and intervening if there were any problems.</li>
  <li>If it found a particular jump in the sweeps, it would continue focusing until it found the first bad commit.</li>
  <li>Search the reviews and issues if the found regression is mentioned anywhere, or if the overhead was known when reviewing.</li>
  <li>Check if the regression is still live on trunk and it wasn’t fixed or reverted already.</li>
</ol>

<p>And since I am touching a lot of unfamiliar parts of clang it helped and misled me a lot of times when trying to understand related clang code, I avoided using it to directly make fixes if the fix is not super obvious.</p>

<h2 id="what-is-next">What is next</h2>

<p>Currently I have done a sweep on clangs with different options (<code class="language-plaintext highlighter-rouge">-fsyntax-only</code>, <code class="language-plaintext highlighter-rouge">-Wdocumentation</code>, <code class="language-plaintext highlighter-rouge">-Wall -Wextra</code>, <code class="language-plaintext highlighter-rouge">-std=c++20</code>, <code class="language-plaintext highlighter-rouge">-O2</code>, <code class="language-plaintext highlighter-rouge">-emit-llvm-only</code>)
and mostly focused on benchmarking for Ir.
Out of the 20 regressions found, only 8 were fixable so far.
Most of them were already solved, or intrinsic, or too complicated to know if they are actually intrinsic or if they could possibly be improved.
Currently I am making a sweep on peak-heap / total memory to hopefully find areas to improve, and will try other possible measurements.
There are some issues that I have also put in my to-do. I will at least try to bisect the cause.</p>]]></content><author><name>Ezzeldin Ibrahim</name></author><category term="cppalliance" /><category term="clang" /><category term="performance" /><category term="benchmarking" /><category term="memory-optimization" /><category term="codegen" /><summary type="html"><![CDATA[A CppAlliance Fellowship 2026 project to systematically improve Clang's performance: benchmarking real-world codebases across releases to find compile-time and memory regressions, tracing them to the upstream changes that caused them, and upstreaming targeted, data-driven fixes.]]></summary></entry><entry><title type="html">Enabling Differentiable Rendering via AD of Parallel C++ STL Primitives in Clad</title><link href="/blogs/gsoc26_abdelrhman_elrawy_introduction_blog" rel="alternate" type="text/html" title="Enabling Differentiable Rendering via AD of Parallel C++ STL Primitives in Clad" /><published>2026-06-17T00:00:00+00:00</published><updated>2026-06-17T00:00:00+00:00</updated><id>/blogs/enabling-differentiable-rendering-via-AD-in-clad</id><content type="html" xml:base="/blogs/gsoc26_abdelrhman_elrawy_introduction_blog"><![CDATA[<h2 id="about-me">About Me</h2>

<p>Hi! I’m Abdelrhman Elrawy, a graduate student in Applied Computing specializing in Machine Learning and Parallel Programming. After successfully adding Thrust API support to Clad during GSoC 2025, I’m back this summer to work on <strong>Enabling Differentiable Rendering via AD of Parallel C++ STL Primitives in Clad</strong>.</p>

<h2 id="project-description">Project Description</h2>

<p><a href="https://github.com/vgvassilev/clad">Clad</a> is a Clang-based automatic differentiation (AD) tool. This project proposes to enhance Clad by leveraging its liveness analysis to automatically generate lock-free backward passes for highly parallel differentiable rendering pipelines. Specifically, the project targets the atomic bottleneck inherent in 3D Gaussian Splatting (3DGS) rasterization.</p>

<p>Modern GPU-based differentiable renderers suffer from heavy use of atomic operations (e.g., <code class="language-plaintext highlighter-rouge">atomicAdd</code>) during the backward pass because many threads attempt to update the same pixel and gradient buffers simultaneously. This contention overwhelms L2 cache atomic units, stalling execution and causing the gradient computation to consume a significant portion of training time.</p>

<h2 id="technical-approach">Technical Approach</h2>

<p>My approach is twofold:</p>

<ol>
  <li>
    <p><strong>Redesign the Rendering Pipeline</strong>: I will avoid write conflicts by construction using deterministic sorting, tile-based memory ownership, and local accumulation before a single global write. Crucially, I plan to build this new architecture on top of my previous GSoC work that integrated the Thrust API into Clad. By utilizing Thrust’s highly optimized parallel primitives (such as <code class="language-plaintext highlighter-rouge">thrust::sort_by_key</code> and <code class="language-plaintext highlighter-rouge">thrust::reduce</code>) for the sorting and tile-based operations, we can provide a clean, high-level C++ structure to the compiler.</p>
  </li>
  <li>
    <p><strong>Generate the Backward Pass</strong>: I will utilize Clad to automatically generate the backward pass. By relying on Clad’s liveness analysis, the compiler will prove exclusive memory ownership and automatically eliminate the need for <code class="language-plaintext highlighter-rouge">atomicAdd</code> calls. To isolate the compiler complexity from the graphics complexity, the project will use a differentiable geometry path tracer as the foundational stepping stone.</p>
  </li>
</ol>

<h2 id="expected-outcomes">Expected Outcomes</h2>

<p>Beyond differentiable rendering, this work establishes a foundation for compiler-driven automatic differentiation of parallel C++ programs, enabling efficient gradient computation in a wide range of high-performance computing applications.</p>

<h2 id="related-links">Related Links</h2>

<ul>
  <li><a href="https://github.com/vgvassilev/clad">Clad GitHub</a></li>
  <li><a href="/assets/docs/Abdelrhman_Elrawy_Proposal_GSoC_2026.pdf">Project Proposal</a></li>
  <li><a href="https://github.com/a-elrawy">My GitHub</a></li>
</ul>]]></content><author><name>Abdelrhman Elrawy</name></author><category term="gsoc" /><category term="llvm" /><category term="clang" /><category term="automatic-differentiation" /><category term="gpu" /><category term="cuda" /><category term="thrust" /><category term="rendering" /><category term="3dgs" /><summary type="html"><![CDATA[This summer, I am working on enhancing Clad to automatically generate lock-free backward passes for highly parallel differentiable rendering pipelines. This project targets the atomic bottleneck inherent in 3D Gaussian Splatting (3DGS) rasterization.]]></summary></entry><entry><title type="html">Final report for creating teaching materials with xeus-cpp</title><link href="/blogs/xeus-cpp_Hristiyan_Shterev_blog_final/" rel="alternate" type="text/html" title="Final report for creating teaching materials with xeus-cpp" /><published>2026-06-10T00:00:00+00:00</published><updated>2026-06-10T00:00:00+00:00</updated><id>/blogs/creating-teaching-materials-xeus-cpp-final</id><content type="html" xml:base="/blogs/xeus-cpp_Hristiyan_Shterev_blog_final/"><![CDATA[<div class="custom-banner-wrapper" role="img" aria-label="">
  <div class="custom-banner-flex">
    <div class="banner-logo">
      <img src="/images/mg-pld-logo.png" alt="Left Logo" />
    </div>

    <div class="banner-separator" aria-hidden="true">
      @
    </div>

    <div class="banner-logo logo-right-bg">
      <img src="/images/cr-logo_old.png" alt="Right Logo" />
    </div>
  </div>

  
  <div class="banner-caption" role="heading" aria-level="2">
    
  </div>
  
</div>

<style>
  .custom-banner-wrapper {
    --b-height: 20vh;
    width: 100%;
    max-width: 95%;
    margin: 0 auto;
    padding: 1.5rem 0;
  }

  .custom-banner-flex {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 3rem;
  }

  .banner-logo img {
    height: calc(var(--b-height) * 0.85);
    width: auto;
    max-width: 30vw;
    min-height: 50px;
    object-fit: contain;
  }

  /* Keep the white background for the right logo badge if needed */
  .logo-right-bg img {
    padding: 8px;
    background: #fff;
    border-radius: 4px;
  }

  .banner-separator {
    font-size: calc(var(--b-height) * 0.5);
    font-weight: 700;
    color: #000;
  }

  .banner-caption {
    text-align: center;
    margin-top: 1rem;
    font-family: Georgia, serif;
    font-size: calc(var(--b-height) * 0.25);
    color: #111;
  }

  @media (max-width: 768px) {
    .custom-banner-wrapper { --b-height: 15vh; }
    .custom-banner-flex { gap: 1.5rem; }
  }

  @media (max-width: 480px) {
    .custom-banner-flex { flex-direction: column; gap: 1rem; }
  }
</style>

<h2 id="main-goals-of-this-project">Main goals of this project</h2>

<p>The main goal of this project was to create interactable examples for the for the CUDA and OpenMP programming models, targeting beginners who want hands-on experience with parallel computing on both the GPU and CPU.</p>

<p>Each notebook builds on the previous one, introducing new concepts gradually through working code examples.</p>

<p>Together the 16 notebooks cover the full beginner to intermediate journey - from launching a first thread to understanding memory hierarchies, synchronisation primitives, and performance optimization on both CPU and GPU.</p>

<h2 id="the-cuda-notebooks">The CUDA notebooks</h2>

<p>The CUDA notebooks include 8 different examples that add to one another. Here is what each one explains:</p>

<ul>
  <li>The first notebook is a basic introduction to CUDA with simple examples like the <strong>global</strong> kernel usage and calling it.</li>
  <li>Next we introduce some more fundamental concepts.</li>
  <li>The third notebook shows how using parallel programming can speed up if we use the threads the right way.</li>
  <li>After that we show thread cooperation. The threads split the work instead of having one thread per task</li>
  <li>Then we demonstrate The Julia set. A complex mathematical shape.</li>
  <li>The sixth example creates a ripple pattern.</li>
  <li>Next we demonstrate the dot product. A mathematical operation that takes two equal-length vectors and returns a single regular number</li>
  <li>Lastly there is a simple ray tracing example.</li>
</ul>

<h3 id="cuda-benchmark-vs-the-cpu">CUDA benchmark vs the CPU</h3>

<p>This benchmark adds two vectors with 10 million elements each into a third one. This is done 3 times using different methods.</p>

<ul>
  <li>The first one is a basic CPU only demonstration. The time is around 21 ms.</li>
  <li>The second example is using the GPU but with only 1 thread per block. We can see that this is slower compared to the first one. This is a very unoptimized way to use the device.</li>
  <li>The third method is now a lot faster than the other 2. We make each block use 256 threads which speeds up the time by a lot - around 2 milliseconds.</li>
</ul>

<p><img src="/images/blog/cuda-vs-cpu-benchmark.png" alt="Benchmarked comparison of CUDA vs the CPU" style="max-width: 70%; height: auto; display: block; margin: 0 auto;" /></p>

<h2 id="the-openmp-notebooks">The OpenMP notebooks</h2>

<p>The OpenMP notebooks also include 8 different examples that add to one another. Here is what each one explains:</p>

<ul>
  <li>The first notebook is a basic introduction to OpenMP with simple examples like the #pragma omp parallel directive and thread creation.</li>
  <li>Next we introduce the fork-join model and how threads are spawned and joined back together.</li>
  <li>Then we demonstrate the Pi integral. A mathematical problem solved by splitting the work across multiple threads.</li>
  <li>The fourth notebook calculates the area of the Mandelbrot set. A complex mathematical shape rendered in parallel by assigning different regions to different threads.</li>
  <li>After that we show linked list traversal. How pointer-based data structures interact with parallel execution.</li>
  <li>The sixth example demonstrates race conditions. What happens when threads write to the same memory without protection and how to fix it.</li>
  <li>Next we demonstrate false sharing. How threads can slow each other down even when touching different variables due to CPU cache line behaviour.</li>
  <li>Lastly there is Conway’s Game of Life. A grid simulation where threads compute the next generation in parallel using double buffering to avoid race conditions by design.</li>
</ul>

<h2 id="related-links">Related links</h2>

<ul>
  <li><a href="https://github.com/compiler-research/xeus-cpp">Xeus-cpp repository</a></li>
  <li><a href="https://github.com/HrisShterev">My github account</a></li>
  <li><a href="https://github.com/compiler-research/live-cpp-tutorials/">Notebooks repository</a></li>
</ul>]]></content><author><name>Hristiyan Shterev</name></author><category term="c++" /><category term="xeus-cpp" /><category term="jupyter" /><category term="internship" /><category term="systems-programming" /><category term="high-school" /><category term="cuda" /><summary type="html"><![CDATA[A Final report of my project about creating notebooks for CUDA and OpenMP with xeus-cpp]]></summary></entry></feed>