Ejemplo n.º 1
0
        public void TestDFN()
        {
            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;
            Graph      g   = new Graph(BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode));
            var        DFN = g.GetDFN();

            int startIndex = g.GetMinBlockId();

            Assert.IsTrue(DFN[startIndex] == 1);
            Assert.IsTrue(DFN[startIndex + 1] == 3);
            Assert.IsTrue(DFN[startIndex + 2] == 2);
            Assert.IsTrue(DFN[startIndex + 3] == 4);
        }
Ejemplo n.º 2
0
        public void FindReverseEdges3()
        {
            string programText = @"
            for i = 1..10
              if i < 5
                println(i);
              else
                println(i-5);
            ";

            SyntaxNode      root             = ParserWrap.Parse(programText);
            var             threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            BasicBlocksList basicBlocks      = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);
            Graph           g            = new Graph(basicBlocks);
            var             reverseEdges = FindReverseEdge.FindReverseEdges(g);

            List <Tuple <int, int> > tuples = new List <Tuple <int, int> >();

            foreach (var v in reverseEdges)
            {
                Trace.WriteLine(v.Source.BlockId + " -> " + v.Target.BlockId);
                tuples.Add(new Tuple <int, int>(v.Source.BlockId, v.Target.BlockId));
            }

            int start = g.GetMinBlockId();

            Assert.IsTrue(tuples.SequenceEqual(new List <Tuple <int, int> >()
            {
                new Tuple <int, int>(start + 5, start + 1)
            }
                                               ));
        }
Ejemplo n.º 3
0
        public void ThreeeAddressCodeTest()
        {
            string text = @"
            a = 2;
            while a > 1
                a = a - 1;";

            SyntaxTree.SyntaxNodes.SyntaxNode root = ParserWrap.Parse(text);
            var threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;

            var expectedCommands = new List <ThreeAddressCommand>
            {
                new Assignment("a", new Int32Const(2)),
                new Assignment("t0", new BinaryOperation("a", Operation.Greater, 1)),
                new ConditionalGoto("$GL_2", new BinaryOperation("t0", Operation.Equal, 0))
                {
                    Label = "$GL_1"
                },
                new Assignment("t1", new BinaryOperation("a", Operation.Subtract, 1)),
                new Assignment("a", new Identifier("t1")),
                new Goto("$GL_1"),
                new NoOperation("$GL_2")
            };

            CollectionAssert.AreEqual(threeAddressCode.Commands, expectedCommands);
        }
Ejemplo n.º 4
0
        public void TransferFunctionStorage()
        {
            string     text    = @"
    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(text);
            var        graph   = new Graph(BasicBlocksGenerator.CreateBasicBlocks(ThreeAddressCodeGenerator.CreateAndVisit(root).Program));
            var        regions = new RegionSequence().CreateSequence(graph);
            var        storage = new AbstractTransferFunctionStorage <int>();

            for (var i = 0; i < regions.Count - 1; i++)
            {
                storage[regions[i], RegionDirection.Out, regions[i + 1]] = 2 * i;
                storage[regions[i], RegionDirection.In, regions[i + 1]]  = 2 * i + 1;
            }

            for (var i = 0; i < regions.Count - 1; i++)
            {
                Assert.IsTrue(storage[regions[i], RegionDirection.Out, regions[i + 1]] == 2 * i);
                Assert.IsTrue(storage[regions[i], RegionDirection.In, regions[i + 1]] == 2 * i + 1);
            }
        }
Ejemplo n.º 5
0
        public void RetreatingNotReverseEdges3()
        {
            var programText = File.ReadAllText("./../../RetreatingNotReverseEdgesEx3.txt");

            SyntaxNode root  = ParserWrap.Parse(programText);
            Graph      graph = new Graph(
                BasicBlocksGenerator.CreateBasicBlocks(
                    ThreeAddressCodeGenerator.CreateAndVisit(root).Program));

            Assert.IsFalse(CheckRetreatingIsReverse.CheckReverseEdges(graph));
        }
        public void CFG2TACodeTransformationTest()
        {
            foreach (string sourseText in sources)
            {
                SyntaxTree.SyntaxNodes.SyntaxNode root            = ParserWrap.Parse(sourseText);
                var                        sourceThreeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
                BasicBlocksList            bbl = BasicBlocksGenerator.CreateBasicBlocks(sourceThreeAddressCode);
                Graph                      cfg = new Graph(bbl);
                List <ThreeAddressCommand> resultThreeAddressCode = cfg.transformToThreeAddressCode();

                CollectionAssert.AreEqual(sourceThreeAddressCode.Commands, resultThreeAddressCode);
            }
        }
Ejemplo n.º 7
0
        public void CreateSequenceTest()
        {
            string programText1 = @"
                                i = 1; 
                                j = 4; 
                                a = 2; 
                                while i < 20 
                                { 
                                i = i + 1; 
                                j = j + 1; 
                                if i > a 
                                a = a + 5; 
                                while j < 5
                                {
                                a = 4;
                                }
                                i = i + 1; 
                                }";

            SyntaxNode     root             = ParserWrap.Parse(programText1);
            var            threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            Graph          g   = new Graph(BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode));
            RegionSequence seq = new RegionSequence();

            List <Region> seqList = seq.CreateSequence(g);

            Assert.IsTrue(seqList.Count == 14);

            string programText2 = @"
                                i = 1; 
                                j = 4; 
                                a = 2; 
                                while i < 20 
                                { 
                                j = j + 1;  
                                i = i + 1; 
                                }";

            SyntaxNode     root2             = ParserWrap.Parse(programText2);
            var            threeAddressCode2 = ThreeAddressCodeGenerator.CreateAndVisit(root2).Program;
            Graph          g2   = new Graph(BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode2));
            RegionSequence seq2 = new RegionSequence();

            List <Region> seqList2 = seq2.CreateSequence(g2);

            Assert.IsTrue(seqList2.Count == 7);
        }
        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]));
        }
Ejemplo n.º 9
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));
        }
Ejemplo n.º 10
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));
        }
Ejemplo n.º 11
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));
        }
        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]));
        }
Ejemplo n.º 13
0
        public void NaturalLoopsTest()
        {
            string programText_1 = @"
b = 1;
if 1 
  b = 3;
else
  b = 2;
";

            string programText_2 = @"
b = 1;
if 1
  b = 3;
else
  for i = 1..5
    b = 6;
";

            string programText_3 = @"
i = 10;
1: i = i - 1;
if i > 0
  goto 1;
";

            string programText_4 = @"
i = 1; 
j = 4; 
a = 2; 
while i < 20 
{ 
  i = i + 1; 
  j = j + 1; 
  if i > a 
    a = a + 5; 
  i = i + 1; 
}
";

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 1");
            Trace.WriteLine("===============");
            SyntaxNode root             = ParserWrap.Parse(programText_1);
            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);

            var allNaturalLoops = SearchNaturalLoops.FindAllNaturalLoops(g);
            var tuples          = new List <Tuple <int, int, SortedSet <int> > >();

            foreach (var v in allNaturalLoops)
            {
                Trace.Write(v.Key.Source.BlockId + " -> " + v.Key.Target.BlockId + " : ");
                foreach (int k in v.Value)
                {
                    Trace.Write(k.ToString() + " ");
                }
                Trace.WriteLine("");
                tuples.Add(new Tuple <int, int, SortedSet <int> >(v.Key.Source.BlockId, v.Key.Target.BlockId, new SortedSet <int>(v.Value)));
            }

            int start = g.GetMinBlockId();

            Assert.IsTrue(tuples.SequenceEqual(new List <Tuple <int, int, SortedSet <int> > >()));

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 2");
            Trace.WriteLine("===============");

            root             = ParserWrap.Parse(programText_2);
            threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            Trace.WriteLine(threeAddressCode);

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

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

            allNaturalLoops = SearchNaturalLoops.FindAllNaturalLoops(g);
            tuples          = new List <Tuple <int, int, SortedSet <int> > >();
            foreach (var v in allNaturalLoops)
            {
                Trace.Write(v.Key.Source.BlockId + " -> " + v.Key.Target.BlockId + " : ");
                foreach (int k in v.Value)
                {
                    Trace.Write(k.ToString() + " ");
                }
                Trace.WriteLine("");
                tuples.Add(new Tuple <int, int, SortedSet <int> >(v.Key.Source.BlockId, v.Key.Target.BlockId, new SortedSet <int>(v.Value)));
            }

            start = g.GetMinBlockId();

            var check = new List <Tuple <int, int, SortedSet <int> > >()
            {
                new Tuple <int, int, SortedSet <int> >(start + 4, start + 3, new SortedSet <int>()
                {
                    start + 3, start + 4
                })
            };

            Assert.IsTrue(tuples.Count == 1);
            Assert.IsTrue(tuples[0].Item1 == check[0].Item1);
            Assert.IsTrue(tuples[0].Item2 == check[0].Item2);
            Assert.IsTrue(tuples[0].Item3.SequenceEqual(check[0].Item3));

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 3");
            Trace.WriteLine("===============");

            root             = ParserWrap.Parse(programText_3);
            threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            Trace.WriteLine(threeAddressCode);

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

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

            allNaturalLoops = SearchNaturalLoops.FindAllNaturalLoops(g);
            tuples          = new List <Tuple <int, int, SortedSet <int> > >();
            foreach (var v in allNaturalLoops)
            {
                Trace.Write(v.Key.Source.BlockId + " -> " + v.Key.Target.BlockId + " : ");
                foreach (int k in v.Value)
                {
                    Trace.Write(k.ToString() + " ");
                }
                Trace.WriteLine("");
                tuples.Add(new Tuple <int, int, SortedSet <int> >(v.Key.Source.BlockId, v.Key.Target.BlockId, new SortedSet <int>(v.Value)));
            }

            start = g.GetMinBlockId();

            check = new List <Tuple <int, int, SortedSet <int> > >()
            {
                new Tuple <int, int, SortedSet <int> >(start + 2, start + 1, new SortedSet <int>()
                {
                    start + 1, start + 2
                })
            };

            Assert.IsTrue(tuples.Count == 1);
            Assert.IsTrue(tuples[0].Item1 == check[0].Item1);
            Assert.IsTrue(tuples[0].Item2 == check[0].Item2);
            Assert.IsTrue(tuples[0].Item3.SequenceEqual(check[0].Item3));

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 4");
            Trace.WriteLine("===============");

            root             = ParserWrap.Parse(programText_4);
            threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            Trace.WriteLine(threeAddressCode);

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

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

            allNaturalLoops = SearchNaturalLoops.FindAllNaturalLoops(g);
            tuples          = new List <Tuple <int, int, SortedSet <int> > >();
            foreach (var v in allNaturalLoops)
            {
                Trace.Write(v.Key.Source.BlockId + " -> " + v.Key.Target.BlockId + " : ");
                foreach (int k in v.Value)
                {
                    Trace.Write(k.ToString() + " ");
                }
                Trace.WriteLine("");
                tuples.Add(new Tuple <int, int, SortedSet <int> >(v.Key.Source.BlockId, v.Key.Target.BlockId, new SortedSet <int>(v.Value)));
            }

            start = g.GetMinBlockId();

            check = new List <Tuple <int, int, SortedSet <int> > >()
            {
                new Tuple <int, int, SortedSet <int> >(start + 4, start + 1, new SortedSet <int>()
                {
                    start + 1, start + 2, start + 3, start + 4
                })
            };

            Assert.IsTrue(tuples.Count == 1);
            Assert.IsTrue(tuples[0].Item1 == check[0].Item1);
            Assert.IsTrue(tuples[0].Item2 == check[0].Item2);
            Assert.IsTrue(tuples[0].Item3.SequenceEqual(check[0].Item3));
        }
        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")
            }));
        }
