llvm / llvm/llvm-project

[CIR] NPE when generating CIR that dereferences a bitfield in riscv64

Open
#215,017 3 comments 0 reactions 0 assignees View on GitHub
ClangIR crash
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

When compiling CIR:

`-cc1 -fclangir -emit-cir -triple riscv64-unknown-linux-gnu` for this program (this is a minimalistic repro)

```c
struct S { int b : 5; };
int f(struct S *s) { return s->b; }
```

I got a crash. Debugging I found out that the crash came from here:

https://github.com/llvm/llvm-project/blob/a4897aa410ebe7ff4f174c16698ac7b66db4304e/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp#L484-L486

Because field ends up being one past the end and the code dereferences it (field is null, field->getSourceRange() is the NPE).

The fix should be to check and use recordDecl, which getStorageType does:

https://github.com/llvm/llvm-project/blob/a4897aa410ebe7ff4f174c16698ac7b66db4304e/clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp#L182-L189

Something like this?

```cpp
if (!astContext.getTargetInfo().hasCheapUnalignedBitFieldAccess())
cirGenTypes.getCGModule().errorNYI(
(field != fieldEnd ? field->getSourceRange()
: recordDecl->getSourceRange()),
"NYI CheapUnalignedBitFieldAccess");
```

Contributor guide

Open the contributing guide

Research direction

Start with clang/lib/CIR/CodeGen/CIRGenRecordLayoutBuilder.cpp around lines 484-486 and compare the recordDecl handling in getStorageType around lines 182-189. Reproduce with the riscv64 -cc1 -fclangir -emit-cir command and the minimal bitfield program. Done means the repro no longer crashes and reports the intended unsupported unaligned bitfield access diagnostic.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
73/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.