Merge pull request #46 from antmicro/set_clock_groups

SDC: Add set_clock_groups command
diff --git a/sdc-plugin/Makefile b/sdc-plugin/Makefile
index 68b0917..f45efdc 100644
--- a/sdc-plugin/Makefile
+++ b/sdc-plugin/Makefile
@@ -1,3 +1,10 @@
 NAME = sdc
-SOURCES = buffers.cc clocks.cc propagation.cc sdc.cc sdc_writer.cc set_false_path.cc set_max_delay.cc
+SOURCES = buffers.cc \
+          clocks.cc \
+          propagation.cc \
+          sdc.cc \
+          sdc_writer.cc \
+          set_false_path.cc \
+          set_max_delay.cc \
+          set_clock_groups.cc
 include ../Makefile_plugin.common
diff --git a/sdc-plugin/buffers.cc b/sdc-plugin/buffers.cc
index cb54743..919de28 100644
--- a/sdc-plugin/buffers.cc
+++ b/sdc-plugin/buffers.cc
@@ -35,7 +35,7 @@
 
 void Pll::CheckInputClockPeriod(RTLIL::Cell* cell, float input_clock_period) {
     float abs_diff = fabs(ClkinPeriod() - input_clock_period);
-    bool approx_equal = abs_diff < max(ClkinPeriod(), input_clock_period) * 10 * std::numeric_limits<float>::epsilon();
+    bool approx_equal = abs_diff < std::max(ClkinPeriod(), input_clock_period) * 10 * std::numeric_limits<float>::epsilon();
     if (!approx_equal) {
 	log_cmd_error(
 	    "CLKIN[1/2]_PERIOD doesn't match the virtual clock constraint "
diff --git a/sdc-plugin/clocks.cc b/sdc-plugin/clocks.cc
index 0a1572a..c177f6a 100644
--- a/sdc-plugin/clocks.cc
+++ b/sdc-plugin/clocks.cc
@@ -18,6 +18,7 @@
 #include "clocks.h"
 #include <cassert>
 #include <cmath>
+#include <regex>
 #include "kernel/log.h"
 #include "kernel/register.h"
 #include "propagation.h"
diff --git a/sdc-plugin/clocks.h b/sdc-plugin/clocks.h
index f5b491c..67ca272 100644
--- a/sdc-plugin/clocks.h
+++ b/sdc-plugin/clocks.h
@@ -18,7 +18,6 @@
 #ifndef _CLOCKS_H_
 #define _CLOCKS_H_
 
-#include <unordered_map>
 #include <vector>
 #include "buffers.h"
 #include "kernel/rtlil.h"
diff --git a/sdc-plugin/propagation.h b/sdc-plugin/propagation.h
index bc7a6d2..6774062 100644
--- a/sdc-plugin/propagation.h
+++ b/sdc-plugin/propagation.h
@@ -26,6 +26,7 @@
    public:
     Propagation(RTLIL::Design* design, Pass* pass)
         : design_(design), pass_(pass) {}
+    virtual ~Propagation(){}
 
     virtual void Run(Clocks& clocks) = 0;
     std::vector<RTLIL::Wire*> FindSinkWiresForCellType(
diff --git a/sdc-plugin/sdc.cc b/sdc-plugin/sdc.cc
index df09526..c138b04 100644
--- a/sdc-plugin/sdc.cc
+++ b/sdc-plugin/sdc.cc
@@ -23,6 +23,7 @@
 #include "propagation.h"
 #include "set_false_path.h"
 #include "set_max_delay.h"
+#include "set_clock_groups.h"
 #include "sdc_writer.h"
 
 USING_YOSYS_NAMESPACE
@@ -255,7 +256,8 @@
           get_clocks_cmd_(clocks_),
           propagate_clocks_cmd_(clocks_),
           set_false_path_cmd_(sdc_writer_),
-          set_max_delay_cmd_(sdc_writer_) {
+          set_max_delay_cmd_(sdc_writer_),
+          set_clock_groups_cmd_(sdc_writer_) {
 	log("Loaded SDC plugin\n");
     }
 
@@ -266,6 +268,7 @@
     PropagateClocksCmd propagate_clocks_cmd_;
     SetFalsePath set_false_path_cmd_;
     SetMaxDelay set_max_delay_cmd_;
+    SetClockGroups set_clock_groups_cmd_;
 
    private:
     Clocks clocks_;
diff --git a/sdc-plugin/sdc_writer.cc b/sdc-plugin/sdc_writer.cc
index 3c106d3..e4076f8 100644
--- a/sdc-plugin/sdc_writer.cc
+++ b/sdc-plugin/sdc_writer.cc
@@ -19,6 +19,12 @@
 
 USING_YOSYS_NAMESPACE
 
+const std::map<ClockGroups::ClockGroupRelation, std::string> ClockGroups::relation_name_map = {
+    {NONE, ""},
+    {ASYNCHRONOUS, "asynchronous"},
+    {PHYSICALLY_EXCLUSIVE, "physically_exclusive"},
+    {LOGICALLY_EXCLUSIVE, "logically_exclusive"}};
+
 void SdcWriter::AddFalsePath(FalsePath false_path) {
     false_paths_.push_back(false_path);
 }
@@ -27,10 +33,15 @@
     timing_paths_.push_back(timing_path);
 }
 
+void SdcWriter::AddClockGroup(ClockGroups::ClockGroup clock_group, ClockGroups::ClockGroupRelation relation) {
+    clock_groups_.Add(clock_group, relation);
+}
+
 void SdcWriter::WriteSdc(Clocks& clocks, std::ostream& file) {
     WriteClocks(clocks, file);
     WriteFalsePaths(file);
     WriteMaxDelay(file);
+    WriteClockGroups(file);
 }
 
 void SdcWriter::WriteClocks(Clocks& clocks, std::ostream& file) {
@@ -79,3 +90,23 @@
 	file << std::endl;
     }
 }
+
+void SdcWriter::WriteClockGroups(std::ostream& file) {
+    for (size_t relation = 0; relation <= ClockGroups::CLOCK_GROUP_RELATION_SIZE; relation++) {
+	auto clock_groups = clock_groups_.GetGroups(static_cast<ClockGroups::ClockGroupRelation>(relation));
+	if (clock_groups.size() == 0) {
+	    continue;
+	}
+	file << "create_clock_groups ";
+	for (auto group : clock_groups) {
+	    file << "-group ";
+	    for (auto signal : group) {
+		file << signal << " ";
+	    }
+	}
+	if (relation != ClockGroups::ClockGroupRelation::NONE) {
+	    file << "-" + ClockGroups::relation_name_map.at(static_cast<ClockGroups::ClockGroupRelation>(relation));
+	}
+	file << std::endl;
+    }
+}
diff --git a/sdc-plugin/sdc_writer.h b/sdc-plugin/sdc_writer.h
index 5620841..05a8dea 100644
--- a/sdc-plugin/sdc_writer.h
+++ b/sdc-plugin/sdc_writer.h
@@ -18,6 +18,7 @@
 #ifndef _SDC_WRITER_H_
 #define _SDC_WRITER_H_
 #include "clocks.h"
+#include <map>
 
 USING_YOSYS_NAMESPACE
 
@@ -32,19 +33,44 @@
     float max_delay;
 };
 
+struct ClockGroups {
+    enum ClockGroupRelation { NONE, ASYNCHRONOUS, PHYSICALLY_EXCLUSIVE, LOGICALLY_EXCLUSIVE, CLOCK_GROUP_RELATION_SIZE };
+    using ClockGroup = std::vector<std::string>;
+    static const std::map<ClockGroupRelation, std::string> relation_name_map;
+
+    void Add(ClockGroup& group, ClockGroupRelation relation) {
+	groups_[relation].push_back(group);
+    }
+    std::vector<ClockGroup> GetGroups(ClockGroupRelation relation) {
+	if (groups_.count(relation)) {
+	    return groups_.at(relation);
+	}
+	return std::vector<ClockGroup>();
+    }
+    size_t size() {
+	return groups_.size();
+    }
+
+   private:
+    std::map<ClockGroupRelation,std::vector<ClockGroup>> groups_;
+};
+
 class SdcWriter {
    public:
     void AddFalsePath(FalsePath false_path);
     void SetMaxDelay(TimingPath timing_path);
+    void AddClockGroup(ClockGroups::ClockGroup clock_group, ClockGroups::ClockGroupRelation relation);
     void WriteSdc(Clocks& clocks, std::ostream& file);
 
    private:
     void WriteClocks(Clocks& clocks, std::ostream& file);
     void WriteFalsePaths(std::ostream& file);
     void WriteMaxDelay(std::ostream& file);
+    void WriteClockGroups(std::ostream& file);
 
     std::vector<FalsePath> false_paths_;
     std::vector<TimingPath> timing_paths_;
+    ClockGroups clock_groups_;
 };
 
 #endif  // _SDC_WRITER_H_
diff --git a/sdc-plugin/set_clock_groups.cc b/sdc-plugin/set_clock_groups.cc
new file mode 100644
index 0000000..301ca96
--- /dev/null
+++ b/sdc-plugin/set_clock_groups.cc
@@ -0,0 +1,116 @@
+/*
+ *  yosys -- Yosys Open SYnthesis Suite
+ *
+ *  Copyright (C) 2020  The Symbiflow Authors
+ *
+ *  Permission to use, copy, modify, and/or distribute this software for any
+ *  purpose with or without fee is hereby granted, provided that the above
+ *  copyright notice and this permission notice appear in all copies.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+#include "set_clock_groups.h"
+#include <regex>
+#include "kernel/log.h"
+
+USING_YOSYS_NAMESPACE
+
+void SetClockGroups::help() {
+    //   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
+    log("\n");
+    log("   set_clock_groups [-quiet] [-group <args>] [-asynchronous] \n");
+    log("\n");
+    log("Set exclusive or asynchronous clock groups\n");
+    log("\n");
+    log("Print the output to stdout too. This is useful when all Yosys is "
+        "executed.\n");
+    log("\n");
+    log("    -quiet\n");
+    log("        Don't print the result of the execution to stdout.\n");
+    log("\n");
+    log("    -group\n");
+    log("        List of clocks to be included in the clock group.\n");
+    log("\n");
+    log("    -asynchronous\n");
+    log("       The specified clocks are asynchronous to each other.\n");
+    log("\n");
+}
+
+void SetClockGroups::execute(std::vector<std::string> args,
+                             RTLIL::Design* design) {
+    RTLIL::Module* top_module = design->top_module();
+    if (top_module == nullptr) {
+	log_cmd_error("No top module detected\n");
+    }
+
+    size_t argidx;
+    bool is_quiet = false;
+    std::vector<ClockGroups::ClockGroup> clock_groups;
+    auto clock_groups_relation = ClockGroups::NONE;
+
+    // Parse command arguments
+    for (argidx = 1; argidx < args.size(); argidx++) {
+	std::string arg = args[argidx];
+	if (arg == "-quiet") {
+	    is_quiet = true;
+	    continue;
+	}
+
+	// Parse clock groups relation: asynchronous, logically_exclusive, physically_exclusive
+	auto is_relation_arg =
+	    [arg](std::pair<ClockGroups::ClockGroupRelation, std::string>
+	            relation) {
+	        if (arg.substr(1) == relation.second) {
+		    return true;
+	        }
+	        return false;
+	    };
+	auto relation_map_it =
+	    std::find_if(ClockGroups::relation_name_map.begin(),
+	                 ClockGroups::relation_name_map.end(), is_relation_arg);
+	if (relation_map_it != ClockGroups::relation_name_map.end()) {
+	    clock_groups_relation = relation_map_it->first;
+	    continue;
+	}
+
+	if (arg == "-group" and argidx + 1 < args.size()) {
+	    ClockGroups::ClockGroup clock_group;
+	    while (argidx + 1 < args.size() and args[argidx+1][0] != '-') {
+		clock_group.push_back(args[++argidx]);
+	    }
+	    clock_groups.push_back(clock_group);
+	    continue;
+	}
+
+	if (arg.size() > 0 and arg[0] == '-') {
+	    log_cmd_error("Unknown option %s.\n", arg.c_str());
+	}
+
+	break;
+    }
+
+    if (clock_groups.size()) {
+	if (!is_quiet) {
+	    std::string msg = ClockGroups::relation_name_map.at(clock_groups_relation);
+	    msg += (!msg.empty()) ? " " : "";
+	    log("Adding %sclock group with following clocks:\n", msg.c_str());
+	}
+	size_t count(0);
+	for (auto& group : clock_groups) {
+	    sdc_writer_.AddClockGroup(group, clock_groups_relation);
+	    if (!is_quiet) {
+		log("%zu: ", count++);
+		for (auto clk : group) {
+		    log("%s ", clk.c_str());
+		}
+		log("\n");
+	    }
+	}
+    }
+}
diff --git a/sdc-plugin/set_clock_groups.h b/sdc-plugin/set_clock_groups.h
new file mode 100644
index 0000000..3114578
--- /dev/null
+++ b/sdc-plugin/set_clock_groups.h
@@ -0,0 +1,39 @@
+/*
+ *  yosys -- Yosys Open SYnthesis Suite
+ *
+ *  Copyright (C) 2020  The Symbiflow Authors
+ *
+ *  Permission to use, copy, modify, and/or distribute this software for any
+ *  purpose with or without fee is hereby granted, provided that the above
+ *  copyright notice and this permission notice appear in all copies.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+#ifndef _SET_CLOCK_GROUPS_H_
+#define _SET_CLOCK_GROUPS_H_
+
+#include "kernel/register.h"
+#include "kernel/rtlil.h"
+#include "sdc_writer.h"
+
+USING_YOSYS_NAMESPACE
+
+struct SetClockGroups : public Pass {
+    SetClockGroups(SdcWriter& sdc_writer)
+        : Pass("set_clock_groups", "Set exclusive or asynchronous clock groups"),
+          sdc_writer_(sdc_writer) {}
+
+    void help() override;
+
+    void execute(std::vector<std::string> args, RTLIL::Design* design) override;
+
+    SdcWriter& sdc_writer_;
+};
+
+#endif  //_SET_CLOCK_GROUPS_H_
diff --git a/sdc-plugin/tests/Makefile b/sdc-plugin/tests/Makefile
index b2d146a..3b45b57 100644
--- a/sdc-plugin/tests/Makefile
+++ b/sdc-plugin/tests/Makefile
@@ -1,6 +1,8 @@
 # counter, counter2, pll - test buffer and clock divider propagation
 # set_false_path - test the set_false_path command
 # set_max_delay - test the set_max_delay command
+# set_clock_groups - test the set_clock_groups command
+
 TESTS = counter \
 	counter2 \
 	pll \
@@ -8,7 +10,9 @@
 	pll_fbout_phase \
 	pll_approx_equal \
 	set_false_path \
-	set_max_delay
+	set_max_delay \
+	set_clock_groups
+
 include $(shell pwd)/../../Makefile_test.common
 
 counter_verify = $(call diff_test,counter,sdc) && $(call diff_test,counter,txt)
@@ -19,3 +23,4 @@
 pll_approx_equal_verify = $(call diff_test,pll_approx_equal,sdc)
 set_false_path_verify = $(call diff_test,set_false_path,sdc)
 set_max_delay_verify = $(call diff_test,set_max_delay,sdc)
+set_clock_groups_verify = $(call diff_test,set_clock_groups,sdc)
diff --git a/sdc-plugin/tests/set_clock_groups/set_clock_groups.golden.sdc b/sdc-plugin/tests/set_clock_groups/set_clock_groups.golden.sdc
new file mode 100644
index 0000000..162e4d0
--- /dev/null
+++ b/sdc-plugin/tests/set_clock_groups/set_clock_groups.golden.sdc
@@ -0,0 +1,4 @@
+create_clock_groups -group clk1 clk2 
+create_clock_groups -group clk3 clk4 -group clk11 clk12 -group clk13 clk14 -asynchronous
+create_clock_groups -group clk7 clk8 -group clk9 clk10 -physically_exclusive
+create_clock_groups -group clk5 clk6 -logically_exclusive
diff --git a/sdc-plugin/tests/set_clock_groups/set_clock_groups.tcl b/sdc-plugin/tests/set_clock_groups/set_clock_groups.tcl
new file mode 100644
index 0000000..5e06b2c
--- /dev/null
+++ b/sdc-plugin/tests/set_clock_groups/set_clock_groups.tcl
@@ -0,0 +1,16 @@
+yosys -import
+plugin -i sdc
+#Import the commands from the plugins to the tcl interpreter
+yosys -import
+
+read_verilog set_clock_groups.v
+# Some of symbiflow expects eblifs with only one module.
+synth_xilinx -vpr -flatten -abc9 -nosrl -noclkbuf -nodsp
+
+set_clock_groups -group clk1 clk2
+set_clock_groups -asynchronous -group clk3 clk4
+set_clock_groups -group clk5 clk6 -logically_exclusive
+set_clock_groups -group clk7 clk8 -physically_exclusive -group clk9 clk10
+set_clock_groups -quiet -group clk11 clk12 -asynchronous -group clk13 clk14
+
+write_sdc set_clock_groups.sdc
diff --git a/sdc-plugin/tests/set_clock_groups/set_clock_groups.v b/sdc-plugin/tests/set_clock_groups/set_clock_groups.v
new file mode 100644
index 0000000..d40055b
--- /dev/null
+++ b/sdc-plugin/tests/set_clock_groups/set_clock_groups.v
@@ -0,0 +1,75 @@
+module top (
+	(* async_reg = "true", mr_ff = "true", dont_touch = "true" *) input  clk,
+	output [3:0] led,
+	inout out_a,
+	output [1:0] out_b,
+	output signal_p,
+	output signal_n
+);
+
+	wire LD6, LD7, LD8, LD9;
+	wire inter_wire, inter_wire_2;
+	localparam BITS = 1;
+	localparam LOG2DELAY = 25;
+
+	reg [BITS+LOG2DELAY-1:0] counter = 0;
+
+	always @(posedge clk) begin
+		counter <= counter + 1;
+	end
+	assign led[1] = inter_wire;
+	assign inter_wire = inter_wire_2;
+	assign {LD9, LD8, LD7, LD6} = counter >> LOG2DELAY;
+	OBUFTDS OBUFTDS_2(
+		.I(LD6),
+		.O(signal_p),
+		.OB(signal_n),
+		.T(1'b1)
+	);
+	OBUF #(
+		.IOSTANDARD("LVCMOS33"),
+		.SLEW("SLOW")
+	) OBUF_6(.I(LD6), .O(led[0]));
+	OBUF #(
+		.IOSTANDARD("LVCMOS33"),
+		.SLEW("SLOW")
+	) OBUF_7(.I(LD7), .O(inter_wire_2));
+	OBUF #(
+		.IOSTANDARD("LVCMOS33"),
+		.SLEW("SLOW")
+	) OBUF_OUT(.I(LD7), .O(out_a));
+	bottom bottom_inst(.I(LD8), .O(led[2]), .OB(out_b));
+	bottom_intermediate bottom_intermediate_inst(.I(LD9), .O(led[3]));
+endmodule
+
+module bottom_intermediate (
+	input I,
+	output O
+);
+	wire bottom_intermediate_wire;
+	assign O = bottom_intermediate_wire;
+	OBUF #(
+		.IOSTANDARD("LVCMOS33"),
+		.SLEW("SLOW")
+	) OBUF_8(.I(I), .O(bottom_intermediate_wire));
+endmodule
+
+module bottom (
+	input I,
+	output [1:0] OB,
+	output O
+);
+	OBUF #(
+		.IOSTANDARD("LVCMOS33"),
+		.SLEW("SLOW")
+	) OBUF_9(.I(I), .O(O));
+	OBUF #(
+		.IOSTANDARD("LVCMOS33"),
+		.SLEW("SLOW")
+	) OBUF_10(.I(I), .O(OB[0]));
+	OBUF #(
+		.IOSTANDARD("LVCMOS33"),
+		.SLEW("SLOW")
+	) OBUF_11(.I(I), .O(OB[1]));
+endmodule
+