Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions Cpp2IL.Core.Tests/IlGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,56 @@ public void StaticCall_DoesNotLoadMethodInfoOperand()
Assert.That(il.Count(i => i.OpCode == CilOpCodes.Ldloc), Is.EqualTo(2),
"expected exactly two Ldloc instructions for the two parameters of the target method");
}

[Test]
public void StoreValueTypeIntoObject_EmitsBox()
{
var appContext = Cpp2IlApi.CurrentAppContext!;
var systemObject = appContext.SystemTypes.SystemObjectType;
var systemVoid = appContext.SystemTypes.SystemVoidType;
var systemBool = appContext.SystemTypes.SystemBooleanType;

var callerContext = new InjectedMethodAnalysisContext(
systemObject,
"CallerBox",
systemVoid,
ReflectionMethodAttributes.Public | ReflectionMethodAttributes.Static,
[]);

var x = new LocalVariable("x", new Register(null, "x")) { Type = systemBool };
var objLocal = new LocalVariable("obj", new Register(null, "obj")) { Type = systemObject };

var instructions = new List<Instruction>
{
new(0, OpCode.Move, x, Imm(1)),
new(1, OpCode.Move, objLocal, x),
new(2, OpCode.Return),
};

callerContext.ControlFlowGraph = new ISILControlFlowGraph(instructions);
callerContext.Locals = [x, objLocal];
callerContext.ParameterLocals = [];
callerContext.AnalysisWarnings = [];

var module = new ModuleDefinition("TestBox.dll", new AssemblyReference("mscorlib", new Version(4, 0, 0, 0)));
var typeDef = new TypeDefinition("Cpp2IL.Core.Tests", "IlGeneratorBoxTestType", TypeAttributes.Class | TypeAttributes.Public);
module.TopLevelTypes.Add(typeDef);

var objTypeDef = new TypeDefinition("System", "Object", TypeAttributes.Public, null);
module.TopLevelTypes.Add(objTypeDef);
systemObject.PutExtraData("AsmResolverType", objTypeDef);

var boolTypeDef = new TypeDefinition("System", "Boolean", TypeAttributes.Public | TypeAttributes.SequentialLayout, module.CorLibTypeFactory.CorLibScope.CreateTypeReference("System", "ValueType"));
module.TopLevelTypes.Add(boolTypeDef);
systemBool.PutExtraData("AsmResolverType", boolTypeDef);

var callerMethodDef = new MethodDefinition("CallerBox", MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));
typeDef.Methods.Add(callerMethodDef);

IlGenerator.GenerateIl(callerContext, callerMethodDef);

var il = callerMethodDef.CilMethodBody!.Instructions;
Assert.That(il.Any(i => i.OpCode == CilOpCodes.Box), Is.True, "expected generated IL to contain a Box instruction when assigning bool to object");
}
}
166 changes: 161 additions & 5 deletions Cpp2IL.Core/Analysis/ArrayRecovery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,24 +33,175 @@ private static void RecoverAccesses(MethodAnalysisContext method)
{
var pointerSize = method.AppContext.Binary.PointerSizeBytes;

// Track array pointer derivations (e.g. ptr = array + 32, or ptr2 = ptr + 8)
var arrayPointers = new Dictionary<LocalVariable, (LocalVariable Array, SzArrayTypeAnalysisContext ArrayType, long Offset)>();
var indexedArrayPointers = new Dictionary<LocalVariable, (LocalVariable Array, SzArrayTypeAnalysisContext ArrayType, IOperand Index, int Scale)>();
var pointerDefs = new Dictionary<LocalVariable, Instruction>();
var convertedPointers = new HashSet<LocalVariable>();

foreach (var instruction in method.ControlFlowGraph!.Instructions)
{
RecoverAllocation(instruction);

if (instruction.OpCode == OpCode.Add && instruction.Operands.Count >= 3 && instruction.Operands[0] is LocalVariable dest)
{
LocalVariable? arrLocal = null;
SzArrayTypeAnalysisContext? arrType = null;
long baseOff = 0;
long? immOffset = null;

if (instruction.Operands[1] is LocalVariable l1 && instruction.Operands[2] is Immediate i2)
{
immOffset = i2.Value;
if (l1.Type is SzArrayTypeAnalysisContext st)
{
arrLocal = l1;
arrType = st;
baseOff = 0;
}
else if (arrayPointers.TryGetValue(l1, out var parent))
{
arrLocal = parent.Array;
arrType = parent.ArrayType;
baseOff = parent.Offset;
}
}
else if (instruction.Operands[2] is LocalVariable l2 && instruction.Operands[1] is Immediate i1)
{
immOffset = i1.Value;
if (l2.Type is SzArrayTypeAnalysisContext st)
{
arrLocal = l2;
arrType = st;
baseOff = 0;
}
else if (arrayPointers.TryGetValue(l2, out var parent))
{
arrLocal = parent.Array;
arrType = parent.ArrayType;
baseOff = parent.Offset;
}
}
else if (instruction.Operands[1] is LocalVariable vl1 && instruction.Operands[2] is LocalVariable vl2)
{
// Variable index addition: ptr = array + (index << shift)
LocalVariable? candArr = vl1.Type is SzArrayTypeAnalysisContext ? vl1 : (vl2.Type is SzArrayTypeAnalysisContext ? vl2 : null);
LocalVariable? candIdx = ReferenceEquals(candArr, vl1) ? vl2 : (ReferenceEquals(candArr, vl2) ? vl1 : null);

if (candArr != null && candArr.Type is SzArrayTypeAnalysisContext st && candIdx != null)
{
IOperand realIndex = candIdx;
int scale = 1;

var shiftDef = method.ControlFlowGraph.Instructions.FirstOrDefault(i => i.OpCode == OpCode.ShiftLeft
&& ReferenceEquals(i.Operands[0], candIdx) && i.Operands.Count >= 3 && i.Operands[2] is Immediate);

if (shiftDef != null && shiftDef.Operands[2] is Immediate shiftImm)
{
realIndex = shiftDef.Operands[1];
scale = 1 << (int)shiftImm.Value;
}

indexedArrayPointers[dest] = (candArr, st, realIndex, scale);
pointerDefs[dest] = instruction;
}
}

if (arrLocal != null && arrType != null && immOffset != null)
{
arrayPointers[dest] = (arrLocal, arrType, baseOff + immOffset.Value);
pointerDefs[dest] = instruction;
}
}
else if (instruction.OpCode == OpCode.Move && instruction.Operands.Count >= 2 && instruction.Operands[0] is LocalVariable mDest && instruction.Operands[1] is LocalVariable mSrc)
{
if (mSrc.Type is SzArrayTypeAnalysisContext st)
{
arrayPointers[mDest] = (mSrc, st, 0);
}
else if (arrayPointers.TryGetValue(mSrc, out var parent))
{
arrayPointers[mDest] = parent;
}
}
}

foreach (var instruction in method.ControlFlowGraph.Instructions)
{
for (var i = 0; i < instruction.Operands.Count; i++)
{
if (instruction.Operands[i] is not MemoryOperand memory
|| memory.Base is not LocalVariable { Type: SzArrayTypeAnalysisContext arrayType } array)
if (instruction.Operands[i] is not MemoryOperand memory)
continue;

if (memory.Index == null && memory.Scale == 0 && memory.Addend == LengthOffset(pointerSize))
LocalVariable? array = null;
SzArrayTypeAnalysisContext? arrayType = null;
long combinedAddend = memory.Addend;

var baseLocal = memory.Base as LocalVariable;

if (baseLocal != null && indexedArrayPointers.TryGetValue(baseLocal, out var idxInfo))
{
var elemSize = ElementSize(idxInfo.ArrayType.ElementType, pointerSize);
if (elemSize > 0 && (idxInfo.Scale == elemSize || idxInfo.Scale == 1) && memory.Addend == ElementsOffset(pointerSize) && memory.Index == null)
{
instruction.SetOperand(i, new ArrayAccess(idxInfo.Array, idxInfo.Index));
convertedPointers.Add(baseLocal);
continue;
}
}

if (baseLocal?.Type is SzArrayTypeAnalysisContext at)
{
array = baseLocal;
arrayType = at;
}
else if (baseLocal != null && arrayPointers.TryGetValue(baseLocal, out var ptrInfo))
{
array = ptrInfo.Array;
arrayType = ptrInfo.ArrayType;
combinedAddend = ptrInfo.Offset + memory.Addend;
}

if (array == null || arrayType == null)
continue;

if (memory.Index == null && memory.Scale == 0 && combinedAddend == LengthOffset(pointerSize))
{
instruction.SetOperand(i, new ArrayLength(array));
continue;
}

if (ElementIndex(memory, arrayType, pointerSize) is { } index)
var effectiveMem = new MemoryOperand(array, memory.Index, combinedAddend, memory.Scale);
if (ElementIndex(effectiveMem, arrayType, pointerSize) is { } index)
{
instruction.SetOperand(i, new ArrayAccess(array, index));
if (baseLocal != null && pointerDefs.ContainsKey(baseLocal))
convertedPointers.Add(baseLocal);
}
}
}

foreach (var ptr in convertedPointers)
{
if (pointerDefs.TryGetValue(ptr, out var defInst)
&& !method.ControlFlowGraph.Instructions.Any(inst => inst != defInst && inst.Operands.Contains(ptr)))
{
defInst.OpCode = OpCode.Nop;
defInst.SetOperands();
}

if (indexedArrayPointers.TryGetValue(ptr, out var idxInfo) && idxInfo.Scale > 1)
{
var shiftDef = method.ControlFlowGraph.Instructions.FirstOrDefault(i => i.OpCode == OpCode.ShiftLeft
&& i.Operands.Count >= 3 && Equals(i.Operands[1], idxInfo.Index)
&& i.Operands[0] is LocalVariable shiftDest
&& !method.ControlFlowGraph.Instructions.Any(inst => inst != i && inst.Operands.Contains(shiftDest)));

if (shiftDef != null)
{
shiftDef.OpCode = OpCode.Nop;
shiftDef.SetOperands();
}
}
}
}
Expand All @@ -70,6 +221,7 @@ private static void GroupInitialisers(ISILControlFlowGraph cfg)
var stores = new List<(Block Block, Instruction Instruction)>();
var current = block;
var index = current.Instructions.IndexOf(allocation) + 1;
var visitedBlocks = new HashSet<Block> { current };

