Issue 239625
Summary [clang] Wrong code: static local in module-exported inline function is silently skipped when the TU imports nn.cli (C++ modules, -O0/-O3)
Labels clang
Assignees
Reporter EthanPeng-2048
    ## Clang version / environment

- `Ubuntu clang version 24.0.0 (++20261105085444+cb20a8e476f5-1~exp1~20261105085458.326)` (also reproduces on the previous snapshot `++20261103085445+920022915a8a`)
- Target: `x86_64-pc-linux-gnu`, libstdc++
- `-std=c++26` (C++20 modules), reproduces at both `-O0` and `-O3`

## Summary

Wrong code with no diagnostic: in a TU that imports C++ modules, a `static local` variable inside a **module-exported inline function** (instantiated into the consuming TU) is silently mis-compiled — the range-for loop over that static container iterates **zero times**. An *identical* static-local construct written directly in the same consuming TU behaves correctly.

## Reduced test case

```cpp
// repro.cpp
#include <algorithm>
#include <cstdio>
#include <string>
#include <string_view>
#include <vector>
import nn.tokenizer;
import nn.cli;
using nn::BPETokenizer;

// Local construct, textually identical to the one inside the module-exported
// inline function BPETokenizer::pre_tokenize (same 14 string literals, same
// sort lambda).
std::vector<std::string> old_pre_tokenize(std::string_view text)
{
    static const std::vector<std::string> markers = []
    {
        std::vector<std::string> m = {
            "<|system|>",      "<|end_of_system|>", "<|user|>",
            "<|end_of_user|>", "<|assistant|>",     "<|end_of_assistant|>",
            "<|end_of_turn|>", "<|sep|>",           "<|tool|>",
            "<|tool_result|>", "<|image|>",         "<|audio|>",
            "<|video|>",       "<|file|>"};
        std::sort(m.begin(), m.end(),
                  [](const auto& a, const auto& b) { return a.size() > b.size(); });
        return m;
    }();
    std::vector<std::string> chunks;
    std::string plain;
    auto flush = [&]() { if (!plain.empty()) { chunks.push_back(std::move(plain)); plain.clear(); } };
    std::size_t pos = 0;
    while (pos < text.size())
    {
        std::size_t mlen = 0;
        for (const auto& mk : markers)
            if (pos + mk.size() <= text.size() && text.compare(pos, mk.size(), mk) == 0)
            { mlen = mk.size(); break; }
        if (mlen > 0) { flush(); chunks.push_back(std::string(text.substr(pos, mlen))); pos += mlen; }
        else { plain.push_back(text[pos]); ++pos; }
    }
    flush();
    return chunks;
}

int main()
{
    int fail = 0;
    for (std::string_view s : {"<|system|>", "hi<|user|>there", "x<|end_of_assistant|>y"})
    {
        auto manual = BPETokenizer::pre_tokenize(s); // module-exported inline fn
        auto old = old_pre_tokenize(s);              // local identical construct
        bool eq = manual.size() == old.size();
        if (eq) for (std::size_t i = 0; i < manual.size(); ++i)
            if (manual[i] != old[i]) { eq = false; break; }
        if (!eq) { ++fail; std::printf("FAIL [%s]\\n", std::string(s).c_str()); }
    }
    std::printf("fails=%d\\n", fail);
    return fail != 0;
}
```

Expected output: `fails=0` (both functions produce `[x][<|end_of_assistant|>][y]`).

Actual output: `fails=3` — the module-exported function's markers loop runs zero times, so `pre_tokenize` falls back to plain splitting:

```
manual:[x][<|][end][of][assistant][|>][y]   <- BPETokenizer::pre_tokenize (markers loop skipped)
old   :[x][<|end_of_assistant|>][y]         <- identical local construct (correct)
```

## How to reproduce

The bug needs two real modules; a self-contained minimization does **not** reproduce (details below). The modules come from an open-source project:

```bash
git clone --branch dev https://github.com/neuralnet-cpp-dev/neuralnet.cpp
cd neuralnet.cpp
cmake -B build -G Ninja -DNN_ENABLE_GPU=OFF
cmake --build build --target nn_core_bmi nn_kvrecord_bmi nn_dataset_bmi nn_tokenizer_bmi nn_cli_bmi
```

then compile `repro.cpp` against the produced BMIs:

```bash
clang++ -std=c++26 -O3 -DNDEBUG -fno-exceptions -fexperimental-library \
  -flto=thin -fno-math-errno -fno-trapping-math -funroll-loops -march=native \
  -fmodule-file=nn.core=build/modules/nn.core.pcm \
  -fmodule-file=nn.kvrecord=build/modules/nn.kvrecord.pcm \
  -fmodule-file=nn.dataset=build/modules/nn.dataset.pcm \
  -fmodule-file=nn.tokenizer=build/modules/nn.tokenizer.pcm \
  -fmodule-file=nn.cli=build/modules/nn.cli.pcm \
  -c repro.cpp -o repro.o
clang++ -flto=thin repro.o -o repro && ./repro
```

The two modules are thin interface modules (global-module-fragment text-includes headers, then `export namespace nn { using ...; }` re-exports). The header containing the mis-compiled exported inline function is `include/neuralnet.cpp/domain_tokenizer_bpe.hpp` (`BPETokenizer::pre_tokenize`, ~60 lines); the header whose import triggers the bug is `include/neuralnet.cpp/cli/text_train_loop.hpp`.

## Bisection / trigger conditions

- Reproduces at `-O0` and `-O3`.
- Does **not** reproduce:
  - with gcc 15.3 (same flags),
  - with a plain TU (no `import` at all),
  - importing only `nn.tokenizer` (chain of 4 BMIs),
  - when the identical local construct is removed (module-exported function alone is correct),
  - when the module-exported function is replaced by a second local function (two identical local constructs in one TU are correct),
  - with a minimized self-contained module mimicking the structure (inline fn with `static const bool` / `static std::vector` locals; large inline export surface of 50–500 exported functions).
- `import nn.cli` is the trigger: `nn.tokenizer` + `nn.cli` reproduces; trimming `nn.cli` to a single header (`text_train_config.hpp`) does not, while `text_train_config.hpp` + `text_train_loop.hpp` still does.
- Replacing the local construct's `std::string` with `std::string_view` (making the two constructs non-identical) reliably avoids the bug.

Hypothesis (unverified): clang's static-local guard / COMDAT handling merges the two *identical* initializers (same 14 string literals + same sort lambda, one inside the module-exported inline function, one local), and one of the two instances ends up with a zero-trip loop. The dependency on the exact module export surface (`nn.cli` vs `nn.tokenizer`) is what prevented a fully self-contained reduction.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to