llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[LifetimeSafety] Support pointer arithmetic on gsl::Pointer types

Open NeKon69 opened this issue 8 months ago • 8 comments

Currently this does not warn:

#include <vector>

auto f() {
    std::vector v{1};
    auto val = v.begin(); // does not diagnose
    val = val + 10;
    return val;
}

Expected behavior would be to emit a warning similar to "address of stack memory is returned later".

https://godbolt.org/z/jGqMv6enE

NeKon69 avatar Apr 02 '26 09:04 NeKon69

@llvm/issue-subscribers-clang-temporal-safety

Author: NeKon69

Currently this does not warn:
#include &lt;vector&gt;

auto f() {
    std::vector v{1};
    auto val = v.begin(); // does not diagnose
    val = val + 10;
    return val;
}

Expected behavior would be to emit a warning similar to "address of stack memory is returned later".

https://godbolt.org/z/jGqMv6enE

llvmbot avatar Apr 02 '26 10:04 llvmbot

This turned out to be a bit harder than I initially anticipated. I’m still working on it, though

NeKon69 avatar Apr 02 '26 20:04 NeKon69

I don't think I can fix that reliably without introducing a lot of false-positives, so I am probably going to leave it for someone more experienced.

NeKon69 avatar Apr 03 '26 12:04 NeKon69

I don't think I can fix that reliably without introducing a lot of false-positives, so I am probably going to leave it for someone more experienced.

Do you have examples where you saw false positives for future reference.

Note that we have to do this only for gsl::pointer types, not all types.

usx95 avatar Apr 06 '26 18:04 usx95

Do you have examples where you saw false positives, for future reference?

What I tried to do was to make some kind of a guess as to whether the produced result depends on this. Some of the checks were whether the return type is the same as this, whether the type was marked with gsl::Pointer, and whether it is not a static function. After that, I also tried adding an isInStlNamespace condition, but that would not really support all user-defined types, so I abandoned that idea.

For example, imagine this scenario:

struct [[gsl::Pointer]] View {
  View operator+(int x) { return View{}; }
};

A user could easily write something like this. Even if it does not make much sense to do something like that, I do not think we can afford to create false-positives here

NeKon69 avatar Apr 06 '26 19:04 NeKon69

Hmmmm.. Now that I know a bit more about LifetimeSafety, I feel like I can try this issue one more time.

NeKon69 avatar May 01 '26 16:05 NeKon69

Is it OK if I only support iterators? I still don't think I can support all of the gsl::Pointer types because their semantics are ambiguous

NeKon69 avatar May 01 '26 18:05 NeKon69

iterators and pointers should be a good enough.

usx95 avatar May 01 '26 18:05 usx95