当前位置: 首页>>代码示例>>C#>>正文


C# ILBlock.GetSelfAndChildrenRecursive方法代码示例

本文整理汇总了C#中ILBlock.GetSelfAndChildrenRecursive方法的典型用法代码示例。如果您正苦于以下问题:C# ILBlock.GetSelfAndChildrenRecursive方法的具体用法?C# ILBlock.GetSelfAndChildrenRecursive怎么用?C# ILBlock.GetSelfAndChildrenRecursive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ILBlock的用法示例。


在下文中一共展示了ILBlock.GetSelfAndChildrenRecursive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Optimize

        public void Optimize(ILBlock method)
        {
            foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>().ToList()) {
                SplitToMovableBlocks(block);
            }

            foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>().Where(b => !(b is ILMoveableBlock)).ToList()) {
                ControlFlowGraph graph;
                graph = BuildGraph(block.Body, block.EntryPoint);
                graph.ComputeDominance();
                graph.ComputeDominanceFrontier();
                block.Body = FindLoops(new HashSet<ControlFlowNode>(graph.Nodes.Skip(3)), graph.EntryPoint, true);
            }

            foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>().Where(b => !(b is ILMoveableBlock)).ToList()) {
                ControlFlowGraph graph;
                graph = BuildGraph(block.Body, block.EntryPoint);
                graph.ComputeDominance();
                graph.ComputeDominanceFrontier();
                block.Body = FindConditions(new HashSet<ControlFlowNode>(graph.Nodes.Skip(3)), graph.EntryPoint);
            }

            // OrderNodes(method);
            FlattenNestedMovableBlocks(method);
            SimpleGotoRemoval(method);
            RemoveDeadLabels(method);
        }
开发者ID:FriedWishes,项目名称:ILSpy,代码行数:27,代码来源:ILAstOptimizer.cs

示例2: RemoveGotos

		public void RemoveGotos(ILBlock method)
		{
			// Build the navigation data
			parent[method] = null;
			foreach (ILNode node in method.GetSelfAndChildrenRecursive<ILNode>()) {
				ILNode previousChild = null;
				foreach (ILNode child in node.GetChildren()) {
					if (parent.ContainsKey(child))
						throw new Exception("The following expression is linked from several locations: " + child.ToString());
					parent[child] = node;
					if (previousChild != null)
						nextSibling[previousChild] = child;
					previousChild = child;
				}
				if (previousChild != null)
					nextSibling[previousChild] = null;
			}
			
			// Simplify gotos
			bool modified;
			do {
				modified = false;
				foreach (ILExpression gotoExpr in method.GetSelfAndChildrenRecursive<ILExpression>(e => e.Code == ILCode.Br || e.Code == ILCode.Leave)) {
					modified |= TrySimplifyGoto(gotoExpr);
				}
			} while(modified);
			
			RemoveRedundantCode(method);
		}
开发者ID:JustasB,项目名称:cudafy,代码行数:29,代码来源:GotoRemoval.cs

示例3: Transform

        public static void Transform(ILBlock method)
        {
            // TODO: move this somewhere else
            // Eliminate 'dups':
            foreach (ILExpression expr in method.GetSelfAndChildrenRecursive<ILExpression>()) {
                for (int i = 0; i < expr.Arguments.Count; i++) {
                    if (expr.Arguments[i].Code == ILCode.Dup)
                        expr.Arguments[i] = expr.Arguments[i].Arguments[0];
                }
            }

            var newArrPattern = new StoreToVariable(new ILExpression(ILCode.Newarr, ILExpression.AnyOperand, new ILExpression(ILCode.Ldc_I4, ILExpression.AnyOperand)));
            var arg1 = new StoreToVariable(new LoadFromVariable(newArrPattern)) { MustBeGenerated = true };
            var arg2 = new StoreToVariable(new LoadFromVariable(newArrPattern)) { MustBeGenerated = true };
            var initializeArrayPattern = new ILCall(
                "System.Runtime.CompilerServices.RuntimeHelpers", "InitializeArray",
                new LoadFromVariable(arg1), new ILExpression(ILCode.Ldtoken, ILExpression.AnyOperand));
            foreach (ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>()) {
                for (int i = block.Body.Count - 1; i >= 0; i--) {
                    if (!newArrPattern.Match(block.Body[i]))
                        continue;
                    ILExpression newArrInst = ((ILExpression)block.Body[i]).Arguments[0];
                    int arrayLength = (int)newArrInst.Arguments[0].Operand;
                    if (arrayLength == 0)
                        continue;
                    if (arg1.Match(block.Body.ElementAtOrDefault(i + 1)) && arg2.Match(block.Body.ElementAtOrDefault(i + 2))) {
                        if (initializeArrayPattern.Match(block.Body.ElementAtOrDefault(i + 3))) {
                            if (HandleStaticallyInitializedArray(arg2, block, i, newArrInst, arrayLength)) {
                                i -= ILInlining.InlineInto(block, i + 1, method) - 1;
                            }
                            continue;
                        }
                    }
                    if (i + 1 + arrayLength > block.Body.Count)
                        continue;
                    List<ILExpression> operands = new List<ILExpression>();
                    for (int j = 0; j < arrayLength; j++) {
                        ILExpression expr = block.Body[i + 1 + j] as ILExpression;
                        if (expr == null || !IsStoreToArray(expr.Code))
                            break;
                        if (!(expr.Arguments[0].Code == ILCode.Ldloc && expr.Arguments[0].Operand == newArrPattern.LastVariable))
                            break;
                        if (!(expr.Arguments[1].Code == ILCode.Ldc_I4 && (int)expr.Arguments[1].Operand == j))
                            break;
                        operands.Add(expr.Arguments[2]);
                    }
                    if (operands.Count == arrayLength) {
                        ((ILExpression)block.Body[i]).Arguments[0] = new ILExpression(
                            ILCode.InitArray, newArrInst.Operand, operands.ToArray());
                        block.Body.RemoveRange(i + 1, arrayLength);
                        i -= ILInlining.InlineInto(block, i + 1, method) - 1;
                    }
                }
            }
        }
