Skip to content

Commit

Permalink
codegen: bitcast to expanded struct type when accessing its fields
Browse files Browse the repository at this point in the history
Cheerp, for structs, expands other structs that are in the first member
position. During this expansion, for technical reasons, it explicitly
already adds the padding to the expanded struct. So for structs like
this:

        struct foo {
                uint16_t a;
                //implicit padding of 2 bytes
                uint32_t b;
        };

        struct bar {
                struct foo f;
        }

It will actually become something like this:

        struct foo {
                uint16_t a;
                //implicit padding of 2 bytes
                uint32_t b;
        };

        struct bar {
                uint16_t a;
                uint8_t _padding[2];
                uint32_t b;
        }

However, accesses to the base struct's fields were not aware of this
extra field being added, and falsely assuming that, for `bar`, `b` would
still be in the second position like it is for `foo`.

The linear memory layout of these two types is, however, still exactly
the same. The only difference for LLVM is that the implicit padding is
already there.

Fixed this by bitcasting to the expanded struct type before trying to
access its fields.

Closes: leaningtech/cheerp-meta#118
  • Loading branch information
Hyxogen committed Feb 9, 2024
1 parent fd1da35 commit 413f41e
Showing 1 changed file with 2 additions and 0 deletions.
2 changes: 2 additions & 0 deletions clang/lib/CodeGen/CGExprConstant.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2025,6 +2025,8 @@ class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
int32_t fieldIndex = cgLayout.getLLVMFieldNo(FD);
if(fieldIndex == -1) {
// Collapsed struct
C = llvm::ConstantExpr::getBitCast(C, CGM.getTypes().ConvertTypeForMem(CurType)->getPointerTo());
CElementType = CGM.getTypes().ConvertTypeForMem(CurType);
continue;
}
Indexes.push_back(llvm::ConstantInt::get(CGM.Int32Ty, fieldIndex));
Expand Down

0 comments on commit 413f41e

Please sign in to comment.