Skip to content

Reduce compile time of FunctionBinaryArithmetic and related headers - #98204

Merged
Algunenano merged 12 commits into
ClickHouse:masterfrom
Algunenano:more_alexey_build
Mar 2, 2026
Merged

Algunenano merged 12 commits into
ClickHouse:masterfrom
Algunenano:more_alexey_build

Conversation

@Algunenano

@Algunenano Algunenano commented Feb 27, 2026 •

Copy link
Copy Markdown
Member

Ref #96721

Summary

  • Move ConvertImplFromDynamicToColumn::execute out of header into .cpp
  • Reduce type dispatch matrix in FunctionBinaryArithmetic for non-string operations by excluding FixedString/String when unused
  • Exclude Date/DateTime/Time from arithmetic type dispatch when the operation doesn't use them (needs_date_time flag)
  • Exclude Decimal types from arithmetic type dispatch when allow_decimal is false (needs_decimal flag)
  • Handle Decimal × Float arithmetic at runtime to avoid 24 redundant template instantiations
  • Replace std::vector<Int64> with three plain Int64 fields in VersionNumber, removing <vector> from a widely-included header
  • Remove unused writeJSONBinary along with Poco/JSON/Object.h, Poco/JSON/Stringifier.h, and <sstream> from WriteHelpers.h
  • Forward-declare llvm::IRBuilderBase in Native.h instead of including the heavy <llvm/IR/IRBuilder.h> header; move toNativeType<T> template to .cpp with explicit instantiations

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reduce compile time of arithmetic functions and related headers by shrinking template dispatch matrices and removing heavy includes.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.3.1.279

Algunenano and others added 8 commits February 27, 2026 12:10
Move the body of `ConvertImplFromDynamicToColumn::execute` from
`FunctionsConversion.h` to `FunctionsConversion.cpp` and remove the
now-redundant `#include <Columns/ColumnDynamic.h>` from the header.

This reduces compile time of each of the 32 `FunctionsConversion_impl*.cpp`
translation units by ~21% (~1.4 sec per TU) by eliminating redundant
template instantiation and optimization of the function body in every TU.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ing operations

Only `plus`, `minus`, and `bitHammingDistance` need `String`, `FixedString`,
and `Interval` types in the `castType` dispatch. All other arithmetic operations
(multiply, divide, modulo, intDiv, etc.) reject these types anyway.

By splitting `castType` into two branches using `if constexpr`, we reduce
the type list from 24 to 21 types for the majority of operations, cutting
the `castBothTypes` combination matrix from 576 to 441 (23% reduction).

Build time impact (128-core aarch64 cross-compilation):
- `positiveModulo.cpp.o`: 63.5s -> 57.7s (-9%)
- `multiply.cpp.o`: 57.5s -> 50.0s (-13%)
- `modulo.cpp.o`: 54.6s -> 52.0s (-5%)
- Clean build wall time: 286.0s -> 281.7s

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…nused

Operations like multiply, divide, intDiv, bitHammingDistance, and midpoint
always produce `InvalidType` for Date/DateTime/Time in
`BinaryOperationTraits::ResultDataType`. Including these 3 types in the
`castType` type list wastes ~120 type-pair instantiations per operation
(matrix drops from 22x22=484 to 19x19=361).

Add a compile-time `needs_date_time` flag (following the existing
`needs_string_types` / `needs_interval` pattern) that includes
Date/DateTime/Time only for operations that actually use them: `plus`,
`minus`, `least`, `greatest`, `modulo`, `positive_modulo`.

Measured on `multiply.cpp`: total compile time 23.9s → 22.3s (-6.7%),
frontend -9.1%, backend -5.5%.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…imal` is false

19 operations (all bitwise ops, GCD, LCM, `divideOrNull`, `intDivOrNull`,
`moduloOrNull`, `positiveModuloOrNull`, `moduloOrZero`, `moduloLegacy`)
have `allow_decimal = false`, meaning every Decimal-involving type pair
produces `InvalidType` and is immediately discarded. Including the 4
Decimal types in their dispatch list wastes significant instantiation work.

Add a compile-time `needs_decimal` flag (following the existing
`needs_date_time` / `needs_string_types` / `needs_interval` pattern)
that includes Decimal types only when `IsOperation<Op>::allow_decimal`
is true.

For operations that exclude Decimals, the type matrix shrinks by 34-44%:
e.g. `bitAnd` drops from 21 to 17 types (441 → 289 pairs),
`intDivOrNull` from 16 to 12 types (256 → 144 pairs).

Operations that use Decimals (plus, minus, multiply, divide, intDiv,
intDivOrZero, modulo, positiveModulo, least, greatest, midpoint) are
unaffected.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ntiations

All 24 Decimal × Float type pairs (4 Decimal widths × 3 Float widths ×
2 directions) produce identical code: convert both sides to Float64 and
compute Float64 × Float64. Handle this case at runtime in `executeImpl2`
(following the existing IPv4/IPv6 pattern) and add an `if constexpr`
guard in the `castBothTypes` lambda to skip these pairs at compile time.

This eliminates 24 `executeNumeric` template instantiations and ~36
backend functions per TU for operations that support both Decimal and
Float types (multiply, divide, plus, minus, etc.).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The `VersionNumber` class used `std::vector<Int64>` to store components,
but all usage is with exactly 2-3 components (major, minor, patch).
Replace with three `Int64` fields to avoid pulling `<vector>` into every
TU that includes `FunctionDocumentation.h` → `VersionNumber.h`.

Fields are named `version_major`/`version_minor`/`version_patch` to
avoid conflict with `major`/`minor` macros from `<sys/sysmacros.h>`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The `writeJSONBinary` function was the only user of `Poco/JSON/Object.h`
and `Poco/JSON/Stringifier.h` in this header, and it had zero callers
anywhere in the codebase. Remove the dead function along with the
now-unused `<sstream>` include.

Add missing `#include <bitset>` to `SettingsConstraints.cpp` which was
getting it transitively through `<sstream>`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ing `<llvm/IR/IRBuilder.h>`

