Skip to content

Incorrect IND(ADDR(LCL_VAR)) folding when types do not match #620

@mikedn

Description

@mikedn

I was looking at reimplementing this kind of folding in LocalAddressVisitor and ran into this morph code:

// If the type of the IND (typ) is a "small int", and the type of the local has the
// same width, then we can reduce to just the local variable -- it will be
// correctly normalized, and signed/unsigned differences won't matter.
//
// The below transformation cannot be applied if the local var needs to be normalized on load.
else if (varTypeIsSmall(typ) && (genTypeSize(lvaTable[lclNum].lvType) == genTypeSize(typ)) &&
!lvaTable[lclNum].lvNormalizeOnLoad())
{
tree->gtType = typ = temp->TypeGet();
foldAndReturnTemp = true;
}
else if (!varTypeIsStruct(typ) && (lvaTable[lclNum].lvType == typ) &&

I don't think that "signed/unsigned differences won't matter":

static void Main() => Test(-1, 1);

[MethodImpl(MethodImplOptions.NoInlining)]
static unsafe void Test(short a, int b)
{
    short c = (short)(a * 2);
    int d = *((ushort*)&c) / b;
    Console.WriteLine(d);
}

generates

G_M41262_IG01:
       4883EC28             sub      rsp, 40
       448BC2               mov      r8d, edx
G_M41262_IG02:
       480FBFC1             movsx    rax, cx
       D1E0                 shl      eax, 1
       480FBFC0             movsx    rax, ax
       99                   cdq
       41F7F8               idiv     edx:eax, r8d
       8BC8                 mov      ecx, eax
       E8A4FCFFFF           call     System.Console:WriteLine(int)
       90                   nop
G_M41262_IG03:
       4883C428             add      rsp, 40
       C3                   ret

and prints [edit] -2. The result is obviously incorrect, ushort / 1 can't ever be negative.

category:correctness
theme:morph
skill-level:intermediate
cost:medium

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIbug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions