public void Visit_NotCorrectOperator() { var source = "c = 9;\na = c == c;\n"; /* * c = 9; * a = c == c; */ var scanner = new Scanner(); scanner.SetSource(source, 0); var parser = new Parser(scanner); parser.Parse(); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var zeroMulVisitor = new CompareToItselfFalseOptVisitor(); parser.root.Visit(zeroMulVisitor); var expected = "c = 9;\na = (c==c);\n"; Assert.AreEqual(expected, parser.root.ToString()); }
public void SplitTACode_FourBasicBlocks() { var source = "a = 123;" + "if (a > 444) {" + "g = 34;" + "}"; /* * a = 123; * if (a > 44) { * g = 34; * } */ var scanner = new Scanner(); scanner.SetSource(source, 0); var parser = new Parser(scanner); parser.Parse(); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var threeAddressCodeVisitor = new ThreeAddressCodeVisitor(); parser.root.Visit(threeAddressCodeVisitor); threeAddressCodeVisitor.Postprocess(); var bblocks = new BasicBlocks(); bblocks.SplitTACode(threeAddressCodeVisitor.TACodeContainer); Assert.AreEqual(4, bblocks.BasicBlockItems.Count); }
public void SplitTACode_ThreeBasicBlocks() { var source = "goto l 7:" + "g = 34;" + "l 7:"; /* * goto l 7; * g = 34; * l 7: */ var scanner = new Scanner(); scanner.SetSource(source, 0); var parser = new Parser(scanner); parser.Parse(); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var threeAddressCodeVisitor = new ThreeAddressCodeVisitor(); parser.root.Visit(threeAddressCodeVisitor); threeAddressCodeVisitor.Postprocess(); var bblocks = new BasicBlocks(); bblocks.SplitTACode(threeAddressCodeVisitor.TACodeContainer); Assert.AreEqual(3, bblocks.BasicBlockItems.Count); }
public void VisitorTest() { var source = "c = a - a; \na = b - b;\n"; /* * c = a - a; * a = b - b; */ var scanner = new Scanner(); scanner.SetSource(source, 0); var parser = new Parser(scanner); parser.Parse(); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var SameMinusVisitor = new SameMinusOptVisitor(); parser.root.Visit(SameMinusVisitor); var expected = "c = 0;\na = 0;\n"; Assert.AreEqual(expected, parser.root.ToString()); }
public void SplitTACode_OneBasicBlock() { var source = "c = 9;\na = c == c;\n"; /* * c = 9; * a = c == c; */ var scanner = new Scanner(); scanner.SetSource(source, 0); var parser = new Parser(scanner); parser.Parse(); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var threeAddressCodeVisitor = new ThreeAddressCodeVisitor(); parser.root.Visit(threeAddressCodeVisitor); threeAddressCodeVisitor.Postprocess(); var bblocks = new BasicBlocks(); bblocks.SplitTACode(threeAddressCodeVisitor.TACodeContainer); Assert.AreEqual(1, bblocks.BasicBlockItems.Count); }
public void VisitorTest() { var source = "a = 777; while(false)\n a = 42; \n"; /* * a = 777 * while(false) * a = 42; */ var scanner = new Scanner(); scanner.SetSource(source, 0); var parser = new Parser(scanner); parser.Parse(); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var WhileFalseVisitor = new WhileFalseOptVisitor(); parser.root.Visit(WhileFalseVisitor); var expected = "a = 777;\n;\n"; Assert.AreEqual(expected, parser.root.ToString()); }
public void Visit_NoZeroOperators() { var source = "c = 9;\na = c * 123;\n"; /* * c = 9; * a = c * 123; */ var scanner = new Scanner(); scanner.SetSource(source, 0); var parser = new Parser(scanner); parser.Parse(); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var zeroMulVisitor = new ZeroMulOptVisitor(); parser.root.Visit(zeroMulVisitor); var expected = "c = 9;\na = (c*123);\n"; Assert.AreEqual(expected, parser.root.ToString()); }
public void Visit_IfNodeWithBoolExprTest() { var source = "if(a == 1){\n" + "a = 3;\n" + "}else{\n" + "a = 4;\n" + "}\n" + "if(true){\n" + "a = 42;\n" + "}else{\n" + "a = 24;\n" + "}\n"; var trueSource = "if(a == 1){\n" + "a = 3;\n" + "}else{\n" + "a = 4;\n" + "}\n" + "{a = 42;}\n"; var scanner1 = new Scanner(); scanner1.SetSource(source, 0); var sourceParser = new Parser(scanner1); sourceParser.Parse(); var fillParent = new FillParentVisitor(); sourceParser.root.Visit(fillParent); var scanner2 = new Scanner(); scanner2.SetSource(trueSource, 0); var trueSourceParser = new Parser(scanner2); trueSourceParser.Parse(); var plusZeroExprVisitor = new IfNodeWithBoolExprVisitor(); sourceParser.root.Visit(plusZeroExprVisitor); var printer1 = new PrettyPrintVisitor(true); var printer2 = new PrettyPrintVisitor(true); sourceParser.root.Visit(printer1); trueSourceParser.root.Visit(printer2); Console.WriteLine(printer1.Text); Console.WriteLine(printer2.Text); Assert.AreEqual(printer1.Text, printer2.Text); }
static void TacTests(Parser parser) // 14.04 { var pf = new FillParentVisitor(); parser.root.Visit(pf); //var ne = new NumberEqualityVisitor(); //parser.root.Visit(ne); //var ifelse = new AlwaysIfOrElseVisitor(); //parser.root.Visit(ifelse); var tac = new ThreeAddressCodeVisitor(); parser.root.Visit(tac); Console.WriteLine("Tac code: \n"); Console.WriteLine(tac.TACodeContainer.ToString()); }
static void TacConstantsAndCopies(Parser parser) // 14.04 { var pf = new FillParentVisitor(); parser.root.Visit(pf); var taco = new ThreeAddressCodeVisitor(); parser.root.Visit(taco); var tacCode = taco.TACodeContainer; Console.WriteLine("Tac code before: \n"); Console.WriteLine(tacCode.ToString()); var cc = new CopyAndConstantsOptimizer(tacCode); Console.WriteLine("Tac code after: \n"); Console.WriteLine(tacCode.ToString()); }
public void Visit_PlusZeroExprTest() { var source = "a = 1;\n" + "b = 1 + 0;\n" + "var1 = 0 + b;"; var trueSource = "a = 1;\n" + "b = 1;\n" + "var1 = b;\n"; var scanner1 = new Scanner(); scanner1.SetSource(source, 0); var sourceParser = new Parser(scanner1); sourceParser.Parse(); var fillParent = new FillParentVisitor(); sourceParser.root.Visit(fillParent); var scanner2 = new Scanner(); scanner2.SetSource(trueSource, 0); var trueSourceParser = new Parser(scanner2); trueSourceParser.Parse(); var plusZeroExprVisitor = new PlusZeroExprVisitor(); sourceParser.root.Visit(plusZeroExprVisitor); var printer1 = new PrettyPrintVisitor(true); var printer2 = new PrettyPrintVisitor(true); sourceParser.root.Visit(printer1); trueSourceParser.root.Visit(printer2); Console.WriteLine(printer1.Text); Console.WriteLine(printer2.Text); Assert.AreEqual(printer1.Text, printer2.Text); }
public void Visit_DelOfDeadConditionsTests() { var source = "if(a == b){;}else{;}"; var trueSource = ";"; var scanner1 = new Scanner(); scanner1.SetSource(source, 0); var sourceParser = new Parser(scanner1); sourceParser.Parse(); var fillParent = new FillParentVisitor(); sourceParser.root.Visit(fillParent); var scanner2 = new Scanner(); scanner2.SetSource(trueSource, 0); var trueSourceParser = new Parser(scanner2); trueSourceParser.Parse(); var dodcv = new DelOfDeadConditionsVisitor(); sourceParser.root.Visit(dodcv); var printer1 = new PrettyPrintVisitor(true); var printer2 = new PrettyPrintVisitor(true); sourceParser.root.Visit(printer1); trueSourceParser.root.Visit(printer2); Console.WriteLine(printer1.Text); Console.WriteLine(printer2.Text); Assert.AreEqual(printer1.Text, printer2.Text); }
public void Visit_ConstFoldingTests() { var source = "x = 50 * 10;"; var trueSource = "x = 500;"; var scanner1 = new Scanner(); scanner1.SetSource(source, 0); var sourceParser = new Parser(scanner1); sourceParser.Parse(); var fillParent = new FillParentVisitor(); sourceParser.root.Visit(fillParent); var scanner2 = new Scanner(); scanner2.SetSource(trueSource, 0); var trueSourceParser = new Parser(scanner2); trueSourceParser.Parse(); var cfv = new ConstFoldingVisitor(); sourceParser.root.Visit(cfv); var printer1 = new PrettyPrintVisitor(true); var printer2 = new PrettyPrintVisitor(true); sourceParser.root.Visit(printer1); trueSourceParser.root.Visit(printer2); Console.WriteLine(printer1.Text); Console.WriteLine(printer2.Text); Assert.AreEqual(printer1.Text, printer2.Text); }
static void CurrentTests(Parser parser) // 07.04 pervie 10 ballov { Console.WriteLine("Syntax tree before: \n"); foreach (var st in parser.root.StList) { Console.WriteLine(st); } var pf = new FillParentVisitor(); parser.root.Visit(pf); var ne = new NumberEqualityVisitor(); parser.root.Visit(ne); var ifelse = new AlwaysIfOrElseVisitor(); parser.root.Visit(ifelse); Console.WriteLine("After visitors: \n"); foreach (var st in parser.root.StList) { Console.WriteLine(st); } }
public static void Main(string[] args) { string FileName = @"../../../data/DeadOrAliveOptimizationTest.txt"; if (args.Length > 0) { FileName = args[0]; } try { string Text = File.ReadAllText(FileName); Scanner scanner = new Scanner(); scanner.SetSource(Text, 0); Parser parser = new Parser(scanner); var b = parser.Parse(); if (!b) { Console.WriteLine("Ошибка"); } else { Console.WriteLine("Синтаксическое дерево построено"); var r = parser.root; FillParentVisitor generateParrent = new FillParentVisitor(); r.Visit(generateParrent); { ThreeAddressCodeVisitor treeCod2e = new ThreeAddressCodeVisitor(); r.Visit(treeCod2e); //var blocks = new Block(treeCod2e).GenerateBlocks(); AutoThreeCodeOptimiser ap2p = new AutoThreeCodeOptimiser(); ap2p.Add(new DeadOrAliveOptimizationAdapter()); var blockwss = ap2p.Apply(treeCod2e); Console.WriteLine(ThreeAddressCodeVisitor.ToString(blockwss)); } //Console.WriteLine(r.ToString()); /*Opt2Visitor opt2 = new Opt2Visitor(); * r.Visit(opt2); * * PrettyPrintVisitor ppvis = new PrettyPrintVisitor(); * r.Visit(ppvis); * Console.WriteLine(ppvis.Text); * * Console.WriteLine("\nAssignCountVisitor"); * AssignCountVisitor vis1 = new AssignCountVisitor(); * r.Visit(vis1); * Console.WriteLine(vis1.Count); * * Console.WriteLine("\nStatementCountVisitor"); * StatementCountVisitor vis2 = new StatementCountVisitor(); * r.Visit(vis2); * Console.WriteLine(vis2.Count); * * Console.WriteLine("\nMaxCountExprOpsVisitor"); * MaxCountExprOpsVisitor vis3 = new MaxCountExprOpsVisitor(); * r.Visit(vis3); * Console.WriteLine(vis3.Max); * * Console.WriteLine("\nNestedCyclesVisitor"); * NestedCyclesVisitor vis4 = new NestedCyclesVisitor(); * r.Visit(vis4); * Console.WriteLine(vis4.HasNestedCycles); * * Console.WriteLine("\nCycleNestedToIfVisitor"); * CycleNestedToIfVisitor vis5 = new CycleNestedToIfVisitor(); * r.Visit(vis5); * Console.WriteLine(vis5.HasCycleNestedToIf); * * Console.WriteLine("\nIfNestedToCycleVisitor"); * IfNestedToCycleVisitor vis6 = new IfNestedToCycleVisitor(); * r.Visit(vis6); * Console.WriteLine(vis6.HasIfNestedToCycle); * * Console.WriteLine("\nMaxDepthOfNestedCyclesVisitor"); * MaxDepthOfNestedCyclesVisitor vis7 = new MaxDepthOfNestedCyclesVisitor(); * r.Visit(vis7); * Console.WriteLine(vis7.Max);*/ Console.WriteLine("\nGenerate Three address code"); ThreeAddressCodeVisitor treeCode = new ThreeAddressCodeVisitor(); r.Visit(treeCode); var blocks = new Block(treeCode).GenerateBlocks(); CFG controlFlowGraph = new CFG(blocks); Console.WriteLine("\nГлубина графа:\n" + GraphDepth.GetGraphDepth(controlFlowGraph)); Console.WriteLine(treeCode.ToString()); // выполнение оптимизации для программы, не разбитой на блоки //DeadOrAliveOptimization.DeleteDeadVariables(treeCode.GetCode()); // вычисление множеств Def и Use для всего графа потоков данных /*var DefUse = new DefUseBlocks(controlFlowGraph); * * var InOut = new InOutActiveVariables(DefUse, controlFlowGraph); * * ControlFlowOptimisations.DeadOrAliveOnGraph(InOut, controlFlowGraph); * * var DefUse = new DefUseBlocks(controlFlowGraph); * * GraphToDOTHelper.SaveAsDOT("C:\\Users\\vladr\\Desktop\\graph.dot", controlFlowGraph); * var InOut = new InOutActiveVariables(DefUse, controlFlowGraph); * * //ControlFlowOptimisations.DeadOrAliveOnGraph(InOut, controlFlowGraph); * Console.WriteLine("\nafter DeleteDeadVariables for graph\n"); * foreach (var block in controlFlowGraph.blocks) * foreach (var line in block) * Console.WriteLine(line); * * Console.Write("");*/ //DeadOrAliveOptimization. /* SimpleLang.Compiler.ILCodeGenerator gen = new SimpleLang.Compiler.ILCodeGenerator(); * gen.Generate(treeCode.GetCode()); * * gen.PrintCommands(); * Console.WriteLine("\nExecute:"); * gen.Execute(); * * Console.Write("");*/ //DeadOrAliveOptimization. /*CFG cfg = SimpleLang.GenericIterativeAlgorithm.Test * .DeadOrAliveOptimization(controlFlowGraph.blocks); * Console.WriteLine("\nafter DeadOrAliveOptimization\n"); * Console.WriteLine(cfg);*/ /*var constPropOptimizer = new ConstantPropagationOptimizer(); * CFG cfg1 = constPropOptimizer.ApplyOptimization(controlFlowGraph.blocks); * Console.WriteLine("\nafter ConstantPropagationOptimization\n"); * Console.WriteLine(cfg1);*/ //var reachingDefsTest = new ReachingDefsTest(); //reachingDefsTest.IterativeAlgorithm(controlFlowGraph.blocks); //reachingDefsTest.PrintOutput(); //SimpleLang.Compiler.ILCodeGenerator gen = new SimpleLang.Compiler.ILCodeGenerator(); //gen.Generate(treeCode.GetCode()); //gen.PrintCommands(); //Console.WriteLine("\nExecute:"); //gen.Execute(); AutoThreeCodeOptimiser app = new AutoThreeCodeOptimiser(); app.Add(new DistributionOfConstants()); app.Add(new EvalConstExpr()); app.Add(new ApplyAlgebraicIdentities()); var blockws = app.Apply(treeCode); Console.WriteLine(ThreeAddressCodeVisitor.ToString(blockws)); /*CFG cfg = new CFG(blocks); * TransferFunction tf = new TransferFunction(cfg); * Console.WriteLine("\nGen 1"); * foreach (var d in tf.Gen(blocks[0])) * Console.WriteLine(d); * Console.WriteLine("\nGen"); * foreach (var d in tf.Gen(blocks[3])) * Console.WriteLine(d); * Console.WriteLine("\nKill"); * foreach (var d in tf.Kill(blocks[3])) * Console.WriteLine(d); * * Console.WriteLine("\nTransfer function"); * var f = tf.BlockTransferFunction(blocks[3]); * foreach (var d in f(tf.Gen(blocks[0]))) * Console.WriteLine(d); * * var code = treeCode.GetCode(); * app.Apply(code);*/ /*Opt11Visitor opt11vis = new Opt11Visitor(); * ppvis.Text = ""; * r.Visit(opt11vis); * r.Visit(ppvis); * Console.WriteLine(ppvis.Text);*/ /*var avis = new AssignCountVisitor(); * parser.root.Visit(avis); * Console.WriteLine("Количество присваиваний = {0}", avis.Count); * Console.WriteLine("-------------------------------"); * * var pp = new PrettyPrintVisitor(); * parser.root.Visit(pp); * Console.WriteLine(pp.Text);*/ } } catch (FileNotFoundException) { Console.WriteLine("Файл {0} не найден", FileName); } catch (Exception e) { Console.WriteLine("{0}", e); } Console.ReadLine(); // ======== // My part, don't touch !!! // Sorry for this troubles, I deleted bad part // CFG controlFlowGraph = new CFG(blocks); // Console.WriteLine(treeCode.ToString()); // // выполнение оптимизации для программы, не разбитой на блоки // //DeadOrAliveOptimization.DeleteDeadVariables(treeCode.GetCode()); // // вычисление множеств Def и Use для всего графа потоков данных // var DefUse = new DefUseBlocks(controlFlowGraph); // // var InOut = new InOutActiveVariables(DefUse, controlFlowGraph); // // ControlFlowOptimisations.DeadOrAliveOnGraph(InOut, controlFlowGraph); // Console.WriteLine("\nafter DeleteDeadVariables for graph\n"); // foreach (var block in controlFlowGraph.blocks) // foreach (var line in block) // Console.WriteLine(line); // Console.Write(""); // ======== }
public static void Main() { var DirectoryPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName; string FileName = Path.Combine(DirectoryPath, "a.txt"); try { string Text = File.ReadAllText(FileName); Text = Text.Replace('\t', ' '); Scanner scanner = new Scanner(); scanner.SetSource(Text, 0); Parser parser = new Parser(scanner); var b = parser.Parse(); var r = parser.root; // Console.WriteLine(r); Console.WriteLine("Исходный текст программы"); var printv = new PrettyPrintVisitor(true); r.Visit(printv); Console.WriteLine(printv.Text); Console.WriteLine("-------------------------------"); if (!b) { Console.WriteLine("Ошибка"); } else { Console.WriteLine("Синтаксическое дерево построено"); // TODO: add loop through all tree optimizations var avis = new AssignCountVisitor(); parser.root.Visit(avis); Console.WriteLine("Количество присваиваний = {0}", avis.Count); Console.WriteLine("-------------------------------"); var operv = new OperatorCountVisitor(); parser.root.Visit(operv); Console.WriteLine(operv.Result); var maxcv = new MaxOpExprVisitor(); parser.root.Visit(maxcv); Console.WriteLine(maxcv.Result); var inncycv = new IsInnerCycleVisitor(); parser.root.Visit(inncycv); Console.WriteLine(inncycv.Result); var innifv = new IsInnerIfCycleVisitor(); parser.root.Visit(innifv); Console.WriteLine(innifv.Result); var maxdeepv = new MaxDeepCycleVistor(); parser.root.Visit(maxdeepv); Console.WriteLine(maxdeepv.Result); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var sameminusv = new SameMinusOptVisitor(); parser.root.Visit(sameminusv); var zeroMulVisitor = new ZeroMulOptVisitor(); parser.root.Visit(zeroMulVisitor); var compareFalseVisitor = new CompareToItselfFalseOptVisitor(); parser.root.Visit(compareFalseVisitor); Console.WriteLine("-------------------------------"); var ifNodeWithBoolExpr = new IfNodeWithBoolExprVisitor(); parser.root.Visit(ifNodeWithBoolExpr); //var plusZeroExpr = new PlusZeroExprVisitor(); //parser.root.Visit(plusZeroExpr); //var alwaysElse = new AlwaysElseVisitor(); //parser.root.Visit(alwaysElse); //var checkTruth = new CheckTruthVisitor(); //parser.root.Visit(checkTruth); //Console.WriteLine("Оптимизированная программа"); //printv = new PrettyPrintVisitor(true); //r.Visit(printv); //Console.WriteLine(printv.Text); //Console.WriteLine("-------------------------------"); Console.WriteLine("Оптимизированная программа"); printv = new PrettyPrintVisitor(true); r.Visit(printv); Console.WriteLine(printv.Text); Console.WriteLine("-------------------------------"); var threeAddressCodeVisitor = new ThreeAddressCodeVisitor(); r.Visit(threeAddressCodeVisitor); var cfg = new ControlFlowGraph(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine(cfg); cfg.SaveToFile(@"cfg.txt"); Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); var availExprOpt = new AvailableExprOptimization(); availExprOpt.Optimize(cfg); Console.WriteLine("======= After algebraic identity ======="); Console.WriteLine(cfg); Console.WriteLine("======= DV ======="); Console.WriteLine(threeAddressCodeVisitor); var detector = new DefUseDetector(); detector.DetectAndFillDefUse(threeAddressCodeVisitor.TACodeContainer); //Console.WriteLine("======= Detector 1 ======="); //Console.WriteLine(detector); //Console.WriteLine("======= Detector 2 ======="); //Console.WriteLine(detector.ToString2()); var constPropagationOptimizer = new DefUseConstPropagation(detector); var result = constPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("======= After const propagation ======="); Console.WriteLine(threeAddressCodeVisitor); result = constPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("======= After const propagation ======="); Console.WriteLine(threeAddressCodeVisitor); var copyPropagationOptimizer = new DefUseCopyPropagation(detector); result = copyPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("======= After copy propagation ======="); Console.WriteLine(threeAddressCodeVisitor); //var bblocks = new BasicBlocks(); //bblocks.SplitTACode(threeAddressCodeVisitor.TACodeContainer); //Console.WriteLine("Разбиение на базовые блоки завершилось"); var emptyopt = new EmptyNodeOptimization(); emptyopt.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("Empty node optimization"); Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); var gotoOpt = new GotoOptimization(); gotoOpt.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("Goto optimization"); Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); //var elimintaion = new EliminateTranToTranOpt(); //elimintaion.Optimize(threeAddressCodeVisitor.TACodeContainer); //Console.WriteLine("Удаление переходов к переходам завершилось"); var unreachableCode = new UnreachableCodeOpt(); var res = unreachableCode.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("Оптимизация для недостижимых блоков"); var algOpt = new AlgebraicIdentityOptimization(); algOpt.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("algebraic identity optimization"); Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); var bblocks = new BasicBlocks(); bblocks.SplitTACode(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("Разбиение на базовые блоки завершилось"); Console.WriteLine(); GenKillVisitor genKillVisitor = new GenKillVisitor(); var genKillContainers = genKillVisitor.GenerateReachingDefinitionForBlocks(cfg.SourceBasicBlocks); InOutContainer inOutContainers = new InOutContainer(cfg.SourceBasicBlocks, genKillContainers); Console.WriteLine("=== InOut для базовых блоков ==="); Console.WriteLine(inOutContainers.ToString()); var defUseContainers = DefUseForBlocksGenerator.Execute(cfg.SourceBasicBlocks); DefUseForBlocksPrinter.Execute(defUseContainers); var reachingDefenitionsITA = new ReachingDefinitionsITA(cfg, genKillContainers); Console.WriteLine("=== InOut после итерационного алгоритма для достигающих определения ==="); Console.WriteLine(reachingDefenitionsITA); var activeVariablesITA = new ActiveVariablesITA(cfg, defUseContainers); Console.WriteLine("=== InOut после итерационного алгоритма для активных переменных ==="); Console.WriteLine(activeVariablesITA); } } catch (FileNotFoundException) { Console.WriteLine("Файл {0} не найден", FileName); } catch (Exception e) { Console.WriteLine("{0}", e); } Console.ReadLine(); }
public static void Main() { string FileName = @"..\..\a.txt"; try { string Text = File.ReadAllText(FileName); Scanner scanner = new Scanner(); scanner.SetSource(Text, 0); Parser parser = new Parser(scanner); var b = parser.Parse(); var r = parser.root; // Console.WriteLine(r); var printv = new PrettyPrintVisitor(true); r.Visit(printv); Console.WriteLine(printv.Text); if (!b) { Console.WriteLine("Ошибка"); } else { Console.WriteLine("Синтаксическое дерево построено"); var avis = new AssignCountVisitor(); parser.root.Visit(avis); Console.WriteLine("Количество присваиваний = {0}", avis.Count); Console.WriteLine("-------------------------------"); var operv = new OperatorCountVisitor(); parser.root.Visit(operv); Console.WriteLine(operv.Result); var maxcv = new MaxOpExprVisitor(); parser.root.Visit(maxcv); Console.WriteLine(maxcv.Result); var inncycv = new IsInnerCycleVisitor(); parser.root.Visit(inncycv); Console.WriteLine(inncycv.Result); var innifv = new IsInnerIfCycleVisitor(); parser.root.Visit(innifv); Console.WriteLine(innifv.Result); var maxdeepv = new MaxDeepCycleVistor(); parser.root.Visit(maxdeepv); Console.WriteLine(maxdeepv.Result); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var sameminusv = new SameMinusOptVisitor(); parser.root.Visit(sameminusv); var whilefalsev = new WhileFalseOptVisitor(); parser.root.Visit(whilefalsev); printv = new PrettyPrintVisitor(true); r.Visit(printv); Console.WriteLine(printv.Text); //var pp = new PrettyPrintVisitor(); //parser.root.Visit(pp); //Console.WriteLine(pp.Text); } } catch (FileNotFoundException) { Console.WriteLine("Файл {0} не найден", FileName); } catch (Exception e) { Console.WriteLine("{0}", e); } Console.ReadLine(); }
public void Compute_CheckFirstBlockActiveVariables() { var source = "c = 123;\nm = 1 + c + y;\nif (m > 2) {\n c = 3;\n} else {\n c = 456;\n}\na = 11;"; /* * c = 123; * m = 1 + c + y; * if (m > 2) { * c = 3; * } else { * c = 456; * } * a = 11; */ var scanner = new Scanner(); scanner.SetSource(source, 0); var parser = new Parser(scanner); parser.Parse(); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var threeAddressCodeVisitor = new ThreeAddressCodeVisitor(); parser.root.Visit(threeAddressCodeVisitor); threeAddressCodeVisitor.Postprocess(); var cfg = new ControlFlowGraph(threeAddressCodeVisitor.TACodeContainer); var basicBlocks = new BasicBlocks(); basicBlocks.SplitTACode(cfg.SourceCode); var defUseContainers = DefUseForBlocksGenerator.Execute(cfg.SourceBasicBlocks); DefUseForBlocksPrinter.Execute(defUseContainers); var tfFunction = new TFByComposition(defUseContainers); var collectionOperator = new UnionCollectionOperator <TacNode>(); var mop = new MeetOverPaths(cfg, tfFunction, collectionOperator, new HashSet <TacNode>(), false); mop.Compute(); var expectedIn = new List <string> { "y" }; var outputIn = mop.InOut.In[cfg.SourceBasicBlocks.BasicBlockItems[0]] .Select(x => x.ToString()).ToList(); Assert.IsTrue(expectedIn.SequenceEqual(outputIn)); var outputOut = mop.InOut.Out[cfg.SourceBasicBlocks.BasicBlockItems[0]] .Select(x => x.ToString()).ToList(); Assert.AreEqual(0, outputOut.Count); }
public static void Main() { var DirectoryPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName; string FileName = Path.Combine(DirectoryPath, "a.txt"); try { string Text = File.ReadAllText(FileName); Text = Text.Replace('\t', ' '); Scanner scanner = new Scanner(); scanner.SetSource(Text, 0); Parser parser = new Parser(scanner); var b = parser.Parse(); var r = parser.root; // Console.WriteLine(r); Console.WriteLine("Исходный текст программы"); var printv = new PrettyPrintVisitor(true); r.Visit(printv); Console.WriteLine(printv.Text); Console.WriteLine("-------------------------------"); if (!b) { Console.WriteLine("Ошибка"); } else { Console.WriteLine("Синтаксическое дерево построено"); // TODO: add loop through all tree optimizations var avis = new AssignCountVisitor(); parser.root.Visit(avis); Console.WriteLine("Количество присваиваний = {0}", avis.Count); Console.WriteLine("-------------------------------"); // var operv = new OperatorCountVisitor(); // parser.root.Visit(operv); // Console.WriteLine(operv.Result); // // var maxcv = new MaxOpExprVisitor(); // parser.root.Visit(maxcv); // Console.WriteLine(maxcv.Result); // // var inncycv = new IsInnerCycleVisitor(); // parser.root.Visit(inncycv); // Console.WriteLine(inncycv.Result); // // var innifv = new IsInnerIfCycleVisitor(); // parser.root.Visit(innifv); // Console.WriteLine(innifv.Result); // // var maxdeepv = new MaxDeepCycleVistor(); // parser.root.Visit(maxdeepv); // Console.WriteLine(maxdeepv.Result); // // var parentv = new FillParentVisitor(); // parser.root.Visit(parentv); // // var sameminusv = new SameMinusOptVisitor(); // parser.root.Visit(sameminusv); // // var zeroMulVisitor = new ZeroMulOptVisitor(); // parser.root.Visit(zeroMulVisitor); // // var compareFalseVisitor = new CompareToItselfFalseOptVisitor(); // parser.root.Visit(compareFalseVisitor); var operv = new OperatorCountVisitor(); parser.root.Visit(operv); Console.WriteLine(operv.Result); var maxcv = new MaxOpExprVisitor(); parser.root.Visit(maxcv); Console.WriteLine(maxcv.Result); var inncycv = new IsInnerCycleVisitor(); parser.root.Visit(inncycv); Console.WriteLine(inncycv.Result); var innifv = new IsInnerIfCycleVisitor(); parser.root.Visit(innifv); Console.WriteLine(innifv.Result); var maxdeepv = new MaxDeepCycleVistor(); parser.root.Visit(maxdeepv); Console.WriteLine(maxdeepv.Result); var parentv = new FillParentVisitor(); parser.root.Visit(parentv); var sameminusv = new SameMinusOptVisitor(); parser.root.Visit(sameminusv); var whilefalsev = new WhileFalseOptVisitor(); parser.root.Visit(whilefalsev); var zeroMulVisitor = new ZeroMulOptVisitor(); parser.root.Visit(zeroMulVisitor); var compareFalseVisitor = new CompareToItselfFalseOptVisitor(); parser.root.Visit(compareFalseVisitor); Console.WriteLine("-------------------------------"); // // var ifNodeWithBoolExpr = new IfNodeWithBoolExprVisitor(); // parser.root.Visit(ifNodeWithBoolExpr); //var plusZeroExpr = new PlusZeroExprVisitor(); //parser.root.Visit(plusZeroExpr); var alwaysElse = new AlwaysElseVisitor(); parser.root.Visit(alwaysElse); //var checkTruth = new CheckTruthVisitor(); //parser.root.Visit(checkTruth); //Console.WriteLine("Оптимизированная программа"); //printv = new PrettyPrintVisitor(true); //r.Visit(printv); //Console.WriteLine(printv.Text); //Console.WriteLine("-------------------------------"); Console.WriteLine("Оптимизированная программа"); printv = new PrettyPrintVisitor(true); r.Visit(printv); Console.WriteLine(printv.Text); Console.WriteLine("-------------------------------"); var threeAddressCodeVisitor = new ThreeAddressCodeVisitor(); r.Visit(threeAddressCodeVisitor); threeAddressCodeVisitor.Postprocess(); Console.WriteLine("========== TAC =============="); Console.WriteLine(threeAddressCodeVisitor); var cfg = new ControlFlowGraph(threeAddressCodeVisitor.TACodeContainer); // Console.WriteLine(cfg); // cfg.SaveToFile(@"cfg.txt"); // var dstClassifier = new DstEdgeClassifier(cfg); // dstClassifier.ClassificateEdges(cfg); // Console.WriteLine(dstClassifier); Console.WriteLine(cfg); cfg.SaveToFile(@"cfg.txt"); var dstClassifier = new DstEdgeClassifier(cfg); dstClassifier.ClassificateEdges(cfg); Console.WriteLine(dstClassifier); var depth = cfg.GetDepth(dstClassifier.EdgeTypes); Console.WriteLine($"Depth CFG = {depth}"); /* -----------------------CFG TASKS START---------------------------------*/ Console.WriteLine("\nCFG TASKS START"); Console.WriteLine(cfg); var edgeClassifierService = new EdgeClassifierService(cfg); Console.WriteLine("EdgeClassifierService: \n" + edgeClassifierService); bool isReducibility = DSTReducibility.IsReducibility(cfg); Console.WriteLine("IsReducibility: " + isReducibility); var naturalCycles = new CFGNaturalCycles(cfg); Console.WriteLine("\nNaturalCycles: \n" + naturalCycles); //Console.WriteLine("\nNestedCycles: \n" + naturalCycles.NestedLoopsText()); Console.WriteLine("\nCFG TASKS END"); /* -----------------------CFG TASKS END---------------------------------*/ //Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); //var availExprOpt = new AvailableExprOptimization(); //availExprOpt.Optimize(cfg); //Console.WriteLine("======= After algebraic identity ======="); //Console.WriteLine(cfg); // Console.WriteLine("======= DV ======="); // Console.WriteLine(threeAddressCodeVisitor); // var detector = new DefUseDetector(); // detector.DetectAndFillDefUse(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine(); Console.WriteLine("Before optimization"); Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); /*Console.WriteLine("======= DV ======="); * Console.WriteLine(threeAddressCodeVisitor); * var detector = new DefUseDetector(); * detector.DetectAndFillDefUse(threeAddressCodeVisitor.TACodeContainer); * * //Console.WriteLine("======= Detector 1 ======="); * //Console.WriteLine(detector); * //Console.WriteLine("======= Detector 2 ======="); * //Console.WriteLine(detector.ToString2()); * * // var constPropagationOptimizer = new DefUseConstPropagation(detector); * // var result = constPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); * // * // Console.WriteLine("======= After const propagation ======="); * // Console.WriteLine(threeAddressCodeVisitor); * // * // result = constPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); * // Console.WriteLine("======= After const propagation ======="); * // Console.WriteLine(threeAddressCodeVisitor); * // * // var copyPropagationOptimizer = new DefUseCopyPropagation(detector); * // result = copyPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); * // * // Console.WriteLine("======= After copy propagation ======="); * // Console.WriteLine(threeAddressCodeVisitor); * ======= * var constPropagationOptimizer = new DefUseConstPropagation(detector); * var result = constPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); * * Console.WriteLine("======= After const propagation ======="); * Console.WriteLine(threeAddressCodeVisitor); * * result = constPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); * Console.WriteLine("======= After const propagation ======="); * Console.WriteLine(threeAddressCodeVisitor); * * var copyPropagationOptimizer = new DefUseCopyPropagation(detector); * result = copyPropagationOptimizer.Optimize(threeAddressCodeVisitor.TACodeContainer); * * Console.WriteLine("======= After copy propagation ======="); * Console.WriteLine(threeAddressCodeVisitor); */ //var bblocks = new BasicBlocks(); //bblocks.SplitTACode(threeAddressCodeVisitor.TACodeContainer); //Console.WriteLine("Разбиение на базовые блоки завершилось"); var emptyopt = new EmptyNodeOptimization(); emptyopt.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("Empty node optimization"); Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); // var gotoOpt = new GotoOptimization(); // gotoOpt.Optimize(threeAddressCodeVisitor.TACodeContainer); // Console.WriteLine("Goto optimization"); // Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); //var elimintaion = new EliminateTranToTranOpt(); //elimintaion.Optimize(threeAddressCodeVisitor.TACodeContainer); //Console.WriteLine("Удаление переходов к переходам завершилось"); // var unreachableCode = new UnreachableCodeOpt(); // var res = unreachableCode.Optimize(threeAddressCodeVisitor.TACodeContainer); // Console.WriteLine("Оптимизация для недостижимых блоков"); var algOpt = new AlgebraicIdentityOptimization(); algOpt.Optimize(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("algebraic identity optimization"); Console.WriteLine(threeAddressCodeVisitor.TACodeContainer); var bblocks = new BasicBlocks(); bblocks.SplitTACode(threeAddressCodeVisitor.TACodeContainer); Console.WriteLine("Разбиение на базовые блоки завершилось"); Console.WriteLine(); GenKillVisitor genKillVisitor = new GenKillVisitor(); var genKillContainers = genKillVisitor.GenerateReachingDefinitionForBlocks(cfg.SourceBasicBlocks); //start var commonTf = new TFByCommonWay(genKillContainers); var composTf = new TFByComposition(genKillContainers); Console.WriteLine("=== Compos ==="); Console.WriteLine(composTf.Calculate(new HashSet <TacNode>(), cfg.SourceBasicBlocks.BasicBlockItems.First())); Console.WriteLine("=== Common ==="); Console.WriteLine(commonTf.Calculate(new HashSet <TacNode>(), cfg.SourceBasicBlocks.BasicBlockItems.First())); //end // InOutContainerWithFilling inOutContainers = // new InOutContainerWithFilling(cfg.SourceBasicBlocks, genKillContainers); // Console.WriteLine("=== InOut для базовых блоков ==="); // Console.WriteLine(inOutContainers.ToString()); var defUseContainers = DefUseForBlocksGenerator.Execute(cfg.SourceBasicBlocks); DefUseForBlocksPrinter.Execute(defUseContainers); var reachingDefenitionsITA = new ReachingDefinitionsITA(cfg, genKillContainers); Console.WriteLine("=== InOut после итерационного алгоритма для достигающих определения ==="); Console.WriteLine(reachingDefenitionsITA.InOut); Console.WriteLine("======================================================================="); var reachingDefConstPropagation = new ReachingDefinitionsConstPropagation(); Console.WriteLine(threeAddressCodeVisitor); reachingDefConstPropagation.Optimize(reachingDefenitionsITA); reachingDefConstPropagation.Optimize(reachingDefenitionsITA); foreach (var bblock in bblocks) { Console.Write(bblock); } Console.WriteLine("============ Dominators ============"); var dominators = new DominatorsFinder(cfg); for (var i = 0; i < dominators.Dominators.Count; ++i) { Console.WriteLine(i + ": "); foreach (var tacNode in dominators.Dominators.ElementAt(i).Value) { Console.WriteLine(tacNode); } } Console.WriteLine("============ Immediate Dominators ============"); for (var i = 0; i < dominators.ImmediateDominators.Count; ++i) { Console.WriteLine(i + ": "); if (dominators.ImmediateDominators.ElementAt(i).Value == null) { Console.WriteLine("null"); } else { foreach (var tacNode in dominators.ImmediateDominators.ElementAt(i).Value) { Console.WriteLine(tacNode); } } Console.WriteLine(); } // var activeVariablesITA = new ActiveVariablesITA(cfg, defUseContainers); // Console.WriteLine("=== InOut после итерационного алгоритма для активных переменных ==="); // Console.WriteLine(activeVariablesITA.InOut); var activeVariablesITA = new ActiveVariablesITA(cfg, defUseContainers); Console.WriteLine("=== InOut после итерационного алгоритма для активных переменных ==="); Console.WriteLine(activeVariablesITA.InOut); /* -----------------------AvailableExpressions START---------------------------------*/ Console.WriteLine("AvailableExpressions Optimization"); Console.WriteLine("Before AvailableExprOptimization"); Console.WriteLine(cfg.SourceBasicBlocks .BasicBlockItems.Select((bl, ind) => $"BLOCK{ind}:\n" + bl.ToString()).Aggregate((b1, b2) => b1 + b2)); E_GenKillVisitor availExprVisitor = new E_GenKillVisitor(); var availExprContainers = availExprVisitor.GenerateAvailableExpressionForBlocks(cfg.SourceBasicBlocks); var availableExpressionsITA = new AvailableExpressionsITA(cfg, availExprContainers); Console.WriteLine("=== InOut после итерационного алгоритма для доступных выражений ==="); Console.WriteLine(availableExpressionsITA.InOut); var inData = availableExpressionsITA.InOut.In; var availableExprOptimization = new AvailableExprOptimization(); bool isUsed = availableExprOptimization.Optimize(availableExpressionsITA); Console.WriteLine("AvailableExprOptimization isUsed: " + isUsed); isUsed = availableExprOptimization.Optimize(availableExpressionsITA); Console.WriteLine("AvailableExprOptimization isUsed: " + isUsed); Console.WriteLine(cfg.SourceBasicBlocks .BasicBlockItems.Select((bl, ind) => $"BLOCK{ind}:\n" + bl.ToString()).Aggregate((b1, b2) => b1 + b2)); /* -----------------------AvailableExpressions END---------------------------------*/ /* -----------------------ConstDistribOptimization START---------------------------------*/ Console.WriteLine("ConstDistributionOptimization: Before"); Console.WriteLine(cfg.SourceBasicBlocks .BasicBlockItems.Select((bl, ind) => $"BLOCK{ind}:\n" + bl.ToString()).Aggregate((b1, b2) => b1 + b2)); var constDistITA = new ConstDistributionITA(cfg); var constDistOpt = new ConstDistributionOptimization(); var isConstDistApplied = constDistOpt.Optimize(constDistITA); Console.WriteLine("ConstDistributionOptimization isUsed: " + isConstDistApplied); Console.WriteLine(cfg.SourceBasicBlocks .BasicBlockItems.Select((bl, ind) => $"BLOCK{ind}:\n" + bl.ToString()).Aggregate((b1, b2) => b1 + b2)); /* -----------------------ConstDistrib END---------------------------------*/ } } catch (FileNotFoundException) { Console.WriteLine("Файл {0} не найден", FileName); } catch (Exception e) { Console.WriteLine("{0}", e); } Console.ReadLine(); }