public static int ComputeMaxStackSize(this MethodBody body)
{
var stackSize = 0;
var maxStack = 0;
var stackSizes = new Dictionary<Instruction, int>();
if (body.HasExceptionHandlers)
{
foreach (var eh in body.ExceptionHandlers)
{
if (eh.HandlerType != ExceptionHandlerType.Catch && eh.HandlerType != ExceptionHandlerType.Filter)
continue;
if (eh.HandlerStart != null)
stackSizes[eh.HandlerStart] = 1;
if (eh.FilterStart != null && eh.HandlerType == ExceptionHandlerType.Filter)
stackSizes[eh.FilterStart] = 1;
}
}
foreach (var instruction in body.Instructions)
{
int computedSize;
if (stackSizes != null && stackSizes.TryGetValue(instruction, out computedSize))
stackSize = computedSize;
maxStack = System.Math.Max(maxStack, stackSize);
ComputeStackDelta(instruction, ref stackSize);
maxStack = System.Math.Max(maxStack, stackSize);
CopyBranchStackSize(instruction, ref stackSizes, stackSize);
ComputeStackSize(instruction, ref stackSize);
}
return maxStack;
}