summaryrefslogtreecommitdiff
path: root/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowGraph.cs
blob: 7cc815a60fad262757bb9921dca6204c2569cc83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;

using ICSharpCode.NRefactory.Utils;

namespace ICSharpCode.Decompiler.FlowAnalysis
{
	/// <summary>
	/// Contains the control flow graph.
	/// </summary>
	/// <remarks>Use ControlFlowGraph builder to create instances of the ControlFlowGraph.</remarks>
	public sealed class ControlFlowGraph
	{
		readonly ReadOnlyCollection<ControlFlowNode> nodes;
		
		public ControlFlowNode EntryPoint {
			get { return nodes[0]; }
		}
		
		public ControlFlowNode RegularExit {
			get { return nodes[1]; }
		}
		
		public ControlFlowNode ExceptionalExit {
			get { return nodes[2]; }
		}
		
		public ReadOnlyCollection<ControlFlowNode> Nodes {
			get { return nodes; }
		}
		
		internal ControlFlowGraph(ControlFlowNode[] nodes)
		{
			this.nodes = new ReadOnlyCollection<ControlFlowNode>(nodes);
			Debug.Assert(EntryPoint.NodeType == ControlFlowNodeType.EntryPoint);
			Debug.Assert(RegularExit.NodeType == ControlFlowNodeType.RegularExit);
			Debug.Assert(ExceptionalExit.NodeType == ControlFlowNodeType.ExceptionalExit);
		}
		
		public GraphVizGraph ExportGraph()
		{
			GraphVizGraph graph = new GraphVizGraph();
			foreach (ControlFlowNode node in nodes) {
				graph.AddNode(new GraphVizNode(node.BlockIndex) { label = node.ToString(), shape = "box" });
			}
			foreach (ControlFlowNode node in nodes) {
				foreach (ControlFlowEdge edge in node.Outgoing) {
					GraphVizEdge e = new GraphVizEdge(edge.Source.BlockIndex, edge.Target.BlockIndex);
					switch (edge.Type) {
						case JumpType.Normal:
							break;
						case JumpType.LeaveTry:
						case JumpType.EndFinally:
							e.color = "red";
							break;
						default:
							e.color = "gray";
							//e.constraint = false;
							break;
					}
					graph.AddEdge(e);
				}
				if (node.ImmediateDominator != null) {
					graph.AddEdge(new GraphVizEdge(node.ImmediateDominator.BlockIndex, node.BlockIndex) { color = "green", constraint = false });
				}
			}
			return graph;
		}
		
		/// <summary>
		/// Resets "Visited" to false for all nodes in this graph.
		/// </summary>
		public void ResetVisited()
		{
			foreach (ControlFlowNode node in nodes) {
				node.Visited = false;
			}
		}
		
		/// <summary>
		/// Computes the dominator tree.
		/// </summary>
		public void ComputeDominance(CancellationToken cancellationToken = default(CancellationToken))
		{
			// A Simple, Fast Dominance Algorithm
			// Keith D. Cooper, Timothy J. Harvey and Ken Kennedy
			
			EntryPoint.ImmediateDominator = EntryPoint;
			bool changed = true;
			while (changed) {
				changed = false;
				ResetVisited();
				
				cancellationToken.ThrowIfCancellationRequested();
				
				// for all nodes b except the entry point
				EntryPoint.TraversePreOrder(
					b => b.Successors,
					b => {
						if (b != EntryPoint) {
							ControlFlowNode newIdom = b.Predecessors.First(block => block.Visited && block != b);
							// for all other predecessors p of b
							foreach (ControlFlowNode p in b.Predecessors) {
								if (p != b && p.ImmediateDominator != null) {
									newIdom = FindCommonDominator(p, newIdom);
								}
							}
							if (b.ImmediateDominator != newIdom) {
								b.ImmediateDominator = newIdom;
								changed = true;
							}
						}
					});
			}
			EntryPoint.ImmediateDominator = null;
			foreach (ControlFlowNode node in nodes) {
				if (node.ImmediateDominator != null)
					node.ImmediateDominator.DominatorTreeChildren.Add(node);
			}
		}
		
		static ControlFlowNode FindCommonDominator(ControlFlowNode b1, ControlFlowNode b2)
		{
			// Here we could use the postorder numbers to get rid of the hashset, see "A Simple, Fast Dominance Algorithm"
			HashSet<ControlFlowNode> path1 = new HashSet<ControlFlowNode>();
			while (b1 != null && path1.Add(b1))
				b1 = b1.ImmediateDominator;
			while (b2 != null) {
				if (path1.Contains(b2))
					return b2;
				else
					b2 = b2.ImmediateDominator;
			}
			throw new Exception("No common dominator found!");
		}
		
		/// <summary>
		/// Computes dominance frontiers.
		/// This method requires that the dominator tree is already computed!
		/// </summary>
		public void ComputeDominanceFrontier()
		{
			ResetVisited();
			
			EntryPoint.TraversePostOrder(
				b => b.DominatorTreeChildren,
				n => {
					//logger.WriteLine("Calculating dominance frontier for " + n.Name);
					n.DominanceFrontier = new HashSet<ControlFlowNode>();
					// DF_local computation
					foreach (ControlFlowNode succ in n.Successors) {
						if (succ.ImmediateDominator != n) {
							//logger.WriteLine("  local: " + succ.Name);
							n.DominanceFrontier.Add(succ);
						}
					}
					// DF_up computation
					foreach (ControlFlowNode child in n.DominatorTreeChildren) {
						foreach (ControlFlowNode p in child.DominanceFrontier) {
							if (p.ImmediateDominator != n) {
								//logger.WriteLine("  DF_up: " + p.Name + " (child=" + child.Name);
								n.DominanceFrontier.Add(p);
							}
						}
					}
				});
		}
	}
}