[llvm] [APInt] Use a std::move() to avoid a copy in the loop in multiplicativeInverse. (PR #87655)

Eli Friedman via llvm-commits llvm-commits at lists.llvm.org
Mon Apr 8 17:46:08 PDT 2024


https://github.com/efriedma-quic approved this pull request.

This is still allocating every iteration.  If you want to completely avoid that, you'd have to avoid freeing the allocation in T.  For example:

```
while (1) {
  T = *this;  // APInt has a special-case to avoid reallocating here.
  T *= Factor;
  if (T.isOne())
    break;
  T.negate();
  T += 2;
  Factor *= T;
}
```

Not sure how much we want to trade off readability here, though.  The current version might be good enough.

> I always wonder, why can't the compiler work this out for itself?

In C++, the compiler is required to emit the operations as written, barring a few special cases where copy-elision is specifically allowed.  There are different tradeoffs in other rules (e.g. this example just works in Rust, but Rust doesn't allow overriding the move construction/assignment operators).

https://github.com/llvm/llvm-project/pull/87655


More information about the llvm-commits mailing list