Ejemplo n.º 15
0
        public void ThisIsAwfulTestDontMakeItWorse()
        {
            string FileName = @"../../../a.txt";

            try
            {
                string     text = File.ReadAllText(FileName);
                SyntaxNode root = ParserWrap.Parse(text);
                Trace.WriteLine(root == null ? "Ошибка" : "Программа распознана");
                if (root != null)
                {
                    var prettyPrintedProgram = PrettyPrinter.CreateAndVisit(root).FormattedCode;
                    Trace.WriteLine(prettyPrintedProgram);

                    var threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
                    Trace.WriteLine(threeAddressCode);

                    Trace.WriteLine("\nУправляющий граф программы");
                    Graph g = new Graph(BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode));

                    Trace.WriteLine(g);

                    Trace.WriteLine("Дерево доминаторов");
                    var dTree = new DominatorsTree(g);
                    Trace.WriteLine(dTree);

                    Trace.WriteLine("Классификация рёбер");
                    var classEdge = EdgeClassification.ClassifyEdge(g);
                    foreach (var p in classEdge)
                    {
                        Trace.WriteLine(p.Key.Source.BlockId + "->" + p.Key.Target.BlockId + "; type = " + p.Value);
                    }

                    Trace.WriteLine("\nНахождение естественных циклов");
                    var findNL = SearchNaturalLoops.FindAllNaturalLoops(g);
                    foreach (var nl in findNL)
                    {
                        Trace.Write(nl.Key.Source.BlockId + "->" + nl.Key.Target.BlockId + ": ");
                        foreach (var node in nl.Value)
                        {
                            Trace.Write(node.ToString() + " ");
                        }
                        Trace.WriteLine("");
                    }

                    Trace.WriteLine(("\nПостроение глубинного остовного дерева"));
                    var DFN = g.GetDFN();
                    foreach (var node in DFN)
                    {
                        Trace.WriteLine("key: " + node.Key + " " + "value: " + node.Value);
                    }

                    List <Region> regions = new List <Region>();
                    foreach (BasicBlock v in g)
                    {
                        regions.Add(new LeafRegion(v));
                    }

                    foreach (var l in findNL)
                    {
                        List <Region> regs = l.Value.Select(x => new LeafRegion(g.getBlockById(x)) as Region).ToList();
                        regions.Add(new LoopRegion(new BodyRegion(l.Key.Target, l.Key.Source.OutputBlocks, regs)));
                    }
                }
            }
            catch (FileNotFoundException)
            {
                Trace.WriteLine("Файл {0} не найден", FileName);
            }
            catch (LexException e)
            {
                Trace.WriteLine("Лексическая ошибка. " + e.Message);
            }
            catch (SyntaxException e)
            {
                Trace.WriteLine("Синтаксическая ошибка. " + e.Message);
            }
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            /*string FileName = @"../../../a.txt";
             * try
             * {
             *  string text = File.ReadAllText(FileName);
             *  SyntaxNode root = ParserWrap.Parse(text);
             *  Console.WriteLine(root == null ? "Ошибка" : "Программа распознана");
             *  if (root != null)
             *  {
             *      var prettyPrintedProgram = PrettyPrinter.CreateAndVisit(root).FormattedCode;
             *      Console.WriteLine(prettyPrintedProgram);
             *  }
             * }
             * catch (FileNotFoundException)
             * {
             *  Console.WriteLine("Файл {0} не найден", FileName);
             * }
             * catch (LexException e)
             * {
             *  Console.WriteLine("Лексическая ошибка. " + e.Message);
             * }
             * catch (SyntaxException e)
             * {
             *  Console.WriteLine("Синтаксическая ошибка. " + e.Message);
             * }*/
            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;

            Console.WriteLine(threeAddressCode);

            var basicBlocks = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);

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

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

            Console.WriteLine(g);

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

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

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

            Console.ReadKey();
        }
        public void EdgeClassificationTest()
        {
            string programText_1 = @"
b = 1;
if 1 
  b = 3;
else
  b = 2;
";

            string programText_2 = @"
b = 1;
if 1
  b = 3;
else
  for i = 1..5
    b = 6;
";

            string programText_3 = @"
i = 10;
1: i = i - 1;
if i > 0
  goto 1;
";

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 1");
            Trace.WriteLine("===============");
            SyntaxNode root             = ParserWrap.Parse(programText_1);
            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);

            var edgeClassify = EdgeClassification.ClassifyEdge(g);
            List <Tuple <int, int, EdgeType> > tuples = new List <Tuple <int, int, EdgeType> >();

            foreach (var v in edgeClassify)
            {
                Trace.WriteLine(v.Key.Source.BlockId + " -> " + v.Key.Target.BlockId + " : " + v.Value);
                tuples.Add(new Tuple <int, int, EdgeType>(v.Key.Source.BlockId, v.Key.Target.BlockId, v.Value));
            }

            int start = g.GetMinBlockId();

            Assert.IsTrue(tuples.SequenceEqual(new List <Tuple <int, int, EdgeType> >()
            {
                new Tuple <int, int, EdgeType>(start, start + 1, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start, start + 2, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start + 1, start + 3, EdgeType.Cross),
                new Tuple <int, int, EdgeType>(start + 2, start + 3, EdgeType.Cross)
            }
                                               ));

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 2");
            Trace.WriteLine("===============");

            root             = ParserWrap.Parse(programText_2);
            threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            Trace.WriteLine(threeAddressCode);

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

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

            edgeClassify = EdgeClassification.ClassifyEdge(g);
            tuples       = new List <Tuple <int, int, EdgeType> >();
            foreach (var v in edgeClassify)
            {
                Trace.WriteLine(v.Key.Source.BlockId + " -> " + v.Key.Target.BlockId + " : " + v.Value);
                tuples.Add(new Tuple <int, int, EdgeType>(v.Key.Source.BlockId, v.Key.Target.BlockId, v.Value));
            }

            start = g.GetMinBlockId();

            Assert.IsTrue(tuples.SequenceEqual(new List <Tuple <int, int, EdgeType> >()
            {
                new Tuple <int, int, EdgeType>(start, start + 1, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start, start + 2, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start + 1, start + 6, EdgeType.Cross),
                new Tuple <int, int, EdgeType>(start + 2, start + 3, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start + 3, start + 4, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start + 3, start + 5, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start + 4, start + 3, EdgeType.Retreating),
                new Tuple <int, int, EdgeType>(start + 5, start + 6, EdgeType.Cross)
            }
                                               ));

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 3");
            Trace.WriteLine("===============");

            root             = ParserWrap.Parse(programText_3);
            threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            Trace.WriteLine(threeAddressCode);

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

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

            edgeClassify = EdgeClassification.ClassifyEdge(g);
            tuples       = new List <Tuple <int, int, EdgeType> >();
            foreach (var v in edgeClassify)
            {
                Trace.WriteLine(v.Key.Source.BlockId + " -> " + v.Key.Target.BlockId + " : " + v.Value);
                tuples.Add(new Tuple <int, int, EdgeType>(v.Key.Source.BlockId, v.Key.Target.BlockId, v.Value));
            }

            start = g.GetMinBlockId();

            Assert.IsTrue(tuples.SequenceEqual(new List <Tuple <int, int, EdgeType> >()
            {
                new Tuple <int, int, EdgeType>(start, start + 1, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start + 1, start + 2, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start + 1, start + 3, EdgeType.Advancing),
                new Tuple <int, int, EdgeType>(start + 2, start + 1, EdgeType.Retreating)
            }
                                               ));
        }
