Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CompilerGeneratedCallGraph.cs « Linker.Dataflow « linker « src - github.com/mono/linker.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 551ff51e5c434b79c46637f28573588cba5b92a9 (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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using System.Diagnostics;
using Mono.Cecil;

namespace Mono.Linker.Dataflow
{
	sealed class CompilerGeneratedCallGraph
	{
		readonly Dictionary<IMemberDefinition, HashSet<IMemberDefinition>> callGraph;

		public CompilerGeneratedCallGraph () => callGraph = new Dictionary<IMemberDefinition, HashSet<IMemberDefinition>> ();

		void TrackCallInternal (IMemberDefinition fromMember, IMemberDefinition toMember)
		{
			if (!callGraph.TryGetValue (fromMember, out HashSet<IMemberDefinition>? toMembers)) {
				toMembers = new HashSet<IMemberDefinition> ();
				callGraph.Add (fromMember, toMembers);
			}
			toMembers.Add (toMember);
		}

		public void TrackCall (MethodDefinition fromMethod, MethodDefinition toMethod)
		{
			Debug.Assert (CompilerGeneratedNames.IsLambdaOrLocalFunction (toMethod.Name));
			TrackCallInternal (fromMethod, toMethod);
		}

		public void TrackCall (MethodDefinition fromMethod, TypeDefinition toType)
		{
			Debug.Assert (CompilerGeneratedNames.IsStateMachineType (toType.Name));
			TrackCallInternal (fromMethod, toType);
		}

		public void TrackCall (TypeDefinition fromType, MethodDefinition toMethod)
		{
			Debug.Assert (CompilerGeneratedNames.IsStateMachineType (fromType.Name));
			Debug.Assert (CompilerGeneratedNames.IsLambdaOrLocalFunction (toMethod.Name));
			TrackCallInternal (fromType, toMethod);
		}

		public IEnumerable<IMemberDefinition> GetReachableMembers (MethodDefinition start)
		{
			Queue<IMemberDefinition> queue = new ();
			HashSet<IMemberDefinition> visited = new ();
			visited.Add (start);
			queue.Enqueue (start);
			while (queue.TryDequeue (out IMemberDefinition? method)) {
				if (!callGraph.TryGetValue (method, out HashSet<IMemberDefinition>? callees))
					continue;

				foreach (var callee in callees) {
					if (visited.Add (callee)) {
						queue.Enqueue (callee);
						yield return callee;
					}
				}
			}
		}
	}
}