while (true)
{
Expand All @@ -79,7 +231,11 @@ private static void GroupInitialisers(ISILControlFlowGraph cfg)
if (current.Successors.Count != 1 || current.Successors[0].Predecessors.Count != 1)
break;

current = current.Successors[0];
var next = current.Successors[0];
if (!visitedBlocks.Add(next))
break;

current = next;
index = 0;
continue;
}
Expand Down
40 changes: 32 additions & 8 deletions Cpp2IL.Core/Analysis/CallArgumentTrimmer.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Linq;
using Cpp2IL.Core.ISIL;
using Cpp2IL.Core.Model.Contexts;

Expand All @@ -10,17 +11,40 @@ public static void Run(MethodAnalysisContext method)
{
foreach (var instruction in method.ControlFlowGraph!.Instructions)
{
if (!instruction.IsCall || instruction.Operands[0] is not MethodAnalysisContext called)
if (!instruction.IsCall)
continue;

// target, [return value], [this], parameters...
var expected = 1
+ (instruction.OpCode == OpCode.Call ? 1 : 0)
+ (called.IsStatic ? 0 : 1)
+ called.Parameters.Count;
if (instruction.Operands[0] is MethodAnalysisContext called)
{
// target, [return value], [this], parameters...
var expected = 1
+ (instruction.OpCode == OpCode.Call ? 1 : 0)
+ (called.IsStatic ? 0 : 1)
+ called.Parameters.Count;

for (var i = instruction.Operands.Count - 1; i >= expected; i--)
instruction.RemoveOperandAt(i);
for (var i = instruction.Operands.Count - 1; i >= expected; i--)
instruction.RemoveOperandAt(i);
}
else if (instruction.Operands[0] is Immediate)
{
// Unresolved call to immediate address (e.g. write barrier)
// If return value is unused, the call has no managed effect and can be eliminated
var retUsed = instruction.OpCode == OpCode.Call
&& instruction.Operands.Count > 1
&& instruction.Operands[1] is LocalVariable ret
&& method.ControlFlowGraph.Instructions.Any(i => i != instruction && i.Operands.Contains(ret));

if (!retUsed)
{
instruction.OpCode = OpCode.Nop;
instruction.SetOperands();
}
else
{
for (var i = instruction.Operands.Count - 1; i >= 2; i--)
instruction.RemoveOperandAt(i);
}
}
}
}
}
3 changes: 3 additions & 0 deletions Cpp2IL.Core/Analysis/ConstantFolder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ private static bool TryFold(Instruction instruction)
{
switch (instruction.OpCode)
{
case OpCode.Add: return ToConstant(instruction, a + b);
case OpCode.Subtract: return ToConstant(instruction, a - b);
case OpCode.Multiply: return ToConstant(instruction, a * b);
case OpCode.CheckEqual: return ToConstant(instruction, a == b ? 1 : 0);
case OpCode.CheckNotEqual: return ToConstant(instruction, a != b ? 1 : 0);
case OpCode.And: return ToConstant(instruction, a & b);
Expand Down
18 changes: 13 additions & 5 deletions Cpp2IL.Core/Analysis/CopyCoalescer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -325,23 +325,31 @@ public LocalVariable Find(LocalVariable local)
if (!_parent.TryGetValue(local, out var parent))
return local;

while (!ReferenceEquals(parent, _parent[parent]))
parent = _parent[parent];
while (_parent.TryGetValue(parent, out var nextParent) && !ReferenceEquals(parent, nextParent))
parent = nextParent;

_parent[local] = parent;
return parent;
}

public IEnumerable<LocalVariable> Members(LocalVariable representative) => _members[representative];
public IEnumerable<LocalVariable> Members(LocalVariable representative) =>
_members.TryGetValue(representative, out var members) ? members : [representative];

public void Union(LocalVariable a, LocalVariable b)
{
if (ReferenceEquals(a, b)) return;

// keep whichever already carries a type
var (keep, drop) = a.Type != null || b.Type == null ? (a, b) : (b, a);

_parent[drop] = keep;
_members[keep].AddRange(_members[drop]);
_members.Remove(drop);
if (_members.TryGetValue(drop, out var dropMembers))
{
if (!_members.TryGetValue(keep, out var keepMembers))
_members[keep] = keepMembers = [keep];
keepMembers.AddRange(dropMembers);
_members.Remove(drop);
}

keep.Type ??= drop.Type;
keep.IsThis |= drop.IsThis;
Expand Down
Loading