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

[clang/lldb] wrong value of element in struct when the value is changed in noinline function

Open iamanonymouscs opened this issue 4 years ago • 3 comments

$ cat small.c

struct bm {
  unsigned a;
};

int __attribute__ ((noinline))
foo (struct bm *p)
{
  p->a = 1;
  return 1;
}

int main()
{
  struct bm v = {0};
  foo (&v);
  return 0;
}

$ clang -O1 -g small.c; lldb a.out

(lldb) target create "a.out"
Current executable set to '/root/DeVIL/a.out' (x86_64).
(lldb) b 16
Breakpoint 1: where = a.out`main at small.c:16:3, address = 0x0000000000000610
(lldb) r
Process 7305 launched: '/root/DeVIL/a.out' (x86_64)
Process 7305 stopped
* thread #1, name = 'a.out', stop reason = breakpoint 1.1
    frame #0: 0x0000555555554610 a.out`main at small.c:16:3
   13  	{
   14  	  struct bm v = {0};
   15  	  foo (&v);
-> 16  	  return 0;
   17  	}
(lldb) fr var
(bm) v = (a = 0)
(lldb)

We can found that the variable a in the struct v is 0. However, the function foo is called, this element a is assigned to 1. I was wondering that this should be a bug.

$ clang --version

Ubuntu clang version 15.0.0-++20220520091548+a61835b1e3f5-1~exp1~20220520091641.498
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

iamanonymouscs avatar May 28 '22 01:05 iamanonymouscs

@llvm/issue-subscribers-lldb

llvmbot avatar May 28 '22 01:05 llvmbot

@dwblaikie How about this issue? When running to the same program point via instruction level stepping, the value of a is equal to 1.

iamanonymouscs avatar Jun 01 '22 13:06 iamanonymouscs

Yeah, arguably a clang/LLVM bug. This does reflect the optimized state of the program, but not what the author wrote.

What happened is that LLVM didn't inline the function, but did the moral equivalent of inlining it - it performed interprocedural analysis, proved the function call had no meaningful effect. The function only wrote to the parameter, the parameter was unused after the call, so the call could be removed.

It's probably a bit difficult to make this better in LLVM - but in theory when LLVM removed the function call it probably should've marked the variable location as unknowable/dead after the point where the call was. (in theory, in this particular case, it could prove the value of 1 and encode that in the DWARF - but that's probably even harder/a bunch more work)

dwblaikie avatar Jun 01 '22 18:06 dwblaikie