开发者ID:richardschneider,项目名称:ILSpy,代码行数:55,代码来源:ArrayInitializers.cs

示例4: SimpleControlFlow

		public SimpleControlFlow(DecompilerContext context, ILBlock method)
		{
			this.context = context;
			this.typeSystem = context.CurrentMethod.Module.TypeSystem;
			
			foreach(ILLabel target in method.GetSelfAndChildrenRecursive<ILExpression>(e => e.IsBranch()).SelectMany(e => e.GetBranchTargets())) {
				labelGlobalRefCount[target] = labelGlobalRefCount.GetOrDefault(target) + 1;
			}
			foreach(ILBasicBlock bb in method.GetSelfAndChildrenRecursive<ILBasicBlock>()) {
				foreach(ILLabel label in bb.GetChildren().OfType<ILLabel>()) {
					labelToBasicBlock[label] = bb;
				}
			}
		}
开发者ID:JustasB,项目名称:cudafy,代码行数:14,代码来源:SimpleControlFlow.cs

示例5: CreateMethodBody

		public BlockStatement CreateMethodBody()
		{
			if (methodDef.Body == null) return null;
			
			context.CancellationToken.ThrowIfCancellationRequested();
			ILBlock ilMethod = new ILBlock();
			ILAstBuilder astBuilder = new ILAstBuilder();
			ilMethod.Body = astBuilder.Build(methodDef, true);
			
			context.CancellationToken.ThrowIfCancellationRequested();
			ILAstOptimizer bodyGraph = new ILAstOptimizer();
			bodyGraph.Optimize(context, ilMethod);
			context.CancellationToken.ThrowIfCancellationRequested();
			
			var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable).Where(v => v != null && !v.IsGenerated).Distinct();
			NameVariables.AssignNamesToVariables(methodDef.Parameters.Select(p => p.Name), allVariables, ilMethod);
			
			context.CancellationToken.ThrowIfCancellationRequested();
			Ast.BlockStatement astBlock = TransformBlock(ilMethod);
			CommentStatement.ReplaceAll(astBlock); // convert CommentStatements to Comments
			foreach (ILVariable v in localVariablesToDefine) {
				DeclareVariableInSmallestScope.DeclareVariable(astBlock, AstBuilder.ConvertType(v.Type), v.Name);
			}
			
			return astBlock;
		}
开发者ID:hlesesne,项目名称:ILSpy,代码行数:26,代码来源:AstMethodBodyBuilder.cs

示例6: DecompileMethod

		public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
		{
			if (!method.HasBody) {
				return;
			}
			
			ILAstBuilder astBuilder = new ILAstBuilder();
			ILBlock ilMethod = new ILBlock();
			ilMethod.Body = astBuilder.Build(method, inlineVariables);
			
			if (abortBeforeStep != null) {
				DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method };
				new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
			}
			
			var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable)
				.Where(v => v != null && !v.IsParameter).Distinct();
			foreach (ILVariable v in allVariables) {
				output.WriteDefinition(v.Name, v);
				if (v.Type != null) {
					output.Write(" : ");
					if (v.IsPinned)
						output.Write("pinned ");
					v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
				}
				output.WriteLine();
			}
			output.WriteLine();
			
			foreach (ILNode node in ilMethod.Body) {
				node.WriteTo(output);
				output.WriteLine();
			}
		}
开发者ID:rmattuschka,项目名称:ILSpy,代码行数:34,代码来源:ILAstLanguage.cs

示例7: DecompileMethod

		public override void DecompileMethod(MethodDef method, ITextOutput output, DecompilationOptions options)
		{
			WriteComment(output, "Method: ");
			output.WriteDefinition(IdentifierEscaper.Escape(method.FullName), method, TextTokenType.Comment, false);
			output.WriteLine();

			if (!method.HasBody) {
				return;
			}
			
			StartKeywordBlock(output, ".body", method);

			ILAstBuilder astBuilder = new ILAstBuilder();
			ILBlock ilMethod = new ILBlock();
			DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method };
			ilMethod.Body = astBuilder.Build(method, inlineVariables, context);
			
			if (abortBeforeStep != null) {
				new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
			}
			
			if (context.CurrentMethodIsAsync) {
				output.Write("async", TextTokenType.Keyword);
				output.Write('/', TextTokenType.Operator);
				output.WriteLine("await", TextTokenType.Keyword);
			}
			
			var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable)
				.Where(v => v != null && !v.IsParameter).Distinct();
			foreach (ILVariable v in allVariables) {
				output.WriteDefinition(IdentifierEscaper.Escape(v.Name), v, v.IsParameter ? TextTokenType.Parameter : TextTokenType.Local);
				if (v.Type != null) {
					output.WriteSpace();
					output.Write(':', TextTokenType.Operator);
					output.WriteSpace();
					if (v.IsPinned) {
						output.Write("pinned", TextTokenType.Keyword);
						output.WriteSpace();
					}
					v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
				}
				if (v.IsGenerated) {
					output.WriteSpace();
					output.Write('[', TextTokenType.Operator);
					output.Write("generated", TextTokenType.Keyword);
					output.Write(']', TextTokenType.Operator);
				}
				output.WriteLine();
			}
			
			var memberMapping = new MemberMapping(method);
			foreach (ILNode node in ilMethod.Body) {
				node.WriteTo(output, memberMapping);
				if (!node.WritesNewLine)
					output.WriteLine();
			}
			output.AddDebugSymbols(memberMapping);
			EndKeywordBlock(output);
		}
开发者ID:nakijun,项目名称:dnSpy,代码行数:59,代码来源:ILAstLanguage.cs

示例8: AssignNamesToVariables

 public static void AssignNamesToVariables(IEnumerable<string> existingNames, IEnumerable<ILVariable> variables, ILBlock methodBody)
 {
     NameVariables nv = new NameVariables();
     nv.AddExistingNames(existingNames);
     foreach (ILVariable varDef in variables) {
         nv.AssignNameToVariable(varDef, methodBody.GetSelfAndChildrenRecursive<ILExpression>());
     }
 }
开发者ID:petr-k,项目名称:ILSpy,代码行数:8,代码来源:NameVariables.cs

示例9: Optimize

        public void Optimize(DecompilerContext context, ILBlock method, ILAstOptimizationStep abortBeforeStep = ILAstOptimizationStep.None)
        {
            if (abortBeforeStep == ILAstOptimizationStep.SplitToMovableBlocks) return;
            foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>().ToList()) {
                SplitToBasicBlocks(block);
            }

            OptimizeShortCircuits(method);

            if (abortBeforeStep == ILAstOptimizationStep.FindLoops) return;
            foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>().ToList()) {
                ControlFlowGraph graph;
                graph = BuildGraph(block.Body, (ILLabel)block.EntryGoto.Operand);
                graph.ComputeDominance(context.CancellationToken);
                graph.ComputeDominanceFrontier();
                block.Body = FindLoops(new HashSet<ControlFlowNode>(graph.Nodes.Skip(3)), graph.EntryPoint, false);
            }

            if (abortBeforeStep == ILAstOptimizationStep.FindConditions) return;
            foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>().ToList()) {
                ControlFlowGraph graph;
                graph = BuildGraph(block.Body, (ILLabel)block.EntryGoto.Operand);
                // TODO: Fix
                if (graph == null)
                    continue;
                graph.ComputeDominance(context.CancellationToken);
                graph.ComputeDominanceFrontier();
                block.Body = FindConditions(new HashSet<ControlFlowNode>(graph.Nodes.Skip(3)), graph.EntryPoint);
            }

            if (abortBeforeStep == ILAstOptimizationStep.FlattenNestedMovableBlocks) return;
            FlattenBasicBlocks(method);

            if (abortBeforeStep == ILAstOptimizationStep.SimpleGotoRemoval) return;
            SimpleGotoRemoval(method);

            if (abortBeforeStep == ILAstOptimizationStep.RemoveDeadLabels) return;
            RemoveDeadLabels(method);

            if (abortBeforeStep == ILAstOptimizationStep.HandleArrayInitializers) return;
            ArrayInitializers.Transform(method);

            if (abortBeforeStep == ILAstOptimizationStep.TypeInference) return;
            TypeAnalysis.Run(context, method);
        }
开发者ID:richardschneider,项目名称:ILSpy,代码行数:45,代码来源:ILAstOptimizer.cs

示例10: RemoveGotos

        public void RemoveGotos(ILBlock method)
        {
            // Build the navigation data
            parent[method] = null;
            foreach (ILNode node in method.GetSelfAndChildrenRecursive<ILNode>())
            {
                ILNode previousChild = null;
                foreach (ILNode child in node.GetChildren())
                {
                    ILExpression e = child as ILExpression;
                    if (e != null && (e.Operand is ILValue || e.Operand is ILVariable)) continue; // This should fix alot of issues
                     if (child is ILValue || child is ILVariable) continue; // we want to skip these.
                    // Added them as nodes so I don't have to dick with them latter with another AST
                    if (parent.ContainsKey(child))
                    { // this throws on one single file and I don't know why the hell it does
                        // its on obj_screen_Step_2  not sure why but its on an expression, so I am putting 
                        // a hack to skip expressions that don't have any gotos in it.  Meh
                        // debug, where the fuck is it
                        var nodes = parent.Keys.Where(x => x == child);
                        throw new Exception("The following expression is linked from several locations: " + child.ToString());

                    }
                    parent[child] = node;
                    if (previousChild != null)
                        nextSibling[previousChild] = child;
                    previousChild = child;
                }
                if (previousChild != null)
                    nextSibling[previousChild] = null;
            }

            // Simplify gotos
            bool modified;
            do
            {
                modified = false;
                foreach (ILExpression gotoExpr in method.GetSelfAndChildrenRecursive<ILExpression>(e => e.Code == GMCode.B))
                {
                    modified |= TrySimplifyGoto(gotoExpr);
                }
            } while (modified);

            RemoveRedundantCode(method);
        }
开发者ID:WarlockD,项目名称:GMdsam,代码行数:44,代码来源:GotoRemoval.cs

示例11: RemoveRedundantCode

		public static void RemoveRedundantCode(ILBlock method)
		{
			// Remove dead lables and nops
			HashSet<ILLabel> liveLabels = new HashSet<ILLabel>(method.GetSelfAndChildrenRecursive<ILExpression>(e => e.IsBranch()).SelectMany(e => e.GetBranchTargets()));
			foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>()) {
				block.Body = block.Body.Where(n => !n.Match(ILCode.Nop) && !(n is ILLabel && !liveLabels.Contains((ILLabel)n))).ToList();
			}
			
			// Remove redundant continue
			foreach(ILWhileLoop loop in method.GetSelfAndChildrenRecursive<ILWhileLoop>()) {
				var body = loop.BodyBlock.Body;
				if (body.Count > 0 && body.Last().Match(ILCode.LoopContinue)) {
					body.RemoveAt(body.Count - 1);
				}
			}
			
			// Remove redundant break at the end of case
			// Remove redundant case blocks altogether
			foreach(ILSwitch ilSwitch in method.GetSelfAndChildrenRecursive<ILSwitch>()) {
				foreach(ILBlock ilCase in ilSwitch.CaseBlocks) {
					Debug.Assert(ilCase.EntryGoto == null);
					
					int count = ilCase.Body.Count;
					if (count >= 2) {
						if (ilCase.Body[count - 2].IsUnconditionalControlFlow() &&
						    ilCase.Body[count - 1].Match(ILCode.LoopOrSwitchBreak)) 
						{
							ilCase.Body.RemoveAt(count - 1);
						}
					}
				}
				
				var defaultCase = ilSwitch.CaseBlocks.Where(cb => cb.Values == null).SingleOrDefault();
				// If there is no default block, remove empty case blocks
				if (defaultCase == null || (defaultCase.Body.Count == 1 && defaultCase.Body.Single().Match(ILCode.LoopOrSwitchBreak))) {
					ilSwitch.CaseBlocks.RemoveAll(b => b.Body.Count == 1 && b.Body.Single().Match(ILCode.LoopOrSwitchBreak));
				}
			}
			
			// Remove redundant return
			if (method.Body.Count > 0 && method.Body.Last().Match(ILCode.Ret) && ((ILExpression)method.Body.Last()).Arguments.Count == 0) {
				method.Body.RemoveAt(method.Body.Count - 1);
			}
		}
开发者ID:JustasB,项目名称:cudafy,代码行数:44,代码来源:GotoRemoval.cs

示例12: RemoveRedundantCode

		public static void RemoveRedundantCode(ILBlock method)
		{
			// Remove dead lables and nops
			HashSet<ILLabel> liveLabels = new HashSet<ILLabel>(method.GetSelfAndChildrenRecursive<ILExpression>().SelectMany(e => e.GetBranchTargets()));
			foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>().ToList()) {
				block.Body = block.Body.Where(n => !n.Match(ILCode.Nop) && !(n is ILLabel && !liveLabels.Contains((ILLabel)n))).ToList();
			}
			
			// Remove redundant continue
			foreach(ILWhileLoop loop in method.GetSelfAndChildrenRecursive<ILWhileLoop>()) {
				var body = loop.BodyBlock.Body;
				if (body.Count > 0 && body.Last().Match(ILCode.LoopContinue)) {
					body.RemoveAt(body.Count - 1);
				}
			}
			
			// Remove redundant return
			if (method.Body.Count > 0 && method.Body.Last().Match(ILCode.Ret) && ((ILExpression)method.Body.Last()).Arguments.Count == 0) {
				method.Body.RemoveAt(method.Body.Count - 1);
			}
		}
开发者ID:stgwilli,项目名称:ILSpy,代码行数:21,代码来源:GotoRemoval.cs

示例13: Initialize

        public void Initialize(DecompilerContext context, ILBlock method)
        {
            this.labelGlobalRefCount.Clear();
            this.labelToBasicBlock.Clear();
            this.context = context;
            this.corLib = context.CurrentMethod.Module.CorLibTypes;

            foreach (var e in method.GetSelfAndChildrenRecursive<ILExpression>(List_ILExpression, e => e.IsBranch())) {
                foreach (var target in e.GetBranchTargets())
                    labelGlobalRefCount[target] = labelGlobalRefCount.GetOrDefault(target) + 1;
            }
            foreach(ILBasicBlock bb in method.GetSelfAndChildrenRecursive<ILBasicBlock>(List_ILBasicBlock)) {
                int index = 0;
                for (;;) {
                    var node = bb.GetNext(ref index);
                    if (node == null)
                        break;
                    var label = node as ILLabel;
                    if (label == null)
                        continue;
                    labelToBasicBlock[label] = bb;
                }
            }
        }
开发者ID:n017,项目名称:dnSpy,代码行数:24,代码来源:SimpleControlFlow.cs

示例14: InlineIfPossible

		/// <summary>
		/// Inlines 'expr' into 'next', if possible.
		/// </summary>
		public static bool InlineIfPossible(ILExpression expr, ILNode next, ILBlock method)
		{
			if (expr.Code != ILCode.Stloc)
				throw new ArgumentException("expr must be stloc");
			// ensure the variable is accessed only a single time
			if (method.GetSelfAndChildrenRecursive<ILExpression>().Count(e => e != expr && e.Operand == expr.Operand) != 1)
				return false;
			ILExpression parent;
			int pos;
			if (FindLoadInNext(next as ILExpression, (ILVariable)expr.Operand, out parent, out pos) == true) {
				parent.Arguments[pos] = expr.Arguments[0];
				return true;
			}
			return false;
		}
开发者ID:hlesesne,项目名称:ILSpy,代码行数:18,代码来源:ILInlining.cs

示例15: RemoveGotos

		public void RemoveGotos(ILBlock method)
		{
			// Build the navigation data
			parent[method] = null;
			foreach (ILNode node in method.GetSelfAndChildrenRecursive<ILNode>()) {
				ILNode previousChild = null;
				foreach (ILNode child in node.GetChildren()) {
					Debug.Assert(!parent.ContainsKey(child));
					parent[child] = node;
					if (previousChild != null)
						nextSibling[previousChild] = child;
					previousChild = child;
				}
				if (previousChild != null)
					nextSibling[previousChild] = null;
			}
			
			// Simplify gotos
			foreach (ILExpression gotoExpr in method.GetSelfAndChildrenRecursive<ILExpression>().Where(e => e.Code == ILCode.Br || e.Code == ILCode.Leave)) {
				TrySimplifyGoto(gotoExpr);
			}
			
			RemoveRedundantCode(method);
		}
开发者ID:stgwilli,项目名称:ILSpy,代码行数:24,代码来源:GotoRemoval.cs


注:本文中的ILBlock.GetSelfAndChildrenRecursive方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。