Ejemplo n.º 18
0
        public void ExplicitReachingDefinition2()
        {
            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 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)
            })));

            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)
            })));
        }
        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");
        }
Ejemplo n.º 20
0
        public void BasicBlockList1()
        {
            string programText = @"
for i = 1 + 2 * 3 .. 10
  println(i);
";

            SyntaxNode root             = ParserWrap.Parse(programText);
            var        threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            var        basicBlocks      = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);

            BasicBlocksList            BBL      = new BasicBlocksList();
            List <ThreeAddressCommand> commands = new List <ThreeAddressCommand>();

            commands.Add(new Assignment("t0",
                                        new BinaryOperation(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(2),
                                                            SyntaxTree.Operation.Multiply,
                                                            new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(3))));
            commands.Add(new Assignment("t1",
                                        new BinaryOperation(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(1),
                                                            SyntaxTree.Operation.Add,
                                                            new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("t0"))));
            commands.Add(new Assignment("i",
                                        new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("t1")));
            BBL.Add(new BasicBlock(commands, new List <int>(), new List <int>()
            {
                1
            }));

            commands.Clear();
            commands.Add(new ConditionalGoto("$GL_2",
                                             new BinaryOperation(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("i"),
                                                                 SyntaxTree.Operation.Greater,
                                                                 new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(10))));
            commands[0].Label = "$GL_1";
            BBL.Add(new BasicBlock(commands, new List <int>()
            {
                0, 2
            }, new List <int>()
            {
                2, 3
            }));

            commands.Clear();
            commands.Add(new Print(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("i"), true));
            commands.Add(new Assignment("i",
                                        new BinaryOperation(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("i"),
                                                            SyntaxTree.Operation.Add,
                                                            new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(1))));
            commands.Add(new Goto("$GL_1"));
            BBL.Add(new BasicBlock(commands, new List <int>()
            {
                1
            }, new List <int>()
            {
                1
            }));

            commands.Clear();
            commands.Add(new NoOperation("$GL_2"));
            BBL.Add(new BasicBlock(commands, new List <int>()
            {
                1
            }, new List <int>()));

            int start = basicBlocks.Blocks[0].BlockId;

            Assert.IsTrue(basicBlocks.Blocks[0].Commands.Select(x => x.ToString()).SequenceEqual(BBL.Blocks[0].Commands.Select(x => x.ToString())));
            Assert.IsTrue(basicBlocks.Blocks[0].InputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[0].InputBlocks));
            Assert.IsTrue(basicBlocks.Blocks[0].OutputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[0].OutputBlocks));

            Assert.IsTrue(basicBlocks.Blocks[1].Commands.Select(x => x.ToString()).SequenceEqual(BBL.Blocks[1].Commands.Select(x => x.ToString())));
            Assert.IsTrue(basicBlocks.Blocks[1].InputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[1].InputBlocks));
            Assert.IsTrue(basicBlocks.Blocks[1].OutputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[1].OutputBlocks));

            Assert.IsTrue(basicBlocks.Blocks[2].Commands.Select(x => x.ToString()).SequenceEqual(BBL.Blocks[2].Commands.Select(x => x.ToString())));
            Assert.IsTrue(basicBlocks.Blocks[2].InputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[2].InputBlocks));
            Assert.IsTrue(basicBlocks.Blocks[2].OutputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[2].OutputBlocks));

            Assert.IsTrue(basicBlocks.Blocks[3].Commands.Select(x => x.ToString()).SequenceEqual(BBL.Blocks[3].Commands.Select(x => x.ToString())));
            Assert.IsTrue(basicBlocks.Blocks[3].InputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[3].InputBlocks));
            Assert.IsTrue(basicBlocks.Blocks[3].OutputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[3].OutputBlocks));
        }
Ejemplo n.º 21
0
        //[TestMethod]
        public void RegionsAlgorithm1()
        {
            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 = RegionsAlgorithm.Apply(g, new ExplicitTransferFunction(g));
            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)
            })));
        }
Ejemplo n.º 22
0
        public void DominatorsTreesTest()
        {
            string programText_1 = @"
b = 1;
if 1 
  b = 3;
else
  b = 2;
";

            string programText_2 = @"
b = 1;
if 1
  b = 3;
else
  for i = 1..5
    b = 6;
";

            string programText_3 = @"
i = 10;
1: i = i - 1;
if i > 0
  goto 1;
";

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 1");
            Trace.WriteLine("===============");
            SyntaxNode root             = ParserWrap.Parse(programText_1);
            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);

            var dominatorsTree = new DominatorsTree(g);

            foreach (var v in dominatorsTree.GetMap())
            {
                Trace.WriteLine(v.Key + " " + v.Value);
            }

            int start = g.GetMinBlockId();

            Assert.IsTrue(dominatorsTree.GetMap().OrderBy(x => x.Key).SequenceEqual(
                              new Dictionary <int, int> {
                { start, start }, { start + 1, start }, { start + 2, start }, { start + 3, start }
            }
                              .OrderBy(x => x.Key)));

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 2");
            Trace.WriteLine("===============");

            root             = ParserWrap.Parse(programText_2);
            threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            Trace.WriteLine(threeAddressCode);

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

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

            dominatorsTree = new DominatorsTree(g);
            foreach (var v in dominatorsTree.GetMap())
            {
                Trace.WriteLine(v.Key + " " + v.Value);
            }
            start = g.GetMinBlockId();
            Assert.IsTrue(dominatorsTree.GetMap().OrderBy(x => x.Key).SequenceEqual(
                              new Dictionary <int, int> {
                { start, start }, { start + 1, start }, { start + 2, start }, { start + 3, start + 2 }, { start + 4, start + 3 }, { start + 5, start + 3 }, { start + 6, start }
            }
                              .OrderBy(x => x.Key)));

            Trace.WriteLine("===============");
            Trace.WriteLine("Тест 3");
            Trace.WriteLine("===============");

            root             = ParserWrap.Parse(programText_3);
            threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            Trace.WriteLine(threeAddressCode);

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

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

            dominatorsTree = new DominatorsTree(g);
            foreach (var v in dominatorsTree.GetMap())
            {
                Trace.WriteLine(v.Key + " " + v.Value);
            }
            start = g.GetMinBlockId();
            Assert.IsTrue(dominatorsTree.GetMap().OrderBy(x => x.Key).SequenceEqual(
                              new Dictionary <int, int> {
                { start, start }, { start + 1, start }, { start + 2, start + 1 }, { start + 3, start + 1 }
            }
                              .OrderBy(x => x.Key)));
        }
        public void TestDefUse()
        {
            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;
            BasicBlocksList basicBlocks      = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);

            DefUseBlockCalculator defUse = new DefUseBlockCalculator();

            var defUseList = new List <KeyValuePair <int, Tuple <ISet <string>, ISet <string> > > >();

            foreach (var block in basicBlocks)
            {
                defUseList.Add(new KeyValuePair <int, Tuple <ISet <string>, ISet <string> > >(block.BlockId, defUse.GetDefUseSetsByBlock(block)));
            }

            Assert.IsTrue(defUseList[0].Value.Item1
                          .SetEquals(
                              new HashSet <string>(new string[]
            {
                "a",
                "t0",
                "b",
                "c"
            })));
            Assert.IsTrue(defUseList[0].Value.Item2.Count == 0);

            Assert.IsTrue(defUseList[1].Value.Item1
                          .SetEquals(
                              new HashSet <string>(new string[]
            {
                "a"
            })));
            Assert.IsTrue(defUseList[1].Value.Item2.Count == 0);

            Assert.IsTrue(defUseList[2].Value.Item1
                          .SetEquals(
                              new HashSet <string>(new string[]
            {
                "b"
            })));
            Assert.IsTrue(defUseList[2].Value.Item2.Count == 0);

            Assert.IsTrue(defUseList[3].Value.Item2
                          .SetEquals(
                              new HashSet <string>(new string[]
            {
                "c"
            })));
            Assert.IsTrue(defUseList[3].Value.Item1.Count == 0);
        }
Ejemplo n.º 24
0
        public void BasicBlockList2()
        {
            string programText = @"
x = 5;
if x < 5 
  x = x + 1;
else
  x = x - 1;
println(x);
";

            SyntaxNode root             = ParserWrap.Parse(programText);
            var        threeAddressCode = ThreeAddressCodeGenerator.CreateAndVisit(root).Program;
            var        basicBlocks      = BasicBlocksGenerator.CreateBasicBlocks(threeAddressCode);

            BasicBlocksList            BBL      = new BasicBlocksList();
            List <ThreeAddressCommand> commands = new List <ThreeAddressCommand>();

            commands.Add(new Assignment("x",
                                        new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(5)));
            commands.Add(new Assignment("t0",
                                        new BinaryOperation(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("x"),
                                                            SyntaxTree.Operation.Lesser,
                                                            new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(5))));
            commands.Add(new ConditionalGoto("$GL_2",
                                             new BinaryOperation(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("t0"),
                                                                 SyntaxTree.Operation.Equal,
                                                                 new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(0))));
            BBL.Add(new BasicBlock(commands, new List <int>(), new List <int>()
            {
                1, 2
            }));

            commands.Clear();
            commands.Add(new Assignment("t1",
                                        new BinaryOperation(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("x"),
                                                            SyntaxTree.Operation.Add,
                                                            new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(1))));
            commands.Add(new Assignment("x",
                                        new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("t1")));
            commands.Add(new Goto("$GL_1"));
            BBL.Add(new BasicBlock(commands, new List <int>()
            {
                0
            }, new List <int>()
            {
                3
            }));

            commands.Clear();
            commands.Add(new NoOperation("$GL_2"));
            commands.Add(new Assignment("t2",
                                        new BinaryOperation(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("x"),
                                                            SyntaxTree.Operation.Subtract,
                                                            new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Int32Const(1))));
            commands.Add(new Assignment("x",
                                        new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("t2")));
            BBL.Add(new BasicBlock(commands, new List <int>()
            {
                0
            }, new List <int>()
            {
                3
            }));

            commands.Clear();
            commands.Add(new NoOperation("$GL_1"));
            commands.Add(new Print(new DataFlowAnalysis.IntermediateRepresentation.ThreeAddressCode.Model.Identifier("x"), true));
            BBL.Add(new BasicBlock(commands, new List <int>()
            {
                1, 2
            }, new List <int>()));

            int start = basicBlocks.Blocks[0].BlockId;

            Assert.IsTrue(basicBlocks.Blocks[0].Commands.Select(x => x.ToString()).SequenceEqual(BBL.Blocks[0].Commands.Select(x => x.ToString())));
            Assert.IsTrue(basicBlocks.Blocks[0].InputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[0].InputBlocks));
            Assert.IsTrue(basicBlocks.Blocks[0].OutputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[0].OutputBlocks));

            Assert.IsTrue(basicBlocks.Blocks[1].Commands.Select(x => x.ToString()).SequenceEqual(BBL.Blocks[1].Commands.Select(x => x.ToString())));
            Assert.IsTrue(basicBlocks.Blocks[1].InputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[1].InputBlocks));
            Assert.IsTrue(basicBlocks.Blocks[1].OutputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[1].OutputBlocks));

            Assert.IsTrue(basicBlocks.Blocks[2].Commands.Select(x => x.ToString()).SequenceEqual(BBL.Blocks[2].Commands.Select(x => x.ToString())));
            Assert.IsTrue(basicBlocks.Blocks[2].InputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[2].InputBlocks));
            Assert.IsTrue(basicBlocks.Blocks[2].OutputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[2].OutputBlocks));

            Assert.IsTrue(basicBlocks.Blocks[3].Commands.Select(x => x.ToString()).SequenceEqual(BBL.Blocks[3].Commands.Select(x => x.ToString())));
            Assert.IsTrue(basicBlocks.Blocks[3].InputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[3].InputBlocks));
            Assert.IsTrue(basicBlocks.Blocks[3].OutputBlocks.Select(x => x - start).SequenceEqual(BBL.Blocks[3].OutputBlocks));
        }