`IRBuilder.h` is a heavy LLVM header that was transitively included into
every TU that includes `Native.h` (via `FunctionBinaryArithmetic.h`,
`FunctionUnaryArithmetic.h`, `FunctionIfBase.h`, etc.).

Replace it with forward declarations of `llvm::IRBuilderBase`,
`llvm::Type`, `llvm::Value`, and `llvm::Constant`. Move the
`toNativeType<ToType>` template (which calls builder methods) from the
header into `Native.cpp` with explicit instantiations for all types.

Files that use LLVM types directly now include `<llvm/IR/IRBuilder.h>`
themselves: `FunctionIfBase.h`, `FunctionsConversion.cpp`,
`toNullable.cpp`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Feb 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b003cfb]

Summary: ❌

job_name test_name status info comment
AST fuzzer (arm_asan) failure
AddressSanitizer: heap-use-after-free (STID: 1003-358c) FAIL cidb, issue ISSUE CREATED
AST fuzzer (amd_ubsan) failure
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-46ad) FAIL cidb, issue ISSUE EXISTS

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Feb 27, 2026
Algunenano and others added 2 commits February 27, 2026 15:07
…untime shortcut

The Decimal × Float runtime optimization (commit 0d6865a) converts
both operands to Float64 and re-dispatches. This is incorrect for
`intDiv`/`intDivOrZero`/`intDivOrNull` because their result type is an
integer whose width depends on the original operand types (e.g.
`intDiv(Decimal32, Float64)` → `Int32`), not `Float64`. Converting to
`Float64 × Float64` produces `Int64` instead, causing a LOGICAL_ERROR:
"Unexpected return type from intDiv. Expected Int32. Got Int64".

Fixes test `02975_intdiv_with_decimal`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall it looks good to me. Maybe too many small "unrelated" changes all together.

It worth showing a couple of numbers on how this PR improves build time? WDTY?

Comment thread src/DataTypes/Native.cpp
}

template <typename ToType>
llvm::Type * toNativeType(llvm::IRBuilderBase & builder)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember that there used to be a check for nullable in this function. Isn't it needed anymore?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't remove it, right? It didn't exist already


return res;
}
const std::function<ColumnPtr(ColumnsWithTypeAndName &, const DataTypePtr)> & nested_convert);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is a good one ;)

Comment thread src/IO/WriteHelpers.h Resolved
Comment thread src/IO/ReadHelpers.h Resolved
Comment thread src/DataTypes/Native.cpp
}

template <typename ToType>
llvm::Type * toNativeType(llvm::IRBuilderBase & builder)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer templates in headers and without explicit definitions... It saves a lot of cyclic includes issues latter and the compiler can handle that fine.

Not sure that this produces real compilation time benefit.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer templates in headers and without explicit definitions... It saves a lot of cyclic includes issues latter and the compiler can handle that fine.

Removing heavy headers from transitive includes does help a lot, both in the general build and also when developing, were adding a tiny change means rebuilding thousands of translation units

@Ergus Ergus Mar 2, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but with templates it is a bit different.

The compiler creates a sort of dictionary for template implementations and implement every variant (specialization) only once; independently of how many times they are included or called (that's why the templates really never inline and always slows down compilation; independently if they are in the header or the source file)
As mentioned bellow, I think that the real benefit here comes from avoiding include <llvm/IR/IRBuilder.h> multiple times.

Just to mention: here are a bunch of practices to reduce compilation time

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned bellow, I think that the real benefit here comes from avoiding include <llvm/IR/IRBuilder.h> multiple times.

Yes, that was the exact reason to move the template to the cpp file. Otherwise llvm headers needed to be included and ended up in hundreds of TUs

Comment thread src/DataTypes/Native.h
# include <Common/Exception.h>
# include <Core/ValueWithType.h>
# include <DataTypes/IDataType.h>
# include <llvm/IR/IRBuilder.h>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually I could be wrong, and removing this include could actually improve build time...

@Ergus Ergus self-assigned this Feb 28, 2026
@Algunenano
Algunenano added this pull request to the merge queue Mar 2, 2026
Merged via the queue into ClickHouse:master with commit 6c9913d Mar 2, 2026
143 of 145 checks passed
@Algunenano
Algunenano deleted the more_alexey_build branch March 2, 2026 17:59
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-build Pull request with build/testing/packaging improvement pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants