コード例 #1
0
        public InOutData <Dictionary <Guid, VarValue> > TempFunc(TACode taCode, ControlFlowGraph cfg)
        {
            Operations       ops = new Operations(taCode);
            TransferFunction f   = new TransferFunction();

            IterativeAlgorithm itAlg = new IterativeAlgorithm();
            var result = itAlg.Analyze(cfg, ops, f);

            return(result);
        }
コード例 #2
0
        public void IterativeAlgorithm(List <LinkedList <ThreeCode> > blocks)
        {
            var bb = new LinkedList <ThreeCode>();

            bb.AddLast(new ThreeCode("entry", "", ThreeOperator.None, null, null));
            var bs = blocks.ToList();

            // добавление пустого входного блока - необходимо для корректной работы ит. алгоритма
            bs.Insert(0, bb);
            // построение CFG по блокам
            controlFlowGraph = new CFG(bs);
            // создание информации о блоках
            var blocksInfo = new List <BlockInfo <Expr> >();

            for (int i = 0; i < bs.Count; i++)
            {
                blocksInfo.Add(new BlockInfo <Expr>(bs[i]));
            }

            // оператор сбора для доступных выражений
            Func <List <BlockInfo <Expr> >, CFG, int, BlockInfo <Expr> > meetOperator =
                (blocksInfos, graph, index) =>
            {
                var inputIndexes = graph.cfg.GetInputNodes(index);
                var resInfo      = new BlockInfo <Expr>(blocksInfos[index]);
                resInfo.IN = resInfo.OUT;     // универсальное множество
                foreach (var i in inputIndexes)
                {
                    resInfo.IN.IntersectWith(blocksInfos[i].OUT);
                }
                return(resInfo);
            };

            var transferFunction = AvaliableExprsAdaptor.TransferFunction();

            var U = new HashSet <Expr>(blocks.Select(b => b.Where(c =>
                                                                  AvaliableExprs.IsDefinition(c.operation))
                                                     .Select(c => (c.arg1, c.operation, c.arg2)))
                                       .Aggregate((s1, s2) => s1.Union(s2)));

            // создание объекта итерационного алгоритма
            var iterativeAlgorithm = new IterativeAlgorithm <Expr>(blocksInfo,
                                                                   controlFlowGraph, meetOperator, true, new HashSet <Expr>(), U, transferFunction);

            // выполнение алгоритма
            iterativeAlgorithm.Perform();
            Ins  = iterativeAlgorithm.GetINs();
            Outs = iterativeAlgorithm.GetOUTs();
        }
コード例 #3
0
        public void ConstantPropagation()
        {
            string     text  = @"
if 1
{
    x = 2;
    y = 3;
}
else
{
    x = 3;
    y = 2;
}
z = x + y;
";
            SyntaxNode root  = ParserWrap.Parse(text);
            Graph      graph = new Graph(
                BasicBlocksGenerator.CreateBasicBlocks(
                    ThreeAddressCodeGenerator.CreateAndVisit(root).Program));

            var constantPropagationIterative = IterativeAlgorithm.Apply(graph, new ConstantsPropagationParameters());
            var constantPropagationMOP       = MeetOverPaths.Apply(graph, new ConstantsPropagationParameters());
            var it = constantPropagationIterative.Out.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            foreach (var outInfo in it)
            {
                Trace.WriteLine(outInfo);
            }

            var mop = constantPropagationMOP.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            Trace.WriteLine("====");
            foreach (var outInfo in mop)
            {
                Trace.WriteLine(outInfo);
            }

            Assert.IsFalse(constantPropagationIterative.In.OrderBy(kvp => kvp.Key).
                           Zip(constantPropagationMOP.OrderBy(kvp => kvp.Key), (v1, v2) =>
                               v1.Key == v2.Key && v1.Value.OrderBy(kvp => kvp.Key).SequenceEqual(v2.Value.OrderBy(kvp => kvp.Key))).All(x => x));
        }
コード例 #4
0
        public void DeadAliveVariables1()
        {
            string     text  = @"
a = 2;
b = 3;

1: c = a + b;
2: a = 3; 
b = 4;
3: c = a;
";
            SyntaxNode root  = ParserWrap.Parse(text);
            Graph      graph = new Graph(
                BasicBlocksGenerator.CreateBasicBlocks(
                    ThreeAddressCodeGenerator.CreateAndVisit(root).Program));

            var deadAliveVars = IterativeAlgorithm.Apply(graph, new DeadAliveIterativeAlgorithmParameters());

            var startIndex = graph.GetMinBlockId();

            // check outs
            Assert.IsTrue(deadAliveVars.Out[startIndex]
                          .SetEquals(new[]
            {
                "a", "b"
            }));

            Assert.IsTrue(deadAliveVars.Out[startIndex + 1].Count == 0);

            Assert.IsTrue(deadAliveVars.Out[startIndex + 2]
                          .SetEquals(new[]
            {
                "a"
            }));

            Assert.IsTrue(deadAliveVars.Out[startIndex + 3].Count == 0);

            // check ins
            Assert.IsTrue(deadAliveVars.In[startIndex].Count == 0);
            Assert.IsTrue(deadAliveVars.In[startIndex + 1].SetEquals(deadAliveVars.Out[startIndex]));
            Assert.IsTrue(deadAliveVars.In[startIndex + 2].SetEquals(deadAliveVars.Out[startIndex + 1]));
            Assert.IsTrue(deadAliveVars.In[startIndex + 3].SetEquals(deadAliveVars.Out[startIndex + 2]));
        }
コード例 #5
0
        public void AvailableExpression()
        {
            string     programText      = @"
a = 4;
b = 4;
c = a + b;
if 1 
  a = 3;
else
  b = 2;
print(c);
";
            SyntaxNode root             = ParserWrap.Parse(programText);
            var        threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            var        basicBlocks      = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);
            Graph      g = new Graph(basicBlocks);

            var availableExprsIterative = IterativeAlgorithm.Apply(g, new AvailableExpressionsCalculator(g));
            var availableExprsMOP       = MeetOverPaths.Apply(g, new AvailableExpressionsCalculator(g));
            var it = availableExprsIterative.Out.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            foreach (var outInfo in it)
            {
                Trace.WriteLine(outInfo);
            }

            var mop = availableExprsMOP.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            Trace.WriteLine("====");
            foreach (var outInfo in mop)
            {
                Trace.WriteLine(outInfo);
            }

            Assert.IsTrue(availableExprsIterative.Out.OrderBy(kvp => kvp.Key).
                          Zip(availableExprsMOP.OrderBy(kvp => kvp.Key), (v1, v2) => v1.Key == v2.Key && v1.Value.SetEquals(v2.Value)).All(x => x));
        }
コード例 #6
0
        public void DeadAliveVariables2()
        {
            string     text  = @"
x = 1;
y = z + 2;

1: z = x - 1;
2: x = y * z;
";
            SyntaxNode root  = ParserWrap.Parse(text);
            Graph      graph = new Graph(
                BasicBlocksGenerator.CreateBasicBlocks(
                    ThreeAddressCodeGenerator.CreateAndVisit(root).Program));

            var deadAliveVars = IterativeAlgorithm.Apply(graph, new DeadAliveIterativeAlgorithmParameters());

            var startIndex = graph.GetMinBlockId();

            // check outs
            Assert.IsTrue(deadAliveVars.Out[startIndex]
                          .SetEquals(new[]
            {
                "x", "y"
            }));

            Assert.IsTrue(deadAliveVars.Out[startIndex + 1]
                          .SetEquals(new[]
            {
                "y", "z"
            }));

            Assert.IsTrue(deadAliveVars.Out[startIndex + 2].Count == 0);

            // check ins
            Assert.IsTrue(deadAliveVars.In[startIndex].Count == 1);
            Assert.IsTrue(deadAliveVars.In[startIndex + 1].SetEquals(deadAliveVars.Out[startIndex]));
            Assert.IsTrue(deadAliveVars.In[startIndex + 2].SetEquals(deadAliveVars.Out[startIndex + 1]));
        }
コード例 #7
0
        public void DeadAliveVariables()
        {
            string     text  = @"
a = 2;
b = 3;

1: c = a + b;
2: a = 3; 
b = 4;
3: c = a;
";
            SyntaxNode root  = ParserWrap.Parse(text);
            Graph      graph = new Graph(
                BasicBlocksGenerator.CreateBasicBlocks(
                    ThreeAddressCodeGenerator.CreateAndVisit(root).Program));

            var deadAliveVarsIterative = IterativeAlgorithm.Apply(graph, new DeadAliveIterativeAlgorithmParameters());
            var deadAliveVarsMOP       = MeetOverPaths.Apply(graph, new DeadAliveIterativeAlgorithmParameters());
            var it = deadAliveVarsIterative.In.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            foreach (var outInfo in it)
            {
                Trace.WriteLine(outInfo);
            }

            var mop = deadAliveVarsMOP.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            Trace.WriteLine("====");
            foreach (var outInfo in mop)
            {
                Trace.WriteLine(outInfo);
            }

            Assert.IsTrue(deadAliveVarsIterative.In.OrderBy(kvp => kvp.Key).
                          Zip(deadAliveVarsMOP.OrderBy(kvp => kvp.Key), (v1, v2) => v1.Key == v2.Key && v1.Value.SetEquals(v2.Value)).All(x => x));
        }
コード例 #8
0
        public void IterativeAlgorithm(List <LinkedList <ThreeCode> > blocks)
        {
            // построение CFG по блокам
            controlFlowGraph = new CFG(blocks.ToList());
            // создание информации о блоках
            var blocksInfo = new List <BlockInfo <ThreeCode> >();

            for (int i = 0; i < blocks.Count; i++)
            {
                blocksInfo.Add(new BlockInfo <ThreeCode>(blocks[i]));
            }

            // оператор сбора в задаче о распространении констант
            Func <List <BlockInfo <ThreeCode> >, CFG, int, BlockInfo <ThreeCode> > meetOperator =
                (blocksInfos, graph, index) =>
            {
                var inputIndexes = graph.cfg.GetInputNodes(index);
                var resInfo      = new BlockInfo <ThreeCode>(blocksInfos[index]);
                foreach (var i in inputIndexes)
                {
                    resInfo.IN.UnionWith(blocksInfos[i].OUT);
                }
                return(resInfo);
            };

            var transferFunction = new ReachingDefsAdaptor(controlFlowGraph).TransferFunction();

            // создание объекта итерационного алгоритма
            var iterativeAlgorithm = new IterativeAlgorithm <ThreeCode>(blocksInfo,
                                                                        controlFlowGraph, meetOperator, true, new HashSet <ThreeCode>(),
                                                                        new HashSet <ThreeCode>(), transferFunction);

            // выполнение алгоритма
            iterativeAlgorithm.Perform();
            Ins  = iterativeAlgorithm.GetINs();
            Outs = iterativeAlgorithm.GetOUTs();
        }
コード例 #9
0
        public Graph Apply(Graph graph)
        {
            var constants = IterativeAlgorithm.Apply(graph, new ConstantsPropagationParameters());

            return(graph);
        }
コード例 #10
0
        public void AvailableExpressionsTest()
        {
            string     programText      = @"
a = 4;
b = 4;
c = a + b;
if 1 
  a = 3;
else
  b = 2;
print(c);
";
            SyntaxNode root             = ParserWrap.Parse(programText);
            var        threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;

            Trace.WriteLine(threeAddressCode);

            var basicBlocks = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);

            Trace.WriteLine(Environment.NewLine + "Базовые блоки");
            Trace.WriteLine(basicBlocks);

            Trace.WriteLine(Environment.NewLine + "Управляющий граф программы");
            Graph g = new Graph(basicBlocks);

            Trace.WriteLine(g);



            Trace.WriteLine(Environment.NewLine + "Доступные выражения");
            var availableExprs = IterativeAlgorithm.Apply(g, new AvailableExpressionsCalculator(g));
            var outExpressions = availableExprs.Out.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            foreach (var outInfo in outExpressions)
            {
                Trace.WriteLine(outInfo);
            }

            int startIndex = availableExprs.Out.Keys.Min();

            Assert.IsTrue(availableExprs.Out[startIndex]
                          .SetEquals(new Expression[]
            {
                new Int32Const(4),
                new BinaryOperation(new identifier("a"), Operation.Add, new identifier("b")),
                new identifier("t0")
            }));

            Assert.IsTrue(availableExprs.Out[startIndex + 1]
                          .SetEquals(new Expression[]
            {
                new Int32Const(4),
                new Int32Const(3),
                new identifier("t0")
            }));

            Assert.IsTrue(availableExprs.Out[startIndex + 2]
                          .SetEquals(
                              new Expression[]
            {
                new Int32Const(4),
                new Int32Const(2),
                new identifier("t0")
            }));

            Assert.IsTrue(availableExprs.Out[startIndex + 3]
                          .SetEquals(
                              new Expression[]
            {
                new Int32Const(4),
                new identifier("t0")
            }));
        }
        public void ReachingExpressionsTest1()
        {
            var taCode = new TACode();

            //TAC выглядит следующим образом

            /**
             * 0)   t0 = 3            |
             * 1)   t1 = 5 + t0       | B1
             * 2)   t2 = t1 + t0      |
             *
             *
             * 3)   t3 = 4 + t2       |
             * 4)   t1 = 10           | B2
             * 5)   if (1) goto 3)    |
             *
             *
             * 6)   t4 = t1 + 5       |
             * 7)   t5 = t3 + t0      |
             * 8)   t0 = 100          | B3
             * 9)   if (2) goto 6)    |
             *
             *
             * 10)  t6 = t5 + 10      |
             * 11)  t7 = t6 + 10      |
             * 12)  t8 = t6 + t7      | B4
             * 13)  t6 = 3            |
             * 14)  t5 = 100          |
             *
             **/

            var ass1 = new Assign
            {
                Operation = OpCode.Plus,
                Right     = new IntConst(3),
                Result    = new Var()
            };

            var ass2 = new Assign
            {
                Left      = new IntConst(5),
                Operation = OpCode.Plus,
                Right     = ass1.Result,
                Result    = new Var()
            };

            var ass3 = new Assign
            {
                Left      = ass2.Result,
                Operation = OpCode.Plus,
                Right     = ass1.Result,
                Result    = new Var()
            };

            var ass4 = new Assign
            {
                Left      = new IntConst(4),
                Operation = OpCode.Plus,
                Right     = ass3.Result,
                Result    = new Var()
            };

            var ass5 = new Assign
            {
                Operation = OpCode.Plus,
                Right     = new IntConst(10),
                Result    = ass2.Result
            };

            var ifgt1 = new IfGoto
            {
                Condition   = new IntConst(1),
                TargetLabel = ass4.Label
            };

            ass4.IsLabeled = true;

            var ass6 = new Assign
            {
                Left      = ass2.Result,
                Operation = OpCode.Plus,
                Right     = new IntConst(5),
                Result    = new Var()
            };

            var ass7 = new Assign
            {
                Left      = ass4.Result,
                Operation = OpCode.Plus,
                Right     = ass1.Result,
                Result    = new Var()
            };

            var ass8 = new Assign
            {
                Operation = OpCode.Plus,
                Right     = new IntConst(100),
                Result    = ass1.Result
            };

            var ifgt2 = new IfGoto
            {
                Condition   = new IntConst(2),
                TargetLabel = ass6.Label
            };

            ass6.IsLabeled = true;

            var ass9 = new Assign
            {
                Left      = ass7.Result,
                Operation = OpCode.Plus,
                Right     = new IntConst(10),
                Result    = new Var()
            };

            var ass10 = new Assign
            {
                Left      = ass9.Result,
                Operation = OpCode.Plus,
                Right     = new IntConst(10),
                Result    = new Var()
            };

            var ass11 = new Assign
            {
                Left      = ass9.Result,
                Operation = OpCode.Plus,
                Right     = ass10.Result,
                Result    = new Var()
            };

            var ass12 = new Assign
            {
                Operation = OpCode.Plus,
                Right     = new IntConst(3),
                Result    = ass9.Result
            };

            var ass13 = new Assign
            {
                Operation = OpCode.Plus,
                Right     = new IntConst(100),
                Result    = ass7.Result
            };

            taCode.AddNode(ass1);
            taCode.AddNode(ass2);
            taCode.AddNode(ass3);
            taCode.AddNode(ass4);
            taCode.AddNode(ass5);
            taCode.AddNode(ifgt1);
            taCode.AddNode(ass6);
            taCode.AddNode(ass7);
            taCode.AddNode(ass8);
            taCode.AddNode(ifgt2);
            taCode.AddNode(ass9);
            taCode.AddNode(ass10);
            taCode.AddNode(ass11);
            taCode.AddNode(ass12);
            taCode.AddNode(ass13);

            /**         CFG имеет следующий вид
             *
             *                  B1
             *                   |
             *                   |   ____
             *                   v  /    \
             *                  B2-v______|
             *                   |
             *                   |   ____
             *                   v  /    \
             *                  B3-v______|
             *                   |
             *                   |
             *                   V
             *                  B4
             * */

            var cfg = new ControlFlowGraph(taCode);

            /**************************Reaching definition test*************************/
            var op        = new Operations(taCode);
            var algo      = new IterativeAlgorithm();
            var transFunc = new TransferFunction(taCode);
            var inout     = algo.Analyze(cfg, op, transFunc);

            //Тестирование множест e_gen и e_kill для каждого базового блока
            var(e_gen, e_kill) = transFunc.GetEGenEKill(cfg.CFGNodes.ElementAt(0));
            Assert.True(e_gen.SetEquals(new HashSet <Guid> {
                ass2.Label, ass3.Label
            }));
            Assert.True(e_kill.SetEquals(new HashSet <Guid> {
                ass4.Label, ass6.Label, ass7.Label
            }));

            (e_gen, e_kill) = transFunc.GetEGenEKill(cfg.CFGNodes.ElementAt(1));
            Assert.True(e_gen.SetEquals(new HashSet <Guid> {
                ass4.Label
            }));
            Assert.True(e_kill.SetEquals(new HashSet <Guid> {
                ass3.Label, ass6.Label, ass7.Label
            }));

            (e_gen, e_kill) = transFunc.GetEGenEKill(cfg.CFGNodes.ElementAt(2));
            Assert.True(e_gen.SetEquals(new HashSet <Guid> {
                ass6.Label
            }));
            Assert.True(e_kill.SetEquals(new HashSet <Guid> {
                ass2.Label, ass3.Label, ass7.Label, ass9.Label
            }));

            (e_gen, e_kill) = transFunc.GetEGenEKill(cfg.CFGNodes.ElementAt(3));
            Assert.True(e_gen.SetEquals(new HashSet <Guid> {
            }));
            Assert.True(e_kill.SetEquals(new HashSet <Guid> {
                ass9.Label, ass10.Label, ass11.Label
            }));

            //Текстирование IN/OUT множеств для каждого ББл
            var trueInOut = new DFA.InOutData <HashSet <System.Guid> >();

            trueInOut.Add(cfg.CFGNodes.ElementAt(0),
                          (new HashSet <Guid>(),
                           new HashSet <Guid> {
                ass2.Label, ass3.Label
            })
                          );
            trueInOut.Add(cfg.CFGNodes.ElementAt(1),
                          (new HashSet <Guid> {
                ass2.Label, ass3.Label
            },
                           new HashSet <Guid> {
                ass2.Label, ass4.Label
            })
                          );
            trueInOut.Add(cfg.CFGNodes.ElementAt(2),
                          (new HashSet <Guid> {
                ass2.Label, ass4.Label
            },
                           new HashSet <Guid> {
                ass4.Label, ass6.Label
            })
                          );
            trueInOut.Add(cfg.CFGNodes.ElementAt(3),
                          (new HashSet <Guid> {
                ass4.Label, ass6.Label
            },
                           new HashSet <Guid> {
                ass4.Label, ass6.Label
            })
                          );

            foreach (var x in cfg.CFGNodes)
            {
                HashSet <Guid> toutItem1 = trueInOut[x].Item1;
                HashSet <Guid> outItem1  = inout[x].Item1;
                HashSet <Guid> toutItem2 = trueInOut[x].Item2;
                HashSet <Guid> outItem2  = inout[x].Item2;

                var inEq  = toutItem1.SetEquals(outItem1);
                var outEq = toutItem2.SetEquals(outItem2);
                Assert.True(inEq && outEq);
            }
        }
コード例 #12
0
        public void IterativeAlgorithm(List <LinkedList <ThreeCode> > blocks)
        {
            // построение CFG по блокам
            controlFlowGraph = new CFG(blocks.ToList());
            // создание информации о блоках
            var blocksInfo = new List <ConstPropBlockInfo>();
            var m          = new Dictionary <string, ConstPropSemilatticeEl>();

            for (int i = 0; i < blocks.Count; i++)
            {
                foreach (var c in blocks[i].Where(com =>
                                                  com.operation != ThreeOperator.Goto && com.operation != ThreeOperator.IfGoto))
                {
                    string[] vars = new string[]
                    { c.result
                      , (c.arg1 as ThreeAddressStringValue)?.Value
                      , (c.arg2 as ThreeAddressStringValue)?.Value };

                    foreach (var v in vars)
                    {
                        if (v != null && v != "" && !m.ContainsKey(v))
                        {
                            m[v] = new ConstPropSemilatticeEl(ValConstType.Undef);
                        }
                    }
                }
            }
            for (int i = 0; i < blocks.Count; i++)
            {
                blocksInfo.Add(new ConstPropBlockInfo(blocks[i]));
            }

            // оператор сбора в задаче о распространении констант
            Func <List <ConstPropBlockInfo>, CFG, int, ConstPropBlockInfo> meetOperator =
                (blocksInfos, graph, index) =>
            {
                var inputIndexes = graph.cfg.GetInputNodes(index);
                var resInfo      = new ConstPropBlockInfo(blocksInfos[index]);
                foreach (var i in inputIndexes)
                {
                    var resIn = resInfo.IN.ToDictionary(e => e.Key);
                    foreach (var Out in blocksInfos[i].OUT)
                    {
                        if (resIn[Out.Key].Value.Constantness == ValConstType.Undef)
                        {
                            resIn[Out.Key] = new ConstPropKeyValue(Out.Key, Out.Value);
                        }
                        else if (resIn[Out.Key].Value.Constantness == ValConstType.NAC ||
                                 Out.Value.Constantness == ValConstType.NAC ||
                                 (resIn[Out.Key].Value.Constantness == ValConstType.Const &&
                                  Out.Value.Constantness == ValConstType.Const &&
                                  resIn[Out.Key].Value.Value != Out.Value.Value))
                        {
                            resIn[Out.Key] = new ConstPropKeyValue(Out.Key,
                                                                   new ConstPropSemilatticeEl(ValConstType.NAC));
                        }
                    }

                    resInfo.IN = new HashSet <ConstPropKeyValue>(resIn.Values);
                }
                return(resInfo);
            };

            var transferFunction = TransferFunction();

            // создание объекта итерационного алгоритма
            var iterativeAlgorithm = new IterativeAlgorithm <ConstPropKeyValue>(blocksInfo,
                                                                                controlFlowGraph, meetOperator, true, new HashSet <ConstPropKeyValue>(m),
                                                                                new HashSet <ConstPropKeyValue>(m), transferFunction);

            // выполнение алгоритма
            iterativeAlgorithm.Perform();
            Ins = iterativeAlgorithm.GetINs();
        }
コード例 #13
0
 public ExpandingPolytopeAlgorithm(IterativeAlgorithm iterationControl = null)
 {
     IterationControl = iterationControl ?? new IterativeAlgorithm();
 }
コード例 #14
0
ファイル: Program.cs プロジェクト: TheSavagest/IHopeAllGood
        private static IterativeAlgorithm <Function <Point>, Point>[] CreateIterableRCGA(int dimension)
        {
            var maxIteration  = dimension * PopulationSize;
            var maxEvaluation = PopulationSize * maxIteration;

            var evaluator = new EvaluatorStandard <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>();
            var coordinatesInitializer =
                new CoordinatesInitializerUniform <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>();
            var fitter =
                new FitterNormalizingMinimization <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>();

            var selectors = new Selector <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>[]
            {
                new SelectorProportional <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>
                    (PopulationSize, 2),
                new SelectorLinearRank <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>
                    (PopulationSize, 2),
                new SelectorTournament <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>
                    (PopulationSize, 2)
            };
            var crossovers = new CoordinatesCrossover <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>[]
            {
                new CoordinatesCrossoverArithmetic <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(),
                new CoordinatesCrossoverBLX <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(),
                new CoordinatesCrossoverExtendedLine <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(),
                new CoordinatesCrossoverHeuristic <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(),
                new CoordinatesCrossoverLinear <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(true),
                new CoordinatesCrossoverLinear <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(false),
                new CoordinatesCrossoverProportional <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>()
            };
            var mutators = new CoordinatesMutator <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>[]
            {
                new CoordinatesMutatorCombined <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(new CoordinatesMutator <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>[]
                {
                    new CoordinatesMutatorUniform <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(),
                    new CoordinatesMutatorClamp <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>()
                }),
                new CoordinatesMutatorCombined <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(new CoordinatesMutator <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>[]
                {
                    new CoordinatesMutatorMPT <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(),
                    new CoordinatesMutatorClamp <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>()
                }),
            };
            var newGenerationCreators = new NewGenerationCreator <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>[]
            {
                new NewGenerationCreatorChildrenOnly <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>
                    (PopulationSize, 0),
                new NewGenerationCreatorChildrenOnly <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>
                    (PopulationSize, 5),
                new NewGenerationCreatorChildrenPLusBest <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>
                    (PopulationSize, 0),
                new NewGenerationCreatorChildrenPLusBest <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>
                    (PopulationSize, 5)
            };

            var stopCondition = new StopCondition <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(new [] { new MoreEvaluationsThan <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(maxEvaluation) },
                                                                                                                          new [] { new DistanceFromBestToOptimumIsLessThan <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(Accuracy) });

            var algorithms = new IterativeAlgorithm <Function <Point>, Point> [selectors.Length * crossovers.Length *
                                                                               mutators.Length *
                                                                               newGenerationCreators.Length];
            var ai = 0;

            foreach (var selector in selectors)
            {
                foreach (var crossover in crossovers)
                {
                    foreach (var mutator in mutators)
                    {
                        foreach (var newGenerationCreator in newGenerationCreators)
                        {
                            algorithms[ai] = new IterativeAlgorithm <Function <Point>, Point>(PopulationSize,
                                                                                              stopCondition,
                                                                                              new MainOperatorRCGA <IterativeAlgorithm <Function <Point>, Point>, Function <Point>, Point>(evaluator, coordinatesInitializer, fitter, selector, crossover, mutator),
                                                                                              newGenerationCreator);
                            ai++;
                        }
                    }
                }
            }

            return(algorithms);
        }
コード例 #15
0
 public GilbertJohnsonKeerthiAlgorithm(IterativeAlgorithm iterationControl = null)
 {
     IterationControl = iterationControl ?? new IterativeAlgorithm();
 }
コード例 #16
0
        public void ExplicitReachingDefinition1()
        {
            string     programText      = @"
    i = 1;
    j = 4;
    a = 2;
    while i < 20
    {  
        i = i + 1;
        j = j + 1;
        if i > a
            a = a + 5;
        i = i + 1;
    }
";
            SyntaxNode root             = ParserWrap.Parse(programText);
            var        threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;

            Trace.WriteLine(threeAddressCode);

            var basicBlocks = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);

            Trace.WriteLine(Environment.NewLine + "Базовые блоки");
            Trace.WriteLine(basicBlocks);

            Trace.WriteLine(Environment.NewLine + "Управляющий граф программы");
            Graph g = new Graph(basicBlocks);

            Trace.WriteLine(g);

            Trace.WriteLine(Environment.NewLine + "Достигающие определения");

            var reachingDefs = IterativeAlgorithm.Apply(g, new ExplicitTransferFunction(g), g.GetDFN());
            var outDefs      = reachingDefs.Out.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            foreach (var outInfo in outDefs)
            {
                Trace.WriteLine(outInfo);
            }

            int startIndex = reachingDefs.Out.Keys.Min();

            Assert.IsTrue(reachingDefs.Out[startIndex]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 1),
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex, 3)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 1]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 1),
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex, 3),
                new CommandNumber(startIndex + 2, 0),
                new CommandNumber(startIndex + 2, 2),
                new CommandNumber(startIndex + 2, 3),
                new CommandNumber(startIndex + 2, 4),
                new CommandNumber(startIndex + 3, 0),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 4, 1),
                new CommandNumber(startIndex + 4, 2)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 2]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex, 3),
                new CommandNumber(startIndex + 2, 0),
                new CommandNumber(startIndex + 2, 1),
                new CommandNumber(startIndex + 2, 2),
                new CommandNumber(startIndex + 2, 3),
                new CommandNumber(startIndex + 2, 4),
                new CommandNumber(startIndex + 3, 0),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 4, 1)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 3]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 3),
                new CommandNumber(startIndex + 2, 0),
                new CommandNumber(startIndex + 2, 1),
                new CommandNumber(startIndex + 2, 2),
                new CommandNumber(startIndex + 2, 3),
                new CommandNumber(startIndex + 2, 4),
                new CommandNumber(startIndex + 3, 0),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 4, 1)
            })));
            Assert.IsTrue(reachingDefs.Out[startIndex + 4]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex, 3),
                new CommandNumber(startIndex + 2, 0),
                new CommandNumber(startIndex + 2, 2),
                new CommandNumber(startIndex + 2, 3),
                new CommandNumber(startIndex + 2, 4),
                new CommandNumber(startIndex + 3, 0),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 4, 1),
                new CommandNumber(startIndex + 4, 2)
            })));
            Assert.IsTrue(reachingDefs.Out[startIndex + 5]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 1),
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex, 3),
                new CommandNumber(startIndex + 2, 0),
                new CommandNumber(startIndex + 2, 2),
                new CommandNumber(startIndex + 2, 3),
                new CommandNumber(startIndex + 2, 4),
                new CommandNumber(startIndex + 3, 0),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 4, 1),
                new CommandNumber(startIndex + 4, 2)
            })));
        }
        public void ConstantsPropagation2()
        {
            string     programText      = @"
    e=10;
    c=4;
    d=2;
    a=4;
    if 0
        goto 2;
    a=c+d;
    e=a;
    goto 3;
2:  a=e;
3:  t=0;
";
            SyntaxNode root             = ParserWrap.Parse(programText);
            var        threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;

            Trace.WriteLine(threeAddressCode);

            var basicBlocks = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);

            Trace.WriteLine(Environment.NewLine + "Базовые блоки");
            Trace.WriteLine(basicBlocks);

            Trace.WriteLine(Environment.NewLine + "Управляющий граф программы");
            Graph g = new Graph(basicBlocks);

            Trace.WriteLine(g);

            Trace.WriteLine(Environment.NewLine + "Распространение констант");
            var consts    = IterativeAlgorithm.Apply(g, new ConstantsPropagationParameters());
            var outConsts = consts.Out.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            foreach (var outInfo in outConsts)
            {
                Trace.WriteLine(outInfo);
            }

            int startIndex = consts.Out.Keys.Min();

            Assert.IsTrue(consts.Out[startIndex]["a"] == "4" &&
                          consts.Out[startIndex]["e"] == "10" &&
                          consts.Out[startIndex]["d"] == "2" &&
                          consts.Out[startIndex]["c"] == "4");

            Assert.IsTrue(consts.Out[startIndex + 1]["a"] == "4" &&
                          consts.Out[startIndex + 1]["e"] == "10" &&
                          consts.Out[startIndex + 1]["d"] == "2" &&
                          consts.Out[startIndex + 1]["c"] == "4");

            Assert.IsTrue(consts.Out[startIndex + 2]["e"] == "6" &&
                          consts.Out[startIndex + 2]["c"] == "4" &&
                          consts.Out[startIndex + 2]["d"] == "2" &&
                          consts.Out[startIndex + 2]["a"] == "6" &&
                          consts.Out[startIndex + 2]["t0"] == "6");

            Assert.IsTrue(consts.Out[startIndex + 3]["a"] == "10" &&
                          consts.Out[startIndex + 3]["e"] == "10" &&
                          consts.Out[startIndex + 3]["d"] == "2" &&
                          consts.Out[startIndex + 3]["c"] == "4");

            Assert.IsTrue(consts.Out[startIndex + 4]["e"] == "NAC" &&
                          consts.Out[startIndex + 4]["c"] == "4" &&
                          consts.Out[startIndex + 4]["d"] == "2" &&
                          consts.Out[startIndex + 4]["t"] == "0" &&
                          consts.Out[startIndex + 4]["t0"] == "6");
        }
        public void CompositionReachingDefinition2()
        {
            string     programText      = @"
    x = 0;
    y = 0;
    if x > y
    {
        x = x + 1;
    }
    else
    {  
2:      y = y - 1;
        if y > 0 
            goto 2;
    }
    z = x + y;
";
            SyntaxNode root             = ParserWrap.Parse(programText);
            var        threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;

            Trace.WriteLine(threeAddressCode);

            var basicBlocks = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);

            Trace.WriteLine(Environment.NewLine + "Базовые блоки");
            Trace.WriteLine(basicBlocks);

            Trace.WriteLine(Environment.NewLine + "Управляющий граф программы");
            Graph g = new Graph(basicBlocks);

            Trace.WriteLine(g);

            Trace.WriteLine(Environment.NewLine + "Достигающие определения");
            var reachingDefs = IterativeAlgorithm.Apply(g, new CompositionReachingDefinitionsParameters(g), g.GetDFN());
            var outDefs      = reachingDefs.Out.Select(
                pair => $"{pair.Key}: {string.Join(", ", pair.Value.Select(ex => ex.ToString()))}");

            foreach (var outInfo in outDefs)
            {
                Trace.WriteLine(outInfo);
            }

            int startIndex = reachingDefs.Out.Keys.Min();

            Assert.IsTrue(reachingDefs.Out[startIndex]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 1),
                new CommandNumber(startIndex, 2)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 1]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 1),
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex + 1, 0),
                new CommandNumber(startIndex + 1, 1)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 2]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 1),
                new CommandNumber(startIndex, 2)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 3]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 3, 2),
                new CommandNumber(startIndex + 3, 3)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 4]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 3, 2),
                new CommandNumber(startIndex + 3, 3)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 5]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 3, 2),
                new CommandNumber(startIndex + 3, 3)
            })));

            Assert.IsTrue(reachingDefs.Out[startIndex + 6]
                          .SetEquals(
                              new SortedSet <CommandNumber>(new CommandNumber[]
            {
                new CommandNumber(startIndex, 0),
                new CommandNumber(startIndex, 1),
                new CommandNumber(startIndex, 2),
                new CommandNumber(startIndex + 1, 0),
                new CommandNumber(startIndex + 1, 1),
                new CommandNumber(startIndex + 3, 1),
                new CommandNumber(startIndex + 3, 2),
                new CommandNumber(startIndex + 3, 3),
                new CommandNumber(startIndex + 6, 1),
                new CommandNumber(startIndex + 6, 2)
            })));
        }
コード例 #19
0
        public CollisionDetector(IterativeAlgorithm iterationControl = null)
        {
            this.iterationControl = new IterativeAlgorithm(50, 1e-2f);

            gjk = new GilbertJohnsonKeerthiAlgorithm(iterationControl);
        }