简体   繁体   中英

Roslyn : get instructions from a basicblock

Control flow graph generated in roslyn contains blocks (basicblock) as nodes, each basicblock contains one or more instructions. for the basicblocks that contains more than one instruction, i try to get all the instructions and their types this is what i did :

var cfg = ControlFlowGraph.Create(method);
foreach(var block in cfg.Blocks)
{
    foreach(var operation in block.Operations)
    {
        var syntax = operation.Syntax;
        Console.WriteLine(syntax.Kind());
    }
}

for the following method :

public int method(int x, int y)
{
y = 10;
x = y;
return x + y;
}

i get the result :

ExpressionStatement
ExpressionStatement

but i wan to get the exacte instruction and it's type for example for the instruction x = y; i want to get AssignmentExpressionSyntax . Also i want to performe some opeartion on each instruction depending on it's type.

Since you are looking at the syntax kind, the ExpressionStatement is the correct kind for the statement. You can find the expressions's kind by looking at the kind of the expression within the ExpressionStatement.

if (operation.Syntax is ExpressionStatement es)
{
    var kind = es.Expression.Kind();
}

However, if you are using operations (IOperation) then you can probably get better info by skipping the syntax and using the OperationKind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM