text
stringlengths 938
1.05M
|
---|
// DESCRIPTION: Verilator: initial edge issue
//
// The module initial_edge drives the output "res" high when the reset signal,
// rst, goes high.
//
// The module initial_edge_n drives the output "res_n" high when the reset
// signal, rst_n, goes low.
//
// For 4-state simulators, that edge occurs when the initial value of rst_n,
// X, goes to zero. However, by default for Verilator, being 2-state, the
// initial value is zero, so no edge is seen.
//
// This is not a bug in verilator (it is bad design to rely on an edge
// transition from an unitialized signal), but the problem is that there are
// quite a few instances of code out there that seems to be dependent on this
// behaviour to get out of reset.
//
// The Verilator --x-initial-edge flag causes these initial edges to trigger,
// thus matching the behaviour of a 4-state simulator. This is reportedly also
// the behaviour of commercial cycle accurate modelling tools as well.
//
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Wilson Snyder.
`timescale 1ns/1ns
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire res;
wire res_n;
reg rst;
reg rst_n;
integer count = 0;
initial_edge i_edge (.res (res),
.rst (rst));
initial_edge_n i_edge_n (.res_n (res_n),
.rst_n (rst_n));
// run for 3 cycles, with one cycle of reset.
always @(posedge clk) begin
rst <= (count == 0) ? 1 : 0;
rst_n <= (count == 0) ? 0 : 1;
if (count == 3) begin
if ((res == 1) && (res_n == 1)) begin
$write ("*-* All Finished *-*\n");
$finish;
end
else begin
`ifdef TEST_VERBOSE
$write ("FAILED: res = %b, res_n = %b\n", res, res_n);
`endif
$stop;
end
end
count = count + 1;
end
endmodule
module initial_edge_n (res_n,
rst_n);
output res_n;
input rst_n;
reg res_n = 1'b0;
always @(negedge rst_n) begin
if (rst_n == 1'b0) begin
res_n <= 1'b1;
end
end
endmodule // initial_edge_n
module initial_edge (res,
rst);
output res;
input rst;
reg res = 1'b0;
always @(posedge rst) begin
if (rst == 1'b1) begin
res <= 1'b1;
end
end
endmodule // initial_edge
|
// DESCRIPTION: Verilator: initial edge issue
//
// The module initial_edge drives the output "res" high when the reset signal,
// rst, goes high.
//
// The module initial_edge_n drives the output "res_n" high when the reset
// signal, rst_n, goes low.
//
// For 4-state simulators, that edge occurs when the initial value of rst_n,
// X, goes to zero. However, by default for Verilator, being 2-state, the
// initial value is zero, so no edge is seen.
//
// This is not a bug in verilator (it is bad design to rely on an edge
// transition from an unitialized signal), but the problem is that there are
// quite a few instances of code out there that seems to be dependent on this
// behaviour to get out of reset.
//
// The Verilator --x-initial-edge flag causes these initial edges to trigger,
// thus matching the behaviour of a 4-state simulator. This is reportedly also
// the behaviour of commercial cycle accurate modelling tools as well.
//
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Wilson Snyder.
`timescale 1ns/1ns
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire res;
wire res_n;
reg rst;
reg rst_n;
integer count = 0;
initial_edge i_edge (.res (res),
.rst (rst));
initial_edge_n i_edge_n (.res_n (res_n),
.rst_n (rst_n));
// run for 3 cycles, with one cycle of reset.
always @(posedge clk) begin
rst <= (count == 0) ? 1 : 0;
rst_n <= (count == 0) ? 0 : 1;
if (count == 3) begin
if ((res == 1) && (res_n == 1)) begin
$write ("*-* All Finished *-*\n");
$finish;
end
else begin
`ifdef TEST_VERBOSE
$write ("FAILED: res = %b, res_n = %b\n", res, res_n);
`endif
$stop;
end
end
count = count + 1;
end
endmodule
module initial_edge_n (res_n,
rst_n);
output res_n;
input rst_n;
reg res_n = 1'b0;
always @(negedge rst_n) begin
if (rst_n == 1'b0) begin
res_n <= 1'b1;
end
end
endmodule // initial_edge_n
module initial_edge (res,
rst);
output res;
input rst;
reg res = 1'b0;
always @(posedge rst) begin
if (rst == 1'b1) begin
res <= 1'b1;
end
end
endmodule // initial_edge
|
// DESCRIPTION: Verilator: initial edge issue
//
// The module initial_edge drives the output "res" high when the reset signal,
// rst, goes high.
//
// The module initial_edge_n drives the output "res_n" high when the reset
// signal, rst_n, goes low.
//
// For 4-state simulators, that edge occurs when the initial value of rst_n,
// X, goes to zero. However, by default for Verilator, being 2-state, the
// initial value is zero, so no edge is seen.
//
// This is not a bug in verilator (it is bad design to rely on an edge
// transition from an unitialized signal), but the problem is that there are
// quite a few instances of code out there that seems to be dependent on this
// behaviour to get out of reset.
//
// The Verilator --x-initial-edge flag causes these initial edges to trigger,
// thus matching the behaviour of a 4-state simulator. This is reportedly also
// the behaviour of commercial cycle accurate modelling tools as well.
//
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Wilson Snyder.
`timescale 1ns/1ns
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire res;
wire res_n;
reg rst;
reg rst_n;
integer count = 0;
initial_edge i_edge (.res (res),
.rst (rst));
initial_edge_n i_edge_n (.res_n (res_n),
.rst_n (rst_n));
// run for 3 cycles, with one cycle of reset.
always @(posedge clk) begin
rst <= (count == 0) ? 1 : 0;
rst_n <= (count == 0) ? 0 : 1;
if (count == 3) begin
if ((res == 1) && (res_n == 1)) begin
$write ("*-* All Finished *-*\n");
$finish;
end
else begin
`ifdef TEST_VERBOSE
$write ("FAILED: res = %b, res_n = %b\n", res, res_n);
`endif
$stop;
end
end
count = count + 1;
end
endmodule
module initial_edge_n (res_n,
rst_n);
output res_n;
input rst_n;
reg res_n = 1'b0;
always @(negedge rst_n) begin
if (rst_n == 1'b0) begin
res_n <= 1'b1;
end
end
endmodule // initial_edge_n
module initial_edge (res,
rst);
output res;
input rst;
reg res = 1'b0;
always @(posedge rst) begin
if (rst == 1'b1) begin
res <= 1'b1;
end
end
endmodule // initial_edge
|
(** * Rel: Properties of Relations *)
Require Export SfLib.
(** This short, optional chapter develops some basic definitions and a
few theorems about binary relations in Coq. The key definitions
are repeated where they are actually used (in the [Smallstep]
chapter), so readers who are already comfortable with these ideas
can safely skim or skip this chapter. However, relations are also
a good source of exercises for developing facility with Coq's
basic reasoning facilities, so it may be useful to look at it just
after the [Logic] chapter. *)
(** A (binary) _relation_ on a set [X] is a family of propositions
parameterized by two elements of [X] -- i.e., a proposition about
pairs of elements of [X]. *)
Definition relation (X: Type) := X->X->Prop.
(** Somewhat confusingly, the Coq standard library hijacks the generic
term "relation" for this specific instance. To maintain
consistency with the library, we will do the same. So, henceforth
the Coq identifier [relation] will always refer to a binary
relation between some set and itself, while the English word
"relation" can refer either to the specific Coq concept or the
more general concept of a relation between any number of possibly
different sets. The context of the discussion should always make
clear which is meant. *)
(** An example relation on [nat] is [le], the less-that-or-equal-to
relation which we usually write like this [n1 <= n2]. *)
Print le.
(* ====> Inductive le (n : nat) : nat -> Prop :=
le_n : n <= n
| le_S : forall m : nat, n <= m -> n <= S m *)
Check le : nat -> nat -> Prop.
Check le : relation nat.
(* ######################################################### *)
(** * Basic Properties of Relations *)
(** As anyone knows who has taken an undergraduate discrete math
course, there is a lot to be said about relations in general --
ways of classifying relations (are they reflexive, transitive,
etc.), theorems that can be proved generically about classes of
relations, constructions that build one relation from another,
etc. For example... *)
(** A relation [R] on a set [X] is a _partial function_ if, for every
[x], there is at most one [y] such that [R x y] -- i.e., if [R x
y1] and [R x y2] together imply [y1 = y2]. *)
Definition partial_function {X: Type} (R: relation X) :=
forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.
(** For example, the [next_nat] relation defined earlier is a partial
function. *)
Print next_nat.
(* ====> Inductive next_nat (n : nat) : nat -> Prop :=
nn : next_nat n (S n) *)
Check next_nat : relation nat.
Theorem next_nat_partial_function :
partial_function next_nat.
Proof.
unfold partial_function.
intros x y1 y2 H1 H2.
inversion H1. inversion H2.
reflexivity. Qed.
(** However, the [<=] relation on numbers is not a partial function.
In short: Assume, for a contradiction, that [<=] is a partial
function. But then, since [0 <= 0] and [0 <= 1], it follows that
[0 = 1]. This is nonsense, so our assumption was
contradictory. *)
Theorem le_not_a_partial_function :
~ (partial_function le).
Proof.
unfold not. unfold partial_function. intros Hc.
assert (0 = 1) as Nonsense.
Case "Proof of assertion".
apply Hc with (x := 0).
apply le_n.
apply le_S. apply le_n.
inversion Nonsense. Qed.
(** **** Exercise: 2 stars, optional *)
(** Show that the [total_relation] defined in earlier is not a partial
function. *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional *)
(** Show that the [empty_relation] defined earlier is a partial
function. *)
(* FILL IN HERE *)
(** [] *)
(** A _reflexive_ relation on a set [X] is one for which every element
of [X] is related to itself. *)
Definition reflexive {X: Type} (R: relation X) :=
forall a : X, R a a.
Theorem le_reflexive :
reflexive le.
Proof.
unfold reflexive. intros n. apply le_n. Qed.
(** A relation [R] is _transitive_ if [R a c] holds whenever [R a b]
and [R b c] do. *)
Definition transitive {X: Type} (R: relation X) :=
forall a b c : X, (R a b) -> (R b c) -> (R a c).
Theorem le_trans :
transitive le.
Proof.
intros n m o Hnm Hmo.
induction Hmo.
Case "le_n". apply Hnm.
Case "le_S". apply le_S. apply IHHmo. Qed.
Theorem lt_trans:
transitive lt.
Proof.
unfold lt. unfold transitive.
intros n m o Hnm Hmo.
apply le_S in Hnm.
apply le_trans with (a := (S n)) (b := (S m)) (c := o).
apply Hnm.
apply Hmo. Qed.
(** **** Exercise: 2 stars, optional *)
(** We can also prove [lt_trans] more laboriously by induction,
without using le_trans. Do this.*)
Theorem lt_trans' :
transitive lt.
Proof.
(* Prove this by induction on evidence that [m] is less than [o]. *)
unfold lt. unfold transitive.
intros n m o Hnm Hmo.
induction Hmo as [| m' Hm'o].
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
(** Prove the same thing again by induction on [o]. *)
Theorem lt_trans'' :
transitive lt.
Proof.
unfold lt. unfold transitive.
intros n m o Hnm Hmo.
induction o as [| o'].
(* FILL IN HERE *) Admitted.
(** [] *)
(** The transitivity of [le], in turn, can be used to prove some facts
that will be useful later (e.g., for the proof of antisymmetry
below)... *)
Theorem le_Sn_le : forall n m, S n <= m -> n <= m.
Proof.
intros n m H. apply le_trans with (S n).
apply le_S. apply le_n.
apply H. Qed.
(** **** Exercise: 1 star, optional *)
Theorem le_S_n : forall n m,
(S n <= S m) -> (n <= m).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional (le_Sn_n_inf) *)
(** Provide an informal proof of the following theorem:
Theorem: For every [n], [~(S n <= n)]
A formal proof of this is an optional exercise below, but try
the informal proof without doing the formal proof first.
Proof:
(* FILL IN HERE *)
[]
*)
(** **** Exercise: 1 star, optional *)
Theorem le_Sn_n : forall n,
~ (S n <= n).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Reflexivity and transitivity are the main concepts we'll need for
later chapters, but, for a bit of additional practice working with
relations in Coq, here are a few more common ones.
A relation [R] is _symmetric_ if [R a b] implies [R b a]. *)
Definition symmetric {X: Type} (R: relation X) :=
forall a b : X, (R a b) -> (R b a).
(** **** Exercise: 2 stars, optional *)
Theorem le_not_symmetric :
~ (symmetric le).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** A relation [R] is _antisymmetric_ if [R a b] and [R b a] together
imply [a = b] -- that is, if the only "cycles" in [R] are trivial
ones. *)
Definition antisymmetric {X: Type} (R: relation X) :=
forall a b : X, (R a b) -> (R b a) -> a = b.
(** **** Exercise: 2 stars, optional *)
Theorem le_antisymmetric :
antisymmetric le.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
Theorem le_step : forall n m p,
n < m ->
m <= S p ->
n <= p.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** A relation is an _equivalence_ if it's reflexive, symmetric, and
transitive. *)
Definition equivalence {X:Type} (R: relation X) :=
(reflexive R) /\ (symmetric R) /\ (transitive R).
(** A relation is a _partial order_ when it's reflexive,
_anti_-symmetric, and transitive. In the Coq standard library
it's called just "order" for short. *)
Definition order {X:Type} (R: relation X) :=
(reflexive R) /\ (antisymmetric R) /\ (transitive R).
(** A preorder is almost like a partial order, but doesn't have to be
antisymmetric. *)
Definition preorder {X:Type} (R: relation X) :=
(reflexive R) /\ (transitive R).
Theorem le_order :
order le.
Proof.
unfold order. split.
Case "refl". apply le_reflexive.
split.
Case "antisym". apply le_antisymmetric.
Case "transitive.". apply le_trans. Qed.
(* ########################################################### *)
(** * Reflexive, Transitive Closure *)
(** The _reflexive, transitive closure_ of a relation [R] is the
smallest relation that contains [R] and that is both reflexive and
transitive. Formally, it is defined like this in the Relations
module of the Coq standard library: *)
Inductive clos_refl_trans {A: Type} (R: relation A) : relation A :=
| rt_step : forall x y, R x y -> clos_refl_trans R x y
| rt_refl : forall x, clos_refl_trans R x x
| rt_trans : forall x y z,
clos_refl_trans R x y ->
clos_refl_trans R y z ->
clos_refl_trans R x z.
(** For example, the reflexive and transitive closure of the
[next_nat] relation coincides with the [le] relation. *)
Theorem next_nat_closure_is_le : forall n m,
(n <= m) <-> ((clos_refl_trans next_nat) n m).
Proof.
intros n m. split.
Case "->".
intro H. induction H.
SCase "le_n". apply rt_refl.
SCase "le_S".
apply rt_trans with m. apply IHle. apply rt_step. apply nn.
Case "<-".
intro H. induction H.
SCase "rt_step". inversion H. apply le_S. apply le_n.
SCase "rt_refl". apply le_n.
SCase "rt_trans".
apply le_trans with y.
apply IHclos_refl_trans1.
apply IHclos_refl_trans2. Qed.
(** The above definition of reflexive, transitive closure is
natural -- it says, explicitly, that the reflexive and transitive
closure of [R] is the least relation that includes [R] and that is
closed under rules of reflexivity and transitivity. But it turns
out that this definition is not very convenient for doing
proofs -- the "nondeterminism" of the [rt_trans] rule can sometimes
lead to tricky inductions.
Here is a more useful definition... *)
Inductive refl_step_closure {X:Type} (R: relation X) : relation X :=
| rsc_refl : forall (x : X), refl_step_closure R x x
| rsc_step : forall (x y z : X),
R x y ->
refl_step_closure R y z ->
refl_step_closure R x z.
(** (Note that, aside from the naming of the constructors, this
definition is the same as the [multi] step relation used in many
other chapters.) *)
(** (The following [Tactic Notation] definitions are explained in
another chapter. You can ignore them if you haven't read the
explanation yet.) *)
Tactic Notation "rt_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "rt_step" | Case_aux c "rt_refl"
| Case_aux c "rt_trans" ].
Tactic Notation "rsc_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "rsc_refl" | Case_aux c "rsc_step" ].
(** Our new definition of reflexive, transitive closure "bundles"
the [rt_step] and [rt_trans] rules into the single rule step.
The left-hand premise of this step is a single use of [R],
leading to a much simpler induction principle.
Before we go on, we should check that the two definitions do
indeed define the same relation...
First, we prove two lemmas showing that [refl_step_closure] mimics
the behavior of the two "missing" [clos_refl_trans]
constructors. *)
Theorem rsc_R : forall (X:Type) (R:relation X) (x y : X),
R x y -> refl_step_closure R x y.
Proof.
intros X R x y H.
apply rsc_step with y. apply H. apply rsc_refl. Qed.
(** **** Exercise: 2 stars, optional (rsc_trans) *)
Theorem rsc_trans :
forall (X:Type) (R: relation X) (x y z : X),
refl_step_closure R x y ->
refl_step_closure R y z ->
refl_step_closure R x z.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Then we use these facts to prove that the two definitions of
reflexive, transitive closure do indeed define the same
relation. *)
(** **** Exercise: 3 stars, optional (rtc_rsc_coincide) *)
Theorem rtc_rsc_coincide :
forall (X:Type) (R: relation X) (x y : X),
clos_refl_trans R x y <-> refl_step_closure R x y.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** $Date: 2014-12-31 15:31:47 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Rel: Properties of Relations *)
Require Export SfLib.
(** This short, optional chapter develops some basic definitions and a
few theorems about binary relations in Coq. The key definitions
are repeated where they are actually used (in the [Smallstep]
chapter), so readers who are already comfortable with these ideas
can safely skim or skip this chapter. However, relations are also
a good source of exercises for developing facility with Coq's
basic reasoning facilities, so it may be useful to look at it just
after the [Logic] chapter. *)
(** A (binary) _relation_ on a set [X] is a family of propositions
parameterized by two elements of [X] -- i.e., a proposition about
pairs of elements of [X]. *)
Definition relation (X: Type) := X->X->Prop.
(** Somewhat confusingly, the Coq standard library hijacks the generic
term "relation" for this specific instance. To maintain
consistency with the library, we will do the same. So, henceforth
the Coq identifier [relation] will always refer to a binary
relation between some set and itself, while the English word
"relation" can refer either to the specific Coq concept or the
more general concept of a relation between any number of possibly
different sets. The context of the discussion should always make
clear which is meant. *)
(** An example relation on [nat] is [le], the less-that-or-equal-to
relation which we usually write like this [n1 <= n2]. *)
Print le.
(* ====> Inductive le (n : nat) : nat -> Prop :=
le_n : n <= n
| le_S : forall m : nat, n <= m -> n <= S m *)
Check le : nat -> nat -> Prop.
Check le : relation nat.
(* ######################################################### *)
(** * Basic Properties of Relations *)
(** As anyone knows who has taken an undergraduate discrete math
course, there is a lot to be said about relations in general --
ways of classifying relations (are they reflexive, transitive,
etc.), theorems that can be proved generically about classes of
relations, constructions that build one relation from another,
etc. For example... *)
(** A relation [R] on a set [X] is a _partial function_ if, for every
[x], there is at most one [y] such that [R x y] -- i.e., if [R x
y1] and [R x y2] together imply [y1 = y2]. *)
Definition partial_function {X: Type} (R: relation X) :=
forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.
(** For example, the [next_nat] relation defined earlier is a partial
function. *)
Print next_nat.
(* ====> Inductive next_nat (n : nat) : nat -> Prop :=
nn : next_nat n (S n) *)
Check next_nat : relation nat.
Theorem next_nat_partial_function :
partial_function next_nat.
Proof.
unfold partial_function.
intros x y1 y2 H1 H2.
inversion H1. inversion H2.
reflexivity. Qed.
(** However, the [<=] relation on numbers is not a partial function.
In short: Assume, for a contradiction, that [<=] is a partial
function. But then, since [0 <= 0] and [0 <= 1], it follows that
[0 = 1]. This is nonsense, so our assumption was
contradictory. *)
Theorem le_not_a_partial_function :
~ (partial_function le).
Proof.
unfold not. unfold partial_function. intros Hc.
assert (0 = 1) as Nonsense.
Case "Proof of assertion".
apply Hc with (x := 0).
apply le_n.
apply le_S. apply le_n.
inversion Nonsense. Qed.
(** **** Exercise: 2 stars, optional *)
(** Show that the [total_relation] defined in earlier is not a partial
function. *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional *)
(** Show that the [empty_relation] defined earlier is a partial
function. *)
(* FILL IN HERE *)
(** [] *)
(** A _reflexive_ relation on a set [X] is one for which every element
of [X] is related to itself. *)
Definition reflexive {X: Type} (R: relation X) :=
forall a : X, R a a.
Theorem le_reflexive :
reflexive le.
Proof.
unfold reflexive. intros n. apply le_n. Qed.
(** A relation [R] is _transitive_ if [R a c] holds whenever [R a b]
and [R b c] do. *)
Definition transitive {X: Type} (R: relation X) :=
forall a b c : X, (R a b) -> (R b c) -> (R a c).
Theorem le_trans :
transitive le.
Proof.
intros n m o Hnm Hmo.
induction Hmo.
Case "le_n". apply Hnm.
Case "le_S". apply le_S. apply IHHmo. Qed.
Theorem lt_trans:
transitive lt.
Proof.
unfold lt. unfold transitive.
intros n m o Hnm Hmo.
apply le_S in Hnm.
apply le_trans with (a := (S n)) (b := (S m)) (c := o).
apply Hnm.
apply Hmo. Qed.
(** **** Exercise: 2 stars, optional *)
(** We can also prove [lt_trans] more laboriously by induction,
without using le_trans. Do this.*)
Theorem lt_trans' :
transitive lt.
Proof.
(* Prove this by induction on evidence that [m] is less than [o]. *)
unfold lt. unfold transitive.
intros n m o Hnm Hmo.
induction Hmo as [| m' Hm'o].
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
(** Prove the same thing again by induction on [o]. *)
Theorem lt_trans'' :
transitive lt.
Proof.
unfold lt. unfold transitive.
intros n m o Hnm Hmo.
induction o as [| o'].
(* FILL IN HERE *) Admitted.
(** [] *)
(** The transitivity of [le], in turn, can be used to prove some facts
that will be useful later (e.g., for the proof of antisymmetry
below)... *)
Theorem le_Sn_le : forall n m, S n <= m -> n <= m.
Proof.
intros n m H. apply le_trans with (S n).
apply le_S. apply le_n.
apply H. Qed.
(** **** Exercise: 1 star, optional *)
Theorem le_S_n : forall n m,
(S n <= S m) -> (n <= m).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional (le_Sn_n_inf) *)
(** Provide an informal proof of the following theorem:
Theorem: For every [n], [~(S n <= n)]
A formal proof of this is an optional exercise below, but try
the informal proof without doing the formal proof first.
Proof:
(* FILL IN HERE *)
[]
*)
(** **** Exercise: 1 star, optional *)
Theorem le_Sn_n : forall n,
~ (S n <= n).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Reflexivity and transitivity are the main concepts we'll need for
later chapters, but, for a bit of additional practice working with
relations in Coq, here are a few more common ones.
A relation [R] is _symmetric_ if [R a b] implies [R b a]. *)
Definition symmetric {X: Type} (R: relation X) :=
forall a b : X, (R a b) -> (R b a).
(** **** Exercise: 2 stars, optional *)
Theorem le_not_symmetric :
~ (symmetric le).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** A relation [R] is _antisymmetric_ if [R a b] and [R b a] together
imply [a = b] -- that is, if the only "cycles" in [R] are trivial
ones. *)
Definition antisymmetric {X: Type} (R: relation X) :=
forall a b : X, (R a b) -> (R b a) -> a = b.
(** **** Exercise: 2 stars, optional *)
Theorem le_antisymmetric :
antisymmetric le.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
Theorem le_step : forall n m p,
n < m ->
m <= S p ->
n <= p.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** A relation is an _equivalence_ if it's reflexive, symmetric, and
transitive. *)
Definition equivalence {X:Type} (R: relation X) :=
(reflexive R) /\ (symmetric R) /\ (transitive R).
(** A relation is a _partial order_ when it's reflexive,
_anti_-symmetric, and transitive. In the Coq standard library
it's called just "order" for short. *)
Definition order {X:Type} (R: relation X) :=
(reflexive R) /\ (antisymmetric R) /\ (transitive R).
(** A preorder is almost like a partial order, but doesn't have to be
antisymmetric. *)
Definition preorder {X:Type} (R: relation X) :=
(reflexive R) /\ (transitive R).
Theorem le_order :
order le.
Proof.
unfold order. split.
Case "refl". apply le_reflexive.
split.
Case "antisym". apply le_antisymmetric.
Case "transitive.". apply le_trans. Qed.
(* ########################################################### *)
(** * Reflexive, Transitive Closure *)
(** The _reflexive, transitive closure_ of a relation [R] is the
smallest relation that contains [R] and that is both reflexive and
transitive. Formally, it is defined like this in the Relations
module of the Coq standard library: *)
Inductive clos_refl_trans {A: Type} (R: relation A) : relation A :=
| rt_step : forall x y, R x y -> clos_refl_trans R x y
| rt_refl : forall x, clos_refl_trans R x x
| rt_trans : forall x y z,
clos_refl_trans R x y ->
clos_refl_trans R y z ->
clos_refl_trans R x z.
(** For example, the reflexive and transitive closure of the
[next_nat] relation coincides with the [le] relation. *)
Theorem next_nat_closure_is_le : forall n m,
(n <= m) <-> ((clos_refl_trans next_nat) n m).
Proof.
intros n m. split.
Case "->".
intro H. induction H.
SCase "le_n". apply rt_refl.
SCase "le_S".
apply rt_trans with m. apply IHle. apply rt_step. apply nn.
Case "<-".
intro H. induction H.
SCase "rt_step". inversion H. apply le_S. apply le_n.
SCase "rt_refl". apply le_n.
SCase "rt_trans".
apply le_trans with y.
apply IHclos_refl_trans1.
apply IHclos_refl_trans2. Qed.
(** The above definition of reflexive, transitive closure is
natural -- it says, explicitly, that the reflexive and transitive
closure of [R] is the least relation that includes [R] and that is
closed under rules of reflexivity and transitivity. But it turns
out that this definition is not very convenient for doing
proofs -- the "nondeterminism" of the [rt_trans] rule can sometimes
lead to tricky inductions.
Here is a more useful definition... *)
Inductive refl_step_closure {X:Type} (R: relation X) : relation X :=
| rsc_refl : forall (x : X), refl_step_closure R x x
| rsc_step : forall (x y z : X),
R x y ->
refl_step_closure R y z ->
refl_step_closure R x z.
(** (Note that, aside from the naming of the constructors, this
definition is the same as the [multi] step relation used in many
other chapters.) *)
(** (The following [Tactic Notation] definitions are explained in
another chapter. You can ignore them if you haven't read the
explanation yet.) *)
Tactic Notation "rt_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "rt_step" | Case_aux c "rt_refl"
| Case_aux c "rt_trans" ].
Tactic Notation "rsc_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "rsc_refl" | Case_aux c "rsc_step" ].
(** Our new definition of reflexive, transitive closure "bundles"
the [rt_step] and [rt_trans] rules into the single rule step.
The left-hand premise of this step is a single use of [R],
leading to a much simpler induction principle.
Before we go on, we should check that the two definitions do
indeed define the same relation...
First, we prove two lemmas showing that [refl_step_closure] mimics
the behavior of the two "missing" [clos_refl_trans]
constructors. *)
Theorem rsc_R : forall (X:Type) (R:relation X) (x y : X),
R x y -> refl_step_closure R x y.
Proof.
intros X R x y H.
apply rsc_step with y. apply H. apply rsc_refl. Qed.
(** **** Exercise: 2 stars, optional (rsc_trans) *)
Theorem rsc_trans :
forall (X:Type) (R: relation X) (x y z : X),
refl_step_closure R x y ->
refl_step_closure R y z ->
refl_step_closure R x z.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Then we use these facts to prove that the two definitions of
reflexive, transitive closure do indeed define the same
relation. *)
(** **** Exercise: 3 stars, optional (rtc_rsc_coincide) *)
Theorem rtc_rsc_coincide :
forall (X:Type) (R: relation X) (x y : X),
clos_refl_trans R x y <-> refl_step_closure R x y.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** $Date: 2014-12-31 15:31:47 -0500 (Wed, 31 Dec 2014) $ *)
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 21:39:39 06/01/2009
// Design Name:
// Module Name: tx_engine
// Project Name: Sora
// Target Devices: Virtex5 LX50T
// Tool versions: ISE10.1.03
// Description:
// Purpose: Non-Posted Packet Builder module. This module takes the
// length info from the Non-Posted Packet Slicer, and requests a tag from
// the Tag Generator and uses that info to build a non-posted memory read
// header which it writes into a FIFO
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// modified by zjs:
// tag content modified: from {length[9:0], addr[21:0]} to {isDes, 8'h000, addr[21:0]}
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module non_posted_pkt_builder(
input clk,
input rst,
input [15:0] req_id, //from pcie block
//to/from the non_posted_pkt_slicer
input go,
output reg ack,
input [63:0] dmaras,
input [31:0] dmarad,
input [9:0] length,
/// Jiansong: added for TX des request
input isDes,
//to/from the tag_generator
input [7:0] tag_value,
input tag_gnt,
output reg tag_inc,
//to the non_posted_pkt_header_fifo
output reg [63:0] header_data_out,
output reg header_data_wren,
//to the read_request_wrapper
output reg [4:0] tx_waddr,
output reg [31:0] tx_wdata,
output reg tx_we
);
//State machine states
localparam IDLE = 4'h0;
localparam HEAD1 = 4'h1;
localparam HEAD2 = 4'h2;
localparam WAIT_FOR_GO_DEASSERT = 4'h3;
//parameters used to define fixed header fields
localparam rsvd = 1'b0; //reserved and unused header fields to zero
localparam MRd = 5'b00000; //format for memory read header
localparam TC = 3'b000; //traffic class 0
localparam TD = 1'b0; //digest bit always 0
localparam EP = 1'b0; //poisoned bit always 0
//localparam ATTR = 2'b10;//enable relaxed ordering to allow completions to pass
//for completion streaming mode
localparam ATTR = 2'b00; //Jiansong: Maybe it's the cause of CPU memory read lock problem
localparam LastBE = 4'b1111; //LastBE is always asserted since all transfers
//are on 128B boundaries and are always at least
//128B long
localparam FirstBE = 4'b1111;//FirstBE is always asserted since all transfers
//are on 128B boundaries
wire [1:0] fmt;
reg [3:0] state;
reg [63:0] dmaras_reg;
reg [31:0] dmarad_reg;
reg rst_reg;
always@(posedge clk) rst_reg <= rst;
//if the upper DWord of the destination address is zero
//than make the format of the packet header 3DW; otherwise 4DW
assign fmt[1:0] = (dmaras_reg[63:32] == 0) ? 2'b00 : 2'b01;
//if the non_posted_pkt_slicer asserts "go" then register the dma read params
always@(posedge clk)begin
if(rst_reg)begin
dmaras_reg[63:0] <= 0;
end else if(go)begin
dmaras_reg <= dmaras;
end
end
//dmarad is sent to the read_request_wrapper so that the RX engine knows
//where to put the incoming completion data in the DDR2
always@(posedge clk)begin
if(rst_reg)begin
dmarad_reg[31:0] <= 0;
end else if(go)begin
dmarad_reg <= dmarad;
end
end
// State machine
// Builds headers for non-posted memory reads
// Writes them into a FIFO
always @ (posedge clk) begin
if (rst_reg) begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
state <= IDLE;
end else begin
case (state)
IDLE : begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
if(go)
state<= HEAD1;
else
state<= IDLE;
end
HEAD1 : begin
//wait for the tag_generator to grant a tag via tag_gnt and then
//write the first 64-bits of a non-posted header into the
//non-posted fifo
header_data_out <= {rsvd,fmt[1:0],MRd,rsvd,TC,rsvd,rsvd,rsvd,rsvd,
TD,EP,ATTR,rsvd,rsvd,length[9:0],req_id[15:0],
tag_value[7:0],LastBE,FirstBE};
ack <= 0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
if(tag_gnt == 1'b0)begin
state <= HEAD1;
header_data_wren <= 1'b0;
end else begin
header_data_wren <= 1'b1;
state <= HEAD2;
end
end
HEAD2 : begin
//write the next 32 or 64 bits of a non-posted header to the
//non-posted header fifo (32 if 3DW - 64 if 4DW header)
header_data_out <= (fmt[0]==1'b1)
? {dmaras_reg[63:2],2'b00}
: {dmaras_reg[31:2], 2'b00, dmaras_reg[63:32]};
header_data_wren <= 1'b1;
//also write needed information by the RX engine into the
//Read Request Wrapper
tx_waddr[4:0] <= tag_value[4:0];
//// tx_wdata[31:0] <= {length[9:0],dmarad_reg[27:6]};
tx_wdata[31:0] <= {isDes,9'b0_0000_0000,dmarad_reg[27:6]};
tx_we <= 1'b1;
ack <= 1'b1; //acknowledge to the non-posted_packet_slicer that
//the packet has been queued up for transmission
tag_inc <=1'b1;//only assert tag_inc once - the tag gets
//incremented for every clock cycle that it is
//asserted
state <= WAIT_FOR_GO_DEASSERT;
end
WAIT_FOR_GO_DEASSERT : begin
//ack causes "go" to deassert but we need to give the
//non-posted_pkt_slicer a chance to deassert "go" before returning
//to IDLE
header_data_wren <= 1'b0;
tx_we <= 1'b0;
tag_inc <=1'b0;
ack <= 1'b0;
state <= IDLE;
end
default : begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
state <= IDLE;
end
endcase
end
end
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 21:39:39 06/01/2009
// Design Name:
// Module Name: tx_engine
// Project Name: Sora
// Target Devices: Virtex5 LX50T
// Tool versions: ISE10.1.03
// Description:
// Purpose: Non-Posted Packet Builder module. This module takes the
// length info from the Non-Posted Packet Slicer, and requests a tag from
// the Tag Generator and uses that info to build a non-posted memory read
// header which it writes into a FIFO
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// modified by zjs:
// tag content modified: from {length[9:0], addr[21:0]} to {isDes, 8'h000, addr[21:0]}
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module non_posted_pkt_builder(
input clk,
input rst,
input [15:0] req_id, //from pcie block
//to/from the non_posted_pkt_slicer
input go,
output reg ack,
input [63:0] dmaras,
input [31:0] dmarad,
input [9:0] length,
/// Jiansong: added for TX des request
input isDes,
//to/from the tag_generator
input [7:0] tag_value,
input tag_gnt,
output reg tag_inc,
//to the non_posted_pkt_header_fifo
output reg [63:0] header_data_out,
output reg header_data_wren,
//to the read_request_wrapper
output reg [4:0] tx_waddr,
output reg [31:0] tx_wdata,
output reg tx_we
);
//State machine states
localparam IDLE = 4'h0;
localparam HEAD1 = 4'h1;
localparam HEAD2 = 4'h2;
localparam WAIT_FOR_GO_DEASSERT = 4'h3;
//parameters used to define fixed header fields
localparam rsvd = 1'b0; //reserved and unused header fields to zero
localparam MRd = 5'b00000; //format for memory read header
localparam TC = 3'b000; //traffic class 0
localparam TD = 1'b0; //digest bit always 0
localparam EP = 1'b0; //poisoned bit always 0
//localparam ATTR = 2'b10;//enable relaxed ordering to allow completions to pass
//for completion streaming mode
localparam ATTR = 2'b00; //Jiansong: Maybe it's the cause of CPU memory read lock problem
localparam LastBE = 4'b1111; //LastBE is always asserted since all transfers
//are on 128B boundaries and are always at least
//128B long
localparam FirstBE = 4'b1111;//FirstBE is always asserted since all transfers
//are on 128B boundaries
wire [1:0] fmt;
reg [3:0] state;
reg [63:0] dmaras_reg;
reg [31:0] dmarad_reg;
reg rst_reg;
always@(posedge clk) rst_reg <= rst;
//if the upper DWord of the destination address is zero
//than make the format of the packet header 3DW; otherwise 4DW
assign fmt[1:0] = (dmaras_reg[63:32] == 0) ? 2'b00 : 2'b01;
//if the non_posted_pkt_slicer asserts "go" then register the dma read params
always@(posedge clk)begin
if(rst_reg)begin
dmaras_reg[63:0] <= 0;
end else if(go)begin
dmaras_reg <= dmaras;
end
end
//dmarad is sent to the read_request_wrapper so that the RX engine knows
//where to put the incoming completion data in the DDR2
always@(posedge clk)begin
if(rst_reg)begin
dmarad_reg[31:0] <= 0;
end else if(go)begin
dmarad_reg <= dmarad;
end
end
// State machine
// Builds headers for non-posted memory reads
// Writes them into a FIFO
always @ (posedge clk) begin
if (rst_reg) begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
state <= IDLE;
end else begin
case (state)
IDLE : begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
if(go)
state<= HEAD1;
else
state<= IDLE;
end
HEAD1 : begin
//wait for the tag_generator to grant a tag via tag_gnt and then
//write the first 64-bits of a non-posted header into the
//non-posted fifo
header_data_out <= {rsvd,fmt[1:0],MRd,rsvd,TC,rsvd,rsvd,rsvd,rsvd,
TD,EP,ATTR,rsvd,rsvd,length[9:0],req_id[15:0],
tag_value[7:0],LastBE,FirstBE};
ack <= 0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
if(tag_gnt == 1'b0)begin
state <= HEAD1;
header_data_wren <= 1'b0;
end else begin
header_data_wren <= 1'b1;
state <= HEAD2;
end
end
HEAD2 : begin
//write the next 32 or 64 bits of a non-posted header to the
//non-posted header fifo (32 if 3DW - 64 if 4DW header)
header_data_out <= (fmt[0]==1'b1)
? {dmaras_reg[63:2],2'b00}
: {dmaras_reg[31:2], 2'b00, dmaras_reg[63:32]};
header_data_wren <= 1'b1;
//also write needed information by the RX engine into the
//Read Request Wrapper
tx_waddr[4:0] <= tag_value[4:0];
//// tx_wdata[31:0] <= {length[9:0],dmarad_reg[27:6]};
tx_wdata[31:0] <= {isDes,9'b0_0000_0000,dmarad_reg[27:6]};
tx_we <= 1'b1;
ack <= 1'b1; //acknowledge to the non-posted_packet_slicer that
//the packet has been queued up for transmission
tag_inc <=1'b1;//only assert tag_inc once - the tag gets
//incremented for every clock cycle that it is
//asserted
state <= WAIT_FOR_GO_DEASSERT;
end
WAIT_FOR_GO_DEASSERT : begin
//ack causes "go" to deassert but we need to give the
//non-posted_pkt_slicer a chance to deassert "go" before returning
//to IDLE
header_data_wren <= 1'b0;
tx_we <= 1'b0;
tag_inc <=1'b0;
ack <= 1'b0;
state <= IDLE;
end
default : begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
state <= IDLE;
end
endcase
end
end
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 21:39:39 06/01/2009
// Design Name:
// Module Name: tx_engine
// Project Name: Sora
// Target Devices: Virtex5 LX50T
// Tool versions: ISE10.1.03
// Description:
// Purpose: Non-Posted Packet Builder module. This module takes the
// length info from the Non-Posted Packet Slicer, and requests a tag from
// the Tag Generator and uses that info to build a non-posted memory read
// header which it writes into a FIFO
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// modified by zjs:
// tag content modified: from {length[9:0], addr[21:0]} to {isDes, 8'h000, addr[21:0]}
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module non_posted_pkt_builder(
input clk,
input rst,
input [15:0] req_id, //from pcie block
//to/from the non_posted_pkt_slicer
input go,
output reg ack,
input [63:0] dmaras,
input [31:0] dmarad,
input [9:0] length,
/// Jiansong: added for TX des request
input isDes,
//to/from the tag_generator
input [7:0] tag_value,
input tag_gnt,
output reg tag_inc,
//to the non_posted_pkt_header_fifo
output reg [63:0] header_data_out,
output reg header_data_wren,
//to the read_request_wrapper
output reg [4:0] tx_waddr,
output reg [31:0] tx_wdata,
output reg tx_we
);
//State machine states
localparam IDLE = 4'h0;
localparam HEAD1 = 4'h1;
localparam HEAD2 = 4'h2;
localparam WAIT_FOR_GO_DEASSERT = 4'h3;
//parameters used to define fixed header fields
localparam rsvd = 1'b0; //reserved and unused header fields to zero
localparam MRd = 5'b00000; //format for memory read header
localparam TC = 3'b000; //traffic class 0
localparam TD = 1'b0; //digest bit always 0
localparam EP = 1'b0; //poisoned bit always 0
//localparam ATTR = 2'b10;//enable relaxed ordering to allow completions to pass
//for completion streaming mode
localparam ATTR = 2'b00; //Jiansong: Maybe it's the cause of CPU memory read lock problem
localparam LastBE = 4'b1111; //LastBE is always asserted since all transfers
//are on 128B boundaries and are always at least
//128B long
localparam FirstBE = 4'b1111;//FirstBE is always asserted since all transfers
//are on 128B boundaries
wire [1:0] fmt;
reg [3:0] state;
reg [63:0] dmaras_reg;
reg [31:0] dmarad_reg;
reg rst_reg;
always@(posedge clk) rst_reg <= rst;
//if the upper DWord of the destination address is zero
//than make the format of the packet header 3DW; otherwise 4DW
assign fmt[1:0] = (dmaras_reg[63:32] == 0) ? 2'b00 : 2'b01;
//if the non_posted_pkt_slicer asserts "go" then register the dma read params
always@(posedge clk)begin
if(rst_reg)begin
dmaras_reg[63:0] <= 0;
end else if(go)begin
dmaras_reg <= dmaras;
end
end
//dmarad is sent to the read_request_wrapper so that the RX engine knows
//where to put the incoming completion data in the DDR2
always@(posedge clk)begin
if(rst_reg)begin
dmarad_reg[31:0] <= 0;
end else if(go)begin
dmarad_reg <= dmarad;
end
end
// State machine
// Builds headers for non-posted memory reads
// Writes them into a FIFO
always @ (posedge clk) begin
if (rst_reg) begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
state <= IDLE;
end else begin
case (state)
IDLE : begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
if(go)
state<= HEAD1;
else
state<= IDLE;
end
HEAD1 : begin
//wait for the tag_generator to grant a tag via tag_gnt and then
//write the first 64-bits of a non-posted header into the
//non-posted fifo
header_data_out <= {rsvd,fmt[1:0],MRd,rsvd,TC,rsvd,rsvd,rsvd,rsvd,
TD,EP,ATTR,rsvd,rsvd,length[9:0],req_id[15:0],
tag_value[7:0],LastBE,FirstBE};
ack <= 0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
if(tag_gnt == 1'b0)begin
state <= HEAD1;
header_data_wren <= 1'b0;
end else begin
header_data_wren <= 1'b1;
state <= HEAD2;
end
end
HEAD2 : begin
//write the next 32 or 64 bits of a non-posted header to the
//non-posted header fifo (32 if 3DW - 64 if 4DW header)
header_data_out <= (fmt[0]==1'b1)
? {dmaras_reg[63:2],2'b00}
: {dmaras_reg[31:2], 2'b00, dmaras_reg[63:32]};
header_data_wren <= 1'b1;
//also write needed information by the RX engine into the
//Read Request Wrapper
tx_waddr[4:0] <= tag_value[4:0];
//// tx_wdata[31:0] <= {length[9:0],dmarad_reg[27:6]};
tx_wdata[31:0] <= {isDes,9'b0_0000_0000,dmarad_reg[27:6]};
tx_we <= 1'b1;
ack <= 1'b1; //acknowledge to the non-posted_packet_slicer that
//the packet has been queued up for transmission
tag_inc <=1'b1;//only assert tag_inc once - the tag gets
//incremented for every clock cycle that it is
//asserted
state <= WAIT_FOR_GO_DEASSERT;
end
WAIT_FOR_GO_DEASSERT : begin
//ack causes "go" to deassert but we need to give the
//non-posted_pkt_slicer a chance to deassert "go" before returning
//to IDLE
header_data_wren <= 1'b0;
tx_we <= 1'b0;
tag_inc <=1'b0;
ack <= 1'b0;
state <= IDLE;
end
default : begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
tag_inc <=1'b0;
tx_waddr[4:0] <= 0;
tx_wdata[31:0] <= 0;
tx_we <= 1'b0;
state <= IDLE;
end
endcase
end
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 11:39:13 09/04/2015
// Design Name:
// Module Name: First_Phase_M
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module First_Phase_M
//SINGLE PRECISION PARAMETERS
# (parameter W = 32)
//DOUBLE PRECISION PARAMETERS
/*# (parameter W = 64) */
(
input wire clk, //system clock
input wire rst, //module reset
input wire load, //load signal
input wire [W-1:0] Data_MX, //Data X and Y are the operands
input wire [W-1:0] Data_MY,
output wire [W-1:0] Op_MX, //Both Op signals are the outputs
output wire [W-1:0] Op_MY
);
//Module's Body
//Both registers could be set with the parameter signal
//to be 32 or 64 bitwidth
RegisterMult #(.W(W)) XMRegister ( //Data X input register
.clk(clk),
.rst(rst),
.load(load),
.D(Data_MX),
.Q(Op_MX)
);
RegisterMult #(.W(W)) YMRegister ( //Data Y input register
.clk(clk),
.rst(rst),
.load(load),
.D(Data_MY),
.Q(Op_MY)
);
endmodule
|
(** * Stlc: The Simply Typed Lambda-Calculus *)
Require Export Types.
(* ###################################################################### *)
(** * The Simply Typed Lambda-Calculus *)
(** The simply typed lambda-calculus (STLC) is a tiny core calculus
embodying the key concept of _functional abstraction_, which shows
up in pretty much every real-world programming language in some
form (functions, procedures, methods, etc.).
We will follow exactly the same pattern as in the previous
chapter when formalizing this calculus (syntax, small-step
semantics, typing rules) and its main properties (progress and
preservation). The new technical challenges (which will take some
work to deal with) all arise from the mechanisms of _variable
binding_ and _substitution_. *)
(* ###################################################################### *)
(** ** Overview *)
(** The STLC is built on some collection of _base types_ -- booleans,
numbers, strings, etc. The exact choice of base types doesn't
matter -- the construction of the language and its theoretical
properties work out pretty much the same -- so for the sake of
brevity let's take just [Bool] for the moment. At the end of the
chapter we'll see how to add more base types, and in later
chapters we'll enrich the pure STLC with other useful constructs
like pairs, records, subtyping, and mutable state.
Starting from the booleans, we add three things:
- variables
- function abstractions
- application
This gives us the following collection of abstract syntax
constructors (written out here in informal BNF notation -- we'll
formalize it below).
*)
(** Informal concrete syntax:
t ::= x variable
| \x:T1.t2 abstraction
| t1 t2 application
| true constant true
| false constant false
| if t1 then t2 else t3 conditional
*)
(** The [\] symbol (backslash, in ascii) in a function abstraction
[\x:T1.t2] is generally written as a greek letter "lambda" (hence
the name of the calculus). The variable [x] is called the
_parameter_ to the function; the term [t2] is its _body_. The
annotation [:T] specifies the type of arguments that the function
can be applied to. *)
(** Some examples:
- [\x:Bool. x]
The identity function for booleans.
- [(\x:Bool. x) true]
The identity function for booleans, applied to the boolean [true].
- [\x:Bool. if x then false else true]
The boolean "not" function.
- [\x:Bool. true]
The constant function that takes every (boolean) argument to
[true]. *)
(**
- [\x:Bool. \y:Bool. x]
A two-argument function that takes two booleans and returns
the first one. (Note that, as in Coq, a two-argument function
is really a one-argument function whose body is also a
one-argument function.)
- [(\x:Bool. \y:Bool. x) false true]
A two-argument function that takes two booleans and returns
the first one, applied to the booleans [false] and [true].
Note that, as in Coq, application associates to the left --
i.e., this expression is parsed as [((\x:Bool. \y:Bool. x)
false) true].
- [\f:Bool->Bool. f (f true)]
A higher-order function that takes a _function_ [f] (from
booleans to booleans) as an argument, applies [f] to [true],
and applies [f] again to the result.
- [(\f:Bool->Bool. f (f true)) (\x:Bool. false)]
The same higher-order function, applied to the constantly
[false] function. *)
(** As the last several examples show, the STLC is a language of
_higher-order_ functions: we can write down functions that take
other functions as arguments and/or return other functions as
results.
Another point to note is that the STLC doesn't provide any
primitive syntax for defining _named_ functions -- all functions
are "anonymous." We'll see in chapter [MoreStlc] that it is easy
to add named functions to what we've got -- indeed, the
fundamental naming and binding mechanisms are exactly the same.
The _types_ of the STLC include [Bool], which classifies the
boolean constants [true] and [false] as well as more complex
computations that yield booleans, plus _arrow types_ that classify
functions. *)
(**
T ::= Bool
| T1 -> T2
For example:
- [\x:Bool. false] has type [Bool->Bool]
- [\x:Bool. x] has type [Bool->Bool]
- [(\x:Bool. x) true] has type [Bool]
- [\x:Bool. \y:Bool. x] has type [Bool->Bool->Bool] (i.e. [Bool -> (Bool->Bool)])
- [(\x:Bool. \y:Bool. x) false] has type [Bool->Bool]
- [(\x:Bool. \y:Bool. x) false true] has type [Bool]
*)
(* ###################################################################### *)
(** ** Syntax *)
Module STLC.
(* ################################### *)
(** *** Types *)
Inductive ty : Type :=
| TBool : ty
| TArrow : ty -> ty -> ty.
(* ################################### *)
(** *** Terms *)
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif" ].
(** Note that an abstraction [\x:T.t] (formally, [tabs x T t]) is
always annotated with the type [T] of its parameter, in contrast
to Coq (and other functional languages like ML, Haskell, etc.),
which use _type inference_ to fill in missing annotations. We're
not considering type inference here, to keep things simple. *)
(** Some examples... *)
Definition x := (Id 0).
Definition y := (Id 1).
Definition z := (Id 2).
Hint Unfold x.
Hint Unfold y.
Hint Unfold z.
(** [idB = \x:Bool. x] *)
Notation idB :=
(tabs x TBool (tvar x)).
(** [idBB = \x:Bool->Bool. x] *)
Notation idBB :=
(tabs x (TArrow TBool TBool) (tvar x)).
(** [idBBBB = \x:(Bool->Bool) -> (Bool->Bool). x] *)
Notation idBBBB :=
(tabs x (TArrow (TArrow TBool TBool)
(TArrow TBool TBool))
(tvar x)).
(** [k = \x:Bool. \y:Bool. x] *)
Notation k := (tabs x TBool (tabs y TBool (tvar x))).
(** [notB = \x:Bool. if x then false else true] *)
Notation notB := (tabs x TBool (tif (tvar x) tfalse ttrue)).
(** (We write these as [Notation]s rather than [Definition]s to make
things easier for [auto].) *)
(* ###################################################################### *)
(** ** Operational Semantics *)
(** To define the small-step semantics of STLC terms, we begin -- as
always -- by defining the set of values. Next, we define the
critical notions of _free variables_ and _substitution_, which are
used in the reduction rule for application expressions. And
finally we give the small-step relation itself. *)
(* ################################### *)
(** *** Values *)
(** To define the values of the STLC, we have a few cases to consider.
First, for the boolean part of the language, the situation is
clear: [true] and [false] are the only values. An [if]
expression is never a value. *)
(** Second, an application is clearly not a value: It represents a
function being invoked on some argument, which clearly still has
work left to do. *)
(** Third, for abstractions, we have a choice:
- We can say that [\x:T.t1] is a value only when [t1] is a
value -- i.e., only if the function's body has been
reduced (as much as it can be without knowing what argument it
is going to be applied to).
- Or we can say that [\x:T.t1] is always a value, no matter
whether [t1] is one or not -- in other words, we can say that
reduction stops at abstractions.
Coq, in its built-in functional programming langauge, makes the
first choice -- for example,
Eval simpl in (fun x:bool => 3 + 4)
yields [fun x:bool => 7].
Most real-world functional programming languages make the second
choice -- reduction of a function's body only begins when the
function is actually applied to an argument. We also make the
second choice here. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse.
Hint Constructors value.
(** Finally, we must consider what constitutes a _complete_ program.
Intuitively, a "complete" program must not refer to any undefined
variables. We'll see shortly how to define the "free" variables
in a STLC term. A program is "closed", that is, it contains no
free variables.
*)
(** Having made the choice not to reduce under abstractions,
we don't need to worry about whether variables are values, since
we'll always be reducing programs "from the outside in," and that
means the [step] relation will always be working with closed
terms (ones with no free variables). *)
(* ###################################################################### *)
(** *** Substitution *)
(** Now we come to the heart of the STLC: the operation of
substituting one term for a variable in another term.
This operation will be used below to define the operational
semantics of function application, where we will need to
substitute the argument term for the function parameter in the
function's body. For example, we reduce
(\x:Bool. if x then true else x) false
to
if false then true else false
]]
by substituting [false] for the parameter [x] in the body of the
function.
In general, we need to be able to substitute some given
term [s] for occurrences of some variable [x] in another term [t].
In informal discussions, this is usually written [ [x:=s]t ] and
pronounced "substitute [x] with [s] in [t]." *)
(** Here are some examples:
- [[x:=true] (if x then x else false)] yields [if true then true else false]
- [[x:=true] x] yields [true]
- [[x:=true] (if x then x else y)] yields [if true then true else y]
- [[x:=true] y] yields [y]
- [[x:=true] false] yields [false] (vacuous substitution)
- [[x:=true] (\y:Bool. if y then x else false)] yields [\y:Bool. if y then true else false]
- [[x:=true] (\y:Bool. x)] yields [\y:Bool. true]
- [[x:=true] (\y:Bool. y)] yields [\y:Bool. y]
- [[x:=true] (\x:Bool. x)] yields [\x:Bool. x]
The last example is very important: substituting [x] with [true] in
[\x:Bool. x] does _not_ yield [\x:Bool. true]! The reason for
this is that the [x] in the body of [\x:Bool. x] is _bound_ by the
abstraction: it is a new, local name that just happens to be
spelled the same as some global name [x]. *)
(** Here is the definition, informally...
[x:=s]x = s
[x:=s]y = y if x <> y
[x:=s](\x:T11.t12) = \x:T11. t12
[x:=s](\y:T11.t12) = \y:T11. [x:=s]t12 if x <> y
[x:=s](t1 t2) = ([x:=s]t1) ([x:=s]t2)
[x:=s]true = true
[x:=s]false = false
[x:=s](if t1 then t2 else t3) =
if [x:=s]t1 then [x:=s]t2 else [x:=s]t3
]]
*)
(** ... and formally: *)
Reserved Notation "'[' x ':=' s ']' t" (at level 20).
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tabs x' T t1 =>
tabs x' T (if eq_id_dec x x' then t1 else ([x:=s] t1))
| tapp t1 t2 =>
tapp ([x:=s] t1) ([x:=s] t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif ([x:=s] t1) ([x:=s] t2) ([x:=s] t3)
end
where "'[' x ':=' s ']' t" := (subst x s t).
(** _Technical note_: Substitution becomes trickier to define if we
consider the case where [s], the term being substituted for a
variable in some other term, may itself contain free variables.
Since we are only interested here in defining the [step] relation
on closed terms (i.e., terms like [\x:Bool. x], that do not mention
variables are not bound by some enclosing lambda), we can skip
this extra complexity here, but it must be dealt with when
formalizing richer languages. *)
(** *** *)
(** **** Exercise: 3 stars (substi) *)
(** The definition that we gave above uses Coq's [Fixpoint] facility
to define substitution as a _function_. Suppose, instead, we
wanted to define substitution as an inductive _relation_ [substi].
We've begun the definition by providing the [Inductive] header and
one of the constructors; your job is to fill in the rest of the
constructors. *)
Inductive substi (s:tm) (x:id) : tm -> tm -> Prop :=
| s_var1 :
substi s x (tvar x) s
(* FILL IN HERE *)
.
Hint Constructors substi.
Theorem substi_correct : forall s x t t',
[x:=s]t = t' <-> substi s x t t'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ################################### *)
(** *** Reduction *)
(** The small-step reduction relation for STLC now follows the same
pattern as the ones we have seen before. Intuitively, to reduce a
function application, we first reduce its left-hand side until it
becomes a literal function; then we reduce its right-hand
side (the argument) until it is also a value; and finally we
substitute the argument for the bound variable in the body of the
function. This last rule, written informally as
(\x:T.t12) v2 ==> [x:=v2]t12
is traditionally called "beta-reduction". *)
(**
value v2
---------------------------- (ST_AppAbs)
(\x:T.t12) v2 ==> [x:=v2]t12
t1 ==> t1'
---------------- (ST_App1)
t1 t2 ==> t1' t2
value v1
t2 ==> t2'
---------------- (ST_App2)
v1 t2 ==> v1 t2'
*)
(** ... plus the usual rules for booleans:
-------------------------------- (ST_IfTrue)
(if true then t1 else t2) ==> t1
--------------------------------- (ST_IfFalse)
(if false then t1 else t2) ==> t2
t1 ==> t1'
---------------------------------------------------- (ST_If)
(if t1 then t2 else t3) ==> (if t1' then t2 else t3)
*)
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
tapp t1 t2 ==> tapp t1' t2
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
tapp v1 t2 ==> tapp v1 t2'
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ].
Hint Constructors step.
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
(* ##################################### *)
(* ##################################### *)
(** *** Examples *)
(** Example:
((\x:Bool->Bool. x) (\x:Bool. x)) ==>* (\x:Bool. x)
i.e.
(idBB idB) ==>* idB
*)
Lemma step_example1 :
(tapp idBB idB) ==>* idB.
Proof.
eapply multi_step.
apply ST_AppAbs.
apply v_abs.
simpl.
apply multi_refl. Qed.
(** Example:
((\x:Bool->Bool. x) ((\x:Bool->Bool. x) (\x:Bool. x)))
==>* (\x:Bool. x)
i.e.
(idBB (idBB idB)) ==>* idB.
*)
Lemma step_example2 :
(tapp idBB (tapp idBB idB)) ==>* idB.
Proof.
eapply multi_step.
apply ST_App2. auto.
apply ST_AppAbs. auto.
eapply multi_step.
apply ST_AppAbs. simpl. auto.
simpl. apply multi_refl. Qed.
(** Example:
((\x:Bool->Bool. x) (\x:Bool. if x then false
else true)) true)
==>* false
i.e.
((idBB notB) ttrue) ==>* tfalse.
*)
Lemma step_example3 :
tapp (tapp idBB notB) ttrue ==>* tfalse.
Proof.
eapply multi_step.
apply ST_App1. apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_IfTrue. apply multi_refl. Qed.
(** Example:
((\x:Bool -> Bool. x) ((\x:Bool. if x then false
else true) true))
==>* false
i.e.
(idBB (notB ttrue)) ==>* tfalse.
*)
Lemma step_example4 :
tapp idBB (tapp notB ttrue) ==>* tfalse.
Proof.
eapply multi_step.
apply ST_App2. auto.
apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_App2. auto.
apply ST_IfTrue.
eapply multi_step.
apply ST_AppAbs. auto. simpl.
apply multi_refl. Qed.
(** A more automatic proof *)
Lemma step_example1' :
(tapp idBB idB) ==>* idB.
Proof. normalize. Qed.
(** Again, we can use the [normalize] tactic from above to simplify
the proof. *)
Lemma step_example2' :
(tapp idBB (tapp idBB idB)) ==>* idB.
Proof.
normalize.
Qed.
Lemma step_example3' :
tapp (tapp idBB notB) ttrue ==>* tfalse.
Proof. normalize. Qed.
Lemma step_example4' :
tapp idBB (tapp notB ttrue) ==>* tfalse.
Proof. normalize. Qed.
(** **** Exercise: 2 stars (step_example3) *)
(** Try to do this one both with and without [normalize]. *)
Lemma step_example5 :
(tapp (tapp idBBBB idBB) idB)
==>* idB.
Proof.
(* FILL IN HERE *) Admitted.
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** ** Typing *)
(* ################################### *)
(** *** Contexts *)
(** _Question_: What is the type of the term "[x y]"?
_Answer_: It depends on the types of [x] and [y]!
I.e., in order to assign a type to a term, we need to know
what assumptions we should make about the types of its free
variables.
This leads us to a three-place "typing judgment", informally
written [Gamma |- t \in T], where [Gamma] is a
"typing context" -- a mapping from variables to their types. *)
(** We hide the definition of partial maps in a module since it is
actually defined in [SfLib]. *)
Module PartialMap.
Definition partial_map (A:Type) := id -> option A.
Definition empty {A:Type} : partial_map A := (fun _ => None).
(** Informally, we'll write [Gamma, x:T] for "extend the partial
function [Gamma] to also map [x] to [T]." Formally, we use the
function [extend] to add a binding to a partial map. *)
Definition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Lemma extend_eq : forall A (ctxt: partial_map A) x T,
(extend ctxt x T) x = Some T.
Proof.
intros. unfold extend. rewrite eq_id. auto.
Qed.
Lemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,
x2 <> x1 ->
(extend ctxt x2 T) x1 = ctxt x1.
Proof.
intros. unfold extend. rewrite neq_id; auto.
Qed.
End PartialMap.
Definition context := partial_map ty.
(* ################################### *)
(** *** Typing Relation *)
(**
Gamma x = T
-------------- (T_Var)
Gamma |- x \in T
Gamma , x:T11 |- t12 \in T12
---------------------------- (T_Abs)
Gamma |- \x:T11.t12 \in T11->T12
Gamma |- t1 \in T11->T12
Gamma |- t2 \in T11
---------------------- (T_App)
Gamma |- t1 t2 \in T12
-------------------- (T_True)
Gamma |- true \in Bool
--------------------- (T_False)
Gamma |- false \in Bool
Gamma |- t1 \in Bool Gamma |- t2 \in T Gamma |- t3 \in T
-------------------------------------------------------- (T_If)
Gamma |- if t1 then t2 else t3 \in T
We can read the three-place relation [Gamma |- t \in T] as:
"to the term [t] we can assign the type [T] using as types for
the free variables of [t] the ones specified in the context
[Gamma]." *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- tvar x \in T
| T_Abs : forall Gamma x T11 T12 t12,
extend Gamma x T11 |- t12 \in T12 ->
Gamma |- tabs x T11 t12 \in TArrow T11 T12
| T_App : forall T11 T12 Gamma t1 t2,
Gamma |- t1 \in TArrow T11 T12 ->
Gamma |- t2 \in T11 ->
Gamma |- tapp t1 t2 \in T12
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- tif t1 t2 t3 \in T
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If" ].
Hint Constructors has_type.
(* ################################### *)
(** *** Examples *)
Example typing_example_1 :
empty |- tabs x TBool (tvar x) \in TArrow TBool TBool.
Proof.
apply T_Abs. apply T_Var. reflexivity. Qed.
(** Note that since we added the [has_type] constructors to the hints
database, auto can actually solve this one immediately. *)
Example typing_example_1' :
empty |- tabs x TBool (tvar x) \in TArrow TBool TBool.
Proof. auto. Qed.
(** Another example:
empty |- \x:A. \y:A->A. y (y x))
\in A -> (A->A) -> A.
*)
Example typing_example_2 :
empty |-
(tabs x TBool
(tabs y (TArrow TBool TBool)
(tapp (tvar y) (tapp (tvar y) (tvar x))))) \in
(TArrow TBool (TArrow (TArrow TBool TBool) TBool)).
Proof with auto using extend_eq.
apply T_Abs.
apply T_Abs.
eapply T_App. apply T_Var...
eapply T_App. apply T_Var...
apply T_Var...
Qed.
(** **** Exercise: 2 stars, optional (typing_example_2_full) *)
(** Prove the same result without using [auto], [eauto], or
[eapply]. *)
Example typing_example_2_full :
empty |-
(tabs x TBool
(tabs y (TArrow TBool TBool)
(tapp (tvar y) (tapp (tvar y) (tvar x))))) \in
(TArrow TBool (TArrow (TArrow TBool TBool) TBool)).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars (typing_example_3) *)
(** Formally prove the following typing derivation holds: *)
(**
empty |- \x:Bool->B. \y:Bool->Bool. \z:Bool.
y (x z)
\in T.
*)
Example typing_example_3 :
exists T,
empty |-
(tabs x (TArrow TBool TBool)
(tabs y (TArrow TBool TBool)
(tabs z TBool
(tapp (tvar y) (tapp (tvar x) (tvar z)))))) \in
T.
Proof with auto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** We can also show that terms are _not_ typable. For example, let's
formally check that there is no typing derivation assigning a type
to the term [\x:Bool. \y:Bool, x y] -- i.e.,
~ exists T,
empty |- \x:Bool. \y:Bool, x y : T.
*)
Example typing_nonexample_1 :
~ exists T,
empty |-
(tabs x TBool
(tabs y TBool
(tapp (tvar x) (tvar y)))) \in
T.
Proof.
intros Hc. inversion Hc.
(* The [clear] tactic is useful here for tidying away bits of
the context that we're not going to need again. *)
inversion H. subst. clear H.
inversion H5. subst. clear H5.
inversion H4. subst. clear H4.
inversion H2. subst. clear H2.
inversion H5. subst. clear H5.
(* rewrite extend_neq in H1. rewrite extend_eq in H1. *)
inversion H1. Qed.
(** **** Exercise: 3 stars, optional (typing_nonexample_3) *)
(** Another nonexample:
~ (exists S, exists T,
empty |- \x:S. x x : T).
*)
Example typing_nonexample_3 :
~ (exists S, exists T,
empty |-
(tabs x S
(tapp (tvar x) (tvar x))) \in
T).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
End STLC.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Stlc: The Simply Typed Lambda-Calculus *)
Require Export Types.
(* ###################################################################### *)
(** * The Simply Typed Lambda-Calculus *)
(** The simply typed lambda-calculus (STLC) is a tiny core calculus
embodying the key concept of _functional abstraction_, which shows
up in pretty much every real-world programming language in some
form (functions, procedures, methods, etc.).
We will follow exactly the same pattern as in the previous
chapter when formalizing this calculus (syntax, small-step
semantics, typing rules) and its main properties (progress and
preservation). The new technical challenges (which will take some
work to deal with) all arise from the mechanisms of _variable
binding_ and _substitution_. *)
(* ###################################################################### *)
(** ** Overview *)
(** The STLC is built on some collection of _base types_ -- booleans,
numbers, strings, etc. The exact choice of base types doesn't
matter -- the construction of the language and its theoretical
properties work out pretty much the same -- so for the sake of
brevity let's take just [Bool] for the moment. At the end of the
chapter we'll see how to add more base types, and in later
chapters we'll enrich the pure STLC with other useful constructs
like pairs, records, subtyping, and mutable state.
Starting from the booleans, we add three things:
- variables
- function abstractions
- application
This gives us the following collection of abstract syntax
constructors (written out here in informal BNF notation -- we'll
formalize it below).
*)
(** Informal concrete syntax:
t ::= x variable
| \x:T1.t2 abstraction
| t1 t2 application
| true constant true
| false constant false
| if t1 then t2 else t3 conditional
*)
(** The [\] symbol (backslash, in ascii) in a function abstraction
[\x:T1.t2] is generally written as a greek letter "lambda" (hence
the name of the calculus). The variable [x] is called the
_parameter_ to the function; the term [t2] is its _body_. The
annotation [:T] specifies the type of arguments that the function
can be applied to. *)
(** Some examples:
- [\x:Bool. x]
The identity function for booleans.
- [(\x:Bool. x) true]
The identity function for booleans, applied to the boolean [true].
- [\x:Bool. if x then false else true]
The boolean "not" function.
- [\x:Bool. true]
The constant function that takes every (boolean) argument to
[true]. *)
(**
- [\x:Bool. \y:Bool. x]
A two-argument function that takes two booleans and returns
the first one. (Note that, as in Coq, a two-argument function
is really a one-argument function whose body is also a
one-argument function.)
- [(\x:Bool. \y:Bool. x) false true]
A two-argument function that takes two booleans and returns
the first one, applied to the booleans [false] and [true].
Note that, as in Coq, application associates to the left --
i.e., this expression is parsed as [((\x:Bool. \y:Bool. x)
false) true].
- [\f:Bool->Bool. f (f true)]
A higher-order function that takes a _function_ [f] (from
booleans to booleans) as an argument, applies [f] to [true],
and applies [f] again to the result.
- [(\f:Bool->Bool. f (f true)) (\x:Bool. false)]
The same higher-order function, applied to the constantly
[false] function. *)
(** As the last several examples show, the STLC is a language of
_higher-order_ functions: we can write down functions that take
other functions as arguments and/or return other functions as
results.
Another point to note is that the STLC doesn't provide any
primitive syntax for defining _named_ functions -- all functions
are "anonymous." We'll see in chapter [MoreStlc] that it is easy
to add named functions to what we've got -- indeed, the
fundamental naming and binding mechanisms are exactly the same.
The _types_ of the STLC include [Bool], which classifies the
boolean constants [true] and [false] as well as more complex
computations that yield booleans, plus _arrow types_ that classify
functions. *)
(**
T ::= Bool
| T1 -> T2
For example:
- [\x:Bool. false] has type [Bool->Bool]
- [\x:Bool. x] has type [Bool->Bool]
- [(\x:Bool. x) true] has type [Bool]
- [\x:Bool. \y:Bool. x] has type [Bool->Bool->Bool] (i.e. [Bool -> (Bool->Bool)])
- [(\x:Bool. \y:Bool. x) false] has type [Bool->Bool]
- [(\x:Bool. \y:Bool. x) false true] has type [Bool]
*)
(* ###################################################################### *)
(** ** Syntax *)
Module STLC.
(* ################################### *)
(** *** Types *)
Inductive ty : Type :=
| TBool : ty
| TArrow : ty -> ty -> ty.
(* ################################### *)
(** *** Terms *)
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif" ].
(** Note that an abstraction [\x:T.t] (formally, [tabs x T t]) is
always annotated with the type [T] of its parameter, in contrast
to Coq (and other functional languages like ML, Haskell, etc.),
which use _type inference_ to fill in missing annotations. We're
not considering type inference here, to keep things simple. *)
(** Some examples... *)
Definition x := (Id 0).
Definition y := (Id 1).
Definition z := (Id 2).
Hint Unfold x.
Hint Unfold y.
Hint Unfold z.
(** [idB = \x:Bool. x] *)
Notation idB :=
(tabs x TBool (tvar x)).
(** [idBB = \x:Bool->Bool. x] *)
Notation idBB :=
(tabs x (TArrow TBool TBool) (tvar x)).
(** [idBBBB = \x:(Bool->Bool) -> (Bool->Bool). x] *)
Notation idBBBB :=
(tabs x (TArrow (TArrow TBool TBool)
(TArrow TBool TBool))
(tvar x)).
(** [k = \x:Bool. \y:Bool. x] *)
Notation k := (tabs x TBool (tabs y TBool (tvar x))).
(** [notB = \x:Bool. if x then false else true] *)
Notation notB := (tabs x TBool (tif (tvar x) tfalse ttrue)).
(** (We write these as [Notation]s rather than [Definition]s to make
things easier for [auto].) *)
(* ###################################################################### *)
(** ** Operational Semantics *)
(** To define the small-step semantics of STLC terms, we begin -- as
always -- by defining the set of values. Next, we define the
critical notions of _free variables_ and _substitution_, which are
used in the reduction rule for application expressions. And
finally we give the small-step relation itself. *)
(* ################################### *)
(** *** Values *)
(** To define the values of the STLC, we have a few cases to consider.
First, for the boolean part of the language, the situation is
clear: [true] and [false] are the only values. An [if]
expression is never a value. *)
(** Second, an application is clearly not a value: It represents a
function being invoked on some argument, which clearly still has
work left to do. *)
(** Third, for abstractions, we have a choice:
- We can say that [\x:T.t1] is a value only when [t1] is a
value -- i.e., only if the function's body has been
reduced (as much as it can be without knowing what argument it
is going to be applied to).
- Or we can say that [\x:T.t1] is always a value, no matter
whether [t1] is one or not -- in other words, we can say that
reduction stops at abstractions.
Coq, in its built-in functional programming langauge, makes the
first choice -- for example,
Eval simpl in (fun x:bool => 3 + 4)
yields [fun x:bool => 7].
Most real-world functional programming languages make the second
choice -- reduction of a function's body only begins when the
function is actually applied to an argument. We also make the
second choice here. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse.
Hint Constructors value.
(** Finally, we must consider what constitutes a _complete_ program.
Intuitively, a "complete" program must not refer to any undefined
variables. We'll see shortly how to define the "free" variables
in a STLC term. A program is "closed", that is, it contains no
free variables.
*)
(** Having made the choice not to reduce under abstractions,
we don't need to worry about whether variables are values, since
we'll always be reducing programs "from the outside in," and that
means the [step] relation will always be working with closed
terms (ones with no free variables). *)
(* ###################################################################### *)
(** *** Substitution *)
(** Now we come to the heart of the STLC: the operation of
substituting one term for a variable in another term.
This operation will be used below to define the operational
semantics of function application, where we will need to
substitute the argument term for the function parameter in the
function's body. For example, we reduce
(\x:Bool. if x then true else x) false
to
if false then true else false
]]
by substituting [false] for the parameter [x] in the body of the
function.
In general, we need to be able to substitute some given
term [s] for occurrences of some variable [x] in another term [t].
In informal discussions, this is usually written [ [x:=s]t ] and
pronounced "substitute [x] with [s] in [t]." *)
(** Here are some examples:
- [[x:=true] (if x then x else false)] yields [if true then true else false]
- [[x:=true] x] yields [true]
- [[x:=true] (if x then x else y)] yields [if true then true else y]
- [[x:=true] y] yields [y]
- [[x:=true] false] yields [false] (vacuous substitution)
- [[x:=true] (\y:Bool. if y then x else false)] yields [\y:Bool. if y then true else false]
- [[x:=true] (\y:Bool. x)] yields [\y:Bool. true]
- [[x:=true] (\y:Bool. y)] yields [\y:Bool. y]
- [[x:=true] (\x:Bool. x)] yields [\x:Bool. x]
The last example is very important: substituting [x] with [true] in
[\x:Bool. x] does _not_ yield [\x:Bool. true]! The reason for
this is that the [x] in the body of [\x:Bool. x] is _bound_ by the
abstraction: it is a new, local name that just happens to be
spelled the same as some global name [x]. *)
(** Here is the definition, informally...
[x:=s]x = s
[x:=s]y = y if x <> y
[x:=s](\x:T11.t12) = \x:T11. t12
[x:=s](\y:T11.t12) = \y:T11. [x:=s]t12 if x <> y
[x:=s](t1 t2) = ([x:=s]t1) ([x:=s]t2)
[x:=s]true = true
[x:=s]false = false
[x:=s](if t1 then t2 else t3) =
if [x:=s]t1 then [x:=s]t2 else [x:=s]t3
]]
*)
(** ... and formally: *)
Reserved Notation "'[' x ':=' s ']' t" (at level 20).
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tabs x' T t1 =>
tabs x' T (if eq_id_dec x x' then t1 else ([x:=s] t1))
| tapp t1 t2 =>
tapp ([x:=s] t1) ([x:=s] t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif ([x:=s] t1) ([x:=s] t2) ([x:=s] t3)
end
where "'[' x ':=' s ']' t" := (subst x s t).
(** _Technical note_: Substitution becomes trickier to define if we
consider the case where [s], the term being substituted for a
variable in some other term, may itself contain free variables.
Since we are only interested here in defining the [step] relation
on closed terms (i.e., terms like [\x:Bool. x], that do not mention
variables are not bound by some enclosing lambda), we can skip
this extra complexity here, but it must be dealt with when
formalizing richer languages. *)
(** *** *)
(** **** Exercise: 3 stars (substi) *)
(** The definition that we gave above uses Coq's [Fixpoint] facility
to define substitution as a _function_. Suppose, instead, we
wanted to define substitution as an inductive _relation_ [substi].
We've begun the definition by providing the [Inductive] header and
one of the constructors; your job is to fill in the rest of the
constructors. *)
Inductive substi (s:tm) (x:id) : tm -> tm -> Prop :=
| s_var1 :
substi s x (tvar x) s
(* FILL IN HERE *)
.
Hint Constructors substi.
Theorem substi_correct : forall s x t t',
[x:=s]t = t' <-> substi s x t t'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ################################### *)
(** *** Reduction *)
(** The small-step reduction relation for STLC now follows the same
pattern as the ones we have seen before. Intuitively, to reduce a
function application, we first reduce its left-hand side until it
becomes a literal function; then we reduce its right-hand
side (the argument) until it is also a value; and finally we
substitute the argument for the bound variable in the body of the
function. This last rule, written informally as
(\x:T.t12) v2 ==> [x:=v2]t12
is traditionally called "beta-reduction". *)
(**
value v2
---------------------------- (ST_AppAbs)
(\x:T.t12) v2 ==> [x:=v2]t12
t1 ==> t1'
---------------- (ST_App1)
t1 t2 ==> t1' t2
value v1
t2 ==> t2'
---------------- (ST_App2)
v1 t2 ==> v1 t2'
*)
(** ... plus the usual rules for booleans:
-------------------------------- (ST_IfTrue)
(if true then t1 else t2) ==> t1
--------------------------------- (ST_IfFalse)
(if false then t1 else t2) ==> t2
t1 ==> t1'
---------------------------------------------------- (ST_If)
(if t1 then t2 else t3) ==> (if t1' then t2 else t3)
*)
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
tapp t1 t2 ==> tapp t1' t2
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
tapp v1 t2 ==> tapp v1 t2'
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ].
Hint Constructors step.
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
(* ##################################### *)
(* ##################################### *)
(** *** Examples *)
(** Example:
((\x:Bool->Bool. x) (\x:Bool. x)) ==>* (\x:Bool. x)
i.e.
(idBB idB) ==>* idB
*)
Lemma step_example1 :
(tapp idBB idB) ==>* idB.
Proof.
eapply multi_step.
apply ST_AppAbs.
apply v_abs.
simpl.
apply multi_refl. Qed.
(** Example:
((\x:Bool->Bool. x) ((\x:Bool->Bool. x) (\x:Bool. x)))
==>* (\x:Bool. x)
i.e.
(idBB (idBB idB)) ==>* idB.
*)
Lemma step_example2 :
(tapp idBB (tapp idBB idB)) ==>* idB.
Proof.
eapply multi_step.
apply ST_App2. auto.
apply ST_AppAbs. auto.
eapply multi_step.
apply ST_AppAbs. simpl. auto.
simpl. apply multi_refl. Qed.
(** Example:
((\x:Bool->Bool. x) (\x:Bool. if x then false
else true)) true)
==>* false
i.e.
((idBB notB) ttrue) ==>* tfalse.
*)
Lemma step_example3 :
tapp (tapp idBB notB) ttrue ==>* tfalse.
Proof.
eapply multi_step.
apply ST_App1. apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_IfTrue. apply multi_refl. Qed.
(** Example:
((\x:Bool -> Bool. x) ((\x:Bool. if x then false
else true) true))
==>* false
i.e.
(idBB (notB ttrue)) ==>* tfalse.
*)
Lemma step_example4 :
tapp idBB (tapp notB ttrue) ==>* tfalse.
Proof.
eapply multi_step.
apply ST_App2. auto.
apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_App2. auto.
apply ST_IfTrue.
eapply multi_step.
apply ST_AppAbs. auto. simpl.
apply multi_refl. Qed.
(** A more automatic proof *)
Lemma step_example1' :
(tapp idBB idB) ==>* idB.
Proof. normalize. Qed.
(** Again, we can use the [normalize] tactic from above to simplify
the proof. *)
Lemma step_example2' :
(tapp idBB (tapp idBB idB)) ==>* idB.
Proof.
normalize.
Qed.
Lemma step_example3' :
tapp (tapp idBB notB) ttrue ==>* tfalse.
Proof. normalize. Qed.
Lemma step_example4' :
tapp idBB (tapp notB ttrue) ==>* tfalse.
Proof. normalize. Qed.
(** **** Exercise: 2 stars (step_example3) *)
(** Try to do this one both with and without [normalize]. *)
Lemma step_example5 :
(tapp (tapp idBBBB idBB) idB)
==>* idB.
Proof.
(* FILL IN HERE *) Admitted.
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** ** Typing *)
(* ################################### *)
(** *** Contexts *)
(** _Question_: What is the type of the term "[x y]"?
_Answer_: It depends on the types of [x] and [y]!
I.e., in order to assign a type to a term, we need to know
what assumptions we should make about the types of its free
variables.
This leads us to a three-place "typing judgment", informally
written [Gamma |- t \in T], where [Gamma] is a
"typing context" -- a mapping from variables to their types. *)
(** We hide the definition of partial maps in a module since it is
actually defined in [SfLib]. *)
Module PartialMap.
Definition partial_map (A:Type) := id -> option A.
Definition empty {A:Type} : partial_map A := (fun _ => None).
(** Informally, we'll write [Gamma, x:T] for "extend the partial
function [Gamma] to also map [x] to [T]." Formally, we use the
function [extend] to add a binding to a partial map. *)
Definition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Lemma extend_eq : forall A (ctxt: partial_map A) x T,
(extend ctxt x T) x = Some T.
Proof.
intros. unfold extend. rewrite eq_id. auto.
Qed.
Lemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,
x2 <> x1 ->
(extend ctxt x2 T) x1 = ctxt x1.
Proof.
intros. unfold extend. rewrite neq_id; auto.
Qed.
End PartialMap.
Definition context := partial_map ty.
(* ################################### *)
(** *** Typing Relation *)
(**
Gamma x = T
-------------- (T_Var)
Gamma |- x \in T
Gamma , x:T11 |- t12 \in T12
---------------------------- (T_Abs)
Gamma |- \x:T11.t12 \in T11->T12
Gamma |- t1 \in T11->T12
Gamma |- t2 \in T11
---------------------- (T_App)
Gamma |- t1 t2 \in T12
-------------------- (T_True)
Gamma |- true \in Bool
--------------------- (T_False)
Gamma |- false \in Bool
Gamma |- t1 \in Bool Gamma |- t2 \in T Gamma |- t3 \in T
-------------------------------------------------------- (T_If)
Gamma |- if t1 then t2 else t3 \in T
We can read the three-place relation [Gamma |- t \in T] as:
"to the term [t] we can assign the type [T] using as types for
the free variables of [t] the ones specified in the context
[Gamma]." *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- tvar x \in T
| T_Abs : forall Gamma x T11 T12 t12,
extend Gamma x T11 |- t12 \in T12 ->
Gamma |- tabs x T11 t12 \in TArrow T11 T12
| T_App : forall T11 T12 Gamma t1 t2,
Gamma |- t1 \in TArrow T11 T12 ->
Gamma |- t2 \in T11 ->
Gamma |- tapp t1 t2 \in T12
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- tif t1 t2 t3 \in T
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If" ].
Hint Constructors has_type.
(* ################################### *)
(** *** Examples *)
Example typing_example_1 :
empty |- tabs x TBool (tvar x) \in TArrow TBool TBool.
Proof.
apply T_Abs. apply T_Var. reflexivity. Qed.
(** Note that since we added the [has_type] constructors to the hints
database, auto can actually solve this one immediately. *)
Example typing_example_1' :
empty |- tabs x TBool (tvar x) \in TArrow TBool TBool.
Proof. auto. Qed.
(** Another example:
empty |- \x:A. \y:A->A. y (y x))
\in A -> (A->A) -> A.
*)
Example typing_example_2 :
empty |-
(tabs x TBool
(tabs y (TArrow TBool TBool)
(tapp (tvar y) (tapp (tvar y) (tvar x))))) \in
(TArrow TBool (TArrow (TArrow TBool TBool) TBool)).
Proof with auto using extend_eq.
apply T_Abs.
apply T_Abs.
eapply T_App. apply T_Var...
eapply T_App. apply T_Var...
apply T_Var...
Qed.
(** **** Exercise: 2 stars, optional (typing_example_2_full) *)
(** Prove the same result without using [auto], [eauto], or
[eapply]. *)
Example typing_example_2_full :
empty |-
(tabs x TBool
(tabs y (TArrow TBool TBool)
(tapp (tvar y) (tapp (tvar y) (tvar x))))) \in
(TArrow TBool (TArrow (TArrow TBool TBool) TBool)).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars (typing_example_3) *)
(** Formally prove the following typing derivation holds: *)
(**
empty |- \x:Bool->B. \y:Bool->Bool. \z:Bool.
y (x z)
\in T.
*)
Example typing_example_3 :
exists T,
empty |-
(tabs x (TArrow TBool TBool)
(tabs y (TArrow TBool TBool)
(tabs z TBool
(tapp (tvar y) (tapp (tvar x) (tvar z)))))) \in
T.
Proof with auto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** We can also show that terms are _not_ typable. For example, let's
formally check that there is no typing derivation assigning a type
to the term [\x:Bool. \y:Bool, x y] -- i.e.,
~ exists T,
empty |- \x:Bool. \y:Bool, x y : T.
*)
Example typing_nonexample_1 :
~ exists T,
empty |-
(tabs x TBool
(tabs y TBool
(tapp (tvar x) (tvar y)))) \in
T.
Proof.
intros Hc. inversion Hc.
(* The [clear] tactic is useful here for tidying away bits of
the context that we're not going to need again. *)
inversion H. subst. clear H.
inversion H5. subst. clear H5.
inversion H4. subst. clear H4.
inversion H2. subst. clear H2.
inversion H5. subst. clear H5.
(* rewrite extend_neq in H1. rewrite extend_eq in H1. *)
inversion H1. Qed.
(** **** Exercise: 3 stars, optional (typing_nonexample_3) *)
(** Another nonexample:
~ (exists S, exists T,
empty |- \x:S. x x : T).
*)
Example typing_nonexample_3 :
~ (exists S, exists T,
empty |-
(tabs x S
(tapp (tvar x) (tvar x))) \in
T).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
End STLC.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Stlc: The Simply Typed Lambda-Calculus *)
Require Export Types.
(* ###################################################################### *)
(** * The Simply Typed Lambda-Calculus *)
(** The simply typed lambda-calculus (STLC) is a tiny core calculus
embodying the key concept of _functional abstraction_, which shows
up in pretty much every real-world programming language in some
form (functions, procedures, methods, etc.).
We will follow exactly the same pattern as in the previous
chapter when formalizing this calculus (syntax, small-step
semantics, typing rules) and its main properties (progress and
preservation). The new technical challenges (which will take some
work to deal with) all arise from the mechanisms of _variable
binding_ and _substitution_. *)
(* ###################################################################### *)
(** ** Overview *)
(** The STLC is built on some collection of _base types_ -- booleans,
numbers, strings, etc. The exact choice of base types doesn't
matter -- the construction of the language and its theoretical
properties work out pretty much the same -- so for the sake of
brevity let's take just [Bool] for the moment. At the end of the
chapter we'll see how to add more base types, and in later
chapters we'll enrich the pure STLC with other useful constructs
like pairs, records, subtyping, and mutable state.
Starting from the booleans, we add three things:
- variables
- function abstractions
- application
This gives us the following collection of abstract syntax
constructors (written out here in informal BNF notation -- we'll
formalize it below).
*)
(** Informal concrete syntax:
t ::= x variable
| \x:T1.t2 abstraction
| t1 t2 application
| true constant true
| false constant false
| if t1 then t2 else t3 conditional
*)
(** The [\] symbol (backslash, in ascii) in a function abstraction
[\x:T1.t2] is generally written as a greek letter "lambda" (hence
the name of the calculus). The variable [x] is called the
_parameter_ to the function; the term [t2] is its _body_. The
annotation [:T] specifies the type of arguments that the function
can be applied to. *)
(** Some examples:
- [\x:Bool. x]
The identity function for booleans.
- [(\x:Bool. x) true]
The identity function for booleans, applied to the boolean [true].
- [\x:Bool. if x then false else true]
The boolean "not" function.
- [\x:Bool. true]
The constant function that takes every (boolean) argument to
[true]. *)
(**
- [\x:Bool. \y:Bool. x]
A two-argument function that takes two booleans and returns
the first one. (Note that, as in Coq, a two-argument function
is really a one-argument function whose body is also a
one-argument function.)
- [(\x:Bool. \y:Bool. x) false true]
A two-argument function that takes two booleans and returns
the first one, applied to the booleans [false] and [true].
Note that, as in Coq, application associates to the left --
i.e., this expression is parsed as [((\x:Bool. \y:Bool. x)
false) true].
- [\f:Bool->Bool. f (f true)]
A higher-order function that takes a _function_ [f] (from
booleans to booleans) as an argument, applies [f] to [true],
and applies [f] again to the result.
- [(\f:Bool->Bool. f (f true)) (\x:Bool. false)]
The same higher-order function, applied to the constantly
[false] function. *)
(** As the last several examples show, the STLC is a language of
_higher-order_ functions: we can write down functions that take
other functions as arguments and/or return other functions as
results.
Another point to note is that the STLC doesn't provide any
primitive syntax for defining _named_ functions -- all functions
are "anonymous." We'll see in chapter [MoreStlc] that it is easy
to add named functions to what we've got -- indeed, the
fundamental naming and binding mechanisms are exactly the same.
The _types_ of the STLC include [Bool], which classifies the
boolean constants [true] and [false] as well as more complex
computations that yield booleans, plus _arrow types_ that classify
functions. *)
(**
T ::= Bool
| T1 -> T2
For example:
- [\x:Bool. false] has type [Bool->Bool]
- [\x:Bool. x] has type [Bool->Bool]
- [(\x:Bool. x) true] has type [Bool]
- [\x:Bool. \y:Bool. x] has type [Bool->Bool->Bool] (i.e. [Bool -> (Bool->Bool)])
- [(\x:Bool. \y:Bool. x) false] has type [Bool->Bool]
- [(\x:Bool. \y:Bool. x) false true] has type [Bool]
*)
(* ###################################################################### *)
(** ** Syntax *)
Module STLC.
(* ################################### *)
(** *** Types *)
Inductive ty : Type :=
| TBool : ty
| TArrow : ty -> ty -> ty.
(* ################################### *)
(** *** Terms *)
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif" ].
(** Note that an abstraction [\x:T.t] (formally, [tabs x T t]) is
always annotated with the type [T] of its parameter, in contrast
to Coq (and other functional languages like ML, Haskell, etc.),
which use _type inference_ to fill in missing annotations. We're
not considering type inference here, to keep things simple. *)
(** Some examples... *)
Definition x := (Id 0).
Definition y := (Id 1).
Definition z := (Id 2).
Hint Unfold x.
Hint Unfold y.
Hint Unfold z.
(** [idB = \x:Bool. x] *)
Notation idB :=
(tabs x TBool (tvar x)).
(** [idBB = \x:Bool->Bool. x] *)
Notation idBB :=
(tabs x (TArrow TBool TBool) (tvar x)).
(** [idBBBB = \x:(Bool->Bool) -> (Bool->Bool). x] *)
Notation idBBBB :=
(tabs x (TArrow (TArrow TBool TBool)
(TArrow TBool TBool))
(tvar x)).
(** [k = \x:Bool. \y:Bool. x] *)
Notation k := (tabs x TBool (tabs y TBool (tvar x))).
(** [notB = \x:Bool. if x then false else true] *)
Notation notB := (tabs x TBool (tif (tvar x) tfalse ttrue)).
(** (We write these as [Notation]s rather than [Definition]s to make
things easier for [auto].) *)
(* ###################################################################### *)
(** ** Operational Semantics *)
(** To define the small-step semantics of STLC terms, we begin -- as
always -- by defining the set of values. Next, we define the
critical notions of _free variables_ and _substitution_, which are
used in the reduction rule for application expressions. And
finally we give the small-step relation itself. *)
(* ################################### *)
(** *** Values *)
(** To define the values of the STLC, we have a few cases to consider.
First, for the boolean part of the language, the situation is
clear: [true] and [false] are the only values. An [if]
expression is never a value. *)
(** Second, an application is clearly not a value: It represents a
function being invoked on some argument, which clearly still has
work left to do. *)
(** Third, for abstractions, we have a choice:
- We can say that [\x:T.t1] is a value only when [t1] is a
value -- i.e., only if the function's body has been
reduced (as much as it can be without knowing what argument it
is going to be applied to).
- Or we can say that [\x:T.t1] is always a value, no matter
whether [t1] is one or not -- in other words, we can say that
reduction stops at abstractions.
Coq, in its built-in functional programming langauge, makes the
first choice -- for example,
Eval simpl in (fun x:bool => 3 + 4)
yields [fun x:bool => 7].
Most real-world functional programming languages make the second
choice -- reduction of a function's body only begins when the
function is actually applied to an argument. We also make the
second choice here. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse.
Hint Constructors value.
(** Finally, we must consider what constitutes a _complete_ program.
Intuitively, a "complete" program must not refer to any undefined
variables. We'll see shortly how to define the "free" variables
in a STLC term. A program is "closed", that is, it contains no
free variables.
*)
(** Having made the choice not to reduce under abstractions,
we don't need to worry about whether variables are values, since
we'll always be reducing programs "from the outside in," and that
means the [step] relation will always be working with closed
terms (ones with no free variables). *)
(* ###################################################################### *)
(** *** Substitution *)
(** Now we come to the heart of the STLC: the operation of
substituting one term for a variable in another term.
This operation will be used below to define the operational
semantics of function application, where we will need to
substitute the argument term for the function parameter in the
function's body. For example, we reduce
(\x:Bool. if x then true else x) false
to
if false then true else false
]]
by substituting [false] for the parameter [x] in the body of the
function.
In general, we need to be able to substitute some given
term [s] for occurrences of some variable [x] in another term [t].
In informal discussions, this is usually written [ [x:=s]t ] and
pronounced "substitute [x] with [s] in [t]." *)
(** Here are some examples:
- [[x:=true] (if x then x else false)] yields [if true then true else false]
- [[x:=true] x] yields [true]
- [[x:=true] (if x then x else y)] yields [if true then true else y]
- [[x:=true] y] yields [y]
- [[x:=true] false] yields [false] (vacuous substitution)
- [[x:=true] (\y:Bool. if y then x else false)] yields [\y:Bool. if y then true else false]
- [[x:=true] (\y:Bool. x)] yields [\y:Bool. true]
- [[x:=true] (\y:Bool. y)] yields [\y:Bool. y]
- [[x:=true] (\x:Bool. x)] yields [\x:Bool. x]
The last example is very important: substituting [x] with [true] in
[\x:Bool. x] does _not_ yield [\x:Bool. true]! The reason for
this is that the [x] in the body of [\x:Bool. x] is _bound_ by the
abstraction: it is a new, local name that just happens to be
spelled the same as some global name [x]. *)
(** Here is the definition, informally...
[x:=s]x = s
[x:=s]y = y if x <> y
[x:=s](\x:T11.t12) = \x:T11. t12
[x:=s](\y:T11.t12) = \y:T11. [x:=s]t12 if x <> y
[x:=s](t1 t2) = ([x:=s]t1) ([x:=s]t2)
[x:=s]true = true
[x:=s]false = false
[x:=s](if t1 then t2 else t3) =
if [x:=s]t1 then [x:=s]t2 else [x:=s]t3
]]
*)
(** ... and formally: *)
Reserved Notation "'[' x ':=' s ']' t" (at level 20).
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tabs x' T t1 =>
tabs x' T (if eq_id_dec x x' then t1 else ([x:=s] t1))
| tapp t1 t2 =>
tapp ([x:=s] t1) ([x:=s] t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif ([x:=s] t1) ([x:=s] t2) ([x:=s] t3)
end
where "'[' x ':=' s ']' t" := (subst x s t).
(** _Technical note_: Substitution becomes trickier to define if we
consider the case where [s], the term being substituted for a
variable in some other term, may itself contain free variables.
Since we are only interested here in defining the [step] relation
on closed terms (i.e., terms like [\x:Bool. x], that do not mention
variables are not bound by some enclosing lambda), we can skip
this extra complexity here, but it must be dealt with when
formalizing richer languages. *)
(** *** *)
(** **** Exercise: 3 stars (substi) *)
(** The definition that we gave above uses Coq's [Fixpoint] facility
to define substitution as a _function_. Suppose, instead, we
wanted to define substitution as an inductive _relation_ [substi].
We've begun the definition by providing the [Inductive] header and
one of the constructors; your job is to fill in the rest of the
constructors. *)
Inductive substi (s:tm) (x:id) : tm -> tm -> Prop :=
| s_var1 :
substi s x (tvar x) s
(* FILL IN HERE *)
.
Hint Constructors substi.
Theorem substi_correct : forall s x t t',
[x:=s]t = t' <-> substi s x t t'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ################################### *)
(** *** Reduction *)
(** The small-step reduction relation for STLC now follows the same
pattern as the ones we have seen before. Intuitively, to reduce a
function application, we first reduce its left-hand side until it
becomes a literal function; then we reduce its right-hand
side (the argument) until it is also a value; and finally we
substitute the argument for the bound variable in the body of the
function. This last rule, written informally as
(\x:T.t12) v2 ==> [x:=v2]t12
is traditionally called "beta-reduction". *)
(**
value v2
---------------------------- (ST_AppAbs)
(\x:T.t12) v2 ==> [x:=v2]t12
t1 ==> t1'
---------------- (ST_App1)
t1 t2 ==> t1' t2
value v1
t2 ==> t2'
---------------- (ST_App2)
v1 t2 ==> v1 t2'
*)
(** ... plus the usual rules for booleans:
-------------------------------- (ST_IfTrue)
(if true then t1 else t2) ==> t1
--------------------------------- (ST_IfFalse)
(if false then t1 else t2) ==> t2
t1 ==> t1'
---------------------------------------------------- (ST_If)
(if t1 then t2 else t3) ==> (if t1' then t2 else t3)
*)
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
tapp t1 t2 ==> tapp t1' t2
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
tapp v1 t2 ==> tapp v1 t2'
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ].
Hint Constructors step.
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
(* ##################################### *)
(* ##################################### *)
(** *** Examples *)
(** Example:
((\x:Bool->Bool. x) (\x:Bool. x)) ==>* (\x:Bool. x)
i.e.
(idBB idB) ==>* idB
*)
Lemma step_example1 :
(tapp idBB idB) ==>* idB.
Proof.
eapply multi_step.
apply ST_AppAbs.
apply v_abs.
simpl.
apply multi_refl. Qed.
(** Example:
((\x:Bool->Bool. x) ((\x:Bool->Bool. x) (\x:Bool. x)))
==>* (\x:Bool. x)
i.e.
(idBB (idBB idB)) ==>* idB.
*)
Lemma step_example2 :
(tapp idBB (tapp idBB idB)) ==>* idB.
Proof.
eapply multi_step.
apply ST_App2. auto.
apply ST_AppAbs. auto.
eapply multi_step.
apply ST_AppAbs. simpl. auto.
simpl. apply multi_refl. Qed.
(** Example:
((\x:Bool->Bool. x) (\x:Bool. if x then false
else true)) true)
==>* false
i.e.
((idBB notB) ttrue) ==>* tfalse.
*)
Lemma step_example3 :
tapp (tapp idBB notB) ttrue ==>* tfalse.
Proof.
eapply multi_step.
apply ST_App1. apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_IfTrue. apply multi_refl. Qed.
(** Example:
((\x:Bool -> Bool. x) ((\x:Bool. if x then false
else true) true))
==>* false
i.e.
(idBB (notB ttrue)) ==>* tfalse.
*)
Lemma step_example4 :
tapp idBB (tapp notB ttrue) ==>* tfalse.
Proof.
eapply multi_step.
apply ST_App2. auto.
apply ST_AppAbs. auto. simpl.
eapply multi_step.
apply ST_App2. auto.
apply ST_IfTrue.
eapply multi_step.
apply ST_AppAbs. auto. simpl.
apply multi_refl. Qed.
(** A more automatic proof *)
Lemma step_example1' :
(tapp idBB idB) ==>* idB.
Proof. normalize. Qed.
(** Again, we can use the [normalize] tactic from above to simplify
the proof. *)
Lemma step_example2' :
(tapp idBB (tapp idBB idB)) ==>* idB.
Proof.
normalize.
Qed.
Lemma step_example3' :
tapp (tapp idBB notB) ttrue ==>* tfalse.
Proof. normalize. Qed.
Lemma step_example4' :
tapp idBB (tapp notB ttrue) ==>* tfalse.
Proof. normalize. Qed.
(** **** Exercise: 2 stars (step_example3) *)
(** Try to do this one both with and without [normalize]. *)
Lemma step_example5 :
(tapp (tapp idBBBB idBB) idB)
==>* idB.
Proof.
(* FILL IN HERE *) Admitted.
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** ** Typing *)
(* ################################### *)
(** *** Contexts *)
(** _Question_: What is the type of the term "[x y]"?
_Answer_: It depends on the types of [x] and [y]!
I.e., in order to assign a type to a term, we need to know
what assumptions we should make about the types of its free
variables.
This leads us to a three-place "typing judgment", informally
written [Gamma |- t \in T], where [Gamma] is a
"typing context" -- a mapping from variables to their types. *)
(** We hide the definition of partial maps in a module since it is
actually defined in [SfLib]. *)
Module PartialMap.
Definition partial_map (A:Type) := id -> option A.
Definition empty {A:Type} : partial_map A := (fun _ => None).
(** Informally, we'll write [Gamma, x:T] for "extend the partial
function [Gamma] to also map [x] to [T]." Formally, we use the
function [extend] to add a binding to a partial map. *)
Definition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Lemma extend_eq : forall A (ctxt: partial_map A) x T,
(extend ctxt x T) x = Some T.
Proof.
intros. unfold extend. rewrite eq_id. auto.
Qed.
Lemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,
x2 <> x1 ->
(extend ctxt x2 T) x1 = ctxt x1.
Proof.
intros. unfold extend. rewrite neq_id; auto.
Qed.
End PartialMap.
Definition context := partial_map ty.
(* ################################### *)
(** *** Typing Relation *)
(**
Gamma x = T
-------------- (T_Var)
Gamma |- x \in T
Gamma , x:T11 |- t12 \in T12
---------------------------- (T_Abs)
Gamma |- \x:T11.t12 \in T11->T12
Gamma |- t1 \in T11->T12
Gamma |- t2 \in T11
---------------------- (T_App)
Gamma |- t1 t2 \in T12
-------------------- (T_True)
Gamma |- true \in Bool
--------------------- (T_False)
Gamma |- false \in Bool
Gamma |- t1 \in Bool Gamma |- t2 \in T Gamma |- t3 \in T
-------------------------------------------------------- (T_If)
Gamma |- if t1 then t2 else t3 \in T
We can read the three-place relation [Gamma |- t \in T] as:
"to the term [t] we can assign the type [T] using as types for
the free variables of [t] the ones specified in the context
[Gamma]." *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- tvar x \in T
| T_Abs : forall Gamma x T11 T12 t12,
extend Gamma x T11 |- t12 \in T12 ->
Gamma |- tabs x T11 t12 \in TArrow T11 T12
| T_App : forall T11 T12 Gamma t1 t2,
Gamma |- t1 \in TArrow T11 T12 ->
Gamma |- t2 \in T11 ->
Gamma |- tapp t1 t2 \in T12
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- tif t1 t2 t3 \in T
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If" ].
Hint Constructors has_type.
(* ################################### *)
(** *** Examples *)
Example typing_example_1 :
empty |- tabs x TBool (tvar x) \in TArrow TBool TBool.
Proof.
apply T_Abs. apply T_Var. reflexivity. Qed.
(** Note that since we added the [has_type] constructors to the hints
database, auto can actually solve this one immediately. *)
Example typing_example_1' :
empty |- tabs x TBool (tvar x) \in TArrow TBool TBool.
Proof. auto. Qed.
(** Another example:
empty |- \x:A. \y:A->A. y (y x))
\in A -> (A->A) -> A.
*)
Example typing_example_2 :
empty |-
(tabs x TBool
(tabs y (TArrow TBool TBool)
(tapp (tvar y) (tapp (tvar y) (tvar x))))) \in
(TArrow TBool (TArrow (TArrow TBool TBool) TBool)).
Proof with auto using extend_eq.
apply T_Abs.
apply T_Abs.
eapply T_App. apply T_Var...
eapply T_App. apply T_Var...
apply T_Var...
Qed.
(** **** Exercise: 2 stars, optional (typing_example_2_full) *)
(** Prove the same result without using [auto], [eauto], or
[eapply]. *)
Example typing_example_2_full :
empty |-
(tabs x TBool
(tabs y (TArrow TBool TBool)
(tapp (tvar y) (tapp (tvar y) (tvar x))))) \in
(TArrow TBool (TArrow (TArrow TBool TBool) TBool)).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars (typing_example_3) *)
(** Formally prove the following typing derivation holds: *)
(**
empty |- \x:Bool->B. \y:Bool->Bool. \z:Bool.
y (x z)
\in T.
*)
Example typing_example_3 :
exists T,
empty |-
(tabs x (TArrow TBool TBool)
(tabs y (TArrow TBool TBool)
(tabs z TBool
(tapp (tvar y) (tapp (tvar x) (tvar z)))))) \in
T.
Proof with auto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** We can also show that terms are _not_ typable. For example, let's
formally check that there is no typing derivation assigning a type
to the term [\x:Bool. \y:Bool, x y] -- i.e.,
~ exists T,
empty |- \x:Bool. \y:Bool, x y : T.
*)
Example typing_nonexample_1 :
~ exists T,
empty |-
(tabs x TBool
(tabs y TBool
(tapp (tvar x) (tvar y)))) \in
T.
Proof.
intros Hc. inversion Hc.
(* The [clear] tactic is useful here for tidying away bits of
the context that we're not going to need again. *)
inversion H. subst. clear H.
inversion H5. subst. clear H5.
inversion H4. subst. clear H4.
inversion H2. subst. clear H2.
inversion H5. subst. clear H5.
(* rewrite extend_neq in H1. rewrite extend_eq in H1. *)
inversion H1. Qed.
(** **** Exercise: 3 stars, optional (typing_nonexample_3) *)
(** Another nonexample:
~ (exists S, exists T,
empty |- \x:S. x x : T).
*)
Example typing_nonexample_3 :
~ (exists S, exists T,
empty |-
(tabs x S
(tapp (tvar x) (tvar x))) \in
T).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
End STLC.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 03/29/2016 05:57:16 AM
// Design Name:
// Module Name: Testbench_FPU
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Testbench_FPU_Mark2();
parameter PERIOD = 10;
`ifdef SINGLE
parameter W = 32;
parameter EW = 8;
parameter SW = 23;
parameter SWR = 26;
parameter EWR = 5;//
`endif
`ifdef DOUBLE
parameter W = 64;
parameter EW = 11;
parameter SW = 52;
parameter SWR = 55;
parameter EWR = 6;
`endif
reg clk;
//INPUT signals
reg rst;
reg begin_operation;
reg ack_operation;
reg [2:0] operation;
//Oper_Start_in signals
reg [W-1:0] Data_1;
reg [W-1:0] Data_2;
reg [1:0] region_flag;
//reg add_subt;
//Round signals signals
reg [1:0] r_mode;
reg add_subt;
//OUTPUT SIGNALS
wire overflow_flag;
wire underflow_flag;
wire operation_ready;
wire zero_flag;
wire NaN_flag;
wire [W-1:0] op_result;
wire busy;
// LOS CODIGOS PARA LAS OPERACIONES
localparam [2:0] FPADD = 3'b000,
FPSUB = 3'b001,
FPCOS = 3'b010,
FPSEN = 3'b011,
FPMULT = 3'b100;
// LAS REGIONES DEL ANGULO
localparam [1:0] IoIV1 = 2'b00,
II = 2'b01,
III = 2'b10,
IoIV2 = 2'b11;
localparam [1:0] ROUNDING_MODE_TRUNCT = 2'b00,
ROUNDING_MODE_NEG_INF = 2'b01,
ROUNDING_MODE_POS_INF = 2'b10;
`ifdef FPUv2_behav
FPU_Interface2 #(
.W(W),
.EW(EW),
.SW(SW),
.SWR(SWR),
.EWR(EWR)
) inst_FPU_Interface (
.clk (clk),
.rst (rst),
.begin_operation (begin_operation),
.ack_operation (ack_operation),
.operation (operation),
.region_flag (region_flag),
.Data_1 (Data_1),
.Data_2 (Data_2),
.r_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.NaN_flag (NaN_flag),
.operation_ready (operation_ready),
.op_result (op_result),
.busy (busy)
);
`endif
`ifdef DW1_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef DW1_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA1_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA1_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef FPADD1_SINGLE
integer PIPE=0;
FPU_Add_Subtract_Function_W32_EW8_SW23_SWR26_EWR5 uut(
.clk(clk),
.rst(rst),
.beg_FSM(begin_operation),
.ack_FSM(ack_operation),
.Data_X(Data_1),
.Data_Y(Data_2),
.add_subt(add_subt),
.r_mode(r_mode),
.overflow_flag(overflow_flag),
.underflow_flag(underflow_flag),
.ready(operation_ready),
.final_result_ieee(op_result)
);
`endif
`ifdef FPADD1_DOUBLE
integer PIPE=0;
FPU_Add_Subtract_Function_W64_EW11_SW52_SWR55_EWR6 uut(
.clk(clk),
.rst(rst),
.beg_FSM(begin_operation),
.ack_FSM(ack_operation),
.Data_X(Data_1),
.Data_Y(Data_2),
.add_subt(add_subt),
.r_mode(r_mode),
.overflow_flag(overflow_flag),
.underflow_flag(underflow_flag),
.ready(operation_ready),
.final_result_ieee(op_result)
);
`endif
`ifdef FPADD2_SINGLE
integer PIPE=1;
FPU_PIPELINED_FPADDSUB_W32_EW8_SW23_SWR26_EWR5 inst_uut (
.clk (clk),
.rst (rst),
.beg_OP (begin_operation),
.Data_X (Data_1),
.Data_Y (Data_2),
.add_subt (add_subt),
.busy (busy),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef FPADD2_DOUBLE
integer PIPE=1;
FPU_PIPELINED_FPADDSUB_W64_EW11_SW52_SWR55_EWR6 inst_uut (
.clk (clk),
.rst (rst),
.beg_OP (begin_operation),
.Data_X (Data_1),
.Data_Y (Data_2),
.add_subt (add_subt),
.busy (busy),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef CORDIC1_SINGLE
integer PIPE=0;
CORDIC_Arch2_W32_EW8_SW23_SWR26_EWR5 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.r_mode (r_mode),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.data_output (op_result)
);
`endif
`ifdef CORDIC1_DOUBLE
integer PIPE=0;
CORDIC_Arch2_W64_EW11_SW52_SWR55_EWR6 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.r_mode (r_mode),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.data_output (op_result)
);
`endif
`ifdef CORDIC2_SINGLE
CORDIC_Arch3_W32_EW8_SW23_SWR26_EWR5 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.busy (busy),
.data_output (op_result)
);
`endif
`ifdef CORDIC2_DOUBLE
CORDIC_Arch3_W64_EW11_SW52_SWR55_EWR6 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.busy (busy),
.data_output (op_result)
);
`endif
reg [W-1:0] Array_IN_1 [0:(((2**PERIOD))-1)];
reg [W-1:0] Array_IN_2 [0:(((2**PERIOD))-1)];
integer contador;
integer FileSaveData;
integer FileSaveData_FLOAT;
initial begin
// Initialize Inputs
$vcdpluson;
clk = 0;
rst = 1;
r_mode=ROUNDING_MODE_TRUNCT;
begin_operation = 0;
ack_operation = 0;
Data_1 = 0;
Data_2 = 0;
region_flag = IoIV1;
add_subt =1'b0;
$display("------------------------OP--------------------------");
$display("------------------------ --------------------------");
$display("------------------------OP--------------------------");
#100;
rst = 0;
$readmemh("Hexadecimal_A.txt", Array_IN_1);
$readmemh("Hexadecimal_B.txt", Array_IN_2);
FileSaveData = $fopen("ResultadoXilinxFLMv2.txt","w");
FileSaveData_FLOAT = $fopen("ResultadoXilinxFLMv2F.txt","w");
if (PIPE) begin
run_PIPE(FileSaveData,FileSaveData_FLOAT,(2**PERIOD));
end else begin
run_Arch2(FileSaveData,FileSaveData_FLOAT,(2**PERIOD));
end
#100 rst = 0;
$finish;
$vcdplusclose;
//Add stimulus here
end
//******************************* Se ejecuta el CLK ************************
initial forever #5 clk = ~clk;
task run_Arch2;
input integer FDataO;
input integer FData1;
input integer Vector_size;
begin
begin_operation = 0;
rst = 0;
#15 rst = 1;
#25 rst = 0;
// begin_operation = 0;
ack_operation = 0;
contador = 0;
repeat(Vector_size) @(negedge clk) begin
//input the new values inside the operator
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
#(PERIOD/4) begin_operation = 1;
//Wait for the operation operation_ready
@(posedge operation_ready) begin
#(PERIOD+2);
ack_operation = 1;
#4;
$display("%h\n",op_result);
$fwrite(FDataO,"%h\n",op_result);
$display("%f\n",$bitstoshortreal(op_result));
`ifdef SINGLE
$fwrite(FData1,"%f\n",$bitstoshortreal(op_result));
`else
$fwrite(FData1,"%f\n",$bitstoreal(op_result));
`endif
end
@(negedge clk) begin
ack_operation = 0;
end
contador = contador + 1;
end
$fclose(FDataO);
$fclose(FData1);
end
endtask
////////////////////////////TASK FOR THE PIPE ADDER/////////////////
////We need to read in a non-linear fashion, therefore
// we are going to write first the 3 first input operands,
// then, the normal running operation,
// and then the final procedure.
task run_PIPE;
input integer FData1;
input integer FData2;
input integer Vector_size2;
begin
begin_operation = 0;
rst = 0;
#15 rst = 1;
#25 rst = 0;
//begin_operation = 0;
contador = 0;
@(posedge clk)
begin_operation = 1;
@(posedge clk)
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
contador = contador + 1;
repeat(Vector_size2*2+6) @(posedge clk) begin
#(PERIOD/3);
if(~busy & ~rst) begin
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
contador = contador + 1;
end
if (operation_ready) begin
$fwrite(FData1,"%h\n",op_result);
`ifdef SINGLE
$fwrite(FData2,"%f\n",$bitstoshortreal(op_result));
`else
$fwrite(FData2,"%f\n",$bitstoreal(op_result));
`endif
end
end
begin_operation = 0;
$fclose(FData1);
$fclose(FData2);
end
endtask
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 03/29/2016 05:57:16 AM
// Design Name:
// Module Name: Testbench_FPU
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Testbench_FPU_Mark2();
parameter PERIOD = 10;
`ifdef SINGLE
parameter W = 32;
parameter EW = 8;
parameter SW = 23;
parameter SWR = 26;
parameter EWR = 5;//
`endif
`ifdef DOUBLE
parameter W = 64;
parameter EW = 11;
parameter SW = 52;
parameter SWR = 55;
parameter EWR = 6;
`endif
reg clk;
//INPUT signals
reg rst;
reg begin_operation;
reg ack_operation;
reg [2:0] operation;
//Oper_Start_in signals
reg [W-1:0] Data_1;
reg [W-1:0] Data_2;
reg [1:0] region_flag;
//reg add_subt;
//Round signals signals
reg [1:0] r_mode;
reg add_subt;
//OUTPUT SIGNALS
wire overflow_flag;
wire underflow_flag;
wire operation_ready;
wire zero_flag;
wire NaN_flag;
wire [W-1:0] op_result;
wire busy;
// LOS CODIGOS PARA LAS OPERACIONES
localparam [2:0] FPADD = 3'b000,
FPSUB = 3'b001,
FPCOS = 3'b010,
FPSEN = 3'b011,
FPMULT = 3'b100;
// LAS REGIONES DEL ANGULO
localparam [1:0] IoIV1 = 2'b00,
II = 2'b01,
III = 2'b10,
IoIV2 = 2'b11;
localparam [1:0] ROUNDING_MODE_TRUNCT = 2'b00,
ROUNDING_MODE_NEG_INF = 2'b01,
ROUNDING_MODE_POS_INF = 2'b10;
`ifdef FPUv2_behav
FPU_Interface2 #(
.W(W),
.EW(EW),
.SW(SW),
.SWR(SWR),
.EWR(EWR)
) inst_FPU_Interface (
.clk (clk),
.rst (rst),
.begin_operation (begin_operation),
.ack_operation (ack_operation),
.operation (operation),
.region_flag (region_flag),
.Data_1 (Data_1),
.Data_2 (Data_2),
.r_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.NaN_flag (NaN_flag),
.operation_ready (operation_ready),
.op_result (op_result),
.busy (busy)
);
`endif
`ifdef DW1_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef DW1_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA1_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA1_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef FPADD1_SINGLE
integer PIPE=0;
FPU_Add_Subtract_Function_W32_EW8_SW23_SWR26_EWR5 uut(
.clk(clk),
.rst(rst),
.beg_FSM(begin_operation),
.ack_FSM(ack_operation),
.Data_X(Data_1),
.Data_Y(Data_2),
.add_subt(add_subt),
.r_mode(r_mode),
.overflow_flag(overflow_flag),
.underflow_flag(underflow_flag),
.ready(operation_ready),
.final_result_ieee(op_result)
);
`endif
`ifdef FPADD1_DOUBLE
integer PIPE=0;
FPU_Add_Subtract_Function_W64_EW11_SW52_SWR55_EWR6 uut(
.clk(clk),
.rst(rst),
.beg_FSM(begin_operation),
.ack_FSM(ack_operation),
.Data_X(Data_1),
.Data_Y(Data_2),
.add_subt(add_subt),
.r_mode(r_mode),
.overflow_flag(overflow_flag),
.underflow_flag(underflow_flag),
.ready(operation_ready),
.final_result_ieee(op_result)
);
`endif
`ifdef FPADD2_SINGLE
integer PIPE=1;
FPU_PIPELINED_FPADDSUB_W32_EW8_SW23_SWR26_EWR5 inst_uut (
.clk (clk),
.rst (rst),
.beg_OP (begin_operation),
.Data_X (Data_1),
.Data_Y (Data_2),
.add_subt (add_subt),
.busy (busy),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef FPADD2_DOUBLE
integer PIPE=1;
FPU_PIPELINED_FPADDSUB_W64_EW11_SW52_SWR55_EWR6 inst_uut (
.clk (clk),
.rst (rst),
.beg_OP (begin_operation),
.Data_X (Data_1),
.Data_Y (Data_2),
.add_subt (add_subt),
.busy (busy),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef CORDIC1_SINGLE
integer PIPE=0;
CORDIC_Arch2_W32_EW8_SW23_SWR26_EWR5 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.r_mode (r_mode),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.data_output (op_result)
);
`endif
`ifdef CORDIC1_DOUBLE
integer PIPE=0;
CORDIC_Arch2_W64_EW11_SW52_SWR55_EWR6 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.r_mode (r_mode),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.data_output (op_result)
);
`endif
`ifdef CORDIC2_SINGLE
CORDIC_Arch3_W32_EW8_SW23_SWR26_EWR5 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.busy (busy),
.data_output (op_result)
);
`endif
`ifdef CORDIC2_DOUBLE
CORDIC_Arch3_W64_EW11_SW52_SWR55_EWR6 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.busy (busy),
.data_output (op_result)
);
`endif
reg [W-1:0] Array_IN_1 [0:(((2**PERIOD))-1)];
reg [W-1:0] Array_IN_2 [0:(((2**PERIOD))-1)];
integer contador;
integer FileSaveData;
integer FileSaveData_FLOAT;
initial begin
// Initialize Inputs
$vcdpluson;
clk = 0;
rst = 1;
r_mode=ROUNDING_MODE_TRUNCT;
begin_operation = 0;
ack_operation = 0;
Data_1 = 0;
Data_2 = 0;
region_flag = IoIV1;
add_subt =1'b0;
$display("------------------------OP--------------------------");
$display("------------------------ --------------------------");
$display("------------------------OP--------------------------");
#100;
rst = 0;
$readmemh("Hexadecimal_A.txt", Array_IN_1);
$readmemh("Hexadecimal_B.txt", Array_IN_2);
FileSaveData = $fopen("ResultadoXilinxFLMv2.txt","w");
FileSaveData_FLOAT = $fopen("ResultadoXilinxFLMv2F.txt","w");
if (PIPE) begin
run_PIPE(FileSaveData,FileSaveData_FLOAT,(2**PERIOD));
end else begin
run_Arch2(FileSaveData,FileSaveData_FLOAT,(2**PERIOD));
end
#100 rst = 0;
$finish;
$vcdplusclose;
//Add stimulus here
end
//******************************* Se ejecuta el CLK ************************
initial forever #5 clk = ~clk;
task run_Arch2;
input integer FDataO;
input integer FData1;
input integer Vector_size;
begin
begin_operation = 0;
rst = 0;
#15 rst = 1;
#25 rst = 0;
// begin_operation = 0;
ack_operation = 0;
contador = 0;
repeat(Vector_size) @(negedge clk) begin
//input the new values inside the operator
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
#(PERIOD/4) begin_operation = 1;
//Wait for the operation operation_ready
@(posedge operation_ready) begin
#(PERIOD+2);
ack_operation = 1;
#4;
$display("%h\n",op_result);
$fwrite(FDataO,"%h\n",op_result);
$display("%f\n",$bitstoshortreal(op_result));
`ifdef SINGLE
$fwrite(FData1,"%f\n",$bitstoshortreal(op_result));
`else
$fwrite(FData1,"%f\n",$bitstoreal(op_result));
`endif
end
@(negedge clk) begin
ack_operation = 0;
end
contador = contador + 1;
end
$fclose(FDataO);
$fclose(FData1);
end
endtask
////////////////////////////TASK FOR THE PIPE ADDER/////////////////
////We need to read in a non-linear fashion, therefore
// we are going to write first the 3 first input operands,
// then, the normal running operation,
// and then the final procedure.
task run_PIPE;
input integer FData1;
input integer FData2;
input integer Vector_size2;
begin
begin_operation = 0;
rst = 0;
#15 rst = 1;
#25 rst = 0;
//begin_operation = 0;
contador = 0;
@(posedge clk)
begin_operation = 1;
@(posedge clk)
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
contador = contador + 1;
repeat(Vector_size2*2+6) @(posedge clk) begin
#(PERIOD/3);
if(~busy & ~rst) begin
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
contador = contador + 1;
end
if (operation_ready) begin
$fwrite(FData1,"%h\n",op_result);
`ifdef SINGLE
$fwrite(FData2,"%f\n",$bitstoshortreal(op_result));
`else
$fwrite(FData2,"%f\n",$bitstoreal(op_result));
`endif
end
end
begin_operation = 0;
$fclose(FData1);
$fclose(FData2);
end
endtask
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 03/29/2016 05:57:16 AM
// Design Name:
// Module Name: Testbench_FPU
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Testbench_FPU_Mark2();
parameter PERIOD = 10;
`ifdef SINGLE
parameter W = 32;
parameter EW = 8;
parameter SW = 23;
parameter SWR = 26;
parameter EWR = 5;//
`endif
`ifdef DOUBLE
parameter W = 64;
parameter EW = 11;
parameter SW = 52;
parameter SWR = 55;
parameter EWR = 6;
`endif
reg clk;
//INPUT signals
reg rst;
reg begin_operation;
reg ack_operation;
reg [2:0] operation;
//Oper_Start_in signals
reg [W-1:0] Data_1;
reg [W-1:0] Data_2;
reg [1:0] region_flag;
//reg add_subt;
//Round signals signals
reg [1:0] r_mode;
reg add_subt;
//OUTPUT SIGNALS
wire overflow_flag;
wire underflow_flag;
wire operation_ready;
wire zero_flag;
wire NaN_flag;
wire [W-1:0] op_result;
wire busy;
// LOS CODIGOS PARA LAS OPERACIONES
localparam [2:0] FPADD = 3'b000,
FPSUB = 3'b001,
FPCOS = 3'b010,
FPSEN = 3'b011,
FPMULT = 3'b100;
// LAS REGIONES DEL ANGULO
localparam [1:0] IoIV1 = 2'b00,
II = 2'b01,
III = 2'b10,
IoIV2 = 2'b11;
localparam [1:0] ROUNDING_MODE_TRUNCT = 2'b00,
ROUNDING_MODE_NEG_INF = 2'b01,
ROUNDING_MODE_POS_INF = 2'b10;
`ifdef FPUv2_behav
FPU_Interface2 #(
.W(W),
.EW(EW),
.SW(SW),
.SWR(SWR),
.EWR(EWR)
) inst_FPU_Interface (
.clk (clk),
.rst (rst),
.begin_operation (begin_operation),
.ack_operation (ack_operation),
.operation (operation),
.region_flag (region_flag),
.Data_1 (Data_1),
.Data_2 (Data_2),
.r_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.NaN_flag (NaN_flag),
.operation_ready (operation_ready),
.op_result (op_result),
.busy (busy)
);
`endif
`ifdef DW1_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef DW1_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA1_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA1_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef FPADD1_SINGLE
integer PIPE=0;
FPU_Add_Subtract_Function_W32_EW8_SW23_SWR26_EWR5 uut(
.clk(clk),
.rst(rst),
.beg_FSM(begin_operation),
.ack_FSM(ack_operation),
.Data_X(Data_1),
.Data_Y(Data_2),
.add_subt(add_subt),
.r_mode(r_mode),
.overflow_flag(overflow_flag),
.underflow_flag(underflow_flag),
.ready(operation_ready),
.final_result_ieee(op_result)
);
`endif
`ifdef FPADD1_DOUBLE
integer PIPE=0;
FPU_Add_Subtract_Function_W64_EW11_SW52_SWR55_EWR6 uut(
.clk(clk),
.rst(rst),
.beg_FSM(begin_operation),
.ack_FSM(ack_operation),
.Data_X(Data_1),
.Data_Y(Data_2),
.add_subt(add_subt),
.r_mode(r_mode),
.overflow_flag(overflow_flag),
.underflow_flag(underflow_flag),
.ready(operation_ready),
.final_result_ieee(op_result)
);
`endif
`ifdef FPADD2_SINGLE
integer PIPE=1;
FPU_PIPELINED_FPADDSUB_W32_EW8_SW23_SWR26_EWR5 inst_uut (
.clk (clk),
.rst (rst),
.beg_OP (begin_operation),
.Data_X (Data_1),
.Data_Y (Data_2),
.add_subt (add_subt),
.busy (busy),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef FPADD2_DOUBLE
integer PIPE=1;
FPU_PIPELINED_FPADDSUB_W64_EW11_SW52_SWR55_EWR6 inst_uut (
.clk (clk),
.rst (rst),
.beg_OP (begin_operation),
.Data_X (Data_1),
.Data_Y (Data_2),
.add_subt (add_subt),
.busy (busy),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef CORDIC1_SINGLE
integer PIPE=0;
CORDIC_Arch2_W32_EW8_SW23_SWR26_EWR5 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.r_mode (r_mode),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.data_output (op_result)
);
`endif
`ifdef CORDIC1_DOUBLE
integer PIPE=0;
CORDIC_Arch2_W64_EW11_SW52_SWR55_EWR6 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.r_mode (r_mode),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.data_output (op_result)
);
`endif
`ifdef CORDIC2_SINGLE
CORDIC_Arch3_W32_EW8_SW23_SWR26_EWR5 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.busy (busy),
.data_output (op_result)
);
`endif
`ifdef CORDIC2_DOUBLE
CORDIC_Arch3_W64_EW11_SW52_SWR55_EWR6 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.busy (busy),
.data_output (op_result)
);
`endif
reg [W-1:0] Array_IN_1 [0:(((2**PERIOD))-1)];
reg [W-1:0] Array_IN_2 [0:(((2**PERIOD))-1)];
integer contador;
integer FileSaveData;
integer FileSaveData_FLOAT;
initial begin
// Initialize Inputs
$vcdpluson;
clk = 0;
rst = 1;
r_mode=ROUNDING_MODE_TRUNCT;
begin_operation = 0;
ack_operation = 0;
Data_1 = 0;
Data_2 = 0;
region_flag = IoIV1;
add_subt =1'b0;
$display("------------------------OP--------------------------");
$display("------------------------ --------------------------");
$display("------------------------OP--------------------------");
#100;
rst = 0;
$readmemh("Hexadecimal_A.txt", Array_IN_1);
$readmemh("Hexadecimal_B.txt", Array_IN_2);
FileSaveData = $fopen("ResultadoXilinxFLMv2.txt","w");
FileSaveData_FLOAT = $fopen("ResultadoXilinxFLMv2F.txt","w");
if (PIPE) begin
run_PIPE(FileSaveData,FileSaveData_FLOAT,(2**PERIOD));
end else begin
run_Arch2(FileSaveData,FileSaveData_FLOAT,(2**PERIOD));
end
#100 rst = 0;
$finish;
$vcdplusclose;
//Add stimulus here
end
//******************************* Se ejecuta el CLK ************************
initial forever #5 clk = ~clk;
task run_Arch2;
input integer FDataO;
input integer FData1;
input integer Vector_size;
begin
begin_operation = 0;
rst = 0;
#15 rst = 1;
#25 rst = 0;
// begin_operation = 0;
ack_operation = 0;
contador = 0;
repeat(Vector_size) @(negedge clk) begin
//input the new values inside the operator
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
#(PERIOD/4) begin_operation = 1;
//Wait for the operation operation_ready
@(posedge operation_ready) begin
#(PERIOD+2);
ack_operation = 1;
#4;
$display("%h\n",op_result);
$fwrite(FDataO,"%h\n",op_result);
$display("%f\n",$bitstoshortreal(op_result));
`ifdef SINGLE
$fwrite(FData1,"%f\n",$bitstoshortreal(op_result));
`else
$fwrite(FData1,"%f\n",$bitstoreal(op_result));
`endif
end
@(negedge clk) begin
ack_operation = 0;
end
contador = contador + 1;
end
$fclose(FDataO);
$fclose(FData1);
end
endtask
////////////////////////////TASK FOR THE PIPE ADDER/////////////////
////We need to read in a non-linear fashion, therefore
// we are going to write first the 3 first input operands,
// then, the normal running operation,
// and then the final procedure.
task run_PIPE;
input integer FData1;
input integer FData2;
input integer Vector_size2;
begin
begin_operation = 0;
rst = 0;
#15 rst = 1;
#25 rst = 0;
//begin_operation = 0;
contador = 0;
@(posedge clk)
begin_operation = 1;
@(posedge clk)
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
contador = contador + 1;
repeat(Vector_size2*2+6) @(posedge clk) begin
#(PERIOD/3);
if(~busy & ~rst) begin
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
contador = contador + 1;
end
if (operation_ready) begin
$fwrite(FData1,"%h\n",op_result);
`ifdef SINGLE
$fwrite(FData2,"%f\n",$bitstoshortreal(op_result));
`else
$fwrite(FData2,"%f\n",$bitstoreal(op_result));
`endif
end
end
begin_operation = 0;
$fclose(FData1);
$fclose(FData2);
end
endtask
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 03/29/2016 05:57:16 AM
// Design Name:
// Module Name: Testbench_FPU
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Testbench_FPU_Mark2();
parameter PERIOD = 10;
`ifdef SINGLE
parameter W = 32;
parameter EW = 8;
parameter SW = 23;
parameter SWR = 26;
parameter EWR = 5;//
`endif
`ifdef DOUBLE
parameter W = 64;
parameter EW = 11;
parameter SW = 52;
parameter SWR = 55;
parameter EWR = 6;
`endif
reg clk;
//INPUT signals
reg rst;
reg begin_operation;
reg ack_operation;
reg [2:0] operation;
//Oper_Start_in signals
reg [W-1:0] Data_1;
reg [W-1:0] Data_2;
reg [1:0] region_flag;
//reg add_subt;
//Round signals signals
reg [1:0] r_mode;
reg add_subt;
//OUTPUT SIGNALS
wire overflow_flag;
wire underflow_flag;
wire operation_ready;
wire zero_flag;
wire NaN_flag;
wire [W-1:0] op_result;
wire busy;
// LOS CODIGOS PARA LAS OPERACIONES
localparam [2:0] FPADD = 3'b000,
FPSUB = 3'b001,
FPCOS = 3'b010,
FPSEN = 3'b011,
FPMULT = 3'b100;
// LAS REGIONES DEL ANGULO
localparam [1:0] IoIV1 = 2'b00,
II = 2'b01,
III = 2'b10,
IoIV2 = 2'b11;
localparam [1:0] ROUNDING_MODE_TRUNCT = 2'b00,
ROUNDING_MODE_NEG_INF = 2'b01,
ROUNDING_MODE_POS_INF = 2'b10;
`ifdef FPUv2_behav
FPU_Interface2 #(
.W(W),
.EW(EW),
.SW(SW),
.SWR(SWR),
.EWR(EWR)
) inst_FPU_Interface (
.clk (clk),
.rst (rst),
.begin_operation (begin_operation),
.ack_operation (ack_operation),
.operation (operation),
.region_flag (region_flag),
.Data_1 (Data_1),
.Data_2 (Data_2),
.r_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.NaN_flag (NaN_flag),
.operation_ready (operation_ready),
.op_result (op_result),
.busy (busy)
);
`endif
`ifdef DW1_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef DW1_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef KOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA1_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA1_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA2_SINGLE
integer PIPE=0;
FPU_Multiplication_Function_W32_EW8_SW23 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef RKOA2_DOUBLE
integer PIPE=0;
FPU_Multiplication_Function_W64_EW11_SW52 uut (
.clk (clk),
.rst (rst),
.beg_FSM (begin_operation),
.ack_FSM (ack_operation),
.Data_MX (Data_1),
.Data_MY (Data_2),
.round_mode (r_mode),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef FPADD1_SINGLE
integer PIPE=0;
FPU_Add_Subtract_Function_W32_EW8_SW23_SWR26_EWR5 uut(
.clk(clk),
.rst(rst),
.beg_FSM(begin_operation),
.ack_FSM(ack_operation),
.Data_X(Data_1),
.Data_Y(Data_2),
.add_subt(add_subt),
.r_mode(r_mode),
.overflow_flag(overflow_flag),
.underflow_flag(underflow_flag),
.ready(operation_ready),
.final_result_ieee(op_result)
);
`endif
`ifdef FPADD1_DOUBLE
integer PIPE=0;
FPU_Add_Subtract_Function_W64_EW11_SW52_SWR55_EWR6 uut(
.clk(clk),
.rst(rst),
.beg_FSM(begin_operation),
.ack_FSM(ack_operation),
.Data_X(Data_1),
.Data_Y(Data_2),
.add_subt(add_subt),
.r_mode(r_mode),
.overflow_flag(overflow_flag),
.underflow_flag(underflow_flag),
.ready(operation_ready),
.final_result_ieee(op_result)
);
`endif
`ifdef FPADD2_SINGLE
integer PIPE=1;
FPU_PIPELINED_FPADDSUB_W32_EW8_SW23_SWR26_EWR5 inst_uut (
.clk (clk),
.rst (rst),
.beg_OP (begin_operation),
.Data_X (Data_1),
.Data_Y (Data_2),
.add_subt (add_subt),
.busy (busy),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef FPADD2_DOUBLE
integer PIPE=1;
FPU_PIPELINED_FPADDSUB_W64_EW11_SW52_SWR55_EWR6 inst_uut (
.clk (clk),
.rst (rst),
.beg_OP (begin_operation),
.Data_X (Data_1),
.Data_Y (Data_2),
.add_subt (add_subt),
.busy (busy),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.ready (operation_ready),
.final_result_ieee (op_result)
);
`endif
`ifdef CORDIC1_SINGLE
integer PIPE=0;
CORDIC_Arch2_W32_EW8_SW23_SWR26_EWR5 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.r_mode (r_mode),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.data_output (op_result)
);
`endif
`ifdef CORDIC1_DOUBLE
integer PIPE=0;
CORDIC_Arch2_W64_EW11_SW52_SWR55_EWR6 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.r_mode (r_mode),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.data_output (op_result)
);
`endif
`ifdef CORDIC2_SINGLE
CORDIC_Arch3_W32_EW8_SW23_SWR26_EWR5 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.busy (busy),
.data_output (op_result)
);
`endif
`ifdef CORDIC2_DOUBLE
CORDIC_Arch3_W64_EW11_SW52_SWR55_EWR6 uut (
.clk (clk),
.rst (rst),
.beg_fsm_cordic (begin_operation),
.ack_cordic (ack_operation),
.operation (1'b1),
.data_in (Data_1),
.shift_region_flag (region_flag),
.ready_cordic (operation_ready),
.overflow_flag (overflow_flag),
.underflow_flag (underflow_flag),
.zero_flag (zero_flag),
.busy (busy),
.data_output (op_result)
);
`endif
reg [W-1:0] Array_IN_1 [0:(((2**PERIOD))-1)];
reg [W-1:0] Array_IN_2 [0:(((2**PERIOD))-1)];
integer contador;
integer FileSaveData;
integer FileSaveData_FLOAT;
initial begin
// Initialize Inputs
$vcdpluson;
clk = 0;
rst = 1;
r_mode=ROUNDING_MODE_TRUNCT;
begin_operation = 0;
ack_operation = 0;
Data_1 = 0;
Data_2 = 0;
region_flag = IoIV1;
add_subt =1'b0;
$display("------------------------OP--------------------------");
$display("------------------------ --------------------------");
$display("------------------------OP--------------------------");
#100;
rst = 0;
$readmemh("Hexadecimal_A.txt", Array_IN_1);
$readmemh("Hexadecimal_B.txt", Array_IN_2);
FileSaveData = $fopen("ResultadoXilinxFLMv2.txt","w");
FileSaveData_FLOAT = $fopen("ResultadoXilinxFLMv2F.txt","w");
if (PIPE) begin
run_PIPE(FileSaveData,FileSaveData_FLOAT,(2**PERIOD));
end else begin
run_Arch2(FileSaveData,FileSaveData_FLOAT,(2**PERIOD));
end
#100 rst = 0;
$finish;
$vcdplusclose;
//Add stimulus here
end
//******************************* Se ejecuta el CLK ************************
initial forever #5 clk = ~clk;
task run_Arch2;
input integer FDataO;
input integer FData1;
input integer Vector_size;
begin
begin_operation = 0;
rst = 0;
#15 rst = 1;
#25 rst = 0;
// begin_operation = 0;
ack_operation = 0;
contador = 0;
repeat(Vector_size) @(negedge clk) begin
//input the new values inside the operator
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
#(PERIOD/4) begin_operation = 1;
//Wait for the operation operation_ready
@(posedge operation_ready) begin
#(PERIOD+2);
ack_operation = 1;
#4;
$display("%h\n",op_result);
$fwrite(FDataO,"%h\n",op_result);
$display("%f\n",$bitstoshortreal(op_result));
`ifdef SINGLE
$fwrite(FData1,"%f\n",$bitstoshortreal(op_result));
`else
$fwrite(FData1,"%f\n",$bitstoreal(op_result));
`endif
end
@(negedge clk) begin
ack_operation = 0;
end
contador = contador + 1;
end
$fclose(FDataO);
$fclose(FData1);
end
endtask
////////////////////////////TASK FOR THE PIPE ADDER/////////////////
////We need to read in a non-linear fashion, therefore
// we are going to write first the 3 first input operands,
// then, the normal running operation,
// and then the final procedure.
task run_PIPE;
input integer FData1;
input integer FData2;
input integer Vector_size2;
begin
begin_operation = 0;
rst = 0;
#15 rst = 1;
#25 rst = 0;
//begin_operation = 0;
contador = 0;
@(posedge clk)
begin_operation = 1;
@(posedge clk)
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
contador = contador + 1;
repeat(Vector_size2*2+6) @(posedge clk) begin
#(PERIOD/3);
if(~busy & ~rst) begin
Data_1 = Array_IN_1[contador];
Data_2 = Array_IN_2[contador];
contador = contador + 1;
end
if (operation_ready) begin
$fwrite(FData1,"%h\n",op_result);
`ifdef SINGLE
$fwrite(FData2,"%f\n",$bitstoshortreal(op_result));
`else
$fwrite(FData2,"%f\n",$bitstoreal(op_result));
`endif
end
end
begin_operation = 0;
$fclose(FData1);
$fclose(FData2);
end
endtask
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
//Simple debug:
//wire [1:1] wir_a [3:3] [2:2]; //11
//logic [1:1] log_a [3:3] [2:2]; //12
//wire [3:3] [2:2] [1:1] wir_p; //13
//logic [3:3] [2:2] [1:1] log_p; //14
integer cyc; initial cyc = 0;
`ifdef iverilog
reg [7:0] arr [3:0];
wire [7:0] arr_w [3:0];
`else
reg [3:0] [7:0] arr;
wire [3:0] [7:0] arr_w;
`endif
reg [7:0] sum;
reg [7:0] sum_w;
integer i0;
initial begin
for (i0=0; i0<5; i0=i0+1) begin
arr[i0] = 1 << (i0[1:0]*2);
end
end
assign arr_w = arr;
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
sum <= 0;
sum_w <= 0;
end
else if (cyc >= 10 && cyc < 14) begin
sum <= sum + arr[cyc-10];
sum_w <= sum_w + arr_w[cyc-10];
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d sum=%x\n",$time, cyc, sum);
if (sum != 8'h55) $stop;
if (sum != sum_w) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
// Test ordering of packed dimensions
logic [31:0] data_out;
logic [31:0] data_out2;
logic [0:0] [2:0] [31:0] data_in;
logic [31:0] data_in2 [0:0] [2:0];
assign data_out = data_in[0][0] + data_in[0][1] + data_in[0][2];
assign data_out2 = data_in2[0][0] + data_in2[0][1] + data_in2[0][2];
logic [31:0] last_data_out;
always @ (posedge clk) begin
if (cyc <= 2) begin
data_in[0][0] <= 0;
data_in[0][1] <= 0;
data_in[0][2] <= 0;
data_in2[0][0] <= 0;
data_in2[0][1] <= 0;
data_in2[0][2] <= 0;
end
else if (cyc > 2 && cyc < 99) begin
data_in[0][0] <= data_in[0][0] + 1;
data_in[0][1] <= data_in[0][1] + 1;
data_in[0][2] <= data_in[0][2] + 1;
data_in2[0][0] <= data_in2[0][0] + 1;
data_in2[0][1] <= data_in2[0][1] + 1;
data_in2[0][2] <= data_in2[0][2] + 1;
last_data_out <= data_out;
`ifdef TEST_VERBOSE
$write("data_out %0x %0x\n", data_out, last_data_out);
`endif
if (cyc > 4 && data_out != last_data_out + 3) $stop;
if (cyc > 4 && data_out != data_out2) $stop;
end
end
// Test for mixed implicit/explicit dimensions and all implicit packed
bit [3:0][7:0][1:0] vld [1:0][1:0];
bit [3:0][7:0][1:0] vld2;
// There are specific nodes for Or, Xor, Xnor and And
logic vld_or;
logic vld2_or;
assign vld_or = |vld[0][0];
assign vld2_or = |vld2;
logic vld_xor;
logic vld2_xor;
assign vld_xor = ^vld[0][0];
assign vld2_xor = ^vld2;
logic vld_xnor;
logic vld2_xnor;
assign vld_xnor = ~^vld[0][0];
assign vld2_xnor = ~^vld2;
logic vld_and;
logic vld2_and;
assign vld_and = &vld[0][0];
assign vld2_and = &vld2;
// Bit reductions should be cloned, other unary operations should clone the
// entire assign.
bit [3:0][7:0][1:0] not_lhs;
bit [3:0][7:0][1:0] not_rhs;
assign not_lhs = ~not_rhs;
// Test an AstNodeUniop that shouldn't be expanded
bit [3:0][7:0][1:0] vld2_inv;
assign vld2_inv = ~vld2;
initial begin
for (int i=0; i<4; i=i+2) begin
for (int j=0; j<8; j=j+2) begin
vld[0][0][i][j] = 2'b00;
vld[0][0][i+1][j+1] = 2'b00;
vld2[i][j] = 2'b00;
vld2[i+1][j+1] = 2'b00;
not_rhs[i][j] = i[1:0];
not_rhs[i+1][j+1] = i[1:0];
end
end
end
logic [3:0] expect_cyc; initial expect_cyc = 'd15;
always @(posedge clk) begin
expect_cyc <= expect_cyc + 1;
for (int i=0; i<4; i=i+1) begin
for (int j=0; j<8; j=j+1) begin
vld[0][0][i][j] <= vld[0][0][i][j] + 1;
vld2[i][j] <= vld2[i][j] + 1;
if (not_rhs[i][j] != ~not_lhs[i][j]) $stop;
not_rhs[i][j] <= not_rhs[i][j] + 1;
end
end
if (cyc % 8 == 0) begin
vld[0][0][0][0] <= vld[0][0][0][0] - 1;
vld2[0][0] <= vld2[0][0] - 1;
end
if (expect_cyc < 8 && !vld_xor) $stop;
else if (expect_cyc > 7 && vld_xor) $stop;
if (expect_cyc < 8 && vld_xnor) $stop;
else if (expect_cyc > 7 && !vld_xnor) $stop;
if (expect_cyc == 15 && vld_or) $stop;
else if (expect_cyc == 11 && vld_or) $stop;
else if (expect_cyc != 15 && expect_cyc != 11 && !vld_or) $stop;
if (expect_cyc == 10 && !vld_and) $stop;
else if (expect_cyc == 14 && !vld_and) $stop;
else if (expect_cyc != 10 && expect_cyc != 14 && vld_and) $stop;
if (vld_xor != vld2_xor) $stop;
if (vld_xnor != vld2_xnor) $stop;
if (vld_or != vld2_or) $stop;
if (vld_and != vld2_and) $stop;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
//Simple debug:
//wire [1:1] wir_a [3:3] [2:2]; //11
//logic [1:1] log_a [3:3] [2:2]; //12
//wire [3:3] [2:2] [1:1] wir_p; //13
//logic [3:3] [2:2] [1:1] log_p; //14
integer cyc; initial cyc = 0;
`ifdef iverilog
reg [7:0] arr [3:0];
wire [7:0] arr_w [3:0];
`else
reg [3:0] [7:0] arr;
wire [3:0] [7:0] arr_w;
`endif
reg [7:0] sum;
reg [7:0] sum_w;
integer i0;
initial begin
for (i0=0; i0<5; i0=i0+1) begin
arr[i0] = 1 << (i0[1:0]*2);
end
end
assign arr_w = arr;
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
sum <= 0;
sum_w <= 0;
end
else if (cyc >= 10 && cyc < 14) begin
sum <= sum + arr[cyc-10];
sum_w <= sum_w + arr_w[cyc-10];
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d sum=%x\n",$time, cyc, sum);
if (sum != 8'h55) $stop;
if (sum != sum_w) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
// Test ordering of packed dimensions
logic [31:0] data_out;
logic [31:0] data_out2;
logic [0:0] [2:0] [31:0] data_in;
logic [31:0] data_in2 [0:0] [2:0];
assign data_out = data_in[0][0] + data_in[0][1] + data_in[0][2];
assign data_out2 = data_in2[0][0] + data_in2[0][1] + data_in2[0][2];
logic [31:0] last_data_out;
always @ (posedge clk) begin
if (cyc <= 2) begin
data_in[0][0] <= 0;
data_in[0][1] <= 0;
data_in[0][2] <= 0;
data_in2[0][0] <= 0;
data_in2[0][1] <= 0;
data_in2[0][2] <= 0;
end
else if (cyc > 2 && cyc < 99) begin
data_in[0][0] <= data_in[0][0] + 1;
data_in[0][1] <= data_in[0][1] + 1;
data_in[0][2] <= data_in[0][2] + 1;
data_in2[0][0] <= data_in2[0][0] + 1;
data_in2[0][1] <= data_in2[0][1] + 1;
data_in2[0][2] <= data_in2[0][2] + 1;
last_data_out <= data_out;
`ifdef TEST_VERBOSE
$write("data_out %0x %0x\n", data_out, last_data_out);
`endif
if (cyc > 4 && data_out != last_data_out + 3) $stop;
if (cyc > 4 && data_out != data_out2) $stop;
end
end
// Test for mixed implicit/explicit dimensions and all implicit packed
bit [3:0][7:0][1:0] vld [1:0][1:0];
bit [3:0][7:0][1:0] vld2;
// There are specific nodes for Or, Xor, Xnor and And
logic vld_or;
logic vld2_or;
assign vld_or = |vld[0][0];
assign vld2_or = |vld2;
logic vld_xor;
logic vld2_xor;
assign vld_xor = ^vld[0][0];
assign vld2_xor = ^vld2;
logic vld_xnor;
logic vld2_xnor;
assign vld_xnor = ~^vld[0][0];
assign vld2_xnor = ~^vld2;
logic vld_and;
logic vld2_and;
assign vld_and = &vld[0][0];
assign vld2_and = &vld2;
// Bit reductions should be cloned, other unary operations should clone the
// entire assign.
bit [3:0][7:0][1:0] not_lhs;
bit [3:0][7:0][1:0] not_rhs;
assign not_lhs = ~not_rhs;
// Test an AstNodeUniop that shouldn't be expanded
bit [3:0][7:0][1:0] vld2_inv;
assign vld2_inv = ~vld2;
initial begin
for (int i=0; i<4; i=i+2) begin
for (int j=0; j<8; j=j+2) begin
vld[0][0][i][j] = 2'b00;
vld[0][0][i+1][j+1] = 2'b00;
vld2[i][j] = 2'b00;
vld2[i+1][j+1] = 2'b00;
not_rhs[i][j] = i[1:0];
not_rhs[i+1][j+1] = i[1:0];
end
end
end
logic [3:0] expect_cyc; initial expect_cyc = 'd15;
always @(posedge clk) begin
expect_cyc <= expect_cyc + 1;
for (int i=0; i<4; i=i+1) begin
for (int j=0; j<8; j=j+1) begin
vld[0][0][i][j] <= vld[0][0][i][j] + 1;
vld2[i][j] <= vld2[i][j] + 1;
if (not_rhs[i][j] != ~not_lhs[i][j]) $stop;
not_rhs[i][j] <= not_rhs[i][j] + 1;
end
end
if (cyc % 8 == 0) begin
vld[0][0][0][0] <= vld[0][0][0][0] - 1;
vld2[0][0] <= vld2[0][0] - 1;
end
if (expect_cyc < 8 && !vld_xor) $stop;
else if (expect_cyc > 7 && vld_xor) $stop;
if (expect_cyc < 8 && vld_xnor) $stop;
else if (expect_cyc > 7 && !vld_xnor) $stop;
if (expect_cyc == 15 && vld_or) $stop;
else if (expect_cyc == 11 && vld_or) $stop;
else if (expect_cyc != 15 && expect_cyc != 11 && !vld_or) $stop;
if (expect_cyc == 10 && !vld_and) $stop;
else if (expect_cyc == 14 && !vld_and) $stop;
else if (expect_cyc != 10 && expect_cyc != 14 && vld_and) $stop;
if (vld_xor != vld2_xor) $stop;
if (vld_xnor != vld2_xnor) $stop;
if (vld_or != vld2_or) $stop;
if (vld_and != vld2_and) $stop;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
//Simple debug:
//wire [1:1] wir_a [3:3] [2:2]; //11
//logic [1:1] log_a [3:3] [2:2]; //12
//wire [3:3] [2:2] [1:1] wir_p; //13
//logic [3:3] [2:2] [1:1] log_p; //14
integer cyc; initial cyc = 0;
`ifdef iverilog
reg [7:0] arr [3:0];
wire [7:0] arr_w [3:0];
`else
reg [3:0] [7:0] arr;
wire [3:0] [7:0] arr_w;
`endif
reg [7:0] sum;
reg [7:0] sum_w;
integer i0;
initial begin
for (i0=0; i0<5; i0=i0+1) begin
arr[i0] = 1 << (i0[1:0]*2);
end
end
assign arr_w = arr;
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
sum <= 0;
sum_w <= 0;
end
else if (cyc >= 10 && cyc < 14) begin
sum <= sum + arr[cyc-10];
sum_w <= sum_w + arr_w[cyc-10];
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d sum=%x\n",$time, cyc, sum);
if (sum != 8'h55) $stop;
if (sum != sum_w) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
// Test ordering of packed dimensions
logic [31:0] data_out;
logic [31:0] data_out2;
logic [0:0] [2:0] [31:0] data_in;
logic [31:0] data_in2 [0:0] [2:0];
assign data_out = data_in[0][0] + data_in[0][1] + data_in[0][2];
assign data_out2 = data_in2[0][0] + data_in2[0][1] + data_in2[0][2];
logic [31:0] last_data_out;
always @ (posedge clk) begin
if (cyc <= 2) begin
data_in[0][0] <= 0;
data_in[0][1] <= 0;
data_in[0][2] <= 0;
data_in2[0][0] <= 0;
data_in2[0][1] <= 0;
data_in2[0][2] <= 0;
end
else if (cyc > 2 && cyc < 99) begin
data_in[0][0] <= data_in[0][0] + 1;
data_in[0][1] <= data_in[0][1] + 1;
data_in[0][2] <= data_in[0][2] + 1;
data_in2[0][0] <= data_in2[0][0] + 1;
data_in2[0][1] <= data_in2[0][1] + 1;
data_in2[0][2] <= data_in2[0][2] + 1;
last_data_out <= data_out;
`ifdef TEST_VERBOSE
$write("data_out %0x %0x\n", data_out, last_data_out);
`endif
if (cyc > 4 && data_out != last_data_out + 3) $stop;
if (cyc > 4 && data_out != data_out2) $stop;
end
end
// Test for mixed implicit/explicit dimensions and all implicit packed
bit [3:0][7:0][1:0] vld [1:0][1:0];
bit [3:0][7:0][1:0] vld2;
// There are specific nodes for Or, Xor, Xnor and And
logic vld_or;
logic vld2_or;
assign vld_or = |vld[0][0];
assign vld2_or = |vld2;
logic vld_xor;
logic vld2_xor;
assign vld_xor = ^vld[0][0];
assign vld2_xor = ^vld2;
logic vld_xnor;
logic vld2_xnor;
assign vld_xnor = ~^vld[0][0];
assign vld2_xnor = ~^vld2;
logic vld_and;
logic vld2_and;
assign vld_and = &vld[0][0];
assign vld2_and = &vld2;
// Bit reductions should be cloned, other unary operations should clone the
// entire assign.
bit [3:0][7:0][1:0] not_lhs;
bit [3:0][7:0][1:0] not_rhs;
assign not_lhs = ~not_rhs;
// Test an AstNodeUniop that shouldn't be expanded
bit [3:0][7:0][1:0] vld2_inv;
assign vld2_inv = ~vld2;
initial begin
for (int i=0; i<4; i=i+2) begin
for (int j=0; j<8; j=j+2) begin
vld[0][0][i][j] = 2'b00;
vld[0][0][i+1][j+1] = 2'b00;
vld2[i][j] = 2'b00;
vld2[i+1][j+1] = 2'b00;
not_rhs[i][j] = i[1:0];
not_rhs[i+1][j+1] = i[1:0];
end
end
end
logic [3:0] expect_cyc; initial expect_cyc = 'd15;
always @(posedge clk) begin
expect_cyc <= expect_cyc + 1;
for (int i=0; i<4; i=i+1) begin
for (int j=0; j<8; j=j+1) begin
vld[0][0][i][j] <= vld[0][0][i][j] + 1;
vld2[i][j] <= vld2[i][j] + 1;
if (not_rhs[i][j] != ~not_lhs[i][j]) $stop;
not_rhs[i][j] <= not_rhs[i][j] + 1;
end
end
if (cyc % 8 == 0) begin
vld[0][0][0][0] <= vld[0][0][0][0] - 1;
vld2[0][0] <= vld2[0][0] - 1;
end
if (expect_cyc < 8 && !vld_xor) $stop;
else if (expect_cyc > 7 && vld_xor) $stop;
if (expect_cyc < 8 && vld_xnor) $stop;
else if (expect_cyc > 7 && !vld_xnor) $stop;
if (expect_cyc == 15 && vld_or) $stop;
else if (expect_cyc == 11 && vld_or) $stop;
else if (expect_cyc != 15 && expect_cyc != 11 && !vld_or) $stop;
if (expect_cyc == 10 && !vld_and) $stop;
else if (expect_cyc == 14 && !vld_and) $stop;
else if (expect_cyc != 10 && expect_cyc != 14 && vld_and) $stop;
if (vld_xor != vld2_xor) $stop;
if (vld_xnor != vld2_xnor) $stop;
if (vld_or != vld2_or) $stop;
if (vld_and != vld2_and) $stop;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
//Simple debug:
//wire [1:1] wir_a [3:3] [2:2]; //11
//logic [1:1] log_a [3:3] [2:2]; //12
//wire [3:3] [2:2] [1:1] wir_p; //13
//logic [3:3] [2:2] [1:1] log_p; //14
integer cyc; initial cyc = 0;
`ifdef iverilog
reg [7:0] arr [3:0];
wire [7:0] arr_w [3:0];
`else
reg [3:0] [7:0] arr;
wire [3:0] [7:0] arr_w;
`endif
reg [7:0] sum;
reg [7:0] sum_w;
integer i0;
initial begin
for (i0=0; i0<5; i0=i0+1) begin
arr[i0] = 1 << (i0[1:0]*2);
end
end
assign arr_w = arr;
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
sum <= 0;
sum_w <= 0;
end
else if (cyc >= 10 && cyc < 14) begin
sum <= sum + arr[cyc-10];
sum_w <= sum_w + arr_w[cyc-10];
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d sum=%x\n",$time, cyc, sum);
if (sum != 8'h55) $stop;
if (sum != sum_w) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
// Test ordering of packed dimensions
logic [31:0] data_out;
logic [31:0] data_out2;
logic [0:0] [2:0] [31:0] data_in;
logic [31:0] data_in2 [0:0] [2:0];
assign data_out = data_in[0][0] + data_in[0][1] + data_in[0][2];
assign data_out2 = data_in2[0][0] + data_in2[0][1] + data_in2[0][2];
logic [31:0] last_data_out;
always @ (posedge clk) begin
if (cyc <= 2) begin
data_in[0][0] <= 0;
data_in[0][1] <= 0;
data_in[0][2] <= 0;
data_in2[0][0] <= 0;
data_in2[0][1] <= 0;
data_in2[0][2] <= 0;
end
else if (cyc > 2 && cyc < 99) begin
data_in[0][0] <= data_in[0][0] + 1;
data_in[0][1] <= data_in[0][1] + 1;
data_in[0][2] <= data_in[0][2] + 1;
data_in2[0][0] <= data_in2[0][0] + 1;
data_in2[0][1] <= data_in2[0][1] + 1;
data_in2[0][2] <= data_in2[0][2] + 1;
last_data_out <= data_out;
`ifdef TEST_VERBOSE
$write("data_out %0x %0x\n", data_out, last_data_out);
`endif
if (cyc > 4 && data_out != last_data_out + 3) $stop;
if (cyc > 4 && data_out != data_out2) $stop;
end
end
// Test for mixed implicit/explicit dimensions and all implicit packed
bit [3:0][7:0][1:0] vld [1:0][1:0];
bit [3:0][7:0][1:0] vld2;
// There are specific nodes for Or, Xor, Xnor and And
logic vld_or;
logic vld2_or;
assign vld_or = |vld[0][0];
assign vld2_or = |vld2;
logic vld_xor;
logic vld2_xor;
assign vld_xor = ^vld[0][0];
assign vld2_xor = ^vld2;
logic vld_xnor;
logic vld2_xnor;
assign vld_xnor = ~^vld[0][0];
assign vld2_xnor = ~^vld2;
logic vld_and;
logic vld2_and;
assign vld_and = &vld[0][0];
assign vld2_and = &vld2;
// Bit reductions should be cloned, other unary operations should clone the
// entire assign.
bit [3:0][7:0][1:0] not_lhs;
bit [3:0][7:0][1:0] not_rhs;
assign not_lhs = ~not_rhs;
// Test an AstNodeUniop that shouldn't be expanded
bit [3:0][7:0][1:0] vld2_inv;
assign vld2_inv = ~vld2;
initial begin
for (int i=0; i<4; i=i+2) begin
for (int j=0; j<8; j=j+2) begin
vld[0][0][i][j] = 2'b00;
vld[0][0][i+1][j+1] = 2'b00;
vld2[i][j] = 2'b00;
vld2[i+1][j+1] = 2'b00;
not_rhs[i][j] = i[1:0];
not_rhs[i+1][j+1] = i[1:0];
end
end
end
logic [3:0] expect_cyc; initial expect_cyc = 'd15;
always @(posedge clk) begin
expect_cyc <= expect_cyc + 1;
for (int i=0; i<4; i=i+1) begin
for (int j=0; j<8; j=j+1) begin
vld[0][0][i][j] <= vld[0][0][i][j] + 1;
vld2[i][j] <= vld2[i][j] + 1;
if (not_rhs[i][j] != ~not_lhs[i][j]) $stop;
not_rhs[i][j] <= not_rhs[i][j] + 1;
end
end
if (cyc % 8 == 0) begin
vld[0][0][0][0] <= vld[0][0][0][0] - 1;
vld2[0][0] <= vld2[0][0] - 1;
end
if (expect_cyc < 8 && !vld_xor) $stop;
else if (expect_cyc > 7 && vld_xor) $stop;
if (expect_cyc < 8 && vld_xnor) $stop;
else if (expect_cyc > 7 && !vld_xnor) $stop;
if (expect_cyc == 15 && vld_or) $stop;
else if (expect_cyc == 11 && vld_or) $stop;
else if (expect_cyc != 15 && expect_cyc != 11 && !vld_or) $stop;
if (expect_cyc == 10 && !vld_and) $stop;
else if (expect_cyc == 14 && !vld_and) $stop;
else if (expect_cyc != 10 && expect_cyc != 14 && vld_and) $stop;
if (vld_xor != vld2_xor) $stop;
if (vld_xnor != vld2_xnor) $stop;
if (vld_or != vld2_or) $stop;
if (vld_and != vld2_and) $stop;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
//Simple debug:
//wire [1:1] wir_a [3:3] [2:2]; //11
//logic [1:1] log_a [3:3] [2:2]; //12
//wire [3:3] [2:2] [1:1] wir_p; //13
//logic [3:3] [2:2] [1:1] log_p; //14
integer cyc; initial cyc = 0;
`ifdef iverilog
reg [7:0] arr [3:0];
wire [7:0] arr_w [3:0];
`else
reg [3:0] [7:0] arr;
wire [3:0] [7:0] arr_w;
`endif
reg [7:0] sum;
reg [7:0] sum_w;
integer i0;
initial begin
for (i0=0; i0<5; i0=i0+1) begin
arr[i0] = 1 << (i0[1:0]*2);
end
end
assign arr_w = arr;
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
sum <= 0;
sum_w <= 0;
end
else if (cyc >= 10 && cyc < 14) begin
sum <= sum + arr[cyc-10];
sum_w <= sum_w + arr_w[cyc-10];
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d sum=%x\n",$time, cyc, sum);
if (sum != 8'h55) $stop;
if (sum != sum_w) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
// Test ordering of packed dimensions
logic [31:0] data_out;
logic [31:0] data_out2;
logic [0:0] [2:0] [31:0] data_in;
logic [31:0] data_in2 [0:0] [2:0];
assign data_out = data_in[0][0] + data_in[0][1] + data_in[0][2];
assign data_out2 = data_in2[0][0] + data_in2[0][1] + data_in2[0][2];
logic [31:0] last_data_out;
always @ (posedge clk) begin
if (cyc <= 2) begin
data_in[0][0] <= 0;
data_in[0][1] <= 0;
data_in[0][2] <= 0;
data_in2[0][0] <= 0;
data_in2[0][1] <= 0;
data_in2[0][2] <= 0;
end
else if (cyc > 2 && cyc < 99) begin
data_in[0][0] <= data_in[0][0] + 1;
data_in[0][1] <= data_in[0][1] + 1;
data_in[0][2] <= data_in[0][2] + 1;
data_in2[0][0] <= data_in2[0][0] + 1;
data_in2[0][1] <= data_in2[0][1] + 1;
data_in2[0][2] <= data_in2[0][2] + 1;
last_data_out <= data_out;
`ifdef TEST_VERBOSE
$write("data_out %0x %0x\n", data_out, last_data_out);
`endif
if (cyc > 4 && data_out != last_data_out + 3) $stop;
if (cyc > 4 && data_out != data_out2) $stop;
end
end
// Test for mixed implicit/explicit dimensions and all implicit packed
bit [3:0][7:0][1:0] vld [1:0][1:0];
bit [3:0][7:0][1:0] vld2;
// There are specific nodes for Or, Xor, Xnor and And
logic vld_or;
logic vld2_or;
assign vld_or = |vld[0][0];
assign vld2_or = |vld2;
logic vld_xor;
logic vld2_xor;
assign vld_xor = ^vld[0][0];
assign vld2_xor = ^vld2;
logic vld_xnor;
logic vld2_xnor;
assign vld_xnor = ~^vld[0][0];
assign vld2_xnor = ~^vld2;
logic vld_and;
logic vld2_and;
assign vld_and = &vld[0][0];
assign vld2_and = &vld2;
// Bit reductions should be cloned, other unary operations should clone the
// entire assign.
bit [3:0][7:0][1:0] not_lhs;
bit [3:0][7:0][1:0] not_rhs;
assign not_lhs = ~not_rhs;
// Test an AstNodeUniop that shouldn't be expanded
bit [3:0][7:0][1:0] vld2_inv;
assign vld2_inv = ~vld2;
initial begin
for (int i=0; i<4; i=i+2) begin
for (int j=0; j<8; j=j+2) begin
vld[0][0][i][j] = 2'b00;
vld[0][0][i+1][j+1] = 2'b00;
vld2[i][j] = 2'b00;
vld2[i+1][j+1] = 2'b00;
not_rhs[i][j] = i[1:0];
not_rhs[i+1][j+1] = i[1:0];
end
end
end
logic [3:0] expect_cyc; initial expect_cyc = 'd15;
always @(posedge clk) begin
expect_cyc <= expect_cyc + 1;
for (int i=0; i<4; i=i+1) begin
for (int j=0; j<8; j=j+1) begin
vld[0][0][i][j] <= vld[0][0][i][j] + 1;
vld2[i][j] <= vld2[i][j] + 1;
if (not_rhs[i][j] != ~not_lhs[i][j]) $stop;
not_rhs[i][j] <= not_rhs[i][j] + 1;
end
end
if (cyc % 8 == 0) begin
vld[0][0][0][0] <= vld[0][0][0][0] - 1;
vld2[0][0] <= vld2[0][0] - 1;
end
if (expect_cyc < 8 && !vld_xor) $stop;
else if (expect_cyc > 7 && vld_xor) $stop;
if (expect_cyc < 8 && vld_xnor) $stop;
else if (expect_cyc > 7 && !vld_xnor) $stop;
if (expect_cyc == 15 && vld_or) $stop;
else if (expect_cyc == 11 && vld_or) $stop;
else if (expect_cyc != 15 && expect_cyc != 11 && !vld_or) $stop;
if (expect_cyc == 10 && !vld_and) $stop;
else if (expect_cyc == 14 && !vld_and) $stop;
else if (expect_cyc != 10 && expect_cyc != 14 && vld_and) $stop;
if (vld_xor != vld2_xor) $stop;
if (vld_xnor != vld2_xnor) $stop;
if (vld_or != vld2_or) $stop;
if (vld_and != vld2_and) $stop;
end
endmodule
|
//////////////////////////////////////////////////////////////////////
//// ////
//// spi_clgen.v ////
//// ////
//// This file is part of the SPI IP core project ////
//// http://www.opencores.org/projects/spi/ ////
//// ////
//// Author(s): ////
//// - Simon Srot ([email protected]) ////
//// ////
//// All additional information is avaliable in the Readme.txt ////
//// file. ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2002 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
module spi_clgen (clk_in, rst, go, enable, last_clk, divider, clk_out, pos_edge, neg_edge);
parameter Tp = 1;
input clk_in; // input clock (system clock)
input rst; // reset
input enable; // clock enable
input go; // start transfer
input last_clk; // last clock
input [3:0] divider; // clock divider (output clock is divided by this value)
output clk_out; // output clock
output pos_edge; // pulse marking positive edge of clk_out
output neg_edge; // pulse marking negative edge of clk_out
reg clk_out;
reg pos_edge;
reg neg_edge;
reg [3:0] cnt; // clock counter
wire cnt_zero; // conter is equal to zero
wire cnt_one; // conter is equal to one
assign cnt_zero = cnt == {4{1'b0}};
assign cnt_one = cnt == {{3{1'b0}}, 1'b1};
// Counter counts half period
always @(posedge clk_in or posedge rst)
begin
if(rst)
cnt <= #Tp {4{1'b1}};
else
begin
if(!enable || cnt_zero)
cnt <= #Tp divider;
else
cnt <= #Tp cnt - {{3{1'b0}}, 1'b1};
end
end
// clk_out is asserted every other half period
always @(posedge clk_in or posedge rst)
begin
if(rst)
clk_out <= #Tp 1'b0;
else
clk_out <= #Tp (enable && cnt_zero && (!last_clk || clk_out)) ? ~clk_out : clk_out;
end
// Pos and neg edge signals
always @(posedge clk_in or posedge rst)
begin
if(rst)
begin
pos_edge <= #Tp 1'b0;
neg_edge <= #Tp 1'b0;
end
else
begin
pos_edge <= #Tp (enable && !clk_out && cnt_one) || (!(|divider) && clk_out) || (!(|divider) && go && !enable);
neg_edge <= #Tp (enable && clk_out && cnt_one) || (!(|divider) && !clk_out && enable);
end
end
endmodule
|
//////////////////////////////////////////////////////////////////////
//// ////
//// spi_clgen.v ////
//// ////
//// This file is part of the SPI IP core project ////
//// http://www.opencores.org/projects/spi/ ////
//// ////
//// Author(s): ////
//// - Simon Srot ([email protected]) ////
//// ////
//// All additional information is avaliable in the Readme.txt ////
//// file. ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2002 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
module spi_clgen (clk_in, rst, go, enable, last_clk, divider, clk_out, pos_edge, neg_edge);
parameter Tp = 1;
input clk_in; // input clock (system clock)
input rst; // reset
input enable; // clock enable
input go; // start transfer
input last_clk; // last clock
input [3:0] divider; // clock divider (output clock is divided by this value)
output clk_out; // output clock
output pos_edge; // pulse marking positive edge of clk_out
output neg_edge; // pulse marking negative edge of clk_out
reg clk_out;
reg pos_edge;
reg neg_edge;
reg [3:0] cnt; // clock counter
wire cnt_zero; // conter is equal to zero
wire cnt_one; // conter is equal to one
assign cnt_zero = cnt == {4{1'b0}};
assign cnt_one = cnt == {{3{1'b0}}, 1'b1};
// Counter counts half period
always @(posedge clk_in or posedge rst)
begin
if(rst)
cnt <= #Tp {4{1'b1}};
else
begin
if(!enable || cnt_zero)
cnt <= #Tp divider;
else
cnt <= #Tp cnt - {{3{1'b0}}, 1'b1};
end
end
// clk_out is asserted every other half period
always @(posedge clk_in or posedge rst)
begin
if(rst)
clk_out <= #Tp 1'b0;
else
clk_out <= #Tp (enable && cnt_zero && (!last_clk || clk_out)) ? ~clk_out : clk_out;
end
// Pos and neg edge signals
always @(posedge clk_in or posedge rst)
begin
if(rst)
begin
pos_edge <= #Tp 1'b0;
neg_edge <= #Tp 1'b0;
end
else
begin
pos_edge <= #Tp (enable && !clk_out && cnt_one) || (!(|divider) && clk_out) || (!(|divider) && go && !enable);
neg_edge <= #Tp (enable && clk_out && cnt_one) || (!(|divider) && !clk_out && enable);
end
end
endmodule
|
//////////////////////////////////////////////////////////////////////
//// ////
//// spi_clgen.v ////
//// ////
//// This file is part of the SPI IP core project ////
//// http://www.opencores.org/projects/spi/ ////
//// ////
//// Author(s): ////
//// - Simon Srot ([email protected]) ////
//// ////
//// All additional information is avaliable in the Readme.txt ////
//// file. ////
//// ////
//////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (C) 2002 Authors ////
//// ////
//// This source file may be used and distributed without ////
//// restriction provided that this copyright statement is not ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer. ////
//// ////
//// This source file is free software; you can redistribute it ////
//// and/or modify it under the terms of the GNU Lesser General ////
//// Public License as published by the Free Software Foundation; ////
//// either version 2.1 of the License, or (at your option) any ////
//// later version. ////
//// ////
//// This source is distributed in the hope that it will be ////
//// useful, but WITHOUT ANY WARRANTY; without even the implied ////
//// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ////
//// PURPOSE. See the GNU Lesser General Public License for more ////
//// details. ////
//// ////
//// You should have received a copy of the GNU Lesser General ////
//// Public License along with this source; if not, download it ////
//// from http://www.opencores.org/lgpl.shtml ////
//// ////
//////////////////////////////////////////////////////////////////////
module spi_clgen (clk_in, rst, go, enable, last_clk, divider, clk_out, pos_edge, neg_edge);
parameter Tp = 1;
input clk_in; // input clock (system clock)
input rst; // reset
input enable; // clock enable
input go; // start transfer
input last_clk; // last clock
input [3:0] divider; // clock divider (output clock is divided by this value)
output clk_out; // output clock
output pos_edge; // pulse marking positive edge of clk_out
output neg_edge; // pulse marking negative edge of clk_out
reg clk_out;
reg pos_edge;
reg neg_edge;
reg [3:0] cnt; // clock counter
wire cnt_zero; // conter is equal to zero
wire cnt_one; // conter is equal to one
assign cnt_zero = cnt == {4{1'b0}};
assign cnt_one = cnt == {{3{1'b0}}, 1'b1};
// Counter counts half period
always @(posedge clk_in or posedge rst)
begin
if(rst)
cnt <= #Tp {4{1'b1}};
else
begin
if(!enable || cnt_zero)
cnt <= #Tp divider;
else
cnt <= #Tp cnt - {{3{1'b0}}, 1'b1};
end
end
// clk_out is asserted every other half period
always @(posedge clk_in or posedge rst)
begin
if(rst)
clk_out <= #Tp 1'b0;
else
clk_out <= #Tp (enable && cnt_zero && (!last_clk || clk_out)) ? ~clk_out : clk_out;
end
// Pos and neg edge signals
always @(posedge clk_in or posedge rst)
begin
if(rst)
begin
pos_edge <= #Tp 1'b0;
neg_edge <= #Tp 1'b0;
end
else
begin
pos_edge <= #Tp (enable && !clk_out && cnt_one) || (!(|divider) && clk_out) || (!(|divider) && go && !enable);
neg_edge <= #Tp (enable && clk_out && cnt_one) || (!(|divider) && !clk_out && enable);
end
end
endmodule
|
(***********************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA-Rocquencourt & LRI-CNRS-Orsay *)
(* \VV/ *************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(***********************************************************************)
(**************************************************************)
(* MSetDecide.v *)
(* *)
(* Author: Aaron Bohannon *)
(**************************************************************)
(** This file implements a decision procedure for a certain
class of propositions involving finite sets. *)
Require Import Decidable Setoid DecidableTypeEx MSetFacts.
(** First, a version for Weak Sets in functorial presentation *)
Module WDecideOn (E : DecidableType)(Import M : WSetsOn E).
Module F := MSetFacts.WFactsOn E M.
(** * Overview
This functor defines the tactic [fsetdec], which will
solve any valid goal of the form
<<
forall s1 ... sn,
forall x1 ... xm,
P1 -> ... -> Pk -> P
>>
where [P]'s are defined by the grammar:
<<
P ::=
| Q
| Empty F
| Subset F F'
| Equal F F'
Q ::=
| E.eq X X'
| In X F
| Q /\ Q'
| Q \/ Q'
| Q -> Q'
| Q <-> Q'
| ~ Q
| True
| False
F ::=
| S
| empty
| singleton X
| add X F
| remove X F
| union F F'
| inter F F'
| diff F F'
X ::= x1 | ... | xm
S ::= s1 | ... | sn
>>
The tactic will also work on some goals that vary slightly from
the above form:
- The variables and hypotheses may be mixed in any order and may
have already been introduced into the context. Moreover,
there may be additional, unrelated hypotheses mixed in (these
will be ignored).
- A conjunction of hypotheses will be handled as easily as
separate hypotheses, i.e., [P1 /\ P2 -> P] can be solved iff
[P1 -> P2 -> P] can be solved.
- [fsetdec] should solve any goal if the MSet-related hypotheses
are contradictory.
- [fsetdec] will first perform any necessary zeta and beta
reductions and will invoke [subst] to eliminate any Coq
equalities between finite sets or their elements.
- If [E.eq] is convertible with Coq's equality, it will not
matter which one is used in the hypotheses or conclusion.
- The tactic can solve goals where the finite sets or set
elements are expressed by Coq terms that are more complicated
than variables. However, non-local definitions are not
expanded, and Coq equalities between non-variable terms are
not used. For example, this goal will be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2)
>>
This one will not be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2)
>>
*)
(** * Facts and Tactics for Propositional Logic
These lemmas and tactics are in a module so that they do
not affect the namespace if you import the enclosing
module [Decide]. *)
Module MSetLogicalFacts.
Export Decidable.
Export Setoid.
(** ** Lemmas and Tactics About Decidable Propositions *)
(** ** Propositional Equivalences Involving Negation
These are all written with the unfolded form of
negation, since I am not sure if setoid rewriting will
always perform conversion. *)
(** ** Tactics for Negations *)
Tactic Notation "fold" "any" "not" :=
repeat (
match goal with
| H: context [?P -> False] |- _ =>
fold (~ P) in H
| |- context [?P -> False] =>
fold (~ P)
end).
(** [push not using db] will pushes all negations to the
leaves of propositions in the goal, using the lemmas in
[db] to assist in checking the decidability of the
propositions involved. If [using db] is omitted, then
[core] will be used. Additional versions are provided
to manipulate the hypotheses or the hypotheses and goal
together.
XXX: This tactic and the similar subsequent ones should
have been defined using [autorewrite]. However, dealing
with multiples rewrite sites and side-conditions is
done more cleverly with the following explicit
analysis of goals. *)
Ltac or_not_l_iff P Q tac :=
(rewrite (or_not_l_iff_1 P Q) by tac) ||
(rewrite (or_not_l_iff_2 P Q) by tac).
Ltac or_not_r_iff P Q tac :=
(rewrite (or_not_r_iff_1 P Q) by tac) ||
(rewrite (or_not_r_iff_2 P Q) by tac).
Ltac or_not_l_iff_in P Q H tac :=
(rewrite (or_not_l_iff_1 P Q) in H by tac) ||
(rewrite (or_not_l_iff_2 P Q) in H by tac).
Ltac or_not_r_iff_in P Q H tac :=
(rewrite (or_not_r_iff_1 P Q) in H by tac) ||
(rewrite (or_not_r_iff_2 P Q) in H by tac).
Tactic Notation "push" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [?P \/ ?Q -> False] => rewrite (not_or_iff P Q)
| |- context [?P /\ ?Q -> False] => rewrite (not_and_iff P Q)
| |- context [(?P -> ?Q) -> False] => rewrite (not_imp_iff P Q) by dec
end);
fold any not.
Tactic Notation "push" "not" :=
push not using core.
Tactic Notation
"push" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [?P \/ ?Q -> False] |- _ => rewrite (not_or_iff P Q) in H
| H: context [?P /\ ?Q -> False] |- _ => rewrite (not_and_iff P Q) in H
| H: context [(?P -> ?Q) -> False] |- _ =>
rewrite (not_imp_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "push" "not" "in" "*" "|-" :=
push not in * |- using core.
Tactic Notation "push" "not" "in" "*" "using" ident(db) :=
push not using db; push not in * |- using db.
Tactic Notation "push" "not" "in" "*" :=
push not in * using core.
(** A simple test case to see how this works. *)
Lemma test_push : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ ((R -> P) \/ (Q -> R))) ->
(~ (P /\ R)) ->
(~ (P -> R)) ->
True.
Proof.
intros. push not in *.
(* note that ~(R->P) remains (since R isnt decidable) *)
tauto.
Qed.
(** [pull not using db] will pull as many negations as
possible toward the top of the propositions in the goal,
using the lemmas in [db] to assist in checking the
decidability of the propositions involved. If [using
db] is omitted, then [core] will be used. Additional
versions are provided to manipulate the hypotheses or
the hypotheses and goal together. *)
Tactic Notation "pull" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [(?P -> False) /\ (?Q -> False)] =>
rewrite <- (not_or_iff P Q)
| |- context [?P -> ?Q -> False] => rewrite <- (not_and_iff P Q)
| |- context [?P /\ (?Q -> False)] => rewrite <- (not_imp_iff P Q) by dec
| |- context [(?Q -> False) /\ ?P] =>
rewrite <- (not_imp_rev_iff P Q) by dec
end);
fold any not.
Tactic Notation "pull" "not" :=
pull not using core.
Tactic Notation
"pull" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
rewrite <- (not_or_iff P Q) in H
| H: context [?P -> ?Q -> False] |- _ =>
rewrite <- (not_and_iff P Q) in H
| H: context [?P /\ (?Q -> False)] |- _ =>
rewrite <- (not_imp_iff P Q) in H by dec
| H: context [(?Q -> False) /\ ?P] |- _ =>
rewrite <- (not_imp_rev_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "pull" "not" "in" "*" "|-" :=
pull not in * |- using core.
Tactic Notation "pull" "not" "in" "*" "using" ident(db) :=
pull not using db; pull not in * |- using db.
Tactic Notation "pull" "not" "in" "*" :=
pull not in * using core.
(** A simple test case to see how this works. *)
Lemma test_pull : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ (R -> P) /\ ~ (Q -> R)) ->
(~ P \/ ~ R) ->
(P /\ ~ R) ->
(~ R /\ P) ->
True.
Proof.
intros. pull not in *. tauto.
Qed.
End MSetLogicalFacts.
Import MSetLogicalFacts.
(** * Auxiliary Tactics
Again, these lemmas and tactics are in a module so that
they do not affect the namespace if you import the
enclosing module [Decide]. *)
Module MSetDecideAuxiliary.
(** ** Generic Tactics
We begin by defining a few generic, useful tactics. *)
(** remove logical hypothesis inter-dependencies (fix #2136). *)
Ltac no_logical_interdep :=
match goal with
| H : ?P |- _ =>
match type of P with
| Prop =>
match goal with H' : context [ H ] |- _ => clear dependent H' end
| _ => fail
end; no_logical_interdep
| _ => idtac
end.
(** [if t then t1 else t2] executes [t] and, if it does not
fail, then [t1] will be applied to all subgoals
produced. If [t] fails, then [t2] is executed. *)
Tactic Notation
"if" tactic(t)
"then" tactic(t1)
"else" tactic(t2) :=
first [ t; first [ t1 | fail 2 ] | t2 ].
Ltac abstract_term t :=
if (is_var t) then fail "no need to abstract a variable"
else (let x := fresh "x" in set (x := t) in *; try clearbody x).
Ltac abstract_elements :=
repeat
(match goal with
| |- context [ singleton ?t ] => abstract_term t
| _ : context [ singleton ?t ] |- _ => abstract_term t
| |- context [ add ?t _ ] => abstract_term t
| _ : context [ add ?t _ ] |- _ => abstract_term t
| |- context [ remove ?t _ ] => abstract_term t
| _ : context [ remove ?t _ ] |- _ => abstract_term t
| |- context [ In ?t _ ] => abstract_term t
| _ : context [ In ?t _ ] |- _ => abstract_term t
end).
(** [prop P holds by t] succeeds (but does not modify the
goal or context) if the proposition [P] can be proved by
[t] in the current context. Otherwise, the tactic
fails. *)
Tactic Notation "prop" constr(P) "holds" "by" tactic(t) :=
let H := fresh in
assert P as H by t;
clear H.
(** This tactic acts just like [assert ... by ...] but will
fail if the context already contains the proposition. *)
Tactic Notation "assert" "new" constr(e) "by" tactic(t) :=
match goal with
| H: e |- _ => fail 1
| _ => assert e by t
end.
(** [subst++] is similar to [subst] except that
- it never fails (as [subst] does on recursive
equations),
- it substitutes locally defined variable for their
definitions,
- it performs beta reductions everywhere, which may
arise after substituting a locally defined function
for its definition.
*)
Tactic Notation "subst" "++" :=
repeat (
match goal with
| x : _ |- _ => subst x
end);
cbv zeta beta in *.
(** [decompose records] calls [decompose record H] on every
relevant hypothesis [H]. *)
Tactic Notation "decompose" "records" :=
repeat (
match goal with
| H: _ |- _ => progress (decompose record H); clear H
end).
(** ** Discarding Irrelevant Hypotheses
We will want to clear the context of any
non-MSet-related hypotheses in order to increase the
speed of the tactic. To do this, we will need to be
able to decide which are relevant. We do this by making
a simple inductive definition classifying the
propositions of interest. *)
Inductive MSet_elt_Prop : Prop -> Prop :=
| eq_Prop : forall (S : Type) (x y : S),
MSet_elt_Prop (x = y)
| eq_elt_prop : forall x y,
MSet_elt_Prop (E.eq x y)
| In_elt_prop : forall x s,
MSet_elt_Prop (In x s)
| True_elt_prop :
MSet_elt_Prop True
| False_elt_prop :
MSet_elt_Prop False
| conj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P /\ Q)
| disj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P \/ Q)
| impl_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P -> Q)
| not_elt_prop : forall P,
MSet_elt_Prop P ->
MSet_elt_Prop (~ P).
Inductive MSet_Prop : Prop -> Prop :=
| elt_MSet_Prop : forall P,
MSet_elt_Prop P ->
MSet_Prop P
| Empty_MSet_Prop : forall s,
MSet_Prop (Empty s)
| Subset_MSet_Prop : forall s1 s2,
MSet_Prop (Subset s1 s2)
| Equal_MSet_Prop : forall s1 s2,
MSet_Prop (Equal s1 s2).
(** Here is the tactic that will throw away hypotheses that
are not useful (for the intended scope of the [fsetdec]
tactic). *)
Hint Constructors MSet_elt_Prop MSet_Prop : MSet_Prop.
Ltac discard_nonMSet :=
repeat (
match goal with
| H : context [ @Logic.eq ?T ?x ?y ] |- _ =>
if (change T with E.t in H) then fail
else if (change T with t in H) then fail
else clear H
| H : ?P |- _ =>
if prop (MSet_Prop P) holds by
(auto 100 with MSet_Prop)
then fail
else clear H
end).
(** ** Turning Set Operators into Propositional Connectives
The lemmas from [MSetFacts] will be used to break down
set operations into propositional formulas built over
the predicates [In] and [E.eq] applied only to
variables. We are going to use them with [autorewrite].
*)
Hint Rewrite
F.empty_iff F.singleton_iff F.add_iff F.remove_iff
F.union_iff F.inter_iff F.diff_iff
: set_simpl.
Lemma eq_refl_iff (x : E.t) : E.eq x x <-> True.
Proof.
now split.
Qed.
Hint Rewrite eq_refl_iff : set_eq_simpl.
(** ** Decidability of MSet Propositions *)
(** [In] is decidable. *)
Lemma dec_In : forall x s,
decidable (In x s).
Proof.
red; intros; generalize (F.mem_iff s x); case (mem x s); intuition.
Qed.
(** [E.eq] is decidable. *)
Lemma dec_eq : forall (x y : E.t),
decidable (E.eq x y).
Proof.
red; intros x y; destruct (E.eq_dec x y); auto.
Qed.
(** The hint database [MSet_decidability] will be given to
the [push_neg] tactic from the module [Negation]. *)
Hint Resolve dec_In dec_eq : MSet_decidability.
(** ** Normalizing Propositions About Equality
We have to deal with the fact that [E.eq] may be
convertible with Coq's equality. Thus, we will find the
following tactics useful to replace one form with the
other everywhere. *)
(** The next tactic, [Logic_eq_to_E_eq], mentions the term
[E.t]; thus, we must ensure that [E.t] is used in favor
of any other convertible but syntactically distinct
term. *)
Ltac change_to_E_t :=
repeat (
match goal with
| H : ?T |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
| H : forall x : ?T, _ |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
end).
(** These two tactics take us from Coq's built-in equality
to [E.eq] (and vice versa) when possible. *)
Ltac Logic_eq_to_E_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change (@Logic.eq E.t) with E.eq in H)
| |- _ =>
progress (change (@Logic.eq E.t) with E.eq)
end).
Ltac E_eq_to_Logic_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change E.eq with (@Logic.eq E.t) in H)
| |- _ =>
progress (change E.eq with (@Logic.eq E.t))
end).
(** This tactic works like the built-in tactic [subst], but
at the level of set element equality (which may not be
the convertible with Coq's equality). *)
Ltac substMSet :=
repeat (
match goal with
| H: E.eq ?x ?x |- _ => clear H
| H: E.eq ?x ?y |- _ => rewrite H in *; clear H
end);
autorewrite with set_eq_simpl in *.
(** ** Considering Decidability of Base Propositions
This tactic adds assertions about the decidability of
[E.eq] and [In] to the context. This is necessary for
the completeness of the [fsetdec] tactic. However, in
order to minimize the cost of proof search, we should be
careful to not add more than we need. Once negations
have been pushed to the leaves of the propositions, we
only need to worry about decidability for those base
propositions that appear in a negated form. *)
Ltac assert_decidability :=
(** We actually don't want these rules to fire if the
syntactic context in the patterns below is trivially
empty, but we'll just do some clean-up at the
afterward. *)
repeat (
match goal with
| H: context [~ E.eq ?x ?y] |- _ =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| H: context [~ In ?x ?s] |- _ =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
| |- context [~ E.eq ?x ?y] =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| |- context [~ In ?x ?s] =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
end);
(** Now we eliminate the useless facts we added (because
they would likely be very harmful to performance). *)
repeat (
match goal with
| _: ~ ?P, H : ?P \/ ~ ?P |- _ => clear H
end).
(** ** Handling [Empty], [Subset], and [Equal]
This tactic instantiates universally quantified
hypotheses (which arise from the unfolding of [Empty],
[Subset], and [Equal]) for each of the set element
expressions that is involved in some membership or
equality fact. Then it throws away those hypotheses,
which should no longer be needed. *)
Ltac inst_MSet_hypotheses :=
repeat (
match goal with
| H : forall a : E.t, _,
_ : context [ In ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ In ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq _ ?x ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq _ ?x ] =>
let P := type of (H x) in
assert new P by (exact (H x))
end);
repeat (
match goal with
| H : forall a : E.t, _ |- _ =>
clear H
end).
(** ** The Core [fsetdec] Auxiliary Tactics *)
(** Here is the crux of the proof search. Recursion through
[intuition]! (This will terminate if I correctly
understand the behavior of [intuition].) *)
Ltac fsetdec_rec := progress substMSet; intuition fsetdec_rec.
(** If we add [unfold Empty, Subset, Equal in *; intros;] to
the beginning of this tactic, it will satisfy the same
specification as the [fsetdec] tactic; however, it will
be much slower than necessary without the pre-processing
done by the wrapper tactic [fsetdec]. *)
Ltac fsetdec_body :=
autorewrite with set_eq_simpl in *;
inst_MSet_hypotheses;
autorewrite with set_simpl set_eq_simpl in *;
push not in * using MSet_decidability;
substMSet;
assert_decidability;
auto;
(intuition fsetdec_rec) ||
fail 1
"because the goal is beyond the scope of this tactic".
End MSetDecideAuxiliary.
Import MSetDecideAuxiliary.
(** * The [fsetdec] Tactic
Here is the top-level tactic (the only one intended for
clients of this library). It's specification is given at
the top of the file. *)
Ltac fsetdec :=
(** We first unfold any occurrences of [iff]. *)
unfold iff in *;
(** We fold occurrences of [not] because it is better for
[intros] to leave us with a goal of [~ P] than a goal of
[False]. *)
fold any not; intros;
(** We don't care about the value of elements : complex ones are
abstracted as new variables (avoiding potential dependencies,
see bug #2464) *)
abstract_elements;
(** We remove dependencies to logical hypothesis. This way,
later "clear" will work nicely (see bug #2136) *)
no_logical_interdep;
(** Now we decompose conjunctions, which will allow the
[discard_nonMSet] and [assert_decidability] tactics to
do a much better job. *)
decompose records;
discard_nonMSet;
(** We unfold these defined propositions on finite sets. If
our goal was one of them, then have one more item to
introduce now. *)
unfold Empty, Subset, Equal in *; intros;
(** We now want to get rid of all uses of [=] in favor of
[E.eq]. However, the best way to eliminate a [=] is in
the context is with [subst], so we will try that first.
In fact, we may as well convert uses of [E.eq] into [=]
when possible before we do [subst] so that we can even
more mileage out of it. Then we will convert all
remaining uses of [=] back to [E.eq] when possible. We
use [change_to_E_t] to ensure that we have a canonical
name for set elements, so that [Logic_eq_to_E_eq] will
work properly. *)
change_to_E_t; E_eq_to_Logic_eq; subst++; Logic_eq_to_E_eq;
(** The next optimization is to swap a negated goal with a
negated hypothesis when possible. Any swap will improve
performance by eliminating the total number of
negations, but we will get the maximum benefit if we
swap the goal with a hypotheses mentioning the same set
element, so we try that first. If we reach the fourth
branch below, we attempt any swap. However, to maintain
completeness of this tactic, we can only perform such a
swap with a decidable proposition; hence, we first test
whether the hypothesis is an [MSet_elt_Prop], noting
that any [MSet_elt_Prop] is decidable. *)
pull not using MSet_decidability;
unfold not in *;
match goal with
| H: (In ?x ?r) -> False |- (In ?x ?s) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
contradict H; fsetdec_body
| H: ?P -> False |- ?Q -> False =>
if prop (MSet_elt_Prop P) holds by
(auto 100 with MSet_Prop)
then (contradict H; fsetdec_body)
else fsetdec_body
| |- _ =>
fsetdec_body
end.
(** * Examples *)
Module MSetDecideTestCases.
Lemma test_eq_trans_1 : forall x y z s,
E.eq x y ->
~ ~ E.eq z y ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_trans_2 : forall x y z r s,
In x (singleton y) ->
~ In z r ->
~ ~ In z (add y r) ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_1 : forall w x y z s,
E.eq x w ->
~ ~ E.eq x y ->
~ E.eq y z ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_2 : forall w x y z r1 r2 s,
In x (singleton w) ->
~ In x r1 ->
In x (add y r1) ->
In y r2 ->
In y (remove z r2) ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_In_singleton : forall x,
In x (singleton x).
Proof. fsetdec. Qed.
Lemma test_add_In : forall x y s,
In x (add y s) ->
~ E.eq x y ->
In x s.
Proof. fsetdec. Qed.
Lemma test_Subset_add_remove : forall x s,
s [<=] (add x (remove x s)).
Proof. fsetdec. Qed.
Lemma test_eq_disjunction : forall w x y z,
In w (add x (add y (singleton z))) ->
E.eq w x \/ E.eq w y \/ E.eq w z.
Proof. fsetdec. Qed.
Lemma test_not_In_disj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ (In x s1 \/ In x s4 \/ E.eq y x).
Proof. fsetdec. Qed.
Lemma test_not_In_conj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ In x s1 /\ ~ In x s4 /\ ~ E.eq y x.
Proof. fsetdec. Qed.
Lemma test_iff_conj : forall a x s s',
(In a s' <-> E.eq x a \/ In a s) ->
(In a s' <-> In a (add x s)).
Proof. fsetdec. Qed.
Lemma test_set_ops_1 : forall x q r s,
(singleton x) [<=] s ->
Empty (union q r) ->
Empty (inter (diff s q) (diff s r)) ->
~ In x s.
Proof. fsetdec. Qed.
Lemma eq_chain_test : forall x1 x2 x3 x4 s1 s2 s3 s4,
Empty s1 ->
In x2 (add x1 s1) ->
In x3 s2 ->
~ In x3 (remove x2 s2) ->
~ In x4 s3 ->
In x4 (add x3 s3) ->
In x1 s4 ->
Subset (add x4 s4) s4.
Proof. fsetdec. Qed.
Lemma test_too_complex : forall x y z r s,
E.eq x y ->
(In x (singleton y) -> r [<=] s) ->
In z r ->
In z s.
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until s; intros Heq H Hr; lapply H; fsetdec.
Qed.
Lemma function_test_1 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2).
Proof. fsetdec. Qed.
Lemma function_test_2 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2).
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until 3. intros g_eq. rewrite <- g_eq. fsetdec.
Qed.
Lemma test_baydemir :
forall (f : t -> t),
forall (s : t),
forall (x y : elt),
In x (add y (f s)) ->
~ E.eq x y ->
In x (f s).
Proof.
fsetdec.
Qed.
End MSetDecideTestCases.
End WDecideOn.
Require Import MSetInterface.
(** Now comes variants for self-contained weak sets and for full sets.
For these variants, only one argument is necessary. Thanks to
the subtyping [WS<=S], the [Decide] functor which is meant to be
used on modules [(M:S)] can simply be an alias of [WDecide]. *)
Module WDecide (M:WSets) := !WDecideOn M.E M.
Module Decide := WDecide.
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// Very simple test for interface pathclearing
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(2) itopa();
ifc #(4) itopb();
sub ca (.isub(itopa),
.clk);
sub cb (.isub(itopb),
.clk);
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d result=%b %b\n",$time, cyc, itopa.valueo, itopb.valueo);
`endif
cyc <= cyc + 1;
itopa.valuei <= cyc[1:0];
itopb.valuei <= cyc[3:0];
if (cyc==1) begin
if (itopa.WIDTH != 2) $stop;
if (itopb.WIDTH != 4) $stop;
if ($bits(itopa.valueo) != 2) $stop;
if ($bits(itopb.valueo) != 4) $stop;
if ($bits(itopa.out_modport.valueo) != 2) $stop;
if ($bits(itopb.out_modport.valueo) != 4) $stop;
end
if (cyc==4) begin
if (itopa.valueo != 2'b11) $stop;
if (itopb.valueo != 4'b0011) $stop;
end
if (cyc==5) begin
if (itopa.valueo != 2'b00) $stop;
if (itopb.valueo != 4'b0100) $stop;
end
if (cyc==20) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
interface ifc
#(parameter WIDTH = 1);
// verilator lint_off MULTIDRIVEN
logic [WIDTH-1:0] valuei;
logic [WIDTH-1:0] valueo;
// verilator lint_on MULTIDRIVEN
modport out_modport (input valuei, output valueo);
endinterface
// Note not parameterized
module sub
(
ifc.out_modport isub,
input clk
);
always @(posedge clk) isub.valueo <= isub.valuei + 1;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// Very simple test for interface pathclearing
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(2) itopa();
ifc #(4) itopb();
sub ca (.isub(itopa),
.clk);
sub cb (.isub(itopb),
.clk);
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d result=%b %b\n",$time, cyc, itopa.valueo, itopb.valueo);
`endif
cyc <= cyc + 1;
itopa.valuei <= cyc[1:0];
itopb.valuei <= cyc[3:0];
if (cyc==1) begin
if (itopa.WIDTH != 2) $stop;
if (itopb.WIDTH != 4) $stop;
if ($bits(itopa.valueo) != 2) $stop;
if ($bits(itopb.valueo) != 4) $stop;
if ($bits(itopa.out_modport.valueo) != 2) $stop;
if ($bits(itopb.out_modport.valueo) != 4) $stop;
end
if (cyc==4) begin
if (itopa.valueo != 2'b11) $stop;
if (itopb.valueo != 4'b0011) $stop;
end
if (cyc==5) begin
if (itopa.valueo != 2'b00) $stop;
if (itopb.valueo != 4'b0100) $stop;
end
if (cyc==20) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
interface ifc
#(parameter WIDTH = 1);
// verilator lint_off MULTIDRIVEN
logic [WIDTH-1:0] valuei;
logic [WIDTH-1:0] valueo;
// verilator lint_on MULTIDRIVEN
modport out_modport (input valuei, output valueo);
endinterface
// Note not parameterized
module sub
(
ifc.out_modport isub,
input clk
);
always @(posedge clk) isub.valueo <= isub.valuei + 1;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// Very simple test for interface pathclearing
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(2) itopa();
ifc #(4) itopb();
sub ca (.isub(itopa),
.clk);
sub cb (.isub(itopb),
.clk);
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d result=%b %b\n",$time, cyc, itopa.valueo, itopb.valueo);
`endif
cyc <= cyc + 1;
itopa.valuei <= cyc[1:0];
itopb.valuei <= cyc[3:0];
if (cyc==1) begin
if (itopa.WIDTH != 2) $stop;
if (itopb.WIDTH != 4) $stop;
if ($bits(itopa.valueo) != 2) $stop;
if ($bits(itopb.valueo) != 4) $stop;
if ($bits(itopa.out_modport.valueo) != 2) $stop;
if ($bits(itopb.out_modport.valueo) != 4) $stop;
end
if (cyc==4) begin
if (itopa.valueo != 2'b11) $stop;
if (itopb.valueo != 4'b0011) $stop;
end
if (cyc==5) begin
if (itopa.valueo != 2'b00) $stop;
if (itopb.valueo != 4'b0100) $stop;
end
if (cyc==20) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
interface ifc
#(parameter WIDTH = 1);
// verilator lint_off MULTIDRIVEN
logic [WIDTH-1:0] valuei;
logic [WIDTH-1:0] valueo;
// verilator lint_on MULTIDRIVEN
modport out_modport (input valuei, output valueo);
endinterface
// Note not parameterized
module sub
(
ifc.out_modport isub,
input clk
);
always @(posedge clk) isub.valueo <= isub.valuei + 1;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// Very simple test for interface pathclearing
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(2) itopa();
ifc #(4) itopb();
sub ca (.isub(itopa),
.clk);
sub cb (.isub(itopb),
.clk);
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d result=%b %b\n",$time, cyc, itopa.valueo, itopb.valueo);
`endif
cyc <= cyc + 1;
itopa.valuei <= cyc[1:0];
itopb.valuei <= cyc[3:0];
if (cyc==1) begin
if (itopa.WIDTH != 2) $stop;
if (itopb.WIDTH != 4) $stop;
if ($bits(itopa.valueo) != 2) $stop;
if ($bits(itopb.valueo) != 4) $stop;
if ($bits(itopa.out_modport.valueo) != 2) $stop;
if ($bits(itopb.out_modport.valueo) != 4) $stop;
end
if (cyc==4) begin
if (itopa.valueo != 2'b11) $stop;
if (itopb.valueo != 4'b0011) $stop;
end
if (cyc==5) begin
if (itopa.valueo != 2'b00) $stop;
if (itopb.valueo != 4'b0100) $stop;
end
if (cyc==20) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
interface ifc
#(parameter WIDTH = 1);
// verilator lint_off MULTIDRIVEN
logic [WIDTH-1:0] valuei;
logic [WIDTH-1:0] valueo;
// verilator lint_on MULTIDRIVEN
modport out_modport (input valuei, output valueo);
endinterface
// Note not parameterized
module sub
(
ifc.out_modport isub,
input clk
);
always @(posedge clk) isub.valueo <= isub.valuei + 1;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// Very simple test for interface pathclearing
`ifdef VCS
`define UNSUPPORTED_MOD_IN_GENS
`endif
`ifdef VERILATOR
`define UNSUPPORTED_MOD_IN_GENS
`endif
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(1) itopa();
ifc #(2) itopb();
sub #(1) ca (.isub(itopa),
.i_value(4));
sub #(2) cb (.isub(itopb),
.i_value(5));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==1) begin
if (itopa.MODE != 1) $stop;
if (itopb.MODE != 2) $stop;
end
if (cyc==20) begin
if (itopa.get_value() != 4) $stop;
if (itopb.get_value() != 5) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module sub
#(parameter MODE = 0)
(
ifc.out_modport isub,
input integer i_value
);
`ifdef UNSUPPORTED_MOD_IN_GENS
always @* isub.value = i_value;
`else
generate if (MODE == 1) begin
always @* isub.valuea = i_value;
end
else if (MODE == 2) begin
always @* isub.valueb = i_value;
end
endgenerate
`endif
endmodule
interface ifc;
parameter MODE = 0;
// Modports under generates not supported by all commercial simulators
`ifdef UNSUPPORTED_MOD_IN_GENS
integer value;
modport out_modport (output value);
function integer get_value(); return value; endfunction
`else
generate if (MODE == 0) begin
integer valuea;
modport out_modport (output valuea);
function integer get_valuea(); return valuea; endfunction
end
else begin
integer valueb;
modport out_modport (output valueb);
function integer get_valueb(); return valueb; endfunction
end
endgenerate
`endif
endinterface
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// Very simple test for interface pathclearing
`ifdef VCS
`define UNSUPPORTED_MOD_IN_GENS
`endif
`ifdef VERILATOR
`define UNSUPPORTED_MOD_IN_GENS
`endif
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(1) itopa();
ifc #(2) itopb();
sub #(1) ca (.isub(itopa),
.i_value(4));
sub #(2) cb (.isub(itopb),
.i_value(5));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==1) begin
if (itopa.MODE != 1) $stop;
if (itopb.MODE != 2) $stop;
end
if (cyc==20) begin
if (itopa.get_value() != 4) $stop;
if (itopb.get_value() != 5) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module sub
#(parameter MODE = 0)
(
ifc.out_modport isub,
input integer i_value
);
`ifdef UNSUPPORTED_MOD_IN_GENS
always @* isub.value = i_value;
`else
generate if (MODE == 1) begin
always @* isub.valuea = i_value;
end
else if (MODE == 2) begin
always @* isub.valueb = i_value;
end
endgenerate
`endif
endmodule
interface ifc;
parameter MODE = 0;
// Modports under generates not supported by all commercial simulators
`ifdef UNSUPPORTED_MOD_IN_GENS
integer value;
modport out_modport (output value);
function integer get_value(); return value; endfunction
`else
generate if (MODE == 0) begin
integer valuea;
modport out_modport (output valuea);
function integer get_valuea(); return valuea; endfunction
end
else begin
integer valueb;
modport out_modport (output valueb);
function integer get_valueb(); return valueb; endfunction
end
endgenerate
`endif
endinterface
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// Very simple test for interface pathclearing
`ifdef VCS
`define UNSUPPORTED_MOD_IN_GENS
`endif
`ifdef VERILATOR
`define UNSUPPORTED_MOD_IN_GENS
`endif
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(1) itopa();
ifc #(2) itopb();
sub #(1) ca (.isub(itopa),
.i_value(4));
sub #(2) cb (.isub(itopb),
.i_value(5));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==1) begin
if (itopa.MODE != 1) $stop;
if (itopb.MODE != 2) $stop;
end
if (cyc==20) begin
if (itopa.get_value() != 4) $stop;
if (itopb.get_value() != 5) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module sub
#(parameter MODE = 0)
(
ifc.out_modport isub,
input integer i_value
);
`ifdef UNSUPPORTED_MOD_IN_GENS
always @* isub.value = i_value;
`else
generate if (MODE == 1) begin
always @* isub.valuea = i_value;
end
else if (MODE == 2) begin
always @* isub.valueb = i_value;
end
endgenerate
`endif
endmodule
interface ifc;
parameter MODE = 0;
// Modports under generates not supported by all commercial simulators
`ifdef UNSUPPORTED_MOD_IN_GENS
integer value;
modport out_modport (output value);
function integer get_value(); return value; endfunction
`else
generate if (MODE == 0) begin
integer valuea;
modport out_modport (output valuea);
function integer get_valuea(); return valuea; endfunction
end
else begin
integer valueb;
modport out_modport (output valueb);
function integer get_valueb(); return valueb; endfunction
end
endgenerate
`endif
endinterface
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// testbench for lp20khz_1MSa_iir_filter
`include "lp20khz_1MSa_iir_filter.v"
`define FIN "tb_tmp/data.in"
`define FOUT "tb_tmp/data.filtered"
module lp20khz_1MSa_iir_filter_tb;
integer fin, fout, r;
reg clk;
reg [7:0] adc_d;
wire data_rdy;
wire [7:0] adc_filtered;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout = $fopen(`FOUT, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
always @(posedge clk)
if (data_rdy) begin
if ($time > 1)
r = $fputc(adc_filtered, fout);
if (!$feof(fin))
adc_d <= $fgetc(fin);
else begin
$fclose(fin);
$fclose(fout);
$finish;
end
end
// module to test
lp20khz_1MSa_iir_filter filter(clk, adc_d, data_rdy, adc_filtered);
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// testbench for lp20khz_1MSa_iir_filter
`include "lp20khz_1MSa_iir_filter.v"
`define FIN "tb_tmp/data.in"
`define FOUT "tb_tmp/data.filtered"
module lp20khz_1MSa_iir_filter_tb;
integer fin, fout, r;
reg clk;
reg [7:0] adc_d;
wire data_rdy;
wire [7:0] adc_filtered;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout = $fopen(`FOUT, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
always @(posedge clk)
if (data_rdy) begin
if ($time > 1)
r = $fputc(adc_filtered, fout);
if (!$feof(fin))
adc_d <= $fgetc(fin);
else begin
$fclose(fin);
$fclose(fout);
$finish;
end
end
// module to test
lp20khz_1MSa_iir_filter filter(clk, adc_d, data_rdy, adc_filtered);
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// testbench for lp20khz_1MSa_iir_filter
`include "lp20khz_1MSa_iir_filter.v"
`define FIN "tb_tmp/data.in"
`define FOUT "tb_tmp/data.filtered"
module lp20khz_1MSa_iir_filter_tb;
integer fin, fout, r;
reg clk;
reg [7:0] adc_d;
wire data_rdy;
wire [7:0] adc_filtered;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout = $fopen(`FOUT, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
always @(posedge clk)
if (data_rdy) begin
if ($time > 1)
r = $fputc(adc_filtered, fout);
if (!$feof(fin))
adc_d <= $fgetc(fin);
else begin
$fclose(fin);
$fclose(fout);
$finish;
end
end
// module to test
lp20khz_1MSa_iir_filter filter(clk, adc_d, data_rdy, adc_filtered);
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// testbench for lp20khz_1MSa_iir_filter
`include "lp20khz_1MSa_iir_filter.v"
`define FIN "tb_tmp/data.in"
`define FOUT "tb_tmp/data.filtered"
module lp20khz_1MSa_iir_filter_tb;
integer fin, fout, r;
reg clk;
reg [7:0] adc_d;
wire data_rdy;
wire [7:0] adc_filtered;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout = $fopen(`FOUT, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
always @(posedge clk)
if (data_rdy) begin
if ($time > 1)
r = $fputc(adc_filtered, fout);
if (!$feof(fin))
adc_d <= $fgetc(fin);
else begin
$fclose(fin);
$fclose(fout);
$finish;
end
end
// module to test
lp20khz_1MSa_iir_filter filter(clk, adc_d, data_rdy, adc_filtered);
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire pick1 = crc[0];
wire [13:0][1:0] data1 = crc[27+1:1];
wire [3:0][2:0][1:0] data2 = crc[23+29:29];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [15:0] [1:0] datao; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.datao (datao/*[15:0][1:0]*/),
// Inputs
.pick1 (pick1),
.data1 (data1/*[13:0][1:0]*/),
.data2 (data2/*[2:0][3:0][1:0]*/));
// Aggregate outputs into a single result vector
wire [63:0] result = {32'h0, datao};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h3ff4bf0e6407b281
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test
(
input logic pick1,
input logic [13:0] [1:0] data1, // 14 x 2 = 28 bits
input logic [ 3:0] [2:0] [1:0] data2, // 4 x 3 x 2 = 24 bits
output logic [15:0] [1:0] datao // 16 x 2 = 32 bits
);
// verilator lint_off WIDTH
always_comb datao[13: 0] // 28 bits
= (pick1)
? {data1} // 28 bits
: {'0, data2}; // 25-28 bits, perhaps not legal as '0 is unsized
// verilator lint_on WIDTH
always_comb datao[15:14] = '0;
endmodule
|
/*
*******************************************************************************
*
* FIFO Generator - Verilog Behavioral Model
*
*******************************************************************************
*
* (c) Copyright 1995 - 2009 Xilinx, Inc. All rights reserved.
*
* This file contains confidential and proprietary information
* of Xilinx, Inc. and is protected under U.S. and
* international copyright and other intellectual property
* laws.
*
* DISCLAIMER
* This disclaimer is not a license and does not grant any
* rights to the materials distributed herewith. Except as
* otherwise provided in a valid license issued to you by
* Xilinx, and to the maximum extent permitted by applicable
* law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
* WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
* AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
* BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
* INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
* (2) Xilinx shall not be liable (whether in contract or tort,
* including negligence, or under any other theory of
* liability) for any loss or damage of any kind or nature
* related to, arising under or in connection with these
* materials, including for any direct, or any indirect,
* special, incidental, or consequential loss or damage
* (including loss of data, profits, goodwill, or any type of
* loss or damage suffered as a result of any action brought
* by a third party) even if such damage or loss was
* reasonably foreseeable or Xilinx had been advised of the
* possibility of the same.
*
* CRITICAL APPLICATIONS
* Xilinx products are not designed or intended to be fail-
* safe, or for use in any application requiring fail-safe
* performance, such as life-support or safety devices or
* systems, Class III medical devices, nuclear facilities,
* applications related to the deployment of airbags, or any
* other applications that could lead to death, personal
* injury, or severe property or environmental damage
* (individually and collectively, "Critical
* Applications"). Customer assumes the sole risk and
* liability of any use of Xilinx products in Critical
* Applications, subject only to applicable laws and
* regulations governing limitations on product liability.
*
* THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
* PART OF THIS FILE AT ALL TIMES.
*
*******************************************************************************
*******************************************************************************
*
* Filename: fifo_generator_vlog_beh.v
*
* Author : Xilinx
*
*******************************************************************************
* Structure:
*
* fifo_generator_vlog_beh.v
* |
* +-fifo_generator_v12_0_bhv_ver_as
* |
* +-fifo_generator_v12_0_bhv_ver_ss
* |
* +-fifo_generator_v12_0_bhv_ver_preload0
*
*******************************************************************************
* Description:
*
* The Verilog behavioral model for the FIFO Generator.
*
* The behavioral model has three parts:
* - The behavioral model for independent clocks FIFOs (_as)
* - The behavioral model for common clock FIFOs (_ss)
* - The "preload logic" block which implements First-word Fall-through
*
*******************************************************************************
* Description:
* The verilog behavioral model for the FIFO generator core.
*
*******************************************************************************
*/
`timescale 1ps/1ps
`ifndef TCQ
`define TCQ 100
`endif
/*******************************************************************************
* Declaration of top-level module
******************************************************************************/
module fifo_generator_vlog_beh
#(
//-----------------------------------------------------------------------
// Generic Declarations
//-----------------------------------------------------------------------
parameter C_COMMON_CLOCK = 0,
parameter C_COUNT_TYPE = 0,
parameter C_DATA_COUNT_WIDTH = 2,
parameter C_DEFAULT_VALUE = "",
parameter C_DIN_WIDTH = 8,
parameter C_DOUT_RST_VAL = "",
parameter C_DOUT_WIDTH = 8,
parameter C_ENABLE_RLOCS = 0,
parameter C_FAMILY = "",
parameter C_FULL_FLAGS_RST_VAL = 1,
parameter C_HAS_ALMOST_EMPTY = 0,
parameter C_HAS_ALMOST_FULL = 0,
parameter C_HAS_BACKUP = 0,
parameter C_HAS_DATA_COUNT = 0,
parameter C_HAS_INT_CLK = 0,
parameter C_HAS_MEMINIT_FILE = 0,
parameter C_HAS_OVERFLOW = 0,
parameter C_HAS_RD_DATA_COUNT = 0,
parameter C_HAS_RD_RST = 0,
parameter C_HAS_RST = 1,
parameter C_HAS_SRST = 0,
parameter C_HAS_UNDERFLOW = 0,
parameter C_HAS_VALID = 0,
parameter C_HAS_WR_ACK = 0,
parameter C_HAS_WR_DATA_COUNT = 0,
parameter C_HAS_WR_RST = 0,
parameter C_IMPLEMENTATION_TYPE = 0,
parameter C_INIT_WR_PNTR_VAL = 0,
parameter C_MEMORY_TYPE = 1,
parameter C_MIF_FILE_NAME = "",
parameter C_OPTIMIZATION_MODE = 0,
parameter C_OVERFLOW_LOW = 0,
parameter C_PRELOAD_LATENCY = 1,
parameter C_PRELOAD_REGS = 0,
parameter C_PRIM_FIFO_TYPE = "4kx4",
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL = 0,
parameter C_PROG_EMPTY_THRESH_NEGATE_VAL = 0,
parameter C_PROG_EMPTY_TYPE = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL = 0,
parameter C_PROG_FULL_THRESH_NEGATE_VAL = 0,
parameter C_PROG_FULL_TYPE = 0,
parameter C_RD_DATA_COUNT_WIDTH = 2,
parameter C_RD_DEPTH = 256,
parameter C_RD_FREQ = 1,
parameter C_RD_PNTR_WIDTH = 8,
parameter C_UNDERFLOW_LOW = 0,
parameter C_USE_DOUT_RST = 0,
parameter C_USE_ECC = 0,
parameter C_USE_EMBEDDED_REG = 0,
parameter C_USE_PIPELINE_REG = 0,
parameter C_POWER_SAVING_MODE = 0,
parameter C_USE_FIFO16_FLAGS = 0,
parameter C_USE_FWFT_DATA_COUNT = 0,
parameter C_VALID_LOW = 0,
parameter C_WR_ACK_LOW = 0,
parameter C_WR_DATA_COUNT_WIDTH = 2,
parameter C_WR_DEPTH = 256,
parameter C_WR_FREQ = 1,
parameter C_WR_PNTR_WIDTH = 8,
parameter C_WR_RESPONSE_LATENCY = 1,
parameter C_MSGON_VAL = 1,
parameter C_ENABLE_RST_SYNC = 1,
parameter C_ERROR_INJECTION_TYPE = 0,
parameter C_SYNCHRONIZER_STAGE = 2,
// AXI Interface related parameters start here
parameter C_INTERFACE_TYPE = 0, // 0: Native Interface, 1: AXI4 Stream, 2: AXI4/AXI3
parameter C_AXI_TYPE = 0, // 1: AXI4, 2: AXI4 Lite, 3: AXI3
parameter C_HAS_AXI_WR_CHANNEL = 0,
parameter C_HAS_AXI_RD_CHANNEL = 0,
parameter C_HAS_SLAVE_CE = 0,
parameter C_HAS_MASTER_CE = 0,
parameter C_ADD_NGC_CONSTRAINT = 0,
parameter C_USE_COMMON_UNDERFLOW = 0,
parameter C_USE_COMMON_OVERFLOW = 0,
parameter C_USE_DEFAULT_SETTINGS = 0,
// AXI Full/Lite
parameter C_AXI_ID_WIDTH = 0,
parameter C_AXI_ADDR_WIDTH = 0,
parameter C_AXI_DATA_WIDTH = 0,
parameter C_AXI_LEN_WIDTH = 8,
parameter C_AXI_LOCK_WIDTH = 2,
parameter C_HAS_AXI_ID = 0,
parameter C_HAS_AXI_AWUSER = 0,
parameter C_HAS_AXI_WUSER = 0,
parameter C_HAS_AXI_BUSER = 0,
parameter C_HAS_AXI_ARUSER = 0,
parameter C_HAS_AXI_RUSER = 0,
parameter C_AXI_ARUSER_WIDTH = 0,
parameter C_AXI_AWUSER_WIDTH = 0,
parameter C_AXI_WUSER_WIDTH = 0,
parameter C_AXI_BUSER_WIDTH = 0,
parameter C_AXI_RUSER_WIDTH = 0,
// AXI Streaming
parameter C_HAS_AXIS_TDATA = 0,
parameter C_HAS_AXIS_TID = 0,
parameter C_HAS_AXIS_TDEST = 0,
parameter C_HAS_AXIS_TUSER = 0,
parameter C_HAS_AXIS_TREADY = 0,
parameter C_HAS_AXIS_TLAST = 0,
parameter C_HAS_AXIS_TSTRB = 0,
parameter C_HAS_AXIS_TKEEP = 0,
parameter C_AXIS_TDATA_WIDTH = 1,
parameter C_AXIS_TID_WIDTH = 1,
parameter C_AXIS_TDEST_WIDTH = 1,
parameter C_AXIS_TUSER_WIDTH = 1,
parameter C_AXIS_TSTRB_WIDTH = 1,
parameter C_AXIS_TKEEP_WIDTH = 1,
// AXI Channel Type
// WACH --> Write Address Channel
// WDCH --> Write Data Channel
// WRCH --> Write Response Channel
// RACH --> Read Address Channel
// RDCH --> Read Data Channel
// AXIS --> AXI Streaming
parameter C_WACH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logic
parameter C_WDCH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie
parameter C_WRCH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie
parameter C_RACH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie
parameter C_RDCH_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie
parameter C_AXIS_TYPE = 0, // 0 = FIFO, 1 = Register Slice, 2 = Pass Through Logie
// AXI Implementation Type
// 1 = Common Clock Block RAM FIFO
// 2 = Common Clock Distributed RAM FIFO
// 11 = Independent Clock Block RAM FIFO
// 12 = Independent Clock Distributed RAM FIFO
parameter C_IMPLEMENTATION_TYPE_WACH = 0,
parameter C_IMPLEMENTATION_TYPE_WDCH = 0,
parameter C_IMPLEMENTATION_TYPE_WRCH = 0,
parameter C_IMPLEMENTATION_TYPE_RACH = 0,
parameter C_IMPLEMENTATION_TYPE_RDCH = 0,
parameter C_IMPLEMENTATION_TYPE_AXIS = 0,
// AXI FIFO Type
// 0 = Data FIFO
// 1 = Packet FIFO
// 2 = Low Latency Sync FIFO
// 3 = Low Latency Async FIFO
parameter C_APPLICATION_TYPE_WACH = 0,
parameter C_APPLICATION_TYPE_WDCH = 0,
parameter C_APPLICATION_TYPE_WRCH = 0,
parameter C_APPLICATION_TYPE_RACH = 0,
parameter C_APPLICATION_TYPE_RDCH = 0,
parameter C_APPLICATION_TYPE_AXIS = 0,
// AXI Built-in FIFO Primitive Type
// 512x36, 1kx18, 2kx9, 4kx4, etc
parameter C_PRIM_FIFO_TYPE_WACH = "512x36",
parameter C_PRIM_FIFO_TYPE_WDCH = "512x36",
parameter C_PRIM_FIFO_TYPE_WRCH = "512x36",
parameter C_PRIM_FIFO_TYPE_RACH = "512x36",
parameter C_PRIM_FIFO_TYPE_RDCH = "512x36",
parameter C_PRIM_FIFO_TYPE_AXIS = "512x36",
// Enable ECC
// 0 = ECC disabled
// 1 = ECC enabled
parameter C_USE_ECC_WACH = 0,
parameter C_USE_ECC_WDCH = 0,
parameter C_USE_ECC_WRCH = 0,
parameter C_USE_ECC_RACH = 0,
parameter C_USE_ECC_RDCH = 0,
parameter C_USE_ECC_AXIS = 0,
// ECC Error Injection Type
// 0 = No Error Injection
// 1 = Single Bit Error Injection
// 2 = Double Bit Error Injection
// 3 = Single Bit and Double Bit Error Injection
parameter C_ERROR_INJECTION_TYPE_WACH = 0,
parameter C_ERROR_INJECTION_TYPE_WDCH = 0,
parameter C_ERROR_INJECTION_TYPE_WRCH = 0,
parameter C_ERROR_INJECTION_TYPE_RACH = 0,
parameter C_ERROR_INJECTION_TYPE_RDCH = 0,
parameter C_ERROR_INJECTION_TYPE_AXIS = 0,
// Input Data Width
// Accumulation of all AXI input signal's width
parameter C_DIN_WIDTH_WACH = 1,
parameter C_DIN_WIDTH_WDCH = 1,
parameter C_DIN_WIDTH_WRCH = 1,
parameter C_DIN_WIDTH_RACH = 1,
parameter C_DIN_WIDTH_RDCH = 1,
parameter C_DIN_WIDTH_AXIS = 1,
parameter C_WR_DEPTH_WACH = 16,
parameter C_WR_DEPTH_WDCH = 16,
parameter C_WR_DEPTH_WRCH = 16,
parameter C_WR_DEPTH_RACH = 16,
parameter C_WR_DEPTH_RDCH = 16,
parameter C_WR_DEPTH_AXIS = 16,
parameter C_WR_PNTR_WIDTH_WACH = 4,
parameter C_WR_PNTR_WIDTH_WDCH = 4,
parameter C_WR_PNTR_WIDTH_WRCH = 4,
parameter C_WR_PNTR_WIDTH_RACH = 4,
parameter C_WR_PNTR_WIDTH_RDCH = 4,
parameter C_WR_PNTR_WIDTH_AXIS = 4,
parameter C_HAS_DATA_COUNTS_WACH = 0,
parameter C_HAS_DATA_COUNTS_WDCH = 0,
parameter C_HAS_DATA_COUNTS_WRCH = 0,
parameter C_HAS_DATA_COUNTS_RACH = 0,
parameter C_HAS_DATA_COUNTS_RDCH = 0,
parameter C_HAS_DATA_COUNTS_AXIS = 0,
parameter C_HAS_PROG_FLAGS_WACH = 0,
parameter C_HAS_PROG_FLAGS_WDCH = 0,
parameter C_HAS_PROG_FLAGS_WRCH = 0,
parameter C_HAS_PROG_FLAGS_RACH = 0,
parameter C_HAS_PROG_FLAGS_RDCH = 0,
parameter C_HAS_PROG_FLAGS_AXIS = 0,
parameter C_PROG_FULL_TYPE_WACH = 0,
parameter C_PROG_FULL_TYPE_WDCH = 0,
parameter C_PROG_FULL_TYPE_WRCH = 0,
parameter C_PROG_FULL_TYPE_RACH = 0,
parameter C_PROG_FULL_TYPE_RDCH = 0,
parameter C_PROG_FULL_TYPE_AXIS = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL_WACH = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL_WDCH = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL_WRCH = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL_RACH = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL_RDCH = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL_AXIS = 0,
parameter C_PROG_EMPTY_TYPE_WACH = 0,
parameter C_PROG_EMPTY_TYPE_WDCH = 0,
parameter C_PROG_EMPTY_TYPE_WRCH = 0,
parameter C_PROG_EMPTY_TYPE_RACH = 0,
parameter C_PROG_EMPTY_TYPE_RDCH = 0,
parameter C_PROG_EMPTY_TYPE_AXIS = 0,
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_WACH = 0,
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_WDCH = 0,
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_WRCH = 0,
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_RACH = 0,
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_RDCH = 0,
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL_AXIS = 0,
parameter C_REG_SLICE_MODE_WACH = 0,
parameter C_REG_SLICE_MODE_WDCH = 0,
parameter C_REG_SLICE_MODE_WRCH = 0,
parameter C_REG_SLICE_MODE_RACH = 0,
parameter C_REG_SLICE_MODE_RDCH = 0,
parameter C_REG_SLICE_MODE_AXIS = 0
)
(
//------------------------------------------------------------------------------
// Input and Output Declarations
//------------------------------------------------------------------------------
// Conventional FIFO Interface Signals
input backup,
input backup_marker,
input clk,
input rst,
input srst,
input wr_clk,
input wr_rst,
input rd_clk,
input rd_rst,
input [C_DIN_WIDTH-1:0] din,
input wr_en,
input rd_en,
// Optional inputs
input [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh,
input [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_assert,
input [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_negate,
input [C_WR_PNTR_WIDTH-1:0] prog_full_thresh,
input [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_assert,
input [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_negate,
input int_clk,
input injectdbiterr,
input injectsbiterr,
input sleep,
output [C_DOUT_WIDTH-1:0] dout,
output full,
output almost_full,
output wr_ack,
output overflow,
output empty,
output almost_empty,
output valid,
output underflow,
output [C_DATA_COUNT_WIDTH-1:0] data_count,
output [C_RD_DATA_COUNT_WIDTH-1:0] rd_data_count,
output [C_WR_DATA_COUNT_WIDTH-1:0] wr_data_count,
output prog_full,
output prog_empty,
output sbiterr,
output dbiterr,
output wr_rst_busy,
output rd_rst_busy,
// AXI Global Signal
input m_aclk,
input s_aclk,
input s_aresetn,
input s_aclk_en,
input m_aclk_en,
// AXI Full/Lite Slave Write Channel (write side)
input [C_AXI_ID_WIDTH-1:0] s_axi_awid,
input [C_AXI_ADDR_WIDTH-1:0] s_axi_awaddr,
input [C_AXI_LEN_WIDTH-1:0] s_axi_awlen,
input [3-1:0] s_axi_awsize,
input [2-1:0] s_axi_awburst,
input [C_AXI_LOCK_WIDTH-1:0] s_axi_awlock,
input [4-1:0] s_axi_awcache,
input [3-1:0] s_axi_awprot,
input [4-1:0] s_axi_awqos,
input [4-1:0] s_axi_awregion,
input [C_AXI_AWUSER_WIDTH-1:0] s_axi_awuser,
input s_axi_awvalid,
output s_axi_awready,
input [C_AXI_ID_WIDTH-1:0] s_axi_wid,
input [C_AXI_DATA_WIDTH-1:0] s_axi_wdata,
input [C_AXI_DATA_WIDTH/8-1:0] s_axi_wstrb,
input s_axi_wlast,
input [C_AXI_WUSER_WIDTH-1:0] s_axi_wuser,
input s_axi_wvalid,
output s_axi_wready,
output [C_AXI_ID_WIDTH-1:0] s_axi_bid,
output [2-1:0] s_axi_bresp,
output [C_AXI_BUSER_WIDTH-1:0] s_axi_buser,
output s_axi_bvalid,
input s_axi_bready,
// AXI Full/Lite Master Write Channel (read side)
output [C_AXI_ID_WIDTH-1:0] m_axi_awid,
output [C_AXI_ADDR_WIDTH-1:0] m_axi_awaddr,
output [C_AXI_LEN_WIDTH-1:0] m_axi_awlen,
output [3-1:0] m_axi_awsize,
output [2-1:0] m_axi_awburst,
output [C_AXI_LOCK_WIDTH-1:0] m_axi_awlock,
output [4-1:0] m_axi_awcache,
output [3-1:0] m_axi_awprot,
output [4-1:0] m_axi_awqos,
output [4-1:0] m_axi_awregion,
output [C_AXI_AWUSER_WIDTH-1:0] m_axi_awuser,
output m_axi_awvalid,
input m_axi_awready,
output [C_AXI_ID_WIDTH-1:0] m_axi_wid,
output [C_AXI_DATA_WIDTH-1:0] m_axi_wdata,
output [C_AXI_DATA_WIDTH/8-1:0] m_axi_wstrb,
output m_axi_wlast,
output [C_AXI_WUSER_WIDTH-1:0] m_axi_wuser,
output m_axi_wvalid,
input m_axi_wready,
input [C_AXI_ID_WIDTH-1:0] m_axi_bid,
input [2-1:0] m_axi_bresp,
input [C_AXI_BUSER_WIDTH-1:0] m_axi_buser,
input m_axi_bvalid,
output m_axi_bready,
// AXI Full/Lite Slave Read Channel (write side)
input [C_AXI_ID_WIDTH-1:0] s_axi_arid,
input [C_AXI_ADDR_WIDTH-1:0] s_axi_araddr,
input [C_AXI_LEN_WIDTH-1:0] s_axi_arlen,
input [3-1:0] s_axi_arsize,
input [2-1:0] s_axi_arburst,
input [C_AXI_LOCK_WIDTH-1:0] s_axi_arlock,
input [4-1:0] s_axi_arcache,
input [3-1:0] s_axi_arprot,
input [4-1:0] s_axi_arqos,
input [4-1:0] s_axi_arregion,
input [C_AXI_ARUSER_WIDTH-1:0] s_axi_aruser,
input s_axi_arvalid,
output s_axi_arready,
output [C_AXI_ID_WIDTH-1:0] s_axi_rid,
output [C_AXI_DATA_WIDTH-1:0] s_axi_rdata,
output [2-1:0] s_axi_rresp,
output s_axi_rlast,
output [C_AXI_RUSER_WIDTH-1:0] s_axi_ruser,
output s_axi_rvalid,
input s_axi_rready,
// AXI Full/Lite Master Read Channel (read side)
output [C_AXI_ID_WIDTH-1:0] m_axi_arid,
output [C_AXI_ADDR_WIDTH-1:0] m_axi_araddr,
output [C_AXI_LEN_WIDTH-1:0] m_axi_arlen,
output [3-1:0] m_axi_arsize,
output [2-1:0] m_axi_arburst,
output [C_AXI_LOCK_WIDTH-1:0] m_axi_arlock,
output [4-1:0] m_axi_arcache,
output [3-1:0] m_axi_arprot,
output [4-1:0] m_axi_arqos,
output [4-1:0] m_axi_arregion,
output [C_AXI_ARUSER_WIDTH-1:0] m_axi_aruser,
output m_axi_arvalid,
input m_axi_arready,
input [C_AXI_ID_WIDTH-1:0] m_axi_rid,
input [C_AXI_DATA_WIDTH-1:0] m_axi_rdata,
input [2-1:0] m_axi_rresp,
input m_axi_rlast,
input [C_AXI_RUSER_WIDTH-1:0] m_axi_ruser,
input m_axi_rvalid,
output m_axi_rready,
// AXI Streaming Slave Signals (Write side)
input s_axis_tvalid,
output s_axis_tready,
input [C_AXIS_TDATA_WIDTH-1:0] s_axis_tdata,
input [C_AXIS_TSTRB_WIDTH-1:0] s_axis_tstrb,
input [C_AXIS_TKEEP_WIDTH-1:0] s_axis_tkeep,
input s_axis_tlast,
input [C_AXIS_TID_WIDTH-1:0] s_axis_tid,
input [C_AXIS_TDEST_WIDTH-1:0] s_axis_tdest,
input [C_AXIS_TUSER_WIDTH-1:0] s_axis_tuser,
// AXI Streaming Master Signals (Read side)
output m_axis_tvalid,
input m_axis_tready,
output [C_AXIS_TDATA_WIDTH-1:0] m_axis_tdata,
output [C_AXIS_TSTRB_WIDTH-1:0] m_axis_tstrb,
output [C_AXIS_TKEEP_WIDTH-1:0] m_axis_tkeep,
output m_axis_tlast,
output [C_AXIS_TID_WIDTH-1:0] m_axis_tid,
output [C_AXIS_TDEST_WIDTH-1:0] m_axis_tdest,
output [C_AXIS_TUSER_WIDTH-1:0] m_axis_tuser,
// AXI Full/Lite Write Address Channel signals
input axi_aw_injectsbiterr,
input axi_aw_injectdbiterr,
input [C_WR_PNTR_WIDTH_WACH-1:0] axi_aw_prog_full_thresh,
input [C_WR_PNTR_WIDTH_WACH-1:0] axi_aw_prog_empty_thresh,
output [C_WR_PNTR_WIDTH_WACH:0] axi_aw_data_count,
output [C_WR_PNTR_WIDTH_WACH:0] axi_aw_wr_data_count,
output [C_WR_PNTR_WIDTH_WACH:0] axi_aw_rd_data_count,
output axi_aw_sbiterr,
output axi_aw_dbiterr,
output axi_aw_overflow,
output axi_aw_underflow,
output axi_aw_prog_full,
output axi_aw_prog_empty,
// AXI Full/Lite Write Data Channel signals
input axi_w_injectsbiterr,
input axi_w_injectdbiterr,
input [C_WR_PNTR_WIDTH_WDCH-1:0] axi_w_prog_full_thresh,
input [C_WR_PNTR_WIDTH_WDCH-1:0] axi_w_prog_empty_thresh,
output [C_WR_PNTR_WIDTH_WDCH:0] axi_w_data_count,
output [C_WR_PNTR_WIDTH_WDCH:0] axi_w_wr_data_count,
output [C_WR_PNTR_WIDTH_WDCH:0] axi_w_rd_data_count,
output axi_w_sbiterr,
output axi_w_dbiterr,
output axi_w_overflow,
output axi_w_underflow,
output axi_w_prog_full,
output axi_w_prog_empty,
// AXI Full/Lite Write Response Channel signals
input axi_b_injectsbiterr,
input axi_b_injectdbiterr,
input [C_WR_PNTR_WIDTH_WRCH-1:0] axi_b_prog_full_thresh,
input [C_WR_PNTR_WIDTH_WRCH-1:0] axi_b_prog_empty_thresh,
output [C_WR_PNTR_WIDTH_WRCH:0] axi_b_data_count,
output [C_WR_PNTR_WIDTH_WRCH:0] axi_b_wr_data_count,
output [C_WR_PNTR_WIDTH_WRCH:0] axi_b_rd_data_count,
output axi_b_sbiterr,
output axi_b_dbiterr,
output axi_b_overflow,
output axi_b_underflow,
output axi_b_prog_full,
output axi_b_prog_empty,
// AXI Full/Lite Read Address Channel signals
input axi_ar_injectsbiterr,
input axi_ar_injectdbiterr,
input [C_WR_PNTR_WIDTH_RACH-1:0] axi_ar_prog_full_thresh,
input [C_WR_PNTR_WIDTH_RACH-1:0] axi_ar_prog_empty_thresh,
output [C_WR_PNTR_WIDTH_RACH:0] axi_ar_data_count,
output [C_WR_PNTR_WIDTH_RACH:0] axi_ar_wr_data_count,
output [C_WR_PNTR_WIDTH_RACH:0] axi_ar_rd_data_count,
output axi_ar_sbiterr,
output axi_ar_dbiterr,
output axi_ar_overflow,
output axi_ar_underflow,
output axi_ar_prog_full,
output axi_ar_prog_empty,
// AXI Full/Lite Read Data Channel Signals
input axi_r_injectsbiterr,
input axi_r_injectdbiterr,
input [C_WR_PNTR_WIDTH_RDCH-1:0] axi_r_prog_full_thresh,
input [C_WR_PNTR_WIDTH_RDCH-1:0] axi_r_prog_empty_thresh,
output [C_WR_PNTR_WIDTH_RDCH:0] axi_r_data_count,
output [C_WR_PNTR_WIDTH_RDCH:0] axi_r_wr_data_count,
output [C_WR_PNTR_WIDTH_RDCH:0] axi_r_rd_data_count,
output axi_r_sbiterr,
output axi_r_dbiterr,
output axi_r_overflow,
output axi_r_underflow,
output axi_r_prog_full,
output axi_r_prog_empty,
// AXI Streaming FIFO Related Signals
input axis_injectsbiterr,
input axis_injectdbiterr,
input [C_WR_PNTR_WIDTH_AXIS-1:0] axis_prog_full_thresh,
input [C_WR_PNTR_WIDTH_AXIS-1:0] axis_prog_empty_thresh,
output [C_WR_PNTR_WIDTH_AXIS:0] axis_data_count,
output [C_WR_PNTR_WIDTH_AXIS:0] axis_wr_data_count,
output [C_WR_PNTR_WIDTH_AXIS:0] axis_rd_data_count,
output axis_sbiterr,
output axis_dbiterr,
output axis_overflow,
output axis_underflow,
output axis_prog_full,
output axis_prog_empty
);
wire BACKUP;
wire BACKUP_MARKER;
wire CLK;
wire RST;
wire SRST;
wire WR_CLK;
wire WR_RST;
wire RD_CLK;
wire RD_RST;
wire [C_DIN_WIDTH-1:0] DIN;
wire WR_EN;
wire RD_EN;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE;
wire INT_CLK;
wire INJECTDBITERR;
wire INJECTSBITERR;
wire SLEEP;
wire [C_DOUT_WIDTH-1:0] DOUT;
wire FULL;
wire ALMOST_FULL;
wire WR_ACK;
wire OVERFLOW;
wire EMPTY;
wire ALMOST_EMPTY;
wire VALID;
wire UNDERFLOW;
wire [C_DATA_COUNT_WIDTH-1:0] DATA_COUNT;
wire [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT;
wire [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT;
wire PROG_FULL;
wire PROG_EMPTY;
wire SBITERR;
wire DBITERR;
wire WR_RST_BUSY;
wire RD_RST_BUSY;
wire M_ACLK;
wire S_ACLK;
wire S_ARESETN;
wire S_ACLK_EN;
wire M_ACLK_EN;
wire [C_AXI_ID_WIDTH-1:0] S_AXI_AWID;
wire [C_AXI_ADDR_WIDTH-1:0] S_AXI_AWADDR;
wire [C_AXI_LEN_WIDTH-1:0] S_AXI_AWLEN;
wire [3-1:0] S_AXI_AWSIZE;
wire [2-1:0] S_AXI_AWBURST;
wire [C_AXI_LOCK_WIDTH-1:0] S_AXI_AWLOCK;
wire [4-1:0] S_AXI_AWCACHE;
wire [3-1:0] S_AXI_AWPROT;
wire [4-1:0] S_AXI_AWQOS;
wire [4-1:0] S_AXI_AWREGION;
wire [C_AXI_AWUSER_WIDTH-1:0] S_AXI_AWUSER;
wire S_AXI_AWVALID;
wire S_AXI_AWREADY;
wire [C_AXI_ID_WIDTH-1:0] S_AXI_WID;
wire [C_AXI_DATA_WIDTH-1:0] S_AXI_WDATA;
wire [C_AXI_DATA_WIDTH/8-1:0] S_AXI_WSTRB;
wire S_AXI_WLAST;
wire [C_AXI_WUSER_WIDTH-1:0] S_AXI_WUSER;
wire S_AXI_WVALID;
wire S_AXI_WREADY;
wire [C_AXI_ID_WIDTH-1:0] S_AXI_BID;
wire [2-1:0] S_AXI_BRESP;
wire [C_AXI_BUSER_WIDTH-1:0] S_AXI_BUSER;
wire S_AXI_BVALID;
wire S_AXI_BREADY;
wire [C_AXI_ID_WIDTH-1:0] M_AXI_AWID;
wire [C_AXI_ADDR_WIDTH-1:0] M_AXI_AWADDR;
wire [C_AXI_LEN_WIDTH-1:0] M_AXI_AWLEN;
wire [3-1:0] M_AXI_AWSIZE;
wire [2-1:0] M_AXI_AWBURST;
wire [C_AXI_LOCK_WIDTH-1:0] M_AXI_AWLOCK;
wire [4-1:0] M_AXI_AWCACHE;
wire [3-1:0] M_AXI_AWPROT;
wire [4-1:0] M_AXI_AWQOS;
wire [4-1:0] M_AXI_AWREGION;
wire [C_AXI_AWUSER_WIDTH-1:0] M_AXI_AWUSER;
wire M_AXI_AWVALID;
wire M_AXI_AWREADY;
wire [C_AXI_ID_WIDTH-1:0] M_AXI_WID;
wire [C_AXI_DATA_WIDTH-1:0] M_AXI_WDATA;
wire [C_AXI_DATA_WIDTH/8-1:0] M_AXI_WSTRB;
wire M_AXI_WLAST;
wire [C_AXI_WUSER_WIDTH-1:0] M_AXI_WUSER;
wire M_AXI_WVALID;
wire M_AXI_WREADY;
wire [C_AXI_ID_WIDTH-1:0] M_AXI_BID;
wire [2-1:0] M_AXI_BRESP;
wire [C_AXI_BUSER_WIDTH-1:0] M_AXI_BUSER;
wire M_AXI_BVALID;
wire M_AXI_BREADY;
wire [C_AXI_ID_WIDTH-1:0] S_AXI_ARID;
wire [C_AXI_ADDR_WIDTH-1:0] S_AXI_ARADDR;
wire [C_AXI_LEN_WIDTH-1:0] S_AXI_ARLEN;
wire [3-1:0] S_AXI_ARSIZE;
wire [2-1:0] S_AXI_ARBURST;
wire [C_AXI_LOCK_WIDTH-1:0] S_AXI_ARLOCK;
wire [4-1:0] S_AXI_ARCACHE;
wire [3-1:0] S_AXI_ARPROT;
wire [4-1:0] S_AXI_ARQOS;
wire [4-1:0] S_AXI_ARREGION;
wire [C_AXI_ARUSER_WIDTH-1:0] S_AXI_ARUSER;
wire S_AXI_ARVALID;
wire S_AXI_ARREADY;
wire [C_AXI_ID_WIDTH-1:0] S_AXI_RID;
wire [C_AXI_DATA_WIDTH-1:0] S_AXI_RDATA;
wire [2-1:0] S_AXI_RRESP;
wire S_AXI_RLAST;
wire [C_AXI_RUSER_WIDTH-1:0] S_AXI_RUSER;
wire S_AXI_RVALID;
wire S_AXI_RREADY;
wire [C_AXI_ID_WIDTH-1:0] M_AXI_ARID;
wire [C_AXI_ADDR_WIDTH-1:0] M_AXI_ARADDR;
wire [C_AXI_LEN_WIDTH-1:0] M_AXI_ARLEN;
wire [3-1:0] M_AXI_ARSIZE;
wire [2-1:0] M_AXI_ARBURST;
wire [C_AXI_LOCK_WIDTH-1:0] M_AXI_ARLOCK;
wire [4-1:0] M_AXI_ARCACHE;
wire [3-1:0] M_AXI_ARPROT;
wire [4-1:0] M_AXI_ARQOS;
wire [4-1:0] M_AXI_ARREGION;
wire [C_AXI_ARUSER_WIDTH-1:0] M_AXI_ARUSER;
wire M_AXI_ARVALID;
wire M_AXI_ARREADY;
wire [C_AXI_ID_WIDTH-1:0] M_AXI_RID;
wire [C_AXI_DATA_WIDTH-1:0] M_AXI_RDATA;
wire [2-1:0] M_AXI_RRESP;
wire M_AXI_RLAST;
wire [C_AXI_RUSER_WIDTH-1:0] M_AXI_RUSER;
wire M_AXI_RVALID;
wire M_AXI_RREADY;
wire S_AXIS_TVALID;
wire S_AXIS_TREADY;
wire [C_AXIS_TDATA_WIDTH-1:0] S_AXIS_TDATA;
wire [C_AXIS_TSTRB_WIDTH-1:0] S_AXIS_TSTRB;
wire [C_AXIS_TKEEP_WIDTH-1:0] S_AXIS_TKEEP;
wire S_AXIS_TLAST;
wire [C_AXIS_TID_WIDTH-1:0] S_AXIS_TID;
wire [C_AXIS_TDEST_WIDTH-1:0] S_AXIS_TDEST;
wire [C_AXIS_TUSER_WIDTH-1:0] S_AXIS_TUSER;
wire M_AXIS_TVALID;
wire M_AXIS_TREADY;
wire [C_AXIS_TDATA_WIDTH-1:0] M_AXIS_TDATA;
wire [C_AXIS_TSTRB_WIDTH-1:0] M_AXIS_TSTRB;
wire [C_AXIS_TKEEP_WIDTH-1:0] M_AXIS_TKEEP;
wire M_AXIS_TLAST;
wire [C_AXIS_TID_WIDTH-1:0] M_AXIS_TID;
wire [C_AXIS_TDEST_WIDTH-1:0] M_AXIS_TDEST;
wire [C_AXIS_TUSER_WIDTH-1:0] M_AXIS_TUSER;
wire AXI_AW_INJECTSBITERR;
wire AXI_AW_INJECTDBITERR;
wire [C_WR_PNTR_WIDTH_WACH-1:0] AXI_AW_PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH_WACH-1:0] AXI_AW_PROG_EMPTY_THRESH;
wire [C_WR_PNTR_WIDTH_WACH:0] AXI_AW_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_WACH:0] AXI_AW_WR_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_WACH:0] AXI_AW_RD_DATA_COUNT;
wire AXI_AW_SBITERR;
wire AXI_AW_DBITERR;
wire AXI_AW_OVERFLOW;
wire AXI_AW_UNDERFLOW;
wire AXI_AW_PROG_FULL;
wire AXI_AW_PROG_EMPTY;
wire AXI_W_INJECTSBITERR;
wire AXI_W_INJECTDBITERR;
wire [C_WR_PNTR_WIDTH_WDCH-1:0] AXI_W_PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH_WDCH-1:0] AXI_W_PROG_EMPTY_THRESH;
wire [C_WR_PNTR_WIDTH_WDCH:0] AXI_W_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_WDCH:0] AXI_W_WR_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_WDCH:0] AXI_W_RD_DATA_COUNT;
wire AXI_W_SBITERR;
wire AXI_W_DBITERR;
wire AXI_W_OVERFLOW;
wire AXI_W_UNDERFLOW;
wire AXI_W_PROG_FULL;
wire AXI_W_PROG_EMPTY;
wire AXI_B_INJECTSBITERR;
wire AXI_B_INJECTDBITERR;
wire [C_WR_PNTR_WIDTH_WRCH-1:0] AXI_B_PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH_WRCH-1:0] AXI_B_PROG_EMPTY_THRESH;
wire [C_WR_PNTR_WIDTH_WRCH:0] AXI_B_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_WRCH:0] AXI_B_WR_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_WRCH:0] AXI_B_RD_DATA_COUNT;
wire AXI_B_SBITERR;
wire AXI_B_DBITERR;
wire AXI_B_OVERFLOW;
wire AXI_B_UNDERFLOW;
wire AXI_B_PROG_FULL;
wire AXI_B_PROG_EMPTY;
wire AXI_AR_INJECTSBITERR;
wire AXI_AR_INJECTDBITERR;
wire [C_WR_PNTR_WIDTH_RACH-1:0] AXI_AR_PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH_RACH-1:0] AXI_AR_PROG_EMPTY_THRESH;
wire [C_WR_PNTR_WIDTH_RACH:0] AXI_AR_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_RACH:0] AXI_AR_WR_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_RACH:0] AXI_AR_RD_DATA_COUNT;
wire AXI_AR_SBITERR;
wire AXI_AR_DBITERR;
wire AXI_AR_OVERFLOW;
wire AXI_AR_UNDERFLOW;
wire AXI_AR_PROG_FULL;
wire AXI_AR_PROG_EMPTY;
wire AXI_R_INJECTSBITERR;
wire AXI_R_INJECTDBITERR;
wire [C_WR_PNTR_WIDTH_RDCH-1:0] AXI_R_PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH_RDCH-1:0] AXI_R_PROG_EMPTY_THRESH;
wire [C_WR_PNTR_WIDTH_RDCH:0] AXI_R_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_RDCH:0] AXI_R_WR_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_RDCH:0] AXI_R_RD_DATA_COUNT;
wire AXI_R_SBITERR;
wire AXI_R_DBITERR;
wire AXI_R_OVERFLOW;
wire AXI_R_UNDERFLOW;
wire AXI_R_PROG_FULL;
wire AXI_R_PROG_EMPTY;
wire AXIS_INJECTSBITERR;
wire AXIS_INJECTDBITERR;
wire [C_WR_PNTR_WIDTH_AXIS-1:0] AXIS_PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH_AXIS-1:0] AXIS_PROG_EMPTY_THRESH;
wire [C_WR_PNTR_WIDTH_AXIS:0] AXIS_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_AXIS:0] AXIS_WR_DATA_COUNT;
wire [C_WR_PNTR_WIDTH_AXIS:0] AXIS_RD_DATA_COUNT;
wire AXIS_SBITERR;
wire AXIS_DBITERR;
wire AXIS_OVERFLOW;
wire AXIS_UNDERFLOW;
wire AXIS_PROG_FULL;
wire AXIS_PROG_EMPTY;
wire [C_WR_DATA_COUNT_WIDTH-1:0] wr_data_count_in;
wire wr_rst_int;
wire rd_rst_int;
function integer find_log2;
input integer int_val;
integer i,j;
begin
i = 1;
j = 0;
for (i = 1; i < int_val; i = i*2) begin
j = j + 1;
end
find_log2 = j;
end
endfunction
// Conventional FIFO Interface Signals
assign BACKUP = backup;
assign BACKUP_MARKER = backup_marker;
assign CLK = clk;
assign RST = rst;
assign SRST = srst;
assign WR_CLK = wr_clk;
assign WR_RST = wr_rst;
assign RD_CLK = rd_clk;
assign RD_RST = rd_rst;
assign WR_EN = wr_en;
assign RD_EN = rd_en;
assign INT_CLK = int_clk;
assign INJECTDBITERR = injectdbiterr;
assign INJECTSBITERR = injectsbiterr;
assign SLEEP = sleep;
assign full = FULL;
assign almost_full = ALMOST_FULL;
assign wr_ack = WR_ACK;
assign overflow = OVERFLOW;
assign empty = EMPTY;
assign almost_empty = ALMOST_EMPTY;
assign valid = VALID;
assign underflow = UNDERFLOW;
assign prog_full = PROG_FULL;
assign prog_empty = PROG_EMPTY;
assign sbiterr = SBITERR;
assign dbiterr = DBITERR;
assign wr_rst_busy = WR_RST_BUSY;
assign rd_rst_busy = RD_RST_BUSY;
assign M_ACLK = m_aclk;
assign S_ACLK = s_aclk;
assign S_ARESETN = s_aresetn;
assign S_ACLK_EN = s_aclk_en;
assign M_ACLK_EN = m_aclk_en;
assign S_AXI_AWVALID = s_axi_awvalid;
assign s_axi_awready = S_AXI_AWREADY;
assign S_AXI_WLAST = s_axi_wlast;
assign S_AXI_WVALID = s_axi_wvalid;
assign s_axi_wready = S_AXI_WREADY;
assign s_axi_bvalid = S_AXI_BVALID;
assign S_AXI_BREADY = s_axi_bready;
assign m_axi_awvalid = M_AXI_AWVALID;
assign M_AXI_AWREADY = m_axi_awready;
assign m_axi_wlast = M_AXI_WLAST;
assign m_axi_wvalid = M_AXI_WVALID;
assign M_AXI_WREADY = m_axi_wready;
assign M_AXI_BVALID = m_axi_bvalid;
assign m_axi_bready = M_AXI_BREADY;
assign S_AXI_ARVALID = s_axi_arvalid;
assign s_axi_arready = S_AXI_ARREADY;
assign s_axi_rlast = S_AXI_RLAST;
assign s_axi_rvalid = S_AXI_RVALID;
assign S_AXI_RREADY = s_axi_rready;
assign m_axi_arvalid = M_AXI_ARVALID;
assign M_AXI_ARREADY = m_axi_arready;
assign M_AXI_RLAST = m_axi_rlast;
assign M_AXI_RVALID = m_axi_rvalid;
assign m_axi_rready = M_AXI_RREADY;
assign S_AXIS_TVALID = s_axis_tvalid;
assign s_axis_tready = S_AXIS_TREADY;
assign S_AXIS_TLAST = s_axis_tlast;
assign m_axis_tvalid = M_AXIS_TVALID;
assign M_AXIS_TREADY = m_axis_tready;
assign m_axis_tlast = M_AXIS_TLAST;
assign AXI_AW_INJECTSBITERR = axi_aw_injectsbiterr;
assign AXI_AW_INJECTDBITERR = axi_aw_injectdbiterr;
assign axi_aw_sbiterr = AXI_AW_SBITERR;
assign axi_aw_dbiterr = AXI_AW_DBITERR;
assign axi_aw_overflow = AXI_AW_OVERFLOW;
assign axi_aw_underflow = AXI_AW_UNDERFLOW;
assign axi_aw_prog_full = AXI_AW_PROG_FULL;
assign axi_aw_prog_empty = AXI_AW_PROG_EMPTY;
assign AXI_W_INJECTSBITERR = axi_w_injectsbiterr;
assign AXI_W_INJECTDBITERR = axi_w_injectdbiterr;
assign axi_w_sbiterr = AXI_W_SBITERR;
assign axi_w_dbiterr = AXI_W_DBITERR;
assign axi_w_overflow = AXI_W_OVERFLOW;
assign axi_w_underflow = AXI_W_UNDERFLOW;
assign axi_w_prog_full = AXI_W_PROG_FULL;
assign axi_w_prog_empty = AXI_W_PROG_EMPTY;
assign AXI_B_INJECTSBITERR = axi_b_injectsbiterr;
assign AXI_B_INJECTDBITERR = axi_b_injectdbiterr;
assign axi_b_sbiterr = AXI_B_SBITERR;
assign axi_b_dbiterr = AXI_B_DBITERR;
assign axi_b_overflow = AXI_B_OVERFLOW;
assign axi_b_underflow = AXI_B_UNDERFLOW;
assign axi_b_prog_full = AXI_B_PROG_FULL;
assign axi_b_prog_empty = AXI_B_PROG_EMPTY;
assign AXI_AR_INJECTSBITERR = axi_ar_injectsbiterr;
assign AXI_AR_INJECTDBITERR = axi_ar_injectdbiterr;
assign axi_ar_sbiterr = AXI_AR_SBITERR;
assign axi_ar_dbiterr = AXI_AR_DBITERR;
assign axi_ar_overflow = AXI_AR_OVERFLOW;
assign axi_ar_underflow = AXI_AR_UNDERFLOW;
assign axi_ar_prog_full = AXI_AR_PROG_FULL;
assign axi_ar_prog_empty = AXI_AR_PROG_EMPTY;
assign AXI_R_INJECTSBITERR = axi_r_injectsbiterr;
assign AXI_R_INJECTDBITERR = axi_r_injectdbiterr;
assign axi_r_sbiterr = AXI_R_SBITERR;
assign axi_r_dbiterr = AXI_R_DBITERR;
assign axi_r_overflow = AXI_R_OVERFLOW;
assign axi_r_underflow = AXI_R_UNDERFLOW;
assign axi_r_prog_full = AXI_R_PROG_FULL;
assign axi_r_prog_empty = AXI_R_PROG_EMPTY;
assign AXIS_INJECTSBITERR = axis_injectsbiterr;
assign AXIS_INJECTDBITERR = axis_injectdbiterr;
assign axis_sbiterr = AXIS_SBITERR;
assign axis_dbiterr = AXIS_DBITERR;
assign axis_overflow = AXIS_OVERFLOW;
assign axis_underflow = AXIS_UNDERFLOW;
assign axis_prog_full = AXIS_PROG_FULL;
assign axis_prog_empty = AXIS_PROG_EMPTY;
assign DIN = din;
assign PROG_EMPTY_THRESH = prog_empty_thresh;
assign PROG_EMPTY_THRESH_ASSERT = prog_empty_thresh_assert;
assign PROG_EMPTY_THRESH_NEGATE = prog_empty_thresh_negate;
assign PROG_FULL_THRESH = prog_full_thresh;
assign PROG_FULL_THRESH_ASSERT = prog_full_thresh_assert;
assign PROG_FULL_THRESH_NEGATE = prog_full_thresh_negate;
assign dout = DOUT;
assign data_count = DATA_COUNT;
assign rd_data_count = RD_DATA_COUNT;
assign wr_data_count = WR_DATA_COUNT;
assign S_AXI_AWID = s_axi_awid;
assign S_AXI_AWADDR = s_axi_awaddr;
assign S_AXI_AWLEN = s_axi_awlen;
assign S_AXI_AWSIZE = s_axi_awsize;
assign S_AXI_AWBURST = s_axi_awburst;
assign S_AXI_AWLOCK = s_axi_awlock;
assign S_AXI_AWCACHE = s_axi_awcache;
assign S_AXI_AWPROT = s_axi_awprot;
assign S_AXI_AWQOS = s_axi_awqos;
assign S_AXI_AWREGION = s_axi_awregion;
assign S_AXI_AWUSER = s_axi_awuser;
assign S_AXI_WID = s_axi_wid;
assign S_AXI_WDATA = s_axi_wdata;
assign S_AXI_WSTRB = s_axi_wstrb;
assign S_AXI_WUSER = s_axi_wuser;
assign s_axi_bid = S_AXI_BID;
assign s_axi_bresp = S_AXI_BRESP;
assign s_axi_buser = S_AXI_BUSER;
assign m_axi_awid = M_AXI_AWID;
assign m_axi_awaddr = M_AXI_AWADDR;
assign m_axi_awlen = M_AXI_AWLEN;
assign m_axi_awsize = M_AXI_AWSIZE;
assign m_axi_awburst = M_AXI_AWBURST;
assign m_axi_awlock = M_AXI_AWLOCK;
assign m_axi_awcache = M_AXI_AWCACHE;
assign m_axi_awprot = M_AXI_AWPROT;
assign m_axi_awqos = M_AXI_AWQOS;
assign m_axi_awregion = M_AXI_AWREGION;
assign m_axi_awuser = M_AXI_AWUSER;
assign m_axi_wid = M_AXI_WID;
assign m_axi_wdata = M_AXI_WDATA;
assign m_axi_wstrb = M_AXI_WSTRB;
assign m_axi_wuser = M_AXI_WUSER;
assign M_AXI_BID = m_axi_bid;
assign M_AXI_BRESP = m_axi_bresp;
assign M_AXI_BUSER = m_axi_buser;
assign S_AXI_ARID = s_axi_arid;
assign S_AXI_ARADDR = s_axi_araddr;
assign S_AXI_ARLEN = s_axi_arlen;
assign S_AXI_ARSIZE = s_axi_arsize;
assign S_AXI_ARBURST = s_axi_arburst;
assign S_AXI_ARLOCK = s_axi_arlock;
assign S_AXI_ARCACHE = s_axi_arcache;
assign S_AXI_ARPROT = s_axi_arprot;
assign S_AXI_ARQOS = s_axi_arqos;
assign S_AXI_ARREGION = s_axi_arregion;
assign S_AXI_ARUSER = s_axi_aruser;
assign s_axi_rid = S_AXI_RID;
assign s_axi_rdata = S_AXI_RDATA;
assign s_axi_rresp = S_AXI_RRESP;
assign s_axi_ruser = S_AXI_RUSER;
assign m_axi_arid = M_AXI_ARID;
assign m_axi_araddr = M_AXI_ARADDR;
assign m_axi_arlen = M_AXI_ARLEN;
assign m_axi_arsize = M_AXI_ARSIZE;
assign m_axi_arburst = M_AXI_ARBURST;
assign m_axi_arlock = M_AXI_ARLOCK;
assign m_axi_arcache = M_AXI_ARCACHE;
assign m_axi_arprot = M_AXI_ARPROT;
assign m_axi_arqos = M_AXI_ARQOS;
assign m_axi_arregion = M_AXI_ARREGION;
assign m_axi_aruser = M_AXI_ARUSER;
assign M_AXI_RID = m_axi_rid;
assign M_AXI_RDATA = m_axi_rdata;
assign M_AXI_RRESP = m_axi_rresp;
assign M_AXI_RUSER = m_axi_ruser;
assign S_AXIS_TDATA = s_axis_tdata;
assign S_AXIS_TSTRB = s_axis_tstrb;
assign S_AXIS_TKEEP = s_axis_tkeep;
assign S_AXIS_TID = s_axis_tid;
assign S_AXIS_TDEST = s_axis_tdest;
assign S_AXIS_TUSER = s_axis_tuser;
assign m_axis_tdata = M_AXIS_TDATA;
assign m_axis_tstrb = M_AXIS_TSTRB;
assign m_axis_tkeep = M_AXIS_TKEEP;
assign m_axis_tid = M_AXIS_TID;
assign m_axis_tdest = M_AXIS_TDEST;
assign m_axis_tuser = M_AXIS_TUSER;
assign AXI_AW_PROG_FULL_THRESH = axi_aw_prog_full_thresh;
assign AXI_AW_PROG_EMPTY_THRESH = axi_aw_prog_empty_thresh;
assign axi_aw_data_count = AXI_AW_DATA_COUNT;
assign axi_aw_wr_data_count = AXI_AW_WR_DATA_COUNT;
assign axi_aw_rd_data_count = AXI_AW_RD_DATA_COUNT;
assign AXI_W_PROG_FULL_THRESH = axi_w_prog_full_thresh;
assign AXI_W_PROG_EMPTY_THRESH = axi_w_prog_empty_thresh;
assign axi_w_data_count = AXI_W_DATA_COUNT;
assign axi_w_wr_data_count = AXI_W_WR_DATA_COUNT;
assign axi_w_rd_data_count = AXI_W_RD_DATA_COUNT;
assign AXI_B_PROG_FULL_THRESH = axi_b_prog_full_thresh;
assign AXI_B_PROG_EMPTY_THRESH = axi_b_prog_empty_thresh;
assign axi_b_data_count = AXI_B_DATA_COUNT;
assign axi_b_wr_data_count = AXI_B_WR_DATA_COUNT;
assign axi_b_rd_data_count = AXI_B_RD_DATA_COUNT;
assign AXI_AR_PROG_FULL_THRESH = axi_ar_prog_full_thresh;
assign AXI_AR_PROG_EMPTY_THRESH = axi_ar_prog_empty_thresh;
assign axi_ar_data_count = AXI_AR_DATA_COUNT;
assign axi_ar_wr_data_count = AXI_AR_WR_DATA_COUNT;
assign axi_ar_rd_data_count = AXI_AR_RD_DATA_COUNT;
assign AXI_R_PROG_FULL_THRESH = axi_r_prog_full_thresh;
assign AXI_R_PROG_EMPTY_THRESH = axi_r_prog_empty_thresh;
assign axi_r_data_count = AXI_R_DATA_COUNT;
assign axi_r_wr_data_count = AXI_R_WR_DATA_COUNT;
assign axi_r_rd_data_count = AXI_R_RD_DATA_COUNT;
assign AXIS_PROG_FULL_THRESH = axis_prog_full_thresh;
assign AXIS_PROG_EMPTY_THRESH = axis_prog_empty_thresh;
assign axis_data_count = AXIS_DATA_COUNT;
assign axis_wr_data_count = AXIS_WR_DATA_COUNT;
assign axis_rd_data_count = AXIS_RD_DATA_COUNT;
generate if (C_INTERFACE_TYPE == 0) begin : conv_fifo
FIFO_GENERATOR_v12_0_CONV_VER
#(
.C_COMMON_CLOCK (C_COMMON_CLOCK),
.C_COUNT_TYPE (C_COUNT_TYPE),
.C_DATA_COUNT_WIDTH (C_DATA_COUNT_WIDTH),
.C_DEFAULT_VALUE (C_DEFAULT_VALUE),
.C_DIN_WIDTH (C_DIN_WIDTH),
.C_DOUT_RST_VAL (C_USE_DOUT_RST == 1 ? C_DOUT_RST_VAL : 0),
.C_DOUT_WIDTH (C_DOUT_WIDTH),
.C_ENABLE_RLOCS (C_ENABLE_RLOCS),
.C_FAMILY (C_FAMILY),
.C_FULL_FLAGS_RST_VAL (C_FULL_FLAGS_RST_VAL),
.C_HAS_ALMOST_EMPTY (C_HAS_ALMOST_EMPTY),
.C_HAS_ALMOST_FULL (C_HAS_ALMOST_FULL),
.C_HAS_BACKUP (C_HAS_BACKUP),
.C_HAS_DATA_COUNT (C_HAS_DATA_COUNT),
.C_HAS_INT_CLK (C_HAS_INT_CLK),
.C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT),
.C_HAS_RD_RST (C_HAS_RD_RST),
.C_HAS_RST (C_HAS_RST),
.C_HAS_SRST (C_HAS_SRST),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_HAS_VALID (C_HAS_VALID),
.C_HAS_WR_ACK (C_HAS_WR_ACK),
.C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT),
.C_HAS_WR_RST (C_HAS_WR_RST),
.C_IMPLEMENTATION_TYPE (C_IMPLEMENTATION_TYPE),
.C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL),
.C_MEMORY_TYPE (C_MEMORY_TYPE),
.C_MIF_FILE_NAME (C_MIF_FILE_NAME),
.C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_PRELOAD_LATENCY (C_PRELOAD_LATENCY),
.C_PRELOAD_REGS (C_PRELOAD_REGS),
.C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL),
.C_PROG_EMPTY_THRESH_NEGATE_VAL (C_PROG_EMPTY_THRESH_NEGATE_VAL),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL),
.C_PROG_FULL_THRESH_NEGATE_VAL (C_PROG_FULL_THRESH_NEGATE_VAL),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE),
.C_RD_DATA_COUNT_WIDTH (C_RD_DATA_COUNT_WIDTH),
.C_RD_DEPTH (C_RD_DEPTH),
.C_RD_FREQ (C_RD_FREQ),
.C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_USE_DOUT_RST (C_USE_DOUT_RST),
.C_USE_ECC (C_USE_ECC),
.C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG),
.C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS),
.C_USE_FWFT_DATA_COUNT (C_USE_FWFT_DATA_COUNT),
.C_VALID_LOW (C_VALID_LOW),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH),
.C_WR_DEPTH (C_WR_DEPTH),
.C_WR_FREQ (C_WR_FREQ),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH),
.C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY),
.C_MSGON_VAL (C_MSGON_VAL),
.C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE),
.C_AXI_TYPE (C_AXI_TYPE),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE)
)
fifo_generator_v12_0_conv_dut
(
.BACKUP (BACKUP),
.BACKUP_MARKER (BACKUP_MARKER),
.CLK (CLK),
.RST (RST),
.SRST (SRST),
.WR_CLK (WR_CLK),
.WR_RST (WR_RST),
.RD_CLK (RD_CLK),
.RD_RST (RD_RST),
.DIN (DIN),
.WR_EN (WR_EN),
.RD_EN (RD_EN),
.PROG_EMPTY_THRESH (PROG_EMPTY_THRESH),
.PROG_EMPTY_THRESH_ASSERT (PROG_EMPTY_THRESH_ASSERT),
.PROG_EMPTY_THRESH_NEGATE (PROG_EMPTY_THRESH_NEGATE),
.PROG_FULL_THRESH (PROG_FULL_THRESH),
.PROG_FULL_THRESH_ASSERT (PROG_FULL_THRESH_ASSERT),
.PROG_FULL_THRESH_NEGATE (PROG_FULL_THRESH_NEGATE),
.INT_CLK (INT_CLK),
.INJECTDBITERR (INJECTDBITERR),
.INJECTSBITERR (INJECTSBITERR),
.DOUT (DOUT),
.FULL (FULL),
.ALMOST_FULL (ALMOST_FULL),
.WR_ACK (WR_ACK),
.OVERFLOW (OVERFLOW),
.EMPTY (EMPTY),
.ALMOST_EMPTY (ALMOST_EMPTY),
.VALID (VALID),
.UNDERFLOW (UNDERFLOW),
.DATA_COUNT (DATA_COUNT),
.RD_DATA_COUNT (RD_DATA_COUNT),
.WR_DATA_COUNT (wr_data_count_in),
.PROG_FULL (PROG_FULL),
.PROG_EMPTY (PROG_EMPTY),
.SBITERR (SBITERR),
.DBITERR (DBITERR),
.wr_rst_busy (wr_rst_busy),
.rd_rst_busy (rd_rst_busy),
.wr_rst_i_out (wr_rst_int),
.rd_rst_i_out (rd_rst_int)
);
end endgenerate
localparam IS_8SERIES = (C_FAMILY == "virtexu" || C_FAMILY == "kintexu" || C_FAMILY == "artixu" || C_FAMILY == "virtexum" || C_FAMILY == "zynque") ? 1 : 0;
localparam C_AXI_SIZE_WIDTH = 3;
localparam C_AXI_BURST_WIDTH = 2;
localparam C_AXI_CACHE_WIDTH = 4;
localparam C_AXI_PROT_WIDTH = 3;
localparam C_AXI_QOS_WIDTH = 4;
localparam C_AXI_REGION_WIDTH = 4;
localparam C_AXI_BRESP_WIDTH = 2;
localparam C_AXI_RRESP_WIDTH = 2;
localparam IS_AXI_STREAMING = C_INTERFACE_TYPE == 1 ? 1 : 0;
localparam TDATA_OFFSET = C_HAS_AXIS_TDATA == 1 ? C_DIN_WIDTH_AXIS-C_AXIS_TDATA_WIDTH : C_DIN_WIDTH_AXIS;
localparam TSTRB_OFFSET = C_HAS_AXIS_TSTRB == 1 ? TDATA_OFFSET-C_AXIS_TSTRB_WIDTH : TDATA_OFFSET;
localparam TKEEP_OFFSET = C_HAS_AXIS_TKEEP == 1 ? TSTRB_OFFSET-C_AXIS_TKEEP_WIDTH : TSTRB_OFFSET;
localparam TID_OFFSET = C_HAS_AXIS_TID == 1 ? TKEEP_OFFSET-C_AXIS_TID_WIDTH : TKEEP_OFFSET;
localparam TDEST_OFFSET = C_HAS_AXIS_TDEST == 1 ? TID_OFFSET-C_AXIS_TDEST_WIDTH : TID_OFFSET;
localparam TUSER_OFFSET = C_HAS_AXIS_TUSER == 1 ? TDEST_OFFSET-C_AXIS_TUSER_WIDTH : TDEST_OFFSET;
localparam LOG_DEPTH_AXIS = find_log2(C_WR_DEPTH_AXIS);
localparam LOG_WR_DEPTH = find_log2(C_WR_DEPTH);
function [LOG_DEPTH_AXIS-1:0] bin2gray;
input [LOG_DEPTH_AXIS-1:0] x;
begin
bin2gray = x ^ (x>>1);
end
endfunction
function [LOG_DEPTH_AXIS-1:0] gray2bin;
input [LOG_DEPTH_AXIS-1:0] x;
integer i;
begin
gray2bin[LOG_DEPTH_AXIS-1] = x[LOG_DEPTH_AXIS-1];
for(i=LOG_DEPTH_AXIS-2; i>=0; i=i-1) begin
gray2bin[i] = gray2bin[i+1] ^ x[i];
end
end
endfunction
wire [(LOG_WR_DEPTH)-1 : 0] w_cnt_gc_asreg_last;
wire [LOG_WR_DEPTH-1 : 0] w_q [0:C_SYNCHRONIZER_STAGE] ;
wire [LOG_WR_DEPTH-1 : 0] w_q_temp [1:C_SYNCHRONIZER_STAGE] ;
reg [LOG_WR_DEPTH-1 : 0] w_cnt_rd = 0;
reg [LOG_WR_DEPTH-1 : 0] w_cnt = 0;
reg [LOG_WR_DEPTH-1 : 0] w_cnt_gc = 0;
reg [LOG_WR_DEPTH-1 : 0] r_cnt = 0;
wire [LOG_WR_DEPTH : 0] adj_w_cnt_rd_pad;
wire [LOG_WR_DEPTH : 0] r_inv_pad;
wire [LOG_WR_DEPTH-1 : 0] d_cnt;
reg [LOG_WR_DEPTH : 0] d_cnt_pad = 0;
reg adj_w_cnt_rd_pad_0 = 0;
reg r_inv_pad_0 = 0;
genvar l;
generate for (l = 1; ((l <= C_SYNCHRONIZER_STAGE) && (C_HAS_DATA_COUNTS_AXIS == 3 && C_INTERFACE_TYPE == 0) ); l = l + 1) begin : g_cnt_sync_stage
fifo_generator_v12_0_sync_stage
#(
.C_WIDTH (LOG_WR_DEPTH)
)
rd_stg_inst
(
.RST (rd_rst_int),
.CLK (RD_CLK),
.DIN (w_q[l-1]),
.DOUT (w_q[l])
);
end endgenerate // gpkt_cnt_sync_stage
generate if (C_INTERFACE_TYPE == 0 && C_HAS_DATA_COUNTS_AXIS == 3) begin : fifo_ic_adapter
assign wr_eop_ad = WR_EN & !(FULL);
assign rd_eop_ad = RD_EN & !(EMPTY);
always @ (posedge wr_rst_int or posedge WR_CLK)
begin
if (wr_rst_int)
w_cnt <= 1'b0;
else if (wr_eop_ad)
w_cnt <= w_cnt + 1;
end
always @ (posedge wr_rst_int or posedge WR_CLK)
begin
if (wr_rst_int)
w_cnt_gc <= 1'b0;
else
w_cnt_gc <= bin2gray(w_cnt);
end
assign w_q[0] = w_cnt_gc;
assign w_cnt_gc_asreg_last = w_q[C_SYNCHRONIZER_STAGE];
always @ (posedge rd_rst_int or posedge RD_CLK)
begin
if (rd_rst_int)
w_cnt_rd <= 1'b0;
else
w_cnt_rd <= gray2bin(w_cnt_gc_asreg_last);
end
always @ (posedge rd_rst_int or posedge RD_CLK)
begin
if (rd_rst_int)
r_cnt <= 1'b0;
else if (rd_eop_ad)
r_cnt <= r_cnt + 1;
end
// Take the difference of write and read packet count
// Logic is similar to rd_pe_as
assign adj_w_cnt_rd_pad[LOG_WR_DEPTH : 1] = w_cnt_rd;
assign r_inv_pad[LOG_WR_DEPTH : 1] = ~r_cnt;
assign adj_w_cnt_rd_pad[0] = adj_w_cnt_rd_pad_0;
assign r_inv_pad[0] = r_inv_pad_0;
always @ ( rd_eop_ad )
begin
if (!rd_eop_ad) begin
adj_w_cnt_rd_pad_0 <= 1'b1;
r_inv_pad_0 <= 1'b1;
end else begin
adj_w_cnt_rd_pad_0 <= 1'b0;
r_inv_pad_0 <= 1'b0;
end
end
always @ (posedge rd_rst_int or posedge RD_CLK)
begin
if (rd_rst_int)
d_cnt_pad <= 1'b0;
else
d_cnt_pad <= adj_w_cnt_rd_pad + r_inv_pad ;
end
assign d_cnt = d_cnt_pad [LOG_WR_DEPTH : 1] ;
assign WR_DATA_COUNT = d_cnt;
end endgenerate // fifo_ic_adapter
generate if (C_INTERFACE_TYPE == 0 && C_HAS_DATA_COUNTS_AXIS != 3) begin : fifo_icn_adapter
assign WR_DATA_COUNT = wr_data_count_in;
end endgenerate // fifo_icn_adapter
wire inverted_reset = ~S_ARESETN;
wire axi_rs_rst;
reg rst_d1 = 0 ;
reg rst_d2 = 0 ;
wire [C_DIN_WIDTH_AXIS-1:0] axis_din ;
wire [C_DIN_WIDTH_AXIS-1:0] axis_dout ;
wire axis_full ;
wire axis_almost_full ;
wire axis_empty ;
wire axis_s_axis_tready;
wire axis_m_axis_tvalid;
wire axis_wr_en ;
wire axis_rd_en ;
wire axis_we ;
wire axis_re ;
wire [C_WR_PNTR_WIDTH_AXIS:0] axis_dc;
reg axis_pkt_read = 1'b0;
wire axis_rd_rst;
wire axis_wr_rst;
generate if (C_INTERFACE_TYPE > 0 && (C_AXIS_TYPE == 1 || C_WACH_TYPE == 1 ||
C_WDCH_TYPE == 1 || C_WRCH_TYPE == 1 || C_RACH_TYPE == 1 || C_RDCH_TYPE == 1)) begin : gaxi_rs_rst
always @ (posedge inverted_reset or posedge S_ACLK) begin
if (inverted_reset) begin
rst_d1 <= 1'b1;
rst_d2 <= 1'b1;
end else begin
rst_d1 <= #`TCQ 1'b0;
rst_d2 <= #`TCQ rst_d1;
end
end
assign axi_rs_rst = rst_d2;
end endgenerate // gaxi_rs_rst
generate if (IS_AXI_STREAMING == 1 && C_AXIS_TYPE == 0) begin : axi_streaming
// Write protection when almost full or prog_full is high
assign axis_we = (C_PROG_FULL_TYPE_AXIS != 0) ? axis_s_axis_tready & S_AXIS_TVALID :
(C_APPLICATION_TYPE_AXIS == 1) ? axis_s_axis_tready & S_AXIS_TVALID : S_AXIS_TVALID;
// Read protection when almost empty or prog_empty is high
assign axis_re = (C_PROG_EMPTY_TYPE_AXIS != 0) ? axis_m_axis_tvalid & M_AXIS_TREADY :
(C_APPLICATION_TYPE_AXIS == 1) ? axis_m_axis_tvalid & M_AXIS_TREADY : M_AXIS_TREADY;
assign axis_wr_en = (C_HAS_SLAVE_CE == 1) ? axis_we & S_ACLK_EN : axis_we;
assign axis_rd_en = (C_HAS_MASTER_CE == 1) ? axis_re & M_ACLK_EN : axis_re;
FIFO_GENERATOR_v12_0_CONV_VER
#(
.C_FAMILY (C_FAMILY),
.C_COMMON_CLOCK (C_COMMON_CLOCK),
.C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_AXIS == 1 || C_IMPLEMENTATION_TYPE_AXIS == 11) ? 1 :
(C_IMPLEMENTATION_TYPE_AXIS == 2 || C_IMPLEMENTATION_TYPE_AXIS == 12) ? 2 : 4),
.C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_AXIS == 1 || C_IMPLEMENTATION_TYPE_AXIS == 2) ? 0 :
(C_IMPLEMENTATION_TYPE_AXIS == 11 || C_IMPLEMENTATION_TYPE_AXIS == 12) ? 2 : 6),
.C_PRELOAD_REGS (1), // always FWFT for AXI
.C_PRELOAD_LATENCY (0), // always FWFT for AXI
.C_DIN_WIDTH (C_DIN_WIDTH_AXIS),
.C_WR_DEPTH (C_WR_DEPTH_AXIS),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_AXIS),
.C_DOUT_WIDTH (C_DIN_WIDTH_AXIS),
.C_RD_DEPTH (C_WR_DEPTH_AXIS),
.C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_AXIS),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_AXIS),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_AXIS),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_AXIS),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_AXIS),
.C_USE_ECC (C_USE_ECC_AXIS),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_AXIS),
.C_HAS_ALMOST_EMPTY (0),
.C_HAS_ALMOST_FULL (C_APPLICATION_TYPE_AXIS == 1 ? 1: 0),
.C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE),
.C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG),
.C_FIFO_TYPE (C_APPLICATION_TYPE_AXIS == 1 ? 0: C_APPLICATION_TYPE_AXIS),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE),
.C_HAS_WR_RST (0),
.C_HAS_RD_RST (0),
.C_HAS_RST (1),
.C_HAS_SRST (0),
.C_DOUT_RST_VAL (0),
.C_HAS_VALID (0),
.C_VALID_LOW (C_VALID_LOW),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_HAS_WR_ACK (0),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_AXIS == 1) ? 1 : 0),
.C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_AXIS + 1),
.C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_AXIS == 1) ? 1 : 0),
.C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_AXIS + 1),
.C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true
.C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_AXIS == 1) ? 1 : 0),
.C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_AXIS + 1),
.C_FULL_FLAGS_RST_VAL (1),
.C_USE_DOUT_RST (0),
.C_MSGON_VAL (C_MSGON_VAL),
.C_ENABLE_RST_SYNC (1),
.C_COUNT_TYPE (C_COUNT_TYPE),
.C_DEFAULT_VALUE (C_DEFAULT_VALUE),
.C_ENABLE_RLOCS (C_ENABLE_RLOCS),
.C_HAS_BACKUP (C_HAS_BACKUP),
.C_HAS_INT_CLK (C_HAS_INT_CLK),
.C_MIF_FILE_NAME (C_MIF_FILE_NAME),
.C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE),
.C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL),
.C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE),
.C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE),
.C_RD_FREQ (C_RD_FREQ),
.C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS),
.C_WR_FREQ (C_WR_FREQ),
.C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY)
)
fifo_generator_v12_0_axis_dut
(
.CLK (S_ACLK),
.WR_CLK (S_ACLK),
.RD_CLK (M_ACLK),
.RST (inverted_reset),
.SRST (1'b0),
.WR_RST (inverted_reset),
.RD_RST (inverted_reset),
.WR_EN (axis_wr_en),
.RD_EN (axis_rd_en),
.PROG_FULL_THRESH (AXIS_PROG_FULL_THRESH),
.PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_AXIS{1'b0}}),
.PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_AXIS{1'b0}}),
.PROG_EMPTY_THRESH (AXIS_PROG_EMPTY_THRESH),
.PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_AXIS{1'b0}}),
.PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_AXIS{1'b0}}),
.INJECTDBITERR (AXIS_INJECTDBITERR),
.INJECTSBITERR (AXIS_INJECTSBITERR),
.DIN (axis_din),
.DOUT (axis_dout),
.FULL (axis_full),
.EMPTY (axis_empty),
.ALMOST_FULL (axis_almost_full),
.PROG_FULL (AXIS_PROG_FULL),
.ALMOST_EMPTY (),
.PROG_EMPTY (AXIS_PROG_EMPTY),
.WR_ACK (),
.OVERFLOW (AXIS_OVERFLOW),
.VALID (),
.UNDERFLOW (AXIS_UNDERFLOW),
.DATA_COUNT (axis_dc),
.RD_DATA_COUNT (AXIS_RD_DATA_COUNT),
.WR_DATA_COUNT (AXIS_WR_DATA_COUNT),
.SBITERR (AXIS_SBITERR),
.DBITERR (AXIS_DBITERR),
.wr_rst_busy (wr_rst_busy_axis),
.rd_rst_busy (rd_rst_busy_axis),
.wr_rst_i_out (axis_wr_rst),
.rd_rst_i_out (axis_rd_rst),
.BACKUP (BACKUP),
.BACKUP_MARKER (BACKUP_MARKER),
.INT_CLK (INT_CLK)
);
assign axis_s_axis_tready = (IS_8SERIES == 0) ? ~axis_full : (C_IMPLEMENTATION_TYPE_AXIS == 5 || C_IMPLEMENTATION_TYPE_AXIS == 13) ? ~(axis_full | wr_rst_busy_axis) : ~axis_full;
assign axis_m_axis_tvalid = (C_APPLICATION_TYPE_AXIS != 1) ? ~axis_empty : ~axis_empty & axis_pkt_read;
assign S_AXIS_TREADY = axis_s_axis_tready;
assign M_AXIS_TVALID = axis_m_axis_tvalid;
end endgenerate // axi_streaming
wire axis_wr_eop;
reg axis_wr_eop_d1 = 1'b0;
wire axis_rd_eop;
integer axis_pkt_cnt;
generate if (C_APPLICATION_TYPE_AXIS == 1 && C_COMMON_CLOCK == 1) begin : gaxis_pkt_fifo_cc
assign axis_wr_eop = axis_wr_en & S_AXIS_TLAST;
assign axis_rd_eop = axis_rd_en & axis_dout[0];
always @ (posedge inverted_reset or posedge S_ACLK)
begin
if (inverted_reset)
axis_pkt_read <= 1'b0;
else if (axis_rd_eop && (axis_pkt_cnt == 1) && ~axis_wr_eop_d1)
axis_pkt_read <= 1'b0;
else if ((axis_pkt_cnt > 0) || (axis_almost_full && ~axis_empty))
axis_pkt_read <= 1'b1;
end
always @ (posedge inverted_reset or posedge S_ACLK)
begin
if (inverted_reset)
axis_wr_eop_d1 <= 1'b0;
else
axis_wr_eop_d1 <= axis_wr_eop;
end
always @ (posedge inverted_reset or posedge S_ACLK)
begin
if (inverted_reset)
axis_pkt_cnt <= 0;
else if (axis_wr_eop_d1 && ~axis_rd_eop)
axis_pkt_cnt <= axis_pkt_cnt + 1;
else if (axis_rd_eop && ~axis_wr_eop_d1)
axis_pkt_cnt <= axis_pkt_cnt - 1;
end
end endgenerate // gaxis_pkt_fifo_cc
reg [LOG_DEPTH_AXIS-1 : 0] axis_wpkt_cnt_gc = 0;
wire [(LOG_DEPTH_AXIS)-1 : 0] axis_wpkt_cnt_gc_asreg_last;
wire axis_rd_has_rst;
wire [0:C_SYNCHRONIZER_STAGE] axis_af_q ;
wire [LOG_DEPTH_AXIS-1 : 0] wpkt_q [0:C_SYNCHRONIZER_STAGE] ;
wire [1:C_SYNCHRONIZER_STAGE] axis_af_q_temp = 0;
wire [LOG_DEPTH_AXIS-1 : 0] wpkt_q_temp [1:C_SYNCHRONIZER_STAGE] ;
reg [LOG_DEPTH_AXIS-1 : 0] axis_wpkt_cnt_rd = 0;
reg [LOG_DEPTH_AXIS-1 : 0] axis_wpkt_cnt = 0;
reg [LOG_DEPTH_AXIS-1 : 0] axis_rpkt_cnt = 0;
wire [LOG_DEPTH_AXIS : 0] adj_axis_wpkt_cnt_rd_pad;
wire [LOG_DEPTH_AXIS : 0] rpkt_inv_pad;
wire [LOG_DEPTH_AXIS-1 : 0] diff_pkt_cnt;
reg [LOG_DEPTH_AXIS : 0] diff_pkt_cnt_pad = 0;
reg adj_axis_wpkt_cnt_rd_pad_0 = 0;
reg rpkt_inv_pad_0 = 0;
wire axis_af_rd ;
generate if (C_HAS_RST == 1) begin : rst_blk_has
assign axis_rd_has_rst = axis_rd_rst;
end endgenerate //rst_blk_has
generate if (C_HAS_RST == 0) begin :rst_blk_no
assign axis_rd_has_rst = 1'b0;
end endgenerate //rst_blk_no
genvar i;
generate for (i = 1; ((i <= C_SYNCHRONIZER_STAGE) && (C_APPLICATION_TYPE_AXIS == 1 && C_COMMON_CLOCK == 0) ); i = i + 1) begin : gpkt_cnt_sync_stage
fifo_generator_v12_0_sync_stage
#(
.C_WIDTH (LOG_DEPTH_AXIS)
)
rd_stg_inst
(
.RST (axis_rd_has_rst),
.CLK (M_ACLK),
.DIN (wpkt_q[i-1]),
.DOUT (wpkt_q[i])
);
fifo_generator_v12_0_sync_stage
#(
.C_WIDTH (1)
)
wr_stg_inst
(
.RST (axis_rd_has_rst),
.CLK (M_ACLK),
.DIN (axis_af_q[i-1]),
.DOUT (axis_af_q[i])
);
end endgenerate // gpkt_cnt_sync_stage
generate if (C_APPLICATION_TYPE_AXIS == 1 && C_COMMON_CLOCK == 0) begin : gaxis_pkt_fifo_ic
assign axis_wr_eop = axis_wr_en & S_AXIS_TLAST;
assign axis_rd_eop = axis_rd_en & axis_dout[0];
always @ (posedge axis_rd_has_rst or posedge M_ACLK)
begin
if (axis_rd_has_rst)
axis_pkt_read <= 1'b0;
else if (axis_rd_eop && (diff_pkt_cnt == 1))
axis_pkt_read <= 1'b0;
else if ((diff_pkt_cnt > 0) || (axis_af_rd && ~axis_empty))
axis_pkt_read <= 1'b1;
end
always @ (posedge axis_wr_rst or posedge S_ACLK)
begin
if (axis_wr_rst)
axis_wpkt_cnt <= 1'b0;
else if (axis_wr_eop)
axis_wpkt_cnt <= axis_wpkt_cnt + 1;
end
always @ (posedge axis_wr_rst or posedge S_ACLK)
begin
if (axis_wr_rst)
axis_wpkt_cnt_gc <= 1'b0;
else
axis_wpkt_cnt_gc <= bin2gray(axis_wpkt_cnt);
end
assign wpkt_q[0] = axis_wpkt_cnt_gc;
assign axis_wpkt_cnt_gc_asreg_last = wpkt_q[C_SYNCHRONIZER_STAGE];
assign axis_af_q[0] = axis_almost_full;
//assign axis_af_q[1:C_SYNCHRONIZER_STAGE] = axis_af_q_temp[1:C_SYNCHRONIZER_STAGE];
assign axis_af_rd = axis_af_q[C_SYNCHRONIZER_STAGE];
always @ (posedge axis_rd_has_rst or posedge M_ACLK)
begin
if (axis_rd_has_rst)
axis_wpkt_cnt_rd <= 1'b0;
else
axis_wpkt_cnt_rd <= gray2bin(axis_wpkt_cnt_gc_asreg_last);
end
always @ (posedge axis_rd_rst or posedge M_ACLK)
begin
if (axis_rd_has_rst)
axis_rpkt_cnt <= 1'b0;
else if (axis_rd_eop)
axis_rpkt_cnt <= axis_rpkt_cnt + 1;
end
// Take the difference of write and read packet count
// Logic is similar to rd_pe_as
assign adj_axis_wpkt_cnt_rd_pad[LOG_DEPTH_AXIS : 1] = axis_wpkt_cnt_rd;
assign rpkt_inv_pad[LOG_DEPTH_AXIS : 1] = ~axis_rpkt_cnt;
assign adj_axis_wpkt_cnt_rd_pad[0] = adj_axis_wpkt_cnt_rd_pad_0;
assign rpkt_inv_pad[0] = rpkt_inv_pad_0;
always @ ( axis_rd_eop )
begin
if (!axis_rd_eop) begin
adj_axis_wpkt_cnt_rd_pad_0 <= 1'b1;
rpkt_inv_pad_0 <= 1'b1;
end else begin
adj_axis_wpkt_cnt_rd_pad_0 <= 1'b0;
rpkt_inv_pad_0 <= 1'b0;
end
end
always @ (posedge axis_rd_rst or posedge M_ACLK)
begin
if (axis_rd_has_rst)
diff_pkt_cnt_pad <= 1'b0;
else
diff_pkt_cnt_pad <= adj_axis_wpkt_cnt_rd_pad + rpkt_inv_pad ;
end
assign diff_pkt_cnt = diff_pkt_cnt_pad [LOG_DEPTH_AXIS : 1] ;
end endgenerate // gaxis_pkt_fifo_ic
// Generate the accurate data count for axi stream packet fifo configuration
reg [C_WR_PNTR_WIDTH_AXIS:0] axis_dc_pkt_fifo = 0;
generate if (IS_AXI_STREAMING == 1 && C_HAS_DATA_COUNTS_AXIS == 1 && C_APPLICATION_TYPE_AXIS == 1) begin : gdc_pkt
always @ (posedge inverted_reset or posedge S_ACLK)
begin
if (inverted_reset)
axis_dc_pkt_fifo <= 0;
else if (axis_wr_en && (~axis_rd_en))
axis_dc_pkt_fifo <= #`TCQ axis_dc_pkt_fifo + 1;
else if (~axis_wr_en && axis_rd_en)
axis_dc_pkt_fifo <= #`TCQ axis_dc_pkt_fifo - 1;
end
assign AXIS_DATA_COUNT = axis_dc_pkt_fifo;
end endgenerate // gdc_pkt
generate if (IS_AXI_STREAMING == 1 && C_HAS_DATA_COUNTS_AXIS == 0 && C_APPLICATION_TYPE_AXIS == 1) begin : gndc_pkt
assign AXIS_DATA_COUNT = 0;
end endgenerate // gndc_pkt
generate if (IS_AXI_STREAMING == 1 && C_APPLICATION_TYPE_AXIS != 1) begin : gdc
assign AXIS_DATA_COUNT = axis_dc;
end endgenerate // gdc
// Register Slice for Write Address Channel
generate if (C_AXIS_TYPE == 1) begin : gaxis_reg_slice
assign axis_wr_en = (C_HAS_SLAVE_CE == 1) ? S_AXIS_TVALID & S_ACLK_EN : S_AXIS_TVALID;
assign axis_rd_en = (C_HAS_MASTER_CE == 1) ? M_AXIS_TREADY & M_ACLK_EN : M_AXIS_TREADY;
fifo_generator_v12_0_axic_reg_slice
#(
.C_FAMILY (C_FAMILY),
.C_DATA_WIDTH (C_DIN_WIDTH_AXIS),
.C_REG_CONFIG (C_REG_SLICE_MODE_AXIS)
)
axis_reg_slice_inst
(
// System Signals
.ACLK (S_ACLK),
.ARESET (axi_rs_rst),
// Slave side
.S_PAYLOAD_DATA (axis_din),
.S_VALID (axis_wr_en),
.S_READY (S_AXIS_TREADY),
// Master side
.M_PAYLOAD_DATA (axis_dout),
.M_VALID (M_AXIS_TVALID),
.M_READY (axis_rd_en)
);
end endgenerate // gaxis_reg_slice
generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TDATA == 1) begin : tdata
assign axis_din[C_DIN_WIDTH_AXIS-1:TDATA_OFFSET] = S_AXIS_TDATA;
assign M_AXIS_TDATA = axis_dout[C_DIN_WIDTH_AXIS-1:TDATA_OFFSET];
end endgenerate
generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TSTRB == 1) begin : tstrb
assign axis_din[TDATA_OFFSET-1:TSTRB_OFFSET] = S_AXIS_TSTRB;
assign M_AXIS_TSTRB = axis_dout[TDATA_OFFSET-1:TSTRB_OFFSET];
end endgenerate
generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TKEEP == 1) begin : tkeep
assign axis_din[TSTRB_OFFSET-1:TKEEP_OFFSET] = S_AXIS_TKEEP;
assign M_AXIS_TKEEP = axis_dout[TSTRB_OFFSET-1:TKEEP_OFFSET];
end endgenerate
generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TID == 1) begin : tid
assign axis_din[TKEEP_OFFSET-1:TID_OFFSET] = S_AXIS_TID;
assign M_AXIS_TID = axis_dout[TKEEP_OFFSET-1:TID_OFFSET];
end endgenerate
generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TDEST == 1) begin : tdest
assign axis_din[TID_OFFSET-1:TDEST_OFFSET] = S_AXIS_TDEST;
assign M_AXIS_TDEST = axis_dout[TID_OFFSET-1:TDEST_OFFSET];
end endgenerate
generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TUSER == 1) begin : tuser
assign axis_din[TDEST_OFFSET-1:TUSER_OFFSET] = S_AXIS_TUSER;
assign M_AXIS_TUSER = axis_dout[TDEST_OFFSET-1:TUSER_OFFSET];
end endgenerate
generate if ((IS_AXI_STREAMING == 1 || C_AXIS_TYPE == 1) && C_HAS_AXIS_TLAST == 1) begin : tlast
assign axis_din[0] = S_AXIS_TLAST;
assign M_AXIS_TLAST = axis_dout[0];
end endgenerate
//###########################################################################
// AXI FULL Write Channel (axi_write_channel)
//###########################################################################
localparam IS_AXI_FULL = ((C_INTERFACE_TYPE == 2) && (C_AXI_TYPE != 2)) ? 1 : 0;
localparam IS_AXI_LITE = ((C_INTERFACE_TYPE == 2) && (C_AXI_TYPE == 2)) ? 1 : 0;
localparam IS_AXI_FULL_WACH = ((IS_AXI_FULL == 1) && (C_WACH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_FULL_WDCH = ((IS_AXI_FULL == 1) && (C_WDCH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_FULL_WRCH = ((IS_AXI_FULL == 1) && (C_WRCH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_FULL_RACH = ((IS_AXI_FULL == 1) && (C_RACH_TYPE == 0) && C_HAS_AXI_RD_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_FULL_RDCH = ((IS_AXI_FULL == 1) && (C_RDCH_TYPE == 0) && C_HAS_AXI_RD_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_LITE_WACH = ((IS_AXI_LITE == 1) && (C_WACH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_LITE_WDCH = ((IS_AXI_LITE == 1) && (C_WDCH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_LITE_WRCH = ((IS_AXI_LITE == 1) && (C_WRCH_TYPE == 0) && C_HAS_AXI_WR_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_LITE_RACH = ((IS_AXI_LITE == 1) && (C_RACH_TYPE == 0) && C_HAS_AXI_RD_CHANNEL == 1) ? 1 : 0;
localparam IS_AXI_LITE_RDCH = ((IS_AXI_LITE == 1) && (C_RDCH_TYPE == 0) && C_HAS_AXI_RD_CHANNEL == 1) ? 1 : 0;
localparam IS_WR_ADDR_CH = ((IS_AXI_FULL_WACH == 1) || (IS_AXI_LITE_WACH == 1)) ? 1 : 0;
localparam IS_WR_DATA_CH = ((IS_AXI_FULL_WDCH == 1) || (IS_AXI_LITE_WDCH == 1)) ? 1 : 0;
localparam IS_WR_RESP_CH = ((IS_AXI_FULL_WRCH == 1) || (IS_AXI_LITE_WRCH == 1)) ? 1 : 0;
localparam IS_RD_ADDR_CH = ((IS_AXI_FULL_RACH == 1) || (IS_AXI_LITE_RACH == 1)) ? 1 : 0;
localparam IS_RD_DATA_CH = ((IS_AXI_FULL_RDCH == 1) || (IS_AXI_LITE_RDCH == 1)) ? 1 : 0;
localparam AWID_OFFSET = (C_AXI_TYPE != 2 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_WACH - C_AXI_ID_WIDTH : C_DIN_WIDTH_WACH;
localparam AWADDR_OFFSET = AWID_OFFSET - C_AXI_ADDR_WIDTH;
localparam AWLEN_OFFSET = C_AXI_TYPE != 2 ? AWADDR_OFFSET - C_AXI_LEN_WIDTH : AWADDR_OFFSET;
localparam AWSIZE_OFFSET = C_AXI_TYPE != 2 ? AWLEN_OFFSET - C_AXI_SIZE_WIDTH : AWLEN_OFFSET;
localparam AWBURST_OFFSET = C_AXI_TYPE != 2 ? AWSIZE_OFFSET - C_AXI_BURST_WIDTH : AWSIZE_OFFSET;
localparam AWLOCK_OFFSET = C_AXI_TYPE != 2 ? AWBURST_OFFSET - C_AXI_LOCK_WIDTH : AWBURST_OFFSET;
localparam AWCACHE_OFFSET = C_AXI_TYPE != 2 ? AWLOCK_OFFSET - C_AXI_CACHE_WIDTH : AWLOCK_OFFSET;
localparam AWPROT_OFFSET = AWCACHE_OFFSET - C_AXI_PROT_WIDTH;
localparam AWQOS_OFFSET = AWPROT_OFFSET - C_AXI_QOS_WIDTH;
localparam AWREGION_OFFSET = C_AXI_TYPE == 1 ? AWQOS_OFFSET - C_AXI_REGION_WIDTH : AWQOS_OFFSET;
localparam AWUSER_OFFSET = C_HAS_AXI_AWUSER == 1 ? AWREGION_OFFSET-C_AXI_AWUSER_WIDTH : AWREGION_OFFSET;
localparam WID_OFFSET = (C_AXI_TYPE == 3 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_WDCH - C_AXI_ID_WIDTH : C_DIN_WIDTH_WDCH;
localparam WDATA_OFFSET = WID_OFFSET - C_AXI_DATA_WIDTH;
localparam WSTRB_OFFSET = WDATA_OFFSET - C_AXI_DATA_WIDTH/8;
localparam WUSER_OFFSET = C_HAS_AXI_WUSER == 1 ? WSTRB_OFFSET-C_AXI_WUSER_WIDTH : WSTRB_OFFSET;
localparam BID_OFFSET = (C_AXI_TYPE != 2 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_WRCH - C_AXI_ID_WIDTH : C_DIN_WIDTH_WRCH;
localparam BRESP_OFFSET = BID_OFFSET - C_AXI_BRESP_WIDTH;
localparam BUSER_OFFSET = C_HAS_AXI_BUSER == 1 ? BRESP_OFFSET-C_AXI_BUSER_WIDTH : BRESP_OFFSET;
wire [C_DIN_WIDTH_WACH-1:0] wach_din ;
wire [C_DIN_WIDTH_WACH-1:0] wach_dout ;
wire [C_DIN_WIDTH_WACH-1:0] wach_dout_pkt ;
wire wach_full ;
wire wach_almost_full ;
wire wach_prog_full ;
wire wach_empty ;
wire wach_almost_empty ;
wire wach_prog_empty ;
wire [C_DIN_WIDTH_WDCH-1:0] wdch_din ;
wire [C_DIN_WIDTH_WDCH-1:0] wdch_dout ;
wire wdch_full ;
wire wdch_almost_full ;
wire wdch_prog_full ;
wire wdch_empty ;
wire wdch_almost_empty ;
wire wdch_prog_empty ;
wire [C_DIN_WIDTH_WRCH-1:0] wrch_din ;
wire [C_DIN_WIDTH_WRCH-1:0] wrch_dout ;
wire wrch_full ;
wire wrch_almost_full ;
wire wrch_prog_full ;
wire wrch_empty ;
wire wrch_almost_empty ;
wire wrch_prog_empty ;
wire axi_aw_underflow_i;
wire axi_w_underflow_i ;
wire axi_b_underflow_i ;
wire axi_aw_overflow_i ;
wire axi_w_overflow_i ;
wire axi_b_overflow_i ;
wire axi_wr_underflow_i;
wire axi_wr_overflow_i ;
wire wach_s_axi_awready;
wire wach_m_axi_awvalid;
wire wach_wr_en ;
wire wach_rd_en ;
wire wdch_s_axi_wready ;
wire wdch_m_axi_wvalid ;
wire wdch_wr_en ;
wire wdch_rd_en ;
wire wrch_s_axi_bvalid ;
wire wrch_m_axi_bready ;
wire wrch_wr_en ;
wire wrch_rd_en ;
wire txn_count_up ;
wire txn_count_down ;
wire awvalid_en ;
wire awvalid_pkt ;
wire awready_pkt ;
integer wr_pkt_count ;
wire wach_we ;
wire wach_re ;
wire wdch_we ;
wire wdch_re ;
wire wrch_we ;
wire wrch_re ;
generate if (IS_WR_ADDR_CH == 1) begin : axi_write_address_channel
// Write protection when almost full or prog_full is high
assign wach_we = (C_PROG_FULL_TYPE_WACH != 0) ? wach_s_axi_awready & S_AXI_AWVALID : S_AXI_AWVALID;
// Read protection when almost empty or prog_empty is high
assign wach_re = (C_PROG_EMPTY_TYPE_WACH != 0 && C_APPLICATION_TYPE_WACH == 1) ?
wach_m_axi_awvalid & awready_pkt & awvalid_en :
(C_PROG_EMPTY_TYPE_WACH != 0 && C_APPLICATION_TYPE_WACH != 1) ?
M_AXI_AWREADY && wach_m_axi_awvalid :
(C_PROG_EMPTY_TYPE_WACH == 0 && C_APPLICATION_TYPE_WACH == 1) ?
awready_pkt & awvalid_en :
(C_PROG_EMPTY_TYPE_WACH == 0 && C_APPLICATION_TYPE_WACH != 1) ?
M_AXI_AWREADY : 1'b0;
assign wach_wr_en = (C_HAS_SLAVE_CE == 1) ? wach_we & S_ACLK_EN : wach_we;
assign wach_rd_en = (C_HAS_MASTER_CE == 1) ? wach_re & M_ACLK_EN : wach_re;
FIFO_GENERATOR_v12_0_CONV_VER
#(
.C_FAMILY (C_FAMILY),
.C_COMMON_CLOCK (C_COMMON_CLOCK),
.C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_WACH == 1 || C_IMPLEMENTATION_TYPE_WACH == 11) ? 1 :
(C_IMPLEMENTATION_TYPE_WACH == 2 || C_IMPLEMENTATION_TYPE_WACH == 12) ? 2 : 4),
.C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_WACH == 1 || C_IMPLEMENTATION_TYPE_WACH == 2) ? 0 :
(C_IMPLEMENTATION_TYPE_WACH == 11 || C_IMPLEMENTATION_TYPE_WACH == 12) ? 2 : 6),
.C_PRELOAD_REGS (1), // always FWFT for AXI
.C_PRELOAD_LATENCY (0), // always FWFT for AXI
.C_DIN_WIDTH (C_DIN_WIDTH_WACH),
.C_WR_DEPTH (C_WR_DEPTH_WACH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_WACH),
.C_DOUT_WIDTH (C_DIN_WIDTH_WACH),
.C_RD_DEPTH (C_WR_DEPTH_WACH),
.C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_WACH),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_WACH),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_WACH),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_WACH),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_WACH),
.C_USE_ECC (C_USE_ECC_WACH),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_WACH),
.C_HAS_ALMOST_EMPTY (0),
.C_HAS_ALMOST_FULL (0),
.C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE),
.C_FIFO_TYPE ((C_APPLICATION_TYPE_WACH == 1)?0:C_APPLICATION_TYPE_WACH),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE),
.C_HAS_WR_RST (0),
.C_HAS_RD_RST (0),
.C_HAS_RST (1),
.C_HAS_SRST (0),
.C_DOUT_RST_VAL (0),
.C_HAS_VALID (0),
.C_VALID_LOW (C_VALID_LOW),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_HAS_WR_ACK (0),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_WACH == 1) ? 1 : 0),
.C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WACH + 1),
.C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WACH == 1) ? 1 : 0),
.C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WACH + 1),
.C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true
.C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WACH == 1) ? 1 : 0),
.C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WACH + 1),
.C_FULL_FLAGS_RST_VAL (1),
.C_USE_EMBEDDED_REG (0),
.C_USE_DOUT_RST (0),
.C_MSGON_VAL (C_MSGON_VAL),
.C_ENABLE_RST_SYNC (1),
.C_COUNT_TYPE (C_COUNT_TYPE),
.C_DEFAULT_VALUE (C_DEFAULT_VALUE),
.C_ENABLE_RLOCS (C_ENABLE_RLOCS),
.C_HAS_BACKUP (C_HAS_BACKUP),
.C_HAS_INT_CLK (C_HAS_INT_CLK),
.C_MIF_FILE_NAME (C_MIF_FILE_NAME),
.C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE),
.C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL),
.C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE),
.C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE),
.C_RD_FREQ (C_RD_FREQ),
.C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS),
.C_WR_FREQ (C_WR_FREQ),
.C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY)
)
fifo_generator_v12_0_wach_dut
(
.CLK (S_ACLK),
.WR_CLK (S_ACLK),
.RD_CLK (M_ACLK),
.RST (inverted_reset),
.SRST (1'b0),
.WR_RST (inverted_reset),
.RD_RST (inverted_reset),
.WR_EN (wach_wr_en),
.RD_EN (wach_rd_en),
.PROG_FULL_THRESH (AXI_AW_PROG_FULL_THRESH),
.PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WACH{1'b0}}),
.PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WACH{1'b0}}),
.PROG_EMPTY_THRESH (AXI_AW_PROG_EMPTY_THRESH),
.PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WACH{1'b0}}),
.PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WACH{1'b0}}),
.INJECTDBITERR (AXI_AW_INJECTDBITERR),
.INJECTSBITERR (AXI_AW_INJECTSBITERR),
.DIN (wach_din),
.DOUT (wach_dout_pkt),
.FULL (wach_full),
.EMPTY (wach_empty),
.ALMOST_FULL (),
.PROG_FULL (AXI_AW_PROG_FULL),
.ALMOST_EMPTY (),
.PROG_EMPTY (AXI_AW_PROG_EMPTY),
.WR_ACK (),
.OVERFLOW (axi_aw_overflow_i),
.VALID (),
.UNDERFLOW (axi_aw_underflow_i),
.DATA_COUNT (AXI_AW_DATA_COUNT),
.RD_DATA_COUNT (AXI_AW_RD_DATA_COUNT),
.WR_DATA_COUNT (AXI_AW_WR_DATA_COUNT),
.SBITERR (AXI_AW_SBITERR),
.DBITERR (AXI_AW_DBITERR),
.wr_rst_busy (wr_rst_busy_wach),
.rd_rst_busy (rd_rst_busy_wach),
.wr_rst_i_out (),
.rd_rst_i_out (),
.BACKUP (BACKUP),
.BACKUP_MARKER (BACKUP_MARKER),
.INT_CLK (INT_CLK)
);
assign wach_s_axi_awready = (IS_8SERIES == 0) ? ~wach_full : (C_IMPLEMENTATION_TYPE_WACH == 5 || C_IMPLEMENTATION_TYPE_WACH == 13) ? ~(wach_full | wr_rst_busy_wach) : ~wach_full;
assign wach_m_axi_awvalid = ~wach_empty;
assign S_AXI_AWREADY = wach_s_axi_awready;
assign AXI_AW_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_aw_underflow_i : 0;
assign AXI_AW_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_aw_overflow_i : 0;
end endgenerate // axi_write_address_channel
// Register Slice for Write Address Channel
generate if (C_WACH_TYPE == 1) begin : gwach_reg_slice
fifo_generator_v12_0_axic_reg_slice
#(
.C_FAMILY (C_FAMILY),
.C_DATA_WIDTH (C_DIN_WIDTH_WACH),
.C_REG_CONFIG (C_REG_SLICE_MODE_WACH)
)
wach_reg_slice_inst
(
// System Signals
.ACLK (S_ACLK),
.ARESET (axi_rs_rst),
// Slave side
.S_PAYLOAD_DATA (wach_din),
.S_VALID (S_AXI_AWVALID),
.S_READY (S_AXI_AWREADY),
// Master side
.M_PAYLOAD_DATA (wach_dout),
.M_VALID (M_AXI_AWVALID),
.M_READY (M_AXI_AWREADY)
);
end endgenerate // gwach_reg_slice
generate if (C_APPLICATION_TYPE_WACH == 1 && C_HAS_AXI_WR_CHANNEL == 1) begin : axi_mm_pkt_fifo_wr
fifo_generator_v12_0_axic_reg_slice
#(
.C_FAMILY (C_FAMILY),
.C_DATA_WIDTH (C_DIN_WIDTH_WACH),
.C_REG_CONFIG (1)
)
wach_pkt_reg_slice_inst
(
// System Signals
.ACLK (S_ACLK),
.ARESET (inverted_reset),
// Slave side
.S_PAYLOAD_DATA (wach_dout_pkt),
.S_VALID (awvalid_pkt),
.S_READY (awready_pkt),
// Master side
.M_PAYLOAD_DATA (wach_dout),
.M_VALID (M_AXI_AWVALID),
.M_READY (M_AXI_AWREADY)
);
assign awvalid_pkt = wach_m_axi_awvalid && awvalid_en;
assign txn_count_up = wdch_s_axi_wready && wdch_wr_en && wdch_din[0];
assign txn_count_down = wach_m_axi_awvalid && awready_pkt && awvalid_en;
always@(posedge S_ACLK or posedge inverted_reset) begin
if(inverted_reset == 1) begin
wr_pkt_count <= 0;
end else begin
if(txn_count_up == 1 && txn_count_down == 0) begin
wr_pkt_count <= wr_pkt_count + 1;
end else if(txn_count_up == 0 && txn_count_down == 1) begin
wr_pkt_count <= wr_pkt_count - 1;
end
end
end //Always end
assign awvalid_en = (wr_pkt_count > 0)?1:0;
end endgenerate
generate if (C_APPLICATION_TYPE_WACH != 1) begin : axi_mm_fifo_wr
assign awvalid_en = 1;
assign wach_dout = wach_dout_pkt;
assign M_AXI_AWVALID = wach_m_axi_awvalid;
end
endgenerate
generate if (IS_WR_DATA_CH == 1) begin : axi_write_data_channel
// Write protection when almost full or prog_full is high
assign wdch_we = (C_PROG_FULL_TYPE_WDCH != 0) ? wdch_s_axi_wready & S_AXI_WVALID : S_AXI_WVALID;
// Read protection when almost empty or prog_empty is high
assign wdch_re = (C_PROG_EMPTY_TYPE_WDCH != 0) ? wdch_m_axi_wvalid & M_AXI_WREADY : M_AXI_WREADY;
assign wdch_wr_en = (C_HAS_SLAVE_CE == 1) ? wdch_we & S_ACLK_EN : wdch_we;
assign wdch_rd_en = (C_HAS_MASTER_CE == 1) ? wdch_re & M_ACLK_EN : wdch_re;
FIFO_GENERATOR_v12_0_CONV_VER
#(
.C_FAMILY (C_FAMILY),
.C_COMMON_CLOCK (C_COMMON_CLOCK),
.C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_WDCH == 1 || C_IMPLEMENTATION_TYPE_WDCH == 11) ? 1 :
(C_IMPLEMENTATION_TYPE_WDCH == 2 || C_IMPLEMENTATION_TYPE_WDCH == 12) ? 2 : 4),
.C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_WDCH == 1 || C_IMPLEMENTATION_TYPE_WDCH == 2) ? 0 :
(C_IMPLEMENTATION_TYPE_WDCH == 11 || C_IMPLEMENTATION_TYPE_WDCH == 12) ? 2 : 6),
.C_PRELOAD_REGS (1), // always FWFT for AXI
.C_PRELOAD_LATENCY (0), // always FWFT for AXI
.C_DIN_WIDTH (C_DIN_WIDTH_WDCH),
.C_WR_DEPTH (C_WR_DEPTH_WDCH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_WDCH),
.C_DOUT_WIDTH (C_DIN_WIDTH_WDCH),
.C_RD_DEPTH (C_WR_DEPTH_WDCH),
.C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_WDCH),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_WDCH),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_WDCH),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_WDCH),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_WDCH),
.C_USE_ECC (C_USE_ECC_WDCH),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_WDCH),
.C_HAS_ALMOST_EMPTY (0),
.C_HAS_ALMOST_FULL (0),
.C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE),
.C_FIFO_TYPE (C_APPLICATION_TYPE_WDCH),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE),
.C_HAS_WR_RST (0),
.C_HAS_RD_RST (0),
.C_HAS_RST (1),
.C_HAS_SRST (0),
.C_DOUT_RST_VAL (0),
.C_HAS_VALID (0),
.C_VALID_LOW (C_VALID_LOW),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_HAS_WR_ACK (0),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_WDCH == 1) ? 1 : 0),
.C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WDCH + 1),
.C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WDCH == 1) ? 1 : 0),
.C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WDCH + 1),
.C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true
.C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WDCH == 1) ? 1 : 0),
.C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WDCH + 1),
.C_FULL_FLAGS_RST_VAL (1),
.C_USE_EMBEDDED_REG (0),
.C_USE_DOUT_RST (0),
.C_MSGON_VAL (C_MSGON_VAL),
.C_ENABLE_RST_SYNC (1),
.C_COUNT_TYPE (C_COUNT_TYPE),
.C_DEFAULT_VALUE (C_DEFAULT_VALUE),
.C_ENABLE_RLOCS (C_ENABLE_RLOCS),
.C_HAS_BACKUP (C_HAS_BACKUP),
.C_HAS_INT_CLK (C_HAS_INT_CLK),
.C_MIF_FILE_NAME (C_MIF_FILE_NAME),
.C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE),
.C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL),
.C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE),
.C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE),
.C_RD_FREQ (C_RD_FREQ),
.C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS),
.C_WR_FREQ (C_WR_FREQ),
.C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY)
)
fifo_generator_v12_0_wdch_dut
(
.CLK (S_ACLK),
.WR_CLK (S_ACLK),
.RD_CLK (M_ACLK),
.RST (inverted_reset),
.SRST (1'b0),
.WR_RST (inverted_reset),
.RD_RST (inverted_reset),
.WR_EN (wdch_wr_en),
.RD_EN (wdch_rd_en),
.PROG_FULL_THRESH (AXI_W_PROG_FULL_THRESH),
.PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WDCH{1'b0}}),
.PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WDCH{1'b0}}),
.PROG_EMPTY_THRESH (AXI_W_PROG_EMPTY_THRESH),
.PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WDCH{1'b0}}),
.PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WDCH{1'b0}}),
.INJECTDBITERR (AXI_W_INJECTDBITERR),
.INJECTSBITERR (AXI_W_INJECTSBITERR),
.DIN (wdch_din),
.DOUT (wdch_dout),
.FULL (wdch_full),
.EMPTY (wdch_empty),
.ALMOST_FULL (),
.PROG_FULL (AXI_W_PROG_FULL),
.ALMOST_EMPTY (),
.PROG_EMPTY (AXI_W_PROG_EMPTY),
.WR_ACK (),
.OVERFLOW (axi_w_overflow_i),
.VALID (),
.UNDERFLOW (axi_w_underflow_i),
.DATA_COUNT (AXI_W_DATA_COUNT),
.RD_DATA_COUNT (AXI_W_RD_DATA_COUNT),
.WR_DATA_COUNT (AXI_W_WR_DATA_COUNT),
.SBITERR (AXI_W_SBITERR),
.DBITERR (AXI_W_DBITERR),
.wr_rst_busy (wr_rst_busy_wdch),
.rd_rst_busy (rd_rst_busy_wdch),
.wr_rst_i_out (),
.rd_rst_i_out (),
.BACKUP (BACKUP),
.BACKUP_MARKER (BACKUP_MARKER),
.INT_CLK (INT_CLK)
);
assign wdch_s_axi_wready = (IS_8SERIES == 0) ? ~wdch_full : (C_IMPLEMENTATION_TYPE_WDCH == 5 || C_IMPLEMENTATION_TYPE_WDCH == 13) ? ~(wdch_full | wr_rst_busy_wdch) : ~wdch_full;
assign wdch_m_axi_wvalid = ~wdch_empty;
assign S_AXI_WREADY = wdch_s_axi_wready;
assign M_AXI_WVALID = wdch_m_axi_wvalid;
assign AXI_W_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_w_underflow_i : 0;
assign AXI_W_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_w_overflow_i : 0;
end endgenerate // axi_write_data_channel
// Register Slice for Write Data Channel
generate if (C_WDCH_TYPE == 1) begin : gwdch_reg_slice
fifo_generator_v12_0_axic_reg_slice
#(
.C_FAMILY (C_FAMILY),
.C_DATA_WIDTH (C_DIN_WIDTH_WDCH),
.C_REG_CONFIG (C_REG_SLICE_MODE_WDCH)
)
wdch_reg_slice_inst
(
// System Signals
.ACLK (S_ACLK),
.ARESET (axi_rs_rst),
// Slave side
.S_PAYLOAD_DATA (wdch_din),
.S_VALID (S_AXI_WVALID),
.S_READY (S_AXI_WREADY),
// Master side
.M_PAYLOAD_DATA (wdch_dout),
.M_VALID (M_AXI_WVALID),
.M_READY (M_AXI_WREADY)
);
end endgenerate // gwdch_reg_slice
generate if (IS_WR_RESP_CH == 1) begin : axi_write_resp_channel
// Write protection when almost full or prog_full is high
assign wrch_we = (C_PROG_FULL_TYPE_WRCH != 0) ? wrch_m_axi_bready & M_AXI_BVALID : M_AXI_BVALID;
// Read protection when almost empty or prog_empty is high
assign wrch_re = (C_PROG_EMPTY_TYPE_WRCH != 0) ? wrch_s_axi_bvalid & S_AXI_BREADY : S_AXI_BREADY;
assign wrch_wr_en = (C_HAS_SLAVE_CE == 1) ? wrch_we & S_ACLK_EN : wrch_we;
assign wrch_rd_en = (C_HAS_MASTER_CE == 1) ? wrch_re & M_ACLK_EN : wrch_re;
FIFO_GENERATOR_v12_0_CONV_VER
#(
.C_FAMILY (C_FAMILY),
.C_COMMON_CLOCK (C_COMMON_CLOCK),
.C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_WRCH == 1 || C_IMPLEMENTATION_TYPE_WRCH == 11) ? 1 :
(C_IMPLEMENTATION_TYPE_WRCH == 2 || C_IMPLEMENTATION_TYPE_WRCH == 12) ? 2 : 4),
.C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_WRCH == 1 || C_IMPLEMENTATION_TYPE_WRCH == 2) ? 0 :
(C_IMPLEMENTATION_TYPE_WRCH == 11 || C_IMPLEMENTATION_TYPE_WRCH == 12) ? 2 : 6),
.C_PRELOAD_REGS (1), // always FWFT for AXI
.C_PRELOAD_LATENCY (0), // always FWFT for AXI
.C_DIN_WIDTH (C_DIN_WIDTH_WRCH),
.C_WR_DEPTH (C_WR_DEPTH_WRCH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_WRCH),
.C_DOUT_WIDTH (C_DIN_WIDTH_WRCH),
.C_RD_DEPTH (C_WR_DEPTH_WRCH),
.C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_WRCH),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_WRCH),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_WRCH),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_WRCH),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_WRCH),
.C_USE_ECC (C_USE_ECC_WRCH),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_WRCH),
.C_HAS_ALMOST_EMPTY (0),
.C_HAS_ALMOST_FULL (0),
.C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE),
.C_FIFO_TYPE (C_APPLICATION_TYPE_WRCH),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE),
.C_HAS_WR_RST (0),
.C_HAS_RD_RST (0),
.C_HAS_RST (1),
.C_HAS_SRST (0),
.C_DOUT_RST_VAL (0),
.C_HAS_VALID (0),
.C_VALID_LOW (C_VALID_LOW),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_HAS_WR_ACK (0),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_WRCH == 1) ? 1 : 0),
.C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WRCH + 1),
.C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WRCH == 1) ? 1 : 0),
.C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WRCH + 1),
.C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true
.C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_WRCH == 1) ? 1 : 0),
.C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_WRCH + 1),
.C_FULL_FLAGS_RST_VAL (1),
.C_USE_EMBEDDED_REG (0),
.C_USE_DOUT_RST (0),
.C_MSGON_VAL (C_MSGON_VAL),
.C_ENABLE_RST_SYNC (1),
.C_COUNT_TYPE (C_COUNT_TYPE),
.C_DEFAULT_VALUE (C_DEFAULT_VALUE),
.C_ENABLE_RLOCS (C_ENABLE_RLOCS),
.C_HAS_BACKUP (C_HAS_BACKUP),
.C_HAS_INT_CLK (C_HAS_INT_CLK),
.C_MIF_FILE_NAME (C_MIF_FILE_NAME),
.C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE),
.C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL),
.C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE),
.C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE),
.C_RD_FREQ (C_RD_FREQ),
.C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS),
.C_WR_FREQ (C_WR_FREQ),
.C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY)
)
fifo_generator_v12_0_wrch_dut
(
.CLK (S_ACLK),
.WR_CLK (M_ACLK),
.RD_CLK (S_ACLK),
.RST (inverted_reset),
.SRST (1'b0),
.WR_RST (inverted_reset),
.RD_RST (inverted_reset),
.WR_EN (wrch_wr_en),
.RD_EN (wrch_rd_en),
.PROG_FULL_THRESH (AXI_B_PROG_FULL_THRESH),
.PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WRCH{1'b0}}),
.PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WRCH{1'b0}}),
.PROG_EMPTY_THRESH (AXI_B_PROG_EMPTY_THRESH),
.PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_WRCH{1'b0}}),
.PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_WRCH{1'b0}}),
.INJECTDBITERR (AXI_B_INJECTDBITERR),
.INJECTSBITERR (AXI_B_INJECTSBITERR),
.DIN (wrch_din),
.DOUT (wrch_dout),
.FULL (wrch_full),
.EMPTY (wrch_empty),
.ALMOST_FULL (),
.ALMOST_EMPTY (),
.PROG_FULL (AXI_B_PROG_FULL),
.PROG_EMPTY (AXI_B_PROG_EMPTY),
.WR_ACK (),
.OVERFLOW (axi_b_overflow_i),
.VALID (),
.UNDERFLOW (axi_b_underflow_i),
.DATA_COUNT (AXI_B_DATA_COUNT),
.RD_DATA_COUNT (AXI_B_RD_DATA_COUNT),
.WR_DATA_COUNT (AXI_B_WR_DATA_COUNT),
.SBITERR (AXI_B_SBITERR),
.DBITERR (AXI_B_DBITERR),
.wr_rst_busy (wr_rst_busy_wrch),
.rd_rst_busy (rd_rst_busy_wrch),
.wr_rst_i_out (),
.rd_rst_i_out (),
.BACKUP (BACKUP),
.BACKUP_MARKER (BACKUP_MARKER),
.INT_CLK (INT_CLK)
);
assign wrch_s_axi_bvalid = ~wrch_empty;
assign wrch_m_axi_bready = (IS_8SERIES == 0) ? ~wrch_full : (C_IMPLEMENTATION_TYPE_WRCH == 5 || C_IMPLEMENTATION_TYPE_WRCH == 13) ? ~(wrch_full | wr_rst_busy_wrch) : ~wrch_full;
assign S_AXI_BVALID = wrch_s_axi_bvalid;
assign M_AXI_BREADY = wrch_m_axi_bready;
assign AXI_B_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_b_underflow_i : 0;
assign AXI_B_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_b_overflow_i : 0;
end endgenerate // axi_write_resp_channel
// Register Slice for Write Response Channel
generate if (C_WRCH_TYPE == 1) begin : gwrch_reg_slice
fifo_generator_v12_0_axic_reg_slice
#(
.C_FAMILY (C_FAMILY),
.C_DATA_WIDTH (C_DIN_WIDTH_WRCH),
.C_REG_CONFIG (C_REG_SLICE_MODE_WRCH)
)
wrch_reg_slice_inst
(
// System Signals
.ACLK (S_ACLK),
.ARESET (axi_rs_rst),
// Slave side
.S_PAYLOAD_DATA (wrch_din),
.S_VALID (M_AXI_BVALID),
.S_READY (M_AXI_BREADY),
// Master side
.M_PAYLOAD_DATA (wrch_dout),
.M_VALID (S_AXI_BVALID),
.M_READY (S_AXI_BREADY)
);
end endgenerate // gwrch_reg_slice
assign axi_wr_underflow_i = C_USE_COMMON_UNDERFLOW == 1 ? (axi_aw_underflow_i || axi_w_underflow_i || axi_b_underflow_i) : 0;
assign axi_wr_overflow_i = C_USE_COMMON_OVERFLOW == 1 ? (axi_aw_overflow_i || axi_w_overflow_i || axi_b_overflow_i) : 0;
generate if (IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) begin : axi_wach_output
assign M_AXI_AWADDR = wach_dout[AWID_OFFSET-1:AWADDR_OFFSET];
assign M_AXI_AWLEN = wach_dout[AWADDR_OFFSET-1:AWLEN_OFFSET];
assign M_AXI_AWSIZE = wach_dout[AWLEN_OFFSET-1:AWSIZE_OFFSET];
assign M_AXI_AWBURST = wach_dout[AWSIZE_OFFSET-1:AWBURST_OFFSET];
assign M_AXI_AWLOCK = wach_dout[AWBURST_OFFSET-1:AWLOCK_OFFSET];
assign M_AXI_AWCACHE = wach_dout[AWLOCK_OFFSET-1:AWCACHE_OFFSET];
assign M_AXI_AWPROT = wach_dout[AWCACHE_OFFSET-1:AWPROT_OFFSET];
assign M_AXI_AWQOS = wach_dout[AWPROT_OFFSET-1:AWQOS_OFFSET];
assign wach_din[AWID_OFFSET-1:AWADDR_OFFSET] = S_AXI_AWADDR;
assign wach_din[AWADDR_OFFSET-1:AWLEN_OFFSET] = S_AXI_AWLEN;
assign wach_din[AWLEN_OFFSET-1:AWSIZE_OFFSET] = S_AXI_AWSIZE;
assign wach_din[AWSIZE_OFFSET-1:AWBURST_OFFSET] = S_AXI_AWBURST;
assign wach_din[AWBURST_OFFSET-1:AWLOCK_OFFSET] = S_AXI_AWLOCK;
assign wach_din[AWLOCK_OFFSET-1:AWCACHE_OFFSET] = S_AXI_AWCACHE;
assign wach_din[AWCACHE_OFFSET-1:AWPROT_OFFSET] = S_AXI_AWPROT;
assign wach_din[AWPROT_OFFSET-1:AWQOS_OFFSET] = S_AXI_AWQOS;
end endgenerate // axi_wach_output
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_AXI_TYPE == 1) begin : axi_awregion
assign M_AXI_AWREGION = wach_dout[AWQOS_OFFSET-1:AWREGION_OFFSET];
end endgenerate // axi_awregion
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_AXI_TYPE != 1) begin : naxi_awregion
assign M_AXI_AWREGION = 0;
end endgenerate // naxi_awregion
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_AWUSER == 1) begin : axi_awuser
assign M_AXI_AWUSER = wach_dout[AWREGION_OFFSET-1:AWUSER_OFFSET];
end endgenerate // axi_awuser
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_AWUSER == 0) begin : naxi_awuser
assign M_AXI_AWUSER = 0;
end endgenerate // naxi_awuser
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : axi_awid
assign M_AXI_AWID = wach_dout[C_DIN_WIDTH_WACH-1:AWID_OFFSET];
end endgenerate //axi_awid
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_ID == 0) begin : naxi_awid
assign M_AXI_AWID = 0;
end endgenerate //naxi_awid
generate if (IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) begin : axi_wdch_output
assign M_AXI_WDATA = wdch_dout[WID_OFFSET-1:WDATA_OFFSET];
assign M_AXI_WSTRB = wdch_dout[WDATA_OFFSET-1:WSTRB_OFFSET];
assign M_AXI_WLAST = wdch_dout[0];
assign wdch_din[WID_OFFSET-1:WDATA_OFFSET] = S_AXI_WDATA;
assign wdch_din[WDATA_OFFSET-1:WSTRB_OFFSET] = S_AXI_WSTRB;
assign wdch_din[0] = S_AXI_WLAST;
end endgenerate // axi_wdch_output
generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && C_HAS_AXI_ID == 1 && C_AXI_TYPE == 3) begin
assign M_AXI_WID = wdch_dout[C_DIN_WIDTH_WDCH-1:WID_OFFSET];
end endgenerate
generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && (C_HAS_AXI_ID == 0 || C_AXI_TYPE != 3)) begin
assign M_AXI_WID = 0;
end endgenerate
generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && C_HAS_AXI_WUSER == 1 ) begin
assign M_AXI_WUSER = wdch_dout[WSTRB_OFFSET-1:WUSER_OFFSET];
end endgenerate
generate if (C_HAS_AXI_WUSER == 0) begin
assign M_AXI_WUSER = 0;
end endgenerate
generate if (IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) begin : axi_wrch_output
assign S_AXI_BRESP = wrch_dout[BID_OFFSET-1:BRESP_OFFSET];
assign wrch_din[BID_OFFSET-1:BRESP_OFFSET] = M_AXI_BRESP;
end endgenerate // axi_wrch_output
generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_BUSER == 1) begin : axi_buser
assign S_AXI_BUSER = wrch_dout[BRESP_OFFSET-1:BUSER_OFFSET];
end endgenerate // axi_buser
generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_BUSER == 0) begin : naxi_buser
assign S_AXI_BUSER = 0;
end endgenerate // naxi_buser
generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : axi_bid
assign S_AXI_BID = wrch_dout[C_DIN_WIDTH_WRCH-1:BID_OFFSET];
end endgenerate // axi_bid
generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_ID == 0) begin : naxi_bid
assign S_AXI_BID = 0 ;
end endgenerate // naxi_bid
generate if (IS_AXI_LITE_WACH == 1 || (IS_AXI_LITE == 1 && C_WACH_TYPE == 1)) begin : axi_wach_output1
assign wach_din = {S_AXI_AWADDR, S_AXI_AWPROT};
assign M_AXI_AWADDR = wach_dout[C_DIN_WIDTH_WACH-1:AWADDR_OFFSET];
assign M_AXI_AWPROT = wach_dout[AWADDR_OFFSET-1:AWPROT_OFFSET];
end endgenerate // axi_wach_output1
generate if (IS_AXI_LITE_WDCH == 1 || (IS_AXI_LITE == 1 && C_WDCH_TYPE == 1)) begin : axi_wdch_output1
assign wdch_din = {S_AXI_WDATA, S_AXI_WSTRB};
assign M_AXI_WDATA = wdch_dout[C_DIN_WIDTH_WDCH-1:WDATA_OFFSET];
assign M_AXI_WSTRB = wdch_dout[WDATA_OFFSET-1:WSTRB_OFFSET];
end endgenerate // axi_wdch_output1
generate if (IS_AXI_LITE_WRCH == 1 || (IS_AXI_LITE == 1 && C_WRCH_TYPE == 1)) begin : axi_wrch_output1
assign wrch_din = M_AXI_BRESP;
assign S_AXI_BRESP = wrch_dout[C_DIN_WIDTH_WRCH-1:BRESP_OFFSET];
end endgenerate // axi_wrch_output1
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_AWUSER == 1) begin : gwach_din1
assign wach_din[AWREGION_OFFSET-1:AWUSER_OFFSET] = S_AXI_AWUSER;
end endgenerate // gwach_din1
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : gwach_din2
assign wach_din[C_DIN_WIDTH_WACH-1:AWID_OFFSET] = S_AXI_AWID;
end endgenerate // gwach_din2
generate if ((IS_AXI_FULL_WACH == 1 || (IS_AXI_FULL == 1 && C_WACH_TYPE == 1)) && C_AXI_TYPE == 1) begin : gwach_din3
assign wach_din[AWQOS_OFFSET-1:AWREGION_OFFSET] = S_AXI_AWREGION;
end endgenerate // gwach_din3
generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && C_HAS_AXI_WUSER == 1) begin : gwdch_din1
assign wdch_din[WSTRB_OFFSET-1:WUSER_OFFSET] = S_AXI_WUSER;
end endgenerate // gwdch_din1
generate if ((IS_AXI_FULL_WDCH == 1 || (IS_AXI_FULL == 1 && C_WDCH_TYPE == 1)) && C_HAS_AXI_ID == 1 && C_AXI_TYPE == 3) begin : gwdch_din2
assign wdch_din[C_DIN_WIDTH_WDCH-1:WID_OFFSET] = S_AXI_WID;
end endgenerate // gwdch_din2
generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_BUSER == 1) begin : gwrch_din1
assign wrch_din[BRESP_OFFSET-1:BUSER_OFFSET] = M_AXI_BUSER;
end endgenerate // gwrch_din1
generate if ((IS_AXI_FULL_WRCH == 1 || (IS_AXI_FULL == 1 && C_WRCH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : gwrch_din2
assign wrch_din[C_DIN_WIDTH_WRCH-1:BID_OFFSET] = M_AXI_BID;
end endgenerate // gwrch_din2
//end of axi_write_channel
//###########################################################################
// AXI FULL Read Channel (axi_read_channel)
//###########################################################################
wire [C_DIN_WIDTH_RACH-1:0] rach_din ;
wire [C_DIN_WIDTH_RACH-1:0] rach_dout ;
wire [C_DIN_WIDTH_RACH-1:0] rach_dout_pkt ;
wire rach_full ;
wire rach_almost_full ;
wire rach_prog_full ;
wire rach_empty ;
wire rach_almost_empty ;
wire rach_prog_empty ;
wire [C_DIN_WIDTH_RDCH-1:0] rdch_din ;
wire [C_DIN_WIDTH_RDCH-1:0] rdch_dout ;
wire rdch_full ;
wire rdch_almost_full ;
wire rdch_prog_full ;
wire rdch_empty ;
wire rdch_almost_empty ;
wire rdch_prog_empty ;
wire axi_ar_underflow_i ;
wire axi_r_underflow_i ;
wire axi_ar_overflow_i ;
wire axi_r_overflow_i ;
wire axi_rd_underflow_i ;
wire axi_rd_overflow_i ;
wire rach_s_axi_arready ;
wire rach_m_axi_arvalid ;
wire rach_wr_en ;
wire rach_rd_en ;
wire rdch_m_axi_rready ;
wire rdch_s_axi_rvalid ;
wire rdch_wr_en ;
wire rdch_rd_en ;
wire arvalid_pkt ;
wire arready_pkt ;
wire arvalid_en ;
wire rdch_rd_ok ;
wire accept_next_pkt ;
integer rdch_free_space ;
integer rdch_commited_space ;
wire rach_we ;
wire rach_re ;
wire rdch_we ;
wire rdch_re ;
localparam ARID_OFFSET = (C_AXI_TYPE != 2 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_RACH - C_AXI_ID_WIDTH : C_DIN_WIDTH_RACH;
localparam ARADDR_OFFSET = ARID_OFFSET - C_AXI_ADDR_WIDTH;
localparam ARLEN_OFFSET = C_AXI_TYPE != 2 ? ARADDR_OFFSET - C_AXI_LEN_WIDTH : ARADDR_OFFSET;
localparam ARSIZE_OFFSET = C_AXI_TYPE != 2 ? ARLEN_OFFSET - C_AXI_SIZE_WIDTH : ARLEN_OFFSET;
localparam ARBURST_OFFSET = C_AXI_TYPE != 2 ? ARSIZE_OFFSET - C_AXI_BURST_WIDTH : ARSIZE_OFFSET;
localparam ARLOCK_OFFSET = C_AXI_TYPE != 2 ? ARBURST_OFFSET - C_AXI_LOCK_WIDTH : ARBURST_OFFSET;
localparam ARCACHE_OFFSET = C_AXI_TYPE != 2 ? ARLOCK_OFFSET - C_AXI_CACHE_WIDTH : ARLOCK_OFFSET;
localparam ARPROT_OFFSET = ARCACHE_OFFSET - C_AXI_PROT_WIDTH;
localparam ARQOS_OFFSET = ARPROT_OFFSET - C_AXI_QOS_WIDTH;
localparam ARREGION_OFFSET = C_AXI_TYPE == 1 ? ARQOS_OFFSET - C_AXI_REGION_WIDTH : ARQOS_OFFSET;
localparam ARUSER_OFFSET = C_HAS_AXI_ARUSER == 1 ? ARREGION_OFFSET-C_AXI_ARUSER_WIDTH : ARREGION_OFFSET;
localparam RID_OFFSET = (C_AXI_TYPE != 2 && C_HAS_AXI_ID == 1) ? C_DIN_WIDTH_RDCH - C_AXI_ID_WIDTH : C_DIN_WIDTH_RDCH;
localparam RDATA_OFFSET = RID_OFFSET - C_AXI_DATA_WIDTH;
localparam RRESP_OFFSET = RDATA_OFFSET - C_AXI_RRESP_WIDTH;
localparam RUSER_OFFSET = C_HAS_AXI_RUSER == 1 ? RRESP_OFFSET-C_AXI_RUSER_WIDTH : RRESP_OFFSET;
generate if (IS_RD_ADDR_CH == 1) begin : axi_read_addr_channel
// Write protection when almost full or prog_full is high
assign rach_we = (C_PROG_FULL_TYPE_RACH != 0) ? rach_s_axi_arready & S_AXI_ARVALID : S_AXI_ARVALID;
// Read protection when almost empty or prog_empty is high
// assign rach_rd_en = (C_PROG_EMPTY_TYPE_RACH != 5) ? rach_m_axi_arvalid & M_AXI_ARREADY : M_AXI_ARREADY && arvalid_en;
assign rach_re = (C_PROG_EMPTY_TYPE_RACH != 0 && C_APPLICATION_TYPE_RACH == 1) ?
rach_m_axi_arvalid & arready_pkt & arvalid_en :
(C_PROG_EMPTY_TYPE_RACH != 0 && C_APPLICATION_TYPE_RACH != 1) ?
M_AXI_ARREADY && rach_m_axi_arvalid :
(C_PROG_EMPTY_TYPE_RACH == 0 && C_APPLICATION_TYPE_RACH == 1) ?
arready_pkt & arvalid_en :
(C_PROG_EMPTY_TYPE_RACH == 0 && C_APPLICATION_TYPE_RACH != 1) ?
M_AXI_ARREADY : 1'b0;
assign rach_wr_en = (C_HAS_SLAVE_CE == 1) ? rach_we & S_ACLK_EN : rach_we;
assign rach_rd_en = (C_HAS_MASTER_CE == 1) ? rach_re & M_ACLK_EN : rach_re;
FIFO_GENERATOR_v12_0_CONV_VER
#(
.C_FAMILY (C_FAMILY),
.C_COMMON_CLOCK (C_COMMON_CLOCK),
.C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_RACH == 1 || C_IMPLEMENTATION_TYPE_RACH == 11) ? 1 :
(C_IMPLEMENTATION_TYPE_RACH == 2 || C_IMPLEMENTATION_TYPE_RACH == 12) ? 2 : 4),
.C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_RACH == 1 || C_IMPLEMENTATION_TYPE_RACH == 2) ? 0 :
(C_IMPLEMENTATION_TYPE_RACH == 11 || C_IMPLEMENTATION_TYPE_RACH == 12) ? 2 : 6),
.C_PRELOAD_REGS (1), // always FWFT for AXI
.C_PRELOAD_LATENCY (0), // always FWFT for AXI
.C_DIN_WIDTH (C_DIN_WIDTH_RACH),
.C_WR_DEPTH (C_WR_DEPTH_RACH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_RACH),
.C_DOUT_WIDTH (C_DIN_WIDTH_RACH),
.C_RD_DEPTH (C_WR_DEPTH_RACH),
.C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_RACH),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_RACH),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_RACH),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_RACH),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_RACH),
.C_USE_ECC (C_USE_ECC_RACH),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_RACH),
.C_HAS_ALMOST_EMPTY (0),
.C_HAS_ALMOST_FULL (0),
.C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE),
.C_FIFO_TYPE ((C_APPLICATION_TYPE_RACH == 1)?0:C_APPLICATION_TYPE_RACH),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE),
.C_HAS_WR_RST (0),
.C_HAS_RD_RST (0),
.C_HAS_RST (1),
.C_HAS_SRST (0),
.C_DOUT_RST_VAL (0),
.C_HAS_VALID (0),
.C_VALID_LOW (C_VALID_LOW),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_HAS_WR_ACK (0),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_RACH == 1) ? 1 : 0),
.C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RACH + 1),
.C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_RACH == 1) ? 1 : 0),
.C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RACH + 1),
.C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true
.C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_RACH == 1) ? 1 : 0),
.C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RACH + 1),
.C_FULL_FLAGS_RST_VAL (1),
.C_USE_EMBEDDED_REG (0),
.C_USE_DOUT_RST (0),
.C_MSGON_VAL (C_MSGON_VAL),
.C_ENABLE_RST_SYNC (1),
.C_COUNT_TYPE (C_COUNT_TYPE),
.C_DEFAULT_VALUE (C_DEFAULT_VALUE),
.C_ENABLE_RLOCS (C_ENABLE_RLOCS),
.C_HAS_BACKUP (C_HAS_BACKUP),
.C_HAS_INT_CLK (C_HAS_INT_CLK),
.C_MIF_FILE_NAME (C_MIF_FILE_NAME),
.C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE),
.C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL),
.C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE),
.C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE),
.C_RD_FREQ (C_RD_FREQ),
.C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS),
.C_WR_FREQ (C_WR_FREQ),
.C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY)
)
fifo_generator_v12_0_rach_dut
(
.CLK (S_ACLK),
.WR_CLK (S_ACLK),
.RD_CLK (M_ACLK),
.RST (inverted_reset),
.SRST (1'b0),
.WR_RST (inverted_reset),
.RD_RST (inverted_reset),
.WR_EN (rach_wr_en),
.RD_EN (rach_rd_en),
.PROG_FULL_THRESH (AXI_AR_PROG_FULL_THRESH),
.PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_RACH{1'b0}}),
.PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_RACH{1'b0}}),
.PROG_EMPTY_THRESH (AXI_AR_PROG_EMPTY_THRESH),
.PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_RACH{1'b0}}),
.PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_RACH{1'b0}}),
.INJECTDBITERR (AXI_AR_INJECTDBITERR),
.INJECTSBITERR (AXI_AR_INJECTSBITERR),
.DIN (rach_din),
.DOUT (rach_dout_pkt),
.FULL (rach_full),
.EMPTY (rach_empty),
.ALMOST_FULL (),
.ALMOST_EMPTY (),
.PROG_FULL (AXI_AR_PROG_FULL),
.PROG_EMPTY (AXI_AR_PROG_EMPTY),
.WR_ACK (),
.OVERFLOW (axi_ar_overflow_i),
.VALID (),
.UNDERFLOW (axi_ar_underflow_i),
.DATA_COUNT (AXI_AR_DATA_COUNT),
.RD_DATA_COUNT (AXI_AR_RD_DATA_COUNT),
.WR_DATA_COUNT (AXI_AR_WR_DATA_COUNT),
.SBITERR (AXI_AR_SBITERR),
.DBITERR (AXI_AR_DBITERR),
.wr_rst_busy (wr_rst_busy_rach),
.rd_rst_busy (rd_rst_busy_rach),
.wr_rst_i_out (),
.rd_rst_i_out (),
.BACKUP (BACKUP),
.BACKUP_MARKER (BACKUP_MARKER),
.INT_CLK (INT_CLK)
);
assign rach_s_axi_arready = (IS_8SERIES == 0) ? ~rach_full : (C_IMPLEMENTATION_TYPE_RACH == 5 || C_IMPLEMENTATION_TYPE_RACH == 13) ? ~(rach_full | wr_rst_busy_rach) : ~rach_full;
assign rach_m_axi_arvalid = ~rach_empty;
assign S_AXI_ARREADY = rach_s_axi_arready;
assign AXI_AR_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_ar_underflow_i : 0;
assign AXI_AR_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_ar_overflow_i : 0;
end endgenerate // axi_read_addr_channel
// Register Slice for Read Address Channel
generate if (C_RACH_TYPE == 1) begin : grach_reg_slice
fifo_generator_v12_0_axic_reg_slice
#(
.C_FAMILY (C_FAMILY),
.C_DATA_WIDTH (C_DIN_WIDTH_RACH),
.C_REG_CONFIG (C_REG_SLICE_MODE_RACH)
)
rach_reg_slice_inst
(
// System Signals
.ACLK (S_ACLK),
.ARESET (axi_rs_rst),
// Slave side
.S_PAYLOAD_DATA (rach_din),
.S_VALID (S_AXI_ARVALID),
.S_READY (S_AXI_ARREADY),
// Master side
.M_PAYLOAD_DATA (rach_dout),
.M_VALID (M_AXI_ARVALID),
.M_READY (M_AXI_ARREADY)
);
end endgenerate // grach_reg_slice
// Register Slice for Read Address Channel for MM Packet FIFO
generate if (C_RACH_TYPE == 0 && C_APPLICATION_TYPE_RACH == 1) begin : grach_reg_slice_mm_pkt_fifo
fifo_generator_v12_0_axic_reg_slice
#(
.C_FAMILY (C_FAMILY),
.C_DATA_WIDTH (C_DIN_WIDTH_RACH),
.C_REG_CONFIG (1)
)
reg_slice_mm_pkt_fifo_inst
(
// System Signals
.ACLK (S_ACLK),
.ARESET (inverted_reset),
// Slave side
.S_PAYLOAD_DATA (rach_dout_pkt),
.S_VALID (arvalid_pkt),
.S_READY (arready_pkt),
// Master side
.M_PAYLOAD_DATA (rach_dout),
.M_VALID (M_AXI_ARVALID),
.M_READY (M_AXI_ARREADY)
);
end endgenerate // grach_reg_slice_mm_pkt_fifo
generate if (C_RACH_TYPE == 0 && C_APPLICATION_TYPE_RACH != 1) begin : grach_m_axi_arvalid
assign M_AXI_ARVALID = rach_m_axi_arvalid;
assign rach_dout = rach_dout_pkt;
end endgenerate // grach_m_axi_arvalid
generate if (C_APPLICATION_TYPE_RACH == 1 && C_HAS_AXI_RD_CHANNEL == 1) begin : axi_mm_pkt_fifo_rd
assign rdch_rd_ok = rdch_s_axi_rvalid && rdch_rd_en;
assign arvalid_pkt = rach_m_axi_arvalid && arvalid_en;
assign accept_next_pkt = rach_m_axi_arvalid && arready_pkt && arvalid_en;
always@(posedge S_ACLK or posedge inverted_reset) begin
if(inverted_reset) begin
rdch_commited_space <= 0;
end else begin
if(rdch_rd_ok && !accept_next_pkt) begin
rdch_commited_space <= rdch_commited_space-1;
end else if(!rdch_rd_ok && accept_next_pkt) begin
rdch_commited_space <= rdch_commited_space+(rach_dout_pkt[ARADDR_OFFSET-1:ARLEN_OFFSET]+1);
end else if(rdch_rd_ok && accept_next_pkt) begin
rdch_commited_space <= rdch_commited_space+(rach_dout_pkt[ARADDR_OFFSET-1:ARLEN_OFFSET]);
end
end
end //Always end
always@(*) begin
rdch_free_space <= (C_WR_DEPTH_RDCH-(rdch_commited_space+rach_dout_pkt[ARADDR_OFFSET-1:ARLEN_OFFSET]+1));
end
assign arvalid_en = (rdch_free_space >= 0)?1:0;
end
endgenerate
generate if (C_APPLICATION_TYPE_RACH != 1) begin : axi_mm_fifo_rd
assign arvalid_en = 1;
end
endgenerate
generate if (IS_RD_DATA_CH == 1) begin : axi_read_data_channel
// Write protection when almost full or prog_full is high
assign rdch_we = (C_PROG_FULL_TYPE_RDCH != 0) ? rdch_m_axi_rready & M_AXI_RVALID : M_AXI_RVALID;
// Read protection when almost empty or prog_empty is high
assign rdch_re = (C_PROG_EMPTY_TYPE_RDCH != 0) ? rdch_s_axi_rvalid & S_AXI_RREADY : S_AXI_RREADY;
assign rdch_wr_en = (C_HAS_SLAVE_CE == 1) ? rdch_we & S_ACLK_EN : rdch_we;
assign rdch_rd_en = (C_HAS_MASTER_CE == 1) ? rdch_re & M_ACLK_EN : rdch_re;
FIFO_GENERATOR_v12_0_CONV_VER
#(
.C_FAMILY (C_FAMILY),
.C_COMMON_CLOCK (C_COMMON_CLOCK),
.C_MEMORY_TYPE ((C_IMPLEMENTATION_TYPE_RDCH == 1 || C_IMPLEMENTATION_TYPE_RDCH == 11) ? 1 :
(C_IMPLEMENTATION_TYPE_RDCH == 2 || C_IMPLEMENTATION_TYPE_RDCH == 12) ? 2 : 4),
.C_IMPLEMENTATION_TYPE ((C_IMPLEMENTATION_TYPE_RDCH == 1 || C_IMPLEMENTATION_TYPE_RDCH == 2) ? 0 :
(C_IMPLEMENTATION_TYPE_RDCH == 11 || C_IMPLEMENTATION_TYPE_RDCH == 12) ? 2 : 6),
.C_PRELOAD_REGS (1), // always FWFT for AXI
.C_PRELOAD_LATENCY (0), // always FWFT for AXI
.C_DIN_WIDTH (C_DIN_WIDTH_RDCH),
.C_WR_DEPTH (C_WR_DEPTH_RDCH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH_RDCH),
.C_DOUT_WIDTH (C_DIN_WIDTH_RDCH),
.C_RD_DEPTH (C_WR_DEPTH_RDCH),
.C_RD_PNTR_WIDTH (C_WR_PNTR_WIDTH_RDCH),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE_RDCH),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL_RDCH),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE_RDCH),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL_RDCH),
.C_USE_ECC (C_USE_ECC_RDCH),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE_RDCH),
.C_HAS_ALMOST_EMPTY (0),
.C_HAS_ALMOST_FULL (0),
.C_AXI_TYPE (C_INTERFACE_TYPE == 1 ? 0 : C_AXI_TYPE),
.C_FIFO_TYPE (C_APPLICATION_TYPE_RDCH),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE),
.C_HAS_WR_RST (0),
.C_HAS_RD_RST (0),
.C_HAS_RST (1),
.C_HAS_SRST (0),
.C_DOUT_RST_VAL (0),
.C_HAS_VALID (0),
.C_VALID_LOW (C_VALID_LOW),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_HAS_WR_ACK (0),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_HAS_DATA_COUNT ((C_COMMON_CLOCK == 1 && C_HAS_DATA_COUNTS_RDCH == 1) ? 1 : 0),
.C_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RDCH + 1),
.C_HAS_RD_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_RDCH == 1) ? 1 : 0),
.C_RD_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RDCH + 1),
.C_USE_FWFT_DATA_COUNT (1), // use extra logic is always true
.C_HAS_WR_DATA_COUNT ((C_COMMON_CLOCK == 0 && C_HAS_DATA_COUNTS_RDCH == 1) ? 1 : 0),
.C_WR_DATA_COUNT_WIDTH (C_WR_PNTR_WIDTH_RDCH + 1),
.C_FULL_FLAGS_RST_VAL (1),
.C_USE_EMBEDDED_REG (0),
.C_USE_DOUT_RST (0),
.C_MSGON_VAL (C_MSGON_VAL),
.C_ENABLE_RST_SYNC (1),
.C_COUNT_TYPE (C_COUNT_TYPE),
.C_DEFAULT_VALUE (C_DEFAULT_VALUE),
.C_ENABLE_RLOCS (C_ENABLE_RLOCS),
.C_HAS_BACKUP (C_HAS_BACKUP),
.C_HAS_INT_CLK (C_HAS_INT_CLK),
.C_MIF_FILE_NAME (C_MIF_FILE_NAME),
.C_HAS_MEMINIT_FILE (C_HAS_MEMINIT_FILE),
.C_INIT_WR_PNTR_VAL (C_INIT_WR_PNTR_VAL),
.C_OPTIMIZATION_MODE (C_OPTIMIZATION_MODE),
.C_PRIM_FIFO_TYPE (C_PRIM_FIFO_TYPE),
.C_RD_FREQ (C_RD_FREQ),
.C_USE_FIFO16_FLAGS (C_USE_FIFO16_FLAGS),
.C_WR_FREQ (C_WR_FREQ),
.C_WR_RESPONSE_LATENCY (C_WR_RESPONSE_LATENCY)
)
fifo_generator_v12_0_rdch_dut
(
.CLK (S_ACLK),
.WR_CLK (M_ACLK),
.RD_CLK (S_ACLK),
.RST (inverted_reset),
.SRST (1'b0),
.WR_RST (inverted_reset),
.RD_RST (inverted_reset),
.WR_EN (rdch_wr_en),
.RD_EN (rdch_rd_en),
.PROG_FULL_THRESH (AXI_R_PROG_FULL_THRESH),
.PROG_FULL_THRESH_ASSERT ({C_WR_PNTR_WIDTH_RDCH{1'b0}}),
.PROG_FULL_THRESH_NEGATE ({C_WR_PNTR_WIDTH_RDCH{1'b0}}),
.PROG_EMPTY_THRESH (AXI_R_PROG_EMPTY_THRESH),
.PROG_EMPTY_THRESH_ASSERT ({C_WR_PNTR_WIDTH_RDCH{1'b0}}),
.PROG_EMPTY_THRESH_NEGATE ({C_WR_PNTR_WIDTH_RDCH{1'b0}}),
.INJECTDBITERR (AXI_R_INJECTDBITERR),
.INJECTSBITERR (AXI_R_INJECTSBITERR),
.DIN (rdch_din),
.DOUT (rdch_dout),
.FULL (rdch_full),
.EMPTY (rdch_empty),
.ALMOST_FULL (),
.ALMOST_EMPTY (),
.PROG_FULL (AXI_R_PROG_FULL),
.PROG_EMPTY (AXI_R_PROG_EMPTY),
.WR_ACK (),
.OVERFLOW (axi_r_overflow_i),
.VALID (),
.UNDERFLOW (axi_r_underflow_i),
.DATA_COUNT (AXI_R_DATA_COUNT),
.RD_DATA_COUNT (AXI_R_RD_DATA_COUNT),
.WR_DATA_COUNT (AXI_R_WR_DATA_COUNT),
.SBITERR (AXI_R_SBITERR),
.DBITERR (AXI_R_DBITERR),
.wr_rst_busy (wr_rst_busy_rdch),
.rd_rst_busy (rd_rst_busy_rdch),
.wr_rst_i_out (),
.rd_rst_i_out (),
.BACKUP (BACKUP),
.BACKUP_MARKER (BACKUP_MARKER),
.INT_CLK (INT_CLK)
);
assign rdch_s_axi_rvalid = ~rdch_empty;
assign rdch_m_axi_rready = (IS_8SERIES == 0) ? ~rdch_full : (C_IMPLEMENTATION_TYPE_RDCH == 5 || C_IMPLEMENTATION_TYPE_RDCH == 13) ? ~(rdch_full | wr_rst_busy_rdch) : ~rdch_full;
assign S_AXI_RVALID = rdch_s_axi_rvalid;
assign M_AXI_RREADY = rdch_m_axi_rready;
assign AXI_R_UNDERFLOW = C_USE_COMMON_UNDERFLOW == 0 ? axi_r_underflow_i : 0;
assign AXI_R_OVERFLOW = C_USE_COMMON_OVERFLOW == 0 ? axi_r_overflow_i : 0;
end endgenerate //axi_read_data_channel
// Register Slice for read Data Channel
generate if (C_RDCH_TYPE == 1) begin : grdch_reg_slice
fifo_generator_v12_0_axic_reg_slice
#(
.C_FAMILY (C_FAMILY),
.C_DATA_WIDTH (C_DIN_WIDTH_RDCH),
.C_REG_CONFIG (C_REG_SLICE_MODE_RDCH)
)
rdch_reg_slice_inst
(
// System Signals
.ACLK (S_ACLK),
.ARESET (axi_rs_rst),
// Slave side
.S_PAYLOAD_DATA (rdch_din),
.S_VALID (M_AXI_RVALID),
.S_READY (M_AXI_RREADY),
// Master side
.M_PAYLOAD_DATA (rdch_dout),
.M_VALID (S_AXI_RVALID),
.M_READY (S_AXI_RREADY)
);
end endgenerate // grdch_reg_slice
assign axi_rd_underflow_i = C_USE_COMMON_UNDERFLOW == 1 ? (axi_ar_underflow_i || axi_r_underflow_i) : 0;
assign axi_rd_overflow_i = C_USE_COMMON_OVERFLOW == 1 ? (axi_ar_overflow_i || axi_r_overflow_i) : 0;
generate if (IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) begin : axi_full_rach_output
assign M_AXI_ARADDR = rach_dout[ARID_OFFSET-1:ARADDR_OFFSET];
assign M_AXI_ARLEN = rach_dout[ARADDR_OFFSET-1:ARLEN_OFFSET];
assign M_AXI_ARSIZE = rach_dout[ARLEN_OFFSET-1:ARSIZE_OFFSET];
assign M_AXI_ARBURST = rach_dout[ARSIZE_OFFSET-1:ARBURST_OFFSET];
assign M_AXI_ARLOCK = rach_dout[ARBURST_OFFSET-1:ARLOCK_OFFSET];
assign M_AXI_ARCACHE = rach_dout[ARLOCK_OFFSET-1:ARCACHE_OFFSET];
assign M_AXI_ARPROT = rach_dout[ARCACHE_OFFSET-1:ARPROT_OFFSET];
assign M_AXI_ARQOS = rach_dout[ARPROT_OFFSET-1:ARQOS_OFFSET];
assign rach_din[ARID_OFFSET-1:ARADDR_OFFSET] = S_AXI_ARADDR;
assign rach_din[ARADDR_OFFSET-1:ARLEN_OFFSET] = S_AXI_ARLEN;
assign rach_din[ARLEN_OFFSET-1:ARSIZE_OFFSET] = S_AXI_ARSIZE;
assign rach_din[ARSIZE_OFFSET-1:ARBURST_OFFSET] = S_AXI_ARBURST;
assign rach_din[ARBURST_OFFSET-1:ARLOCK_OFFSET] = S_AXI_ARLOCK;
assign rach_din[ARLOCK_OFFSET-1:ARCACHE_OFFSET] = S_AXI_ARCACHE;
assign rach_din[ARCACHE_OFFSET-1:ARPROT_OFFSET] = S_AXI_ARPROT;
assign rach_din[ARPROT_OFFSET-1:ARQOS_OFFSET] = S_AXI_ARQOS;
end endgenerate // axi_full_rach_output
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_AXI_TYPE == 1) begin : axi_arregion
assign M_AXI_ARREGION = rach_dout[ARQOS_OFFSET-1:ARREGION_OFFSET];
end endgenerate // axi_arregion
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_AXI_TYPE != 1) begin : naxi_arregion
assign M_AXI_ARREGION = 0;
end endgenerate // naxi_arregion
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ARUSER == 1) begin : axi_aruser
assign M_AXI_ARUSER = rach_dout[ARREGION_OFFSET-1:ARUSER_OFFSET];
end endgenerate // axi_aruser
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ARUSER == 0) begin : naxi_aruser
assign M_AXI_ARUSER = 0;
end endgenerate // naxi_aruser
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : axi_arid
assign M_AXI_ARID = rach_dout[C_DIN_WIDTH_RACH-1:ARID_OFFSET];
end endgenerate // axi_arid
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ID == 0) begin : naxi_arid
assign M_AXI_ARID = 0;
end endgenerate // naxi_arid
generate if (IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) begin : axi_full_rdch_output
assign S_AXI_RDATA = rdch_dout[RID_OFFSET-1:RDATA_OFFSET];
assign S_AXI_RRESP = rdch_dout[RDATA_OFFSET-1:RRESP_OFFSET];
assign S_AXI_RLAST = rdch_dout[0];
assign rdch_din[RID_OFFSET-1:RDATA_OFFSET] = M_AXI_RDATA;
assign rdch_din[RDATA_OFFSET-1:RRESP_OFFSET] = M_AXI_RRESP;
assign rdch_din[0] = M_AXI_RLAST;
end endgenerate // axi_full_rdch_output
generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_RUSER == 1) begin : axi_full_ruser_output
assign S_AXI_RUSER = rdch_dout[RRESP_OFFSET-1:RUSER_OFFSET];
end endgenerate // axi_full_ruser_output
generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_RUSER == 0) begin : axi_full_nruser_output
assign S_AXI_RUSER = 0;
end endgenerate // axi_full_nruser_output
generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : axi_rid
assign S_AXI_RID = rdch_dout[C_DIN_WIDTH_RDCH-1:RID_OFFSET];
end endgenerate // axi_rid
generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_ID == 0) begin : naxi_rid
assign S_AXI_RID = 0;
end endgenerate // naxi_rid
generate if (IS_AXI_LITE_RACH == 1 || (IS_AXI_LITE == 1 && C_RACH_TYPE == 1)) begin : axi_lite_rach_output1
assign rach_din = {S_AXI_ARADDR, S_AXI_ARPROT};
assign M_AXI_ARADDR = rach_dout[C_DIN_WIDTH_RACH-1:ARADDR_OFFSET];
assign M_AXI_ARPROT = rach_dout[ARADDR_OFFSET-1:ARPROT_OFFSET];
end endgenerate // axi_lite_rach_output
generate if (IS_AXI_LITE_RDCH == 1 || (IS_AXI_LITE == 1 && C_RDCH_TYPE == 1)) begin : axi_lite_rdch_output1
assign rdch_din = {M_AXI_RDATA, M_AXI_RRESP};
assign S_AXI_RDATA = rdch_dout[C_DIN_WIDTH_RDCH-1:RDATA_OFFSET];
assign S_AXI_RRESP = rdch_dout[RDATA_OFFSET-1:RRESP_OFFSET];
end endgenerate // axi_lite_rdch_output
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ARUSER == 1) begin : grach_din1
assign rach_din[ARREGION_OFFSET-1:ARUSER_OFFSET] = S_AXI_ARUSER;
end endgenerate // grach_din1
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : grach_din2
assign rach_din[C_DIN_WIDTH_RACH-1:ARID_OFFSET] = S_AXI_ARID;
end endgenerate // grach_din2
generate if ((IS_AXI_FULL_RACH == 1 || (IS_AXI_FULL == 1 && C_RACH_TYPE == 1)) && C_AXI_TYPE == 1) begin
assign rach_din[ARQOS_OFFSET-1:ARREGION_OFFSET] = S_AXI_ARREGION;
end endgenerate
generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_RUSER == 1) begin : grdch_din1
assign rdch_din[RRESP_OFFSET-1:RUSER_OFFSET] = M_AXI_RUSER;
end endgenerate // grdch_din1
generate if ((IS_AXI_FULL_RDCH == 1 || (IS_AXI_FULL == 1 && C_RDCH_TYPE == 1)) && C_HAS_AXI_ID == 1) begin : grdch_din2
assign rdch_din[C_DIN_WIDTH_RDCH-1:RID_OFFSET] = M_AXI_RID;
end endgenerate // grdch_din2
//end of axi_read_channel
generate if (C_INTERFACE_TYPE == 1 && C_USE_COMMON_UNDERFLOW == 1) begin : gaxi_comm_uf
assign UNDERFLOW = (C_HAS_AXI_WR_CHANNEL == 1 && C_HAS_AXI_RD_CHANNEL == 1) ? (axi_wr_underflow_i || axi_rd_underflow_i) :
(C_HAS_AXI_WR_CHANNEL == 1 && C_HAS_AXI_RD_CHANNEL == 0) ? axi_wr_underflow_i :
(C_HAS_AXI_WR_CHANNEL == 0 && C_HAS_AXI_RD_CHANNEL == 1) ? axi_rd_underflow_i : 0;
end endgenerate // gaxi_comm_uf
generate if (C_INTERFACE_TYPE == 1 && C_USE_COMMON_OVERFLOW == 1) begin : gaxi_comm_of
assign OVERFLOW = (C_HAS_AXI_WR_CHANNEL == 1 && C_HAS_AXI_RD_CHANNEL == 1) ? (axi_wr_overflow_i || axi_rd_overflow_i) :
(C_HAS_AXI_WR_CHANNEL == 1 && C_HAS_AXI_RD_CHANNEL == 0) ? axi_wr_overflow_i :
(C_HAS_AXI_WR_CHANNEL == 0 && C_HAS_AXI_RD_CHANNEL == 1) ? axi_rd_overflow_i : 0;
end endgenerate // gaxi_comm_of
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Pass Through Logic or Wiring Logic
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Pass Through Logic for Read Channel
//-------------------------------------------------------------------------
// Wiring logic for Write Address Channel
generate if (C_WACH_TYPE == 2) begin : gwach_pass_through
assign M_AXI_AWID = S_AXI_AWID;
assign M_AXI_AWADDR = S_AXI_AWADDR;
assign M_AXI_AWLEN = S_AXI_AWLEN;
assign M_AXI_AWSIZE = S_AXI_AWSIZE;
assign M_AXI_AWBURST = S_AXI_AWBURST;
assign M_AXI_AWLOCK = S_AXI_AWLOCK;
assign M_AXI_AWCACHE = S_AXI_AWCACHE;
assign M_AXI_AWPROT = S_AXI_AWPROT;
assign M_AXI_AWQOS = S_AXI_AWQOS;
assign M_AXI_AWREGION = S_AXI_AWREGION;
assign M_AXI_AWUSER = S_AXI_AWUSER;
assign S_AXI_AWREADY = M_AXI_AWREADY;
assign M_AXI_AWVALID = S_AXI_AWVALID;
end endgenerate // gwach_pass_through;
// Wiring logic for Write Data Channel
generate if (C_WDCH_TYPE == 2) begin : gwdch_pass_through
assign M_AXI_WID = S_AXI_WID;
assign M_AXI_WDATA = S_AXI_WDATA;
assign M_AXI_WSTRB = S_AXI_WSTRB;
assign M_AXI_WLAST = S_AXI_WLAST;
assign M_AXI_WUSER = S_AXI_WUSER;
assign S_AXI_WREADY = M_AXI_WREADY;
assign M_AXI_WVALID = S_AXI_WVALID;
end endgenerate // gwdch_pass_through;
// Wiring logic for Write Response Channel
generate if (C_WRCH_TYPE == 2) begin : gwrch_pass_through
assign S_AXI_BID = M_AXI_BID;
assign S_AXI_BRESP = M_AXI_BRESP;
assign S_AXI_BUSER = M_AXI_BUSER;
assign M_AXI_BREADY = S_AXI_BREADY;
assign S_AXI_BVALID = M_AXI_BVALID;
end endgenerate // gwrch_pass_through;
//-------------------------------------------------------------------------
// Pass Through Logic for Read Channel
//-------------------------------------------------------------------------
// Wiring logic for Read Address Channel
generate if (C_RACH_TYPE == 2) begin : grach_pass_through
assign M_AXI_ARID = S_AXI_ARID;
assign M_AXI_ARADDR = S_AXI_ARADDR;
assign M_AXI_ARLEN = S_AXI_ARLEN;
assign M_AXI_ARSIZE = S_AXI_ARSIZE;
assign M_AXI_ARBURST = S_AXI_ARBURST;
assign M_AXI_ARLOCK = S_AXI_ARLOCK;
assign M_AXI_ARCACHE = S_AXI_ARCACHE;
assign M_AXI_ARPROT = S_AXI_ARPROT;
assign M_AXI_ARQOS = S_AXI_ARQOS;
assign M_AXI_ARREGION = S_AXI_ARREGION;
assign M_AXI_ARUSER = S_AXI_ARUSER;
assign S_AXI_ARREADY = M_AXI_ARREADY;
assign M_AXI_ARVALID = S_AXI_ARVALID;
end endgenerate // grach_pass_through;
// Wiring logic for Read Data Channel
generate if (C_RDCH_TYPE == 2) begin : grdch_pass_through
assign S_AXI_RID = M_AXI_RID;
assign S_AXI_RLAST = M_AXI_RLAST;
assign S_AXI_RUSER = M_AXI_RUSER;
assign S_AXI_RDATA = M_AXI_RDATA;
assign S_AXI_RRESP = M_AXI_RRESP;
assign S_AXI_RVALID = M_AXI_RVALID;
assign M_AXI_RREADY = S_AXI_RREADY;
end endgenerate // grdch_pass_through;
// Wiring logic for AXI Streaming
generate if (C_AXIS_TYPE == 2) begin : gaxis_pass_through
assign M_AXIS_TDATA = S_AXIS_TDATA;
assign M_AXIS_TSTRB = S_AXIS_TSTRB;
assign M_AXIS_TKEEP = S_AXIS_TKEEP;
assign M_AXIS_TID = S_AXIS_TID;
assign M_AXIS_TDEST = S_AXIS_TDEST;
assign M_AXIS_TUSER = S_AXIS_TUSER;
assign M_AXIS_TLAST = S_AXIS_TLAST;
assign S_AXIS_TREADY = M_AXIS_TREADY;
assign M_AXIS_TVALID = S_AXIS_TVALID;
end endgenerate // gaxis_pass_through;
endmodule //FIFO_GENERATOR_v12_0
/*******************************************************************************
* Declaration of top-level module for Conventional FIFO
******************************************************************************/
module FIFO_GENERATOR_v12_0_CONV_VER
#(
parameter C_COMMON_CLOCK = 0,
parameter C_COUNT_TYPE = 0,
parameter C_DATA_COUNT_WIDTH = 2,
parameter C_DEFAULT_VALUE = "",
parameter C_DIN_WIDTH = 8,
parameter C_DOUT_RST_VAL = "",
parameter C_DOUT_WIDTH = 8,
parameter C_ENABLE_RLOCS = 0,
parameter C_FAMILY = "virtex7", //Not allowed in Verilog model
parameter C_FULL_FLAGS_RST_VAL = 1,
parameter C_HAS_ALMOST_EMPTY = 0,
parameter C_HAS_ALMOST_FULL = 0,
parameter C_HAS_BACKUP = 0,
parameter C_HAS_DATA_COUNT = 0,
parameter C_HAS_INT_CLK = 0,
parameter C_HAS_MEMINIT_FILE = 0,
parameter C_HAS_OVERFLOW = 0,
parameter C_HAS_RD_DATA_COUNT = 0,
parameter C_HAS_RD_RST = 0,
parameter C_HAS_RST = 0,
parameter C_HAS_SRST = 0,
parameter C_HAS_UNDERFLOW = 0,
parameter C_HAS_VALID = 0,
parameter C_HAS_WR_ACK = 0,
parameter C_HAS_WR_DATA_COUNT = 0,
parameter C_HAS_WR_RST = 0,
parameter C_IMPLEMENTATION_TYPE = 0,
parameter C_INIT_WR_PNTR_VAL = 0,
parameter C_MEMORY_TYPE = 1,
parameter C_MIF_FILE_NAME = "",
parameter C_OPTIMIZATION_MODE = 0,
parameter C_OVERFLOW_LOW = 0,
parameter C_PRELOAD_LATENCY = 1,
parameter C_PRELOAD_REGS = 0,
parameter C_PRIM_FIFO_TYPE = "",
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL = 0,
parameter C_PROG_EMPTY_THRESH_NEGATE_VAL = 0,
parameter C_PROG_EMPTY_TYPE = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL = 0,
parameter C_PROG_FULL_THRESH_NEGATE_VAL = 0,
parameter C_PROG_FULL_TYPE = 0,
parameter C_RD_DATA_COUNT_WIDTH = 2,
parameter C_RD_DEPTH = 256,
parameter C_RD_FREQ = 1,
parameter C_RD_PNTR_WIDTH = 8,
parameter C_UNDERFLOW_LOW = 0,
parameter C_USE_DOUT_RST = 0,
parameter C_USE_ECC = 0,
parameter C_USE_EMBEDDED_REG = 0,
parameter C_USE_FIFO16_FLAGS = 0,
parameter C_USE_FWFT_DATA_COUNT = 0,
parameter C_VALID_LOW = 0,
parameter C_WR_ACK_LOW = 0,
parameter C_WR_DATA_COUNT_WIDTH = 2,
parameter C_WR_DEPTH = 256,
parameter C_WR_FREQ = 1,
parameter C_WR_PNTR_WIDTH = 8,
parameter C_WR_RESPONSE_LATENCY = 1,
parameter C_MSGON_VAL = 1,
parameter C_ENABLE_RST_SYNC = 1,
parameter C_ERROR_INJECTION_TYPE = 0,
parameter C_FIFO_TYPE = 0,
parameter C_SYNCHRONIZER_STAGE = 2,
parameter C_AXI_TYPE = 0
)
(
input BACKUP,
input BACKUP_MARKER,
input CLK,
input RST,
input SRST,
input WR_CLK,
input WR_RST,
input RD_CLK,
input RD_RST,
input [C_DIN_WIDTH-1:0] DIN,
input WR_EN,
input RD_EN,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE,
input INT_CLK,
input INJECTDBITERR,
input INJECTSBITERR,
output [C_DOUT_WIDTH-1:0] DOUT,
output FULL,
output ALMOST_FULL,
output WR_ACK,
output OVERFLOW,
output EMPTY,
output ALMOST_EMPTY,
output VALID,
output UNDERFLOW,
output [C_DATA_COUNT_WIDTH-1:0] DATA_COUNT,
output [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT,
output [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT,
output PROG_FULL,
output PROG_EMPTY,
output SBITERR,
output DBITERR,
output wr_rst_busy,
output rd_rst_busy,
output wr_rst_i_out,
output rd_rst_i_out
);
/*
******************************************************************************
* Definition of Parameters
******************************************************************************
* C_COMMON_CLOCK : Common Clock (1), Independent Clocks (0)
* C_COUNT_TYPE : *not used
* C_DATA_COUNT_WIDTH : Width of DATA_COUNT bus
* C_DEFAULT_VALUE : *not used
* C_DIN_WIDTH : Width of DIN bus
* C_DOUT_RST_VAL : Reset value of DOUT
* C_DOUT_WIDTH : Width of DOUT bus
* C_ENABLE_RLOCS : *not used
* C_FAMILY : not used in bhv model
* C_FULL_FLAGS_RST_VAL : Full flags rst val (0 or 1)
* C_HAS_ALMOST_EMPTY : 1=Core has ALMOST_EMPTY flag
* C_HAS_ALMOST_FULL : 1=Core has ALMOST_FULL flag
* C_HAS_BACKUP : *not used
* C_HAS_DATA_COUNT : 1=Core has DATA_COUNT bus
* C_HAS_INT_CLK : not used in bhv model
* C_HAS_MEMINIT_FILE : *not used
* C_HAS_OVERFLOW : 1=Core has OVERFLOW flag
* C_HAS_RD_DATA_COUNT : 1=Core has RD_DATA_COUNT bus
* C_HAS_RD_RST : *not used
* C_HAS_RST : 1=Core has Async Rst
* C_HAS_SRST : 1=Core has Sync Rst
* C_HAS_UNDERFLOW : 1=Core has UNDERFLOW flag
* C_HAS_VALID : 1=Core has VALID flag
* C_HAS_WR_ACK : 1=Core has WR_ACK flag
* C_HAS_WR_DATA_COUNT : 1=Core has WR_DATA_COUNT bus
* C_HAS_WR_RST : *not used
* C_IMPLEMENTATION_TYPE : 0=Common-Clock Bram/Dram
* 1=Common-Clock ShiftRam
* 2=Indep. Clocks Bram/Dram
* 3=Virtex-4 Built-in
* 4=Virtex-5 Built-in
* C_INIT_WR_PNTR_VAL : *not used
* C_MEMORY_TYPE : 1=Block RAM
* 2=Distributed RAM
* 3=Shift RAM
* 4=Built-in FIFO
* C_MIF_FILE_NAME : *not used
* C_OPTIMIZATION_MODE : *not used
* C_OVERFLOW_LOW : 1=OVERFLOW active low
* C_PRELOAD_LATENCY : Latency of read: 0, 1, 2
* C_PRELOAD_REGS : 1=Use output registers
* C_PRIM_FIFO_TYPE : not used in bhv model
* C_PROG_EMPTY_THRESH_ASSERT_VAL: PROG_EMPTY assert threshold
* C_PROG_EMPTY_THRESH_NEGATE_VAL: PROG_EMPTY negate threshold
* C_PROG_EMPTY_TYPE : 0=No programmable empty
* 1=Single prog empty thresh constant
* 2=Multiple prog empty thresh constants
* 3=Single prog empty thresh input
* 4=Multiple prog empty thresh inputs
* C_PROG_FULL_THRESH_ASSERT_VAL : PROG_FULL assert threshold
* C_PROG_FULL_THRESH_NEGATE_VAL : PROG_FULL negate threshold
* C_PROG_FULL_TYPE : 0=No prog full
* 1=Single prog full thresh constant
* 2=Multiple prog full thresh constants
* 3=Single prog full thresh input
* 4=Multiple prog full thresh inputs
* C_RD_DATA_COUNT_WIDTH : Width of RD_DATA_COUNT bus
* C_RD_DEPTH : Depth of read interface (2^N)
* C_RD_FREQ : not used in bhv model
* C_RD_PNTR_WIDTH : always log2(C_RD_DEPTH)
* C_UNDERFLOW_LOW : 1=UNDERFLOW active low
* C_USE_DOUT_RST : 1=Resets DOUT on RST
* C_USE_ECC : Used for error injection purpose
* C_USE_EMBEDDED_REG : 1=Use BRAM embedded output register
* C_USE_FIFO16_FLAGS : not used in bhv model
* C_USE_FWFT_DATA_COUNT : 1=Use extra logic for FWFT data count
* C_VALID_LOW : 1=VALID active low
* C_WR_ACK_LOW : 1=WR_ACK active low
* C_WR_DATA_COUNT_WIDTH : Width of WR_DATA_COUNT bus
* C_WR_DEPTH : Depth of write interface (2^N)
* C_WR_FREQ : not used in bhv model
* C_WR_PNTR_WIDTH : always log2(C_WR_DEPTH)
* C_WR_RESPONSE_LATENCY : *not used
* C_MSGON_VAL : *not used by bhv model
* C_ENABLE_RST_SYNC : 0 = Use WR_RST & RD_RST
* 1 = Use RST
* C_ERROR_INJECTION_TYPE : 0 = No error injection
* 1 = Single bit error injection only
* 2 = Double bit error injection only
* 3 = Single and double bit error injection
******************************************************************************
* Definition of Ports
******************************************************************************
* BACKUP : Not used
* BACKUP_MARKER: Not used
* CLK : Clock
* DIN : Input data bus
* PROG_EMPTY_THRESH : Threshold for Programmable Empty Flag
* PROG_EMPTY_THRESH_ASSERT: Threshold for Programmable Empty Flag
* PROG_EMPTY_THRESH_NEGATE: Threshold for Programmable Empty Flag
* PROG_FULL_THRESH : Threshold for Programmable Full Flag
* PROG_FULL_THRESH_ASSERT : Threshold for Programmable Full Flag
* PROG_FULL_THRESH_NEGATE : Threshold for Programmable Full Flag
* RD_CLK : Read Domain Clock
* RD_EN : Read enable
* RD_RST : Read Reset
* RST : Asynchronous Reset
* SRST : Synchronous Reset
* WR_CLK : Write Domain Clock
* WR_EN : Write enable
* WR_RST : Write Reset
* INT_CLK : Internal Clock
* INJECTSBITERR: Inject Signle bit error
* INJECTDBITERR: Inject Double bit error
* ALMOST_EMPTY : One word remaining in FIFO
* ALMOST_FULL : One empty space remaining in FIFO
* DATA_COUNT : Number of data words in fifo( synchronous to CLK)
* DOUT : Output data bus
* EMPTY : Empty flag
* FULL : Full flag
* OVERFLOW : Last write rejected
* PROG_EMPTY : Programmable Empty Flag
* PROG_FULL : Programmable Full Flag
* RD_DATA_COUNT: Number of data words in fifo (synchronous to RD_CLK)
* UNDERFLOW : Last read rejected
* VALID : Last read acknowledged, DOUT bus VALID
* WR_ACK : Last write acknowledged
* WR_DATA_COUNT: Number of data words in fifo (synchronous to WR_CLK)
* SBITERR : Single Bit ECC Error Detected
* DBITERR : Double Bit ECC Error Detected
******************************************************************************
*/
//----------------------------------------------------------------------------
//- Internal Signals for delayed input signals
//- All the input signals except Clock are delayed by 100 ps and then given to
//- the models.
//----------------------------------------------------------------------------
reg rst_delayed ;
reg empty_fb ;
reg srst_delayed ;
reg wr_rst_delayed ;
reg rd_rst_delayed ;
reg wr_en_delayed ;
reg rd_en_delayed ;
reg [C_DIN_WIDTH-1:0] din_delayed ;
reg [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_delayed ;
reg [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_assert_delayed ;
reg [C_RD_PNTR_WIDTH-1:0] prog_empty_thresh_negate_delayed ;
reg [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_delayed ;
reg [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_assert_delayed ;
reg [C_WR_PNTR_WIDTH-1:0] prog_full_thresh_negate_delayed ;
reg injectdbiterr_delayed ;
reg injectsbiterr_delayed ;
wire empty_p0_out;
always @* rst_delayed <= #`TCQ RST ;
always @* empty_fb <= #`TCQ empty_p0_out ;
always @* srst_delayed <= #`TCQ SRST ;
always @* wr_rst_delayed <= #`TCQ WR_RST ;
always @* rd_rst_delayed <= #`TCQ RD_RST ;
always @* din_delayed <= #`TCQ DIN ;
always @* wr_en_delayed <= #`TCQ WR_EN ;
always @* rd_en_delayed <= #`TCQ RD_EN ;
always @* prog_empty_thresh_delayed <= #`TCQ PROG_EMPTY_THRESH ;
always @* prog_empty_thresh_assert_delayed <= #`TCQ PROG_EMPTY_THRESH_ASSERT ;
always @* prog_empty_thresh_negate_delayed <= #`TCQ PROG_EMPTY_THRESH_NEGATE ;
always @* prog_full_thresh_delayed <= #`TCQ PROG_FULL_THRESH ;
always @* prog_full_thresh_assert_delayed <= #`TCQ PROG_FULL_THRESH_ASSERT ;
always @* prog_full_thresh_negate_delayed <= #`TCQ PROG_FULL_THRESH_NEGATE ;
always @* injectdbiterr_delayed <= #`TCQ INJECTDBITERR ;
always @* injectsbiterr_delayed <= #`TCQ INJECTSBITERR ;
/*****************************************************************************
* Derived parameters
****************************************************************************/
//There are 2 Verilog behavioral models
// 0 = Common-Clock FIFO/ShiftRam FIFO
// 1 = Independent Clocks FIFO
// 2 = Low Latency Synchronous FIFO
// 3 = Low Latency Asynchronous FIFO
localparam C_VERILOG_IMPL = (C_FIFO_TYPE == 3) ? 2 :
(C_IMPLEMENTATION_TYPE == 2) ? 1 : 0;
localparam IS_8SERIES = (C_FAMILY == "virtexu" || C_FAMILY == "kintexu" || C_FAMILY == "artixu" || C_FAMILY == "virtexum" || C_FAMILY == "zynque") ? 1 : 0;
//Internal reset signals
reg rd_rst_asreg = 0;
reg rd_rst_asreg_d1 = 0;
reg rd_rst_asreg_d2 = 0;
reg rd_rst_asreg_d3 = 0;
reg rd_rst_reg = 0;
wire rd_rst_comb;
reg wr_rst_d0 = 0;
reg wr_rst_d1 = 0;
reg wr_rst_d2 = 0;
reg rd_rst_d0 = 0;
reg rd_rst_d1 = 0;
reg rd_rst_d2 = 0;
reg rd_rst_d3 = 0;
reg wrrst_done = 0;
reg rdrst_done = 0;
reg wr_rst_asreg = 0;
reg wr_rst_asreg_d1 = 0;
reg wr_rst_asreg_d2 = 0;
reg wr_rst_asreg_d3 = 0;
reg rd_rst_wr_d0 = 0;
reg rd_rst_wr_d1 = 0;
reg rd_rst_wr_d2 = 0;
reg wr_rst_reg = 0;
reg rst_active_i = 1'b1;
reg rst_delayed_d1 = 1'b1;
reg rst_delayed_d2 = 1'b1;
wire wr_rst_comb;
wire wr_rst_i;
wire rd_rst_i;
wire rst_i;
//Internal reset signals
reg rst_asreg = 0;
reg srst_asreg = 0;
reg rst_asreg_d1 = 0;
reg rst_asreg_d2 = 0;
reg srst_asreg_d1 = 0;
reg srst_asreg_d2 = 0;
reg rst_reg = 0;
reg srst_reg = 0;
wire rst_comb;
wire srst_comb;
reg rst_full_gen_i = 0;
reg rst_full_ff_i = 0;
wire RD_CLK_P0_IN;
wire RST_P0_IN;
wire RD_EN_FIFO_IN;
wire RD_EN_P0_IN;
wire ALMOST_EMPTY_FIFO_OUT;
wire ALMOST_FULL_FIFO_OUT;
wire [C_DATA_COUNT_WIDTH-1:0] DATA_COUNT_FIFO_OUT;
wire [C_DOUT_WIDTH-1:0] DOUT_FIFO_OUT;
wire EMPTY_FIFO_OUT;
wire FULL_FIFO_OUT;
wire OVERFLOW_FIFO_OUT;
wire PROG_EMPTY_FIFO_OUT;
wire PROG_FULL_FIFO_OUT;
wire VALID_FIFO_OUT;
wire [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT_FIFO_OUT;
wire UNDERFLOW_FIFO_OUT;
wire WR_ACK_FIFO_OUT;
wire [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT_FIFO_OUT;
//***************************************************************************
// Internal Signals
// The core uses either the internal_ wires or the preload0_ wires depending
// on whether the core uses Preload0 or not.
// When using preload0, the internal signals connect the internal core to
// the preload logic, and the external core's interfaces are tied to the
// preload0 signals from the preload logic.
//***************************************************************************
wire [C_DOUT_WIDTH-1:0] DATA_P0_OUT;
wire VALID_P0_OUT;
wire EMPTY_P0_OUT;
wire ALMOSTEMPTY_P0_OUT;
reg EMPTY_P0_OUT_Q;
reg ALMOSTEMPTY_P0_OUT_Q;
wire UNDERFLOW_P0_OUT;
wire RDEN_P0_OUT;
wire [C_DOUT_WIDTH-1:0] DATA_P0_IN;
wire EMPTY_P0_IN;
reg [31:0] DATA_COUNT_FWFT;
reg SS_FWFT_WR ;
reg SS_FWFT_RD ;
wire sbiterr_fifo_out;
wire dbiterr_fifo_out;
wire inject_sbit_err;
wire inject_dbit_err;
// Assign 0 if not selected to avoid 'X' propogation to S/DBITERR.
assign inject_sbit_err = ((C_ERROR_INJECTION_TYPE == 1) || (C_ERROR_INJECTION_TYPE == 3)) ?
injectsbiterr_delayed : 0;
assign inject_dbit_err = ((C_ERROR_INJECTION_TYPE == 2) || (C_ERROR_INJECTION_TYPE == 3)) ?
injectdbiterr_delayed : 0;
assign wr_rst_i_out = wr_rst_i;
assign rd_rst_i_out = rd_rst_i;
// Choose the behavioral model to instantiate based on the C_VERILOG_IMPL
// parameter (1=Independent Clocks, 0=Common Clock)
localparam FULL_FLAGS_RST_VAL = (C_HAS_SRST == 1) ? 0 : C_FULL_FLAGS_RST_VAL;
generate
case (C_VERILOG_IMPL)
0 : begin : block1
//Common Clock Behavioral Model
fifo_generator_v12_0_bhv_ver_ss
#(
.C_FAMILY (C_FAMILY),
.C_DATA_COUNT_WIDTH (C_DATA_COUNT_WIDTH),
.C_DIN_WIDTH (C_DIN_WIDTH),
.C_DOUT_RST_VAL (C_DOUT_RST_VAL),
.C_DOUT_WIDTH (C_DOUT_WIDTH),
.C_FULL_FLAGS_RST_VAL (FULL_FLAGS_RST_VAL),
.C_HAS_ALMOST_EMPTY (C_HAS_ALMOST_EMPTY),
.C_HAS_ALMOST_FULL ((C_AXI_TYPE == 0 && C_FIFO_TYPE == 1) ? 1 : C_HAS_ALMOST_FULL),
.C_HAS_DATA_COUNT (C_HAS_DATA_COUNT),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT),
.C_HAS_RST (C_HAS_RST),
.C_HAS_SRST (C_HAS_SRST),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_HAS_VALID (C_HAS_VALID),
.C_HAS_WR_ACK (C_HAS_WR_ACK),
.C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT),
.C_IMPLEMENTATION_TYPE (C_IMPLEMENTATION_TYPE),
.C_MEMORY_TYPE (C_MEMORY_TYPE),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_PRELOAD_LATENCY (C_PRELOAD_LATENCY),
.C_PRELOAD_REGS (C_PRELOAD_REGS),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL),
.C_PROG_EMPTY_THRESH_NEGATE_VAL (C_PROG_EMPTY_THRESH_NEGATE_VAL),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL),
.C_PROG_FULL_THRESH_NEGATE_VAL (C_PROG_FULL_THRESH_NEGATE_VAL),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE),
.C_RD_DATA_COUNT_WIDTH (C_RD_DATA_COUNT_WIDTH),
.C_RD_DEPTH (C_RD_DEPTH),
.C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_USE_DOUT_RST (C_USE_DOUT_RST),
.C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG),
.C_USE_FWFT_DATA_COUNT (C_USE_FWFT_DATA_COUNT),
.C_VALID_LOW (C_VALID_LOW),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH),
.C_WR_DEPTH (C_WR_DEPTH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH),
.C_USE_ECC (C_USE_ECC),
.C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE),
.C_FIFO_TYPE (C_FIFO_TYPE)
)
gen_ss
(
.CLK (CLK),
.RST (rst_i),
.SRST (srst_delayed),
.RST_FULL_GEN (rst_full_gen_i),
.RST_FULL_FF (rst_full_ff_i),
.DIN (din_delayed),
.WR_EN (wr_en_delayed),
.RD_EN (RD_EN_FIFO_IN),
.RD_EN_USER (rd_en_delayed),
.USER_EMPTY_FB (empty_fb),
.PROG_EMPTY_THRESH (prog_empty_thresh_delayed),
.PROG_EMPTY_THRESH_ASSERT (prog_empty_thresh_assert_delayed),
.PROG_EMPTY_THRESH_NEGATE (prog_empty_thresh_negate_delayed),
.PROG_FULL_THRESH (prog_full_thresh_delayed),
.PROG_FULL_THRESH_ASSERT (prog_full_thresh_assert_delayed),
.PROG_FULL_THRESH_NEGATE (prog_full_thresh_negate_delayed),
.INJECTSBITERR (inject_sbit_err),
.INJECTDBITERR (inject_dbit_err),
.DOUT (DOUT_FIFO_OUT),
.FULL (FULL_FIFO_OUT),
.ALMOST_FULL (ALMOST_FULL_FIFO_OUT),
.WR_ACK (WR_ACK_FIFO_OUT),
.OVERFLOW (OVERFLOW_FIFO_OUT),
.EMPTY (EMPTY_FIFO_OUT),
.ALMOST_EMPTY (ALMOST_EMPTY_FIFO_OUT),
.VALID (VALID_FIFO_OUT),
.UNDERFLOW (UNDERFLOW_FIFO_OUT),
.DATA_COUNT (DATA_COUNT_FIFO_OUT),
.RD_DATA_COUNT (RD_DATA_COUNT_FIFO_OUT),
.WR_DATA_COUNT (WR_DATA_COUNT_FIFO_OUT),
.PROG_FULL (PROG_FULL_FIFO_OUT),
.PROG_EMPTY (PROG_EMPTY_FIFO_OUT),
.WR_RST_BUSY (wr_rst_busy),
.RD_RST_BUSY (rd_rst_busy),
.SBITERR (sbiterr_fifo_out),
.DBITERR (dbiterr_fifo_out)
);
end
1 : begin : block1
//Independent Clocks Behavioral Model
fifo_generator_v12_0_bhv_ver_as
#(
.C_FAMILY (C_FAMILY),
.C_DATA_COUNT_WIDTH (C_DATA_COUNT_WIDTH),
.C_DIN_WIDTH (C_DIN_WIDTH),
.C_DOUT_RST_VAL (C_DOUT_RST_VAL),
.C_DOUT_WIDTH (C_DOUT_WIDTH),
.C_FULL_FLAGS_RST_VAL (C_FULL_FLAGS_RST_VAL),
.C_HAS_ALMOST_EMPTY (C_HAS_ALMOST_EMPTY),
.C_HAS_ALMOST_FULL (C_HAS_ALMOST_FULL),
.C_HAS_DATA_COUNT (C_HAS_DATA_COUNT),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT),
.C_HAS_RST (C_HAS_RST),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_HAS_VALID (C_HAS_VALID),
.C_HAS_WR_ACK (C_HAS_WR_ACK),
.C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT),
.C_IMPLEMENTATION_TYPE (C_IMPLEMENTATION_TYPE),
.C_MEMORY_TYPE (C_MEMORY_TYPE),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_PRELOAD_LATENCY (C_PRELOAD_LATENCY),
.C_PRELOAD_REGS (C_PRELOAD_REGS),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL),
.C_PROG_EMPTY_THRESH_NEGATE_VAL (C_PROG_EMPTY_THRESH_NEGATE_VAL),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL),
.C_PROG_FULL_THRESH_NEGATE_VAL (C_PROG_FULL_THRESH_NEGATE_VAL),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE),
.C_RD_DATA_COUNT_WIDTH (C_RD_DATA_COUNT_WIDTH),
.C_RD_DEPTH (C_RD_DEPTH),
.C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_USE_DOUT_RST (C_USE_DOUT_RST),
.C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG),
.C_USE_FWFT_DATA_COUNT (C_USE_FWFT_DATA_COUNT),
.C_VALID_LOW (C_VALID_LOW),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH),
.C_WR_DEPTH (C_WR_DEPTH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH),
.C_USE_ECC (C_USE_ECC),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE),
.C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE)
)
gen_as
(
.WR_CLK (WR_CLK),
.RD_CLK (RD_CLK),
.RST (rst_i),
.RST_FULL_GEN (rst_full_gen_i),
.RST_FULL_FF (rst_full_ff_i),
.WR_RST (wr_rst_i),
.RD_RST (rd_rst_i),
.DIN (din_delayed),
.WR_EN (wr_en_delayed),
.RD_EN (RD_EN_FIFO_IN),
.RD_EN_USER (rd_en_delayed),
.PROG_EMPTY_THRESH (prog_empty_thresh_delayed),
.PROG_EMPTY_THRESH_ASSERT (prog_empty_thresh_assert_delayed),
.PROG_EMPTY_THRESH_NEGATE (prog_empty_thresh_negate_delayed),
.PROG_FULL_THRESH (prog_full_thresh_delayed),
.PROG_FULL_THRESH_ASSERT (prog_full_thresh_assert_delayed),
.PROG_FULL_THRESH_NEGATE (prog_full_thresh_negate_delayed),
.INJECTSBITERR (inject_sbit_err),
.INJECTDBITERR (inject_dbit_err),
.USER_EMPTY_FB (EMPTY_P0_OUT),
.DOUT (DOUT_FIFO_OUT),
.FULL (FULL_FIFO_OUT),
.ALMOST_FULL (ALMOST_FULL_FIFO_OUT),
.WR_ACK (WR_ACK_FIFO_OUT),
.OVERFLOW (OVERFLOW_FIFO_OUT),
.EMPTY (EMPTY_FIFO_OUT),
.ALMOST_EMPTY (ALMOST_EMPTY_FIFO_OUT),
.VALID (VALID_FIFO_OUT),
.UNDERFLOW (UNDERFLOW_FIFO_OUT),
.RD_DATA_COUNT (RD_DATA_COUNT_FIFO_OUT),
.WR_DATA_COUNT (WR_DATA_COUNT_FIFO_OUT),
.PROG_FULL (PROG_FULL_FIFO_OUT),
.PROG_EMPTY (PROG_EMPTY_FIFO_OUT),
.SBITERR (sbiterr_fifo_out),
.DBITERR (dbiterr_fifo_out)
);
end
2 : begin : ll_afifo_inst
fifo_generator_v12_0_beh_ver_ll_afifo
#(
.C_DIN_WIDTH (C_DIN_WIDTH),
.C_DOUT_RST_VAL (C_DOUT_RST_VAL),
.C_DOUT_WIDTH (C_DOUT_WIDTH),
.C_FULL_FLAGS_RST_VAL (C_FULL_FLAGS_RST_VAL),
.C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT),
.C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT),
.C_RD_DEPTH (C_RD_DEPTH),
.C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH),
.C_USE_DOUT_RST (C_USE_DOUT_RST),
.C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH),
.C_WR_DEPTH (C_WR_DEPTH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH),
.C_FIFO_TYPE (C_FIFO_TYPE)
)
gen_ll_afifo
(
.DIN (din_delayed),
.RD_CLK (RD_CLK),
.RD_EN (rd_en_delayed),
.WR_RST (wr_rst_i),
.RD_RST (rd_rst_i),
.WR_CLK (WR_CLK),
.WR_EN (wr_en_delayed),
.DOUT (DOUT),
.EMPTY (EMPTY),
.FULL (FULL)
);
end
default : begin : block1
//Independent Clocks Behavioral Model
fifo_generator_v12_0_bhv_ver_as
#(
.C_FAMILY (C_FAMILY),
.C_DATA_COUNT_WIDTH (C_DATA_COUNT_WIDTH),
.C_DIN_WIDTH (C_DIN_WIDTH),
.C_DOUT_RST_VAL (C_DOUT_RST_VAL),
.C_DOUT_WIDTH (C_DOUT_WIDTH),
.C_FULL_FLAGS_RST_VAL (C_FULL_FLAGS_RST_VAL),
.C_HAS_ALMOST_EMPTY (C_HAS_ALMOST_EMPTY),
.C_HAS_ALMOST_FULL (C_HAS_ALMOST_FULL),
.C_HAS_DATA_COUNT (C_HAS_DATA_COUNT),
.C_HAS_OVERFLOW (C_HAS_OVERFLOW),
.C_HAS_RD_DATA_COUNT (C_HAS_RD_DATA_COUNT),
.C_HAS_RST (C_HAS_RST),
.C_HAS_UNDERFLOW (C_HAS_UNDERFLOW),
.C_HAS_VALID (C_HAS_VALID),
.C_HAS_WR_ACK (C_HAS_WR_ACK),
.C_HAS_WR_DATA_COUNT (C_HAS_WR_DATA_COUNT),
.C_IMPLEMENTATION_TYPE (C_IMPLEMENTATION_TYPE),
.C_MEMORY_TYPE (C_MEMORY_TYPE),
.C_OVERFLOW_LOW (C_OVERFLOW_LOW),
.C_PRELOAD_LATENCY (C_PRELOAD_LATENCY),
.C_PRELOAD_REGS (C_PRELOAD_REGS),
.C_PROG_EMPTY_THRESH_ASSERT_VAL (C_PROG_EMPTY_THRESH_ASSERT_VAL),
.C_PROG_EMPTY_THRESH_NEGATE_VAL (C_PROG_EMPTY_THRESH_NEGATE_VAL),
.C_PROG_EMPTY_TYPE (C_PROG_EMPTY_TYPE),
.C_PROG_FULL_THRESH_ASSERT_VAL (C_PROG_FULL_THRESH_ASSERT_VAL),
.C_PROG_FULL_THRESH_NEGATE_VAL (C_PROG_FULL_THRESH_NEGATE_VAL),
.C_PROG_FULL_TYPE (C_PROG_FULL_TYPE),
.C_RD_DATA_COUNT_WIDTH (C_RD_DATA_COUNT_WIDTH),
.C_RD_DEPTH (C_RD_DEPTH),
.C_RD_PNTR_WIDTH (C_RD_PNTR_WIDTH),
.C_UNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_USE_DOUT_RST (C_USE_DOUT_RST),
.C_USE_EMBEDDED_REG (C_USE_EMBEDDED_REG),
.C_USE_FWFT_DATA_COUNT (C_USE_FWFT_DATA_COUNT),
.C_VALID_LOW (C_VALID_LOW),
.C_WR_ACK_LOW (C_WR_ACK_LOW),
.C_WR_DATA_COUNT_WIDTH (C_WR_DATA_COUNT_WIDTH),
.C_WR_DEPTH (C_WR_DEPTH),
.C_WR_PNTR_WIDTH (C_WR_PNTR_WIDTH),
.C_USE_ECC (C_USE_ECC),
.C_SYNCHRONIZER_STAGE (C_SYNCHRONIZER_STAGE),
.C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC),
.C_ERROR_INJECTION_TYPE (C_ERROR_INJECTION_TYPE)
)
gen_as
(
.WR_CLK (WR_CLK),
.RD_CLK (RD_CLK),
.RST (rst_i),
.RST_FULL_GEN (rst_full_gen_i),
.RST_FULL_FF (rst_full_ff_i),
.WR_RST (wr_rst_i),
.RD_RST (rd_rst_i),
.DIN (din_delayed),
.WR_EN (wr_en_delayed),
.RD_EN (RD_EN_FIFO_IN),
.RD_EN_USER (rd_en_delayed),
.PROG_EMPTY_THRESH (prog_empty_thresh_delayed),
.PROG_EMPTY_THRESH_ASSERT (prog_empty_thresh_assert_delayed),
.PROG_EMPTY_THRESH_NEGATE (prog_empty_thresh_negate_delayed),
.PROG_FULL_THRESH (prog_full_thresh_delayed),
.PROG_FULL_THRESH_ASSERT (prog_full_thresh_assert_delayed),
.PROG_FULL_THRESH_NEGATE (prog_full_thresh_negate_delayed),
.INJECTSBITERR (inject_sbit_err),
.INJECTDBITERR (inject_dbit_err),
.USER_EMPTY_FB (EMPTY_P0_OUT),
.DOUT (DOUT_FIFO_OUT),
.FULL (FULL_FIFO_OUT),
.ALMOST_FULL (ALMOST_FULL_FIFO_OUT),
.WR_ACK (WR_ACK_FIFO_OUT),
.OVERFLOW (OVERFLOW_FIFO_OUT),
.EMPTY (EMPTY_FIFO_OUT),
.ALMOST_EMPTY (ALMOST_EMPTY_FIFO_OUT),
.VALID (VALID_FIFO_OUT),
.UNDERFLOW (UNDERFLOW_FIFO_OUT),
.RD_DATA_COUNT (RD_DATA_COUNT_FIFO_OUT),
.WR_DATA_COUNT (WR_DATA_COUNT_FIFO_OUT),
.PROG_FULL (PROG_FULL_FIFO_OUT),
.PROG_EMPTY (PROG_EMPTY_FIFO_OUT),
.SBITERR (sbiterr_fifo_out),
.DBITERR (dbiterr_fifo_out)
);
end
endcase
endgenerate
//**************************************************************************
// Connect Internal Signals
// (Signals labeled internal_*)
// In the normal case, these signals tie directly to the FIFO's inputs and
// outputs.
// In the case of Preload Latency 0 or 1, there are intermediate
// signals between the internal FIFO and the preload logic.
//**************************************************************************
//***********************************************
// If First-Word Fall-Through, instantiate
// the preload0 (FWFT) module
//***********************************************
wire rd_en_to_fwft_fifo;
wire sbiterr_fwft;
wire dbiterr_fwft;
wire [C_DOUT_WIDTH-1:0] dout_fwft;
wire empty_fwft;
wire rd_en_fifo_in;
wire stage2_reg_en_i;
wire [1:0] valid_stages_i;
wire rst_fwft;
//wire empty_p0_out;
reg [C_SYNCHRONIZER_STAGE-1:0] pkt_empty_sync = 'b1;
localparam IS_FWFT = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? 1 : 0;
localparam IS_PKT_FIFO = (C_FIFO_TYPE == 1) ? 1 : 0;
localparam IS_AXIS_PKT_FIFO = (C_FIFO_TYPE == 1 && C_AXI_TYPE == 0) ? 1 : 0;
assign rst_fwft = (C_COMMON_CLOCK == 0) ? rd_rst_i : (C_HAS_RST == 1) ? rst_i : 1'b0;
generate if (IS_FWFT == 1 && C_FIFO_TYPE != 3) begin : block2
fifo_generator_v12_0_bhv_ver_preload0
#(
.C_DOUT_RST_VAL (C_DOUT_RST_VAL),
.C_DOUT_WIDTH (C_DOUT_WIDTH),
.C_HAS_RST (C_HAS_RST),
.C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC),
.C_HAS_SRST (C_HAS_SRST),
.C_USE_DOUT_RST (C_USE_DOUT_RST),
.C_USE_ECC (C_USE_ECC),
.C_USERVALID_LOW (C_VALID_LOW),
.C_USERUNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_MEMORY_TYPE (C_MEMORY_TYPE),
.C_FIFO_TYPE (C_FIFO_TYPE)
)
fgpl0
(
.RD_CLK (RD_CLK_P0_IN),
.RD_RST (RST_P0_IN),
.SRST (srst_delayed),
.WR_RST_BUSY (wr_rst_busy),
.RD_RST_BUSY (rd_rst_busy),
.RD_EN (RD_EN_P0_IN),
.FIFOEMPTY (EMPTY_P0_IN),
.FIFODATA (DATA_P0_IN),
.FIFOSBITERR (sbiterr_fifo_out),
.FIFODBITERR (dbiterr_fifo_out),
// Output
.USERDATA (dout_fwft),
.USERVALID (VALID_P0_OUT),
.USEREMPTY (empty_fwft),
.USERALMOSTEMPTY (ALMOSTEMPTY_P0_OUT),
.USERUNDERFLOW (UNDERFLOW_P0_OUT),
.RAMVALID (),
.FIFORDEN (rd_en_fifo_in),
.USERSBITERR (sbiterr_fwft),
.USERDBITERR (dbiterr_fwft),
.STAGE2_REG_EN (stage2_reg_en_i),
.VALID_STAGES (valid_stages_i)
);
//***********************************************
// Connect inputs to preload (FWFT) module
//***********************************************
//Connect the RD_CLK of the Preload (FWFT) module to CLK if we
// have a common-clock FIFO, or RD_CLK if we have an
// independent clock FIFO
assign RD_CLK_P0_IN = ((C_VERILOG_IMPL == 0) ? CLK : RD_CLK);
assign RST_P0_IN = (C_COMMON_CLOCK == 0) ? rd_rst_i : (C_HAS_RST == 1) ? rst_i : 0;
assign RD_EN_P0_IN = (C_FIFO_TYPE != 1) ? rd_en_delayed : rd_en_to_fwft_fifo;
assign EMPTY_P0_IN = EMPTY_FIFO_OUT;
assign DATA_P0_IN = DOUT_FIFO_OUT;
//***********************************************
// Connect outputs from preload (FWFT) module
//***********************************************
assign VALID = VALID_P0_OUT ;
assign ALMOST_EMPTY = ALMOSTEMPTY_P0_OUT;
assign UNDERFLOW = UNDERFLOW_P0_OUT ;
assign RD_EN_FIFO_IN = rd_en_fifo_in;
//***********************************************
// Create DATA_COUNT from First-Word Fall-Through
// data count
//***********************************************
assign DATA_COUNT = (C_USE_FWFT_DATA_COUNT == 0)? DATA_COUNT_FIFO_OUT:
(C_DATA_COUNT_WIDTH>C_RD_PNTR_WIDTH) ? DATA_COUNT_FWFT[C_RD_PNTR_WIDTH:0] :
DATA_COUNT_FWFT[C_RD_PNTR_WIDTH:C_RD_PNTR_WIDTH-C_DATA_COUNT_WIDTH+1];
//***********************************************
// Create DATA_COUNT from First-Word Fall-Through
// data count
//***********************************************
always @ (posedge RD_CLK_P0_IN or posedge RST_P0_IN) begin
if (RST_P0_IN) begin
EMPTY_P0_OUT_Q <= #`TCQ 1;
ALMOSTEMPTY_P0_OUT_Q <= #`TCQ 1;
end else begin
EMPTY_P0_OUT_Q <= #`TCQ empty_p0_out;
// EMPTY_P0_OUT_Q <= #`TCQ EMPTY_FIFO_OUT;
ALMOSTEMPTY_P0_OUT_Q <= #`TCQ ALMOSTEMPTY_P0_OUT;
end
end //always
//***********************************************
// logic for common-clock data count when FWFT is selected
//***********************************************
initial begin
SS_FWFT_RD = 1'b0;
DATA_COUNT_FWFT = 0 ;
SS_FWFT_WR = 1'b0 ;
end //initial
//***********************************************
// common-clock data count is implemented as an
// up-down counter. SS_FWFT_WR and SS_FWFT_RD
// are the up/down enables for the counter.
//***********************************************
always @ (RD_EN or VALID_P0_OUT or WR_EN or FULL_FIFO_OUT or empty_p0_out) begin
if (C_VALID_LOW == 1) begin
SS_FWFT_RD = (C_FIFO_TYPE != 1) ? (RD_EN && ~VALID_P0_OUT) : (~empty_p0_out && RD_EN && ~VALID_P0_OUT) ;
end else begin
SS_FWFT_RD = (C_FIFO_TYPE != 1) ? (RD_EN && VALID_P0_OUT) : (~empty_p0_out && RD_EN && VALID_P0_OUT) ;
end
SS_FWFT_WR = (WR_EN && (~FULL_FIFO_OUT)) ;
end
//***********************************************
// common-clock data count is implemented as an
// up-down counter for FWFT. This always block
// calculates the counter.
//***********************************************
always @ (posedge RD_CLK_P0_IN or posedge RST_P0_IN) begin
if (RST_P0_IN) begin
DATA_COUNT_FWFT <= #`TCQ 0;
end else begin
//if (srst_delayed && (C_HAS_SRST == 1) ) begin
if ((srst_delayed | wr_rst_busy | rd_rst_busy) && (C_HAS_SRST == 1) ) begin
DATA_COUNT_FWFT <= #`TCQ 0;
end else begin
case ( {SS_FWFT_WR, SS_FWFT_RD})
2'b00: DATA_COUNT_FWFT <= #`TCQ DATA_COUNT_FWFT ;
2'b01: DATA_COUNT_FWFT <= #`TCQ DATA_COUNT_FWFT - 1 ;
2'b10: DATA_COUNT_FWFT <= #`TCQ DATA_COUNT_FWFT + 1 ;
2'b11: DATA_COUNT_FWFT <= #`TCQ DATA_COUNT_FWFT ;
endcase
end //if SRST
end //IF RST
end //always
end endgenerate // : block2
// AXI Streaming Packet FIFO
reg [C_WR_PNTR_WIDTH-1:0] wr_pkt_count = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pkt_count = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pkt_count_plus1 = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pkt_count_reg = 0;
reg partial_packet = 0;
reg stage1_eop_d1 = 0;
reg rd_en_fifo_in_d1 = 0;
reg eop_at_stage2 = 0;
reg ram_pkt_empty = 0;
reg ram_pkt_empty_d1 = 0;
wire [C_DOUT_WIDTH-1:0] dout_p0_out;
wire packet_empty_wr;
wire wr_rst_fwft_pkt_fifo;
wire dummy_wr_eop;
wire ram_wr_en_pkt_fifo;
wire wr_eop;
wire ram_rd_en_compare;
wire stage1_eop;
wire pkt_ready_to_read;
wire rd_en_2_stage2;
// Generate Dummy WR_EOP for partial packet (Only for AXI Streaming)
// When Packet EMPTY is high, and FIFO is full, then generate the dummy WR_EOP
// When dummy WR_EOP is high, mask the actual EOP to avoid double increment of
// write packet count
generate if (IS_FWFT == 1 && IS_AXIS_PKT_FIFO == 1) begin // gdummy_wr_eop
always @ (posedge wr_rst_fwft_pkt_fifo or posedge WR_CLK) begin
if (wr_rst_fwft_pkt_fifo)
partial_packet <= 1'b0;
else begin
if (srst_delayed | wr_rst_busy | rd_rst_busy)
partial_packet <= #`TCQ 1'b0;
else if (ALMOST_FULL_FIFO_OUT && ram_wr_en_pkt_fifo && packet_empty_wr && (~din_delayed[0]))
partial_packet <= #`TCQ 1'b1;
else if (partial_packet && din_delayed[0] && ram_wr_en_pkt_fifo)
partial_packet <= #`TCQ 1'b0;
end
end
end endgenerate // gdummy_wr_eop
generate if (IS_FWFT == 1 && IS_PKT_FIFO == 1) begin // gpkt_fifo_fwft
assign wr_rst_fwft_pkt_fifo = (C_COMMON_CLOCK == 0) ? wr_rst_i : (C_HAS_RST == 1) ? rst_i:1'b0;
assign dummy_wr_eop = ALMOST_FULL_FIFO_OUT && ram_wr_en_pkt_fifo && packet_empty_wr && (~din_delayed[0]) && (~partial_packet);
assign packet_empty_wr = (C_COMMON_CLOCK == 1) ? empty_p0_out : pkt_empty_sync[C_SYNCHRONIZER_STAGE-1];
always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin
if (rst_fwft) begin
stage1_eop_d1 <= 1'b0;
rd_en_fifo_in_d1 <= 1'b0;
end else begin
if (srst_delayed | wr_rst_busy | rd_rst_busy) begin
stage1_eop_d1 <= #`TCQ 1'b0;
rd_en_fifo_in_d1 <= #`TCQ 1'b0;
end else begin
stage1_eop_d1 <= #`TCQ stage1_eop;
rd_en_fifo_in_d1 <= #`TCQ rd_en_fifo_in;
end
end
end
assign stage1_eop = (rd_en_fifo_in_d1) ? DOUT_FIFO_OUT[0] : stage1_eop_d1;
assign ram_wr_en_pkt_fifo = wr_en_delayed && (~FULL_FIFO_OUT);
assign wr_eop = ram_wr_en_pkt_fifo && ((din_delayed[0] && (~partial_packet)) || dummy_wr_eop);
assign ram_rd_en_compare = stage2_reg_en_i && stage1_eop;
fifo_generator_v12_0_bhv_ver_preload0
#(
.C_DOUT_RST_VAL (C_DOUT_RST_VAL),
.C_DOUT_WIDTH (C_DOUT_WIDTH),
.C_HAS_RST (C_HAS_RST),
.C_HAS_SRST (C_HAS_SRST),
.C_USE_DOUT_RST (C_USE_DOUT_RST),
.C_USE_ECC (C_USE_ECC),
.C_USERVALID_LOW (C_VALID_LOW),
.C_USERUNDERFLOW_LOW (C_UNDERFLOW_LOW),
.C_ENABLE_RST_SYNC (C_ENABLE_RST_SYNC),
.C_MEMORY_TYPE (C_MEMORY_TYPE),
.C_FIFO_TYPE (2) // Enable low latency fwft logic
)
pkt_fifo_fwft
(
.RD_CLK (RD_CLK_P0_IN),
.RD_RST (rst_fwft),
.SRST (srst_delayed),
.WR_RST_BUSY (wr_rst_busy),
.RD_RST_BUSY (rd_rst_busy),
.RD_EN (rd_en_delayed),
.FIFOEMPTY (pkt_ready_to_read),
.FIFODATA (dout_fwft),
.FIFOSBITERR (sbiterr_fwft),
.FIFODBITERR (dbiterr_fwft),
// Output
.USERDATA (dout_p0_out),
.USERVALID (),
.USEREMPTY (empty_p0_out),
.USERALMOSTEMPTY (),
.USERUNDERFLOW (),
.RAMVALID (),
.FIFORDEN (rd_en_2_stage2),
.USERSBITERR (SBITERR),
.USERDBITERR (DBITERR),
.STAGE2_REG_EN (),
.VALID_STAGES ()
);
assign pkt_ready_to_read = ~(!(ram_pkt_empty || empty_fwft) && ((valid_stages_i[0] && valid_stages_i[1]) || eop_at_stage2));
assign rd_en_to_fwft_fifo = ~empty_fwft && rd_en_2_stage2;
always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin
if (rst_fwft)
eop_at_stage2 <= 1'b0;
else if (stage2_reg_en_i)
eop_at_stage2 <= #`TCQ stage1_eop;
end
//---------------------------------------------------------------------------
// Write and Read Packet Count
//---------------------------------------------------------------------------
always @ (posedge wr_rst_fwft_pkt_fifo or posedge WR_CLK) begin
if (wr_rst_fwft_pkt_fifo)
wr_pkt_count <= 0;
else if (srst_delayed | wr_rst_busy | rd_rst_busy)
wr_pkt_count <= #`TCQ 0;
else if (wr_eop)
wr_pkt_count <= #`TCQ wr_pkt_count + 1;
end
end endgenerate // gpkt_fifo_fwft
assign DOUT = (C_FIFO_TYPE != 1) ? dout_fwft : dout_p0_out;
assign EMPTY = (C_FIFO_TYPE != 1) ? empty_fwft : empty_p0_out;
generate if (IS_FWFT == 1 && IS_PKT_FIFO == 1 && C_COMMON_CLOCK == 1) begin // grss_pkt_cnt
always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin
if (rst_fwft) begin
rd_pkt_count <= 0;
rd_pkt_count_plus1 <= 1;
end else if (srst_delayed | wr_rst_busy | rd_rst_busy) begin
rd_pkt_count <= #`TCQ 0;
rd_pkt_count_plus1 <= #`TCQ 1;
end else if (stage2_reg_en_i && stage1_eop) begin
rd_pkt_count <= #`TCQ rd_pkt_count + 1;
rd_pkt_count_plus1 <= #`TCQ rd_pkt_count_plus1 + 1;
end
end
always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin
if (rst_fwft) begin
ram_pkt_empty <= 1'b1;
ram_pkt_empty_d1 <= 1'b1;
end else if (SRST | wr_rst_busy | rd_rst_busy) begin
ram_pkt_empty <= #`TCQ 1'b1;
ram_pkt_empty_d1 <= #`TCQ 1'b1;
end else if ((rd_pkt_count == wr_pkt_count) && wr_eop) begin
ram_pkt_empty <= #`TCQ 1'b0;
ram_pkt_empty_d1 <= #`TCQ 1'b0;
end else if (ram_pkt_empty_d1 && rd_en_to_fwft_fifo) begin
ram_pkt_empty <= #`TCQ 1'b1;
end else if ((rd_pkt_count_plus1 == wr_pkt_count) && ~wr_eop && ~ALMOST_FULL_FIFO_OUT && ram_rd_en_compare) begin
ram_pkt_empty_d1 <= #`TCQ 1'b1;
end
end
end endgenerate //grss_pkt_cnt
localparam SYNC_STAGE_WIDTH = (C_SYNCHRONIZER_STAGE+1)*C_WR_PNTR_WIDTH;
reg [SYNC_STAGE_WIDTH-1:0] wr_pkt_count_q = 0;
reg [C_WR_PNTR_WIDTH-1:0] wr_pkt_count_b2g = 0;
wire [C_WR_PNTR_WIDTH-1:0] wr_pkt_count_rd;
generate if (IS_FWFT == 1 && IS_PKT_FIFO == 1 && C_COMMON_CLOCK == 0) begin // gras_pkt_cnt
// Delay the write packet count in write clock domain to accomodate the binary to gray conversion delay
always @ (posedge wr_rst_fwft_pkt_fifo or posedge WR_CLK) begin
if (wr_rst_fwft_pkt_fifo)
wr_pkt_count_b2g <= 0;
else
wr_pkt_count_b2g <= #`TCQ wr_pkt_count;
end
// Synchronize the delayed write packet count in read domain, and also compensate the gray to binay conversion delay
always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin
if (rst_fwft)
wr_pkt_count_q <= 0;
else
wr_pkt_count_q <= #`TCQ {wr_pkt_count_q[SYNC_STAGE_WIDTH-C_WR_PNTR_WIDTH-1:0],wr_pkt_count_b2g};
end
always @* begin
if (stage1_eop)
rd_pkt_count <= rd_pkt_count_reg + 1;
else
rd_pkt_count <= rd_pkt_count_reg;
end
assign wr_pkt_count_rd = wr_pkt_count_q[SYNC_STAGE_WIDTH-1:SYNC_STAGE_WIDTH-C_WR_PNTR_WIDTH];
always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin
if (rst_fwft)
rd_pkt_count_reg <= 0;
else if (rd_en_fifo_in)
rd_pkt_count_reg <= #`TCQ rd_pkt_count;
end
always @ (posedge rst_fwft or posedge RD_CLK_P0_IN) begin
if (rst_fwft) begin
ram_pkt_empty <= 1'b1;
ram_pkt_empty_d1 <= 1'b1;
end else if (rd_pkt_count != wr_pkt_count_rd) begin
ram_pkt_empty <= #`TCQ 1'b0;
ram_pkt_empty_d1 <= #`TCQ 1'b0;
end else if (ram_pkt_empty_d1 && rd_en_to_fwft_fifo) begin
ram_pkt_empty <= #`TCQ 1'b1;
end else if ((rd_pkt_count == wr_pkt_count_rd) && stage2_reg_en_i) begin
ram_pkt_empty_d1 <= #`TCQ 1'b1;
end
end
// Synchronize the empty in write domain
always @ (posedge wr_rst_fwft_pkt_fifo or posedge WR_CLK) begin
if (wr_rst_fwft_pkt_fifo)
pkt_empty_sync <= 'b1;
else
pkt_empty_sync <= #`TCQ {pkt_empty_sync[C_SYNCHRONIZER_STAGE-2:0], empty_p0_out};
end
end endgenerate //gras_pkt_cnt
generate if (IS_FWFT == 0 || C_FIFO_TYPE == 3) begin : STD_FIFO
//***********************************************
// If NOT First-Word Fall-Through, wire the outputs
// of the internal _ss or _as FIFO directly to the
// output, and do not instantiate the preload0
// module.
//***********************************************
assign RD_CLK_P0_IN = 0;
assign RST_P0_IN = 0;
assign RD_EN_P0_IN = 0;
assign RD_EN_FIFO_IN = rd_en_delayed;
assign DOUT = DOUT_FIFO_OUT;
assign DATA_P0_IN = 0;
assign VALID = VALID_FIFO_OUT;
assign EMPTY = EMPTY_FIFO_OUT;
assign ALMOST_EMPTY = ALMOST_EMPTY_FIFO_OUT;
assign EMPTY_P0_IN = 0;
assign UNDERFLOW = UNDERFLOW_FIFO_OUT;
assign DATA_COUNT = DATA_COUNT_FIFO_OUT;
assign SBITERR = sbiterr_fifo_out;
assign DBITERR = dbiterr_fifo_out;
end endgenerate // STD_FIFO
generate if (IS_FWFT == 1 && C_FIFO_TYPE != 1) begin : NO_PKT_FIFO
assign empty_p0_out = empty_fwft;
assign SBITERR = sbiterr_fwft;
assign DBITERR = dbiterr_fwft;
assign DOUT = dout_fwft;
assign RD_EN_P0_IN = (C_FIFO_TYPE != 1) ? rd_en_delayed : rd_en_to_fwft_fifo;
end endgenerate // NO_PKT_FIFO
//***********************************************
// Connect user flags to internal signals
//***********************************************
//If we are using extra logic for the FWFT data count, then override the
//RD_DATA_COUNT output when we are EMPTY or ALMOST_EMPTY.
//RD_DATA_COUNT is 0 when EMPTY and 1 when ALMOST_EMPTY.
generate
if (C_USE_FWFT_DATA_COUNT==1 && (C_RD_DATA_COUNT_WIDTH>C_RD_PNTR_WIDTH) ) begin : block3
if (C_COMMON_CLOCK == 0) begin : block_ic
assign RD_DATA_COUNT = (EMPTY_P0_OUT_Q | RST_P0_IN) ? 0 : (ALMOSTEMPTY_P0_OUT_Q ? 1 : RD_DATA_COUNT_FIFO_OUT);
end //block_ic
else begin
assign RD_DATA_COUNT = RD_DATA_COUNT_FIFO_OUT;
end
end //block3
endgenerate
//If we are using extra logic for the FWFT data count, then override the
//RD_DATA_COUNT output when we are EMPTY or ALMOST_EMPTY.
//Due to asymmetric ports, RD_DATA_COUNT is 0 when EMPTY or ALMOST_EMPTY.
generate
if (C_USE_FWFT_DATA_COUNT==1 && (C_RD_DATA_COUNT_WIDTH <=C_RD_PNTR_WIDTH) ) begin : block30
if (C_COMMON_CLOCK == 0) begin : block_ic
assign RD_DATA_COUNT = (EMPTY_P0_OUT_Q | RST_P0_IN) ? 0 : (ALMOSTEMPTY_P0_OUT_Q ? 0 : RD_DATA_COUNT_FIFO_OUT);
end
else begin
assign RD_DATA_COUNT = RD_DATA_COUNT_FIFO_OUT;
end
end //block30
endgenerate
//If we are not using extra logic for the FWFT data count,
//then connect RD_DATA_COUNT to the RD_DATA_COUNT from the
//internal FIFO instance
generate
if (C_USE_FWFT_DATA_COUNT==0 ) begin : block31
assign RD_DATA_COUNT = RD_DATA_COUNT_FIFO_OUT;
end
endgenerate
//Always connect WR_DATA_COUNT to the WR_DATA_COUNT from the internal
//FIFO instance
generate
if (C_USE_FWFT_DATA_COUNT==1) begin : block4
assign WR_DATA_COUNT = WR_DATA_COUNT_FIFO_OUT;
end
else begin : block4
assign WR_DATA_COUNT = WR_DATA_COUNT_FIFO_OUT;
end
endgenerate
//Connect other flags to the internal FIFO instance
assign FULL = FULL_FIFO_OUT;
assign ALMOST_FULL = ALMOST_FULL_FIFO_OUT;
assign WR_ACK = WR_ACK_FIFO_OUT;
assign OVERFLOW = OVERFLOW_FIFO_OUT;
assign PROG_FULL = PROG_FULL_FIFO_OUT;
assign PROG_EMPTY = PROG_EMPTY_FIFO_OUT;
/**************************************************************************
* find_log2
* Returns the 'log2' value for the input value for the supported ratios
***************************************************************************/
function integer find_log2;
input integer int_val;
integer i,j;
begin
i = 1;
j = 0;
for (i = 1; i < int_val; i = i*2) begin
j = j + 1;
end
find_log2 = j;
end
endfunction
// if an asynchronous FIFO has been selected, display a message that the FIFO
// will not be cycle-accurate in simulation
initial begin
if (C_IMPLEMENTATION_TYPE == 2) begin
$display("WARNING: Behavioral models for independent clock FIFO configurations do not model synchronization delays. The behavioral models are functionally correct, and will represent the behavior of the configured FIFO. See the FIFO Generator User Guide for more information.");
end else if (C_MEMORY_TYPE == 4) begin
$display("FAILURE : Behavioral models do not support built-in FIFO configurations. Please use post-synthesis or post-implement simulation in Vivado.");
$finish;
end
if (C_WR_PNTR_WIDTH != find_log2(C_WR_DEPTH)) begin
$display("FAILURE : C_WR_PNTR_WIDTH is not log2 of C_WR_DEPTH.");
$finish;
end
if (C_RD_PNTR_WIDTH != find_log2(C_RD_DEPTH)) begin
$display("FAILURE : C_RD_PNTR_WIDTH is not log2 of C_RD_DEPTH.");
$finish;
end
if (C_USE_ECC == 1) begin
if (C_DIN_WIDTH != C_DOUT_WIDTH) begin
$display("FAILURE : C_DIN_WIDTH and C_DOUT_WIDTH must be equal for ECC configuration.");
$finish;
end
if (C_DIN_WIDTH == 1 && C_ERROR_INJECTION_TYPE > 1) begin
$display("FAILURE : C_DIN_WIDTH and C_DOUT_WIDTH must be > 1 for double bit error injection.");
$finish;
end
end
end //initial
/**************************************************************************
* Internal reset logic
**************************************************************************/
assign wr_rst_i = (C_HAS_RST == 1 || C_ENABLE_RST_SYNC == 0) ? wr_rst_reg : 0;
assign rd_rst_i = (C_HAS_RST == 1 || C_ENABLE_RST_SYNC == 0) ? rd_rst_reg : 0;
assign rst_i = C_HAS_RST ? rst_reg : 0;
wire rst_2_sync;
wire clk_2_sync = (C_COMMON_CLOCK == 1) ? CLK : WR_CLK;
generate
if (C_ENABLE_RST_SYNC == 0) begin : gnrst_sync
always @* begin
wr_rst_reg <= wr_rst_delayed;
rd_rst_reg <= rd_rst_delayed;
rst_reg <= 1'b0;
srst_reg <= 1'b0;
end
assign rst_2_sync = wr_rst_delayed;
assign wr_rst_busy = 1'b0;
assign rd_rst_busy = 1'b0;
end else if (C_HAS_RST == 1 && C_COMMON_CLOCK == 0) begin : g7s_ic_rst
assign wr_rst_comb = !wr_rst_asreg_d2 && wr_rst_asreg;
assign rd_rst_comb = !rd_rst_asreg_d2 && rd_rst_asreg;
assign rst_2_sync = rst_delayed;
assign wr_rst_busy = 1'b0;
assign rd_rst_busy = 1'b0;
always @(posedge WR_CLK or posedge rst_delayed) begin
if (rst_delayed == 1'b1) begin
wr_rst_asreg <= #`TCQ 1'b1;
end else begin
if (wr_rst_asreg_d1 == 1'b1) begin
wr_rst_asreg <= #`TCQ 1'b0;
end else begin
wr_rst_asreg <= #`TCQ wr_rst_asreg;
end
end
end
always @(posedge WR_CLK) begin
wr_rst_asreg_d1 <= #`TCQ wr_rst_asreg;
wr_rst_asreg_d2 <= #`TCQ wr_rst_asreg_d1;
end
always @(posedge WR_CLK or posedge wr_rst_comb) begin
if (wr_rst_comb == 1'b1) begin
wr_rst_reg <= #`TCQ 1'b1;
end else begin
wr_rst_reg <= #`TCQ 1'b0;
end
end
always @(posedge RD_CLK or posedge rst_delayed) begin
if (rst_delayed == 1'b1) begin
rd_rst_asreg <= #`TCQ 1'b1;
end else begin
if (rd_rst_asreg_d1 == 1'b1) begin
rd_rst_asreg <= #`TCQ 1'b0;
end else begin
rd_rst_asreg <= #`TCQ rd_rst_asreg;
end
end
end
always @(posedge RD_CLK) begin
rd_rst_asreg_d1 <= #`TCQ rd_rst_asreg;
rd_rst_asreg_d2 <= #`TCQ rd_rst_asreg_d1;
end
always @(posedge RD_CLK or posedge rd_rst_comb) begin
if (rd_rst_comb == 1'b1) begin
rd_rst_reg <= #`TCQ 1'b1;
end else begin
rd_rst_reg <= #`TCQ 1'b0;
end
end
end else if (C_HAS_RST == 1 && C_COMMON_CLOCK == 1) begin : g7s_cc_rst
assign rst_comb = !rst_asreg_d2 && rst_asreg;
assign rst_2_sync = rst_delayed;
assign wr_rst_busy = 1'b0;
assign rd_rst_busy = 1'b0;
always @(posedge CLK or posedge rst_delayed) begin
if (rst_delayed == 1'b1) begin
rst_asreg <= #`TCQ 1'b1;
end else begin
if (rst_asreg_d1 == 1'b1) begin
rst_asreg <= #`TCQ 1'b0;
end else begin
rst_asreg <= #`TCQ rst_asreg;
end
end
end
always @(posedge CLK) begin
rst_asreg_d1 <= #`TCQ rst_asreg;
rst_asreg_d2 <= #`TCQ rst_asreg_d1;
end
always @(posedge CLK or posedge rst_comb) begin
if (rst_comb == 1'b1) begin
rst_reg <= #`TCQ 1'b1;
end else begin
rst_reg <= #`TCQ 1'b0;
end
end
end else if (IS_8SERIES == 1 && C_HAS_SRST == 1 && C_COMMON_CLOCK == 1) begin : g8s_cc_rst
assign wr_rst_busy = (C_MEMORY_TYPE != 4) ? rst_reg : rst_active_i;
assign rd_rst_busy = rst_reg;
assign rst_2_sync = srst_delayed;
always @* rst_full_ff_i <= rst_reg;
always @* rst_full_gen_i <= C_FULL_FLAGS_RST_VAL == 1 ? rst_active_i : 0;
always @(posedge CLK) begin
rst_delayed_d1 <= #`TCQ srst_delayed;
rst_delayed_d2 <= #`TCQ rst_delayed_d1;
if (rst_reg || rst_delayed_d2) begin
rst_active_i <= #`TCQ 1'b1;
end else begin
rst_active_i <= #`TCQ rst_reg;
end
end
always @(posedge CLK) begin
if (~rst_reg && srst_delayed) begin
rst_reg <= #`TCQ 1'b1;
end else if (rst_reg) begin
rst_reg <= #`TCQ 1'b0;
end else begin
rst_reg <= #`TCQ rst_reg;
end
end
end else begin
assign wr_rst_busy = 1'b0;
assign rd_rst_busy = 1'b0;
end
// end g8s_cc_rst
endgenerate
reg rst_d1 = 1'b0;
reg rst_d2 = 1'b0;
reg rst_d3 = 1'b0;
reg rst_d4 = 1'b0;
generate
if ((C_HAS_RST == 1 || C_HAS_SRST == 1 || C_ENABLE_RST_SYNC == 0) && C_FULL_FLAGS_RST_VAL == 1) begin : grstd1
// RST_FULL_GEN replaces the reset falling edge detection used to de-assert
// FULL, ALMOST_FULL & PROG_FULL flags if C_FULL_FLAGS_RST_VAL = 1.
// RST_FULL_FF goes to the reset pin of the final flop of FULL, ALMOST_FULL &
// PROG_FULL
always @ (posedge rst_2_sync or posedge clk_2_sync) begin
if (rst_2_sync) begin
rst_d1 <= 1'b1;
rst_d2 <= 1'b1;
rst_d3 <= 1'b1;
rst_d4 <= 1'b0;
end else begin
if (srst_delayed) begin
rst_d1 <= #`TCQ 1'b1;
rst_d2 <= #`TCQ 1'b1;
rst_d3 <= #`TCQ 1'b1;
rst_d4 <= #`TCQ 1'b0;
end else begin
rst_d1 <= #`TCQ 1'b0;
rst_d2 <= #`TCQ rst_d1;
rst_d3 <= #`TCQ rst_d2;
rst_d4 <= #`TCQ rst_d3;
end
end
end
always @* rst_full_ff_i <= (C_HAS_SRST == 0) ? rst_d2 : 1'b0 ;
always @* rst_full_gen_i <= rst_d4;
end else if ((C_HAS_RST == 1 || C_HAS_SRST == 1 || C_ENABLE_RST_SYNC == 0) && C_FULL_FLAGS_RST_VAL == 0) begin : gnrst_full
always @* rst_full_ff_i <= (C_COMMON_CLOCK == 0) ? wr_rst_i : rst_i;
end
endgenerate // grstd1
endmodule //FIFO_GENERATOR_v12_0_CONV_VER
module fifo_generator_v12_0_sync_stage
#(
parameter C_WIDTH = 10
)
(
input RST,
input CLK,
input [C_WIDTH-1:0] DIN,
output reg [C_WIDTH-1:0] DOUT = 0
);
always @ (posedge RST or posedge CLK) begin
if (RST)
DOUT <= 0;
else
DOUT <= #`TCQ DIN;
end
endmodule // fifo_generator_v12_0_sync_stage
/*******************************************************************************
* Declaration of Independent-Clocks FIFO Module
******************************************************************************/
module fifo_generator_v12_0_bhv_ver_as
/***************************************************************************
* Declare user parameters and their defaults
***************************************************************************/
#(
parameter C_FAMILY = "virtex7",
parameter C_DATA_COUNT_WIDTH = 2,
parameter C_DIN_WIDTH = 8,
parameter C_DOUT_RST_VAL = "",
parameter C_DOUT_WIDTH = 8,
parameter C_FULL_FLAGS_RST_VAL = 1,
parameter C_HAS_ALMOST_EMPTY = 0,
parameter C_HAS_ALMOST_FULL = 0,
parameter C_HAS_DATA_COUNT = 0,
parameter C_HAS_OVERFLOW = 0,
parameter C_HAS_RD_DATA_COUNT = 0,
parameter C_HAS_RST = 0,
parameter C_HAS_UNDERFLOW = 0,
parameter C_HAS_VALID = 0,
parameter C_HAS_WR_ACK = 0,
parameter C_HAS_WR_DATA_COUNT = 0,
parameter C_IMPLEMENTATION_TYPE = 0,
parameter C_MEMORY_TYPE = 1,
parameter C_OVERFLOW_LOW = 0,
parameter C_PRELOAD_LATENCY = 1,
parameter C_PRELOAD_REGS = 0,
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL = 0,
parameter C_PROG_EMPTY_THRESH_NEGATE_VAL = 0,
parameter C_PROG_EMPTY_TYPE = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL = 0,
parameter C_PROG_FULL_THRESH_NEGATE_VAL = 0,
parameter C_PROG_FULL_TYPE = 0,
parameter C_RD_DATA_COUNT_WIDTH = 2,
parameter C_RD_DEPTH = 256,
parameter C_RD_PNTR_WIDTH = 8,
parameter C_UNDERFLOW_LOW = 0,
parameter C_USE_DOUT_RST = 0,
parameter C_USE_EMBEDDED_REG = 0,
parameter C_USE_FWFT_DATA_COUNT = 0,
parameter C_VALID_LOW = 0,
parameter C_WR_ACK_LOW = 0,
parameter C_WR_DATA_COUNT_WIDTH = 2,
parameter C_WR_DEPTH = 256,
parameter C_WR_PNTR_WIDTH = 8,
parameter C_USE_ECC = 0,
parameter C_ENABLE_RST_SYNC = 1,
parameter C_ERROR_INJECTION_TYPE = 0,
parameter C_SYNCHRONIZER_STAGE = 2
)
/***************************************************************************
* Declare Input and Output Ports
***************************************************************************/
(
input [C_DIN_WIDTH-1:0] DIN,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE,
input RD_CLK,
input RD_EN,
input RD_EN_USER,
input RST,
input RST_FULL_GEN,
input RST_FULL_FF,
input WR_RST,
input RD_RST,
input WR_CLK,
input WR_EN,
input INJECTDBITERR,
input INJECTSBITERR,
input USER_EMPTY_FB,
output reg ALMOST_EMPTY = 1'b1,
output reg ALMOST_FULL = C_FULL_FLAGS_RST_VAL,
output [C_DOUT_WIDTH-1:0] DOUT,
output reg EMPTY = 1'b1,
output reg FULL = C_FULL_FLAGS_RST_VAL,
output OVERFLOW,
output PROG_EMPTY,
output PROG_FULL,
output VALID,
output [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT,
output UNDERFLOW,
output WR_ACK,
output [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT,
output SBITERR,
output DBITERR
);
reg [C_RD_PNTR_WIDTH:0] rd_data_count_int = 0;
reg [C_WR_PNTR_WIDTH:0] wr_data_count_int = 0;
reg [C_WR_PNTR_WIDTH:0] wdc_fwft_ext_as = 0;
/***************************************************************************
* Parameters used as constants
**************************************************************************/
localparam IS_8SERIES = (C_FAMILY == "virtexu" || C_FAMILY == "kintexu" || C_FAMILY == "artixu" || C_FAMILY == "virtexum" || C_FAMILY == "zynque") ? 1 : 0;
//When RST is present, set FULL reset value to '1'.
//If core has no RST, make sure FULL powers-on as '0'.
localparam C_DEPTH_RATIO_WR =
(C_WR_DEPTH>C_RD_DEPTH) ? (C_WR_DEPTH/C_RD_DEPTH) : 1;
localparam C_DEPTH_RATIO_RD =
(C_RD_DEPTH>C_WR_DEPTH) ? (C_RD_DEPTH/C_WR_DEPTH) : 1;
localparam C_FIFO_WR_DEPTH = C_WR_DEPTH - 1;
localparam C_FIFO_RD_DEPTH = C_RD_DEPTH - 1;
// C_DEPTH_RATIO_WR | C_DEPTH_RATIO_RD | C_PNTR_WIDTH | EXTRA_WORDS_DC
// -----------------|------------------|-----------------|---------------
// 1 | 8 | C_RD_PNTR_WIDTH | 2
// 1 | 4 | C_RD_PNTR_WIDTH | 2
// 1 | 2 | C_RD_PNTR_WIDTH | 2
// 1 | 1 | C_WR_PNTR_WIDTH | 2
// 2 | 1 | C_WR_PNTR_WIDTH | 4
// 4 | 1 | C_WR_PNTR_WIDTH | 8
// 8 | 1 | C_WR_PNTR_WIDTH | 16
localparam C_PNTR_WIDTH = (C_WR_PNTR_WIDTH>=C_RD_PNTR_WIDTH) ? C_WR_PNTR_WIDTH : C_RD_PNTR_WIDTH;
wire [C_PNTR_WIDTH:0] EXTRA_WORDS_DC = (C_DEPTH_RATIO_WR == 1) ? 2 : (2 * C_DEPTH_RATIO_WR/C_DEPTH_RATIO_RD);
localparam [31:0] reads_per_write = C_DIN_WIDTH/C_DOUT_WIDTH;
localparam [31:0] log2_reads_per_write = log2_val(reads_per_write);
localparam [31:0] writes_per_read = C_DOUT_WIDTH/C_DIN_WIDTH;
localparam [31:0] log2_writes_per_read = log2_val(writes_per_read);
/**************************************************************************
* FIFO Contents Tracking and Data Count Calculations
*************************************************************************/
// Memory which will be used to simulate a FIFO
reg [C_DIN_WIDTH-1:0] memory[C_WR_DEPTH-1:0];
// Local parameters used to determine whether to inject ECC error or not
localparam SYMMETRIC_PORT = (C_DIN_WIDTH == C_DOUT_WIDTH) ? 1 : 0;
localparam ERR_INJECTION = (C_ERROR_INJECTION_TYPE != 0) ? 1 : 0;
localparam ENABLE_ERR_INJECTION = C_USE_ECC && SYMMETRIC_PORT && ERR_INJECTION;
// Array that holds the error injection type (single/double bit error) on
// a specific write operation, which is returned on read to corrupt the
// output data.
reg [1:0] ecc_err[C_WR_DEPTH-1:0];
//The amount of data stored in the FIFO at any time is given
// by num_wr_bits (in the WR_CLK domain) and num_rd_bits (in the RD_CLK
// domain.
//num_wr_bits is calculated by considering the total words in the FIFO,
// and the state of the read pointer (which may not have yet crossed clock
// domains.)
//num_rd_bits is calculated by considering the total words in the FIFO,
// and the state of the write pointer (which may not have yet crossed clock
// domains.)
reg [31:0] num_wr_bits;
reg [31:0] num_rd_bits;
reg [31:0] next_num_wr_bits;
reg [31:0] next_num_rd_bits;
//The write pointer - tracks write operations
// (Works opposite to core: wr_ptr is a DOWN counter)
reg [31:0] wr_ptr;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr = 0; // UP counter: Rolls back to 0 when reaches to max value.
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd1 = 0;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd2 = 0;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd3 = 0;
wire [C_RD_PNTR_WIDTH-1:0] adj_wr_pntr_rd;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd = 0;
wire wr_rst_i = WR_RST;
reg wr_rst_d1 =0;
//The read pointer - tracks read operations
// (rd_ptr Works opposite to core: rd_ptr is a DOWN counter)
reg [31:0] rd_ptr;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr = 0; // UP counter: Rolls back to 0 when reaches to max value.
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr1 = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr2 = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr3 = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr4 = 0;
wire [C_WR_PNTR_WIDTH-1:0] adj_rd_pntr_wr;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr = 0;
wire rd_rst_i = RD_RST;
wire ram_rd_en;
wire empty_int;
wire almost_empty_int;
wire ram_wr_en;
wire full_int;
wire almost_full_int;
reg ram_rd_en_d1 = 1'b0;
// Delayed ram_rd_en is needed only for STD Embedded register option
generate
if (C_PRELOAD_LATENCY == 2) begin : grd_d
always @ (posedge RD_CLK or posedge rd_rst_i) begin
if (rd_rst_i)
ram_rd_en_d1 <= #`TCQ 1'b0;
else
ram_rd_en_d1 <= #`TCQ ram_rd_en;
end
end
endgenerate
// Write pointer adjustment based on pointers width for EMPTY/ALMOST_EMPTY generation
generate
if (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) begin : rdg // Read depth greater than write depth
assign adj_wr_pntr_rd[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr_rd;
assign adj_wr_pntr_rd[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1:0] = 0;
end else begin : rdl // Read depth lesser than or equal to write depth
assign adj_wr_pntr_rd = wr_pntr_rd[C_WR_PNTR_WIDTH-1:C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH];
end
endgenerate
// Generate Empty and Almost Empty
// ram_rd_en used to determine EMPTY should depend on the EMPTY.
assign ram_rd_en = RD_EN & !EMPTY;
assign empty_int = ((adj_wr_pntr_rd == rd_pntr) || (ram_rd_en && (adj_wr_pntr_rd == (rd_pntr+1'h1))));
assign almost_empty_int = ((adj_wr_pntr_rd == (rd_pntr+1'h1)) || (ram_rd_en && (adj_wr_pntr_rd == (rd_pntr+2'h2))));
// Register Empty and Almost Empty
always @ (posedge RD_CLK or posedge rd_rst_i)
begin
if (rd_rst_i) begin
EMPTY <= #`TCQ 1'b1;
ALMOST_EMPTY <= #`TCQ 1'b1;
rd_data_count_int <= #`TCQ {C_RD_PNTR_WIDTH{1'b0}};
end else begin
rd_data_count_int <= #`TCQ {(adj_wr_pntr_rd[C_RD_PNTR_WIDTH-1:0] - rd_pntr[C_RD_PNTR_WIDTH-1:0]), 1'b0};
if (empty_int)
EMPTY <= #`TCQ 1'b1;
else
EMPTY <= #`TCQ 1'b0;
if (!EMPTY) begin
if (almost_empty_int)
ALMOST_EMPTY <= #`TCQ 1'b1;
else
ALMOST_EMPTY <= #`TCQ 1'b0;
end
end // rd_rst_i
end // always
// Read pointer adjustment based on pointers width for EMPTY/ALMOST_EMPTY generation
generate
if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : wdg // Write depth greater than read depth
assign adj_rd_pntr_wr[C_WR_PNTR_WIDTH-1:C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH] = rd_pntr_wr;
assign adj_rd_pntr_wr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1:0] = 0;
end else begin : wdl // Write depth lesser than or equal to read depth
assign adj_rd_pntr_wr = rd_pntr_wr[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH];
end
endgenerate
// Generate FULL and ALMOST_FULL
// ram_wr_en used to determine FULL should depend on the FULL.
assign ram_wr_en = WR_EN & !FULL;
assign full_int = ((adj_rd_pntr_wr == (wr_pntr+1'h1)) || (ram_wr_en && (adj_rd_pntr_wr == (wr_pntr+2'h2))));
assign almost_full_int = ((adj_rd_pntr_wr == (wr_pntr+2'h2)) || (ram_wr_en && (adj_rd_pntr_wr == (wr_pntr+3'h3))));
// Register FULL and ALMOST_FULL Empty
always @ (posedge WR_CLK or posedge RST_FULL_FF)
begin
if (RST_FULL_FF) begin
FULL <= #`TCQ C_FULL_FLAGS_RST_VAL;
ALMOST_FULL <= #`TCQ C_FULL_FLAGS_RST_VAL;
end else begin
if (full_int) begin
FULL <= #`TCQ 1'b1;
end else begin
FULL <= #`TCQ 1'b0;
end
if (RST_FULL_GEN) begin
ALMOST_FULL <= #`TCQ 1'b0;
end else if (!FULL) begin
if (almost_full_int)
ALMOST_FULL <= #`TCQ 1'b1;
else
ALMOST_FULL <= #`TCQ 1'b0;
end
end // wr_rst_i
end // always
always @ (posedge WR_CLK or posedge wr_rst_i)
begin
if (wr_rst_i) begin
wr_data_count_int <= #`TCQ {C_WR_DATA_COUNT_WIDTH{1'b0}};
end else begin
wr_data_count_int <= #`TCQ {(wr_pntr[C_WR_PNTR_WIDTH-1:0] - adj_rd_pntr_wr[C_WR_PNTR_WIDTH-1:0]), 1'b0};
end // wr_rst_i
end // always
// Determine which stage in FWFT registers are valid
reg stage1_valid = 0;
reg stage2_valid = 0;
generate
if (C_PRELOAD_LATENCY == 0) begin : grd_fwft_proc
always @ (posedge RD_CLK or posedge rd_rst_i) begin
if (rd_rst_i) begin
stage1_valid <= #`TCQ 0;
stage2_valid <= #`TCQ 0;
end else begin
if (!stage1_valid && !stage2_valid) begin
if (!EMPTY)
stage1_valid <= #`TCQ 1'b1;
else
stage1_valid <= #`TCQ 1'b0;
end else if (stage1_valid && !stage2_valid) begin
if (EMPTY) begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b1;
end else begin
stage1_valid <= #`TCQ 1'b1;
stage2_valid <= #`TCQ 1'b1;
end
end else if (!stage1_valid && stage2_valid) begin
if (EMPTY && RD_EN_USER) begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b0;
end else if (!EMPTY && RD_EN_USER) begin
stage1_valid <= #`TCQ 1'b1;
stage2_valid <= #`TCQ 1'b0;
end else if (!EMPTY && !RD_EN_USER) begin
stage1_valid <= #`TCQ 1'b1;
stage2_valid <= #`TCQ 1'b1;
end else begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b1;
end
end else if (stage1_valid && stage2_valid) begin
if (EMPTY && RD_EN_USER) begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b1;
end else begin
stage1_valid <= #`TCQ 1'b1;
stage2_valid <= #`TCQ 1'b1;
end
end else begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b0;
end
end // rd_rst_i
end // always
end
endgenerate
//Pointers passed into opposite clock domain
reg [31:0] wr_ptr_rdclk;
reg [31:0] wr_ptr_rdclk_next;
reg [31:0] rd_ptr_wrclk;
reg [31:0] rd_ptr_wrclk_next;
//Amount of data stored in the FIFO scaled to the narrowest (deepest) port
// (Do not include data in FWFT stages)
//Used to calculate PROG_EMPTY.
wire [31:0] num_read_words_pe =
num_rd_bits/(C_DOUT_WIDTH/C_DEPTH_RATIO_WR);
//Amount of data stored in the FIFO scaled to the narrowest (deepest) port
// (Do not include data in FWFT stages)
//Used to calculate PROG_FULL.
wire [31:0] num_write_words_pf =
num_wr_bits/(C_DIN_WIDTH/C_DEPTH_RATIO_RD);
/**************************
* Read Data Count
*************************/
reg [31:0] num_read_words_dc;
reg [C_RD_DATA_COUNT_WIDTH-1:0] num_read_words_sized_i;
always @(num_rd_bits) begin
if (C_USE_FWFT_DATA_COUNT) begin
//If using extra logic for FWFT Data Counts,
// then scale FIFO contents to read domain,
// and add two read words for FWFT stages
//This value is only a temporary value and not used in the code.
num_read_words_dc = (num_rd_bits/C_DOUT_WIDTH+2);
//Trim the read words for use with RD_DATA_COUNT
num_read_words_sized_i =
num_read_words_dc[C_RD_PNTR_WIDTH : C_RD_PNTR_WIDTH-C_RD_DATA_COUNT_WIDTH+1];
end else begin
//If not using extra logic for FWFT Data Counts,
// then scale FIFO contents to read domain.
//This value is only a temporary value and not used in the code.
num_read_words_dc = num_rd_bits/C_DOUT_WIDTH;
//Trim the read words for use with RD_DATA_COUNT
num_read_words_sized_i =
num_read_words_dc[C_RD_PNTR_WIDTH-1 : C_RD_PNTR_WIDTH-C_RD_DATA_COUNT_WIDTH];
end //if (C_USE_FWFT_DATA_COUNT)
end //always
/**************************
* Write Data Count
*************************/
reg [31:0] num_write_words_dc;
reg [C_WR_DATA_COUNT_WIDTH-1:0] num_write_words_sized_i;
always @(num_wr_bits) begin
if (C_USE_FWFT_DATA_COUNT) begin
//Calculate the Data Count value for the number of write words,
// when using First-Word Fall-Through with extra logic for Data
// Counts. This takes into consideration the number of words that
// are expected to be stored in the FWFT register stages (it always
// assumes they are filled).
//This value is scaled to the Write Domain.
//The expression (((A-1)/B))+1 divides A/B, but takes the
// ceiling of the result.
//When num_wr_bits==0, set the result manually to prevent
// division errors.
//EXTRA_WORDS_DC is the number of words added to write_words
// due to FWFT.
//This value is only a temporary value and not used in the code.
num_write_words_dc = (num_wr_bits==0) ? EXTRA_WORDS_DC : (((num_wr_bits-1)/C_DIN_WIDTH)+1) + EXTRA_WORDS_DC ;
//Trim the write words for use with WR_DATA_COUNT
num_write_words_sized_i =
num_write_words_dc[C_WR_PNTR_WIDTH : C_WR_PNTR_WIDTH-C_WR_DATA_COUNT_WIDTH+1];
end else begin
//Calculate the Data Count value for the number of write words, when NOT
// using First-Word Fall-Through with extra logic for Data Counts. This
// calculates only the number of words in the internal FIFO.
//The expression (((A-1)/B))+1 divides A/B, but takes the
// ceiling of the result.
//This value is scaled to the Write Domain.
//When num_wr_bits==0, set the result manually to prevent
// division errors.
//This value is only a temporary value and not used in the code.
num_write_words_dc = (num_wr_bits==0) ? 0 : ((num_wr_bits-1)/C_DIN_WIDTH)+1;
//Trim the read words for use with RD_DATA_COUNT
num_write_words_sized_i =
num_write_words_dc[C_WR_PNTR_WIDTH-1 : C_WR_PNTR_WIDTH-C_WR_DATA_COUNT_WIDTH];
end //if (C_USE_FWFT_DATA_COUNT)
end //always
/***************************************************************************
* Internal registers and wires
**************************************************************************/
//Temporary signals used for calculating the model's outputs. These
//are only used in the assign statements immediately following wire,
//parameter, and function declarations.
wire [C_DOUT_WIDTH-1:0] ideal_dout_out;
wire valid_i;
wire valid_out;
wire underflow_i;
//Ideal FIFO signals. These are the raw output of the behavioral model,
//which behaves like an ideal FIFO.
reg [1:0] err_type = 0;
reg [1:0] err_type_d1 = 0;
reg [C_DOUT_WIDTH-1:0] ideal_dout = 0;
reg [C_DOUT_WIDTH-1:0] ideal_dout_d1 = 0;
reg ideal_wr_ack = 0;
reg ideal_valid = 0;
reg ideal_overflow = C_OVERFLOW_LOW;
reg ideal_underflow = C_UNDERFLOW_LOW;
reg ideal_prog_full = 0;
reg ideal_prog_empty = 1;
reg [C_WR_DATA_COUNT_WIDTH-1 : 0] ideal_wr_count = 0;
reg [C_RD_DATA_COUNT_WIDTH-1 : 0] ideal_rd_count = 0;
//Assorted reg values for delayed versions of signals
reg valid_d1 = 0;
//user specified value for reseting the size of the fifo
reg [C_DOUT_WIDTH-1:0] dout_reset_val = 0;
//temporary registers for WR_RESPONSE_LATENCY feature
integer tmp_wr_listsize;
integer tmp_rd_listsize;
//Signal for registered version of prog full and empty
//Threshold values for Programmable Flags
integer prog_empty_actual_thresh_assert;
integer prog_empty_actual_thresh_negate;
integer prog_full_actual_thresh_assert;
integer prog_full_actual_thresh_negate;
/****************************************************************************
* Function Declarations
***************************************************************************/
/**************************************************************************
* write_fifo
* This task writes a word to the FIFO memory and updates the
* write pointer.
* FIFO size is relative to write domain.
***************************************************************************/
task write_fifo;
begin
memory[wr_ptr] <= DIN;
wr_pntr <= #`TCQ wr_pntr + 1;
// Store the type of error injection (double/single) on write
case (C_ERROR_INJECTION_TYPE)
3: ecc_err[wr_ptr] <= {INJECTDBITERR,INJECTSBITERR};
2: ecc_err[wr_ptr] <= {INJECTDBITERR,1'b0};
1: ecc_err[wr_ptr] <= {1'b0,INJECTSBITERR};
default: ecc_err[wr_ptr] <= 0;
endcase
// (Works opposite to core: wr_ptr is a DOWN counter)
if (wr_ptr == 0) begin
wr_ptr <= C_WR_DEPTH - 1;
end else begin
wr_ptr <= wr_ptr - 1;
end
end
endtask // write_fifo
/**************************************************************************
* read_fifo
* This task reads a word from the FIFO memory and updates the read
* pointer. It's output is the ideal_dout bus.
* FIFO size is relative to write domain.
***************************************************************************/
task read_fifo;
integer i;
reg [C_DOUT_WIDTH-1:0] tmp_dout;
reg [C_DIN_WIDTH-1:0] memory_read;
reg [31:0] tmp_rd_ptr;
reg [31:0] rd_ptr_high;
reg [31:0] rd_ptr_low;
reg [1:0] tmp_ecc_err;
begin
rd_pntr <= #`TCQ rd_pntr + 1;
// output is wider than input
if (reads_per_write == 0) begin
tmp_dout = 0;
tmp_rd_ptr = (rd_ptr << log2_writes_per_read)+(writes_per_read-1);
for (i = writes_per_read - 1; i >= 0; i = i - 1) begin
tmp_dout = tmp_dout << C_DIN_WIDTH;
tmp_dout = tmp_dout | memory[tmp_rd_ptr];
// (Works opposite to core: rd_ptr is a DOWN counter)
if (tmp_rd_ptr == 0) begin
tmp_rd_ptr = C_WR_DEPTH - 1;
end else begin
tmp_rd_ptr = tmp_rd_ptr - 1;
end
end
// output is symmetric
end else if (reads_per_write == 1) begin
tmp_dout = memory[rd_ptr][C_DIN_WIDTH-1:0];
// Retreive the error injection type. Based on the error injection type
// corrupt the output data.
tmp_ecc_err = ecc_err[rd_ptr];
if (ENABLE_ERR_INJECTION && C_DIN_WIDTH == C_DOUT_WIDTH) begin
if (tmp_ecc_err[1]) begin // Corrupt the output data only for double bit error
if (C_DOUT_WIDTH == 1) begin
$display("FAILURE : Data width must be >= 2 for double bit error injection.");
$finish;
end else if (C_DOUT_WIDTH == 2)
tmp_dout = {~tmp_dout[C_DOUT_WIDTH-1],~tmp_dout[C_DOUT_WIDTH-2]};
else
tmp_dout = {~tmp_dout[C_DOUT_WIDTH-1],~tmp_dout[C_DOUT_WIDTH-2],(tmp_dout << 2)};
end else begin
tmp_dout = tmp_dout[C_DOUT_WIDTH-1:0];
end
err_type <= {tmp_ecc_err[1], tmp_ecc_err[0] & !tmp_ecc_err[1]};
end else begin
err_type <= 0;
end
// input is wider than output
end else begin
rd_ptr_high = rd_ptr >> log2_reads_per_write;
rd_ptr_low = rd_ptr & (reads_per_write - 1);
memory_read = memory[rd_ptr_high];
tmp_dout = memory_read >> (rd_ptr_low*C_DOUT_WIDTH);
end
ideal_dout <= tmp_dout;
// (Works opposite to core: rd_ptr is a DOWN counter)
if (rd_ptr == 0) begin
rd_ptr <= C_RD_DEPTH - 1;
end else begin
rd_ptr <= rd_ptr - 1;
end
end
endtask
/**************************************************************************
* log2_val
* Returns the 'log2' value for the input value for the supported ratios
***************************************************************************/
function [31:0] log2_val;
input [31:0] binary_val;
begin
if (binary_val == 8) begin
log2_val = 3;
end else if (binary_val == 4) begin
log2_val = 2;
end else begin
log2_val = 1;
end
end
endfunction
/***********************************************************************
* hexstr_conv
* Converts a string of type hex to a binary value (for C_DOUT_RST_VAL)
***********************************************************************/
function [C_DOUT_WIDTH-1:0] hexstr_conv;
input [(C_DOUT_WIDTH*8)-1:0] def_data;
integer index,i,j;
reg [3:0] bin;
begin
index = 0;
hexstr_conv = 'b0;
for( i=C_DOUT_WIDTH-1; i>=0; i=i-1 )
begin
case (def_data[7:0])
8'b00000000 :
begin
bin = 4'b0000;
i = -1;
end
8'b00110000 : bin = 4'b0000;
8'b00110001 : bin = 4'b0001;
8'b00110010 : bin = 4'b0010;
8'b00110011 : bin = 4'b0011;
8'b00110100 : bin = 4'b0100;
8'b00110101 : bin = 4'b0101;
8'b00110110 : bin = 4'b0110;
8'b00110111 : bin = 4'b0111;
8'b00111000 : bin = 4'b1000;
8'b00111001 : bin = 4'b1001;
8'b01000001 : bin = 4'b1010;
8'b01000010 : bin = 4'b1011;
8'b01000011 : bin = 4'b1100;
8'b01000100 : bin = 4'b1101;
8'b01000101 : bin = 4'b1110;
8'b01000110 : bin = 4'b1111;
8'b01100001 : bin = 4'b1010;
8'b01100010 : bin = 4'b1011;
8'b01100011 : bin = 4'b1100;
8'b01100100 : bin = 4'b1101;
8'b01100101 : bin = 4'b1110;
8'b01100110 : bin = 4'b1111;
default :
begin
bin = 4'bx;
end
endcase
for( j=0; j<4; j=j+1)
begin
if ((index*4)+j < C_DOUT_WIDTH)
begin
hexstr_conv[(index*4)+j] = bin[j];
end
end
index = index + 1;
def_data = def_data >> 8;
end
end
endfunction
/*************************************************************************
* Initialize Signals for clean power-on simulation
*************************************************************************/
initial begin
num_wr_bits = 0;
num_rd_bits = 0;
next_num_wr_bits = 0;
next_num_rd_bits = 0;
rd_ptr = C_RD_DEPTH - 1;
wr_ptr = C_WR_DEPTH - 1;
wr_pntr = 0;
rd_pntr = 0;
rd_ptr_wrclk = rd_ptr;
wr_ptr_rdclk = wr_ptr;
dout_reset_val = hexstr_conv(C_DOUT_RST_VAL);
ideal_dout = dout_reset_val;
err_type = 0;
ideal_dout_d1 = dout_reset_val;
ideal_wr_ack = 1'b0;
ideal_valid = 1'b0;
valid_d1 = 1'b0;
ideal_overflow = C_OVERFLOW_LOW;
ideal_underflow = C_UNDERFLOW_LOW;
ideal_wr_count = 0;
ideal_rd_count = 0;
ideal_prog_full = 1'b0;
ideal_prog_empty = 1'b1;
end
/*************************************************************************
* Connect the module inputs and outputs to the internal signals of the
* behavioral model.
*************************************************************************/
//Inputs
/*
wire [C_DIN_WIDTH-1:0] DIN;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE;
wire RD_CLK;
wire RD_EN;
wire RST;
wire WR_CLK;
wire WR_EN;
*/
//***************************************************************************
// Dout may change behavior based on latency
//***************************************************************************
assign ideal_dout_out[C_DOUT_WIDTH-1:0] = (C_PRELOAD_LATENCY==2 &&
(C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1))?
ideal_dout_d1: ideal_dout;
assign DOUT[C_DOUT_WIDTH-1:0] = ideal_dout_out;
//***************************************************************************
// Assign SBITERR and DBITERR based on latency
//***************************************************************************
assign SBITERR = (C_ERROR_INJECTION_TYPE == 1 || C_ERROR_INJECTION_TYPE == 3) &&
(C_PRELOAD_LATENCY == 2 &&
(C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1)) ?
err_type_d1[0]: err_type[0];
assign DBITERR = (C_ERROR_INJECTION_TYPE == 2 || C_ERROR_INJECTION_TYPE == 3) &&
(C_PRELOAD_LATENCY==2 && (C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1)) ?
err_type_d1[1]: err_type[1];
//***************************************************************************
// Overflow may be active-low
//***************************************************************************
generate
if (C_HAS_OVERFLOW==1) begin : blockOF1
assign OVERFLOW = ideal_overflow ? !C_OVERFLOW_LOW : C_OVERFLOW_LOW;
end
endgenerate
assign PROG_EMPTY = ideal_prog_empty;
assign PROG_FULL = ideal_prog_full;
//***************************************************************************
// Valid may change behavior based on latency or active-low
//***************************************************************************
generate
if (C_HAS_VALID==1) begin : blockVL1
assign valid_i = (C_PRELOAD_LATENCY==0) ? (RD_EN & ~EMPTY) : ideal_valid;
assign valid_out = (C_PRELOAD_LATENCY==2 &&
(C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1))?
valid_d1: valid_i;
assign VALID = valid_out ? !C_VALID_LOW : C_VALID_LOW;
end
endgenerate
//***************************************************************************
// Underflow may change behavior based on latency or active-low
//***************************************************************************
generate
if (C_HAS_UNDERFLOW==1) begin : blockUF1
assign underflow_i = (C_PRELOAD_LATENCY==0) ? (RD_EN & EMPTY) : ideal_underflow;
assign UNDERFLOW = underflow_i ? !C_UNDERFLOW_LOW : C_UNDERFLOW_LOW;
end
endgenerate
//***************************************************************************
// Write acknowledge may be active low
//***************************************************************************
generate
if (C_HAS_WR_ACK==1) begin : blockWK1
assign WR_ACK = ideal_wr_ack ? !C_WR_ACK_LOW : C_WR_ACK_LOW;
end
endgenerate
//***************************************************************************
// Generate RD_DATA_COUNT if Use Extra Logic option is selected
//***************************************************************************
generate
if (C_HAS_WR_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT == 1) begin : wdc_fwft_ext
reg [C_PNTR_WIDTH-1:0] adjusted_wr_pntr = 0;
reg [C_PNTR_WIDTH-1:0] adjusted_rd_pntr = 0;
wire [C_PNTR_WIDTH-1:0] diff_wr_rd_tmp;
wire [C_PNTR_WIDTH:0] diff_wr_rd;
reg [C_PNTR_WIDTH:0] wr_data_count_i = 0;
always @* begin
if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin
adjusted_wr_pntr = wr_pntr;
adjusted_rd_pntr = 0;
adjusted_rd_pntr[C_PNTR_WIDTH-1:C_PNTR_WIDTH-C_RD_PNTR_WIDTH] = rd_pntr_wr;
end else if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin
adjusted_rd_pntr = rd_pntr_wr;
adjusted_wr_pntr = 0;
adjusted_wr_pntr[C_PNTR_WIDTH-1:C_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr;
end else begin
adjusted_wr_pntr = wr_pntr;
adjusted_rd_pntr = rd_pntr_wr;
end
end // always @*
assign diff_wr_rd_tmp = adjusted_wr_pntr - adjusted_rd_pntr;
assign diff_wr_rd = {1'b0,diff_wr_rd_tmp};
always @ (posedge wr_rst_i or posedge WR_CLK)
begin
if (wr_rst_i)
wr_data_count_i <= #`TCQ 0;
else
wr_data_count_i <= #`TCQ diff_wr_rd + EXTRA_WORDS_DC;
end // always @ (posedge WR_CLK or posedge WR_CLK)
always @* begin
if (C_WR_PNTR_WIDTH >= C_RD_PNTR_WIDTH)
wdc_fwft_ext_as = wr_data_count_i[C_PNTR_WIDTH:0];
else
wdc_fwft_ext_as = wr_data_count_i[C_PNTR_WIDTH:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH];
end // always @*
end // wdc_fwft_ext
endgenerate
//***************************************************************************
// Generate RD_DATA_COUNT if Use Extra Logic option is selected
//***************************************************************************
reg [C_RD_PNTR_WIDTH:0] rdc_fwft_ext_as = 0;
generate
if (C_HAS_RD_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT == 1) begin : rdc_fwft_ext
reg [C_RD_PNTR_WIDTH-1:0] adjusted_wr_pntr_rd = 0;
wire [C_RD_PNTR_WIDTH-1:0] diff_rd_wr_tmp;
wire [C_RD_PNTR_WIDTH:0] diff_rd_wr;
always @* begin
if (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) begin
adjusted_wr_pntr_rd = 0;
adjusted_wr_pntr_rd[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr_rd;
end else begin
adjusted_wr_pntr_rd = wr_pntr_rd[C_WR_PNTR_WIDTH-1:C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH];
end
end // always @*
assign diff_rd_wr_tmp = adjusted_wr_pntr_rd - rd_pntr;
assign diff_rd_wr = {1'b0,diff_rd_wr_tmp};
always @ (posedge rd_rst_i or posedge RD_CLK)
begin
if (rd_rst_i) begin
rdc_fwft_ext_as <= #`TCQ 0;
end else begin
if (!stage2_valid)
rdc_fwft_ext_as <= #`TCQ 0;
else if (!stage1_valid && stage2_valid)
rdc_fwft_ext_as <= #`TCQ 1;
else
rdc_fwft_ext_as <= #`TCQ diff_rd_wr + 2'h2;
end
end // always @ (posedge WR_CLK or posedge WR_CLK)
end // rdc_fwft_ext
endgenerate
//***************************************************************************
// Assign the read data count value only if it is selected,
// otherwise output zeros.
//***************************************************************************
generate
if (C_HAS_RD_DATA_COUNT == 1) begin : grdc
assign RD_DATA_COUNT[C_RD_DATA_COUNT_WIDTH-1:0] = C_USE_FWFT_DATA_COUNT ?
rdc_fwft_ext_as[C_RD_PNTR_WIDTH:C_RD_PNTR_WIDTH+1-C_RD_DATA_COUNT_WIDTH] :
rd_data_count_int[C_RD_PNTR_WIDTH:C_RD_PNTR_WIDTH+1-C_RD_DATA_COUNT_WIDTH];
end
endgenerate
generate
if (C_HAS_RD_DATA_COUNT == 0) begin : gnrdc
assign RD_DATA_COUNT[C_RD_DATA_COUNT_WIDTH-1:0] = {C_RD_DATA_COUNT_WIDTH{1'b0}};
end
endgenerate
//***************************************************************************
// Assign the write data count value only if it is selected,
// otherwise output zeros
//***************************************************************************
generate
if (C_HAS_WR_DATA_COUNT == 1) begin : gwdc
assign WR_DATA_COUNT[C_WR_DATA_COUNT_WIDTH-1:0] = (C_USE_FWFT_DATA_COUNT == 1) ?
wdc_fwft_ext_as[C_WR_PNTR_WIDTH:C_WR_PNTR_WIDTH+1-C_WR_DATA_COUNT_WIDTH] :
wr_data_count_int[C_WR_PNTR_WIDTH:C_WR_PNTR_WIDTH+1-C_WR_DATA_COUNT_WIDTH];
end
endgenerate
generate
if (C_HAS_WR_DATA_COUNT == 0) begin : gnwdc
assign WR_DATA_COUNT[C_WR_DATA_COUNT_WIDTH-1:0] = {C_WR_DATA_COUNT_WIDTH{1'b0}};
end
endgenerate
/**************************************************************************
* Assorted registers for delayed versions of signals
**************************************************************************/
//Capture delayed version of valid
generate
if (C_HAS_VALID==1) begin : blockVL2
always @(posedge RD_CLK or posedge rd_rst_i) begin
if (rd_rst_i == 1'b1) begin
valid_d1 <= #`TCQ 1'b0;
end else begin
valid_d1 <= #`TCQ valid_i;
end
end
end
endgenerate
//Capture delayed version of dout
always @(posedge RD_CLK or posedge rd_rst_i) begin
if (rd_rst_i == 1'b1) begin
// Reset err_type only if ECC is not selected
if (C_USE_ECC == 0)
err_type_d1 <= #`TCQ 0;
end else if (ram_rd_en_d1) begin
ideal_dout_d1 <= #`TCQ ideal_dout;
err_type_d1 <= #`TCQ err_type;
end
end
/**************************************************************************
* Overflow and Underflow Flag calculation
* (handled separately because they don't support rst)
**************************************************************************/
generate
if (C_HAS_OVERFLOW == 1 && IS_8SERIES == 0) begin : g7s_ovflw
always @(posedge WR_CLK) begin
ideal_overflow <= #`TCQ WR_EN & FULL;
end
end else if (C_HAS_OVERFLOW == 1 && IS_8SERIES == 1) begin : g8s_ovflw
always @(posedge WR_CLK) begin
//ideal_overflow <= #`TCQ WR_EN & (FULL | wr_rst_i);
ideal_overflow <= #`TCQ WR_EN & (FULL );
end
end
endgenerate
generate
if (C_HAS_UNDERFLOW == 1 && IS_8SERIES == 0) begin : g7s_unflw
always @(posedge RD_CLK) begin
ideal_underflow <= #`TCQ EMPTY & RD_EN;
end
end else if (C_HAS_UNDERFLOW == 1 && IS_8SERIES == 1) begin : g8s_unflw
always @(posedge RD_CLK) begin
ideal_underflow <= #`TCQ (EMPTY) & RD_EN;
//ideal_underflow <= #`TCQ (rd_rst_i | EMPTY) & RD_EN;
end
end
endgenerate
/**************************************************************************
* Write/Read Pointer Synchronization
**************************************************************************/
localparam NO_OF_SYNC_STAGE_INC_G2B = C_SYNCHRONIZER_STAGE + 1;
wire [C_WR_PNTR_WIDTH-1:0] wr_pntr_sync_stgs [0:NO_OF_SYNC_STAGE_INC_G2B];
wire [C_RD_PNTR_WIDTH-1:0] rd_pntr_sync_stgs [0:NO_OF_SYNC_STAGE_INC_G2B];
genvar gss;
generate for (gss = 1; gss <= NO_OF_SYNC_STAGE_INC_G2B; gss = gss + 1) begin : Sync_stage_inst
fifo_generator_v12_0_sync_stage
#(
.C_WIDTH (C_WR_PNTR_WIDTH)
)
rd_stg_inst
(
.RST (rd_rst_i),
.CLK (RD_CLK),
.DIN (wr_pntr_sync_stgs[gss-1]),
.DOUT (wr_pntr_sync_stgs[gss])
);
fifo_generator_v12_0_sync_stage
#(
.C_WIDTH (C_RD_PNTR_WIDTH)
)
wr_stg_inst
(
.RST (wr_rst_i),
.CLK (WR_CLK),
.DIN (rd_pntr_sync_stgs[gss-1]),
.DOUT (rd_pntr_sync_stgs[gss])
);
end endgenerate // Sync_stage_inst
assign wr_pntr_sync_stgs[0] = wr_pntr_rd1;
assign rd_pntr_sync_stgs[0] = rd_pntr_wr1;
always@* begin
wr_pntr_rd <= wr_pntr_sync_stgs[NO_OF_SYNC_STAGE_INC_G2B];
rd_pntr_wr <= rd_pntr_sync_stgs[NO_OF_SYNC_STAGE_INC_G2B];
end
/**************************************************************************
* Write Domain Logic
**************************************************************************/
reg [C_WR_PNTR_WIDTH-1:0] diff_pntr = 0;
always @(posedge WR_CLK or posedge wr_rst_i) begin : gen_fifo_w
/****** Reset fifo (case 1)***************************************/
if (wr_rst_i == 1'b1) begin
num_wr_bits <= #`TCQ 0;
next_num_wr_bits = #`TCQ 0;
wr_ptr <= #`TCQ C_WR_DEPTH - 1;
rd_ptr_wrclk <= #`TCQ C_RD_DEPTH - 1;
ideal_wr_ack <= #`TCQ 0;
ideal_wr_count <= #`TCQ 0;
tmp_wr_listsize = #`TCQ 0;
rd_ptr_wrclk_next <= #`TCQ 0;
wr_pntr <= #`TCQ 0;
wr_pntr_rd1 <= #`TCQ 0;
end else begin //wr_rst_i==0
wr_pntr_rd1 <= #`TCQ wr_pntr;
//Determine the current number of words in the FIFO
tmp_wr_listsize = (C_DEPTH_RATIO_RD > 1) ? num_wr_bits/C_DOUT_WIDTH :
num_wr_bits/C_DIN_WIDTH;
rd_ptr_wrclk_next = rd_ptr;
if (rd_ptr_wrclk < rd_ptr_wrclk_next) begin
next_num_wr_bits = num_wr_bits -
C_DOUT_WIDTH*(rd_ptr_wrclk + C_RD_DEPTH
- rd_ptr_wrclk_next);
end else begin
next_num_wr_bits = num_wr_bits -
C_DOUT_WIDTH*(rd_ptr_wrclk - rd_ptr_wrclk_next);
end
//If this is a write, handle the write by adding the value
// to the linked list, and updating all outputs appropriately
if (WR_EN == 1'b1) begin
if (FULL == 1'b1) begin
//If the FIFO is full, do NOT perform the write,
// update flags accordingly
if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD
>= C_FIFO_WR_DEPTH) begin
//write unsuccessful - do not change contents
//Do not acknowledge the write
ideal_wr_ack <= #`TCQ 0;
//Reminder that FIFO is still full
ideal_wr_count <= #`TCQ num_write_words_sized_i;
//If the FIFO is one from full, but reporting full
end else
if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD ==
C_FIFO_WR_DEPTH-1) begin
//No change to FIFO
//Write not successful
ideal_wr_ack <= #`TCQ 0;
//With DEPTH-1 words in the FIFO, it is almost_full
ideal_wr_count <= #`TCQ num_write_words_sized_i;
//If the FIFO is completely empty, but it is
// reporting FULL for some reason (like reset)
end else
if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD <=
C_FIFO_WR_DEPTH-2) begin
//No change to FIFO
//Write not successful
ideal_wr_ack <= #`TCQ 0;
//FIFO is really not close to full, so change flag status.
ideal_wr_count <= #`TCQ num_write_words_sized_i;
end //(tmp_wr_listsize == 0)
end else begin
//If the FIFO is full, do NOT perform the write,
// update flags accordingly
if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD >=
C_FIFO_WR_DEPTH) begin
//write unsuccessful - do not change contents
//Do not acknowledge the write
ideal_wr_ack <= #`TCQ 0;
//Reminder that FIFO is still full
ideal_wr_count <= #`TCQ num_write_words_sized_i;
//If the FIFO is one from full
end else
if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD ==
C_FIFO_WR_DEPTH-1) begin
//Add value on DIN port to FIFO
write_fifo;
next_num_wr_bits = next_num_wr_bits + C_DIN_WIDTH;
//Write successful, so issue acknowledge
// and no error
ideal_wr_ack <= #`TCQ 1;
//This write is CAUSING the FIFO to go full
ideal_wr_count <= #`TCQ num_write_words_sized_i;
//If the FIFO is 2 from full
end else
if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD ==
C_FIFO_WR_DEPTH-2) begin
//Add value on DIN port to FIFO
write_fifo;
next_num_wr_bits = next_num_wr_bits + C_DIN_WIDTH;
//Write successful, so issue acknowledge
// and no error
ideal_wr_ack <= #`TCQ 1;
//Still 2 from full
ideal_wr_count <= #`TCQ num_write_words_sized_i;
//If the FIFO is not close to being full
end else
if ((tmp_wr_listsize + C_DEPTH_RATIO_RD - 1)/C_DEPTH_RATIO_RD <
C_FIFO_WR_DEPTH-2) begin
//Add value on DIN port to FIFO
write_fifo;
next_num_wr_bits = next_num_wr_bits + C_DIN_WIDTH;
//Write successful, so issue acknowledge
// and no error
ideal_wr_ack <= #`TCQ 1;
//Not even close to full.
ideal_wr_count <= num_write_words_sized_i;
end
end
end else begin //(WR_EN == 1'b1)
//If user did not attempt a write, then do not
// give ack or err
ideal_wr_ack <= #`TCQ 0;
ideal_wr_count <= #`TCQ num_write_words_sized_i;
end
num_wr_bits <= #`TCQ next_num_wr_bits;
rd_ptr_wrclk <= #`TCQ rd_ptr;
end //wr_rst_i==0
end // gen_fifo_w
/***************************************************************************
* Programmable FULL flags
***************************************************************************/
wire [C_WR_PNTR_WIDTH-1:0] pf_thr_assert_val;
wire [C_WR_PNTR_WIDTH-1:0] pf_thr_negate_val;
generate if (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) begin : FWFT
assign pf_thr_assert_val = C_PROG_FULL_THRESH_ASSERT_VAL - EXTRA_WORDS_DC;
assign pf_thr_negate_val = C_PROG_FULL_THRESH_NEGATE_VAL - EXTRA_WORDS_DC;
end else begin // STD
assign pf_thr_assert_val = C_PROG_FULL_THRESH_ASSERT_VAL;
assign pf_thr_negate_val = C_PROG_FULL_THRESH_NEGATE_VAL;
end endgenerate
always @(posedge WR_CLK or posedge wr_rst_i) begin
if (wr_rst_i == 1'b1) begin
diff_pntr <= 0;
end else begin
if (ram_wr_en)
diff_pntr <= #`TCQ (wr_pntr - adj_rd_pntr_wr + 2'h1);
else if (!ram_wr_en)
diff_pntr <= #`TCQ (wr_pntr - adj_rd_pntr_wr);
end
end
always @(posedge WR_CLK or posedge RST_FULL_FF) begin : gen_pf
if (RST_FULL_FF == 1'b1) begin
ideal_prog_full <= #`TCQ C_FULL_FLAGS_RST_VAL;
end else begin
if (RST_FULL_GEN)
ideal_prog_full <= #`TCQ 0;
//Single Programmable Full Constant Threshold
else if (C_PROG_FULL_TYPE == 1) begin
if (FULL == 0) begin
if (diff_pntr >= pf_thr_assert_val)
ideal_prog_full <= #`TCQ 1;
else
ideal_prog_full <= #`TCQ 0;
end else
ideal_prog_full <= #`TCQ ideal_prog_full;
//Two Programmable Full Constant Thresholds
end else if (C_PROG_FULL_TYPE == 2) begin
if (FULL == 0) begin
if (diff_pntr >= pf_thr_assert_val)
ideal_prog_full <= #`TCQ 1;
else if (diff_pntr < pf_thr_negate_val)
ideal_prog_full <= #`TCQ 0;
else
ideal_prog_full <= #`TCQ ideal_prog_full;
end else
ideal_prog_full <= #`TCQ ideal_prog_full;
//Single Programmable Full Threshold Input
end else if (C_PROG_FULL_TYPE == 3) begin
if (FULL == 0) begin
if (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) begin // FWFT
if (diff_pntr >= (PROG_FULL_THRESH - EXTRA_WORDS_DC))
ideal_prog_full <= #`TCQ 1;
else
ideal_prog_full <= #`TCQ 0;
end else begin // STD
if (diff_pntr >= PROG_FULL_THRESH)
ideal_prog_full <= #`TCQ 1;
else
ideal_prog_full <= #`TCQ 0;
end
end else
ideal_prog_full <= #`TCQ ideal_prog_full;
//Two Programmable Full Threshold Inputs
end else if (C_PROG_FULL_TYPE == 4) begin
if (FULL == 0) begin
if (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) begin // FWFT
if (diff_pntr >= (PROG_FULL_THRESH_ASSERT - EXTRA_WORDS_DC))
ideal_prog_full <= #`TCQ 1;
else if (diff_pntr < (PROG_FULL_THRESH_NEGATE - EXTRA_WORDS_DC))
ideal_prog_full <= #`TCQ 0;
else
ideal_prog_full <= #`TCQ ideal_prog_full;
end else begin // STD
if (diff_pntr >= PROG_FULL_THRESH_ASSERT)
ideal_prog_full <= #`TCQ 1;
else if (diff_pntr < PROG_FULL_THRESH_NEGATE)
ideal_prog_full <= #`TCQ 0;
else
ideal_prog_full <= #`TCQ ideal_prog_full;
end
end else
ideal_prog_full <= #`TCQ ideal_prog_full;
end // C_PROG_FULL_TYPE
end //wr_rst_i==0
end //
/**************************************************************************
* Read Domain Logic
**************************************************************************/
/*********************************************************
* Programmable EMPTY flags
*********************************************************/
//Determine the Assert and Negate thresholds for Programmable Empty
wire [C_RD_PNTR_WIDTH-1:0] pe_thr_assert_val;
wire [C_RD_PNTR_WIDTH-1:0] pe_thr_negate_val;
reg [C_RD_PNTR_WIDTH-1:0] diff_pntr_rd = 0;
always @(posedge RD_CLK or posedge rd_rst_i) begin : gen_pe
if (rd_rst_i) begin
diff_pntr_rd <= #`TCQ 0;
ideal_prog_empty <= #`TCQ 1'b1;
end else begin
if (ram_rd_en)
diff_pntr_rd <= #`TCQ (adj_wr_pntr_rd - rd_pntr) - 1'h1;
else if (!ram_rd_en)
diff_pntr_rd <= #`TCQ (adj_wr_pntr_rd - rd_pntr);
else
diff_pntr_rd <= #`TCQ diff_pntr_rd;
if (C_PROG_EMPTY_TYPE == 1) begin
if (EMPTY == 0) begin
if (diff_pntr_rd <= pe_thr_assert_val)
ideal_prog_empty <= #`TCQ 1;
else
ideal_prog_empty <= #`TCQ 0;
end else
ideal_prog_empty <= #`TCQ ideal_prog_empty;
end else if (C_PROG_EMPTY_TYPE == 2) begin
if (EMPTY == 0) begin
if (diff_pntr_rd <= pe_thr_assert_val)
ideal_prog_empty <= #`TCQ 1;
else if (diff_pntr_rd > pe_thr_negate_val)
ideal_prog_empty <= #`TCQ 0;
else
ideal_prog_empty <= #`TCQ ideal_prog_empty;
end else
ideal_prog_empty <= #`TCQ ideal_prog_empty;
end else if (C_PROG_EMPTY_TYPE == 3) begin
if (EMPTY == 0) begin
if (diff_pntr_rd <= pe_thr_assert_val)
ideal_prog_empty <= #`TCQ 1;
else
ideal_prog_empty <= #`TCQ 0;
end else
ideal_prog_empty <= #`TCQ ideal_prog_empty;
end else if (C_PROG_EMPTY_TYPE == 4) begin
if (EMPTY == 0) begin
if (diff_pntr_rd <= pe_thr_assert_val)
ideal_prog_empty <= #`TCQ 1;
else if (diff_pntr_rd > pe_thr_negate_val)
ideal_prog_empty <= #`TCQ 0;
else
ideal_prog_empty <= #`TCQ ideal_prog_empty;
end else
ideal_prog_empty <= #`TCQ ideal_prog_empty;
end //C_PROG_EMPTY_TYPE
end
end // gen_pe
generate if (C_PROG_EMPTY_TYPE == 3) begin : single_pe_thr_input
assign pe_thr_assert_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ?
PROG_EMPTY_THRESH - 2'h2 : PROG_EMPTY_THRESH;
end endgenerate // single_pe_thr_input
generate if (C_PROG_EMPTY_TYPE == 4) begin : multiple_pe_thr_input
assign pe_thr_assert_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ?
PROG_EMPTY_THRESH_ASSERT - 2'h2 : PROG_EMPTY_THRESH_ASSERT;
assign pe_thr_negate_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ?
PROG_EMPTY_THRESH_NEGATE - 2'h2 : PROG_EMPTY_THRESH_NEGATE;
end endgenerate // multiple_pe_thr_input
generate if (C_PROG_EMPTY_TYPE < 3) begin : single_multiple_pe_thr_const
assign pe_thr_assert_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ?
C_PROG_EMPTY_THRESH_ASSERT_VAL - 2'h2 : C_PROG_EMPTY_THRESH_ASSERT_VAL;
assign pe_thr_negate_val = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ?
C_PROG_EMPTY_THRESH_NEGATE_VAL - 2'h2 : C_PROG_EMPTY_THRESH_NEGATE_VAL;
end endgenerate // single_multiple_pe_thr_const
// block memory has a synchronous reset
always @(posedge RD_CLK) begin : gen_fifo_blkmemdout
// make it consistent with the core.
if (rd_rst_i) begin
// Reset err_type only if ECC is not selected
if (C_USE_ECC == 0 && C_MEMORY_TYPE < 2)
err_type <= #`TCQ 0;
// BRAM resets synchronously
if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE < 2) begin
ideal_dout <= #`TCQ dout_reset_val;
ideal_dout_d1 <= #`TCQ dout_reset_val;
end
end
end //always
always @(posedge RD_CLK or posedge rd_rst_i) begin : gen_fifo_r
/****** Reset fifo (case 1)***************************************/
if (rd_rst_i) begin
num_rd_bits <= #`TCQ 0;
next_num_rd_bits = #`TCQ 0;
rd_ptr <= #`TCQ C_RD_DEPTH -1;
rd_pntr <= #`TCQ 0;
rd_pntr_wr1 <= #`TCQ 0;
wr_ptr_rdclk <= #`TCQ C_WR_DEPTH -1;
// DRAM resets asynchronously
if (C_MEMORY_TYPE == 2 && C_USE_DOUT_RST == 1)
ideal_dout <= #`TCQ dout_reset_val;
// Reset err_type only if ECC is not selected
if (C_USE_ECC == 0)
err_type <= #`TCQ 0;
ideal_valid <= #`TCQ 1'b0;
ideal_rd_count <= #`TCQ 0;
end else begin //rd_rst_i==0
rd_pntr_wr1 <= #`TCQ rd_pntr;
//Determine the current number of words in the FIFO
tmp_rd_listsize = (C_DEPTH_RATIO_WR > 1) ? num_rd_bits/C_DIN_WIDTH :
num_rd_bits/C_DOUT_WIDTH;
wr_ptr_rdclk_next = wr_ptr;
if (wr_ptr_rdclk < wr_ptr_rdclk_next) begin
next_num_rd_bits = num_rd_bits +
C_DIN_WIDTH*(wr_ptr_rdclk +C_WR_DEPTH
- wr_ptr_rdclk_next);
end else begin
next_num_rd_bits = num_rd_bits +
C_DIN_WIDTH*(wr_ptr_rdclk - wr_ptr_rdclk_next);
end
/*****************************************************************/
// Read Operation - Read Latency 1
/*****************************************************************/
if (C_PRELOAD_LATENCY==1 || C_PRELOAD_LATENCY==2) begin
ideal_valid <= #`TCQ 1'b0;
if (ram_rd_en == 1'b1) begin
if (EMPTY == 1'b1) begin
//If the FIFO is completely empty, and is reporting empty
if (tmp_rd_listsize/C_DEPTH_RATIO_WR <= 0)
begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Reminder that FIFO is still empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize <= 0)
//If the FIFO is one from empty, but it is reporting empty
else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 1)
begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Note that FIFO is no longer empty, but is almost empty (has one word left)
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize == 1)
//If the FIFO is two from empty, and is reporting empty
else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 2)
begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Fifo has two words, so is neither empty or almost empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize == 2)
//If the FIFO is not close to empty, but is reporting that it is
// Treat the FIFO as empty this time, but unset EMPTY flags.
if ((tmp_rd_listsize/C_DEPTH_RATIO_WR > 2) && (tmp_rd_listsize/C_DEPTH_RATIO_WR<C_FIFO_RD_DEPTH))
begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Note that the FIFO is No Longer Empty or Almost Empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if ((tmp_rd_listsize > 2) && (tmp_rd_listsize<=C_FIFO_RD_DEPTH-1))
end // else: if(ideal_empty == 1'b1)
else //if (ideal_empty == 1'b0)
begin
//If the FIFO is completely full, and we are successfully reading from it
if (tmp_rd_listsize/C_DEPTH_RATIO_WR >= C_FIFO_RD_DEPTH)
begin
//Read the value from the FIFO
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
//Not close to empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize == C_FIFO_RD_DEPTH)
//If the FIFO is not close to being empty
else if ((tmp_rd_listsize/C_DEPTH_RATIO_WR > 2) && (tmp_rd_listsize/C_DEPTH_RATIO_WR<=C_FIFO_RD_DEPTH))
begin
//Read the value from the FIFO
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
//Not close to empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if ((tmp_rd_listsize > 2) && (tmp_rd_listsize<=C_FIFO_RD_DEPTH-1))
//If the FIFO is two from empty
else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 2)
begin
//Read the value from the FIFO
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
//Fifo is not yet empty. It is going almost_empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize == 2)
//If the FIFO is one from empty
else if ((tmp_rd_listsize/C_DEPTH_RATIO_WR == 1))
begin
//Read the value from the FIFO
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
//Note that FIFO is GOING empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize == 1)
//If the FIFO is completely empty
else if (tmp_rd_listsize/C_DEPTH_RATIO_WR <= 0)
begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize <= 0)
end // if (ideal_empty == 1'b0)
end //(RD_EN == 1'b1)
else //if (RD_EN == 1'b0)
begin
//If user did not attempt a read, do not give an ack or err
ideal_valid <= #`TCQ 1'b0;
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // else: !if(RD_EN == 1'b1)
/*****************************************************************/
// Read Operation - Read Latency 0
/*****************************************************************/
end else if (C_PRELOAD_REGS==1 && C_PRELOAD_LATENCY==0) begin
ideal_valid <= #`TCQ 1'b0;
if (ram_rd_en == 1'b1) begin
if (EMPTY == 1'b1) begin
//If the FIFO is completely empty, and is reporting empty
if (tmp_rd_listsize/C_DEPTH_RATIO_WR <= 0) begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Reminder that FIFO is still empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
//If the FIFO is one from empty, but it is reporting empty
end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 1) begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Note that FIFO is no longer empty, but is almost empty (has one word left)
ideal_rd_count <= #`TCQ num_read_words_sized_i;
//If the FIFO is two from empty, and is reporting empty
end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 2) begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Fifo has two words, so is neither empty or almost empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
//If the FIFO is not close to empty, but is reporting that it is
// Treat the FIFO as empty this time, but unset EMPTY flags.
end else if ((tmp_rd_listsize/C_DEPTH_RATIO_WR > 2) &&
(tmp_rd_listsize/C_DEPTH_RATIO_WR<C_FIFO_RD_DEPTH)) begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Note that the FIFO is No Longer Empty or Almost Empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if ((tmp_rd_listsize > 2) && (tmp_rd_listsize<=C_FIFO_RD_DEPTH-1))
end else begin
//If the FIFO is completely full, and we are successfully reading from it
if (tmp_rd_listsize/C_DEPTH_RATIO_WR >= C_FIFO_RD_DEPTH) begin
//Read the value from the FIFO
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
//Not close to empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
//If the FIFO is not close to being empty
end else if ((tmp_rd_listsize/C_DEPTH_RATIO_WR > 2) &&
(tmp_rd_listsize/C_DEPTH_RATIO_WR<=C_FIFO_RD_DEPTH)) begin
//Read the value from the FIFO
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
//Not close to empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
//If the FIFO is two from empty
end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 2) begin
//Read the value from the FIFO
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
//Fifo is not yet empty. It is going almost_empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
//If the FIFO is one from empty
end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR == 1) begin
//Read the value from the FIFO
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
//Note that FIFO is GOING empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
//If the FIFO is completely empty
end else if (tmp_rd_listsize/C_DEPTH_RATIO_WR <= 0) begin
//Do not change the contents of the FIFO
//Do not acknowledge the read from empty FIFO
ideal_valid <= #`TCQ 1'b0;
//Reminder that FIFO is still empty
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize <= 0)
end // if (ideal_empty == 1'b0)
end else begin//(RD_EN == 1'b0)
//If user did not attempt a read, do not give an ack or err
ideal_valid <= #`TCQ 1'b0;
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // else: !if(RD_EN == 1'b1)
end //if (C_PRELOAD_REGS==1 && C_PRELOAD_LATENCY==0)
num_rd_bits <= #`TCQ next_num_rd_bits;
wr_ptr_rdclk <= #`TCQ wr_ptr;
end //rd_rst_i==0
end //always
endmodule // fifo_generator_v12_0_bhv_ver_as
/*******************************************************************************
* Declaration of Low Latency Asynchronous FIFO
******************************************************************************/
module fifo_generator_v12_0_beh_ver_ll_afifo
/***************************************************************************
* Declare user parameters and their defaults
***************************************************************************/
#(
parameter C_DIN_WIDTH = 8,
parameter C_DOUT_RST_VAL = "",
parameter C_DOUT_WIDTH = 8,
parameter C_FULL_FLAGS_RST_VAL = 1,
parameter C_HAS_RD_DATA_COUNT = 0,
parameter C_HAS_WR_DATA_COUNT = 0,
parameter C_RD_DEPTH = 256,
parameter C_RD_PNTR_WIDTH = 8,
parameter C_USE_DOUT_RST = 0,
parameter C_WR_DATA_COUNT_WIDTH = 2,
parameter C_WR_DEPTH = 256,
parameter C_WR_PNTR_WIDTH = 8,
parameter C_FIFO_TYPE = 0
)
/***************************************************************************
* Declare Input and Output Ports
***************************************************************************/
(
input [C_DIN_WIDTH-1:0] DIN,
input RD_CLK,
input RD_EN,
input WR_RST,
input RD_RST,
input WR_CLK,
input WR_EN,
output reg [C_DOUT_WIDTH-1:0] DOUT = 0,
output reg EMPTY = 1'b1,
output reg FULL = C_FULL_FLAGS_RST_VAL
);
//-----------------------------------------------------------------------------
// Low Latency Asynchronous FIFO
//-----------------------------------------------------------------------------
// Memory which will be used to simulate a FIFO
reg [C_DIN_WIDTH-1:0] memory[C_WR_DEPTH-1:0];
integer i;
initial begin
for (i = 0; i < C_WR_DEPTH; i = i + 1)
memory[i] = 0;
end
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_ll_afifo = 0;
wire [C_RD_PNTR_WIDTH-1:0] rd_pntr_ll_afifo;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_ll_afifo_q = 0;
reg ll_afifo_full = 1'b0;
reg ll_afifo_empty = 1'b1;
wire write_allow;
wire read_allow;
assign write_allow = WR_EN & ~ll_afifo_full;
assign read_allow = RD_EN & ~ll_afifo_empty;
//-----------------------------------------------------------------------------
// Write Pointer Generation
//-----------------------------------------------------------------------------
always @(posedge WR_CLK or posedge WR_RST) begin
if (WR_RST)
wr_pntr_ll_afifo <= 0;
else if (write_allow)
wr_pntr_ll_afifo <= #`TCQ wr_pntr_ll_afifo + 1;
end
//-----------------------------------------------------------------------------
// Read Pointer Generation
//-----------------------------------------------------------------------------
always @(posedge RD_CLK or posedge RD_RST) begin
if (RD_RST)
rd_pntr_ll_afifo_q <= 0;
else
rd_pntr_ll_afifo_q <= #`TCQ rd_pntr_ll_afifo;
end
assign rd_pntr_ll_afifo = read_allow ? rd_pntr_ll_afifo_q + 1 : rd_pntr_ll_afifo_q;
//-----------------------------------------------------------------------------
// Fill the Memory
//-----------------------------------------------------------------------------
always @(posedge WR_CLK) begin
if (write_allow)
memory[wr_pntr_ll_afifo] <= #`TCQ DIN;
end
//-----------------------------------------------------------------------------
// Generate DOUT
//-----------------------------------------------------------------------------
always @(posedge RD_CLK) begin
DOUT <= #`TCQ memory[rd_pntr_ll_afifo];
end
//-----------------------------------------------------------------------------
// Generate EMPTY
//-----------------------------------------------------------------------------
always @(posedge RD_CLK or posedge RD_RST) begin
if (RD_RST)
ll_afifo_empty <= 1'b1;
else
ll_afifo_empty <= ((wr_pntr_ll_afifo == rd_pntr_ll_afifo_q) |
(read_allow & (wr_pntr_ll_afifo == (rd_pntr_ll_afifo_q + 2'h1))));
end
//-----------------------------------------------------------------------------
// Generate FULL
//-----------------------------------------------------------------------------
always @(posedge WR_CLK or posedge WR_RST) begin
if (WR_RST)
ll_afifo_full <= 1'b1;
else
ll_afifo_full <= ((rd_pntr_ll_afifo_q == (wr_pntr_ll_afifo + 2'h1)) |
(write_allow & (rd_pntr_ll_afifo_q == (wr_pntr_ll_afifo + 2'h2))));
end
always @* begin
FULL <= ll_afifo_full;
EMPTY <= ll_afifo_empty;
end
endmodule // fifo_generator_v12_0_beh_ver_ll_afifo
/*******************************************************************************
* Declaration of top-level module
******************************************************************************/
module fifo_generator_v12_0_bhv_ver_ss
/**************************************************************************
* Declare user parameters and their defaults
*************************************************************************/
#(
parameter C_FAMILY = "virtex7",
parameter C_DATA_COUNT_WIDTH = 2,
parameter C_DIN_WIDTH = 8,
parameter C_DOUT_RST_VAL = "",
parameter C_DOUT_WIDTH = 8,
parameter C_FULL_FLAGS_RST_VAL = 1,
parameter C_HAS_ALMOST_EMPTY = 0,
parameter C_HAS_ALMOST_FULL = 0,
parameter C_HAS_DATA_COUNT = 0,
parameter C_HAS_OVERFLOW = 0,
parameter C_HAS_RD_DATA_COUNT = 0,
parameter C_HAS_RST = 0,
parameter C_HAS_SRST = 0,
parameter C_HAS_UNDERFLOW = 0,
parameter C_HAS_VALID = 0,
parameter C_HAS_WR_ACK = 0,
parameter C_HAS_WR_DATA_COUNT = 0,
parameter C_IMPLEMENTATION_TYPE = 0,
parameter C_MEMORY_TYPE = 1,
parameter C_OVERFLOW_LOW = 0,
parameter C_PRELOAD_LATENCY = 1,
parameter C_PRELOAD_REGS = 0,
parameter C_PROG_EMPTY_THRESH_ASSERT_VAL = 0,
parameter C_PROG_EMPTY_THRESH_NEGATE_VAL = 0,
parameter C_PROG_EMPTY_TYPE = 0,
parameter C_PROG_FULL_THRESH_ASSERT_VAL = 0,
parameter C_PROG_FULL_THRESH_NEGATE_VAL = 0,
parameter C_PROG_FULL_TYPE = 0,
parameter C_RD_DATA_COUNT_WIDTH = 2,
parameter C_RD_DEPTH = 256,
parameter C_RD_PNTR_WIDTH = 8,
parameter C_UNDERFLOW_LOW = 0,
parameter C_USE_DOUT_RST = 0,
parameter C_USE_EMBEDDED_REG = 0,
parameter C_USE_FWFT_DATA_COUNT = 0,
parameter C_VALID_LOW = 0,
parameter C_WR_ACK_LOW = 0,
parameter C_WR_DATA_COUNT_WIDTH = 2,
parameter C_WR_DEPTH = 256,
parameter C_WR_PNTR_WIDTH = 8,
parameter C_USE_ECC = 0,
parameter C_ENABLE_RST_SYNC = 1,
parameter C_ERROR_INJECTION_TYPE = 0,
parameter C_FIFO_TYPE = 0
)
/**************************************************************************
* Declare Input and Output Ports
*************************************************************************/
(
//Inputs
input CLK,
input [C_DIN_WIDTH-1:0] DIN,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT,
input [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT,
input [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE,
input RD_EN,
input RD_EN_USER,
input USER_EMPTY_FB,
input RST,
input RST_FULL_GEN,
input RST_FULL_FF,
input SRST,
input WR_EN,
input INJECTDBITERR,
input INJECTSBITERR,
input WR_RST_BUSY,
input RD_RST_BUSY,
//Outputs
output ALMOST_EMPTY,
output ALMOST_FULL,
output reg [C_DATA_COUNT_WIDTH-1:0] DATA_COUNT = 0,
output [C_DOUT_WIDTH-1:0] DOUT,
output EMPTY,
output FULL,
output OVERFLOW,
output [C_RD_DATA_COUNT_WIDTH-1:0] RD_DATA_COUNT,
output [C_WR_DATA_COUNT_WIDTH-1:0] WR_DATA_COUNT,
output PROG_EMPTY,
output PROG_FULL,
output VALID,
output UNDERFLOW,
output WR_ACK,
output SBITERR,
output DBITERR
);
reg [C_RD_PNTR_WIDTH:0] rd_data_count_int = 0;
reg [C_WR_PNTR_WIDTH:0] wr_data_count_int = 0;
wire [C_RD_PNTR_WIDTH:0] rd_data_count_i_ss;
wire [C_WR_PNTR_WIDTH:0] wr_data_count_i_ss;
reg [C_WR_PNTR_WIDTH:0] wdc_fwft_ext_as = 0;
/***************************************************************************
* Parameters used as constants
**************************************************************************/
localparam IS_8SERIES = (C_FAMILY == "virtexu" || C_FAMILY == "kintexu" || C_FAMILY == "artixu" || C_FAMILY == "virtexum" || C_FAMILY == "zynque") ? 1 : 0;
localparam C_DEPTH_RATIO_WR =
(C_WR_DEPTH>C_RD_DEPTH) ? (C_WR_DEPTH/C_RD_DEPTH) : 1;
localparam C_DEPTH_RATIO_RD =
(C_RD_DEPTH>C_WR_DEPTH) ? (C_RD_DEPTH/C_WR_DEPTH) : 1;
//localparam C_FIFO_WR_DEPTH = C_WR_DEPTH - 1;
//localparam C_FIFO_RD_DEPTH = C_RD_DEPTH - 1;
localparam C_GRTR_PNTR_WIDTH = (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) ? C_WR_PNTR_WIDTH : C_RD_PNTR_WIDTH ;
// C_DEPTH_RATIO_WR | C_DEPTH_RATIO_RD | C_PNTR_WIDTH | EXTRA_WORDS_DC
// -----------------|------------------|-----------------|---------------
// 1 | 8 | C_RD_PNTR_WIDTH | 2
// 1 | 4 | C_RD_PNTR_WIDTH | 2
// 1 | 2 | C_RD_PNTR_WIDTH | 2
// 1 | 1 | C_WR_PNTR_WIDTH | 2
// 2 | 1 | C_WR_PNTR_WIDTH | 4
// 4 | 1 | C_WR_PNTR_WIDTH | 8
// 8 | 1 | C_WR_PNTR_WIDTH | 16
localparam C_PNTR_WIDTH = (C_WR_PNTR_WIDTH>=C_RD_PNTR_WIDTH) ? C_WR_PNTR_WIDTH : C_RD_PNTR_WIDTH;
wire [C_PNTR_WIDTH:0] EXTRA_WORDS_DC = (C_DEPTH_RATIO_WR == 1) ? 2 : (2 * C_DEPTH_RATIO_WR/C_DEPTH_RATIO_RD);
wire [C_WR_PNTR_WIDTH:0] EXTRA_WORDS_PF = (C_DEPTH_RATIO_WR == 1) ? 2 : (2 * C_DEPTH_RATIO_WR/C_DEPTH_RATIO_RD);
//wire [C_RD_PNTR_WIDTH:0] EXTRA_WORDS_PE = (C_DEPTH_RATIO_RD == 1) ? 2 : (2 * C_DEPTH_RATIO_RD/C_DEPTH_RATIO_WR);
localparam EXTRA_WORDS_PF_PARAM = (C_DEPTH_RATIO_WR == 1) ? 2 : (2 * C_DEPTH_RATIO_WR/C_DEPTH_RATIO_RD);
//localparam EXTRA_WORDS_PE_PARAM = (C_DEPTH_RATIO_RD == 1) ? 2 : (2 * C_DEPTH_RATIO_RD/C_DEPTH_RATIO_WR);
localparam [31:0] reads_per_write = C_DIN_WIDTH/C_DOUT_WIDTH;
localparam [31:0] log2_reads_per_write = log2_val(reads_per_write);
localparam [31:0] writes_per_read = C_DOUT_WIDTH/C_DIN_WIDTH;
localparam [31:0] log2_writes_per_read = log2_val(writes_per_read);
//When RST is present, set FULL reset value to '1'.
//If core has no RST, make sure FULL powers-on as '0'.
//The reset value assignments for FULL, ALMOST_FULL, and PROG_FULL are not
//changed for v3.2(IP2_Im). When the core has Sync Reset, C_HAS_SRST=1 and C_HAS_RST=0.
// Therefore, during SRST, all the FULL flags reset to 0.
localparam C_HAS_FAST_FIFO = 0;
localparam C_FIFO_WR_DEPTH = C_WR_DEPTH;
localparam C_FIFO_RD_DEPTH = C_RD_DEPTH;
// Local parameters used to determine whether to inject ECC error or not
localparam SYMMETRIC_PORT = (C_DIN_WIDTH == C_DOUT_WIDTH) ? 1 : 0;
localparam ERR_INJECTION = (C_ERROR_INJECTION_TYPE != 0) ? 1 : 0;
localparam ENABLE_ERR_INJECTION = C_USE_ECC && SYMMETRIC_PORT && ERR_INJECTION;
localparam C_DATA_WIDTH = (ENABLE_ERR_INJECTION == 1) ? (C_DIN_WIDTH+2) : C_DIN_WIDTH;
localparam IS_ASYMMETRY = (C_DIN_WIDTH == C_DOUT_WIDTH) ? 0 : 1;
localparam LESSER_WIDTH = (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) ? C_WR_PNTR_WIDTH : C_RD_PNTR_WIDTH;
localparam [C_RD_PNTR_WIDTH-1 : 0] DIFF_MAX_RD = {C_RD_PNTR_WIDTH{1'b1}};
localparam [C_WR_PNTR_WIDTH-1 : 0] DIFF_MAX_WR = {C_WR_PNTR_WIDTH{1'b1}};
/**************************************************************************
* FIFO Contents Tracking and Data Count Calculations
*************************************************************************/
// Memory which will be used to simulate a FIFO
reg [C_DIN_WIDTH-1:0] memory[C_WR_DEPTH-1:0];
reg [1:0] ecc_err[C_WR_DEPTH-1:0];
/**************************************************************************
* Internal Registers and wires
*************************************************************************/
//Temporary signals used for calculating the model's outputs. These
//are only used in the assign statements immediately following wire,
//parameter, and function declarations.
wire underflow_i;
wire valid_i;
wire valid_out;
reg [31:0] num_wr_bits;
reg [31:0] num_rd_bits;
reg [31:0] next_num_wr_bits;
reg [31:0] next_num_rd_bits;
//The write pointer - tracks write operations
// (Works opposite to core: wr_ptr is a DOWN counter)
reg [31:0] wr_ptr;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd1 = 0;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd2 = 0;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd3 = 0;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr_rd = 0;
reg wr_rst_d1 =0;
//The read pointer - tracks read operations
// (rd_ptr Works opposite to core: rd_ptr is a DOWN counter)
reg [31:0] rd_ptr;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr1 = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr2 = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr3 = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr4 = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr_wr = 0;
wire ram_rd_en;
wire empty_int;
wire almost_empty_int;
wire ram_wr_en;
wire full_int;
wire almost_full_int;
reg ram_rd_en_reg = 1'b0;
//Ideal FIFO signals. These are the raw output of the behavioral model,
//which behaves like an ideal FIFO.
reg [1:0] err_type = 0;
reg [1:0] err_type_d1 = 0;
reg [C_DOUT_WIDTH-1:0] ideal_dout = 0;
reg [C_DOUT_WIDTH-1:0] ideal_dout_d1 = 0;
wire [C_DOUT_WIDTH-1:0] ideal_dout_out;
wire fwft_enabled;
reg ideal_wr_ack = 0;
reg ideal_valid = 0;
reg ideal_overflow = C_OVERFLOW_LOW;
reg ideal_underflow = C_UNDERFLOW_LOW;
reg full_i = C_FULL_FLAGS_RST_VAL;
reg full_i_temp = 0;
reg empty_i = 1;
reg almost_full_i = 0;
reg almost_empty_i = 1;
reg prog_full_i = 0;
reg prog_empty_i = 1;
reg [C_WR_PNTR_WIDTH-1:0] wr_pntr = 0;
reg [C_RD_PNTR_WIDTH-1:0] rd_pntr = 0;
wire [C_RD_PNTR_WIDTH-1:0] adj_wr_pntr_rd;
wire [C_WR_PNTR_WIDTH-1:0] adj_rd_pntr_wr;
reg [C_RD_PNTR_WIDTH-1:0] diff_count = 0;
reg write_allow_q = 0;
reg read_allow_q = 0;
reg valid_d1 = 0;
wire rst_i;
wire srst_i;
//user specified value for reseting the size of the fifo
reg [C_DOUT_WIDTH-1:0] dout_reset_val = 0;
reg [31:0] wr_ptr_rdclk;
reg [31:0] wr_ptr_rdclk_next;
reg [31:0] rd_ptr_wrclk;
reg [31:0] rd_ptr_wrclk_next;
/****************************************************************************
* Function Declarations
***************************************************************************/
/****************************************************************************
* hexstr_conv
* Converts a string of type hex to a binary value (for C_DOUT_RST_VAL)
***************************************************************************/
function [C_DOUT_WIDTH-1:0] hexstr_conv;
input [(C_DOUT_WIDTH*8)-1:0] def_data;
integer index,i,j;
reg [3:0] bin;
begin
index = 0;
hexstr_conv = 'b0;
for( i=C_DOUT_WIDTH-1; i>=0; i=i-1 ) begin
case (def_data[7:0])
8'b00000000 : begin
bin = 4'b0000;
i = -1;
end
8'b00110000 : bin = 4'b0000;
8'b00110001 : bin = 4'b0001;
8'b00110010 : bin = 4'b0010;
8'b00110011 : bin = 4'b0011;
8'b00110100 : bin = 4'b0100;
8'b00110101 : bin = 4'b0101;
8'b00110110 : bin = 4'b0110;
8'b00110111 : bin = 4'b0111;
8'b00111000 : bin = 4'b1000;
8'b00111001 : bin = 4'b1001;
8'b01000001 : bin = 4'b1010;
8'b01000010 : bin = 4'b1011;
8'b01000011 : bin = 4'b1100;
8'b01000100 : bin = 4'b1101;
8'b01000101 : bin = 4'b1110;
8'b01000110 : bin = 4'b1111;
8'b01100001 : bin = 4'b1010;
8'b01100010 : bin = 4'b1011;
8'b01100011 : bin = 4'b1100;
8'b01100100 : bin = 4'b1101;
8'b01100101 : bin = 4'b1110;
8'b01100110 : bin = 4'b1111;
default : begin
bin = 4'bx;
end
endcase
for( j=0; j<4; j=j+1) begin
if ((index*4)+j < C_DOUT_WIDTH) begin
hexstr_conv[(index*4)+j] = bin[j];
end
end
index = index + 1;
def_data = def_data >> 8;
end
end
endfunction
/**************************************************************************
* log2_val
* Returns the 'log2' value for the input value for the supported ratios
***************************************************************************/
function [31:0] log2_val;
input [31:0] binary_val;
begin
if (binary_val == 8) begin
log2_val = 3;
end else if (binary_val == 4) begin
log2_val = 2;
end else begin
log2_val = 1;
end
end
endfunction
reg ideal_prog_full = 0;
reg ideal_prog_empty = 1;
reg [C_WR_DATA_COUNT_WIDTH-1 : 0] ideal_wr_count = 0;
reg [C_RD_DATA_COUNT_WIDTH-1 : 0] ideal_rd_count = 0;
//Assorted reg values for delayed versions of signals
//reg valid_d1 = 0;
//user specified value for reseting the size of the fifo
//reg [C_DOUT_WIDTH-1:0] dout_reset_val = 0;
//temporary registers for WR_RESPONSE_LATENCY feature
integer tmp_wr_listsize;
integer tmp_rd_listsize;
//Signal for registered version of prog full and empty
//Threshold values for Programmable Flags
integer prog_empty_actual_thresh_assert;
integer prog_empty_actual_thresh_negate;
integer prog_full_actual_thresh_assert;
integer prog_full_actual_thresh_negate;
/**************************************************************************
* write_fifo
* This task writes a word to the FIFO memory and updates the
* write pointer.
* FIFO size is relative to write domain.
***************************************************************************/
task write_fifo;
begin
memory[wr_ptr] <= DIN;
wr_pntr <= #`TCQ wr_pntr + 1;
// Store the type of error injection (double/single) on write
case (C_ERROR_INJECTION_TYPE)
3: ecc_err[wr_ptr] <= {INJECTDBITERR,INJECTSBITERR};
2: ecc_err[wr_ptr] <= {INJECTDBITERR,1'b0};
1: ecc_err[wr_ptr] <= {1'b0,INJECTSBITERR};
default: ecc_err[wr_ptr] <= 0;
endcase
// (Works opposite to core: wr_ptr is a DOWN counter)
if (wr_ptr == 0) begin
wr_ptr <= C_WR_DEPTH - 1;
end else begin
wr_ptr <= wr_ptr - 1;
end
end
endtask // write_fifo
/**************************************************************************
* read_fifo
* This task reads a word from the FIFO memory and updates the read
* pointer. It's output is the ideal_dout bus.
* FIFO size is relative to write domain.
***************************************************************************/
task read_fifo;
integer i;
reg [C_DOUT_WIDTH-1:0] tmp_dout;
reg [C_DIN_WIDTH-1:0] memory_read;
reg [31:0] tmp_rd_ptr;
reg [31:0] rd_ptr_high;
reg [31:0] rd_ptr_low;
reg [1:0] tmp_ecc_err;
begin
rd_pntr <= #`TCQ rd_pntr + 1;
// output is wider than input
if (reads_per_write == 0) begin
tmp_dout = 0;
tmp_rd_ptr = (rd_ptr << log2_writes_per_read)+(writes_per_read-1);
for (i = writes_per_read - 1; i >= 0; i = i - 1) begin
tmp_dout = tmp_dout << C_DIN_WIDTH;
tmp_dout = tmp_dout | memory[tmp_rd_ptr];
// (Works opposite to core: rd_ptr is a DOWN counter)
if (tmp_rd_ptr == 0) begin
tmp_rd_ptr = C_WR_DEPTH - 1;
end else begin
tmp_rd_ptr = tmp_rd_ptr - 1;
end
end
// output is symmetric
end else if (reads_per_write == 1) begin
tmp_dout = memory[rd_ptr][C_DIN_WIDTH-1:0];
// Retreive the error injection type. Based on the error injection type
// corrupt the output data.
tmp_ecc_err = ecc_err[rd_ptr];
if (ENABLE_ERR_INJECTION && C_DIN_WIDTH == C_DOUT_WIDTH) begin
if (tmp_ecc_err[1]) begin // Corrupt the output data only for double bit error
if (C_DOUT_WIDTH == 1) begin
$display("FAILURE : Data width must be >= 2 for double bit error injection.");
$finish;
end else if (C_DOUT_WIDTH == 2)
tmp_dout = {~tmp_dout[C_DOUT_WIDTH-1],~tmp_dout[C_DOUT_WIDTH-2]};
else
tmp_dout = {~tmp_dout[C_DOUT_WIDTH-1],~tmp_dout[C_DOUT_WIDTH-2],(tmp_dout << 2)};
end else begin
tmp_dout = tmp_dout[C_DOUT_WIDTH-1:0];
end
err_type <= {tmp_ecc_err[1], tmp_ecc_err[0] & !tmp_ecc_err[1]};
end else begin
err_type <= 0;
end
// input is wider than output
end else begin
rd_ptr_high = rd_ptr >> log2_reads_per_write;
rd_ptr_low = rd_ptr & (reads_per_write - 1);
memory_read = memory[rd_ptr_high];
tmp_dout = memory_read >> (rd_ptr_low*C_DOUT_WIDTH);
end
ideal_dout <= tmp_dout;
// (Works opposite to core: rd_ptr is a DOWN counter)
if (rd_ptr == 0) begin
rd_ptr <= C_RD_DEPTH - 1;
end else begin
rd_ptr <= rd_ptr - 1;
end
end
endtask
/*************************************************************************
* Initialize Signals for clean power-on simulation
*************************************************************************/
initial begin
num_wr_bits = 0;
num_rd_bits = 0;
next_num_wr_bits = 0;
next_num_rd_bits = 0;
rd_ptr = C_RD_DEPTH - 1;
wr_ptr = C_WR_DEPTH - 1;
wr_pntr = 0;
rd_pntr = 0;
rd_ptr_wrclk = rd_ptr;
wr_ptr_rdclk = wr_ptr;
dout_reset_val = hexstr_conv(C_DOUT_RST_VAL);
ideal_dout = dout_reset_val;
err_type = 0;
ideal_dout_d1 = dout_reset_val;
ideal_wr_ack = 1'b0;
ideal_valid = 1'b0;
valid_d1 = 1'b0;
ideal_overflow = C_OVERFLOW_LOW;
ideal_underflow = C_UNDERFLOW_LOW;
ideal_wr_count = 0;
ideal_rd_count = 0;
ideal_prog_full = 1'b0;
ideal_prog_empty = 1'b1;
end
/*************************************************************************
* Connect the module inputs and outputs to the internal signals of the
* behavioral model.
*************************************************************************/
//Inputs
/*
wire CLK;
wire [C_DIN_WIDTH-1:0] DIN;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_ASSERT;
wire [C_RD_PNTR_WIDTH-1:0] PROG_EMPTY_THRESH_NEGATE;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_ASSERT;
wire [C_WR_PNTR_WIDTH-1:0] PROG_FULL_THRESH_NEGATE;
wire RD_EN;
wire RST;
wire WR_EN;
*/
// Assign ALMOST_EPMTY
generate if (C_HAS_ALMOST_EMPTY == 1) begin : gae
assign ALMOST_EMPTY = almost_empty_i;
end else begin : gnae
assign ALMOST_EMPTY = 0;
end endgenerate // gae
// Assign ALMOST_FULL
generate if (C_HAS_ALMOST_FULL==1) begin : gaf
assign ALMOST_FULL = almost_full_i;
end else begin : gnaf
assign ALMOST_FULL = 0;
end endgenerate // gaf
// Dout may change behavior based on latency
assign fwft_enabled = (C_PRELOAD_LATENCY == 0 && C_PRELOAD_REGS == 1)?
1: 0;
assign ideal_dout_out= ((C_USE_EMBEDDED_REG==1 && (fwft_enabled == 0)) &&
(C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1))?
ideal_dout_d1: ideal_dout;
assign DOUT = ideal_dout_out;
// Assign SBITERR and DBITERR based on latency
assign SBITERR = (C_ERROR_INJECTION_TYPE == 1 || C_ERROR_INJECTION_TYPE == 3) &&
((C_USE_EMBEDDED_REG==1 && (fwft_enabled == 0)) &&
(C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1)) ?
err_type_d1[0]: err_type[0];
assign DBITERR = (C_ERROR_INJECTION_TYPE == 2 || C_ERROR_INJECTION_TYPE == 3) &&
((C_USE_EMBEDDED_REG==1 && (fwft_enabled == 0)) &&
(C_MEMORY_TYPE==0 || C_MEMORY_TYPE==1)) ?
err_type_d1[1]: err_type[1];
assign EMPTY = empty_i;
assign FULL = full_i;
//Overflow may be active-low
generate if (C_HAS_OVERFLOW==1) begin : gof
assign OVERFLOW = ideal_overflow ? !C_OVERFLOW_LOW : C_OVERFLOW_LOW;
end else begin : gnof
assign OVERFLOW = 0;
end endgenerate // gof
assign PROG_EMPTY = prog_empty_i;
assign PROG_FULL = prog_full_i;
//Valid may change behavior based on latency or active-low
generate if (C_HAS_VALID==1) begin : gvalid
assign valid_i = (C_PRELOAD_LATENCY == 0) ? (RD_EN & ~EMPTY) : ideal_valid;
assign valid_out = (C_PRELOAD_LATENCY == 2 && C_MEMORY_TYPE < 2) ?
valid_d1 : valid_i;
assign VALID = valid_out ? !C_VALID_LOW : C_VALID_LOW;
end else begin : gnvalid
assign VALID = 0;
end endgenerate // gvalid
//Trim data count differently depending on set widths
generate if (C_HAS_DATA_COUNT == 1) begin : gdc
always @* begin
diff_count <= wr_pntr - rd_pntr;
if (C_DATA_COUNT_WIDTH > C_RD_PNTR_WIDTH) begin
DATA_COUNT[C_RD_PNTR_WIDTH-1:0] <= diff_count;
DATA_COUNT[C_DATA_COUNT_WIDTH-1] <= 1'b0 ;
end else begin
DATA_COUNT <= diff_count[C_RD_PNTR_WIDTH-1:C_RD_PNTR_WIDTH-C_DATA_COUNT_WIDTH];
end
end
// end else begin : gndc
// always @* DATA_COUNT <= 0;
end endgenerate // gdc
//Underflow may change behavior based on latency or active-low
generate if (C_HAS_UNDERFLOW==1) begin : guf
assign underflow_i = ideal_underflow;
assign UNDERFLOW = underflow_i ? !C_UNDERFLOW_LOW : C_UNDERFLOW_LOW;
end else begin : gnuf
assign UNDERFLOW = 0;
end endgenerate // guf
//Write acknowledge may be active low
generate if (C_HAS_WR_ACK==1) begin : gwr_ack
assign WR_ACK = ideal_wr_ack ? !C_WR_ACK_LOW : C_WR_ACK_LOW;
end else begin : gnwr_ack
assign WR_ACK = 0;
end endgenerate // gwr_ack
/*****************************************************************************
* Internal reset logic
****************************************************************************/
assign srst_i = C_HAS_SRST ? SRST : 0;
assign srst_wrst_busy = C_HAS_SRST ? (SRST || WR_RST_BUSY) : 0;
assign srst_rrst_busy = C_HAS_SRST ? (SRST || RD_RST_BUSY) : 0;
assign rst_i = C_HAS_RST ? RST : 0;
/**************************************************************************
* Assorted registers for delayed versions of signals
**************************************************************************/
//Capture delayed version of valid
generate if (C_HAS_VALID == 1) begin : blockVL20
always @(posedge CLK or posedge rst_i) begin
if (rst_i == 1'b1) begin
valid_d1 <= #`TCQ 1'b0;
end else begin
if (srst_rrst_busy) begin
valid_d1 <= #`TCQ 1'b0;
end else begin
valid_d1 <= #`TCQ valid_i;
end
end
end // always @ (posedge CLK or posedge rst_i)
end endgenerate // blockVL20
// Determine which stage in FWFT registers are valid
reg stage1_valid = 0;
reg stage2_valid = 0;
generate
if (C_PRELOAD_LATENCY == 0) begin : grd_fwft_proc
always @ (posedge CLK or posedge rst_i) begin
if (rst_i) begin
stage1_valid <= #`TCQ 0;
stage2_valid <= #`TCQ 0;
end else begin
if (!stage1_valid && !stage2_valid) begin
if (!EMPTY)
stage1_valid <= #`TCQ 1'b1;
else
stage1_valid <= #`TCQ 1'b0;
end else if (stage1_valid && !stage2_valid) begin
if (EMPTY) begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b1;
end else begin
stage1_valid <= #`TCQ 1'b1;
stage2_valid <= #`TCQ 1'b1;
end
end else if (!stage1_valid && stage2_valid) begin
if (EMPTY && RD_EN) begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b0;
end else if (!EMPTY && RD_EN) begin
stage1_valid <= #`TCQ 1'b1;
stage2_valid <= #`TCQ 1'b0;
end else if (!EMPTY && !RD_EN) begin
stage1_valid <= #`TCQ 1'b1;
stage2_valid <= #`TCQ 1'b1;
end else begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b1;
end
end else if (stage1_valid && stage2_valid) begin
if (EMPTY && RD_EN) begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b1;
end else begin
stage1_valid <= #`TCQ 1'b1;
stage2_valid <= #`TCQ 1'b1;
end
end else begin
stage1_valid <= #`TCQ 1'b0;
stage2_valid <= #`TCQ 1'b0;
end
end // rd_rst_i
end // always
end
endgenerate
//***************************************************************************
// Assign the read data count value only if it is selected,
// otherwise output zeros.
//***************************************************************************
generate
if (C_HAS_RD_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT ==1) begin : grdc
assign RD_DATA_COUNT[C_RD_DATA_COUNT_WIDTH-1:0] = rd_data_count_i_ss[C_RD_PNTR_WIDTH:C_RD_PNTR_WIDTH+1-C_RD_DATA_COUNT_WIDTH];
end
endgenerate
generate
if (C_HAS_RD_DATA_COUNT == 0) begin : gnrdc
assign RD_DATA_COUNT[C_RD_DATA_COUNT_WIDTH-1:0] = {C_RD_DATA_COUNT_WIDTH{1'b0}};
end
endgenerate
//***************************************************************************
// Assign the write data count value only if it is selected,
// otherwise output zeros
//***************************************************************************
generate
if (C_HAS_WR_DATA_COUNT == 1 && C_USE_FWFT_DATA_COUNT == 1) begin : gwdc
assign WR_DATA_COUNT[C_WR_DATA_COUNT_WIDTH-1:0] = wr_data_count_i_ss[C_WR_PNTR_WIDTH:C_WR_PNTR_WIDTH+1-C_WR_DATA_COUNT_WIDTH] ;
end
endgenerate
generate
if (C_HAS_WR_DATA_COUNT == 0) begin : gnwdc
assign WR_DATA_COUNT[C_WR_DATA_COUNT_WIDTH-1:0] = {C_WR_DATA_COUNT_WIDTH{1'b0}};
end
endgenerate
// block memory has a synchronous reset
generate if (C_MEMORY_TYPE < 2) begin : gen_fifo_blkmemdout_emb
always @(posedge CLK) begin
// BRAM resets synchronously
// make it consistent with the core.
if ((rst_i || srst_rrst_busy) && (C_USE_DOUT_RST == 1))
ideal_dout_d1 <= #`TCQ dout_reset_val;
end //always
end endgenerate // gen_fifo_blkmemdout_emb
reg ram_rd_en_d1 = 1'b0;
//Capture delayed version of dout
always @(posedge CLK or posedge rst_i) begin
if (rst_i == 1'b1) begin
// Reset err_type only if ECC is not selected
if (C_USE_ECC == 0)
err_type_d1 <= #`TCQ 0;
// DRAM and SRAM reset asynchronously
if ((C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3) && C_USE_DOUT_RST == 1)
ideal_dout_d1 <= #`TCQ dout_reset_val;
ram_rd_en_d1 <= #`TCQ 1'b0;
end else begin
ram_rd_en_d1 <= #`TCQ RD_EN & ~EMPTY;
if (srst_rrst_busy) begin
ram_rd_en_d1 <= #`TCQ 1'b0;
// Reset err_type only if ECC is not selected
if (C_USE_ECC == 0)
err_type_d1 <= #`TCQ 0;
// Reset DRAM and SRAM based FIFO, BRAM based FIFO is reset above
if ((C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3) && C_USE_DOUT_RST == 1)
ideal_dout_d1 <= #`TCQ dout_reset_val;
end else if (ram_rd_en_d1) begin
ideal_dout_d1 <= #`TCQ ideal_dout;
err_type_d1 <= #`TCQ err_type;
end
end
end
/**************************************************************************
* Overflow and Underflow Flag calculation
* (handled separately because they don't support rst)
**************************************************************************/
generate if (C_HAS_OVERFLOW == 1 && IS_8SERIES == 0) begin : g7s_ovflw
always @(posedge CLK) begin
ideal_overflow <= #`TCQ WR_EN & full_i;
end
end else if (C_HAS_OVERFLOW == 1 && IS_8SERIES == 1) begin : g8s_ovflw
always @(posedge CLK) begin
//ideal_overflow <= #`TCQ WR_EN & (rst_i | full_i);
ideal_overflow <= #`TCQ WR_EN & (WR_RST_BUSY | full_i);
end
end endgenerate // blockOF20
generate if (C_HAS_UNDERFLOW == 1 && IS_8SERIES == 0) begin : g7s_unflw
always @(posedge CLK) begin
ideal_underflow <= #`TCQ empty_i & RD_EN;
end
end else if (C_HAS_UNDERFLOW == 1 && IS_8SERIES == 1) begin : g8s_unflw
always @(posedge CLK) begin
//ideal_underflow <= #`TCQ (rst_i | empty_i) & RD_EN;
ideal_underflow <= #`TCQ (RD_RST_BUSY | empty_i) & RD_EN;
end
end endgenerate // blockUF20
/**************************
* Read Data Count
*************************/
reg [31:0] num_read_words_dc;
reg [C_RD_DATA_COUNT_WIDTH-1:0] num_read_words_sized_i;
always @(num_rd_bits) begin
if (C_USE_FWFT_DATA_COUNT) begin
//If using extra logic for FWFT Data Counts,
// then scale FIFO contents to read domain,
// and add two read words for FWFT stages
//This value is only a temporary value and not used in the code.
num_read_words_dc = (num_rd_bits/C_DOUT_WIDTH+2);
//Trim the read words for use with RD_DATA_COUNT
num_read_words_sized_i =
num_read_words_dc[C_RD_PNTR_WIDTH : C_RD_PNTR_WIDTH-C_RD_DATA_COUNT_WIDTH+1];
end else begin
//If not using extra logic for FWFT Data Counts,
// then scale FIFO contents to read domain.
//This value is only a temporary value and not used in the code.
num_read_words_dc = num_rd_bits/C_DOUT_WIDTH;
//Trim the read words for use with RD_DATA_COUNT
num_read_words_sized_i =
num_read_words_dc[C_RD_PNTR_WIDTH-1 : C_RD_PNTR_WIDTH-C_RD_DATA_COUNT_WIDTH];
end //if (C_USE_FWFT_DATA_COUNT)
end //always
/**************************
* Write Data Count
*************************/
reg [31:0] num_write_words_dc;
reg [C_WR_DATA_COUNT_WIDTH-1:0] num_write_words_sized_i;
always @(num_wr_bits) begin
if (C_USE_FWFT_DATA_COUNT) begin
//Calculate the Data Count value for the number of write words,
// when using First-Word Fall-Through with extra logic for Data
// Counts. This takes into consideration the number of words that
// are expected to be stored in the FWFT register stages (it always
// assumes they are filled).
//This value is scaled to the Write Domain.
//The expression (((A-1)/B))+1 divides A/B, but takes the
// ceiling of the result.
//When num_wr_bits==0, set the result manually to prevent
// division errors.
//EXTRA_WORDS_DC is the number of words added to write_words
// due to FWFT.
//This value is only a temporary value and not used in the code.
num_write_words_dc = (num_wr_bits==0) ? EXTRA_WORDS_DC : (((num_wr_bits-1)/C_DIN_WIDTH)+1) + EXTRA_WORDS_DC ;
//Trim the write words for use with WR_DATA_COUNT
num_write_words_sized_i =
num_write_words_dc[C_WR_PNTR_WIDTH : C_WR_PNTR_WIDTH-C_WR_DATA_COUNT_WIDTH+1];
end else begin
//Calculate the Data Count value for the number of write words, when NOT
// using First-Word Fall-Through with extra logic for Data Counts. This
// calculates only the number of words in the internal FIFO.
//The expression (((A-1)/B))+1 divides A/B, but takes the
// ceiling of the result.
//This value is scaled to the Write Domain.
//When num_wr_bits==0, set the result manually to prevent
// division errors.
//This value is only a temporary value and not used in the code.
num_write_words_dc = (num_wr_bits==0) ? 0 : ((num_wr_bits-1)/C_DIN_WIDTH)+1;
//Trim the read words for use with RD_DATA_COUNT
num_write_words_sized_i =
num_write_words_dc[C_WR_PNTR_WIDTH-1 : C_WR_PNTR_WIDTH-C_WR_DATA_COUNT_WIDTH];
end //if (C_USE_FWFT_DATA_COUNT)
end //always
/*************************************************************************
* Write and Read Logic
************************************************************************/
wire write_allow;
wire read_allow;
wire read_allow_dc;
wire write_only;
wire read_only;
//wire write_only_q;
reg write_only_q;
//wire read_only_q;
reg read_only_q;
reg full_reg;
reg rst_full_ff_reg1;
reg rst_full_ff_reg2;
wire ram_full_comb;
wire carry;
assign write_allow = WR_EN & ~full_i;
assign read_allow = RD_EN & ~empty_i;
assign read_allow_dc = RD_EN_USER & ~USER_EMPTY_FB;
//assign write_only = write_allow & ~read_allow;
//assign write_only_q = write_allow_q;
//assign read_only = read_allow & ~write_allow;
//assign read_only_q = read_allow_q ;
wire [C_WR_PNTR_WIDTH-1:0] diff_pntr;
wire [C_RD_PNTR_WIDTH-1:0] diff_pntr_pe;
reg [C_WR_PNTR_WIDTH-1:0] diff_pntr_reg1 = 0;
reg [C_RD_PNTR_WIDTH-1:0] diff_pntr_pe_reg1 = 0;
reg [C_RD_PNTR_WIDTH:0] diff_pntr_pe_asym = 0;
wire [C_RD_PNTR_WIDTH:0] adj_wr_pntr_rd_asym ;
wire [C_RD_PNTR_WIDTH:0] rd_pntr_asym;
reg [C_WR_PNTR_WIDTH-1:0] diff_pntr_reg2 = 0;
reg [C_WR_PNTR_WIDTH-1:0] diff_pntr_pe_reg2 = 0;
wire [C_RD_PNTR_WIDTH-1:0] diff_pntr_pe_max;
wire [C_RD_PNTR_WIDTH-1:0] diff_pntr_max;
assign diff_pntr_pe_max = DIFF_MAX_RD;
assign diff_pntr_max = DIFF_MAX_WR;
generate if (IS_ASYMMETRY == 0) begin : diff_pntr_sym
assign write_only = write_allow & ~read_allow;
assign read_only = read_allow & ~write_allow;
end endgenerate
generate if ( IS_ASYMMETRY == 1 && C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : wr_grt_rd
assign read_only = read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0]) & ~write_allow;
assign write_only = write_allow & ~(read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0]));
end endgenerate
generate if (IS_ASYMMETRY ==1 && C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : rd_grt_wr
assign read_only = read_allow & ~(write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0]));
assign write_only = write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0]) & ~read_allow;
end endgenerate
//-----------------------------------------------------------------------------
// Write and Read pointer generation
//-----------------------------------------------------------------------------
always @(posedge CLK or posedge rst_i) begin
if (rst_i) begin
wr_pntr <= 0;
rd_pntr <= 0;
end else begin
if (srst_i || srst_wrst_busy || srst_rrst_busy ) begin
if (srst_wrst_busy)
wr_pntr <= #`TCQ 0;
if (srst_rrst_busy)
rd_pntr <= #`TCQ 0;
end else begin
if (write_allow) wr_pntr <= #`TCQ wr_pntr + 1;
if (read_allow) rd_pntr <= #`TCQ rd_pntr + 1;
end
end
end
generate if (C_FIFO_TYPE == 2) begin : gll_dm_dout
always @(posedge CLK) begin
if (write_allow) begin
if (ENABLE_ERR_INJECTION == 1)
memory[wr_pntr] <= #`TCQ {INJECTDBITERR,INJECTSBITERR,DIN};
else
memory[wr_pntr] <= #`TCQ DIN;
end
end
reg [C_DATA_WIDTH-1:0] dout_tmp_q;
reg [C_DATA_WIDTH-1:0] dout_tmp = 0;
reg [C_DATA_WIDTH-1:0] dout_tmp1 = 0;
always @(posedge CLK) begin
dout_tmp_q <= #`TCQ ideal_dout;
end
always @* begin
if (read_allow)
ideal_dout <= memory[rd_pntr];
else
ideal_dout <= dout_tmp_q;
end
end endgenerate // gll_dm_dout
/**************************************************************************
* Write Domain Logic
**************************************************************************/
assign ram_rd_en = RD_EN & !EMPTY;
//reg [C_WR_PNTR_WIDTH-1:0] diff_pntr = 0;
generate if (C_FIFO_TYPE != 2) begin : gnll_din
always @(posedge CLK or posedge rst_i) begin : gen_fifo_w
/****** Reset fifo (case 1)***************************************/
if (rst_i == 1'b1) begin
num_wr_bits <= #`TCQ 0;
next_num_wr_bits = #`TCQ 0;
wr_ptr <= #`TCQ C_WR_DEPTH - 1;
rd_ptr_wrclk <= #`TCQ C_RD_DEPTH - 1;
ideal_wr_ack <= #`TCQ 0;
ideal_wr_count <= #`TCQ 0;
tmp_wr_listsize = #`TCQ 0;
rd_ptr_wrclk_next <= #`TCQ 0;
wr_pntr <= #`TCQ 0;
wr_pntr_rd1 <= #`TCQ 0;
end else begin //rst_i==0
if (srst_wrst_busy) begin
num_wr_bits <= #`TCQ 0;
next_num_wr_bits = #`TCQ 0;
wr_ptr <= #`TCQ C_WR_DEPTH - 1;
rd_ptr_wrclk <= #`TCQ C_RD_DEPTH - 1;
ideal_wr_ack <= #`TCQ 0;
ideal_wr_count <= #`TCQ 0;
tmp_wr_listsize = #`TCQ 0;
rd_ptr_wrclk_next <= #`TCQ 0;
wr_pntr <= #`TCQ 0;
wr_pntr_rd1 <= #`TCQ 0;
end else begin//srst_i=0
wr_pntr_rd1 <= #`TCQ wr_pntr;
//Determine the current number of words in the FIFO
tmp_wr_listsize = (C_DEPTH_RATIO_RD > 1) ? num_wr_bits/C_DOUT_WIDTH :
num_wr_bits/C_DIN_WIDTH;
rd_ptr_wrclk_next = rd_ptr;
if (rd_ptr_wrclk < rd_ptr_wrclk_next) begin
next_num_wr_bits = num_wr_bits -
C_DOUT_WIDTH*(rd_ptr_wrclk + C_RD_DEPTH
- rd_ptr_wrclk_next);
end else begin
next_num_wr_bits = num_wr_bits -
C_DOUT_WIDTH*(rd_ptr_wrclk - rd_ptr_wrclk_next);
end
if (WR_EN == 1'b1) begin
if (FULL == 1'b1) begin
ideal_wr_ack <= #`TCQ 0;
//Reminder that FIFO is still full
ideal_wr_count <= #`TCQ num_write_words_sized_i;
end else begin
write_fifo;
next_num_wr_bits = next_num_wr_bits + C_DIN_WIDTH;
//Write successful, so issue acknowledge
// and no error
ideal_wr_ack <= #`TCQ 1;
//Not even close to full.
ideal_wr_count <= num_write_words_sized_i;
//end
end
end else begin //(WR_EN == 1'b1)
//If user did not attempt a write, then do not
// give ack or err
ideal_wr_ack <= #`TCQ 0;
ideal_wr_count <= #`TCQ num_write_words_sized_i;
end
num_wr_bits <= #`TCQ next_num_wr_bits;
rd_ptr_wrclk <= #`TCQ rd_ptr;
end //srst_i==0
end //wr_rst_i==0
end // gen_fifo_w
end endgenerate
generate if (C_FIFO_TYPE < 2 && C_MEMORY_TYPE < 2) begin : gnll_dm_dout
always @(posedge CLK) begin
if (rst_i || srst_rrst_busy) begin
if (C_USE_DOUT_RST == 1)
ideal_dout <= #`TCQ dout_reset_val;
end
end
end endgenerate
generate if (C_FIFO_TYPE != 2) begin : gnll_dout
always @(posedge CLK or posedge rst_i) begin : gen_fifo_r
/****** Reset fifo (case 1)***************************************/
if (rst_i) begin
num_rd_bits <= #`TCQ 0;
next_num_rd_bits = #`TCQ 0;
rd_ptr <= #`TCQ C_RD_DEPTH -1;
rd_pntr <= #`TCQ 0;
//rd_pntr_wr1 <= #`TCQ 0;
wr_ptr_rdclk <= #`TCQ C_WR_DEPTH -1;
// DRAM resets asynchronously
if (C_FIFO_TYPE < 2 && (C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3 )&& C_USE_DOUT_RST == 1)
ideal_dout <= #`TCQ dout_reset_val;
// Reset err_type only if ECC is not selected
if (C_USE_ECC == 0)
err_type <= #`TCQ 0;
ideal_valid <= #`TCQ 1'b0;
ideal_rd_count <= #`TCQ 0;
end else begin //rd_rst_i==0
if (srst_rrst_busy) begin
num_rd_bits <= #`TCQ 0;
next_num_rd_bits = #`TCQ 0;
rd_ptr <= #`TCQ C_RD_DEPTH -1;
rd_pntr <= #`TCQ 0;
//rd_pntr_wr1 <= #`TCQ 0;
wr_ptr_rdclk <= #`TCQ C_WR_DEPTH -1;
// DRAM resets synchronously
if (C_FIFO_TYPE < 2 && (C_MEMORY_TYPE == 2 || C_MEMORY_TYPE == 3 )&& C_USE_DOUT_RST == 1)
ideal_dout <= #`TCQ dout_reset_val;
// Reset err_type only if ECC is not selected
if (C_USE_ECC == 0)
err_type <= #`TCQ 0;
ideal_valid <= #`TCQ 1'b0;
ideal_rd_count <= #`TCQ 0;
end //srst_i
else begin
//rd_pntr_wr1 <= #`TCQ rd_pntr;
//Determine the current number of words in the FIFO
tmp_rd_listsize = (C_DEPTH_RATIO_WR > 1) ? num_rd_bits/C_DIN_WIDTH :
num_rd_bits/C_DOUT_WIDTH;
wr_ptr_rdclk_next = wr_ptr;
if (wr_ptr_rdclk < wr_ptr_rdclk_next) begin
next_num_rd_bits = num_rd_bits +
C_DIN_WIDTH*(wr_ptr_rdclk +C_WR_DEPTH
- wr_ptr_rdclk_next);
end else begin
next_num_rd_bits = num_rd_bits +
C_DIN_WIDTH*(wr_ptr_rdclk - wr_ptr_rdclk_next);
end
if (RD_EN == 1'b1) begin
if (EMPTY == 1'b1) begin
ideal_valid <= #`TCQ 1'b0;
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end
else
begin
read_fifo;
next_num_rd_bits = next_num_rd_bits - C_DOUT_WIDTH;
//Acknowledge the read from the FIFO, no error
ideal_valid <= #`TCQ 1'b1;
ideal_rd_count <= #`TCQ num_read_words_sized_i;
end // if (tmp_rd_listsize == 2)
end
num_rd_bits <= #`TCQ next_num_rd_bits;
wr_ptr_rdclk <= #`TCQ wr_ptr;
end //s_rst_i==0
end //rd_rst_i==0
end //always
end endgenerate
//-----------------------------------------------------------------------------
// Generate diff_pntr for PROG_FULL generation
// Generate diff_pntr_pe for PROG_EMPTY generation
//-----------------------------------------------------------------------------
generate if ((C_PROG_FULL_TYPE != 0 || C_PROG_EMPTY_TYPE != 0) && IS_ASYMMETRY == 0) begin : reg_write_allow
always @(posedge CLK ) begin
if (rst_i) begin
write_only_q <= 1'b0;
read_only_q <= 1'b0;
diff_pntr_reg1 <= 0;
diff_pntr_pe_reg1 <= 0;
diff_pntr_reg2 <= 0;
diff_pntr_pe_reg2 <= 0;
end else begin
if (srst_i || srst_wrst_busy || srst_rrst_busy) begin
if (srst_rrst_busy) begin
read_only_q <= #`TCQ 1'b0;
diff_pntr_pe_reg1 <= #`TCQ 0;
diff_pntr_pe_reg2 <= #`TCQ 0;
end
if (srst_wrst_busy) begin
write_only_q <= #`TCQ 1'b0;
diff_pntr_reg1 <= #`TCQ 0;
diff_pntr_reg2 <= #`TCQ 0;
end
end else begin
write_only_q <= #`TCQ write_only;
read_only_q <= #`TCQ read_only;
diff_pntr_reg2 <= #`TCQ diff_pntr_reg1;
diff_pntr_pe_reg2 <= #`TCQ diff_pntr_pe_reg1;
// Add 1 to the difference pointer value when only write happens.
if (write_only)
diff_pntr_reg1 <= #`TCQ wr_pntr - adj_rd_pntr_wr + 1;
else
diff_pntr_reg1 <= #`TCQ wr_pntr - adj_rd_pntr_wr;
// Add 1 to the difference pointer value when write or both write & read or no write & read happen.
if (read_only)
diff_pntr_pe_reg1 <= #`TCQ adj_wr_pntr_rd - rd_pntr - 1;
else
diff_pntr_pe_reg1 <= #`TCQ adj_wr_pntr_rd - rd_pntr;
end
end
end
assign diff_pntr_pe = diff_pntr_pe_reg1;
assign diff_pntr = diff_pntr_reg1;
end endgenerate // reg_write_allow
generate if ((C_PROG_FULL_TYPE != 0 || C_PROG_EMPTY_TYPE != 0) && IS_ASYMMETRY == 1) begin : reg_write_allow_asym
assign adj_wr_pntr_rd_asym[C_RD_PNTR_WIDTH:0] = {adj_wr_pntr_rd,1'b1};
assign rd_pntr_asym[C_RD_PNTR_WIDTH:0] = {~rd_pntr,1'b1};
always @(posedge CLK ) begin
if (rst_i) begin
diff_pntr_pe_asym <= 0;
diff_pntr_reg1 <= 0;
full_reg <= 0;
rst_full_ff_reg1 <= 1;
rst_full_ff_reg2 <= 1;
diff_pntr_pe_reg1 <= 0;
end else begin
if (srst_i || srst_wrst_busy || srst_rrst_busy) begin
if (srst_wrst_busy)
diff_pntr_reg1 <= #`TCQ 0;
if (srst_rrst_busy)
full_reg <= #`TCQ 0;
rst_full_ff_reg1 <= #`TCQ 1;
rst_full_ff_reg2 <= #`TCQ 1;
diff_pntr_pe_asym <= #`TCQ 0;
diff_pntr_pe_reg1 <= #`TCQ 0;
end else begin
diff_pntr_pe_asym <= #`TCQ adj_wr_pntr_rd_asym + rd_pntr_asym;
full_reg <= #`TCQ full_i;
rst_full_ff_reg1 <= #`TCQ RST_FULL_FF;
rst_full_ff_reg2 <= #`TCQ rst_full_ff_reg1;
if (~full_i) begin
diff_pntr_reg1 <= #`TCQ wr_pntr - adj_rd_pntr_wr;
end
end
end
end
assign carry = (~(|(diff_pntr_pe_asym [C_RD_PNTR_WIDTH : 1])));
assign diff_pntr_pe = (full_reg && ~rst_full_ff_reg2 && carry ) ? diff_pntr_pe_max : diff_pntr_pe_asym[C_RD_PNTR_WIDTH:1];
assign diff_pntr = diff_pntr_reg1;
end endgenerate // reg_write_allow_asym
//-----------------------------------------------------------------------------
// Generate FULL flag
//-----------------------------------------------------------------------------
wire comp0;
wire comp1;
wire going_full;
wire leaving_full;
generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : gpad
assign adj_rd_pntr_wr [C_WR_PNTR_WIDTH-1 : C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH] = rd_pntr;
assign adj_rd_pntr_wr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0] = 0;
end endgenerate
generate if (C_WR_PNTR_WIDTH <= C_RD_PNTR_WIDTH) begin : gtrim
assign adj_rd_pntr_wr = rd_pntr[C_RD_PNTR_WIDTH-1 : C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH];
end endgenerate
assign comp1 = (adj_rd_pntr_wr == (wr_pntr + 1'b1));
assign comp0 = (adj_rd_pntr_wr == wr_pntr);
generate if (C_WR_PNTR_WIDTH == C_RD_PNTR_WIDTH) begin : gf_wp_eq_rp
assign going_full = (comp1 & write_allow & ~read_allow);
assign leaving_full = (comp0 & read_allow) | RST_FULL_GEN;
end endgenerate
// Write data width is bigger than read data width
// Write depth is smaller than read depth
// One write could be equal to 2 or 4 or 8 reads
generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : gf_asym
assign going_full = (comp1 & write_allow & (~ (read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0]))));
assign leaving_full = (comp0 & read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0])) | RST_FULL_GEN;
end endgenerate
generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : gf_wp_gt_rp
assign going_full = (comp1 & write_allow & ~read_allow);
assign leaving_full =(comp0 & read_allow) | RST_FULL_GEN;
end endgenerate
assign ram_full_comb = going_full | (~leaving_full & full_i);
always @(posedge CLK or posedge RST_FULL_FF) begin
if (RST_FULL_FF)
full_i <= C_FULL_FLAGS_RST_VAL;
else if (srst_wrst_busy)
full_i <= #`TCQ C_FULL_FLAGS_RST_VAL;
else
full_i <= #`TCQ ram_full_comb;
end
//-----------------------------------------------------------------------------
// Generate EMPTY flag
//-----------------------------------------------------------------------------
wire ecomp0;
wire ecomp1;
wire going_empty;
wire leaving_empty;
wire ram_empty_comb;
generate if (C_RD_PNTR_WIDTH > C_WR_PNTR_WIDTH) begin : pad
assign adj_wr_pntr_rd [C_RD_PNTR_WIDTH-1 : C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH] = wr_pntr;
assign adj_wr_pntr_rd[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0] = 0;
end endgenerate
generate if (C_RD_PNTR_WIDTH <= C_WR_PNTR_WIDTH) begin : trim
assign adj_wr_pntr_rd = wr_pntr[C_WR_PNTR_WIDTH-1 : C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH];
end endgenerate
assign ecomp1 = (adj_wr_pntr_rd == (rd_pntr + 1'b1));
assign ecomp0 = (adj_wr_pntr_rd == rd_pntr);
generate if (C_WR_PNTR_WIDTH == C_RD_PNTR_WIDTH) begin : ge_wp_eq_rp
assign going_empty = (ecomp1 & ~write_allow & read_allow);
assign leaving_empty = (ecomp0 & write_allow);
end endgenerate
generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : ge_wp_gt_rp
assign going_empty = (ecomp1 & read_allow & (~(write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0]))));
assign leaving_empty = (ecomp0 & write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0]));
end endgenerate
generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : ge_wp_lt_rp
assign going_empty = (ecomp1 & ~write_allow & read_allow);
assign leaving_empty =(ecomp0 & write_allow);
end endgenerate
assign ram_empty_comb = going_empty | (~leaving_empty & empty_i);
always @(posedge CLK or posedge rst_i) begin
if (rst_i)
empty_i <= 1'b1;
else if (srst_rrst_busy)
empty_i <= #`TCQ 1'b1;
else
empty_i <= #`TCQ ram_empty_comb;
end
//-----------------------------------------------------------------------------
// Generate Read and write data counts for asymmetic common clock
//-----------------------------------------------------------------------------
reg [C_GRTR_PNTR_WIDTH :0] count_dc = 0;
wire [C_GRTR_PNTR_WIDTH :0] ratio;
wire decr_by_one;
wire incr_by_ratio;
wire incr_by_one;
wire decr_by_ratio;
localparam IS_FWFT = (C_PRELOAD_REGS == 1 && C_PRELOAD_LATENCY == 0) ? 1 : 0;
generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : rd_depth_gt_wr
assign ratio = C_DEPTH_RATIO_RD;
assign decr_by_one = (IS_FWFT == 1)? read_allow_dc : read_allow;
assign incr_by_ratio = write_allow;
always @(posedge CLK or posedge rst_i) begin
if (rst_i)
count_dc <= #`TCQ 0;
else if (srst_wrst_busy)
count_dc <= #`TCQ 0;
else begin
if (decr_by_one) begin
if (!incr_by_ratio)
count_dc <= #`TCQ count_dc - 1;
else
count_dc <= #`TCQ count_dc - 1 + ratio ;
end
else begin
if (!incr_by_ratio)
count_dc <= #`TCQ count_dc ;
else
count_dc <= #`TCQ count_dc + ratio ;
end
end
end
assign rd_data_count_i_ss[C_RD_PNTR_WIDTH : 0] = count_dc;
assign wr_data_count_i_ss[C_WR_PNTR_WIDTH : 0] = count_dc[C_RD_PNTR_WIDTH : C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH];
end endgenerate
generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : wr_depth_gt_rd
assign ratio = C_DEPTH_RATIO_WR;
assign incr_by_one = write_allow;
assign decr_by_ratio = (IS_FWFT == 1)? read_allow_dc : read_allow;
always @(posedge CLK or posedge rst_i) begin
if (rst_i)
count_dc <= #`TCQ 0;
else if (srst_wrst_busy)
count_dc <= #`TCQ 0;
else begin
if (incr_by_one) begin
if (!decr_by_ratio)
count_dc <= #`TCQ count_dc + 1;
else
count_dc <= #`TCQ count_dc + 1 - ratio ;
end
else begin
if (!decr_by_ratio)
count_dc <= #`TCQ count_dc ;
else
count_dc <= #`TCQ count_dc - ratio ;
end
end
end
assign wr_data_count_i_ss[C_WR_PNTR_WIDTH : 0] = count_dc;
assign rd_data_count_i_ss[C_RD_PNTR_WIDTH : 0] = count_dc[C_WR_PNTR_WIDTH : C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH];
end endgenerate
//-----------------------------------------------------------------------------
// Generate WR_ACK flag
//-----------------------------------------------------------------------------
always @(posedge CLK or posedge rst_i) begin
if (rst_i)
ideal_wr_ack <= 1'b0;
else if (srst_wrst_busy)
ideal_wr_ack <= #`TCQ 1'b0;
else if (WR_EN & ~full_i)
ideal_wr_ack <= #`TCQ 1'b1;
else
ideal_wr_ack <= #`TCQ 1'b0;
end
//-----------------------------------------------------------------------------
// Generate VALID flag
//-----------------------------------------------------------------------------
always @(posedge CLK or posedge rst_i) begin
if (rst_i)
ideal_valid <= 1'b0;
else if (srst_rrst_busy)
ideal_valid <= #`TCQ 1'b0;
else if (RD_EN & ~empty_i)
ideal_valid <= #`TCQ 1'b1;
else
ideal_valid <= #`TCQ 1'b0;
end
//-----------------------------------------------------------------------------
// Generate ALMOST_FULL flag
//-----------------------------------------------------------------------------
//generate if (C_HAS_ALMOST_FULL == 1 || C_PROG_FULL_TYPE > 2 || C_PROG_EMPTY_TYPE > 2) begin : gaf_ss
wire fcomp2;
wire going_afull;
wire leaving_afull;
wire ram_afull_comb;
assign fcomp2 = (adj_rd_pntr_wr == (wr_pntr + 2'h2));
generate if (C_WR_PNTR_WIDTH == C_RD_PNTR_WIDTH) begin : gaf_wp_eq_rp
assign going_afull = (fcomp2 & write_allow & ~read_allow);
assign leaving_afull = (comp1 & read_allow & ~write_allow) | RST_FULL_GEN;
end endgenerate
// Write data width is bigger than read data width
// Write depth is smaller than read depth
// One write could be equal to 2 or 4 or 8 reads
generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : gaf_asym
assign going_afull = (fcomp2 & write_allow & (~ (read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0]))));
assign leaving_afull = (comp1 & (~write_allow) & read_allow & &(rd_pntr[C_RD_PNTR_WIDTH-C_WR_PNTR_WIDTH-1 : 0])) | RST_FULL_GEN;
end endgenerate
generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : gaf_wp_gt_rp
assign going_afull = (fcomp2 & write_allow & ~read_allow);
assign leaving_afull =((comp0 | comp1 | fcomp2) & read_allow) | RST_FULL_GEN;
end endgenerate
assign ram_afull_comb = going_afull | (~leaving_afull & almost_full_i);
always @(posedge CLK or posedge RST_FULL_FF) begin
if (RST_FULL_FF)
almost_full_i <= C_FULL_FLAGS_RST_VAL;
else if (srst_wrst_busy)
almost_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL;
else
almost_full_i <= #`TCQ ram_afull_comb;
end
// end endgenerate // gaf_ss
//-----------------------------------------------------------------------------
// Generate ALMOST_EMPTY flag
//-----------------------------------------------------------------------------
//generate if (C_HAS_ALMOST_EMPTY == 1) begin : gae_ss
wire ecomp2;
wire going_aempty;
wire leaving_aempty;
wire ram_aempty_comb;
assign ecomp2 = (adj_wr_pntr_rd == (rd_pntr + 2'h2));
generate if (C_WR_PNTR_WIDTH == C_RD_PNTR_WIDTH) begin : gae_wp_eq_rp
assign going_aempty = (ecomp2 & ~write_allow & read_allow);
assign leaving_aempty = (ecomp1 & write_allow & ~read_allow);
end endgenerate
generate if (C_WR_PNTR_WIDTH > C_RD_PNTR_WIDTH) begin : gae_wp_gt_rp
assign going_aempty = (ecomp2 & read_allow & (~(write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0]))));
assign leaving_aempty = (ecomp1 & ~read_allow & write_allow & &(wr_pntr[C_WR_PNTR_WIDTH-C_RD_PNTR_WIDTH-1 : 0]));
end endgenerate
generate if (C_WR_PNTR_WIDTH < C_RD_PNTR_WIDTH) begin : gae_wp_lt_rp
assign going_aempty = (ecomp2 & ~write_allow & read_allow);
assign leaving_aempty =((ecomp2 | ecomp1 |ecomp0) & write_allow);
end endgenerate
assign ram_aempty_comb = going_aempty | (~leaving_aempty & almost_empty_i);
always @(posedge CLK or posedge rst_i) begin
if (rst_i)
almost_empty_i <= 1'b1;
else if (srst_rrst_busy)
almost_empty_i <= #`TCQ 1'b1;
else
almost_empty_i <= #`TCQ ram_aempty_comb;
end
// end endgenerate // gae_ss
//-----------------------------------------------------------------------------
// Generate PROG_FULL
//-----------------------------------------------------------------------------
localparam C_PF_ASSERT_VAL = (C_PRELOAD_LATENCY == 0) ?
C_PROG_FULL_THRESH_ASSERT_VAL - EXTRA_WORDS_PF_PARAM : // FWFT
C_PROG_FULL_THRESH_ASSERT_VAL; // STD
localparam C_PF_NEGATE_VAL = (C_PRELOAD_LATENCY == 0) ?
C_PROG_FULL_THRESH_NEGATE_VAL - EXTRA_WORDS_PF_PARAM: // FWFT
C_PROG_FULL_THRESH_NEGATE_VAL; // STD
//-----------------------------------------------------------------------------
// Generate PROG_FULL for single programmable threshold constant
//-----------------------------------------------------------------------------
wire [C_WR_PNTR_WIDTH-1:0] temp = C_PF_ASSERT_VAL;
generate if (C_PROG_FULL_TYPE == 1) begin : single_pf_const
always @(posedge CLK or posedge RST_FULL_FF) begin
if (RST_FULL_FF && C_HAS_RST)
prog_full_i <= C_FULL_FLAGS_RST_VAL;
else begin
if (srst_wrst_busy)
prog_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL;
else if (IS_ASYMMETRY == 0) begin
if (RST_FULL_GEN)
prog_full_i <= #`TCQ 1'b0;
else if (diff_pntr == C_PF_ASSERT_VAL && write_only_q)
prog_full_i <= #`TCQ 1'b1;
else if (diff_pntr == C_PF_ASSERT_VAL && read_only_q)
prog_full_i <= #`TCQ 1'b0;
else
prog_full_i <= #`TCQ prog_full_i;
end
else begin
if (RST_FULL_GEN)
prog_full_i <= #`TCQ 1'b0;
else if (~RST_FULL_GEN ) begin
if (diff_pntr>= C_PF_ASSERT_VAL )
prog_full_i <= #`TCQ 1'b1;
else if ((diff_pntr) < C_PF_ASSERT_VAL )
prog_full_i <= #`TCQ 1'b0;
else
prog_full_i <= #`TCQ 1'b0;
end
else
prog_full_i <= #`TCQ prog_full_i;
end
end
end
end endgenerate // single_pf_const
//-----------------------------------------------------------------------------
// Generate PROG_FULL for multiple programmable threshold constants
//-----------------------------------------------------------------------------
generate if (C_PROG_FULL_TYPE == 2) begin : multiple_pf_const
always @(posedge CLK or posedge RST_FULL_FF) begin
//if (RST_FULL_FF)
if (RST_FULL_FF && C_HAS_RST)
prog_full_i <= C_FULL_FLAGS_RST_VAL;
else begin
if (srst_wrst_busy)
prog_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL;
else if (IS_ASYMMETRY == 0) begin
if (RST_FULL_GEN)
prog_full_i <= #`TCQ 1'b0;
else if (diff_pntr == C_PF_ASSERT_VAL && write_only_q)
prog_full_i <= #`TCQ 1'b1;
else if (diff_pntr == C_PF_NEGATE_VAL && read_only_q)
prog_full_i <= #`TCQ 1'b0;
else
prog_full_i <= #`TCQ prog_full_i;
end
else begin
if (RST_FULL_GEN)
prog_full_i <= #`TCQ 1'b0;
else if (~RST_FULL_GEN ) begin
if (diff_pntr >= C_PF_ASSERT_VAL )
prog_full_i <= #`TCQ 1'b1;
else if (diff_pntr < C_PF_NEGATE_VAL)
prog_full_i <= #`TCQ 1'b0;
else
prog_full_i <= #`TCQ prog_full_i;
end
else
prog_full_i <= #`TCQ prog_full_i;
end
end
end
end endgenerate //multiple_pf_const
//-----------------------------------------------------------------------------
// Generate PROG_FULL for single programmable threshold input port
//-----------------------------------------------------------------------------
wire [C_WR_PNTR_WIDTH-1:0] pf3_assert_val = (C_PRELOAD_LATENCY == 0) ?
PROG_FULL_THRESH - EXTRA_WORDS_PF: // FWFT
PROG_FULL_THRESH; // STD
generate if (C_PROG_FULL_TYPE == 3) begin : single_pf_input
always @(posedge CLK or posedge RST_FULL_FF) begin//0
//if (RST_FULL_FF)
if (RST_FULL_FF && C_HAS_RST)
prog_full_i <= C_FULL_FLAGS_RST_VAL;
else begin //1
if (srst_wrst_busy)
prog_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL;
else if (IS_ASYMMETRY == 0) begin//2
if (RST_FULL_GEN)
prog_full_i <= #`TCQ 1'b0;
else if (~almost_full_i) begin//3
if (diff_pntr > pf3_assert_val)
prog_full_i <= #`TCQ 1'b1;
else if (diff_pntr == pf3_assert_val) begin//4
if (read_only_q)
prog_full_i <= #`TCQ 1'b0;
else
prog_full_i <= #`TCQ 1'b1;
end else//4
prog_full_i <= #`TCQ 1'b0;
end else//3
prog_full_i <= #`TCQ prog_full_i;
end //2
else begin//5
if (RST_FULL_GEN)
prog_full_i <= #`TCQ 1'b0;
else if (~full_i ) begin//6
if (diff_pntr >= pf3_assert_val )
prog_full_i <= #`TCQ 1'b1;
else if (diff_pntr < pf3_assert_val) begin//7
prog_full_i <= #`TCQ 1'b0;
end//7
end//6
else
prog_full_i <= #`TCQ prog_full_i;
end//5
end//1
end//0
end endgenerate //single_pf_input
//-----------------------------------------------------------------------------
// Generate PROG_FULL for multiple programmable threshold input ports
//-----------------------------------------------------------------------------
wire [C_WR_PNTR_WIDTH-1:0] pf_assert_val = (C_PRELOAD_LATENCY == 0) ?
(PROG_FULL_THRESH_ASSERT -EXTRA_WORDS_PF) : // FWFT
PROG_FULL_THRESH_ASSERT; // STD
wire [C_WR_PNTR_WIDTH-1:0] pf_negate_val = (C_PRELOAD_LATENCY == 0) ?
(PROG_FULL_THRESH_NEGATE -EXTRA_WORDS_PF) : // FWFT
PROG_FULL_THRESH_NEGATE; // STD
generate if (C_PROG_FULL_TYPE == 4) begin : multiple_pf_inputs
always @(posedge CLK or posedge RST_FULL_FF) begin
if (RST_FULL_FF && C_HAS_RST)
prog_full_i <= C_FULL_FLAGS_RST_VAL;
else begin
if (srst_wrst_busy)
prog_full_i <= #`TCQ C_FULL_FLAGS_RST_VAL;
else if (IS_ASYMMETRY == 0) begin
if (RST_FULL_GEN)
prog_full_i <= #`TCQ 1'b0;
else if (~almost_full_i) begin
if (diff_pntr >= pf_assert_val)
prog_full_i <= #`TCQ 1'b1;
else if ((diff_pntr == pf_negate_val && read_only_q) ||
diff_pntr < pf_negate_val)
prog_full_i <= #`TCQ 1'b0;
else
prog_full_i <= #`TCQ prog_full_i;
end else
prog_full_i <= #`TCQ prog_full_i;
end
else begin
if (RST_FULL_GEN)
prog_full_i <= #`TCQ 1'b0;
else if (~full_i ) begin
if (diff_pntr >= pf_assert_val )
prog_full_i <= #`TCQ 1'b1;
else if (diff_pntr < pf_negate_val)
prog_full_i <= #`TCQ 1'b0;
else
prog_full_i <= #`TCQ prog_full_i;
end
else
prog_full_i <= #`TCQ prog_full_i;
end
end
end
end endgenerate //multiple_pf_inputs
//-----------------------------------------------------------------------------
// Generate PROG_EMPTY
//-----------------------------------------------------------------------------
localparam C_PE_ASSERT_VAL = (C_PRELOAD_LATENCY == 0) ?
C_PROG_EMPTY_THRESH_ASSERT_VAL - 2: // FWFT
C_PROG_EMPTY_THRESH_ASSERT_VAL; // STD
localparam C_PE_NEGATE_VAL = (C_PRELOAD_LATENCY == 0) ?
C_PROG_EMPTY_THRESH_NEGATE_VAL - 2: // FWFT
C_PROG_EMPTY_THRESH_NEGATE_VAL; // STD
//-----------------------------------------------------------------------------
// Generate PROG_EMPTY for single programmable threshold constant
//-----------------------------------------------------------------------------
generate if (C_PROG_EMPTY_TYPE == 1) begin : single_pe_const
always @(posedge CLK or posedge rst_i) begin
//if (rst_i)
if (rst_i && C_HAS_RST)
prog_empty_i <= 1'b1;
else begin
if (srst_rrst_busy)
prog_empty_i <= #`TCQ 1'b1;
else if (IS_ASYMMETRY == 0) begin
if (diff_pntr_pe == C_PE_ASSERT_VAL && read_only_q)
prog_empty_i <= #`TCQ 1'b1;
else if (diff_pntr_pe == C_PE_ASSERT_VAL && write_only_q)
prog_empty_i <= #`TCQ 1'b0;
else
prog_empty_i <= #`TCQ prog_empty_i;
end
else begin
if (~rst_i ) begin
if (diff_pntr_pe <= C_PE_ASSERT_VAL)
prog_empty_i <= #`TCQ 1'b1;
else if (diff_pntr_pe > C_PE_ASSERT_VAL)
prog_empty_i <= #`TCQ 1'b0;
end
else
prog_empty_i <= #`TCQ prog_empty_i;
end
end
end
end endgenerate // single_pe_const
//-----------------------------------------------------------------------------
// Generate PROG_EMPTY for multiple programmable threshold constants
//-----------------------------------------------------------------------------
generate if (C_PROG_EMPTY_TYPE == 2) begin : multiple_pe_const
always @(posedge CLK or posedge rst_i) begin
//if (rst_i)
if (rst_i && C_HAS_RST)
prog_empty_i <= 1'b1;
else begin
if (srst_rrst_busy)
prog_empty_i <= #`TCQ 1'b1;
else if (IS_ASYMMETRY == 0) begin
if (diff_pntr_pe == C_PE_ASSERT_VAL && read_only_q)
prog_empty_i <= #`TCQ 1'b1;
else if (diff_pntr_pe == C_PE_NEGATE_VAL && write_only_q)
prog_empty_i <= #`TCQ 1'b0;
else
prog_empty_i <= #`TCQ prog_empty_i;
end
else begin
if (~rst_i ) begin
if (diff_pntr_pe <= C_PE_ASSERT_VAL )
prog_empty_i <= #`TCQ 1'b1;
else if (diff_pntr_pe > C_PE_NEGATE_VAL)
prog_empty_i <= #`TCQ 1'b0;
else
prog_empty_i <= #`TCQ prog_empty_i;
end
else
prog_empty_i <= #`TCQ prog_empty_i;
end
end
end
end endgenerate //multiple_pe_const
//-----------------------------------------------------------------------------
// Generate PROG_EMPTY for single programmable threshold input port
//-----------------------------------------------------------------------------
wire [C_RD_PNTR_WIDTH-1:0] pe3_assert_val = (C_PRELOAD_LATENCY == 0) ?
(PROG_EMPTY_THRESH -2) : // FWFT
PROG_EMPTY_THRESH; // STD
generate if (C_PROG_EMPTY_TYPE == 3) begin : single_pe_input
always @(posedge CLK or posedge rst_i) begin
//if (rst_i)
if (rst_i && C_HAS_RST)
prog_empty_i <= 1'b1;
else begin
if (srst_rrst_busy)
prog_empty_i <= #`TCQ 1'b1;
else if (IS_ASYMMETRY == 0) begin
if (~almost_full_i) begin
if (diff_pntr_pe < pe3_assert_val)
prog_empty_i <= #`TCQ 1'b1;
else if (diff_pntr_pe == pe3_assert_val) begin
if (write_only_q)
prog_empty_i <= #`TCQ 1'b0;
else
prog_empty_i <= #`TCQ 1'b1;
end else
prog_empty_i <= #`TCQ 1'b0;
end else
prog_empty_i <= #`TCQ prog_empty_i;
end
else begin
if (diff_pntr_pe <= pe3_assert_val )
prog_empty_i <= #`TCQ 1'b1;
else if (diff_pntr_pe > pe3_assert_val)
prog_empty_i <= #`TCQ 1'b0;
else
prog_empty_i <= #`TCQ prog_empty_i;
end
end
end
end endgenerate // single_pe_input
//-----------------------------------------------------------------------------
// Generate PROG_EMPTY for multiple programmable threshold input ports
//-----------------------------------------------------------------------------
wire [C_RD_PNTR_WIDTH-1:0] pe4_assert_val = (C_PRELOAD_LATENCY == 0) ?
(PROG_EMPTY_THRESH_ASSERT - 2) : // FWFT
PROG_EMPTY_THRESH_ASSERT; // STD
wire [C_RD_PNTR_WIDTH-1:0] pe4_negate_val = (C_PRELOAD_LATENCY == 0) ?
(PROG_EMPTY_THRESH_NEGATE - 2) : // FWFT
PROG_EMPTY_THRESH_NEGATE; // STD
generate if (C_PROG_EMPTY_TYPE == 4) begin : multiple_pe_inputs
always @(posedge CLK or posedge rst_i) begin
//if (rst_i)
if (rst_i && C_HAS_RST)
prog_empty_i <= 1'b1;
else begin
if (srst_rrst_busy)
prog_empty_i <= #`TCQ 1'b1;
else if (IS_ASYMMETRY == 0) begin
if (~almost_full_i) begin
if (diff_pntr_pe <= pe4_assert_val)
prog_empty_i <= #`TCQ 1'b1;
else if (((diff_pntr_pe == pe4_negate_val) && write_only_q) ||
(diff_pntr_pe > pe4_negate_val)) begin
prog_empty_i <= #`TCQ 1'b0;
end else
prog_empty_i <= #`TCQ prog_empty_i;
end else
prog_empty_i <= #`TCQ prog_empty_i;
end
else begin
if (diff_pntr_pe <= pe4_assert_val )
prog_empty_i <= #`TCQ 1'b1;
else if (diff_pntr_pe > pe4_negate_val)
prog_empty_i <= #`TCQ 1'b0;
else
prog_empty_i <= #`TCQ prog_empty_i;
end
end
end
end endgenerate // multiple_pe_inputs
endmodule // fifo_generator_v12_0_bhv_ver_ss
/**************************************************************************
* First-Word Fall-Through module (preload 0)
**************************************************************************/
module fifo_generator_v12_0_bhv_ver_preload0
#(
parameter C_DOUT_RST_VAL = "",
parameter C_DOUT_WIDTH = 8,
parameter C_HAS_RST = 0,
parameter C_ENABLE_RST_SYNC = 0,
parameter C_HAS_SRST = 0,
parameter C_USE_DOUT_RST = 0,
parameter C_USE_ECC = 0,
parameter C_USERVALID_LOW = 0,
parameter C_USERUNDERFLOW_LOW = 0,
parameter C_MEMORY_TYPE = 0,
parameter C_FIFO_TYPE = 0
)
(
//Inputs
input RD_CLK,
input RD_RST,
input SRST,
input WR_RST_BUSY,
input RD_RST_BUSY,
input RD_EN,
input FIFOEMPTY,
input [C_DOUT_WIDTH-1:0] FIFODATA,
input FIFOSBITERR,
input FIFODBITERR,
//Outputs
output reg [C_DOUT_WIDTH-1:0] USERDATA,
output USERVALID,
output USERUNDERFLOW,
output USEREMPTY,
output USERALMOSTEMPTY,
output RAMVALID,
output FIFORDEN,
output reg USERSBITERR,
output reg USERDBITERR,
output reg STAGE2_REG_EN,
output [1:0] VALID_STAGES
);
//Internal signals
wire preloadstage1;
wire preloadstage2;
reg ram_valid_i;
reg read_data_valid_i;
wire ram_regout_en;
wire ram_rd_en;
reg empty_i = 1'b1;
reg empty_q = 1'b1;
reg rd_en_q = 1'b0;
reg almost_empty_i = 1'b1;
reg almost_empty_q = 1'b1;
wire rd_rst_i;
wire srst_i;
/*************************************************************************
* FUNCTIONS
*************************************************************************/
/*************************************************************************
* hexstr_conv
* Converts a string of type hex to a binary value (for C_DOUT_RST_VAL)
***********************************************************************/
function [C_DOUT_WIDTH-1:0] hexstr_conv;
input [(C_DOUT_WIDTH*8)-1:0] def_data;
integer index,i,j;
reg [3:0] bin;
begin
index = 0;
hexstr_conv = 'b0;
for( i=C_DOUT_WIDTH-1; i>=0; i=i-1 )
begin
case (def_data[7:0])
8'b00000000 :
begin
bin = 4'b0000;
i = -1;
end
8'b00110000 : bin = 4'b0000;
8'b00110001 : bin = 4'b0001;
8'b00110010 : bin = 4'b0010;
8'b00110011 : bin = 4'b0011;
8'b00110100 : bin = 4'b0100;
8'b00110101 : bin = 4'b0101;
8'b00110110 : bin = 4'b0110;
8'b00110111 : bin = 4'b0111;
8'b00111000 : bin = 4'b1000;
8'b00111001 : bin = 4'b1001;
8'b01000001 : bin = 4'b1010;
8'b01000010 : bin = 4'b1011;
8'b01000011 : bin = 4'b1100;
8'b01000100 : bin = 4'b1101;
8'b01000101 : bin = 4'b1110;
8'b01000110 : bin = 4'b1111;
8'b01100001 : bin = 4'b1010;
8'b01100010 : bin = 4'b1011;
8'b01100011 : bin = 4'b1100;
8'b01100100 : bin = 4'b1101;
8'b01100101 : bin = 4'b1110;
8'b01100110 : bin = 4'b1111;
default :
begin
bin = 4'bx;
end
endcase
for( j=0; j<4; j=j+1)
begin
if ((index*4)+j < C_DOUT_WIDTH)
begin
hexstr_conv[(index*4)+j] = bin[j];
end
end
index = index + 1;
def_data = def_data >> 8;
end
end
endfunction
//*************************************************************************
// Set power-on states for regs
//*************************************************************************
initial begin
ram_valid_i = 1'b0;
read_data_valid_i = 1'b0;
USERDATA = hexstr_conv(C_DOUT_RST_VAL);
USERSBITERR = 1'b0;
USERDBITERR = 1'b0;
end //initial
//***************************************************************************
// connect up optional reset
//***************************************************************************
assign rd_rst_i = (C_HAS_RST == 1 || C_ENABLE_RST_SYNC == 0) ? RD_RST : 0;
assign srst_i = C_HAS_SRST ? SRST || WR_RST_BUSY || RD_RST_BUSY : 0;
localparam INVALID = 0;
localparam STAGE1_VALID = 2;
localparam STAGE2_VALID = 1;
localparam BOTH_STAGES_VALID = 3;
reg [1:0] curr_fwft_state = INVALID;
reg [1:0] next_fwft_state = INVALID;
generate if (C_FIFO_TYPE != 2) begin : gnll_fifo
always @* begin
case (curr_fwft_state)
INVALID: begin
if (~FIFOEMPTY)
next_fwft_state <= STAGE1_VALID;
else
next_fwft_state <= INVALID;
end
STAGE1_VALID: begin
if (FIFOEMPTY)
next_fwft_state <= STAGE2_VALID;
else
next_fwft_state <= BOTH_STAGES_VALID;
end
STAGE2_VALID: begin
if (FIFOEMPTY && RD_EN)
next_fwft_state <= INVALID;
else if (~FIFOEMPTY && RD_EN)
next_fwft_state <= STAGE1_VALID;
else if (~FIFOEMPTY && ~RD_EN)
next_fwft_state <= BOTH_STAGES_VALID;
else
next_fwft_state <= STAGE2_VALID;
end
BOTH_STAGES_VALID: begin
if (FIFOEMPTY && RD_EN)
next_fwft_state <= STAGE2_VALID;
else if (~FIFOEMPTY && RD_EN)
next_fwft_state <= BOTH_STAGES_VALID;
else
next_fwft_state <= BOTH_STAGES_VALID;
end
default: next_fwft_state <= INVALID;
endcase
end
always @ (posedge rd_rst_i or posedge RD_CLK) begin
if (rd_rst_i)
curr_fwft_state <= INVALID;
else if (srst_i)
curr_fwft_state <= #`TCQ INVALID;
else
curr_fwft_state <= #`TCQ next_fwft_state;
end
always @* begin
case (curr_fwft_state)
INVALID: STAGE2_REG_EN <= 1'b0;
STAGE1_VALID: STAGE2_REG_EN <= 1'b1;
STAGE2_VALID: STAGE2_REG_EN <= 1'b0;
BOTH_STAGES_VALID: STAGE2_REG_EN <= RD_EN;
default: STAGE2_REG_EN <= 1'b0;
endcase
end
assign VALID_STAGES = curr_fwft_state;
//***************************************************************************
// preloadstage2 indicates that stage2 needs to be updated. This is true
// whenever read_data_valid is false, and RAM_valid is true.
//***************************************************************************
assign preloadstage2 = ram_valid_i & (~read_data_valid_i | RD_EN);
//***************************************************************************
// preloadstage1 indicates that stage1 needs to be updated. This is true
// whenever the RAM has data (RAM_EMPTY is false), and either RAM_Valid is
// false (indicating that Stage1 needs updating), or preloadstage2 is active
// (indicating that Stage2 is going to update, so Stage1, therefore, must
// also be updated to keep it valid.
//***************************************************************************
assign preloadstage1 = ((~ram_valid_i | preloadstage2) & ~FIFOEMPTY);
//***************************************************************************
// Calculate RAM_REGOUT_EN
// The output registers are controlled by the ram_regout_en signal.
// These registers should be updated either when the output in Stage2 is
// invalid (preloadstage2), OR when the user is reading, in which case the
// Stage2 value will go invalid unless it is replenished.
//***************************************************************************
assign ram_regout_en = preloadstage2;
//***************************************************************************
// Calculate RAM_RD_EN
// RAM_RD_EN will be asserted whenever the RAM needs to be read in order to
// update the value in Stage1.
// One case when this happens is when preloadstage1=true, which indicates
// that the data in Stage1 or Stage2 is invalid, and needs to automatically
// be updated.
// The other case is when the user is reading from the FIFO, which
// guarantees that Stage1 or Stage2 will be invalid on the next clock
// cycle, unless it is replinished by data from the memory. So, as long
// as the RAM has data in it, a read of the RAM should occur.
//***************************************************************************
assign ram_rd_en = (RD_EN & ~FIFOEMPTY) | preloadstage1;
end endgenerate // gnll_fifo
reg curr_state = 0;
reg next_state = 0;
reg leaving_empty_fwft = 0;
reg going_empty_fwft = 0;
reg empty_i_q = 0;
reg ram_rd_en_fwft = 0;
generate if (C_FIFO_TYPE == 2) begin : gll_fifo
always @* begin // FSM fo FWFT
case (curr_state)
1'b0: begin
if (~FIFOEMPTY)
next_state <= 1'b1;
else
next_state <= 1'b0;
end
1'b1: begin
if (FIFOEMPTY && RD_EN)
next_state <= 1'b0;
else
next_state <= 1'b1;
end
default: next_state <= 1'b0;
endcase
end
always @ (posedge RD_CLK or posedge rd_rst_i) begin
if (rd_rst_i) begin
empty_i <= 1'b1;
empty_i_q <= 1'b1;
curr_state <= 1'b0;
ram_valid_i <= 1'b0;
end else if (srst_i) begin
empty_i <= #`TCQ 1'b1;
empty_i_q <= #`TCQ 1'b1;
curr_state <= #`TCQ 1'b0;
ram_valid_i <= #`TCQ 1'b0;
end else begin
empty_i <= #`TCQ going_empty_fwft | (~leaving_empty_fwft & empty_i);
empty_i_q <= #`TCQ FIFOEMPTY;
curr_state <= #`TCQ next_state;
ram_valid_i <= #`TCQ next_state;
end
end //always
wire fe_of_empty;
assign fe_of_empty = empty_i_q & ~FIFOEMPTY;
always @* begin // Finding leaving empty
case (curr_state)
1'b0: leaving_empty_fwft <= fe_of_empty;
1'b1: leaving_empty_fwft <= 1'b1;
default: leaving_empty_fwft <= 1'b0;
endcase
end
always @* begin // Finding going empty
case (curr_state)
1'b1: going_empty_fwft <= FIFOEMPTY & RD_EN;
default: going_empty_fwft <= 1'b0;
endcase
end
always @* begin // Generating FWFT rd_en
case (curr_state)
1'b0: ram_rd_en_fwft <= ~FIFOEMPTY;
1'b1: ram_rd_en_fwft <= ~FIFOEMPTY & RD_EN;
default: ram_rd_en_fwft <= 1'b0;
endcase
end
assign ram_regout_en = ram_rd_en_fwft;
assign ram_rd_en = ram_rd_en_fwft;
end endgenerate // gll_fifo
//***************************************************************************
// Calculate RAMVALID_P0_OUT
// RAMVALID_P0_OUT indicates that the data in Stage1 is valid.
//
// If the RAM is being read from on this clock cycle (ram_rd_en=1), then
// RAMVALID_P0_OUT is certainly going to be true.
// If the RAM is not being read from, but the output registers are being
// updated to fill Stage2 (ram_regout_en=1), then Stage1 will be emptying,
// therefore causing RAMVALID_P0_OUT to be false.
// Otherwise, RAMVALID_P0_OUT will remain unchanged.
//***************************************************************************
// PROCESS regout_valid
generate if (C_FIFO_TYPE < 2) begin : gnll_fifo_ram_valid
always @ (posedge RD_CLK or posedge rd_rst_i) begin
if (rd_rst_i) begin
// asynchronous reset (active high)
ram_valid_i <= #`TCQ 1'b0;
end else begin
if (srst_i) begin
// synchronous reset (active high)
ram_valid_i <= #`TCQ 1'b0;
end else begin
if (ram_rd_en == 1'b1) begin
ram_valid_i <= #`TCQ 1'b1;
end else begin
if (ram_regout_en == 1'b1)
ram_valid_i <= #`TCQ 1'b0;
else
ram_valid_i <= #`TCQ ram_valid_i;
end
end //srst_i
end //rd_rst_i
end //always
end endgenerate // gnll_fifo_ram_valid
//***************************************************************************
// Calculate READ_DATA_VALID
// READ_DATA_VALID indicates whether the value in Stage2 is valid or not.
// Stage2 has valid data whenever Stage1 had valid data and
// ram_regout_en_i=1, such that the data in Stage1 is propogated
// into Stage2.
//***************************************************************************
always @ (posedge RD_CLK or posedge rd_rst_i) begin
if (rd_rst_i)
read_data_valid_i <= #`TCQ 1'b0;
else if (srst_i)
read_data_valid_i <= #`TCQ 1'b0;
else
read_data_valid_i <= #`TCQ ram_valid_i | (read_data_valid_i & ~RD_EN);
end //always
//**************************************************************************
// Calculate EMPTY
// Defined as the inverse of READ_DATA_VALID
//
// Description:
//
// If read_data_valid_i indicates that the output is not valid,
// and there is no valid data on the output of the ram to preload it
// with, then we will report empty.
//
// If there is no valid data on the output of the ram and we are
// reading, then the FIFO will go empty.
//
//**************************************************************************
generate if (C_FIFO_TYPE < 2) begin : gnll_fifo_empty
always @ (posedge RD_CLK or posedge rd_rst_i) begin
if (rd_rst_i) begin
// asynchronous reset (active high)
empty_i <= #`TCQ 1'b1;
end else begin
if (srst_i) begin
// synchronous reset (active high)
empty_i <= #`TCQ 1'b1;
end else begin
// rising clock edge
empty_i <= #`TCQ (~ram_valid_i & ~read_data_valid_i) | (~ram_valid_i & RD_EN);
end
end
end //always
end endgenerate // gnll_fifo_empty
// Register RD_EN from user to calculate USERUNDERFLOW.
// Register empty_i to calculate USERUNDERFLOW.
always @ (posedge RD_CLK) begin
rd_en_q <= #`TCQ RD_EN;
empty_q <= #`TCQ empty_i;
end //always
//***************************************************************************
// Calculate user_almost_empty
// user_almost_empty is defined such that, unless more words are written
// to the FIFO, the next read will cause the FIFO to go EMPTY.
//
// In most cases, whenever the output registers are updated (due to a user
// read or a preload condition), then user_almost_empty will update to
// whatever RAM_EMPTY is.
//
// The exception is when the output is valid, the user is not reading, and
// Stage1 is not empty. In this condition, Stage1 will be preloaded from the
// memory, so we need to make sure user_almost_empty deasserts properly under
// this condition.
//***************************************************************************
always @ (posedge RD_CLK or posedge rd_rst_i)
begin
if (rd_rst_i) begin // asynchronous reset (active high)
almost_empty_i <= #`TCQ 1'b1;
almost_empty_q <= #`TCQ 1'b1;
end else begin // rising clock edge
if (srst_i) begin // synchronous reset (active high)
almost_empty_i <= #`TCQ 1'b1;
almost_empty_q <= #`TCQ 1'b1;
end else begin
if ((ram_regout_en) | (~FIFOEMPTY & read_data_valid_i & ~RD_EN)) begin
almost_empty_i <= #`TCQ FIFOEMPTY;
end
almost_empty_q <= #`TCQ empty_i;
end
end
end //always
assign USEREMPTY = empty_i;
assign USERALMOSTEMPTY = almost_empty_i;
assign FIFORDEN = ram_rd_en;
assign RAMVALID = ram_valid_i;
assign USERVALID = C_USERVALID_LOW ? ~read_data_valid_i : read_data_valid_i;
assign USERUNDERFLOW = C_USERUNDERFLOW_LOW ? ~(empty_q & rd_en_q) : empty_q & rd_en_q;
// BRAM resets synchronously
always @ (posedge RD_CLK)
begin
if (rd_rst_i || srst_i) begin
if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE < 2)
USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL);
end
end //always
always @ (posedge RD_CLK or posedge rd_rst_i)
begin
if (rd_rst_i) begin //asynchronous reset (active high)
if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF
USERSBITERR <= #`TCQ 0;
USERDBITERR <= #`TCQ 0;
end
// DRAM resets asynchronously
if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE == 2) //asynchronous reset (active high)
USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL);
end else begin // rising clock edge
if (srst_i) begin
if (C_USE_ECC == 0) begin // Reset S/DBITERR only if ECC is OFF
USERSBITERR <= #`TCQ 0;
USERDBITERR <= #`TCQ 0;
end
if (C_USE_DOUT_RST == 1 && C_MEMORY_TYPE == 2)
USERDATA <= #`TCQ hexstr_conv(C_DOUT_RST_VAL);
end else begin
if (ram_regout_en) begin
USERDATA <= #`TCQ FIFODATA;
USERSBITERR <= #`TCQ FIFOSBITERR;
USERDBITERR <= #`TCQ FIFODBITERR;
end
end
end
end //always
endmodule
//-----------------------------------------------------------------------------
//
// Register Slice
// Register one AXI channel on forward and/or reverse signal path
//
// Verilog-standard: Verilog 2001
//--------------------------------------------------------------------------
//
// Structure:
// reg_slice
//
//--------------------------------------------------------------------------
module fifo_generator_v12_0_axic_reg_slice #
(
parameter C_FAMILY = "virtex7",
parameter C_DATA_WIDTH = 32,
parameter C_REG_CONFIG = 32'h00000000
)
(
// System Signals
input wire ACLK,
input wire ARESET,
// Slave side
input wire [C_DATA_WIDTH-1:0] S_PAYLOAD_DATA,
input wire S_VALID,
output wire S_READY,
// Master side
output wire [C_DATA_WIDTH-1:0] M_PAYLOAD_DATA,
output wire M_VALID,
input wire M_READY
);
generate
////////////////////////////////////////////////////////////////////
//
// Both FWD and REV mode
//
////////////////////////////////////////////////////////////////////
if (C_REG_CONFIG == 32'h00000000)
begin
reg [1:0] state;
localparam [1:0]
ZERO = 2'b10,
ONE = 2'b11,
TWO = 2'b01;
reg [C_DATA_WIDTH-1:0] storage_data1 = 0;
reg [C_DATA_WIDTH-1:0] storage_data2 = 0;
reg load_s1;
wire load_s2;
wire load_s1_from_s2;
reg s_ready_i; //local signal of output
wire m_valid_i; //local signal of output
// assign local signal to its output signal
assign S_READY = s_ready_i;
assign M_VALID = m_valid_i;
reg areset_d1; // Reset delay register
always @(posedge ACLK) begin
areset_d1 <= ARESET;
end
// Load storage1 with either slave side data or from storage2
always @(posedge ACLK)
begin
if (load_s1)
if (load_s1_from_s2)
storage_data1 <= storage_data2;
else
storage_data1 <= S_PAYLOAD_DATA;
end
// Load storage2 with slave side data
always @(posedge ACLK)
begin
if (load_s2)
storage_data2 <= S_PAYLOAD_DATA;
end
assign M_PAYLOAD_DATA = storage_data1;
// Always load s2 on a valid transaction even if it's unnecessary
assign load_s2 = S_VALID & s_ready_i;
// Loading s1
always @ *
begin
if ( ((state == ZERO) && (S_VALID == 1)) || // Load when empty on slave transaction
// Load when ONE if we both have read and write at the same time
((state == ONE) && (S_VALID == 1) && (M_READY == 1)) ||
// Load when TWO and we have a transaction on Master side
((state == TWO) && (M_READY == 1)))
load_s1 = 1'b1;
else
load_s1 = 1'b0;
end // always @ *
assign load_s1_from_s2 = (state == TWO);
// State Machine for handling output signals
always @(posedge ACLK) begin
if (ARESET) begin
s_ready_i <= 1'b0;
state <= ZERO;
end else if (areset_d1) begin
s_ready_i <= 1'b1;
end else begin
case (state)
// No transaction stored locally
ZERO: if (S_VALID) state <= ONE; // Got one so move to ONE
// One transaction stored locally
ONE: begin
if (M_READY & ~S_VALID) state <= ZERO; // Read out one so move to ZERO
if (~M_READY & S_VALID) begin
state <= TWO; // Got another one so move to TWO
s_ready_i <= 1'b0;
end
end
// TWO transaction stored locally
TWO: if (M_READY) begin
state <= ONE; // Read out one so move to ONE
s_ready_i <= 1'b1;
end
endcase // case (state)
end
end // always @ (posedge ACLK)
assign m_valid_i = state[0];
end // if (C_REG_CONFIG == 1)
////////////////////////////////////////////////////////////////////
//
// 1-stage pipeline register with bubble cycle, both FWD and REV pipelining
// Operates same as 1-deep FIFO
//
////////////////////////////////////////////////////////////////////
else if (C_REG_CONFIG == 32'h00000001)
begin
reg [C_DATA_WIDTH-1:0] storage_data1 = 0;
reg s_ready_i; //local signal of output
reg m_valid_i; //local signal of output
// assign local signal to its output signal
assign S_READY = s_ready_i;
assign M_VALID = m_valid_i;
reg areset_d1; // Reset delay register
always @(posedge ACLK) begin
areset_d1 <= ARESET;
end
// Load storage1 with slave side data
always @(posedge ACLK)
begin
if (ARESET) begin
s_ready_i <= 1'b0;
m_valid_i <= 1'b0;
end else if (areset_d1) begin
s_ready_i <= 1'b1;
end else if (m_valid_i & M_READY) begin
s_ready_i <= 1'b1;
m_valid_i <= 1'b0;
end else if (S_VALID & s_ready_i) begin
s_ready_i <= 1'b0;
m_valid_i <= 1'b1;
end
if (~m_valid_i) begin
storage_data1 <= S_PAYLOAD_DATA;
end
end
assign M_PAYLOAD_DATA = storage_data1;
end // if (C_REG_CONFIG == 7)
else begin : default_case
// Passthrough
assign M_PAYLOAD_DATA = S_PAYLOAD_DATA;
assign M_VALID = S_VALID;
assign S_READY = M_READY;
end
endgenerate
endmodule // reg_slice
|
//*****************************************************************************
// Copyright (c) 2006 Xilinx, Inc.
// This design is confidential and proprietary of Xilinx, Inc.
// All Rights Reserved
//*****************************************************************************
// ____ ____
// / /\/ /
// /___/ \ / Vendor: Xilinx
// \ \ \/ Version: $Name: i+IP+125372 $
// \ \ Application: MIG
// / / Filename: mem_interface_top.v
// /___/ /\ Date Last Modified: $Date: 2007/04/18 13:49:32 $
// \ \ / \ Date Created: Wed Aug 16 2006
// \___\/\___\
//
//Device: Virtex-5
//Design Name: DDR2
//Purpose:
// Top-level module. Simple model for what the user might use
// Typically, the user will only instantiate MEM_INTERFACE_TOP in their
// code, and generate all the other infrastructure and backend logic
// separately. This module serves both as an example, and allows the user
// to synthesize a self-contained design, which they can use to test their
// hardware.
// In addition to the memory controller, the module instantiates:
// 1. Clock generation/distribution, reset logic
// 2. IDELAY control block
// 3. Synthesizable testbench - used to model user's backend logic
//Reference:
//Revision History:
//*****************************************************************************
`timescale 1ns/1ps
module mem_interface_top #
(
parameter BANK_WIDTH = 3, // # of memory bank addr bits
parameter CKE_WIDTH = 1, // # of memory clock enable outputs
parameter CLK_WIDTH = 1, // # of clock outputs
parameter COL_WIDTH = 10, // # of memory column bits
parameter CS_NUM = 1, // # of separate memory chip selects
parameter CS_WIDTH = 1, // # of total memory chip selects
parameter CS_BITS = 0, // set to log2(CS_NUM) (rounded up)
parameter DM_WIDTH = 9, // # of data mask bits
parameter DQ_WIDTH = 72, // # of data width
parameter DQ_PER_DQS = 8, // # of DQ data bits per strobe
parameter DQS_WIDTH = 9, // # of DQS strobes
parameter DQ_BITS = 7, // set to log2(DQS_WIDTH*DQ_PER_DQS)
parameter DQS_BITS = 4, // set to log2(DQS_WIDTH)
parameter ODT_WIDTH = 1, // # of memory on-die term enables
parameter ROW_WIDTH = 14, // # of memory row and # of addr bits
parameter ADDITIVE_LAT = 0, // additive write latency
parameter BURST_LEN = 4, // burst length (in double words)
parameter BURST_TYPE = 0, // burst type (=0 seq; =1 interleaved)
parameter CAS_LAT = 3, // CAS latency
parameter ECC_ENABLE = 0, // enable ECC (=1 enable)
parameter MULTI_BANK_EN = 1, // Keeps multiple banks open. (= 1 enable)
parameter ODT_TYPE = 0, // ODT (=0(none),=1(75),=2(150),=3(50))
parameter REDUCE_DRV = 0, // reduced strength mem I/O (=1 yes)
parameter REG_ENABLE = 1, // registered addr/ctrl (=1 yes)
parameter TREFI_NS = 7800, // auto refresh interval (uS)
parameter TRAS = 40000, // active->precharge delay
parameter TRCD = 15000, // active->read/write delay
parameter TRFC = 127500, // refresh->refresh, refresh->active delay
parameter TRP = 15000, // precharge->command delay
parameter TRTP = 7500, // read->precharge delay
parameter TWR = 15000, // used to determine write->precharge
parameter TWTR = 10000, // write->read delay
parameter IDEL_HIGH_PERF = "TRUE", // # initial # taps for DQ IDELAY
parameter SIM_ONLY = 0, // = 1 to skip SDRAM power up delay
parameter CLK_PERIOD = 5000, // Core/Memory clock period (in ps)
parameter RST_ACT_LOW = 1, // =1 for active low reset, =0 for active high
parameter DLL_FREQ_MODE = "HIGH" // DCM Frequency range
)
(
inout [DQ_WIDTH-1:0] ddr2_dq,
output [ROW_WIDTH-1:0] ddr2_a,
output [BANK_WIDTH-1:0] ddr2_ba,
output ddr2_ras_n,
output ddr2_cas_n,
output ddr2_we_n,
output [CS_WIDTH-1:0] ddr2_cs_n,
output [ODT_WIDTH-1:0] ddr2_odt,
output [CKE_WIDTH-1:0] ddr2_cke,
output ddr2_reset_n,
output [DM_WIDTH-1:0] ddr2_dm,
//// input sys_clk_p,
//// input sys_clk_n,
input sys_clk,
input clk200_p,
input clk200_n,
/// Jiansong: 200MHz clock output
output clk200_o,
input sys_rst_n,
output phy_init_done,
output rst0_tb,
output clk0_tb,
output app_wdf_afull,
output app_af_afull,
output rd_data_valid,
input app_wdf_wren,
input app_af_wren,
input [30:0] app_af_addr,
input [2:0] app_af_cmd,
output [(2*DQ_WIDTH)-1:0] rd_data_fifo_out,
input [(2*DQ_WIDTH)-1:0] app_wdf_data,
input [(2*DM_WIDTH)-1:0] app_wdf_mask_data,
inout [DQS_WIDTH-1:0] ddr2_dqs,
inout [DQS_WIDTH-1:0] ddr2_dqs_n,
output [CLK_WIDTH-1:0] ddr2_ck,
output [CLK_WIDTH-1:0] ddr2_ck_n
);
wire rst0;
wire rst90;
wire rst200;
wire clk0;
wire clk90;
wire clk200;
wire idelay_ctrl_rdy;
//***************************************************************************
assign rst0_tb = rst0;
assign clk0_tb = clk0;
assign ddr2_reset_n= ~rst0;
/// Jiansong:
assign clk200_o = clk200;
mem_interface_top_idelay_ctrl u_idelay_ctrl
(
.rst200(rst200),
.clk200(clk200),
.idelay_ctrl_rdy(idelay_ctrl_rdy)
);
mem_interface_top_infrastructure #
(
.CLK_PERIOD(CLK_PERIOD),
.RST_ACT_LOW(RST_ACT_LOW),
.DLL_FREQ_MODE(DLL_FREQ_MODE)
)
u_infrastructure
(
//// .sys_clk_p(sys_clk_p),
//// .sys_clk_n(sys_clk_n),
.sys_clk(sys_clk),
.clk200_p(clk200_p),
.clk200_n(clk200_n),
.sys_rst_n(sys_rst_n),
.rst0(rst0),
.rst90(rst90),
.rst200(rst200),
.clk0(clk0),
.clk90(clk90),
.clk200(clk200),
.idelay_ctrl_rdy(idelay_ctrl_rdy)
);
mem_interface_top_ddr2_top_0 #
(
.BANK_WIDTH(BANK_WIDTH),
.CKE_WIDTH(CKE_WIDTH),
.CLK_WIDTH(CLK_WIDTH),
.COL_WIDTH(COL_WIDTH),
.CS_NUM(CS_NUM),
.CS_WIDTH(CS_WIDTH),
.CS_BITS(CS_BITS),
.DM_WIDTH(DM_WIDTH),
.DQ_WIDTH(DQ_WIDTH),
.DQ_PER_DQS(DQ_PER_DQS),
.DQS_WIDTH(DQS_WIDTH),
.DQ_BITS(DQ_BITS),
.DQS_BITS(DQS_BITS),
.ODT_WIDTH(ODT_WIDTH),
.ROW_WIDTH(ROW_WIDTH),
.ADDITIVE_LAT(ADDITIVE_LAT),
.BURST_LEN(BURST_LEN),
.BURST_TYPE(BURST_TYPE),
.CAS_LAT(CAS_LAT),
.ECC_ENABLE(ECC_ENABLE),
.MULTI_BANK_EN(MULTI_BANK_EN),
.ODT_TYPE(ODT_TYPE),
.REDUCE_DRV(REDUCE_DRV),
.REG_ENABLE(REG_ENABLE),
.TREFI_NS(TREFI_NS),
.TRAS(TRAS),
.TRCD(TRCD),
.TRFC(TRFC),
.TRP(TRP),
.TRTP(TRTP),
.TWR(TWR),
.TWTR(TWTR),
.IDEL_HIGH_PERF(IDEL_HIGH_PERF),
.SIM_ONLY(SIM_ONLY),
.CLK_PERIOD(CLK_PERIOD)
)
u_ddr2_top_0
(
.ddr2_dq(ddr2_dq),
.ddr2_a(ddr2_a),
.ddr2_ba(ddr2_ba),
.ddr2_ras_n(ddr2_ras_n),
.ddr2_cas_n(ddr2_cas_n),
.ddr2_we_n(ddr2_we_n),
.ddr2_cs_n(ddr2_cs_n),
.ddr2_odt(ddr2_odt),
.ddr2_cke(ddr2_cke),
.ddr2_dm(ddr2_dm),
.phy_init_done(phy_init_done),
.rst0(rst0),
.rst90(rst90),
.clk0(clk0),
.clk90(clk90),
.app_wdf_afull(app_wdf_afull),
.app_af_afull(app_af_afull),
.rd_data_valid(rd_data_valid),
.app_wdf_wren(app_wdf_wren),
.app_af_wren(app_af_wren),
.app_af_addr(app_af_addr),
.app_af_cmd(app_af_cmd),
.rd_data_fifo_out(rd_data_fifo_out),
.app_wdf_data(app_wdf_data),
.app_wdf_mask_data(app_wdf_mask_data),
.ddr2_dqs(ddr2_dqs),
.ddr2_dqs_n(ddr2_dqs_n),
.ddr2_ck(ddr2_ck),
.ddr2_ck_n(ddr2_ck_n)
);
endmodule
|
// DESCRIPTION: Verilator: System Verilog test of case and if
//
// This code instantiates and runs a simple CPU written in System Verilog.
//
// This file ONLY is placed into the Public Domain, for any use, without
// warranty.
// Contributed 2012 by M W Lund, Atmel Corporation and Jeremy Bennett, Embecosm.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
/*AUTOWIRE*/
// **************************************************************************
// Regs and Wires
// **************************************************************************
reg rst;
integer rst_count;
st3_testbench st3_testbench_i (/*AUTOINST*/
// Inputs
.clk (clk),
.rst (rst));
// **************************************************************************
// Reset Generation
// **************************************************************************
initial begin
rst = 1'b1;
rst_count = 0;
end
always @( posedge clk ) begin
if (rst_count < 2) begin
rst_count++;
end
else begin
rst = 1'b0;
end
end
// **************************************************************************
// Closing message
// **************************************************************************
final begin
$write("*-* All Finished *-*\n");
end
endmodule
module st3_testbench (/*AUTOARG*/
// Inputs
clk, rst
);
input clk;
input rst;
logic clk;
logic rst;
logic [8*16-1:0] wide_input_bus;
logic decrementA; // 0=Up-counting, 1=down-counting
logic dual_countA; // Advance counter by 2 steps at a time
logic cntA_en; // Enable Counter A
logic decrementB; // 0=Up-counting, 1=down-counting
logic dual_countB; // Advance counter by 2 steps at a time
logic cntB_en; // Enable counter B
logic [47:0] selected_out;
integer i;
initial begin
decrementA = 1'b0;
dual_countA = 1'b0;
cntA_en = 1'b1;
decrementB = 1'b0;
dual_countB = 1'b0;
cntB_en = 1'b1;
wide_input_bus = {8'hf5,
8'hef,
8'hd5,
8'hc5,
8'hb5,
8'ha5,
8'h95,
8'h85,
8'ha7,
8'ha6,
8'ha5,
8'ha4,
8'ha3,
8'ha2,
8'ha1,
8'ha0};
i = 0;
end
simple_test_3
simple_test_3_i
(// Outputs
.selected_out (selected_out[47:0]),
// Inputs
.wide_input_bus (wide_input_bus[8*16-1:0]),
.rst (rst),
.clk (clk),
.decrementA (decrementA),
.dual_countA (dual_countA),
.cntA_en (cntA_en),
.decrementB (decrementB),
.dual_countB (dual_countB),
.cntB_en (cntB_en));
// Logic to print outputs and then finish.
always @(posedge clk) begin
if (i < 50) begin
`ifdef TEST_VERBOSE
$display("%x", simple_test_3_i.cntA_reg ,"%x",
simple_test_3_i.cntB_reg ," ", "%x", selected_out);
`endif
i <= i + 1;
end
else begin
$finish();
end
end // always @ (posedge clk)
endmodule
// Module testing:
// - Unique case
// - Priority case
// - Unique if
// - ++, --, =- and =+ operands.
module simple_test_3
(input logic [8*16-1:0] wide_input_bus,
input logic rst,
input logic clk,
// Counter A
input logic decrementA, // 0=Up-counting, 1=down-counting
input logic dual_countA, // Advance counter by 2 steps at a time
input logic cntA_en, // Enable Counter A
// Counter B
input logic decrementB, // 0=Up-counting, 1=down-counting
input logic dual_countB, // Advance counter by 2 steps at a time
input logic cntB_en, // Enable counter B
// Outputs
output logic [47:0] selected_out);
// Declarations
logic [3:0] cntA_reg; // Registered version of cntA
logic [3:0] cntB_reg; // Registered version of cntA
counterA
counterA_inst
(/*AUTOINST*/
// Outputs
.cntA_reg (cntA_reg[3:0]),
// Inputs
.decrementA (decrementA),
.dual_countA (dual_countA),
.cntA_en (cntA_en),
.clk (clk),
.rst (rst));
counterB
counterB_inst
(/*AUTOINST*/
// Outputs
.cntB_reg (cntB_reg[3:0]),
// Inputs
.decrementB (decrementB),
.dual_countB (dual_countB),
.cntB_en (cntB_en),
.clk (clk),
.rst (rst));
simple_test_3a
sta
(.wide_input_bus (wide_input_bus),
.selector (cntA_reg),
.selected_out (selected_out[7:0]));
simple_test_3b
stb
(.wide_input_bus (wide_input_bus),
.selector (cntA_reg),
.selected_out (selected_out[15:8]));
simple_test_3c
stc
(.wide_input_bus (wide_input_bus),
.selector (cntB_reg),
.selected_out (selected_out[23:16]));
simple_test_3d
std
(.wide_input_bus (wide_input_bus),
.selector (cntB_reg),
.selected_out (selected_out[31:24]));
simple_test_3e
ste
(.wide_input_bus (wide_input_bus),
.selector (cntB_reg),
.selected_out (selected_out[39:32]));
simple_test_3f
stf
(.wide_input_bus (wide_input_bus),
.selector (cntB_reg),
.selected_out (selected_out[47:40]));
endmodule // simple_test_3
module counterA
(output logic [3:0] cntA_reg, // Registered version of cntA
input logic decrementA, // 0=Up-counting, 1=down-counting
input logic dual_countA, // Advance counter by 2 steps at a time
input logic cntA_en, // Enable Counter A
input logic clk, // Clock
input logic rst); // Synchronous reset
logic [3:0] cntA; // combinational count variable.
// Counter A
// Sequential part of counter CntA
always_ff @(posedge clk)
begin
cntA_reg <= cntA;
end
// Combinational part of counter
// Had to be split up to test C-style update, as there are no
// non-blocking version like -<=
always_comb
if (rst)
cntA = 0;
else begin
cntA = cntA_reg; // Necessary to avoid latch
if (cntA_en) begin
if (decrementA)
if (dual_countA)
//cntA = cntA - 2;
cntA -= 2;
else
//cntA = cntA - 1;
cntA--;
else
if (dual_countA)
//cntA = cntA + 2;
cntA += 2;
else
//cntA = cntA + 1;
cntA++;
end // if (cntA_en)
end
endmodule // counterA
module counterB
(output logic [3:0] cntB_reg, // Registered version of cntA
input logic decrementB, // 0=Up-counting, 1=down-counting
input logic dual_countB, // Advance counter by 2 steps at a time
input logic cntB_en, // Enable counter B
input logic clk, // Clock
input logic rst); // Synchronous reset
// Counter B - tried to write sequential only, but ended up without
// SystemVerilog.
always_ff @(posedge clk) begin
if (rst)
cntB_reg <= 0;
else
if (cntB_en) begin
if (decrementB)
if (dual_countB)
cntB_reg <= cntB_reg - 2;
else
cntB_reg <= cntB_reg - 1;
// Attempts to write in SystemVerilog:
else
if (dual_countB)
cntB_reg <= cntB_reg + 2;
else
cntB_reg <= cntB_reg + 1;
// Attempts to write in SystemVerilog:
end
end // always_ff @
endmodule
// A multiplexor in terms of look-up
module simple_test_3a
(input logic [8*16-1:0] wide_input_bus,
input logic [3:0] selector,
output logic [7:0] selected_out);
always_comb
selected_out = {wide_input_bus[selector*8+7],
wide_input_bus[selector*8+6],
wide_input_bus[selector*8+5],
wide_input_bus[selector*8+4],
wide_input_bus[selector*8+3],
wide_input_bus[selector*8+2],
wide_input_bus[selector*8+1],
wide_input_bus[selector*8]};
endmodule // simple_test_3a
// A multiplexer in terms of standard case
module simple_test_3b
(input logic [8*16-1:0] wide_input_bus,
input logic [3:0] selector,
output logic [7:0] selected_out);
always_comb begin
case (selector)
4'h0: selected_out = wide_input_bus[ 7: 0];
4'h1: selected_out = wide_input_bus[ 15: 8];
4'h2: selected_out = wide_input_bus[ 23: 16];
4'h3: selected_out = wide_input_bus[ 31: 24];
4'h4: selected_out = wide_input_bus[ 39: 32];
4'h5: selected_out = wide_input_bus[ 47: 40];
4'h6: selected_out = wide_input_bus[ 55: 48];
4'h7: selected_out = wide_input_bus[ 63: 56];
4'h8: selected_out = wide_input_bus[ 71: 64];
4'h9: selected_out = wide_input_bus[ 79: 72];
4'ha: selected_out = wide_input_bus[ 87: 80];
4'hb: selected_out = wide_input_bus[ 95: 88];
4'hc: selected_out = wide_input_bus[103: 96];
4'hd: selected_out = wide_input_bus[111:104];
4'he: selected_out = wide_input_bus[119:112];
4'hf: selected_out = wide_input_bus[127:120];
endcase // case (selector)
end
endmodule // simple_test_3b
// A multiplexer in terms of unique case
module simple_test_3c
(input logic [8*16-1:0] wide_input_bus,
input logic [3:0] selector,
output logic [7:0] selected_out);
always_comb begin
unique case (selector)
4'h0: selected_out = wide_input_bus[ 7: 0];
4'h1: selected_out = wide_input_bus[ 15: 8];
4'h2: selected_out = wide_input_bus[ 23: 16];
4'h3: selected_out = wide_input_bus[ 31: 24];
4'h4: selected_out = wide_input_bus[ 39: 32];
4'h5: selected_out = wide_input_bus[ 47: 40];
4'h6: selected_out = wide_input_bus[ 55: 48];
4'h7: selected_out = wide_input_bus[ 63: 56];
4'h8: selected_out = wide_input_bus[ 71: 64];
4'h9: selected_out = wide_input_bus[ 79: 72];
4'ha: selected_out = wide_input_bus[ 87: 80];
4'hb: selected_out = wide_input_bus[ 95: 88];
4'hc: selected_out = wide_input_bus[103: 96];
4'hd: selected_out = wide_input_bus[111:104];
4'he: selected_out = wide_input_bus[119:112];
4'hf: selected_out = wide_input_bus[127:120];
endcase // case (selector)
end
endmodule // simple_test_3c
// A multiplexer in terms of unique if
module simple_test_3d
(input logic [8*16-1:0] wide_input_bus,
input logic [3:0] selector,
output logic [7:0] selected_out);
always_comb begin
unique if (selector == 4'h0) selected_out = wide_input_bus[ 7: 0];
else if (selector == 4'h1) selected_out = wide_input_bus[ 15: 8];
else if (selector == 4'h2) selected_out = wide_input_bus[ 23: 16];
else if (selector == 4'h3) selected_out = wide_input_bus[ 31: 24];
else if (selector == 4'h4) selected_out = wide_input_bus[ 39: 32];
else if (selector == 4'h5) selected_out = wide_input_bus[ 47: 40];
else if (selector == 4'h6) selected_out = wide_input_bus[ 55: 48];
else if (selector == 4'h7) selected_out = wide_input_bus[ 63: 56];
else if (selector == 4'h8) selected_out = wide_input_bus[ 71: 64];
else if (selector == 4'h9) selected_out = wide_input_bus[ 79: 72];
else if (selector == 4'ha) selected_out = wide_input_bus[ 87: 80];
else if (selector == 4'hb) selected_out = wide_input_bus[ 95: 88];
else if (selector == 4'hc) selected_out = wide_input_bus[103: 96];
else if (selector == 4'hd) selected_out = wide_input_bus[111:104];
else if (selector == 4'he) selected_out = wide_input_bus[119:112];
else if (selector == 4'hf) selected_out = wide_input_bus[127:120];
end
endmodule // simple_test_3d
// Test of priority case
// Note: This does NOT try to implement the same function as above.
module simple_test_3e
(input logic [8*16-1:0] wide_input_bus,
input logic [3:0] selector,
output logic [7:0] selected_out);
always_comb begin
priority case (1'b1)
selector[0]: selected_out = wide_input_bus[ 7: 0]; // Bit 0 has highets priority
selector[2]: selected_out = wide_input_bus[ 39: 32]; // Note 2 higher priority than 1
selector[1]: selected_out = wide_input_bus[ 23: 16]; // Note 1 lower priority than 2
selector[3]: selected_out = wide_input_bus[ 71: 64]; // Bit 3 has lowest priority
default: selected_out = wide_input_bus[127:120]; // for selector = 0.
endcase // case (selector)
end
endmodule // simple_test_3e
// Test of "inside"
// Note: This does NOT try to implement the same function as above.
// Note: Support for "inside" is a separate Verilator feature request, so is
// not used inside a this version of the test.
module simple_test_3f
(input logic [8*16-1:0] wide_input_bus,
input logic [3:0] selector,
output logic [7:0] selected_out);
always_comb begin
/* -----\/----- EXCLUDED -----\/-----
if ( selector[3:0] inside { 4'b?00?, 4'b1100}) // Matching 0000, 0001, 1000, 1100, 1001
// if ( selector[3:2] inside { 2'b?0, selector[1:0]})
selected_out = wide_input_bus[ 7: 0];
else
-----/\----- EXCLUDED -----/\----- */
/* verilator lint_off CASEOVERLAP */
priority casez (selector[3:0])
4'b0?10: selected_out = wide_input_bus[ 15: 8]; // Matching 0010 and 0110
4'b0??0: selected_out = wide_input_bus[ 23: 16]; // Overlap: only 0100 remains (0000 in "if" above)
4'b0100: selected_out = wide_input_bus[ 31: 24]; // Overlap: Will never occur
default: selected_out = wide_input_bus[127:120]; // Remaining 0011,0100,0101,0111,1010,1011,1101,1110,1111
endcase // case (selector)
/* verilator lint_on CASEOVERLAP */
end
endmodule // simple_test_3f
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Iztok Jeras.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
localparam NO = 10; // number of access events
// packed structures
struct packed {
logic e0;
logic [1:0] e1;
logic [3:0] e2;
logic [7:0] e3;
} struct_bg; // big endian structure
/* verilator lint_off LITENDIAN */
struct packed {
logic e0;
logic [0:1] e1;
logic [0:3] e2;
logic [0:7] e3;
} struct_lt; // little endian structure
/* verilator lint_on LITENDIAN */
localparam WS = 15; // $bits(struct_bg)
integer cnt = 0;
// event counter
always @ (posedge clk)
begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if ((cnt[30:2]==NO) && (cnt[1:0]==2'd0)) begin
$write("*-* All Finished *-*\n");
$finish;
end
// big endian
always @ (posedge clk)
if (cnt[1:0]==2'd0) begin
// initialize to defaaults (all bits to 0)
if (cnt[30:2]==0) struct_bg <= '0;
else if (cnt[30:2]==1) struct_bg <= '0;
else if (cnt[30:2]==2) struct_bg <= '0;
else if (cnt[30:2]==3) struct_bg <= '0;
else if (cnt[30:2]==4) struct_bg <= '0;
else if (cnt[30:2]==5) struct_bg <= '0;
end else if (cnt[1:0]==2'd1) begin
// write value to structure
if (cnt[30:2]==0) begin end
else if (cnt[30:2]==1) struct_bg <= '1;
else if (cnt[30:2]==2) struct_bg.e0 <= '1;
else if (cnt[30:2]==3) struct_bg.e1 <= '1;
else if (cnt[30:2]==4) struct_bg.e2 <= '1;
else if (cnt[30:2]==5) struct_bg.e3 <= '1;
end else if (cnt[1:0]==2'd2) begin
// check structure value
if (cnt[30:2]==0) begin if (struct_bg !== 15'b000000000000000) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==1) begin if (struct_bg !== 15'b111111111111111) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==2) begin if (struct_bg !== 15'b100000000000000) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==3) begin if (struct_bg !== 15'b011000000000000) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==4) begin if (struct_bg !== 15'b000111100000000) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==5) begin if (struct_bg !== 15'b000000011111111) begin $display("%b", struct_bg); $stop(); end end
end else if (cnt[1:0]==2'd3) begin
// read value from structure (not a very good test for now)
if (cnt[30:2]==0) begin if (struct_bg !== {WS{1'b0}}) $stop(); end
else if (cnt[30:2]==1) begin if (struct_bg !== {WS{1'b1}}) $stop(); end
else if (cnt[30:2]==2) begin if (struct_bg.e0 !== { 1{1'b1}}) $stop(); end
else if (cnt[30:2]==3) begin if (struct_bg.e1 !== { 2{1'b1}}) $stop(); end
else if (cnt[30:2]==4) begin if (struct_bg.e2 !== { 4{1'b1}}) $stop(); end
else if (cnt[30:2]==5) begin if (struct_bg.e3 !== { 8{1'b1}}) $stop(); end
end
// little endian
always @ (posedge clk)
if (cnt[1:0]==2'd0) begin
// initialize to defaaults (all bits to 0)
if (cnt[30:2]==0) struct_lt <= '0;
else if (cnt[30:2]==1) struct_lt <= '0;
else if (cnt[30:2]==2) struct_lt <= '0;
else if (cnt[30:2]==3) struct_lt <= '0;
else if (cnt[30:2]==4) struct_lt <= '0;
else if (cnt[30:2]==5) struct_lt <= '0;
end else if (cnt[1:0]==2'd1) begin
// write value to structure
if (cnt[30:2]==0) begin end
else if (cnt[30:2]==1) struct_lt <= '1;
else if (cnt[30:2]==2) struct_lt.e0 <= '1;
else if (cnt[30:2]==3) struct_lt.e1 <= '1;
else if (cnt[30:2]==4) struct_lt.e2 <= '1;
else if (cnt[30:2]==5) struct_lt.e3 <= '1;
end else if (cnt[1:0]==2'd2) begin
// check structure value
if (cnt[30:2]==0) begin if (struct_lt !== 15'b000000000000000) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==1) begin if (struct_lt !== 15'b111111111111111) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==2) begin if (struct_lt !== 15'b100000000000000) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==3) begin if (struct_lt !== 15'b011000000000000) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==4) begin if (struct_lt !== 15'b000111100000000) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==5) begin if (struct_lt !== 15'b000000011111111) begin $display("%b", struct_lt); $stop(); end end
end else if (cnt[1:0]==2'd3) begin
// read value from structure (not a very good test for now)
if (cnt[30:2]==0) begin if (struct_lt !== {WS{1'b0}}) $stop(); end
else if (cnt[30:2]==1) begin if (struct_lt !== {WS{1'b1}}) $stop(); end
else if (cnt[30:2]==2) begin if (struct_lt.e0 !== { 1{1'b1}}) $stop(); end
else if (cnt[30:2]==3) begin if (struct_lt.e1 !== { 2{1'b1}}) $stop(); end
else if (cnt[30:2]==4) begin if (struct_lt.e2 !== { 4{1'b1}}) $stop(); end
else if (cnt[30:2]==5) begin if (struct_lt.e3 !== { 8{1'b1}}) $stop(); end
end
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Butterworth low pass IIR filter
// input: 8bit ADC signal, 1MS/s
// output: 8bit value, Fc=20khz
//
// coef: (using http://www-users.cs.york.ac.uk/~fisher/mkfilter/trad.html)
// Recurrence relation:
// y[n] = ( 1 * x[n- 2])
// + ( 2 * x[n- 1])
// + ( 1 * x[n- 0])
// + ( -0.8371816513 * y[n- 2])
// + ( 1.8226949252 * y[n- 1])
//
// therefore:
// a = [1,2,1]
// b = [-0.8371816513, 1.8226949252]
// b is approximated to b = [-0xd6/0x100, 0x1d3 / 0x100] (for optimization)
// gain = 2.761139367e2
//
// See details about its design see
// https://fail0verflow.com/blog/2014/proxmark3-fpga-iir-filter.html
module lp20khz_1MSa_iir_filter(input clk, input [7:0] adc_d, output rdy, output [7:0] out);
// clk is 24Mhz, the IIR filter is designed for 1MS/s
// hence we need to divide it by 24
// using a shift register takes less area than a counter
reg [23:0] cnt = 1;
assign rdy = cnt[0];
always @(posedge clk)
cnt <= {cnt[22:0], cnt[23]};
reg [7:0] x0 = 0;
reg [7:0] x1 = 0;
reg [16:0] y0 = 0;
reg [16:0] y1 = 0;
always @(posedge clk)
begin
if (rdy)
begin
x0 <= x1;
x1 <= adc_d;
y0 <= y1;
y1 <=
// center the signal:
// input range is [0; 255]
// We want "128" to be at the center of the 17bit register
// (128+z)*gain = 17bit center
// z = (1<<16)/gain - 128 = 109
// We could use 9bit x registers for that, but that would be
// a waste, let's just add the constant during the computation
// (x0+109) + 2*(x1+109) + (x2+109) = x0 + 2*x1 + x2 + 436
x0 + {x1, 1'b0} + adc_d + 436
// we want "- y0 * 0xd6 / 0x100" using only shift and add
// 0xd6 == 0b11010110
// so *0xd6/0x100 is equivalent to
// ((x << 1) + (x << 2) + (x << 4) + (x << 6) + (x << 7)) >> 8
// which is also equivalent to
// (x >> 7) + (x >> 6) + (x >> 4) + (x >> 2) + (x >> 1)
- ((y0 >> 7) + (y0 >> 6) + (y0 >> 4) + (y0 >> 2) + (y0 >> 1)) // - y0 * 0xd6 / 0x100
// we want "+ y1 * 0x1d3 / 0x100"
// 0x1d3 == 0b111010011
// so this is equivalent to
// ((x << 0) + (x << 1) + (x << 4) + (x << 6) + (x << 7) + (x << 8)) >> 8
// which is also equivalent to
// (x >> 8) + (x >> 7) + (x >> 4) + (x >> 2) + (x >> 1) + (x >> 0)
+ ((y1 >> 8) + (y1 >> 7) + (y1 >> 4) + (y1 >> 2) + (y1 >> 1) + y1);
end
end
// output: reduce to 8bit
assign out = y1[16:9];
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Butterworth low pass IIR filter
// input: 8bit ADC signal, 1MS/s
// output: 8bit value, Fc=20khz
//
// coef: (using http://www-users.cs.york.ac.uk/~fisher/mkfilter/trad.html)
// Recurrence relation:
// y[n] = ( 1 * x[n- 2])
// + ( 2 * x[n- 1])
// + ( 1 * x[n- 0])
// + ( -0.8371816513 * y[n- 2])
// + ( 1.8226949252 * y[n- 1])
//
// therefore:
// a = [1,2,1]
// b = [-0.8371816513, 1.8226949252]
// b is approximated to b = [-0xd6/0x100, 0x1d3 / 0x100] (for optimization)
// gain = 2.761139367e2
//
// See details about its design see
// https://fail0verflow.com/blog/2014/proxmark3-fpga-iir-filter.html
module lp20khz_1MSa_iir_filter(input clk, input [7:0] adc_d, output rdy, output [7:0] out);
// clk is 24Mhz, the IIR filter is designed for 1MS/s
// hence we need to divide it by 24
// using a shift register takes less area than a counter
reg [23:0] cnt = 1;
assign rdy = cnt[0];
always @(posedge clk)
cnt <= {cnt[22:0], cnt[23]};
reg [7:0] x0 = 0;
reg [7:0] x1 = 0;
reg [16:0] y0 = 0;
reg [16:0] y1 = 0;
always @(posedge clk)
begin
if (rdy)
begin
x0 <= x1;
x1 <= adc_d;
y0 <= y1;
y1 <=
// center the signal:
// input range is [0; 255]
// We want "128" to be at the center of the 17bit register
// (128+z)*gain = 17bit center
// z = (1<<16)/gain - 128 = 109
// We could use 9bit x registers for that, but that would be
// a waste, let's just add the constant during the computation
// (x0+109) + 2*(x1+109) + (x2+109) = x0 + 2*x1 + x2 + 436
x0 + {x1, 1'b0} + adc_d + 436
// we want "- y0 * 0xd6 / 0x100" using only shift and add
// 0xd6 == 0b11010110
// so *0xd6/0x100 is equivalent to
// ((x << 1) + (x << 2) + (x << 4) + (x << 6) + (x << 7)) >> 8
// which is also equivalent to
// (x >> 7) + (x >> 6) + (x >> 4) + (x >> 2) + (x >> 1)
- ((y0 >> 7) + (y0 >> 6) + (y0 >> 4) + (y0 >> 2) + (y0 >> 1)) // - y0 * 0xd6 / 0x100
// we want "+ y1 * 0x1d3 / 0x100"
// 0x1d3 == 0b111010011
// so this is equivalent to
// ((x << 0) + (x << 1) + (x << 4) + (x << 6) + (x << 7) + (x << 8)) >> 8
// which is also equivalent to
// (x >> 8) + (x >> 7) + (x >> 4) + (x >> 2) + (x >> 1) + (x >> 0)
+ ((y1 >> 8) + (y1 >> 7) + (y1 >> 4) + (y1 >> 2) + (y1 >> 1) + y1);
end
end
// output: reduce to 8bit
assign out = y1[16:9];
endmodule
|
/*+--------------------------------------------------------------------------
Copyright (c) 2015, Microsoft Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
module RCB_FRL_OSERDES(OQ, CLK, CLKDIV, DI, OCE, SR);
output OQ;
input CLK, CLKDIV;
input [7:0] DI;
input OCE, SR;
wire SHIFT1, SHIFT2;
OSERDES OSERDES_inst1 (
.OQ(OQ), // 1-bit data path output
.SHIFTOUT1(), // 1-bit data expansion output
.SHIFTOUT2(), // 1-bit data expansion output
.TQ(), // 1-bit 3-state control output
.CLK(CLK), // 1-bit clock input
.CLKDIV(CLKDIV), // 1-bit divided clock input
.D1(DI[7]), // 1-bit parallel data input
.D2(DI[6]), // 1-bit parallel data input
.D3(DI[5]), // 1-bit parallel data input
.D4(DI[4]), // 1-bit parallel data input
.D5(DI[3]), // 1-bit parallel data input
.D6(DI[2]), // 1-bit parallel data input
.OCE(OCE), // 1-bit clock enable input
.REV(1'b0), // 1-bit reverse SR input
.SHIFTIN1(SHIFT1), // 1-bit data expansion input
.SHIFTIN2(SHIFT2), // 1-bit data expansion input
.SR(SR), // 1-bit set/reset input
.T1(), // 1-bit parallel 3-state input
.T2(), // 1-bit parallel 3-state input
.T3(), // 1-bit parallel 3-state input
.T4(), // 1-bit parallel 3-state input
.TCE(1'b1) // 1-bit 3-state signal clock enable input
);
defparam OSERDES_inst1.DATA_RATE_OQ = "DDR";
defparam OSERDES_inst1.DATA_RATE_TQ = "DDR";
defparam OSERDES_inst1.DATA_WIDTH = 8;
defparam OSERDES_inst1.SERDES_MODE = "MASTER";
defparam OSERDES_inst1.TRISTATE_WIDTH = 1;
OSERDES OSERDES_inst2 (
.OQ(), // 1-bit data path output
.SHIFTOUT1(SHIFT1), // 1-bit data expansion output
.SHIFTOUT2(SHIFT2), // 1-bit data expansion output
.TQ(), // 1-bit 3-state control output
.CLK(CLK), // 1-bit clock input
.CLKDIV(CLKDIV), // 1-bit divided clock input
.D1(), // 1-bit parallel data input
.D2(), // 1-bit parallel data input
.D3(DI[1]), // 1-bit parallel data input
.D4(DI[0]), // 1-bit parallel data input
.D5(), // 1-bit parallel data input
.D6(), // 1-bit parallel data input
.OCE(OCE), // 1-bit clock enable input
.REV(1'b0), // 1-bit reverse SR input
.SHIFTIN1(), // 1-bit data expansion input
.SHIFTIN2(), // 1-bit data expansion input
.SR(SR), // 1-bit set/reset input
.T1(), // 1-bit parallel 3-state input
.T2(), // 1-bit parallel 3-state input
.T3(), // 1-bit parallel 3-state input
.T4(), // 1-bit parallel 3-state input
.TCE(1'b1) // 1-bit 3-state signal clock enable input
);
defparam OSERDES_inst2.DATA_RATE_OQ = "DDR";
defparam OSERDES_inst2.DATA_RATE_TQ = "DDR";
defparam OSERDES_inst2.DATA_WIDTH = 8;
defparam OSERDES_inst2.SERDES_MODE = "SLAVE";
defparam OSERDES_inst2.TRISTATE_WIDTH = 1;
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 06:19:33 AM
// Design Name:
// Module Name: Barrel_Shifter_M
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Barrel_Shifter_M
#(parameter SW=26)
(
input wire clk,
input wire rst,
input wire load_i,
input wire Shift_Value_i,
input wire [SW-1:0] Shift_Data_i,
/////////////////////////////////////////////7
output wire [SW-1:0] N_mant_o
);
wire [SW-1:0] Data_Reg;
////////////////////////////////////////////////////7
shift_mux_array #(.SWR(SW), .LEVEL(0)) shift_mux_array(
.Data_i(Shift_Data_i),
.select_i(Shift_Value_i),
.bit_shift_i(1'b1),
.Data_o(Data_Reg)
);
RegisterMult #(.W(SW)) Output_Reg(
.clk(clk),
.rst(rst),
.load(load_i),
.D(Data_Reg),
.Q(N_mant_o)
);
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 07:00:53 AM
// Design Name:
// Module Name: Adder_Round
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Adder_Round
#(parameter SW=26) (
input wire clk,
input wire rst,
input wire load_i,//Reg load input
input wire [SW-1:0] Data_A_i,
input wire [SW-1:0] Data_B_i,
/////////////////////////////////////////////////////////////
output wire [SW-1:0] Data_Result_o,
output wire FSM_C_o
);
wire [SW:0] result_A_adder;
adder #(.W(SW)) A_operation (
.Data_A_i(Data_A_i),
.Data_B_i(Data_B_i),
.Data_S_o(result_A_adder)
);
RegisterAdd #(.W(SW)) Add_Subt_Result(
.clk (clk),
.rst (rst),
.load (load_i),
.D (result_A_adder[SW-1:0]),
.Q (Data_Result_o)
);
RegisterAdd #(.W(1)) Add_overflow_Result(
.clk (clk),
.rst (rst),
.load (load_i),
.D (result_A_adder[SW]),
.Q (FSM_C_o)
);
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2006 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc; initial cyc=0;
reg [63:0] crc;
wire [65:0] outData; // From fifo of fifo.v
wire [15:0] inData = crc[15:0];
wire [1:0] inWordPtr = crc[17:16];
wire wrEn = crc[20];
wire [1:0] wrPtr = crc[33:32];
wire [1:0] rdPtr = crc[34:33];
fifo fifo (
// Outputs
.outData (outData[65:0]),
// Inputs
.clk (clk),
.inWordPtr (inWordPtr[1:0]),
.inData (inData[15:0]),
.rdPtr (rdPtr),
.wrPtr (wrPtr),
.wrEn (wrEn));
always @ (posedge clk) begin
//$write("[%0t] cyc==%0d crc=%b q=%x\n",$time, cyc, crc, outData);
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
end
else if (cyc==90) begin
if (outData[63:0] != 64'hd9bcbc276f0984ea) $stop;
end
else if (cyc==91) begin
if (outData[63:0] != 64'hef77cd9b13a866f0) $stop;
end
else if (cyc==92) begin
if (outData[63:0] != 64'h2750cd9b13a866f0) $stop;
end
else if (cyc==93) begin
if (outData[63:0] != 64'h4ea0bc276f0984ea) $stop;
end
else if (cyc==94) begin
if (outData[63:0] != 64'h9d41bc276f0984ea) $stop;
end
else if (cyc==99) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module fifo (/*AUTOARG*/
// Outputs
outData,
// Inputs
clk, inWordPtr, inData, wrPtr, rdPtr, wrEn
);
parameter fifoDepthLog2 = 1;
parameter fifoDepth = 1<<fifoDepthLog2;
`define PTRBITS (fifoDepthLog2+1)
`define PTRBITSM1 fifoDepthLog2
`define PTRBITSM2 (fifoDepthLog2-1)
input clk;
input [1:0] inWordPtr;
input [15:0] inData;
input [`PTRBITSM1:0] wrPtr;
input [`PTRBITSM1:0] rdPtr;
output [65:0] outData;
input wrEn;
reg [65:0] outData;
// verilator lint_off VARHIDDEN
// verilator lint_off LITENDIAN
reg [65:0] fifo[0:fifoDepth-1];
// verilator lint_on LITENDIAN
// verilator lint_on VARHIDDEN
//reg [65:0] temp;
always @(posedge clk) begin
//$write ("we=%x PT=%x ID=%x D=%x\n", wrEn, wrPtr[`PTRBITSM2:0], {1'b0,~inWordPtr,4'b0}, inData[15:0]);
if (wrEn) begin
fifo[ wrPtr[`PTRBITSM2:0] ][{1'b0,~inWordPtr,4'b0}+:16] <= inData[15:0];
// Equivelent to:
//temp = fifo[ wrPtr[`PTRBITSM2:0] ];
//temp [{1'b0,~inWordPtr,4'b0}+:16] = inData[15:0];
//fifo[ wrPtr[`PTRBITSM2:0] ] <= temp;
end
outData <= fifo[rdPtr[`PTRBITSM2:0]];
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
`ifndef VERILATOR
module t;
/*AUTOREGINPUT*/
// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)
reg c0; // To t2 of t2.v
reg c1; // To t2 of t2.v
reg check; // To t2 of t2.v
reg [1:0] clks; // To t2 of t2.v
// End of automatics
t2 t2 (/*AUTOINST*/
// Inputs
.clks (clks[1:0]),
.c0 (c0),
.c1 (c1),
.check (check));
task clockit (input v1, v0);
c1 = v1;
c0 = v0;
clks[1] = v1;
clks[0] = v0;
`ifdef TEST_VERBOSE $write("[%0t] c1=%x c0=%x\n", $time,v0,v1); `endif
#1;
endtask
initial begin
check = '0;
c0 = '0;
c1 = '0;
clks = '0;
#1
t2.clear();
#10;
for (int i=0; i<2; i++) begin
clockit(0, 0);
clockit(0, 0);
clockit(0, 1);
clockit(1, 1);
clockit(0, 0);
clockit(1, 1);
clockit(1, 0);
clockit(0, 0);
clockit(1, 0);
clockit(0, 1);
clockit(0, 0);
end
check = 1;
clockit(0, 0);
end
endmodule
`endif
`ifdef VERILATOR
`define t2 t
`else
`define t2 t2
`endif
module `t2 (
input [1:0] clks,
input c0,
input c1,
input check
);
`ifdef T_CLK_2IN_VEC
wire clk0 = clks[0];
wire clk1 = clks[1];
`else
wire clk0 = c0;
wire clk1 = c1;
`endif
integer p0 = 0;
integer p1 = 0;
integer p01 = 0;
integer n0 = 0;
integer n1 = 0;
integer n01 = 0;
integer vp = 0;
integer vn = 0;
integer vpn = 0;
task clear;
`ifdef TEST_VERBOSE $display("[%0t] clear\n",$time); `endif
p0 = 0;
p1 = 0;
p01 = 0;
n0 = 0;
n1 = 0;
n01 = 0;
vp = 0;
vn = 0;
vpn = 0;
endtask
`define display_counts(text) begin \
$write("[%0t] ",$time); \
`ifdef T_CLK_2IN_VEC $write(" 2v "); `endif \
$write(text); \
$write(": %0d %0d %0d %0d %0d %0d %0d %0d %0d\n", p0, p1, p01, n0, n1, n01, vp, vn, vpn); \
end
always @ (posedge clk0) begin
p0 = p0 + 1; // Want blocking, so don't miss clock counts
`ifdef TEST_VERBOSE `display_counts("posedge 0"); `endif
end
always @ (posedge clk1) begin
p1 = p1 + 1;
`ifdef TEST_VERBOSE `display_counts("posedge 1"); `endif
end
always @ (posedge clk0 or posedge clk1) begin
p01 = p01 + 1;
`ifdef TEST_VERBOSE `display_counts("posedge *"); `endif
end
always @ (negedge clk0) begin
n0 = n0 + 1;
`ifdef TEST_VERBOSE `display_counts("negedge 0"); `endif
end
always @ (negedge clk1) begin
n1 = n1 + 1;
`ifdef TEST_VERBOSE `display_counts("negedge 1"); `endif
end
always @ (negedge clk0 or negedge clk1) begin
n01 = n01 + 1;
`ifdef TEST_VERBOSE `display_counts("negedge *"); `endif
end
`ifndef VERILATOR
always @ (posedge clks) begin
vp = vp + 1;
`ifdef TEST_VERBOSE `display_counts("pos vec"); `endif
end
always @ (negedge clks) begin
vn = vn + 1;
`ifdef TEST_VERBOSE `display_counts("neg vec"); `endif
end
always @ (posedge clks or negedge clks) begin
vpn = vpn + 1;
`ifdef TEST_VERBOSE `display_counts("or vec"); `endif
end
`endif
always @ (posedge check) begin
if (p0!=6) $stop;
if (p1!=6) $stop;
if (p01!=10) $stop;
if (n0!=6) $stop;
if (n1!=6) $stop;
if (n01!=10) $stop;
`ifndef VERILATOR
if (vp!=6) $stop;
if (vn!=6) $stop;
if (vpn!=12) $stop;
`endif
$write("*-* All Finished *-*\n");
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Iztok Jeras.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
localparam NO = 7; // number of access events
// packed structures
struct packed {
logic e0;
logic [1:0] e1;
logic [3:0] e2;
logic [7:0] e3;
} struct_bg; // big endian structure
/* verilator lint_off LITENDIAN */
struct packed {
logic e0;
logic [0:1] e1;
logic [0:3] e2;
logic [0:7] e3;
} struct_lt; // little endian structure
/* verilator lint_on LITENDIAN */
localparam WS = 15; // $bits(struct_bg)
integer cnt = 0;
// event counter
always @ (posedge clk)
begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if ((cnt[30:2]==(NO-1)) && (cnt[1:0]==2'd3)) begin
$write("*-* All Finished *-*\n");
$finish;
end
// big endian
always @ (posedge clk)
if (cnt[1:0]==2'd0) begin
// initialize to defaults (all bits 1'b0)
if (cnt[30:2]==0) struct_bg <= '0;
else if (cnt[30:2]==1) struct_bg <= '0;
else if (cnt[30:2]==2) struct_bg <= '0;
else if (cnt[30:2]==3) struct_bg <= '0;
else if (cnt[30:2]==4) struct_bg <= '0;
else if (cnt[30:2]==5) struct_bg <= '0;
else if (cnt[30:2]==6) struct_bg <= '0;
end else if (cnt[1:0]==2'd1) begin
// write data into whole or part of the array using literals
if (cnt[30:2]==0) begin end
else if (cnt[30:2]==1) struct_bg <= '{0 ,1 , 2, 3};
else if (cnt[30:2]==2) struct_bg <= '{e0:1, e1:2, e2:3, e3:4};
else if (cnt[30:2]==3) struct_bg <= '{e3:6, e2:4, e1:2, e0:0};
// verilator lint_off WIDTH
else if (cnt[30:2]==4) struct_bg <= '{default:13};
else if (cnt[30:2]==5) struct_bg <= '{e2:8'haa, default:1};
else if (cnt[30:2]==6) struct_bg <= '{cnt+0 ,cnt+1 , cnt+2, cnt+3};
// verilator lint_on WIDTH
end else if (cnt[1:0]==2'd2) begin
// chack array agains expected value
if (cnt[30:2]==0) begin if (struct_bg !== 15'b0_00_0000_00000000) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==1) begin if (struct_bg !== 15'b0_01_0010_00000011) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==2) begin if (struct_bg !== 15'b1_10_0011_00000100) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==3) begin if (struct_bg !== 15'b0_10_0100_00000110) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==4) begin if (struct_bg !== 15'b1_01_1101_00001101) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==5) begin if (struct_bg !== 15'b1_01_1010_00000001) begin $display("%b", struct_bg); $stop(); end end
else if (cnt[30:2]==6) begin if (struct_bg !== 15'b1_10_1011_00011100) begin $display("%b", struct_bg); $stop(); end end
end
// little endian
always @ (posedge clk)
if (cnt[1:0]==2'd0) begin
// initialize to defaults (all bits 1'b0)
if (cnt[30:2]==0) struct_lt <= '0;
else if (cnt[30:2]==1) struct_lt <= '0;
else if (cnt[30:2]==2) struct_lt <= '0;
else if (cnt[30:2]==3) struct_lt <= '0;
else if (cnt[30:2]==4) struct_lt <= '0;
else if (cnt[30:2]==5) struct_lt <= '0;
else if (cnt[30:2]==6) struct_lt <= '0;
end else if (cnt[1:0]==2'd1) begin
// write data into whole or part of the array using literals
if (cnt[30:2]==0) begin end
else if (cnt[30:2]==1) struct_lt <= '{0 ,1 , 2, 3};
else if (cnt[30:2]==2) struct_lt <= '{e0:1, e1:2, e2:3, e3:4};
else if (cnt[30:2]==3) struct_lt <= '{e3:6, e2:4, e1:2, e0:0};
// verilator lint_off WIDTH
else if (cnt[30:2]==4) struct_lt <= '{default:13};
else if (cnt[30:2]==5) struct_lt <= '{e2:8'haa, default:1};
else if (cnt[30:2]==6) struct_lt <= '{cnt+0 ,cnt+1 , cnt+2, cnt+3};
// verilator lint_on WIDTH
end else if (cnt[1:0]==2'd2) begin
// chack array agains expected value
if (cnt[30:2]==0) begin if (struct_lt !== 15'b0_00_0000_00000000) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==1) begin if (struct_lt !== 15'b0_01_0010_00000011) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==2) begin if (struct_lt !== 15'b1_10_0011_00000100) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==3) begin if (struct_lt !== 15'b0_10_0100_00000110) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==4) begin if (struct_lt !== 15'b1_01_1101_00001101) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==5) begin if (struct_lt !== 15'b1_01_1010_00000001) begin $display("%b", struct_lt); $stop(); end end
else if (cnt[30:2]==6) begin if (struct_lt !== 15'b1_10_1011_00011100) begin $display("%b", struct_lt); $stop(); end end
end
endmodule
|
// DESCRIPTION: Verilator: Simple test of unoptflat
//
// Demonstration of an UNOPTFLAT combinatorial loop using 3 bits and looping
// through 2 sub-modules.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Jeremy Bennett.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [2:0] x;
initial begin
x = 3'b000;
end
test1 test1i ( .clk (clk),
.xvecin (x[1:0]),
.xvecout (x[2:1]));
test2 test2i ( .clk (clk),
.xvecin (x[2:1]),
.xvecout (x[1:0]));
always @(posedge clk or negedge clk) begin
`ifdef TEST_VERBOSE
$write("x = %x\n", x);
`endif
if (x[1] != 0) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule // t
module test1
(/*AUTOARG*/
// Inputs
clk,
xvecin,
// Outputs
xvecout
);
input clk;
input wire [1:0] xvecin;
output wire [1:0] xvecout;
assign xvecout = {xvecin[0], clk};
endmodule // test
module test2
(/*AUTOARG*/
// Inputs
clk,
xvecin,
// Outputs
xvecout
);
input clk;
input wire [1:0] xvecin;
output wire [1:0] xvecout;
assign xvecout = {clk, xvecin[1]};
endmodule // test
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug511
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [7:0] au;
wire [7:0] as;
Test1 test1 (.au);
Test2 test2 (.as);
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] result=%x %x\n",$time, au, as);
`endif
if (au != 'h12) $stop;
if (as != 'h02) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module Test1 (output [7:0] au);
wire [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign au=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
module Test2 (output [7:0] as);
wire signed [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign as=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug511
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [7:0] au;
wire [7:0] as;
Test1 test1 (.au);
Test2 test2 (.as);
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] result=%x %x\n",$time, au, as);
`endif
if (au != 'h12) $stop;
if (as != 'h02) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module Test1 (output [7:0] au);
wire [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign au=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
module Test2 (output [7:0] as);
wire signed [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign as=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug511
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [7:0] au;
wire [7:0] as;
Test1 test1 (.au);
Test2 test2 (.as);
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] result=%x %x\n",$time, au, as);
`endif
if (au != 'h12) $stop;
if (as != 'h02) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module Test1 (output [7:0] au);
wire [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign au=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
module Test2 (output [7:0] as);
wire signed [7:0] b;
wire signed [3:0] c;
// verilator lint_off WIDTH
assign c=-1; // 'hf
assign b=3; // 'h3
assign as=b+c; // 'h12
// verilator lint_on WIDTH
endmodule
|
//-----------------------------------------------------------------------------
// Copyright (C) 2014 iZsh <izsh at fail0verflow.com>
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// input clk is 24Mhz
`include "min_max_tracker.v"
module lf_edge_detect(input clk, input [7:0] adc_d, input [7:0] lf_ed_threshold,
output [7:0] max, output [7:0] min,
output [7:0] high_threshold, output [7:0] highz_threshold,
output [7:0] lowz_threshold, output [7:0] low_threshold,
output edge_state, output edge_toggle);
min_max_tracker tracker(clk, adc_d, lf_ed_threshold, min, max);
// auto-tune
assign high_threshold = (max + min) / 2 + (max - min) / 4;
assign highz_threshold = (max + min) / 2 + (max - min) / 8;
assign lowz_threshold = (max + min) / 2 - (max - min) / 8;
assign low_threshold = (max + min) / 2 - (max - min) / 4;
// heuristic to see if it makes sense to try to detect an edge
wire enabled =
(high_threshold > highz_threshold)
& (highz_threshold > lowz_threshold)
& (lowz_threshold > low_threshold)
& ((high_threshold - highz_threshold) > 8)
& ((highz_threshold - lowz_threshold) > 16)
& ((lowz_threshold - low_threshold) > 8);
// Toggle the output with hysteresis
// Set to high if the ADC value is above the threshold
// Set to low if the ADC value is below the threshold
reg is_high = 0;
reg is_low = 0;
reg is_zero = 0;
reg trigger_enabled = 1;
reg output_edge = 0;
reg output_state;
always @(posedge clk)
begin
is_high <= (adc_d >= high_threshold);
is_low <= (adc_d <= low_threshold);
is_zero <= ((adc_d > lowz_threshold) & (adc_d < highz_threshold));
end
// all edges detection
always @(posedge clk)
if (enabled) begin
// To enable detecting two consecutive peaks at the same level
// (low or high) we check whether or not we went back near 0 in-between.
// This extra check is necessary to prevent from noise artifacts
// around the threshold values.
if (trigger_enabled & (is_high | is_low)) begin
output_edge <= ~output_edge;
trigger_enabled <= 0;
end else
trigger_enabled <= trigger_enabled | is_zero;
end
// edge states
always @(posedge clk)
if (enabled) begin
if (is_high)
output_state <= 1'd1;
else if (is_low)
output_state <= 1'd0;
end
assign edge_state = output_state;
assign edge_toggle = output_edge;
endmodule
|
// DESCRIPTION: Verilator: Dedupe optimization test.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty.
// Contributed 2012 by Varun Koyyalagunta, Centaur Technology.
//
// Test consists of the follow logic tree, which has many obvious
// places for dedupe:
/*
output
+
--------------/ \--------------
/ \
+ +
----/ \----- ----/ \----
/ + / +
+ / \ + / \
-/ \- a b -/ \- a b
/ \ / \
+ + + +
/ \ / \ / \ / \
a b c d a b c d
*/
module t(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left,right;
add add(sum,left,right,clk);
l l(left,a,b,c,d,clk);
r r(right,a,b,c,d,clk);
endmodule
module l(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
ll ll(left,a,b,c,d,clk);
lr lr(right,a,b,c,d,clk);
endmodule
module ll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
lll lll(left,a,b,c,d,clk);
llr llr(right,a,b,c,d,clk);
endmodule
module lll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module llr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,c,d,clk);
endmodule
module lr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module r(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
rl rl(left,a,b,c,d,clk);
rr rr(right,a,b,c,d,clk);
endmodule
module rr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module rl(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
rll rll(left,a,b,c,d,clk);
rlr rlr(right,a,b,c,d,clk);
endmodule
module rll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add2 add(sum,a,b,clk);
endmodule
module rlr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add2 add(sum,c,d,clk);
endmodule
module add(sum,x,y,clk);
output sum;
input x,y,clk;
reg t1,t2;
always @(posedge clk) begin
sum <= x + y;
end
endmodule
module add2(sum,x,y,clk);
output sum;
input x,y,clk;
reg t1,t2;
always @(posedge clk) begin
sum <= x + y;
end
endmodule
|
// DESCRIPTION: Verilator: Dedupe optimization test.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty.
// Contributed 2012 by Varun Koyyalagunta, Centaur Technology.
//
// Test consists of the follow logic tree, which has many obvious
// places for dedupe:
/*
output
+
--------------/ \--------------
/ \
+ +
----/ \----- ----/ \----
/ + / +
+ / \ + / \
-/ \- a b -/ \- a b
/ \ / \
+ + + +
/ \ / \ / \ / \
a b c d a b c d
*/
module t(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left,right;
add add(sum,left,right,clk);
l l(left,a,b,c,d,clk);
r r(right,a,b,c,d,clk);
endmodule
module l(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
ll ll(left,a,b,c,d,clk);
lr lr(right,a,b,c,d,clk);
endmodule
module ll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
lll lll(left,a,b,c,d,clk);
llr llr(right,a,b,c,d,clk);
endmodule
module lll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module llr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,c,d,clk);
endmodule
module lr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module r(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
rl rl(left,a,b,c,d,clk);
rr rr(right,a,b,c,d,clk);
endmodule
module rr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add add(sum,a,b,clk);
endmodule
module rl(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
wire left, right;
add add(sum,left,right,clk);
rll rll(left,a,b,c,d,clk);
rlr rlr(right,a,b,c,d,clk);
endmodule
module rll(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add2 add(sum,a,b,clk);
endmodule
module rlr(sum,a,b,c,d,clk);
output sum;
input a,b,c,d,clk;
add2 add(sum,c,d,clk);
endmodule
module add(sum,x,y,clk);
output sum;
input x,y,clk;
reg t1,t2;
always @(posedge clk) begin
sum <= x + y;
end
endmodule
module add2(sum,x,y,clk);
output sum;
input x,y,clk;
reg t1,t2;
always @(posedge clk) begin
sum <= x + y;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
// that should not work.
//
// The given generate loops should attempt to access invalid bits of mask and
// trigger errors.
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 3
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, so we can immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that all have errors in applying short-circuting to
// generate "if" conditionals.
// Attempt to access invalid bits of MASK in different ways
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE + 1)) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g + 1]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise AND
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE)) & MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise OR
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) | ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug598
module t (/*AUTOARG*/
// Outputs
val,
// Inputs
clk
);
input clk;
output integer val;
integer dbg_addr = 0;
function func1;
input en;
input [31:0] a;
func1 = en && (a == 1);
endfunction
function func2;
input en;
input [31:0] a;
func2 = en && (a == 2);
endfunction
always @(posedge clk) begin
case( 1'b1 )
// This line is OK:
func1(1'b1, dbg_addr) : val = 1;
// This fails:
// %Error: Internal Error: test.v:23: ../V3Task.cpp:993: Function not underneath a statement
// %Error: Internal Error: See the manual and http://www.veripool.org/verilator for more assistance.
func2(1'b1, dbg_addr) : val = 2;
default : val = 0;
endcase
//
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
// bug598
module t (/*AUTOARG*/
// Outputs
val,
// Inputs
clk
);
input clk;
output integer val;
integer dbg_addr = 0;
function func1;
input en;
input [31:0] a;
func1 = en && (a == 1);
endfunction
function func2;
input en;
input [31:0] a;
func2 = en && (a == 2);
endfunction
always @(posedge clk) begin
case( 1'b1 )
// This line is OK:
func1(1'b1, dbg_addr) : val = 1;
// This fails:
// %Error: Internal Error: test.v:23: ../V3Task.cpp:993: Function not underneath a statement
// %Error: Internal Error: See the manual and http://www.veripool.org/verilator for more assistance.
func2(1'b1, dbg_addr) : val = 2;
default : val = 0;
endcase
//
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2005 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// verilator lint_off LITENDIAN
// verilator lint_off BLKANDNBLK
// 3 3 4
reg [71:0] memw [2:0][1:3][5:2];
reg [7:0] memn [2:0][1:3][5:2];
// verilator lint_on BLKANDNBLK
integer cyc; initial cyc=0;
reg [63:0] crc;
reg [71:0] wide;
reg [7:0] narrow;
reg [1:0] index0;
reg [1:0] index1;
reg [2:0] index2;
integer i0,i1,i2;
integer imem[2:0][1:3];
reg [2:0] cstyle[2];
// verilator lint_on LITENDIAN
initial begin
for (i0=0; i0<3; i0=i0+1) begin
for (i1=1; i1<4; i1=i1+1) begin
imem[i0[1:0]] [i1[1:0]] = i1;
for (i2=2; i2<6; i2=i2+1) begin
memw[i0[1:0]] [i1[1:0]] [i2[2:0]] = {56'hfe_fee0_fee0_fee0_,4'b0,i0[3:0],i1[3:0],i2[3:0]};
memn[i0[1:0]] [i1[1:0]] [i2[2:0]] = 8'b1000_0001;
end
end
end
end
reg [71:0] wread;
reg wreadb;
always @ (posedge clk) begin
//$write("cyc==%0d crc=%x i[%d][%d][%d] nar=%x wide=%x\n",cyc, crc, index0,index1,index2, narrow, wide);
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
narrow <= 8'h0;
wide <= 72'h0;
index0 <= 2'b0;
index1 <= 2'b0;
index2 <= 3'b0;
end
else if (cyc<90) begin
index0 <= crc[1:0];
index1 <= crc[3:2];
index2 <= crc[6:4];
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
// We never read past bounds, or get unspecific results
// We also never read lowest indexes, as writing outside of range may corrupt them
if (index0>=0+1 && index0<=2 && index1>=1+1 /*&& index1<=3 CMPCONST*/ && index2>=2+1 && index2<=5) begin
narrow <= ({narrow[6:0], narrow[7]^narrow[0]}
^ {memn[index0][index1][index2]});
wread = memw[index0][index1][index2];
wreadb = memw[index0][index1][index2][2];
wide <= ({wide[70:0], wide[71]^wide[2]^wide[0]} ^ wread);
//$write("Get memw[%d][%d][%d] -> %x\n",index0,index1,index2, wread);
end
// We may write past bounds of memory
memn[index0][index1][index2] [crc[10:8]+:3] <= crc[2:0];
memn[index0][index1][index2] <= {~crc[6:0],crc[7]};
memw[index0][index1][index2] <= {~crc[7:0],crc};
//$write("Set memw[%d][%d][%d] <= %x\n",index0,index1,index2, {~crc[7:0],crc});
cstyle[cyc[0]] <= cyc[2:0];
if (cyc>20) if (cstyle[~cyc[0]] != (cyc[2:0]-3'b1)) $stop;
end
else if (cyc==90) begin
memn[0][1][3] <= memn[0][1][3] ^ 8'ha8;
end
else if (cyc==91) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x nar=%x wide=%x\n",$time, cyc, crc, narrow, wide);
if (crc != 64'h65e3bddcd9bc2750) $stop;
if (narrow != 8'hca) $stop;
if (wide != 72'h4edafed31ba6873f73) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2005 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// verilator lint_off LITENDIAN
// verilator lint_off BLKANDNBLK
// 3 3 4
reg [71:0] memw [2:0][1:3][5:2];
reg [7:0] memn [2:0][1:3][5:2];
// verilator lint_on BLKANDNBLK
integer cyc; initial cyc=0;
reg [63:0] crc;
reg [71:0] wide;
reg [7:0] narrow;
reg [1:0] index0;
reg [1:0] index1;
reg [2:0] index2;
integer i0,i1,i2;
integer imem[2:0][1:3];
reg [2:0] cstyle[2];
// verilator lint_on LITENDIAN
initial begin
for (i0=0; i0<3; i0=i0+1) begin
for (i1=1; i1<4; i1=i1+1) begin
imem[i0[1:0]] [i1[1:0]] = i1;
for (i2=2; i2<6; i2=i2+1) begin
memw[i0[1:0]] [i1[1:0]] [i2[2:0]] = {56'hfe_fee0_fee0_fee0_,4'b0,i0[3:0],i1[3:0],i2[3:0]};
memn[i0[1:0]] [i1[1:0]] [i2[2:0]] = 8'b1000_0001;
end
end
end
end
reg [71:0] wread;
reg wreadb;
always @ (posedge clk) begin
//$write("cyc==%0d crc=%x i[%d][%d][%d] nar=%x wide=%x\n",cyc, crc, index0,index1,index2, narrow, wide);
cyc <= cyc + 1;
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
narrow <= 8'h0;
wide <= 72'h0;
index0 <= 2'b0;
index1 <= 2'b0;
index2 <= 3'b0;
end
else if (cyc<90) begin
index0 <= crc[1:0];
index1 <= crc[3:2];
index2 <= crc[6:4];
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
// We never read past bounds, or get unspecific results
// We also never read lowest indexes, as writing outside of range may corrupt them
if (index0>=0+1 && index0<=2 && index1>=1+1 /*&& index1<=3 CMPCONST*/ && index2>=2+1 && index2<=5) begin
narrow <= ({narrow[6:0], narrow[7]^narrow[0]}
^ {memn[index0][index1][index2]});
wread = memw[index0][index1][index2];
wreadb = memw[index0][index1][index2][2];
wide <= ({wide[70:0], wide[71]^wide[2]^wide[0]} ^ wread);
//$write("Get memw[%d][%d][%d] -> %x\n",index0,index1,index2, wread);
end
// We may write past bounds of memory
memn[index0][index1][index2] [crc[10:8]+:3] <= crc[2:0];
memn[index0][index1][index2] <= {~crc[6:0],crc[7]};
memw[index0][index1][index2] <= {~crc[7:0],crc};
//$write("Set memw[%d][%d][%d] <= %x\n",index0,index1,index2, {~crc[7:0],crc});
cstyle[cyc[0]] <= cyc[2:0];
if (cyc>20) if (cstyle[~cyc[0]] != (cyc[2:0]-3'b1)) $stop;
end
else if (cyc==90) begin
memn[0][1][3] <= memn[0][1][3] ^ 8'ha8;
end
else if (cyc==91) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x nar=%x wide=%x\n",$time, cyc, crc, narrow, wide);
if (crc != 64'h65e3bddcd9bc2750) $stop;
if (narrow != 8'hca) $stop;
if (wide != 72'h4edafed31ba6873f73) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_arb2
#(
// Configuration
parameter string PIPELINE = "data_stall", // none|data|stall|data_stall|stall_data
parameter integer KEEP_LAST_GRANT = 1, // 0|1 - if one request can last multiple cycles (e.g. write burst), KEEP_LAST_GRANT must be 1
parameter integer NO_STALL_NETWORK = 0, // 0|1 - if one, remove the ability for arb to stall backward - must guarantee no collisions!
// Masters
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
// INPUTS
input logic clock,
input logic resetn,
// INTERFACES
acl_arb_intf m0_intf,
acl_arb_intf m1_intf,
acl_arb_intf mout_intf
);
/////////////////////////////////////////////
// ARCHITECTURE
/////////////////////////////////////////////
// mux_intf acts as an interface immediately after request arbitration
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
mux_intf();
// Selector and request arbitration.
logic mux_sel;
assign mux_intf.req = mux_sel ? m1_intf.req : m0_intf.req;
generate
if( KEEP_LAST_GRANT == 1 )
begin
logic last_mux_sel_r;
always_ff @( posedge clock )
last_mux_sel_r <= mux_sel;
always_comb
// Maintain last grant.
if( last_mux_sel_r == 1'b0 && m0_intf.req.request )
mux_sel = 1'b0;
else if( last_mux_sel_r == 1'b1 && m1_intf.req.request )
mux_sel = 1'b1;
// Arbitrarily favor m0.
else
mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
else
begin
// Arbitrarily favor m0.
assign mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
endgenerate
// Stall signal for each upstream master.
generate
if( NO_STALL_NETWORK == 1 )
begin
assign m0_intf.stall = '0;
assign m1_intf.stall = '0;
end
else
begin
assign m0_intf.stall = ( mux_sel & m1_intf.req.request) | mux_intf.stall;
assign m1_intf.stall = (~mux_sel & m0_intf.req.request) | mux_intf.stall;
end
endgenerate
// What happens at the output of the arbitration block? Depends on the pipelining option...
// Each option is responsible for the following:
// 1. Connecting mout_intf.req: request output of the arbitration block
// 2. Connecting mux_intf.stall: upstream (to input masters) stall signal
generate
if( PIPELINE == "none" )
begin
// Purely combinational. Not a single register to be seen.
// Request for downstream blocks.
assign mout_intf.req = mux_intf.req;
// Stall signal from downstream blocks
assign mux_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data" )
begin
// Standard pipeline register at output. Latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall" )
begin
// Staging register at output. Min. latency of zero cycles, max. latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data_stall" )
begin
// Pipeline register followed by staging register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf(), staging_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( pipe_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall_data" )
begin
// Staging register followed by pipeline register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf(), pipe_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( staging_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
endgenerate
endmodule
module acl_arb_pipeline_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_r();
// Pipeline register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
pipe_r.req <= 'x; // only signals reset explicitly below need to be reset at all
pipe_r.req.request <= 1'b0;
pipe_r.req.read <= 1'b0;
pipe_r.req.write <= 1'b0;
end
else if( !(out_intf.stall & pipe_r.req.request) )
pipe_r.req <= in_intf.req;
// Request for downstream blocks.
assign out_intf.req = pipe_r.req;
// Upstream stall signal.
assign in_intf.stall = out_intf.stall & pipe_r.req.request;
endmodule
module acl_arb_staging_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
logic stall_r;
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_r();
// Staging register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
staging_r.req <= 'x; // only signals reset explicitly below need to be reset at all
staging_r.req.request <= 1'b0;
staging_r.req.read <= 1'b0;
staging_r.req.write <= 1'b0;
end
else if( !stall_r )
staging_r.req <= in_intf.req;
// Stall register.
always @( posedge clock or negedge resetn )
if( !resetn )
stall_r <= 1'b0;
else
stall_r <= out_intf.stall & (stall_r | in_intf.req.request);
// Request for downstream blocks.
assign out_intf.req = stall_r ? staging_r.req : in_intf.req;
// Upstream stall signal.
assign in_intf.stall = stall_r;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_arb2
#(
// Configuration
parameter string PIPELINE = "data_stall", // none|data|stall|data_stall|stall_data
parameter integer KEEP_LAST_GRANT = 1, // 0|1 - if one request can last multiple cycles (e.g. write burst), KEEP_LAST_GRANT must be 1
parameter integer NO_STALL_NETWORK = 0, // 0|1 - if one, remove the ability for arb to stall backward - must guarantee no collisions!
// Masters
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
// INPUTS
input logic clock,
input logic resetn,
// INTERFACES
acl_arb_intf m0_intf,
acl_arb_intf m1_intf,
acl_arb_intf mout_intf
);
/////////////////////////////////////////////
// ARCHITECTURE
/////////////////////////////////////////////
// mux_intf acts as an interface immediately after request arbitration
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
mux_intf();
// Selector and request arbitration.
logic mux_sel;
assign mux_intf.req = mux_sel ? m1_intf.req : m0_intf.req;
generate
if( KEEP_LAST_GRANT == 1 )
begin
logic last_mux_sel_r;
always_ff @( posedge clock )
last_mux_sel_r <= mux_sel;
always_comb
// Maintain last grant.
if( last_mux_sel_r == 1'b0 && m0_intf.req.request )
mux_sel = 1'b0;
else if( last_mux_sel_r == 1'b1 && m1_intf.req.request )
mux_sel = 1'b1;
// Arbitrarily favor m0.
else
mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
else
begin
// Arbitrarily favor m0.
assign mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
endgenerate
// Stall signal for each upstream master.
generate
if( NO_STALL_NETWORK == 1 )
begin
assign m0_intf.stall = '0;
assign m1_intf.stall = '0;
end
else
begin
assign m0_intf.stall = ( mux_sel & m1_intf.req.request) | mux_intf.stall;
assign m1_intf.stall = (~mux_sel & m0_intf.req.request) | mux_intf.stall;
end
endgenerate
// What happens at the output of the arbitration block? Depends on the pipelining option...
// Each option is responsible for the following:
// 1. Connecting mout_intf.req: request output of the arbitration block
// 2. Connecting mux_intf.stall: upstream (to input masters) stall signal
generate
if( PIPELINE == "none" )
begin
// Purely combinational. Not a single register to be seen.
// Request for downstream blocks.
assign mout_intf.req = mux_intf.req;
// Stall signal from downstream blocks
assign mux_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data" )
begin
// Standard pipeline register at output. Latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall" )
begin
// Staging register at output. Min. latency of zero cycles, max. latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data_stall" )
begin
// Pipeline register followed by staging register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf(), staging_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( pipe_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall_data" )
begin
// Staging register followed by pipeline register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf(), pipe_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( staging_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
endgenerate
endmodule
module acl_arb_pipeline_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_r();
// Pipeline register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
pipe_r.req <= 'x; // only signals reset explicitly below need to be reset at all
pipe_r.req.request <= 1'b0;
pipe_r.req.read <= 1'b0;
pipe_r.req.write <= 1'b0;
end
else if( !(out_intf.stall & pipe_r.req.request) )
pipe_r.req <= in_intf.req;
// Request for downstream blocks.
assign out_intf.req = pipe_r.req;
// Upstream stall signal.
assign in_intf.stall = out_intf.stall & pipe_r.req.request;
endmodule
module acl_arb_staging_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
logic stall_r;
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_r();
// Staging register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
staging_r.req <= 'x; // only signals reset explicitly below need to be reset at all
staging_r.req.request <= 1'b0;
staging_r.req.read <= 1'b0;
staging_r.req.write <= 1'b0;
end
else if( !stall_r )
staging_r.req <= in_intf.req;
// Stall register.
always @( posedge clock or negedge resetn )
if( !resetn )
stall_r <= 1'b0;
else
stall_r <= out_intf.stall & (stall_r | in_intf.req.request);
// Request for downstream blocks.
assign out_intf.req = stall_r ? staging_r.req : in_intf.req;
// Upstream stall signal.
assign in_intf.stall = stall_r;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [31:0] in = crc[31:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
wire [31:0] out; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.out (out[31:0]),
// Inputs
.clk (clk),
.in (in[31:0]));
// Aggregate outputs into a single result vector
wire [63:0] result = {32'h0, out};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h458c2de282e30f8b
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test (/*AUTOARG*/
// Outputs
out,
// Inputs
clk, in
);
input clk;
input [31:0] in;
output wire [31:0] out;
reg [31:0] stage [3:0];
genvar g;
generate
for (g=0; g<4; g++) begin
always_comb begin
if (g==0) stage[g] = in;
else stage[g] = {stage[g-1][30:0],1'b1};
end
end
endgenerate
assign out = stage[3];
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
/****************************
* --------------------------
* Atomic Instruction Handler
* --------------------------
*
* Design Goal#1:
* --------------
* This module is instantiated at the end of global or local memory arbitration.
* It monitors every memory request issued to the memory, as well as readdata
* that is returned back. In case an incoming atomic request is detected, it
* activates necessary mechanisms so that memory state and readdata are consistent.
*
* Design Goal#2:
* --------------
* Because local memory interconnect and routers do not expect local
* memory to stall, this module does not stall incoming requests as long as
* (1) there is enough hardware to store all the state, (2) there is no incoming
* read/write/atomic request at the same cycle an earlier atomic request is writing
* to memory. The former requirement is handled by selecting approriate value
* for NUM_TXS parameter. The latter requirement is handled in the local memory
* interconnect, but not in global memory interconnect.
*
* Atomic Request Operands:
* ------------------------
* The operands for atomic operations are stored in writedata signal which is
* normally not used for read requests. This is the layout for writedata signal:
* Bit 0: high is this is atomic request.
* Bits 1-32: operand0 of atomic operation (valid atomic_add, atomic_min, etc.)
* Bits 33-64: operand1 of atomic operation (valid for atomic_cmpxchg)
* Bits 65-67: atomic operation types (e.g. add, min, cmpxchg, etc.)
* Bits 67-71: segment offset of the 32-bit atomic operation at the given address.
*
* Anatomy of an Atomic Request:
* -----------------------------
* We refer each memory request "a transaction" which
* go through the following states:
*
* ST_READ(R): a read from memory request is issued a response is expected.
* ST_ALU(A): readdata from memory is received and returned back to the arbitration
* in the previous cycle. In this cycle, the atomic operation (add, min, xor, etc.)
* is performed. At the end of this cycle, the result of atomic operation is stored
* in a register.
* ST_WRITEBACK(W): The result of atomic operation is written to memory.
*
* Hence, atomic requests can be represented with the following pipeline diagram
* (the number of ST_READ cycles depends on whether global or local memory is used).
*
* #1: atomic_inst: R1 R2 R3 R4 A W
*
* For ease of implementation, non-atomic read requests also go through the same
* pipeline stages. Non-atomic writes take one cycle, hence, do not go through
* pipeline stages.
*
* Conflicts:
* ----------
* We say two transactions are "conflicting", if they access the same
* address. Conflicts can potentially cause inconsistent memory state and
* incorrect readdata returns.
*
* Data Forwarding:
* ----------------
* "No-stall" atomics are realized via data forwarding between
* subsequent conflicting atomic transactions.
*
* ST_ALU-to-ST_ALU forwarding:
*
* #1: atomic_inc(A): R1 R2 R3 R4 A W
* #2: atomic_inc(A): R1 R2 R3 R4 A W
*
* We forward from ALU output of #1 to ALU input of #2.
*
* ST_ALU-to-ST_READ forwarding:
*
* #1: atomic_inc(A): R1 R2 R3 R4 A W
* #2: atomic_inc(A): R1 R2 R3 R4 A W
*
* We forward from ALU output of #1 to R3 of #2. Hence, each atomic transaction
* records data it receives via forwarding during its ST_READ stages.
*
* Selecting the readdata: Due to forwarding logic, an atomic transaction needs to
* choose which readdata to take as input to its ALU.
*
* There are 3 sources: (1) readdata received from memory,
* (2) ST_ALU-to-ST_READ forwarded data,
* (3) ST_ALU-to-ST_ALU forwarded data.
*
* This is in the order of most recent to least recent data in memory. Hence,
* priorities are 3-2-1.
*
* FMAX WARNING: This selection of inputs is the critical path for Fmax.
*
* Sequential Consistency:
* -----------------------
* For performance reasons, the atomic module does not provide sequential
* consistency for non-atomic read requests. That is, if a read request is received
* while there are conflicting atomic transactions, data forwarding will not be
* performed from atomic transactions to non-atomic read transactions, hence, the
* read request will return "old" data. It is trivial to perform data forwarding
* for non-atomic reads as long as they operate on 32-bit data. It is very complex
* to forward data when the non-atomic read request operates on wide data
* (burstcount > 1, or reads larger than 32-bit).
*
* Sequential consistency is provided for non-atomic writes. When an incoming
* non-atomic write conflicts with atomic transactions in flight, the atomic
* transactions take notice and dont write their results to memory in order not to
* overwrite the data of the non-atomic write.
*
* Optimizations:
* --------------
* (1) Selective ALU: instantiate ALU operations only for operations used in kernel,
* e.g. dont instantiate min operation if atomic_min is not used in kernel.
* (2) Free Transactions: dont keep state for non-atomic reads, if there are
* no atomics in flight.
*
*****************************/
module acl_atomics_nostall
(
clock, resetn,
// arbitration port
mem_arb_read,
mem_arb_write,
mem_arb_burstcount,
mem_arb_address,
mem_arb_writedata,
mem_arb_byteenable,
mem_arb_waitrequest,
mem_arb_readdata,
mem_arb_readdatavalid,
mem_arb_writeack,
// Avalon port
mem_avm_read,
mem_avm_write,
mem_avm_burstcount,
mem_avm_address,
mem_avm_writedata,
mem_avm_byteenable,
mem_avm_waitrequest,
mem_avm_readdata,
mem_avm_readdatavalid,
mem_avm_writeack
);
/*************
* Parameters *
*************/
// WARNING: this MUST match numAtomicOperations in ACLIntrinsics.h
parameter ATOMIC_OP_WIDTH=3; // this many atomic operations
// WARNING: this MUST match the alignment of atomic instructions (for now, it is
// always 4).
parameter SEGMENT_WIDTH_BYTES=4;
parameter USED_ATOMIC_OPERATIONS=8'b11111111; // atomics operations used in kernel
parameter ADDR_WIDTH=27; // width of addresses to memory
parameter DATA_WIDTH=96; // size of data chunks from/to memory
parameter BURST_WIDTH=6; // size of burst
parameter BYTEEN_WIDTH=32; // this many bytes in each data chunk
parameter OPERATION_WIDTH=32; // atomic operations are ALL 32-bit
parameter NUM_TXS=4; // support this many txs in flight
parameter COUNTER_WIDTH=32; // keep track of this many request between a memory request and its response
parameter LOCAL_MEM=0;
/******************
* Local Variables *
******************/
localparam OPERATION_WIDTH_BITS=$clog2(OPERATION_WIDTH);
localparam DATA_WIDTH_BITS=$clog2(DATA_WIDTH);
localparam DATA_WIDTH_BYTES=(DATA_WIDTH >> 3);
localparam DATA_WIDTH_BYTES_BITS=$clog2(DATA_WIDTH_BYTES);
localparam SEGMENT_WIDTH_BITS=$clog2(SEGMENT_WIDTH_BYTES);
// tx states
localparam tx_ST_IDLE=0;
localparam tx_ST_READ=1;
localparam tx_ST_ALU=2;
localparam tx_ST_WRITEBACK=3;
localparam NUM_STATES = 4; // must be power-of-2
// memory request types
localparam op_NONE=0;
localparam op_READ=1;
localparam op_WRITE=2;
localparam op_ATOMIC=3;
localparam NUM_OPS = 4; // must be power-of-2
localparam NO_TX=NUM_TXS;
localparam NUM_TXS_BITS = $clog2(NUM_TXS);
localparam NUM_STATES_BITS = $clog2(NUM_STATES);
localparam NUM_OPS_BITS = $clog2(NUM_OPS);
/********
* Ports *
********/
// Standard global signals
input logic clock;
input logic resetn;
// Arbitration port
input logic mem_arb_read;
input logic mem_arb_write;
input logic [BURST_WIDTH-1:0] mem_arb_burstcount;
input logic [ADDR_WIDTH-1:0] mem_arb_address;
input logic [DATA_WIDTH-1:0] mem_arb_writedata;
input logic [BYTEEN_WIDTH-1:0] mem_arb_byteenable;
output logic mem_arb_waitrequest;
output logic [DATA_WIDTH-1:0] mem_arb_readdata;
output logic mem_arb_readdatavalid;
output logic mem_arb_writeack;
// Avalon port
output mem_avm_read;
output mem_avm_write;
output [BURST_WIDTH-1:0] mem_avm_burstcount;
output [ADDR_WIDTH-1:0] mem_avm_address;
output [DATA_WIDTH-1:0] mem_avm_writedata;
output [BYTEEN_WIDTH-1:0] mem_avm_byteenable;
input mem_avm_waitrequest;
input [DATA_WIDTH-1:0] mem_avm_readdata;
input mem_avm_readdatavalid;
input mem_avm_writeack;
/***********************
* Transaction Metadata *
***********************/
reg [NUM_OPS_BITS-1:0] tx_op [0:NUM_TXS]; // read, write, atomic
reg [NUM_STATES_BITS-1:0] tx_state [0:NUM_TXS]; // read, alu, writeback
reg [ATOMIC_OP_WIDTH-1:0] tx_atomic_op [0:NUM_TXS]; // add, min, max, xor, and, etc.
reg [ADDR_WIDTH-1:0] tx_address [0:NUM_TXS];
reg [BYTEEN_WIDTH-1:0] tx_byteenable [0:NUM_TXS];
reg [BURST_WIDTH-1:0] tx_burstcount [0:NUM_TXS];
reg [DATA_WIDTH_BITS-1:0] tx_segment_address [0:NUM_TXS];
reg [OPERATION_WIDTH-1:0] tx_operand0 [0:NUM_TXS]; // operand0 of atomic operation
reg [OPERATION_WIDTH-1:0] tx_operand1 [0:NUM_TXS]; // operand1 of atomic operation
reg [OPERATION_WIDTH-1:0] tx_atomic_forwarded_readdata [0:NUM_TXS]; // forwarded data from earlier txs
reg tx_atomic_forwarded [0:NUM_TXS]; // data is forwarded from another atomic tx
reg [BYTEEN_WIDTH-1:0] tx_bytedisable [0:NUM_TXS]; // dont write to this address
reg [NUM_TXS-1:0] tx_conflict_list[0:NUM_TXS]; // active txs that this tx is conflicting with
reg [BURST_WIDTH-1:0] tx_num_outstanding_responses [0:NUM_TXS]; // responses this tx will receive, it is initialized to burstcount, tx remains in READ state until it is zero
reg [OPERATION_WIDTH-1:0] tx_writedata [0:NUM_TXS]; // what will be commited to memory
// these registers are used by a single tx at a time, so they are pipelined, and
// not replicated.
reg [OPERATION_WIDTH-1:0] tx_readdata; // what was read from memory, or forwarded, input for alu
wire [OPERATION_WIDTH-1:0] tx_alu_out; // the result of the atomic operation
reg [COUNTER_WIDTH-1:0] count_requests; // number of read requests that are sent to memory
reg [COUNTER_WIDTH-1:0] count_responses; // number of responses received from memory
/******************
* Various Signals *
******************/
reg [NUM_TXS_BITS:0] num_active_atomic_txs; // number of atomic txs in flight
reg [NUM_TXS_BITS:0] free_slot; // unoccupied slot next tx will be inserted in
wire slots_full; // high if all slots are full
// conflict detection
logic atomic_active[0:NUM_TXS];
logic conflicting_ops[0:NUM_TXS];
logic address_conflict[0:NUM_TXS];
logic byteen_conflict[0:NUM_TXS];
logic conflict[0:NUM_TXS];
logic [NUM_TXS:0] conflicts;
wire [NUM_TXS:0] conflicting_txs;
// decode the new transaction
wire [NUM_OPS_BITS-1:0] new_op_type;
wire [OPERATION_WIDTH-1:0] new_operand0;
wire [OPERATION_WIDTH-1:0] new_operand1;
wire [DATA_WIDTH_BITS-1:0] new_segment_address;
wire [ATOMIC_OP_WIDTH-1:0] new_atomic_op;
// find transactions in various stages
wire is_readdata_received;
logic [NUM_TXS_BITS:0] tx_readdata_received;
wire [DATA_WIDTH_BITS-1:0] segment_address_in_read_received;
wire atomic_forwarded_in_read_received;
wire [OPERATION_WIDTH-1:0] atomic_forwarded_readdata_in_read_received;
// oldest tx in READ state
reg [NUM_TXS_BITS:0] tx_next_readdata_received;
reg [NUM_TXS_BITS:0] tx_in_alu;
reg [NUM_OPS_BITS-1:0] op_in_alu;
reg [ATOMIC_OP_WIDTH-1:0] atomic_op_in_alu;
reg [OPERATION_WIDTH-1:0] operand0_in_alu;
reg [OPERATION_WIDTH-1:0] operand1_in_alu;
reg [DATA_WIDTH_BITS-1:0] segment_address_in_alu;
reg [DATA_WIDTH-1:0] tx_alu_out_last; // what was alu out last cycle?
reg [NUM_TXS_BITS:0] tx_in_alu_last; // which tx was in alu last cycle?
reg [NUM_TXS_BITS:0] num_txs_in_writeback; // number of txs waiting to commit to memory
reg [NUM_TXS_BITS:0] tx_in_writeback;
reg [NUM_OPS_BITS-1:0] op_in_writeback;
reg [DATA_WIDTH-1:0] writedata_in_writeback;
reg [ADDR_WIDTH-1:0] address_in_writeback;
reg [BYTEEN_WIDTH-1:0] byteenable_in_writeback;
reg [BURST_WIDTH-1:0] burstcount_in_writeback;
// keep track of oldest/youngest transaction
wire oldest_tx_is_committing;
wire youngest_tx_is_committing;
reg [NUM_TXS_BITS:0] oldest_tx;
reg [NUM_TXS_BITS:0] youngest_tx;
// control signals
wire can_send_read;
wire can_send_non_atomic_write;
wire can_send_atomic_write;
wire can_return_readdata;
wire [DATA_WIDTH-1:0] rrp_readdata;
wire send_read;
wire send_non_atomic_write;
wire send_atomic_write;
wire tx_commits;
wire new_read_request;
wire atomic_tx_starts;
wire atomic_tx_commits;
// support for "free" txs
// (i.e. txs that are not inserted in slots because they are no atomics in flight)
wire free_tx; // no atomic read tx and no atomics in slots.
wire free_tx_starts; // no atomic read tx and no atomics in slots.
wire free_readdata_expected; // next readdata response belongs to a free tx
wire free_readdata_received; // received readdata response belongs to a free tx
reg [COUNTER_WIDTH-1:0] free_requests;
reg [COUNTER_WIDTH-1:0] free_responses;
integer t;
/***************
* Local Memory *
***************/
wire [BURST_WIDTH-1:0] input_burstcount;
// connect unconnected signals in local memory
generate
if( LOCAL_MEM == 0 ) assign input_burstcount = mem_arb_burstcount;
else assign input_burstcount = 1;
endgenerate
/*********************************
* Arbitration/Avalon connections *
*********************************/
assign mem_avm_read = ( send_read || free_tx );
assign mem_avm_write = ( send_non_atomic_write || send_atomic_write );
assign mem_avm_burstcount = ( send_read || free_tx || send_non_atomic_write ) ? input_burstcount : burstcount_in_writeback;
assign mem_avm_address = ( send_read || free_tx || send_non_atomic_write ) ? mem_arb_address : address_in_writeback;
assign mem_avm_writedata = send_non_atomic_write ? mem_arb_writedata : writedata_in_writeback;
assign mem_avm_byteenable = ( send_read || free_tx || send_non_atomic_write ) ? mem_arb_byteenable : byteenable_in_writeback;
assign mem_arb_waitrequest = ( mem_avm_waitrequest || ( mem_arb_read && !can_send_read && !free_tx ) );
assign mem_arb_readdatavalid = ( can_return_readdata | free_readdata_received );
assign mem_arb_writeack = mem_avm_writeack;
assign mem_arb_readdata = free_readdata_received ? mem_avm_readdata : rrp_readdata;
/******************
* Control Signals *
******************/
// a read request (atomic or non-atomic) is stalled if all slots are full or
// there is an atomic tx writing to memory.
// free txs are never stalled.
assign can_send_read = ~free_tx && // no need to occupy slot
~slots_full &&
~send_atomic_write;
// non atomic write has priority, it is never stalled
assign can_send_non_atomic_write = 1'b1;
// atomic writes are stalled only if there is a free tx request
assign can_send_atomic_write = ~( free_tx || ( mem_arb_write && can_send_non_atomic_write) );
// what goes through the atomic module (for arbitration/avalon connections)
assign send_read = mem_arb_read && can_send_read;
assign send_non_atomic_write = mem_arb_write && can_send_non_atomic_write;
assign send_atomic_write = can_send_atomic_write && tx_in_writeback != NO_TX && op_in_writeback == op_ATOMIC;
// what actually happens (take into account waitrequest)
assign tx_can_commit = ( ~mem_avm_waitrequest && can_send_atomic_write );
assign tx_commits = ( ~mem_avm_waitrequest && can_send_atomic_write && tx_in_writeback != NO_TX );
assign new_read_request = ( ~mem_avm_waitrequest && can_send_read && mem_arb_read );
assign atomic_tx_starts = ( ~mem_avm_waitrequest && can_send_read && new_op_type == op_ATOMIC );
assign atomic_tx_commits = ( ~mem_avm_waitrequest && can_send_atomic_write && tx_in_writeback != NO_TX && op_in_writeback == op_ATOMIC );
/*************************
* Decode the new request *
**************************/
assign new_op_type = ( mem_arb_read & mem_arb_writedata[0:0] ) ? op_ATOMIC : mem_arb_read ? op_READ : mem_arb_write ? op_WRITE : op_NONE;
assign new_operand0 = mem_arb_writedata[1 +: OPERATION_WIDTH]; // mem_arb_writedata[32:1]
assign new_operand1 = mem_arb_writedata[OPERATION_WIDTH+1 +: OPERATION_WIDTH]; //mem_arb_writedata[64:33]
assign new_atomic_op = mem_arb_writedata[2*OPERATION_WIDTH+1 +: ATOMIC_OP_WIDTH]; // mem_arb_writedata[70:65]
assign new_segment_address = ( mem_arb_writedata[2*OPERATION_WIDTH+ATOMIC_OP_WIDTH+1 +: DATA_WIDTH_BYTES_BITS ] << (OPERATION_WIDTH_BITS - SEGMENT_WIDTH_BITS) ); // mem_arb_writedata[75:71]
/********************
* Free Transactions *
********************/
assign free_tx = ( new_op_type == op_READ && num_active_atomic_txs == 0 );
assign free_tx_starts = ( free_tx && ~mem_avm_waitrequest );
// the next readdata will belong to a free tx if the number of free requests dont
// match the number of responses received for free txs
assign free_readdata_expected = ( free_requests != free_responses );
assign free_readdata_received = ( ( mem_avm_readdatavalid == 1'b1 ) && ( free_requests != free_responses ) );
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
free_requests <= { COUNTER_WIDTH{1'b0} };
free_responses <= { COUNTER_WIDTH{1'b0} };
end
else begin
if( free_tx_starts ) begin
free_requests <= free_requests + input_burstcount;
end
if( free_readdata_received ) begin
free_responses <= free_responses + 1;
end
end
end
/*****************
* Find Free Slot *
*****************/
assign slots_full = (free_slot == NO_TX);
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
free_slot <= 0;
end
else begin
// initial condition, no tx in flight and there is no new request
if( youngest_tx == NO_TX && !new_read_request ) begin
free_slot <= 0;
end
// no tx in flight, and there is a new request
else if( youngest_tx == NO_TX && new_read_request ) begin
free_slot <= 1;
end
// there are txs in flight, and there is a new request
else if( new_read_request ) begin
free_slot <= ( tx_state[(free_slot+1)%NUM_TXS] == tx_ST_IDLE ) ? ( (free_slot+1)%NUM_TXS ) :
( oldest_tx_is_committing ) ? oldest_tx : NO_TX;
end
// there is no new request and youngest tx (and only tx) is committing
else if( youngest_tx_is_committing ) begin
free_slot <= 0;
end
// there is no new request, all slots are full but oldest tx is committing
else if( oldest_tx_is_committing && free_slot == NO_TX ) begin
free_slot <= oldest_tx;
end
end
end
/***************************
* Find Active Transactions *
****************************/
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
num_active_atomic_txs <= {NUM_TXS_BITS{1'b0}};
end
else begin
// new atomic transaction starting
if( atomic_tx_starts && !atomic_tx_commits ) begin
num_active_atomic_txs <= num_active_atomic_txs + 1;
end
// atomic transaction is committing
if( !atomic_tx_starts && atomic_tx_commits ) begin
num_active_atomic_txs <= num_active_atomic_txs - 1;
end
end
end
/*********************
* Conflict Detection *
*********************/
always @(*)
begin
conflicts = {NUM_TXS{1'b0}};
for (t=0; t<=NUM_TXS; t=t+1)
begin
// tx is active and not committing in this cycle
atomic_active[t] = ( ( tx_state[t] != tx_ST_IDLE ) && !( tx_can_commit && t == tx_in_writeback ) );
// keep track of conflicts only with atomics, non-atomic conflicts do not
// matter because we dont support sequential consistency
conflicting_ops[t] = ( ( new_op_type == op_ATOMIC || new_op_type == op_WRITE ) && ( tx_op[t] == op_ATOMIC ) );
address_conflict[t] = ( tx_address[t] == mem_arb_address );
byteen_conflict[t] = ( ( ( tx_byteenable[t] & ~tx_bytedisable[t] ) & mem_arb_byteenable ) != {BYTEEN_WIDTH{1'b0}} );
conflict[t] = atomic_active[t] & conflicting_ops[t] & address_conflict[t] & byteen_conflict[t];
if( conflict[t] ) begin
conflicts = conflicts | ( 1 << t );
end
end
end
assign conflicting_txs = conflicts;
/******************************
* Youngest/Oldest transaction *
******************************/
assign youngest_tx_is_committing = ( tx_can_commit && tx_in_writeback == youngest_tx );
assign oldest_tx_is_committing = ( tx_can_commit && tx_in_writeback == oldest_tx );
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
youngest_tx <= NO_TX;
end
else begin
// new transaction in free_slot
if( new_read_request ) begin
youngest_tx <= free_slot;
end
else if( youngest_tx_is_committing ) begin
youngest_tx <= NO_TX;
end
end
end
// find the first active transaction that comes after oldest_tx
wire [NUM_TXS_BITS:0] next_oldest_tx;
wire [NUM_TXS_BITS:0] next_oldest_tx_index;
assign next_oldest_tx_index = ( (oldest_tx+1) % NUM_TXS );
assign next_oldest_tx = ( tx_state[ next_oldest_tx_index ] != tx_ST_IDLE ) ? next_oldest_tx_index : NO_TX;
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
oldest_tx <= NO_TX;
end
else begin
// oldest tx is committing, there is no other tx, and there is a new request inserted in free_slot
if( oldest_tx_is_committing && next_oldest_tx == NO_TX && new_read_request ) begin
oldest_tx <= free_slot;
end
// oldest tx is committing, but there are other txs or there is no new request
else if ( oldest_tx_is_committing ) begin
oldest_tx <= next_oldest_tx;
end
// there are no txs in flight, and new request inserted in free_slot
else if ( new_read_request && ( oldest_tx == NO_TX ) ) begin
oldest_tx <= free_slot;
end
end
end
/********************
* State Transitions *
********************/
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_state[t] <= tx_ST_IDLE;
tx_op[t] <= op_NONE;
tx_atomic_op[t] <= {ATOMIC_OP_WIDTH{1'b0}};
tx_address[t] <= {ADDR_WIDTH{1'b0}};
tx_byteenable[t] <= {BYTEEN_WIDTH{1'b0}};
tx_segment_address[t] <= {DATA_WIDTH_BITS{1'b0}};
tx_operand0[t] <= {OPERATION_WIDTH{1'b0}};
tx_operand1[t] <= {OPERATION_WIDTH{1'b0}};
tx_conflict_list[t] <= {NUM_TXS{1'b0}};
end
else begin
case (tx_state[t])
tx_ST_IDLE:
begin
// new request inserted in free_slot
if ( new_read_request && ( t == free_slot ) ) begin
tx_state[t] <= tx_ST_READ;
tx_op[t] <= new_op_type;
tx_atomic_op[t] <= new_atomic_op;
tx_address[t] <= mem_arb_address;
tx_byteenable[t] <= mem_arb_byteenable;
tx_burstcount[t] <= input_burstcount;
tx_segment_address[t] <= new_segment_address;
tx_operand0[t] <= new_operand0;
tx_operand1[t] <= new_operand1;
tx_conflict_list[t] <= conflicting_txs;
end
end
tx_ST_READ:
begin
// readdata received from memory, sending readdatavalid to arb
// all the conflicts must already be resolved, also guaranteed
// to return data in order
// dont switch state unless ALL responses have arrived if burstcount >1
if( tx_readdata_received == t && (tx_num_outstanding_responses[t] == 1) ) begin
tx_state[t] <= tx_ST_ALU;
end
end
// ALU takes a single cycle
tx_ST_ALU:
begin
tx_state[t] <= tx_ST_WRITEBACK;
end
// write atomic result to memory if not stalled
tx_ST_WRITEBACK:
begin
tx_state[t] <= ( tx_can_commit && tx_in_writeback == t ) ? tx_ST_IDLE : tx_ST_WRITEBACK;
end
endcase
end
end
end
/**************************************
* Find Transaction that Receives Data *
**************************************/
// find the first active transaction that comes after tx_next_readdata_received
wire [NUM_TXS_BITS:0] next_tx_next_readdata_received;
wire [NUM_TXS_BITS:0] next_tx_next_readdata_received_index;
// the next-next tx that will receive readdata comes after the current tx expecting readddata
assign next_tx_next_readdata_received_index = ( (tx_next_readdata_received+1) % NUM_TXS );
// the next tx has already issued a read request, or it is issueing it in this cycle
assign next_tx_next_readdata_received = ( tx_state[ next_tx_next_readdata_received_index ] == tx_ST_READ ||
( new_read_request && free_slot == next_tx_next_readdata_received_index ) ) ? next_tx_next_readdata_received_index : NO_TX;
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
tx_next_readdata_received <= NO_TX;
end
else begin
// currently no tx is expecting readdata and there is a new tx at free_slot
if( tx_next_readdata_received == NO_TX && new_read_request ) begin
tx_next_readdata_received <= free_slot;
end
// the tx that expects readdata received it in this cycle,
// so it is not expecting readdata anymore, move to the next
else if ( tx_next_readdata_received != NO_TX &&
mem_avm_readdatavalid &&
~free_readdata_expected &&
// all readdata responses have been received in case burstcount > 1
( tx_num_outstanding_responses[tx_next_readdata_received] == 1 ) ) begin
tx_next_readdata_received <= next_tx_next_readdata_received;
end
end
end
// certain parameters that belong to tx that receives the readdata in this cycle
// if no readdata is received (i.e. tx_readdata_received == NO_TX ),
// these values would be wrong, but neither alu input nor return readdata does not matter anyways
assign segment_address_in_read_received = tx_segment_address[tx_next_readdata_received];
assign atomic_forwarded_in_read_received = tx_atomic_forwarded[tx_next_readdata_received];
assign atomic_forwarded_readdata_in_read_received = tx_atomic_forwarded_readdata[tx_next_readdata_received];
assign is_readdata_received = ( mem_avm_readdatavalid && ~free_readdata_expected );
assign tx_readdata_received = is_readdata_received ? tx_next_readdata_received : NO_TX;
/**************************
* Find Transaction in ALU *
**************************/
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
tx_in_alu <= NO_TX;
op_in_alu <= op_NONE;
atomic_op_in_alu <= op_NONE;
operand0_in_alu <= {OPERATION_WIDTH{1'b0}};
operand1_in_alu <= {OPERATION_WIDTH{1'b0}};
segment_address_in_alu <= {DATA_WIDTH_BITS{1'b0}};
end
// do not transition to alu state if tx that received readdata has burstcount > 1
// and still serving outstanding requests
else if(tx_num_outstanding_responses[tx_readdata_received] != 1) begin
tx_in_alu <= NO_TX;
end
else begin
tx_in_alu <= tx_readdata_received;
op_in_alu <= tx_op[tx_next_readdata_received];
atomic_op_in_alu <= tx_atomic_op[tx_next_readdata_received];
operand0_in_alu <= tx_operand0[tx_next_readdata_received];
operand1_in_alu <= tx_operand1[tx_next_readdata_received];
segment_address_in_alu <= tx_segment_address[tx_next_readdata_received];
end
end
// find tx that was in alu in the last cycle
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
tx_alu_out_last <= { DATA_WIDTH{1'bx} };
tx_in_alu_last <= NO_TX;
end
else begin
tx_alu_out_last <= tx_alu_out;
tx_in_alu_last <= tx_in_alu;
end
end
/***************************************
* Find Transactions in Writeback State *
***************************************/
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
num_txs_in_writeback <= {NUM_TXS_BITS{1'b0}};
end
else
begin
if( tx_commits && tx_in_alu == NO_TX ) begin
num_txs_in_writeback <= num_txs_in_writeback - 1;
end
else if( !tx_commits && tx_in_alu != NO_TX ) begin
num_txs_in_writeback <= num_txs_in_writeback + 1;
end
end
end
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
tx_in_writeback <= NO_TX;
op_in_writeback <= op_NONE;
writedata_in_writeback <= {DATA_WIDTH{1'b0}};
address_in_writeback <= {ADDR_WIDTH{1'b0}};
byteenable_in_writeback <= {BYTEEN_WIDTH{1'b0}};
burstcount_in_writeback <= {BURST_WIDTH{1'b0}};
end
else
// oldest tx (i.e. tx_in_writeback) is committing
// and next_oldest is also in atomic_writeback
if( tx_can_commit && num_txs_in_writeback > 1 )
//if(oldest_tx_is_committing && tx_state[next_oldest_tx_index] == tx_ST_WRITEBACK )
begin
tx_in_writeback <= next_oldest_tx;
op_in_writeback <= tx_op[next_oldest_tx_index];
writedata_in_writeback <= ( tx_writedata[next_oldest_tx_index] << tx_segment_address[next_oldest_tx_index] );
address_in_writeback <= tx_address[next_oldest_tx_index];
byteenable_in_writeback <= ( tx_byteenable[next_oldest_tx_index] & ~tx_bytedisable[next_oldest_tx_index] );
burstcount_in_writeback <= tx_burstcount[next_oldest_tx_index];
end
else
// oldest tx (i.e. tx_in_writeback) is committing
// or there is no tx in atomic writeback stage
if( tx_can_commit || ( num_txs_in_writeback == 0 ) )
begin
tx_in_writeback <= tx_in_alu;
op_in_writeback <= tx_op[tx_in_alu];
writedata_in_writeback <= ( tx_alu_out << segment_address_in_alu );
address_in_writeback <= tx_address[tx_in_alu];
byteenable_in_writeback <= ( tx_byteenable[tx_in_alu] & ~tx_bytedisable[tx_in_alu] );
burstcount_in_writeback <= tx_burstcount[tx_in_alu];
end
end
/********************************
* Count read requests/responses *
********************************/
always@(posedge clock or negedge resetn)
begin
if ( !resetn ) begin
count_requests <= { COUNTER_WIDTH{1'b0} };
count_responses <= { COUNTER_WIDTH{1'b0} };
end
else begin
// new read request
if( mem_avm_read & ~mem_avm_waitrequest ) begin
count_requests <= count_requests + input_burstcount;
end
// new read response
if( mem_avm_readdatavalid ) begin
count_responses <= count_responses + 1;
end
end
end
/****************************************
* Compute outstanding requests for a tx *
****************************************/
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_num_outstanding_responses[t] <= {BURST_WIDTH{1'b0}};
end
else if( new_read_request && t == free_slot ) begin
tx_num_outstanding_responses[t] <= input_burstcount;
end
else if( t == tx_readdata_received ) begin //&& tx_state[t] == tx_ST_READ ) begin
tx_num_outstanding_responses[t] <= tx_num_outstanding_responses[t] - 1;
end
end
end
/**********************************
* Non-atomic Write to Bytedisable *
**********************************/
// WARNING: Arbitration should make sure that a non-atomic write and atomic writeback
// do not happen in the same cycle. Thus, atomic does not miss the bytedisable
// signal when it writebacks
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_bytedisable[t] <= {BYTEEN_WIDTH{1'b0}};
end
else if ( tx_state[t] == tx_ST_IDLE ) begin
tx_bytedisable[t] <= {BYTEEN_WIDTH{1'b0}};
end
else
// conflicting write with this tx
if( mem_arb_write && ( conflicts & (1 << t) ) ) begin
tx_bytedisable[t] <= ( tx_bytedisable[t] | mem_arb_byteenable );
end
end
end
/****************************
* Find conflict with ALU tx *
****************************/
// detect the dependence early, so next cycle we know the conflict
reg readdata_received_conflicts_with_alu;
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
readdata_received_conflicts_with_alu <= 1'b0;
end
// readdata is received by a tx and this tx conflicts with tx that comes after it
// i.e. when this tx reaches ALU in the next cycle, it will conflict with the
// tx that receives readdata
else if ( ( is_readdata_received ) &&
( ( tx_conflict_list[next_tx_next_readdata_received_index] & (1 << tx_next_readdata_received) ) != 0 ) ) begin
readdata_received_conflicts_with_alu <= 1'b1;
end
else begin
readdata_received_conflicts_with_alu <= 1'b0;
end
end
/**************************
* Compute Return Readdata *
**************************/
logic [DATA_WIDTH-1:0] merge_readdata;
integer p;
always@(*)
begin
merge_readdata = mem_avm_readdata;
// merge with alu out
if( readdata_received_conflicts_with_alu ) begin
merge_readdata[segment_address_in_read_received +: OPERATION_WIDTH] = tx_alu_out;
end
// merge with forwarded data
else if( atomic_forwarded_in_read_received == 1'b1 ) begin
merge_readdata[segment_address_in_read_received +: OPERATION_WIDTH] = atomic_forwarded_readdata_in_read_received;
end
end
// readdata path is guaranteed to be in program order because
// a single tx will send read signal in each cycle
assign can_return_readdata = is_readdata_received;
assign rrp_readdata = merge_readdata;
/*******************
* Select ALU Input *
*******************/
wire [OPERATION_WIDTH-1:0] selected_readdata;
assign selected_readdata = readdata_received_conflicts_with_alu ? tx_alu_out :
( atomic_forwarded_in_read_received == 1'b1 ) ? atomic_forwarded_readdata_in_read_received :
mem_avm_readdata[segment_address_in_read_received +: OPERATION_WIDTH];
always@(posedge clock or negedge resetn)
begin
if (!resetn) begin
tx_readdata <= {OPERATION_WIDTH{1'b0}};
end
else begin
tx_readdata <= selected_readdata;
end
end
/*********************
* Compute Atomic Out *
*********************/
atomic_alu # (.USED_ATOMIC_OPERATIONS(USED_ATOMIC_OPERATIONS), .ATOMIC_OP_WIDTH(ATOMIC_OP_WIDTH), .OPERATION_WIDTH(OPERATION_WIDTH)) tx_alu
(
.readdata( tx_readdata ),
.atomic_op( atomic_op_in_alu ),
.operand0( operand0_in_alu ),
.operand1( operand1_in_alu ),
.atomic_out( tx_alu_out )
);
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_writedata[t] <= {DATA_WIDTH{1'b0}};
end
else if( tx_state[t] == tx_ST_ALU ) begin
tx_writedata[t] <= tx_alu_out;
end
end
end
/******************
* Data Forwarding *
******************/
always@(posedge clock or negedge resetn)
begin
for (t=0; t<=NUM_TXS; t=t+1)
begin
if (!resetn) begin
tx_atomic_forwarded_readdata[t] <= {OPERATION_WIDTH{1'b0}};
tx_atomic_forwarded[t] <= 1'b0;
end
// this tx is a new tx
else if( mem_arb_read == 1'b1 && t == free_slot ) begin
tx_atomic_forwarded_readdata[t] <= {OPERATION_WIDTH{1'b0}};
tx_atomic_forwarded[t] <= 1'b0;
end
// this tx has a conflict with the tx in ALU
else if( (tx_conflict_list[t] & (1 << tx_in_alu)) != 0 ) begin
tx_atomic_forwarded_readdata[t] <= tx_alu_out;
tx_atomic_forwarded[t] <= 1'b1;
end
// this tx had a conflict with the tx in ALU last cycle (matters when this is a new tx)
else if( ( tx_conflict_list[t] & (1 << tx_in_alu_last) ) != 0 ) begin
tx_atomic_forwarded_readdata[t] <= tx_alu_out_last;
tx_atomic_forwarded[t] <= 1'b1;
end
end
end
endmodule
/****************************
* ALU for atomic operations *
****************************/
module atomic_alu
(
readdata,
atomic_op,
operand0,
operand1,
atomic_out
);
parameter ATOMIC_OP_WIDTH=3; // this many atomic operations
parameter OPERATION_WIDTH=32; // atomic operations are ALL 32-bit
parameter USED_ATOMIC_OPERATIONS=8'b00000001;
// WARNING: these MUST match ACLIntrinsics::ID enum in ACLIntrinsics.h
localparam a_ADD=0;
localparam a_XCHG=1;
localparam a_CMPXCHG=2;
localparam a_MIN=3;
localparam a_MAX=4;
localparam a_AND=5;
localparam a_OR=6;
localparam a_XOR=7;
// Standard global signals
input logic [OPERATION_WIDTH-1:0] readdata;
input logic [ATOMIC_OP_WIDTH-1:0] atomic_op;
input logic [OPERATION_WIDTH-1:0] operand0;
input logic [OPERATION_WIDTH-1:0] operand1;
output logic [OPERATION_WIDTH-1:0] atomic_out;
wire [31:0] atomic_out_add /* synthesis keep */;
wire [31:0] atomic_out_cmp /* synthesis keep */;
wire [31:0] atomic_out_cmpxchg /* synthesis keep */;
wire [31:0] atomic_out_min /* synthesis keep */;
wire [31:0] atomic_out_max /* synthesis keep */;
wire [31:0] atomic_out_and /* synthesis keep */;
wire [31:0] atomic_out_or /* synthesis keep */;
wire [31:0] atomic_out_xor /* synthesis keep */;
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_ADD) ) != 0 ) assign atomic_out_add = readdata + operand0;
else assign atomic_out_add = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_XCHG) ) != 0 ) assign atomic_out_cmp = operand0;
else assign atomic_out_cmp = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_CMPXCHG) ) != 0 ) assign atomic_out_cmpxchg = ( readdata == operand0 ) ? operand1 : readdata;
else assign atomic_out_cmpxchg = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_MIN) ) != 0 ) assign atomic_out_min = ( readdata < operand0 ) ? readdata : operand0;
else assign atomic_out_min = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_MAX) ) != 0 ) assign atomic_out_max = (readdata > operand0) ? readdata : operand0;
else assign atomic_out_max = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_AND) ) != 0 ) assign atomic_out_and = ( readdata & operand0 );
else assign atomic_out_and = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_OR) ) != 0 ) assign atomic_out_or = ( readdata | operand0 );
else assign atomic_out_or = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
generate
if( ( USED_ATOMIC_OPERATIONS & (1 << a_XOR) ) != 0 ) assign atomic_out_xor = ( readdata ^ operand0 );
else assign atomic_out_xor = {ATOMIC_OP_WIDTH{1'bx}};
endgenerate
always @(*)
begin
case ( atomic_op )
a_ADD:
begin
atomic_out = atomic_out_add;
end
a_XCHG:
begin
atomic_out = atomic_out_cmp;
end
a_CMPXCHG:
begin
atomic_out = atomic_out_cmpxchg;
end
a_MIN:
begin
atomic_out = atomic_out_min;
end
a_MAX:
begin
atomic_out = atomic_out_max;
end
a_AND:
begin
atomic_out = atomic_out_and;
end
a_OR:
begin
atomic_out = atomic_out_or;
end
default:
begin
atomic_out = atomic_out_xor;
end
endcase
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_slave_rrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
parameter integer FIFO_DEPTH = 32, // > 0 (don't care if SLAVE_FIXED_LATENCY > 0)
parameter integer USE_LL_FIFO = 1, // 0|1
parameter integer SLAVE_FIXED_LATENCY = 0, // 0=not fixed latency, >0=# fixed latency cycles
// if >0 effectively FIFO_DEPTH=SLAVE_FIXED_LATENCY+1
parameter integer PIPELINE = 1 // 0|1
)
(
input logic clock,
input logic resetn,
acl_arb_intf m_intf,
input logic s_readdatavalid,
input logic [DATA_W-1:0] s_readdata,
acl_ic_rrp_intf rrp_intf,
output logic stall
);
typedef struct packed {
logic valid;
logic [DATA_W-1:0] data;
} slave_raw_read;
slave_raw_read slave_read_in;
slave_raw_read slave_read; // this is the slave interface to the rest of the module
assign slave_read_in = {s_readdatavalid, s_readdata};
generate
if( PIPELINE )
begin
// Pipeline the return path from the slave.
slave_raw_read slave_read_pipe;
always @(posedge clock or negedge resetn)
if( !resetn )
begin
slave_read_pipe <= 'x;
slave_read_pipe.valid <= 1'b0;
end
else
slave_read_pipe <= slave_read_in;
assign slave_read = slave_read_pipe;
end
else
begin
assign slave_read = slave_read_in;
end
endgenerate
generate
if( NUM_MASTERS > 1 )
begin
localparam READ_FIFO_DEPTH = SLAVE_FIXED_LATENCY > 0 ? SLAVE_FIXED_LATENCY : FIFO_DEPTH;
typedef struct packed {
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} raw_read_item;
typedef struct packed {
logic valid;
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} read_item;
logic rf_full, rf_empty, rf_read, rf_write, next_read_item;
raw_read_item m_raw_read_item, rf_raw_read_item;
read_item rf_read_item, cur_read_item;
// FIFO of pending reads.
// Two parts to this FIFO:
// 1. An actual FIFO (either llfifo or scfifo).
// 2. cur_read_item is the current pending read
//
// Together, there must be at least READ_FIFO_DEPTH
// entries. Since cur_read_item counts as one,
// the actual FIFOs are sized to READ_FIFO_DEPTH-1.
if( USE_LL_FIFO == 1 )
begin
acl_ll_fifo #(
.WIDTH( $bits(raw_read_item) ),
.DEPTH( READ_FIFO_DEPTH - 1 )
)
read_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_raw_read_item ),
.write( rf_write ),
.data_out( rf_raw_read_item ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
end
else
begin
scfifo #(
.lpm_width( $bits(raw_read_item) ),
.lpm_widthu( $clog2(READ_FIFO_DEPTH-1) ),
.lpm_numwords( READ_FIFO_DEPTH-1 ),
.add_ram_output_register( "ON" ),
.intended_device_family( "stratixiv" )
)
read_fifo (
.aclr( ~resetn ),
.clock( clock ),
.empty( rf_empty ),
.full( rf_full ),
.data( m_raw_read_item ),
.q( rf_raw_read_item ),
.wrreq( rf_write ),
.rdreq( rf_read ),
.sclr(),
.usedw(),
.almost_full(),
.almost_empty()
);
end
assign m_raw_read_item.id = m_intf.req.id;
assign m_raw_read_item.burstcount = m_intf.req.burstcount;
assign rf_read_item.id = rf_raw_read_item.id;
assign rf_read_item.burstcount = rf_raw_read_item.burstcount;
// Place incoming read requests from the master into read FIFO.
assign rf_write = ~m_intf.stall & m_intf.req.read;
// Read next item from the FIFO.
assign rf_read = ~rf_empty & (~rf_read_item.valid | next_read_item);
// Determine when cur_read_item can be updated, which is controlled by next_read_item.
assign next_read_item = ~cur_read_item.valid | (slave_read.valid & (cur_read_item.burstcount == 1));
// Stall upstream when read FIFO is full. If the slave is fixed latency, the read FIFO
// is sized such that it can never stall.
assign stall = SLAVE_FIXED_LATENCY > 0 ? 1'b0 : rf_full;
// cur_read_item
always @( posedge clock or negedge resetn )
begin
if( !resetn )
begin
cur_read_item <= 'x; // only fields explicitly reset below need to be reset at all
cur_read_item.valid <= 1'b0;
end
else
begin
// Handle incoming data from the slave.
if( slave_read.valid )
cur_read_item.burstcount <= cur_read_item.burstcount - 1;
// Update current read from the read FIFO. This logic takes priority over
// the logic above (both update cur_read_item.burstcount).
if( next_read_item )
cur_read_item <= rf_read_item;
end
end
// rrp_intf
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign rrp_intf.id = cur_read_item.id;
// Handle the rf_read_item.valid signal. Different behavior between
// sc_fifo and acl_ll_fifo.
if( USE_LL_FIFO == 1 )
begin
// The data is already at the output of the acl_ll_fifo, so the
// data is valid as long as the FIFO is not empty.
assign rf_read_item.valid = ~rf_empty;
end
else
begin
// The data is valid on the next cycle (due to output register on
// scfifo RAM block).
always @( posedge clock or negedge resetn )
begin
if( !resetn )
rf_read_item.valid <= 1'b0;
else if( rf_read )
rf_read_item.valid <= 1'b1;
else if( next_read_item & ~rf_read )
rf_read_item.valid <= 1'b0;
end
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign stall = 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_slave_rrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
parameter integer FIFO_DEPTH = 32, // > 0 (don't care if SLAVE_FIXED_LATENCY > 0)
parameter integer USE_LL_FIFO = 1, // 0|1
parameter integer SLAVE_FIXED_LATENCY = 0, // 0=not fixed latency, >0=# fixed latency cycles
// if >0 effectively FIFO_DEPTH=SLAVE_FIXED_LATENCY+1
parameter integer PIPELINE = 1 // 0|1
)
(
input logic clock,
input logic resetn,
acl_arb_intf m_intf,
input logic s_readdatavalid,
input logic [DATA_W-1:0] s_readdata,
acl_ic_rrp_intf rrp_intf,
output logic stall
);
typedef struct packed {
logic valid;
logic [DATA_W-1:0] data;
} slave_raw_read;
slave_raw_read slave_read_in;
slave_raw_read slave_read; // this is the slave interface to the rest of the module
assign slave_read_in = {s_readdatavalid, s_readdata};
generate
if( PIPELINE )
begin
// Pipeline the return path from the slave.
slave_raw_read slave_read_pipe;
always @(posedge clock or negedge resetn)
if( !resetn )
begin
slave_read_pipe <= 'x;
slave_read_pipe.valid <= 1'b0;
end
else
slave_read_pipe <= slave_read_in;
assign slave_read = slave_read_pipe;
end
else
begin
assign slave_read = slave_read_in;
end
endgenerate
generate
if( NUM_MASTERS > 1 )
begin
localparam READ_FIFO_DEPTH = SLAVE_FIXED_LATENCY > 0 ? SLAVE_FIXED_LATENCY : FIFO_DEPTH;
typedef struct packed {
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} raw_read_item;
typedef struct packed {
logic valid;
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} read_item;
logic rf_full, rf_empty, rf_read, rf_write, next_read_item;
raw_read_item m_raw_read_item, rf_raw_read_item;
read_item rf_read_item, cur_read_item;
// FIFO of pending reads.
// Two parts to this FIFO:
// 1. An actual FIFO (either llfifo or scfifo).
// 2. cur_read_item is the current pending read
//
// Together, there must be at least READ_FIFO_DEPTH
// entries. Since cur_read_item counts as one,
// the actual FIFOs are sized to READ_FIFO_DEPTH-1.
if( USE_LL_FIFO == 1 )
begin
acl_ll_fifo #(
.WIDTH( $bits(raw_read_item) ),
.DEPTH( READ_FIFO_DEPTH - 1 )
)
read_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_raw_read_item ),
.write( rf_write ),
.data_out( rf_raw_read_item ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
end
else
begin
scfifo #(
.lpm_width( $bits(raw_read_item) ),
.lpm_widthu( $clog2(READ_FIFO_DEPTH-1) ),
.lpm_numwords( READ_FIFO_DEPTH-1 ),
.add_ram_output_register( "ON" ),
.intended_device_family( "stratixiv" )
)
read_fifo (
.aclr( ~resetn ),
.clock( clock ),
.empty( rf_empty ),
.full( rf_full ),
.data( m_raw_read_item ),
.q( rf_raw_read_item ),
.wrreq( rf_write ),
.rdreq( rf_read ),
.sclr(),
.usedw(),
.almost_full(),
.almost_empty()
);
end
assign m_raw_read_item.id = m_intf.req.id;
assign m_raw_read_item.burstcount = m_intf.req.burstcount;
assign rf_read_item.id = rf_raw_read_item.id;
assign rf_read_item.burstcount = rf_raw_read_item.burstcount;
// Place incoming read requests from the master into read FIFO.
assign rf_write = ~m_intf.stall & m_intf.req.read;
// Read next item from the FIFO.
assign rf_read = ~rf_empty & (~rf_read_item.valid | next_read_item);
// Determine when cur_read_item can be updated, which is controlled by next_read_item.
assign next_read_item = ~cur_read_item.valid | (slave_read.valid & (cur_read_item.burstcount == 1));
// Stall upstream when read FIFO is full. If the slave is fixed latency, the read FIFO
// is sized such that it can never stall.
assign stall = SLAVE_FIXED_LATENCY > 0 ? 1'b0 : rf_full;
// cur_read_item
always @( posedge clock or negedge resetn )
begin
if( !resetn )
begin
cur_read_item <= 'x; // only fields explicitly reset below need to be reset at all
cur_read_item.valid <= 1'b0;
end
else
begin
// Handle incoming data from the slave.
if( slave_read.valid )
cur_read_item.burstcount <= cur_read_item.burstcount - 1;
// Update current read from the read FIFO. This logic takes priority over
// the logic above (both update cur_read_item.burstcount).
if( next_read_item )
cur_read_item <= rf_read_item;
end
end
// rrp_intf
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign rrp_intf.id = cur_read_item.id;
// Handle the rf_read_item.valid signal. Different behavior between
// sc_fifo and acl_ll_fifo.
if( USE_LL_FIFO == 1 )
begin
// The data is already at the output of the acl_ll_fifo, so the
// data is valid as long as the FIFO is not empty.
assign rf_read_item.valid = ~rf_empty;
end
else
begin
// The data is valid on the next cycle (due to output register on
// scfifo RAM block).
always @( posedge clock or negedge resetn )
begin
if( !resetn )
rf_read_item.valid <= 1'b0;
else if( rf_read )
rf_read_item.valid <= 1'b1;
else if( next_read_item & ~rf_read )
rf_read_item.valid <= 1'b0;
end
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign stall = 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
(***********************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA-Rocquencourt & LRI-CNRS-Orsay *)
(* \VV/ *************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(***********************************************************************)
(**************************************************************)
(* MSetDecide.v *)
(* *)
(* Author: Aaron Bohannon *)
(**************************************************************)
(** This file implements a decision procedure for a certain
class of propositions involving finite sets. *)
Require Import Decidable DecidableTypeEx MSetFacts.
(** First, a version for Weak Sets in functorial presentation *)
Module WDecideOn (E : DecidableType)(Import M : WSetsOn E).
Module F := MSetFacts.WFactsOn E M.
(** * Overview
This functor defines the tactic [fsetdec], which will
solve any valid goal of the form
<<
forall s1 ... sn,
forall x1 ... xm,
P1 -> ... -> Pk -> P
>>
where [P]'s are defined by the grammar:
<<
P ::=
| Q
| Empty F
| Subset F F'
| Equal F F'
Q ::=
| E.eq X X'
| In X F
| Q /\ Q'
| Q \/ Q'
| Q -> Q'
| Q <-> Q'
| ~ Q
| True
| False
F ::=
| S
| empty
| singleton X
| add X F
| remove X F
| union F F'
| inter F F'
| diff F F'
X ::= x1 | ... | xm
S ::= s1 | ... | sn
>>
The tactic will also work on some goals that vary slightly from
the above form:
- The variables and hypotheses may be mixed in any order and may
have already been introduced into the context. Moreover,
there may be additional, unrelated hypotheses mixed in (these
will be ignored).
- A conjunction of hypotheses will be handled as easily as
separate hypotheses, i.e., [P1 /\ P2 -> P] can be solved iff
[P1 -> P2 -> P] can be solved.
- [fsetdec] should solve any goal if the MSet-related hypotheses
are contradictory.
- [fsetdec] will first perform any necessary zeta and beta
reductions and will invoke [subst] to eliminate any Coq
equalities between finite sets or their elements.
- If [E.eq] is convertible with Coq's equality, it will not
matter which one is used in the hypotheses or conclusion.
- The tactic can solve goals where the finite sets or set
elements are expressed by Coq terms that are more complicated
than variables. However, non-local definitions are not
expanded, and Coq equalities between non-variable terms are
not used. For example, this goal will be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2)
>>
This one will not be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2)
>>
*)
(** * Facts and Tactics for Propositional Logic
These lemmas and tactics are in a module so that they do
not affect the namespace if you import the enclosing
module [Decide]. *)
Module MSetLogicalFacts.
Require Export Decidable.
Require Export Setoid.
(** ** Lemmas and Tactics About Decidable Propositions *)
(** ** Propositional Equivalences Involving Negation
These are all written with the unfolded form of
negation, since I am not sure if setoid rewriting will
always perform conversion. *)
(** ** Tactics for Negations *)
Tactic Notation "fold" "any" "not" :=
repeat (
match goal with
| H: context [?P -> False] |- _ =>
fold (~ P) in H
| |- context [?P -> False] =>
fold (~ P)
end).
(** [push not using db] will pushes all negations to the
leaves of propositions in the goal, using the lemmas in
[db] to assist in checking the decidability of the
propositions involved. If [using db] is omitted, then
[core] will be used. Additional versions are provided
to manipulate the hypotheses or the hypotheses and goal
together.
XXX: This tactic and the similar subsequent ones should
have been defined using [autorewrite]. However, dealing
with multiples rewrite sites and side-conditions is
done more cleverly with the following explicit
analysis of goals. *)
Ltac or_not_l_iff P Q tac :=
(rewrite (or_not_l_iff_1 P Q) by tac) ||
(rewrite (or_not_l_iff_2 P Q) by tac).
Ltac or_not_r_iff P Q tac :=
(rewrite (or_not_r_iff_1 P Q) by tac) ||
(rewrite (or_not_r_iff_2 P Q) by tac).
Ltac or_not_l_iff_in P Q H tac :=
(rewrite (or_not_l_iff_1 P Q) in H by tac) ||
(rewrite (or_not_l_iff_2 P Q) in H by tac).
Ltac or_not_r_iff_in P Q H tac :=
(rewrite (or_not_r_iff_1 P Q) in H by tac) ||
(rewrite (or_not_r_iff_2 P Q) in H by tac).
Tactic Notation "push" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [?P \/ ?Q -> False] => rewrite (not_or_iff P Q)
| |- context [?P /\ ?Q -> False] => rewrite (not_and_iff P Q)
| |- context [(?P -> ?Q) -> False] => rewrite (not_imp_iff P Q) by dec
end);
fold any not.
Tactic Notation "push" "not" :=
push not using core.
Tactic Notation
"push" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [?P \/ ?Q -> False] |- _ => rewrite (not_or_iff P Q) in H
| H: context [?P /\ ?Q -> False] |- _ => rewrite (not_and_iff P Q) in H
| H: context [(?P -> ?Q) -> False] |- _ =>
rewrite (not_imp_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "push" "not" "in" "*" "|-" :=
push not in * |- using core.
Tactic Notation "push" "not" "in" "*" "using" ident(db) :=
push not using db; push not in * |- using db.
Tactic Notation "push" "not" "in" "*" :=
push not in * using core.
(** A simple test case to see how this works. *)
Lemma test_push : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ ((R -> P) \/ (Q -> R))) ->
(~ (P /\ R)) ->
(~ (P -> R)) ->
True.
Proof.
intros. push not in *.
(* note that ~(R->P) remains (since R isnt decidable) *)
tauto.
Qed.
(** [pull not using db] will pull as many negations as
possible toward the top of the propositions in the goal,
using the lemmas in [db] to assist in checking the
decidability of the propositions involved. If [using
db] is omitted, then [core] will be used. Additional
versions are provided to manipulate the hypotheses or
the hypotheses and goal together. *)
Tactic Notation "pull" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [(?P -> False) /\ (?Q -> False)] =>
rewrite <- (not_or_iff P Q)
| |- context [?P -> ?Q -> False] => rewrite <- (not_and_iff P Q)
| |- context [?P /\ (?Q -> False)] => rewrite <- (not_imp_iff P Q) by dec
| |- context [(?Q -> False) /\ ?P] =>
rewrite <- (not_imp_rev_iff P Q) by dec
end);
fold any not.
Tactic Notation "pull" "not" :=
pull not using core.
Tactic Notation
"pull" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
rewrite <- (not_or_iff P Q) in H
| H: context [?P -> ?Q -> False] |- _ =>
rewrite <- (not_and_iff P Q) in H
| H: context [?P /\ (?Q -> False)] |- _ =>
rewrite <- (not_imp_iff P Q) in H by dec
| H: context [(?Q -> False) /\ ?P] |- _ =>
rewrite <- (not_imp_rev_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "pull" "not" "in" "*" "|-" :=
pull not in * |- using core.
Tactic Notation "pull" "not" "in" "*" "using" ident(db) :=
pull not using db; pull not in * |- using db.
Tactic Notation "pull" "not" "in" "*" :=
pull not in * using core.
(** A simple test case to see how this works. *)
Lemma test_pull : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ (R -> P) /\ ~ (Q -> R)) ->
(~ P \/ ~ R) ->
(P /\ ~ R) ->
(~ R /\ P) ->
True.
Proof.
intros. pull not in *. tauto.
Qed.
End MSetLogicalFacts.
Import MSetLogicalFacts.
(** * Auxiliary Tactics
Again, these lemmas and tactics are in a module so that
they do not affect the namespace if you import the
enclosing module [Decide]. *)
Module MSetDecideAuxiliary.
(** ** Generic Tactics
We begin by defining a few generic, useful tactics. *)
(** remove logical hypothesis inter-dependencies (fix #2136). *)
Ltac no_logical_interdep :=
match goal with
| H : ?P |- _ =>
match type of P with
| Prop =>
match goal with H' : context [ H ] |- _ => clear dependent H' end
| _ => fail
end; no_logical_interdep
| _ => idtac
end.
(** [if t then t1 else t2] executes [t] and, if it does not
fail, then [t1] will be applied to all subgoals
produced. If [t] fails, then [t2] is executed. *)
Tactic Notation
"if" tactic(t)
"then" tactic(t1)
"else" tactic(t2) :=
first [ t; first [ t1 | fail 2 ] | t2 ].
Ltac abstract_term t :=
if (is_var t) then fail "no need to abstract a variable"
else (let x := fresh "x" in set (x := t) in *; try clearbody x).
Ltac abstract_elements :=
repeat
(match goal with
| |- context [ singleton ?t ] => abstract_term t
| _ : context [ singleton ?t ] |- _ => abstract_term t
| |- context [ add ?t _ ] => abstract_term t
| _ : context [ add ?t _ ] |- _ => abstract_term t
| |- context [ remove ?t _ ] => abstract_term t
| _ : context [ remove ?t _ ] |- _ => abstract_term t
| |- context [ In ?t _ ] => abstract_term t
| _ : context [ In ?t _ ] |- _ => abstract_term t
end).
(** [prop P holds by t] succeeds (but does not modify the
goal or context) if the proposition [P] can be proved by
[t] in the current context. Otherwise, the tactic
fails. *)
Tactic Notation "prop" constr(P) "holds" "by" tactic(t) :=
let H := fresh in
assert P as H by t;
clear H.
(** This tactic acts just like [assert ... by ...] but will
fail if the context already contains the proposition. *)
Tactic Notation "assert" "new" constr(e) "by" tactic(t) :=
match goal with
| H: e |- _ => fail 1
| _ => assert e by t
end.
(** [subst++] is similar to [subst] except that
- it never fails (as [subst] does on recursive
equations),
- it substitutes locally defined variable for their
definitions,
- it performs beta reductions everywhere, which may
arise after substituting a locally defined function
for its definition.
*)
Tactic Notation "subst" "++" :=
repeat (
match goal with
| x : _ |- _ => subst x
end);
cbv zeta beta in *.
(** [decompose records] calls [decompose record H] on every
relevant hypothesis [H]. *)
Tactic Notation "decompose" "records" :=
repeat (
match goal with
| H: _ |- _ => progress (decompose record H); clear H
end).
(** ** Discarding Irrelevant Hypotheses
We will want to clear the context of any
non-MSet-related hypotheses in order to increase the
speed of the tactic. To do this, we will need to be
able to decide which are relevant. We do this by making
a simple inductive definition classifying the
propositions of interest. *)
Inductive MSet_elt_Prop : Prop -> Prop :=
| eq_Prop : forall (S : Type) (x y : S),
MSet_elt_Prop (x = y)
| eq_elt_prop : forall x y,
MSet_elt_Prop (E.eq x y)
| In_elt_prop : forall x s,
MSet_elt_Prop (In x s)
| True_elt_prop :
MSet_elt_Prop True
| False_elt_prop :
MSet_elt_Prop False
| conj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P /\ Q)
| disj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P \/ Q)
| impl_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P -> Q)
| not_elt_prop : forall P,
MSet_elt_Prop P ->
MSet_elt_Prop (~ P).
Inductive MSet_Prop : Prop -> Prop :=
| elt_MSet_Prop : forall P,
MSet_elt_Prop P ->
MSet_Prop P
| Empty_MSet_Prop : forall s,
MSet_Prop (Empty s)
| Subset_MSet_Prop : forall s1 s2,
MSet_Prop (Subset s1 s2)
| Equal_MSet_Prop : forall s1 s2,
MSet_Prop (Equal s1 s2).
(** Here is the tactic that will throw away hypotheses that
are not useful (for the intended scope of the [fsetdec]
tactic). *)
Hint Constructors MSet_elt_Prop MSet_Prop : MSet_Prop.
Ltac discard_nonMSet :=
repeat (
match goal with
| H : context [ @Logic.eq ?T ?x ?y ] |- _ =>
if (change T with E.t in H) then fail
else if (change T with t in H) then fail
else clear H
| H : ?P |- _ =>
if prop (MSet_Prop P) holds by
(auto 100 with MSet_Prop)
then fail
else clear H
end).
(** ** Turning Set Operators into Propositional Connectives
The lemmas from [MSetFacts] will be used to break down
set operations into propositional formulas built over
the predicates [In] and [E.eq] applied only to
variables. We are going to use them with [autorewrite].
*)
Hint Rewrite
F.empty_iff F.singleton_iff F.add_iff F.remove_iff
F.union_iff F.inter_iff F.diff_iff
: set_simpl.
Lemma eq_refl_iff (x : E.t) : E.eq x x <-> True.
Proof.
now split.
Qed.
Hint Rewrite eq_refl_iff : set_eq_simpl.
(** ** Decidability of MSet Propositions *)
(** [In] is decidable. *)
Lemma dec_In : forall x s,
decidable (In x s).
Proof.
red; intros; generalize (F.mem_iff s x); case (mem x s); intuition.
Qed.
(** [E.eq] is decidable. *)
Lemma dec_eq : forall (x y : E.t),
decidable (E.eq x y).
Proof.
red; intros x y; destruct (E.eq_dec x y); auto.
Qed.
(** The hint database [MSet_decidability] will be given to
the [push_neg] tactic from the module [Negation]. *)
Hint Resolve dec_In dec_eq : MSet_decidability.
(** ** Normalizing Propositions About Equality
We have to deal with the fact that [E.eq] may be
convertible with Coq's equality. Thus, we will find the
following tactics useful to replace one form with the
other everywhere. *)
(** The next tactic, [Logic_eq_to_E_eq], mentions the term
[E.t]; thus, we must ensure that [E.t] is used in favor
of any other convertible but syntactically distinct
term. *)
Ltac change_to_E_t :=
repeat (
match goal with
| H : ?T |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
| H : forall x : ?T, _ |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
end).
(** These two tactics take us from Coq's built-in equality
to [E.eq] (and vice versa) when possible. *)
Ltac Logic_eq_to_E_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change (@Logic.eq E.t) with E.eq in H)
| |- _ =>
progress (change (@Logic.eq E.t) with E.eq)
end).
Ltac E_eq_to_Logic_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change E.eq with (@Logic.eq E.t) in H)
| |- _ =>
progress (change E.eq with (@Logic.eq E.t))
end).
(** This tactic works like the built-in tactic [subst], but
at the level of set element equality (which may not be
the convertible with Coq's equality). *)
Ltac substMSet :=
repeat (
match goal with
| H: E.eq ?x ?x |- _ => clear H
| H: E.eq ?x ?y |- _ => rewrite H in *; clear H
end);
autorewrite with set_eq_simpl in *.
(** ** Considering Decidability of Base Propositions
This tactic adds assertions about the decidability of
[E.eq] and [In] to the context. This is necessary for
the completeness of the [fsetdec] tactic. However, in
order to minimize the cost of proof search, we should be
careful to not add more than we need. Once negations
have been pushed to the leaves of the propositions, we
only need to worry about decidability for those base
propositions that appear in a negated form. *)
Ltac assert_decidability :=
(** We actually don't want these rules to fire if the
syntactic context in the patterns below is trivially
empty, but we'll just do some clean-up at the
afterward. *)
repeat (
match goal with
| H: context [~ E.eq ?x ?y] |- _ =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| H: context [~ In ?x ?s] |- _ =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
| |- context [~ E.eq ?x ?y] =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| |- context [~ In ?x ?s] =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
end);
(** Now we eliminate the useless facts we added (because
they would likely be very harmful to performance). *)
repeat (
match goal with
| _: ~ ?P, H : ?P \/ ~ ?P |- _ => clear H
end).
(** ** Handling [Empty], [Subset], and [Equal]
This tactic instantiates universally quantified
hypotheses (which arise from the unfolding of [Empty],
[Subset], and [Equal]) for each of the set element
expressions that is involved in some membership or
equality fact. Then it throws away those hypotheses,
which should no longer be needed. *)
Ltac inst_MSet_hypotheses :=
repeat (
match goal with
| H : forall a : E.t, _,
_ : context [ In ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ In ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq _ ?x ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq _ ?x ] =>
let P := type of (H x) in
assert new P by (exact (H x))
end);
repeat (
match goal with
| H : forall a : E.t, _ |- _ =>
clear H
end).
(** ** The Core [fsetdec] Auxiliary Tactics *)
(** Here is the crux of the proof search. Recursion through
[intuition]! (This will terminate if I correctly
understand the behavior of [intuition].) *)
Ltac fsetdec_rec := progress substMSet; intuition fsetdec_rec.
(** If we add [unfold Empty, Subset, Equal in *; intros;] to
the beginning of this tactic, it will satisfy the same
specification as the [fsetdec] tactic; however, it will
be much slower than necessary without the pre-processing
done by the wrapper tactic [fsetdec]. *)
Ltac fsetdec_body :=
autorewrite with set_eq_simpl in *;
inst_MSet_hypotheses;
autorewrite with set_simpl set_eq_simpl in *;
push not in * using MSet_decidability;
substMSet;
assert_decidability;
auto;
(intuition fsetdec_rec) ||
fail 1
"because the goal is beyond the scope of this tactic".
End MSetDecideAuxiliary.
Import MSetDecideAuxiliary.
(** * The [fsetdec] Tactic
Here is the top-level tactic (the only one intended for
clients of this library). It's specification is given at
the top of the file. *)
Ltac fsetdec :=
(** We first unfold any occurrences of [iff]. *)
unfold iff in *;
(** We fold occurrences of [not] because it is better for
[intros] to leave us with a goal of [~ P] than a goal of
[False]. *)
fold any not; intros;
(** We don't care about the value of elements : complex ones are
abstracted as new variables (avoiding potential dependencies,
see bug #2464) *)
abstract_elements;
(** We remove dependencies to logical hypothesis. This way,
later "clear" will work nicely (see bug #2136) *)
no_logical_interdep;
(** Now we decompose conjunctions, which will allow the
[discard_nonMSet] and [assert_decidability] tactics to
do a much better job. *)
decompose records;
discard_nonMSet;
(** We unfold these defined propositions on finite sets. If
our goal was one of them, then have one more item to
introduce now. *)
unfold Empty, Subset, Equal in *; intros;
(** We now want to get rid of all uses of [=] in favor of
[E.eq]. However, the best way to eliminate a [=] is in
the context is with [subst], so we will try that first.
In fact, we may as well convert uses of [E.eq] into [=]
when possible before we do [subst] so that we can even
more mileage out of it. Then we will convert all
remaining uses of [=] back to [E.eq] when possible. We
use [change_to_E_t] to ensure that we have a canonical
name for set elements, so that [Logic_eq_to_E_eq] will
work properly. *)
change_to_E_t; E_eq_to_Logic_eq; subst++; Logic_eq_to_E_eq;
(** The next optimization is to swap a negated goal with a
negated hypothesis when possible. Any swap will improve
performance by eliminating the total number of
negations, but we will get the maximum benefit if we
swap the goal with a hypotheses mentioning the same set
element, so we try that first. If we reach the fourth
branch below, we attempt any swap. However, to maintain
completeness of this tactic, we can only perform such a
swap with a decidable proposition; hence, we first test
whether the hypothesis is an [MSet_elt_Prop], noting
that any [MSet_elt_Prop] is decidable. *)
pull not using MSet_decidability;
unfold not in *;
match goal with
| H: (In ?x ?r) -> False |- (In ?x ?s) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
contradict H; fsetdec_body
| H: ?P -> False |- ?Q -> False =>
if prop (MSet_elt_Prop P) holds by
(auto 100 with MSet_Prop)
then (contradict H; fsetdec_body)
else fsetdec_body
| |- _ =>
fsetdec_body
end.
(** * Examples *)
Module MSetDecideTestCases.
Lemma test_eq_trans_1 : forall x y z s,
E.eq x y ->
~ ~ E.eq z y ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_trans_2 : forall x y z r s,
In x (singleton y) ->
~ In z r ->
~ ~ In z (add y r) ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_1 : forall w x y z s,
E.eq x w ->
~ ~ E.eq x y ->
~ E.eq y z ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_2 : forall w x y z r1 r2 s,
In x (singleton w) ->
~ In x r1 ->
In x (add y r1) ->
In y r2 ->
In y (remove z r2) ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_In_singleton : forall x,
In x (singleton x).
Proof. fsetdec. Qed.
Lemma test_add_In : forall x y s,
In x (add y s) ->
~ E.eq x y ->
In x s.
Proof. fsetdec. Qed.
Lemma test_Subset_add_remove : forall x s,
s [<=] (add x (remove x s)).
Proof. fsetdec. Qed.
Lemma test_eq_disjunction : forall w x y z,
In w (add x (add y (singleton z))) ->
E.eq w x \/ E.eq w y \/ E.eq w z.
Proof. fsetdec. Qed.
Lemma test_not_In_disj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ (In x s1 \/ In x s4 \/ E.eq y x).
Proof. fsetdec. Qed.
Lemma test_not_In_conj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ In x s1 /\ ~ In x s4 /\ ~ E.eq y x.
Proof. fsetdec. Qed.
Lemma test_iff_conj : forall a x s s',
(In a s' <-> E.eq x a \/ In a s) ->
(In a s' <-> In a (add x s)).
Proof. fsetdec. Qed.
Lemma test_set_ops_1 : forall x q r s,
(singleton x) [<=] s ->
Empty (union q r) ->
Empty (inter (diff s q) (diff s r)) ->
~ In x s.
Proof. fsetdec. Qed.
Lemma eq_chain_test : forall x1 x2 x3 x4 s1 s2 s3 s4,
Empty s1 ->
In x2 (add x1 s1) ->
In x3 s2 ->
~ In x3 (remove x2 s2) ->
~ In x4 s3 ->
In x4 (add x3 s3) ->
In x1 s4 ->
Subset (add x4 s4) s4.
Proof. fsetdec. Qed.
Lemma test_too_complex : forall x y z r s,
E.eq x y ->
(In x (singleton y) -> r [<=] s) ->
In z r ->
In z s.
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until s; intros Heq H Hr; lapply H; fsetdec.
Qed.
Lemma function_test_1 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2).
Proof. fsetdec. Qed.
Lemma function_test_2 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2).
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until 3. intros g_eq. rewrite <- g_eq. fsetdec.
Qed.
Lemma test_baydemir :
forall (f : t -> t),
forall (s : t),
forall (x y : elt),
In x (add y (f s)) ->
~ E.eq x y ->
In x (f s).
Proof.
fsetdec.
Qed.
End MSetDecideTestCases.
End WDecideOn.
Require Import MSetInterface.
(** Now comes variants for self-contained weak sets and for full sets.
For these variants, only one argument is necessary. Thanks to
the subtyping [WS<=S], the [Decide] functor which is meant to be
used on modules [(M:S)] can simply be an alias of [WDecide]. *)
Module WDecide (M:WSets) := !WDecideOn M.E M.
Module Decide := WDecide.
|
(***********************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA-Rocquencourt & LRI-CNRS-Orsay *)
(* \VV/ *************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(***********************************************************************)
(**************************************************************)
(* MSetDecide.v *)
(* *)
(* Author: Aaron Bohannon *)
(**************************************************************)
(** This file implements a decision procedure for a certain
class of propositions involving finite sets. *)
Require Import Decidable DecidableTypeEx MSetFacts.
(** First, a version for Weak Sets in functorial presentation *)
Module WDecideOn (E : DecidableType)(Import M : WSetsOn E).
Module F := MSetFacts.WFactsOn E M.
(** * Overview
This functor defines the tactic [fsetdec], which will
solve any valid goal of the form
<<
forall s1 ... sn,
forall x1 ... xm,
P1 -> ... -> Pk -> P
>>
where [P]'s are defined by the grammar:
<<
P ::=
| Q
| Empty F
| Subset F F'
| Equal F F'
Q ::=
| E.eq X X'
| In X F
| Q /\ Q'
| Q \/ Q'
| Q -> Q'
| Q <-> Q'
| ~ Q
| True
| False
F ::=
| S
| empty
| singleton X
| add X F
| remove X F
| union F F'
| inter F F'
| diff F F'
X ::= x1 | ... | xm
S ::= s1 | ... | sn
>>
The tactic will also work on some goals that vary slightly from
the above form:
- The variables and hypotheses may be mixed in any order and may
have already been introduced into the context. Moreover,
there may be additional, unrelated hypotheses mixed in (these
will be ignored).
- A conjunction of hypotheses will be handled as easily as
separate hypotheses, i.e., [P1 /\ P2 -> P] can be solved iff
[P1 -> P2 -> P] can be solved.
- [fsetdec] should solve any goal if the MSet-related hypotheses
are contradictory.
- [fsetdec] will first perform any necessary zeta and beta
reductions and will invoke [subst] to eliminate any Coq
equalities between finite sets or their elements.
- If [E.eq] is convertible with Coq's equality, it will not
matter which one is used in the hypotheses or conclusion.
- The tactic can solve goals where the finite sets or set
elements are expressed by Coq terms that are more complicated
than variables. However, non-local definitions are not
expanded, and Coq equalities between non-variable terms are
not used. For example, this goal will be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2)
>>
This one will not be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2)
>>
*)
(** * Facts and Tactics for Propositional Logic
These lemmas and tactics are in a module so that they do
not affect the namespace if you import the enclosing
module [Decide]. *)
Module MSetLogicalFacts.
Require Export Decidable.
Require Export Setoid.
(** ** Lemmas and Tactics About Decidable Propositions *)
(** ** Propositional Equivalences Involving Negation
These are all written with the unfolded form of
negation, since I am not sure if setoid rewriting will
always perform conversion. *)
(** ** Tactics for Negations *)
Tactic Notation "fold" "any" "not" :=
repeat (
match goal with
| H: context [?P -> False] |- _ =>
fold (~ P) in H
| |- context [?P -> False] =>
fold (~ P)
end).
(** [push not using db] will pushes all negations to the
leaves of propositions in the goal, using the lemmas in
[db] to assist in checking the decidability of the
propositions involved. If [using db] is omitted, then
[core] will be used. Additional versions are provided
to manipulate the hypotheses or the hypotheses and goal
together.
XXX: This tactic and the similar subsequent ones should
have been defined using [autorewrite]. However, dealing
with multiples rewrite sites and side-conditions is
done more cleverly with the following explicit
analysis of goals. *)
Ltac or_not_l_iff P Q tac :=
(rewrite (or_not_l_iff_1 P Q) by tac) ||
(rewrite (or_not_l_iff_2 P Q) by tac).
Ltac or_not_r_iff P Q tac :=
(rewrite (or_not_r_iff_1 P Q) by tac) ||
(rewrite (or_not_r_iff_2 P Q) by tac).
Ltac or_not_l_iff_in P Q H tac :=
(rewrite (or_not_l_iff_1 P Q) in H by tac) ||
(rewrite (or_not_l_iff_2 P Q) in H by tac).
Ltac or_not_r_iff_in P Q H tac :=
(rewrite (or_not_r_iff_1 P Q) in H by tac) ||
(rewrite (or_not_r_iff_2 P Q) in H by tac).
Tactic Notation "push" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [?P \/ ?Q -> False] => rewrite (not_or_iff P Q)
| |- context [?P /\ ?Q -> False] => rewrite (not_and_iff P Q)
| |- context [(?P -> ?Q) -> False] => rewrite (not_imp_iff P Q) by dec
end);
fold any not.
Tactic Notation "push" "not" :=
push not using core.
Tactic Notation
"push" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [?P \/ ?Q -> False] |- _ => rewrite (not_or_iff P Q) in H
| H: context [?P /\ ?Q -> False] |- _ => rewrite (not_and_iff P Q) in H
| H: context [(?P -> ?Q) -> False] |- _ =>
rewrite (not_imp_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "push" "not" "in" "*" "|-" :=
push not in * |- using core.
Tactic Notation "push" "not" "in" "*" "using" ident(db) :=
push not using db; push not in * |- using db.
Tactic Notation "push" "not" "in" "*" :=
push not in * using core.
(** A simple test case to see how this works. *)
Lemma test_push : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ ((R -> P) \/ (Q -> R))) ->
(~ (P /\ R)) ->
(~ (P -> R)) ->
True.
Proof.
intros. push not in *.
(* note that ~(R->P) remains (since R isnt decidable) *)
tauto.
Qed.
(** [pull not using db] will pull as many negations as
possible toward the top of the propositions in the goal,
using the lemmas in [db] to assist in checking the
decidability of the propositions involved. If [using
db] is omitted, then [core] will be used. Additional
versions are provided to manipulate the hypotheses or
the hypotheses and goal together. *)
Tactic Notation "pull" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [(?P -> False) /\ (?Q -> False)] =>
rewrite <- (not_or_iff P Q)
| |- context [?P -> ?Q -> False] => rewrite <- (not_and_iff P Q)
| |- context [?P /\ (?Q -> False)] => rewrite <- (not_imp_iff P Q) by dec
| |- context [(?Q -> False) /\ ?P] =>
rewrite <- (not_imp_rev_iff P Q) by dec
end);
fold any not.
Tactic Notation "pull" "not" :=
pull not using core.
Tactic Notation
"pull" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
rewrite <- (not_or_iff P Q) in H
| H: context [?P -> ?Q -> False] |- _ =>
rewrite <- (not_and_iff P Q) in H
| H: context [?P /\ (?Q -> False)] |- _ =>
rewrite <- (not_imp_iff P Q) in H by dec
| H: context [(?Q -> False) /\ ?P] |- _ =>
rewrite <- (not_imp_rev_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "pull" "not" "in" "*" "|-" :=
pull not in * |- using core.
Tactic Notation "pull" "not" "in" "*" "using" ident(db) :=
pull not using db; pull not in * |- using db.
Tactic Notation "pull" "not" "in" "*" :=
pull not in * using core.
(** A simple test case to see how this works. *)
Lemma test_pull : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ (R -> P) /\ ~ (Q -> R)) ->
(~ P \/ ~ R) ->
(P /\ ~ R) ->
(~ R /\ P) ->
True.
Proof.
intros. pull not in *. tauto.
Qed.
End MSetLogicalFacts.
Import MSetLogicalFacts.
(** * Auxiliary Tactics
Again, these lemmas and tactics are in a module so that
they do not affect the namespace if you import the
enclosing module [Decide]. *)
Module MSetDecideAuxiliary.
(** ** Generic Tactics
We begin by defining a few generic, useful tactics. *)
(** remove logical hypothesis inter-dependencies (fix #2136). *)
Ltac no_logical_interdep :=
match goal with
| H : ?P |- _ =>
match type of P with
| Prop =>
match goal with H' : context [ H ] |- _ => clear dependent H' end
| _ => fail
end; no_logical_interdep
| _ => idtac
end.
(** [if t then t1 else t2] executes [t] and, if it does not
fail, then [t1] will be applied to all subgoals
produced. If [t] fails, then [t2] is executed. *)
Tactic Notation
"if" tactic(t)
"then" tactic(t1)
"else" tactic(t2) :=
first [ t; first [ t1 | fail 2 ] | t2 ].
Ltac abstract_term t :=
if (is_var t) then fail "no need to abstract a variable"
else (let x := fresh "x" in set (x := t) in *; try clearbody x).
Ltac abstract_elements :=
repeat
(match goal with
| |- context [ singleton ?t ] => abstract_term t
| _ : context [ singleton ?t ] |- _ => abstract_term t
| |- context [ add ?t _ ] => abstract_term t
| _ : context [ add ?t _ ] |- _ => abstract_term t
| |- context [ remove ?t _ ] => abstract_term t
| _ : context [ remove ?t _ ] |- _ => abstract_term t
| |- context [ In ?t _ ] => abstract_term t
| _ : context [ In ?t _ ] |- _ => abstract_term t
end).
(** [prop P holds by t] succeeds (but does not modify the
goal or context) if the proposition [P] can be proved by
[t] in the current context. Otherwise, the tactic
fails. *)
Tactic Notation "prop" constr(P) "holds" "by" tactic(t) :=
let H := fresh in
assert P as H by t;
clear H.
(** This tactic acts just like [assert ... by ...] but will
fail if the context already contains the proposition. *)
Tactic Notation "assert" "new" constr(e) "by" tactic(t) :=
match goal with
| H: e |- _ => fail 1
| _ => assert e by t
end.
(** [subst++] is similar to [subst] except that
- it never fails (as [subst] does on recursive
equations),
- it substitutes locally defined variable for their
definitions,
- it performs beta reductions everywhere, which may
arise after substituting a locally defined function
for its definition.
*)
Tactic Notation "subst" "++" :=
repeat (
match goal with
| x : _ |- _ => subst x
end);
cbv zeta beta in *.
(** [decompose records] calls [decompose record H] on every
relevant hypothesis [H]. *)
Tactic Notation "decompose" "records" :=
repeat (
match goal with
| H: _ |- _ => progress (decompose record H); clear H
end).
(** ** Discarding Irrelevant Hypotheses
We will want to clear the context of any
non-MSet-related hypotheses in order to increase the
speed of the tactic. To do this, we will need to be
able to decide which are relevant. We do this by making
a simple inductive definition classifying the
propositions of interest. *)
Inductive MSet_elt_Prop : Prop -> Prop :=
| eq_Prop : forall (S : Type) (x y : S),
MSet_elt_Prop (x = y)
| eq_elt_prop : forall x y,
MSet_elt_Prop (E.eq x y)
| In_elt_prop : forall x s,
MSet_elt_Prop (In x s)
| True_elt_prop :
MSet_elt_Prop True
| False_elt_prop :
MSet_elt_Prop False
| conj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P /\ Q)
| disj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P \/ Q)
| impl_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P -> Q)
| not_elt_prop : forall P,
MSet_elt_Prop P ->
MSet_elt_Prop (~ P).
Inductive MSet_Prop : Prop -> Prop :=
| elt_MSet_Prop : forall P,
MSet_elt_Prop P ->
MSet_Prop P
| Empty_MSet_Prop : forall s,
MSet_Prop (Empty s)
| Subset_MSet_Prop : forall s1 s2,
MSet_Prop (Subset s1 s2)
| Equal_MSet_Prop : forall s1 s2,
MSet_Prop (Equal s1 s2).
(** Here is the tactic that will throw away hypotheses that
are not useful (for the intended scope of the [fsetdec]
tactic). *)
Hint Constructors MSet_elt_Prop MSet_Prop : MSet_Prop.
Ltac discard_nonMSet :=
repeat (
match goal with
| H : context [ @Logic.eq ?T ?x ?y ] |- _ =>
if (change T with E.t in H) then fail
else if (change T with t in H) then fail
else clear H
| H : ?P |- _ =>
if prop (MSet_Prop P) holds by
(auto 100 with MSet_Prop)
then fail
else clear H
end).
(** ** Turning Set Operators into Propositional Connectives
The lemmas from [MSetFacts] will be used to break down
set operations into propositional formulas built over
the predicates [In] and [E.eq] applied only to
variables. We are going to use them with [autorewrite].
*)
Hint Rewrite
F.empty_iff F.singleton_iff F.add_iff F.remove_iff
F.union_iff F.inter_iff F.diff_iff
: set_simpl.
Lemma eq_refl_iff (x : E.t) : E.eq x x <-> True.
Proof.
now split.
Qed.
Hint Rewrite eq_refl_iff : set_eq_simpl.
(** ** Decidability of MSet Propositions *)
(** [In] is decidable. *)
Lemma dec_In : forall x s,
decidable (In x s).
Proof.
red; intros; generalize (F.mem_iff s x); case (mem x s); intuition.
Qed.
(** [E.eq] is decidable. *)
Lemma dec_eq : forall (x y : E.t),
decidable (E.eq x y).
Proof.
red; intros x y; destruct (E.eq_dec x y); auto.
Qed.
(** The hint database [MSet_decidability] will be given to
the [push_neg] tactic from the module [Negation]. *)
Hint Resolve dec_In dec_eq : MSet_decidability.
(** ** Normalizing Propositions About Equality
We have to deal with the fact that [E.eq] may be
convertible with Coq's equality. Thus, we will find the
following tactics useful to replace one form with the
other everywhere. *)
(** The next tactic, [Logic_eq_to_E_eq], mentions the term
[E.t]; thus, we must ensure that [E.t] is used in favor
of any other convertible but syntactically distinct
term. *)
Ltac change_to_E_t :=
repeat (
match goal with
| H : ?T |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
| H : forall x : ?T, _ |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
end).
(** These two tactics take us from Coq's built-in equality
to [E.eq] (and vice versa) when possible. *)
Ltac Logic_eq_to_E_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change (@Logic.eq E.t) with E.eq in H)
| |- _ =>
progress (change (@Logic.eq E.t) with E.eq)
end).
Ltac E_eq_to_Logic_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change E.eq with (@Logic.eq E.t) in H)
| |- _ =>
progress (change E.eq with (@Logic.eq E.t))
end).
(** This tactic works like the built-in tactic [subst], but
at the level of set element equality (which may not be
the convertible with Coq's equality). *)
Ltac substMSet :=
repeat (
match goal with
| H: E.eq ?x ?x |- _ => clear H
| H: E.eq ?x ?y |- _ => rewrite H in *; clear H
end);
autorewrite with set_eq_simpl in *.
(** ** Considering Decidability of Base Propositions
This tactic adds assertions about the decidability of
[E.eq] and [In] to the context. This is necessary for
the completeness of the [fsetdec] tactic. However, in
order to minimize the cost of proof search, we should be
careful to not add more than we need. Once negations
have been pushed to the leaves of the propositions, we
only need to worry about decidability for those base
propositions that appear in a negated form. *)
Ltac assert_decidability :=
(** We actually don't want these rules to fire if the
syntactic context in the patterns below is trivially
empty, but we'll just do some clean-up at the
afterward. *)
repeat (
match goal with
| H: context [~ E.eq ?x ?y] |- _ =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| H: context [~ In ?x ?s] |- _ =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
| |- context [~ E.eq ?x ?y] =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| |- context [~ In ?x ?s] =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
end);
(** Now we eliminate the useless facts we added (because
they would likely be very harmful to performance). *)
repeat (
match goal with
| _: ~ ?P, H : ?P \/ ~ ?P |- _ => clear H
end).
(** ** Handling [Empty], [Subset], and [Equal]
This tactic instantiates universally quantified
hypotheses (which arise from the unfolding of [Empty],
[Subset], and [Equal]) for each of the set element
expressions that is involved in some membership or
equality fact. Then it throws away those hypotheses,
which should no longer be needed. *)
Ltac inst_MSet_hypotheses :=
repeat (
match goal with
| H : forall a : E.t, _,
_ : context [ In ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ In ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq _ ?x ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq _ ?x ] =>
let P := type of (H x) in
assert new P by (exact (H x))
end);
repeat (
match goal with
| H : forall a : E.t, _ |- _ =>
clear H
end).
(** ** The Core [fsetdec] Auxiliary Tactics *)
(** Here is the crux of the proof search. Recursion through
[intuition]! (This will terminate if I correctly
understand the behavior of [intuition].) *)
Ltac fsetdec_rec := progress substMSet; intuition fsetdec_rec.
(** If we add [unfold Empty, Subset, Equal in *; intros;] to
the beginning of this tactic, it will satisfy the same
specification as the [fsetdec] tactic; however, it will
be much slower than necessary without the pre-processing
done by the wrapper tactic [fsetdec]. *)
Ltac fsetdec_body :=
autorewrite with set_eq_simpl in *;
inst_MSet_hypotheses;
autorewrite with set_simpl set_eq_simpl in *;
push not in * using MSet_decidability;
substMSet;
assert_decidability;
auto;
(intuition fsetdec_rec) ||
fail 1
"because the goal is beyond the scope of this tactic".
End MSetDecideAuxiliary.
Import MSetDecideAuxiliary.
(** * The [fsetdec] Tactic
Here is the top-level tactic (the only one intended for
clients of this library). It's specification is given at
the top of the file. *)
Ltac fsetdec :=
(** We first unfold any occurrences of [iff]. *)
unfold iff in *;
(** We fold occurrences of [not] because it is better for
[intros] to leave us with a goal of [~ P] than a goal of
[False]. *)
fold any not; intros;
(** We don't care about the value of elements : complex ones are
abstracted as new variables (avoiding potential dependencies,
see bug #2464) *)
abstract_elements;
(** We remove dependencies to logical hypothesis. This way,
later "clear" will work nicely (see bug #2136) *)
no_logical_interdep;
(** Now we decompose conjunctions, which will allow the
[discard_nonMSet] and [assert_decidability] tactics to
do a much better job. *)
decompose records;
discard_nonMSet;
(** We unfold these defined propositions on finite sets. If
our goal was one of them, then have one more item to
introduce now. *)
unfold Empty, Subset, Equal in *; intros;
(** We now want to get rid of all uses of [=] in favor of
[E.eq]. However, the best way to eliminate a [=] is in
the context is with [subst], so we will try that first.
In fact, we may as well convert uses of [E.eq] into [=]
when possible before we do [subst] so that we can even
more mileage out of it. Then we will convert all
remaining uses of [=] back to [E.eq] when possible. We
use [change_to_E_t] to ensure that we have a canonical
name for set elements, so that [Logic_eq_to_E_eq] will
work properly. *)
change_to_E_t; E_eq_to_Logic_eq; subst++; Logic_eq_to_E_eq;
(** The next optimization is to swap a negated goal with a
negated hypothesis when possible. Any swap will improve
performance by eliminating the total number of
negations, but we will get the maximum benefit if we
swap the goal with a hypotheses mentioning the same set
element, so we try that first. If we reach the fourth
branch below, we attempt any swap. However, to maintain
completeness of this tactic, we can only perform such a
swap with a decidable proposition; hence, we first test
whether the hypothesis is an [MSet_elt_Prop], noting
that any [MSet_elt_Prop] is decidable. *)
pull not using MSet_decidability;
unfold not in *;
match goal with
| H: (In ?x ?r) -> False |- (In ?x ?s) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
contradict H; fsetdec_body
| H: ?P -> False |- ?Q -> False =>
if prop (MSet_elt_Prop P) holds by
(auto 100 with MSet_Prop)
then (contradict H; fsetdec_body)
else fsetdec_body
| |- _ =>
fsetdec_body
end.
(** * Examples *)
Module MSetDecideTestCases.
Lemma test_eq_trans_1 : forall x y z s,
E.eq x y ->
~ ~ E.eq z y ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_trans_2 : forall x y z r s,
In x (singleton y) ->
~ In z r ->
~ ~ In z (add y r) ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_1 : forall w x y z s,
E.eq x w ->
~ ~ E.eq x y ->
~ E.eq y z ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_2 : forall w x y z r1 r2 s,
In x (singleton w) ->
~ In x r1 ->
In x (add y r1) ->
In y r2 ->
In y (remove z r2) ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_In_singleton : forall x,
In x (singleton x).
Proof. fsetdec. Qed.
Lemma test_add_In : forall x y s,
In x (add y s) ->
~ E.eq x y ->
In x s.
Proof. fsetdec. Qed.
Lemma test_Subset_add_remove : forall x s,
s [<=] (add x (remove x s)).
Proof. fsetdec. Qed.
Lemma test_eq_disjunction : forall w x y z,
In w (add x (add y (singleton z))) ->
E.eq w x \/ E.eq w y \/ E.eq w z.
Proof. fsetdec. Qed.
Lemma test_not_In_disj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ (In x s1 \/ In x s4 \/ E.eq y x).
Proof. fsetdec. Qed.
Lemma test_not_In_conj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ In x s1 /\ ~ In x s4 /\ ~ E.eq y x.
Proof. fsetdec. Qed.
Lemma test_iff_conj : forall a x s s',
(In a s' <-> E.eq x a \/ In a s) ->
(In a s' <-> In a (add x s)).
Proof. fsetdec. Qed.
Lemma test_set_ops_1 : forall x q r s,
(singleton x) [<=] s ->
Empty (union q r) ->
Empty (inter (diff s q) (diff s r)) ->
~ In x s.
Proof. fsetdec. Qed.
Lemma eq_chain_test : forall x1 x2 x3 x4 s1 s2 s3 s4,
Empty s1 ->
In x2 (add x1 s1) ->
In x3 s2 ->
~ In x3 (remove x2 s2) ->
~ In x4 s3 ->
In x4 (add x3 s3) ->
In x1 s4 ->
Subset (add x4 s4) s4.
Proof. fsetdec. Qed.
Lemma test_too_complex : forall x y z r s,
E.eq x y ->
(In x (singleton y) -> r [<=] s) ->
In z r ->
In z s.
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until s; intros Heq H Hr; lapply H; fsetdec.
Qed.
Lemma function_test_1 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2).
Proof. fsetdec. Qed.
Lemma function_test_2 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2).
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until 3. intros g_eq. rewrite <- g_eq. fsetdec.
Qed.
Lemma test_baydemir :
forall (f : t -> t),
forall (s : t),
forall (x y : elt),
In x (add y (f s)) ->
~ E.eq x y ->
In x (f s).
Proof.
fsetdec.
Qed.
End MSetDecideTestCases.
End WDecideOn.
Require Import MSetInterface.
(** Now comes variants for self-contained weak sets and for full sets.
For these variants, only one argument is necessary. Thanks to
the subtyping [WS<=S], the [Decide] functor which is meant to be
used on modules [(M:S)] can simply be an alias of [WDecide]. *)
Module WDecide (M:WSets) := !WDecideOn M.E M.
Module Decide := WDecide.
|
module timer #
(
parameter WIDTH = 64,
parameter USE_2XCLK = 0,
parameter S_WIDTH_A = 2
)
(
input clk,
input clk2x,
input resetn,
// Slave port
input [S_WIDTH_A-1:0] slave_address, // Word address
input [WIDTH-1:0] slave_writedata,
input slave_read,
input slave_write,
input [WIDTH/8-1:0] slave_byteenable,
output slave_waitrequest,
output [WIDTH-1:0] slave_readdata,
output slave_readdatavalid
);
reg [WIDTH-1:0] counter;
reg [WIDTH-1:0] counter2x;
reg clock_sel;
always@(posedge clk or negedge resetn)
if (!resetn)
clock_sel <= 1'b0;
else if (slave_write)
if (|slave_writedata)
clock_sel <= 1'b1;
else
clock_sel <= 1'b0;
always@(posedge clk or negedge resetn)
if (!resetn)
counter <= {WIDTH{1'b0}};
else if (slave_write)
counter <= {WIDTH{1'b0}};
else
counter <= counter + 2'b01;
always@(posedge clk2x or negedge resetn)
if (!resetn)
counter2x <= {WIDTH{1'b0}};
else if (slave_write)
counter2x <= {WIDTH{1'b0}};
else
counter2x <= counter2x + 2'b01;
assign slave_waitrequest = 1'b0;
assign slave_readdata = (USE_2XCLK && clock_sel) ? counter2x : counter;
assign slave_readdatavalid = slave_read;
endmodule
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
`timescale 1ps/1ps
module altera_pll_reconfig_core
#(
parameter reconf_width = 64,
parameter device_family = "Stratix V",
// MIF Streaming parameters
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter ROM_ADDR_WIDTH = 9,
parameter ROM_DATA_WIDTH = 32,
parameter ROM_NUM_WORDS = 512
) (
//input
input wire mgmt_clk,
input wire mgmt_reset,
//conduits
output wire [reconf_width-1:0] reconfig_to_pll,
input wire [reconf_width-1:0] reconfig_from_pll,
// user data (avalon-MM slave interface)
output wire [31:0] mgmt_readdata,
output wire mgmt_waitrequest,
input wire [5:0] mgmt_address,
input wire mgmt_read,
input wire mgmt_write,
input wire [31:0] mgmt_writedata,
//other
output wire mif_start_out,
output reg [ROM_ADDR_WIDTH-1:0] mif_base_addr
);
localparam mode_WR = 1'b0;
localparam mode_POLL = 1'b1;
localparam MODE_REG = 6'b000000;
localparam STATUS_REG = 6'b000001;
localparam START_REG = 6'b000010;
localparam N_REG = 6'b000011;
localparam M_REG = 6'b000100;
localparam C_COUNTERS_REG = 6'b000101;
localparam DPS_REG = 6'b000110;
localparam DSM_REG = 6'b000111;
localparam BWCTRL_REG = 6'b001000;
localparam CP_CURRENT_REG = 6'b001001;
localparam ANY_DPRIO = 6'b100000;
localparam CNT_BASE = 5'b001010;
localparam MIF_REG = 6'b011111;
//C Counters
localparam number_of_counters = 5'd18;
localparam CNT_0 = 1'd0, CNT_1 = 5'd1, CNT_2 = 5'd2,
CNT_3 = 5'd3, CNT_4 = 5'd4, CNT_5 = 5'd5,
CNT_6 = 5'd6, CNT_7 = 5'd7, CNT_8 = 5'd8,
CNT_9 = 5'd9, CNT_10 = 5'd10, CNT_11 = 5'd11,
CNT_12 = 5'd12, CNT_13 = 5'd13, CNT_14 = 5'd14,
CNT_15 = 5'd15, CNT_16 = 5'd16, CNT_17 = 5'd17;
//C counter addresses
localparam C_CNT_0_DIV_ADDR = 5'h00;
localparam C_CNT_0_DIV_ADDR_DPRIO_1 = 5'h11;
localparam C_CNT_0_3_BYPASS_EN_ADDR = 5'h15;
localparam C_CNT_0_3_ODD_DIV_EN_ADDR = 5'h17;
localparam C_CNT_4_17_BYPASS_EN_ADDR = 5'h14;
localparam C_CNT_4_17_ODD_DIV_EN_ADDR = 5'h16;
//N counter addresses
localparam N_CNT_DIV_ADDR = 5'h13;
localparam N_CNT_BYPASS_EN_ADDR = 5'h15;
localparam N_CNT_ODD_DIV_EN_ADDR = 5'h17;
//M counter addresses
localparam M_CNT_DIV_ADDR = 5'h12;
localparam M_CNT_BYPASS_EN_ADDR = 5'h15;
localparam M_CNT_ODD_DIV_EN_ADDR = 5'h17;
//DSM address
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_0 = 5'h18;
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_1 = 5'h19;
localparam DSM_K_READY_ADDR = 5'h17;
localparam DSM_K_DITHER_ADDR = 5'h17;
localparam DSM_OUT_SEL_ADDR = 6'h30;
//Other DSM params
localparam DSM_K_READY_BIT_INDEX = 4'd11;
//BWCTRL address
//Bit 0-3 of addr
localparam BWCTRL_ADDR = 6'h30;
//CP_CURRENT address
//Bit 0-2 of addr
localparam CP_CURRENT_ADDR = 6'h31;
localparam DPRIO_IDLE = 3'd0, ONE = 3'd1, TWO = 3'd2, THREE = 3'd3, FOUR = 3'd4,
FIVE = 3'd5, SIX = 3'd6, SEVEN = 3'd7, EIGHT = 4'd8, NINE = 4'd9, TEN = 4'd10,
ELEVEN = 4'd11, TWELVE = 4'd12, THIRTEEN = 4'd13, FOURTEEN = 4'd14, DPRIO_DONE = 4'd15;
localparam IDLE = 2'b00, WAIT_ON_LOCK = 2'b01, LOCKED = 2'b10;
wire clk;
wire reset;
wire gnd;
wire [5: 0] slave_address;
wire slave_read;
wire slave_write;
wire [31: 0] slave_writedata;
reg [31: 0] slave_readdata_d;
reg [31: 0] slave_readdata_q;
wire slave_waitrequest;
assign clk = mgmt_clk;
assign slave_address = mgmt_address;
assign slave_read = mgmt_read;
assign slave_write = mgmt_write;
assign slave_writedata = mgmt_writedata;
// Outputs
assign mgmt_readdata = slave_readdata_q;
assign mgmt_waitrequest = slave_waitrequest;
//internal signals
wire locked;
wire pll_start;
wire pll_start_valid;
reg status_read;
wire read_slave_mode_asserted;
wire pll_start_asserted;
reg [1:0] current_state;
reg [1:0] next_state;
reg slave_mode;
reg status;//0=busy, 1=ready
//user_mode_init user_mode_init_inst (clk, reset, dprio_mdio_dis, ser_shift_load);
//declaring the init wires. These will have 0 on them for 64 clk cycles
wire [ 5:0] init_dprio_address;
wire init_dprio_read;
wire [ 1:0] init_dprio_byteen;
wire init_dprio_write;
wire [15:0] init_dprio_writedata;
wire init_atpgmode;
wire init_mdio_dis;
wire init_scanen;
wire init_ser_shift_load;
wire dprio_init_done;
//DPRIO output signals after initialization is done
wire dprio_clk;
reg avmm_dprio_write;
reg avmm_dprio_read;
reg [5:0] avmm_dprio_address;
reg [15:0] avmm_dprio_writedata;
reg [1:0] avmm_dprio_byteen;
wire avmm_atpgmode;
wire avmm_mdio_dis;
wire avmm_scanen;
//Final output wires that are muxed between the init and avmm wires.
wire dprio_init_reset;
wire [5:0] dprio_address /*synthesis keep*/;
wire dprio_read/*synthesis keep*/;
wire [1:0] dprio_byteen/*synthesis keep*/;
wire dprio_write/*synthesis keep*/;
wire [15:0] dprio_writedata/*synthesis keep*/;
wire dprio_mdio_dis/*synthesis keep*/;
wire dprio_ser_shift_load/*synthesis keep*/;
wire dprio_atpgmode/*synthesis keep*/;
wire dprio_scanen/*synthesis keep*/;
//other PLL signals for dyn ph shift
wire phase_done/*synthesis keep*/;
wire phase_en/*synthesis keep*/;
wire up_dn/*synthesis keep*/;
wire [4:0] cnt_sel;
//DPRIO input signals
wire [15:0] dprio_readdata;
//internal logic signals
//storage registers for user sent data
reg dprio_temp_read_1;
reg dprio_temp_read_2;
reg dprio_start;
reg mif_start_assert;
reg dps_start_assert;
wire usr_valid_changes;
reg [3:0] dprio_cur_state;
reg [3:0] dprio_next_state;
reg [15:0] dprio_temp_m_n_c_readdata_1_d;
reg [15:0] dprio_temp_m_n_c_readdata_2_d;
reg [15:0] dprio_temp_m_n_c_readdata_1_q;
reg [15:0] dprio_temp_m_n_c_readdata_2_q;
reg dprio_write_done;
//C counters signals
reg [7:0] usr_c_cnt_lo;
reg [7:0] usr_c_cnt_hi;
reg usr_c_cnt_bypass_en;
reg usr_c_cnt_odd_duty_div_en;
reg [7:0] temp_c_cnt_lo [0:17];
reg [7:0] temp_c_cnt_hi [0:17];
reg temp_c_cnt_bypass_en [0:17];
reg temp_c_cnt_odd_duty_div_en [0:17];
reg any_c_cnt_changed;
reg all_c_cnt_done_q;
reg all_c_cnt_done_d;
reg [17:0] c_cnt_changed;
reg [17:0] c_cnt_done_d;
reg [17:0] c_cnt_done_q;
//N counter signals
reg [7:0] usr_n_cnt_lo;
reg [7:0] usr_n_cnt_hi;
reg usr_n_cnt_bypass_en;
reg usr_n_cnt_odd_duty_div_en;
reg n_cnt_changed;
reg n_cnt_done_d;
reg n_cnt_done_q;
//M counter signals
reg [7:0] usr_m_cnt_lo;
reg [7:0] usr_m_cnt_hi;
reg usr_m_cnt_bypass_en;
reg usr_m_cnt_odd_duty_div_en;
reg m_cnt_changed;
reg m_cnt_done_d;
reg m_cnt_done_q;
//dyn phase regs
reg [15:0] usr_num_shifts;
reg [4:0] usr_cnt_sel /*synthesis preserve*/;
reg usr_up_dn;
reg dps_changed;
wire dps_changed_valid;
wire dps_done;
//DSM Signals
reg [31:0] usr_k_value;
reg dsm_k_changed;
reg dsm_k_done_d;
reg dsm_k_done_q;
reg dsm_k_ready_false_done_d;
//BW signals
reg [3:0] usr_bwctrl_value;
reg bwctrl_changed;
reg bwctrl_done_d;
reg bwctrl_done_q;
//CP signals
reg [2:0] usr_cp_current_value;
reg cp_current_changed;
reg cp_current_done_d;
reg cp_current_done_q;
//Manual DPRIO signals
reg manual_dprio_done_q;
reg manual_dprio_done_d;
reg manual_dprio_changed;
reg [5:0] usr_dprio_address;
reg [15:0] usr_dprio_writedata_0;
reg usr_r_w;
//keeping track of which operation happened last
reg [5:0] operation_address;
// Address wires for all C_counter DPRIO registers
// These are outputs of LUTS, changing depending
// on whether PLL_0 or PLL_1 being used
//Fitter will tell if FPLL1 is being used
wire fpll_1;
// other
reg mif_reg_asserted;
// MAIN FSM
always @(posedge clk)
begin
if (reset)
begin
dprio_cur_state <= DPRIO_IDLE;
current_state <= IDLE;
end
else
begin
current_state <= next_state;
dprio_cur_state <= dprio_next_state;
end
end
always @(*)
begin
case(current_state)
IDLE:
begin
if (pll_start & !slave_waitrequest & usr_valid_changes)
next_state = WAIT_ON_LOCK;
else
next_state = IDLE;
end
WAIT_ON_LOCK:
begin
if (locked & dps_done & dprio_write_done) // received locked high from PLL
begin
if (slave_mode==mode_WR) //if the mode is waitrequest, then
// goto IDLE state directly
next_state = IDLE;
else
next_state = LOCKED; //otherwise go the locked state
end
else
next_state = WAIT_ON_LOCK;
end
LOCKED:
begin
if (status_read) // stay in LOCKED until user reads status
next_state = IDLE;
else
next_state = LOCKED;
end
default: next_state = 2'bxx;
endcase
end
// ask the pll to start reconfig
assign pll_start = (pll_start_asserted & (current_state==IDLE)) ;
assign pll_start_valid = (pll_start & (next_state==WAIT_ON_LOCK)) ;
// WRITE OPERATIONS
assign pll_start_asserted = slave_write & (slave_address == START_REG);
assign mif_start_out = pll_start & mif_reg_asserted;
//reading the mode register to determine what mode the slave will operate
//in.
always @(posedge clk)
begin
if (reset)
slave_mode <= mode_WR;
else if (slave_write & (slave_address == MODE_REG) & !slave_waitrequest)
slave_mode <= slave_writedata[0];
end
//record which values user wants to change.
//reading in the actual values that need to be reconfigged and sending
//them to the PLL
always @(posedge clk)
begin
if (reset)
begin
//reset all regs here
//BW signals reset
usr_bwctrl_value <= 0;
bwctrl_changed <= 0;
bwctrl_done_q <= 0;
//CP signals reset
usr_cp_current_value <= 0;
cp_current_changed <= 0;
cp_current_done_q <= 0;
//DSM signals reset
usr_k_value <= 0;
dsm_k_changed <= 0;
dsm_k_done_q <= 0;
//N counter signals reset
usr_n_cnt_lo <= 0;
usr_n_cnt_hi <= 0;
usr_n_cnt_bypass_en <= 0;
usr_n_cnt_odd_duty_div_en <= 0;
n_cnt_changed <= 0;
n_cnt_done_q <= 0;
//M counter signals reset
usr_m_cnt_lo <= 0;
usr_m_cnt_hi <= 0;
usr_m_cnt_bypass_en <= 0;
usr_m_cnt_odd_duty_div_en <= 0;
m_cnt_changed <= 0;
m_cnt_done_q <= 0;
//C counter signals reset
usr_c_cnt_lo <= 0;
usr_c_cnt_hi <= 0;
usr_c_cnt_bypass_en <= 0;
usr_c_cnt_odd_duty_div_en <= 0;
any_c_cnt_changed <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
//generic signals
dprio_start <= 0;
mif_start_assert <= 0;
dps_start_assert <= 0;
dprio_temp_m_n_c_readdata_1_q <= 0;
dprio_temp_m_n_c_readdata_2_q <= 0;
c_cnt_done_q <= 0;
//DPS signals
usr_up_dn <= 0;
usr_cnt_sel <= 0;
usr_num_shifts <= 0;
dps_changed <= 0;
//manual DPRIO signals
manual_dprio_changed <= 0;
usr_dprio_address <= 0;
usr_dprio_writedata_0 <= 0;
usr_r_w <= 0;
operation_address <= 0;
mif_reg_asserted <= 0;
mif_base_addr <= 0;
end
else
begin
if (dprio_temp_read_1)
begin
dprio_temp_m_n_c_readdata_1_q <= dprio_temp_m_n_c_readdata_1_d;
end
if (dprio_temp_read_2)
begin
dprio_temp_m_n_c_readdata_2_q <= dprio_temp_m_n_c_readdata_2_d;
end
if ((dps_done)) dps_changed <= 0;
if (dsm_k_done_d) dsm_k_done_q <= dsm_k_done_d;
if (n_cnt_done_d) n_cnt_done_q <= n_cnt_done_d;
if (m_cnt_done_d) m_cnt_done_q <= m_cnt_done_d;
if (all_c_cnt_done_d) all_c_cnt_done_q <= all_c_cnt_done_d;
if (c_cnt_done_d != 0) c_cnt_done_q <= c_cnt_done_q | c_cnt_done_d;
if (bwctrl_done_d) bwctrl_done_q <= bwctrl_done_d;
if (cp_current_done_d) cp_current_done_q <= cp_current_done_d;
if (manual_dprio_done_d) manual_dprio_done_q <= manual_dprio_done_d;
if (mif_start_out == 1'b1)
mif_start_assert <= 0; // Signaled MIF block to start, so deassert on next cycle
if (dps_done != 1'b1)
dps_start_assert <= 0; // DPS has started, so dessert its start signal on next cycle
if (dprio_next_state == ONE)
dprio_start <= 0;
if (dprio_write_done)
begin
bwctrl_done_q <= 0;
cp_current_done_q <= 0;
dsm_k_done_q <= 0;
dsm_k_done_q <= 0;
n_cnt_done_q <= 0;
m_cnt_done_q <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
dsm_k_changed <= 0;
n_cnt_changed <= 0;
m_cnt_changed <= 0;
any_c_cnt_changed <= 0;
bwctrl_changed <= 0;
cp_current_changed <= 0;
manual_dprio_changed <= 0;
manual_dprio_done_q <= 0;
if (dps_changed | dps_changed_valid | !dps_done )
begin
usr_cnt_sel <= usr_cnt_sel;
end
else
begin
usr_cnt_sel <= 0;
end
mif_reg_asserted <= 0;
end
else
begin
dsm_k_changed <= dsm_k_changed;
n_cnt_changed <= n_cnt_changed;
m_cnt_changed <= m_cnt_changed;
any_c_cnt_changed <= any_c_cnt_changed;
manual_dprio_changed <= manual_dprio_changed;
mif_reg_asserted <= mif_reg_asserted;
usr_cnt_sel <= usr_cnt_sel;
end
if(slave_write & !slave_waitrequest)
begin
case(slave_address)
//read in the values here from the user and act on them
DSM_REG:
begin
operation_address <= DSM_REG;
usr_k_value <= slave_writedata[31:0];
dsm_k_changed <= 1'b1;
dsm_k_done_q <= 0;
dprio_start <= 1'b1;
end
N_REG:
begin
operation_address <= N_REG;
usr_n_cnt_lo <= slave_writedata[7:0];
usr_n_cnt_hi <= slave_writedata[15:8];
usr_n_cnt_bypass_en <= slave_writedata[16];
usr_n_cnt_odd_duty_div_en <= slave_writedata[17];
n_cnt_changed <= 1'b1;
n_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
M_REG:
begin
operation_address <= M_REG;
usr_m_cnt_lo <= slave_writedata[7:0];
usr_m_cnt_hi <= slave_writedata[15:8];
usr_m_cnt_bypass_en <= slave_writedata[16];
usr_m_cnt_odd_duty_div_en <= slave_writedata[17];
m_cnt_changed <= 1'b1;
m_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
DPS_REG:
begin
operation_address <= DPS_REG;
usr_num_shifts <= slave_writedata[15:0];
usr_cnt_sel <= slave_writedata[20:16];
usr_up_dn <= slave_writedata[21];
dps_changed <= 1;
dps_start_assert <= 1;
end
C_COUNTERS_REG:
begin
operation_address <= C_COUNTERS_REG;
usr_c_cnt_lo <= slave_writedata[7:0];
usr_c_cnt_hi <= slave_writedata[15:8];
usr_c_cnt_bypass_en <= slave_writedata[16];
usr_c_cnt_odd_duty_div_en <= slave_writedata[17];
usr_cnt_sel <= slave_writedata[22:18];
any_c_cnt_changed <= 1'b1;
all_c_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
BWCTRL_REG:
begin
usr_bwctrl_value <= slave_writedata[3:0];
bwctrl_changed <= 1'b1;
bwctrl_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= BWCTRL_REG;
end
CP_CURRENT_REG:
begin
usr_cp_current_value <= slave_writedata[2:0];
cp_current_changed <= 1'b1;
cp_current_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= CP_CURRENT_REG;
end
ANY_DPRIO:
begin
operation_address <= ANY_DPRIO;
manual_dprio_changed <= 1'b1;
usr_dprio_address <= slave_writedata[5:0];
usr_dprio_writedata_0 <= slave_writedata[21:6];
usr_r_w <= slave_writedata[22];
manual_dprio_done_q <= 0;
dprio_start <= 1'b1;
end
MIF_REG:
begin
mif_reg_asserted <= 1'b1;
mif_base_addr <= slave_writedata[ROM_ADDR_WIDTH-1:0];
mif_start_assert <= 1'b1;
end
endcase
end
end
end
//C Counter assigning values to the 2-d array of values for each C counter
reg [4:0] j;
always @(posedge clk)
begin
if (reset)
begin
c_cnt_changed[17:0] <= 0;
for (j = 0; j < number_of_counters; j = j + 1'b1)
begin : c_cnt_reset
temp_c_cnt_bypass_en[j] <= 0;
temp_c_cnt_odd_duty_div_en[j] <= 0;
temp_c_cnt_lo[j][7:0] <= 0;
temp_c_cnt_hi[j][7:0] <= 0;
end
end
else
begin
if (dprio_write_done)
begin
c_cnt_changed <= 0;
end
if (any_c_cnt_changed && (operation_address == C_COUNTERS_REG))
begin
case (cnt_sel)
CNT_0:
begin
temp_c_cnt_lo [0] <= usr_c_cnt_lo;
temp_c_cnt_hi [0] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [0] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [0] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [0] <= 1'b1;
end
CNT_1:
begin
temp_c_cnt_lo [1] <= usr_c_cnt_lo;
temp_c_cnt_hi [1] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [1] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [1] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [1] <= 1'b1;
end
CNT_2:
begin
temp_c_cnt_lo [2] <= usr_c_cnt_lo;
temp_c_cnt_hi [2] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [2] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [2] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [2] <= 1'b1;
end
CNT_3:
begin
temp_c_cnt_lo [3] <= usr_c_cnt_lo;
temp_c_cnt_hi [3] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [3] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [3] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [3] <= 1'b1;
end
CNT_4:
begin
temp_c_cnt_lo [4] <= usr_c_cnt_lo;
temp_c_cnt_hi [4] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [4] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [4] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [4] <= 1'b1;
end
CNT_5:
begin
temp_c_cnt_lo [5] <= usr_c_cnt_lo;
temp_c_cnt_hi [5] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [5] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [5] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [5] <= 1'b1;
end
CNT_6:
begin
temp_c_cnt_lo [6] <= usr_c_cnt_lo;
temp_c_cnt_hi [6] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [6] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [6] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [6] <= 1'b1;
end
CNT_7:
begin
temp_c_cnt_lo [7] <= usr_c_cnt_lo;
temp_c_cnt_hi [7] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [7] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [7] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [7] <= 1'b1;
end
CNT_8:
begin
temp_c_cnt_lo [8] <= usr_c_cnt_lo;
temp_c_cnt_hi [8] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [8] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [8] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [8] <= 1'b1;
end
CNT_9:
begin
temp_c_cnt_lo [9] <= usr_c_cnt_lo;
temp_c_cnt_hi [9] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [9] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [9] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [9] <= 1'b1;
end
CNT_10:
begin
temp_c_cnt_lo [10] <= usr_c_cnt_lo;
temp_c_cnt_hi [10] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [10] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [10] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [10] <= 1'b1;
end
CNT_11:
begin
temp_c_cnt_lo [11] <= usr_c_cnt_lo;
temp_c_cnt_hi [11] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [11] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [11] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [11] <= 1'b1;
end
CNT_12:
begin
temp_c_cnt_lo [12] <= usr_c_cnt_lo;
temp_c_cnt_hi [12] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [12] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [12] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [12] <= 1'b1;
end
CNT_13:
begin
temp_c_cnt_lo [13] <= usr_c_cnt_lo;
temp_c_cnt_hi [13] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [13] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [13] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [13] <= 1'b1;
end
CNT_14:
begin
temp_c_cnt_lo [14] <= usr_c_cnt_lo;
temp_c_cnt_hi [14] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [14] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [14] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [14] <= 1'b1;
end
CNT_15:
begin
temp_c_cnt_lo [15] <= usr_c_cnt_lo;
temp_c_cnt_hi [15] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [15] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [15] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [15] <= 1'b1;
end
CNT_16:
begin
temp_c_cnt_lo [16] <= usr_c_cnt_lo;
temp_c_cnt_hi [16] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [16] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [16] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [16] <= 1'b1;
end
CNT_17:
begin
temp_c_cnt_lo [17] <= usr_c_cnt_lo;
temp_c_cnt_hi [17] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [17] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [17] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [17] <= 1'b1;
end
endcase
end
end
end
//logic to handle which writes the user indicated and wants to start.
assign usr_valid_changes =dsm_k_changed| any_c_cnt_changed |n_cnt_changed | m_cnt_changed | dps_changed_valid |manual_dprio_changed |cp_current_changed|bwctrl_changed;
//start the reconfig operations by writing to the DPRIO
reg break_loop;
reg [4:0] i;
always @(*)
begin
dprio_temp_read_1 = 0;
dprio_temp_read_2 = 0;
dprio_temp_m_n_c_readdata_1_d = 0;
dprio_temp_m_n_c_readdata_2_d = 0;
break_loop = 0;
dprio_next_state = DPRIO_IDLE;
avmm_dprio_write = 0;
avmm_dprio_read = 0;
avmm_dprio_address = 0;
avmm_dprio_writedata = 0;
avmm_dprio_byteen = 0;
dprio_write_done = 1;
manual_dprio_done_d = 0;
n_cnt_done_d = 0;
dsm_k_done_d = 0;
dsm_k_ready_false_done_d = 0;
m_cnt_done_d = 0;
c_cnt_done_d[17:0] = 0;
all_c_cnt_done_d = 0;
bwctrl_done_d = 0;
cp_current_done_d = 0;
i = 0;
// Deassert dprio_write_done so it doesn't reset mif_reg_asserted (toggled writes)
if (dprio_start | mif_start_assert)
dprio_write_done = 0;
if (current_state == WAIT_ON_LOCK)
begin
case (dprio_cur_state)
ONE:
begin
if (n_cnt_changed & !n_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = N_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_n_cnt_lo;
avmm_dprio_writedata[15:8] = usr_n_cnt_hi;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = M_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_m_cnt_lo;
avmm_dprio_writedata[15:8] = usr_m_cnt_hi;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_hilo
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
if (fpll_1) avmm_dprio_address = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - i;
else avmm_dprio_address = C_CNT_0_DIV_ADDR + i;
avmm_dprio_writedata[7:0] = temp_c_cnt_lo[i];
avmm_dprio_writedata[15:8] = temp_c_cnt_hi[i];
//To break from the loop, since only one counter
//is addressed at a time
break_loop = 1'b1;
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (cp_current_changed & !cp_current_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_write = usr_r_w;
avmm_dprio_address = usr_dprio_address;
avmm_dprio_writedata[15:0] = usr_dprio_writedata_0;
end
else dprio_next_state = DPRIO_IDLE;
end
TWO:
begin
//handle reading the two setting bits on n_cnt, then
//writing them back while preserving other bits.
//Issue two consecutive reads then wait; readLatency=3
dprio_write_done = 0;
dprio_next_state = THREE;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
//reading the K ready 16 bit word. Need to write 0 to it
//afterwards to indicate that K has not been done writing
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
dprio_next_state = FOUR;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
dprio_next_state = FOUR;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
dprio_next_state = FOUR;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
avmm_dprio_read = ~usr_r_w;
avmm_dprio_address = usr_dprio_address;
dprio_next_state = DPRIO_DONE;
end
else dprio_next_state = DPRIO_IDLE;
end
THREE:
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
dprio_next_state = FOUR;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
else dprio_next_state = DPRIO_IDLE;
end
FOUR:
begin
dprio_temp_read_1 = 1'b1;
dprio_write_done = 0;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
dprio_temp_m_n_c_readdata_1_d = dprio_readdata;
dprio_next_state = FIVE;
end
else dprio_next_state = DPRIO_IDLE;
end
FIVE:
begin
dprio_write_done = 0;
dprio_temp_read_2 = 1'b1;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
//this is where DSM ready value comes.
//Need to store in a register to be used later
dprio_temp_m_n_c_readdata_2_d = dprio_readdata;
dprio_next_state = SIX;
end
else dprio_next_state = DPRIO_IDLE;
end
SIX:
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = SEVEN;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_1_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_bypass_en;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_bypass_en;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_write = 0;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_write = 0;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_write = 0;
end
else dprio_next_state = DPRIO_IDLE;
end
SEVEN:
begin
dprio_write_done = 0;
dprio_next_state = EIGHT;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_odd_duty_div_en;
n_cnt_done_d = 1'b1;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_odd_duty_div_en;
m_cnt_done_d = 1'b1;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b0;
dsm_k_ready_false_done_d = 1'b1;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
avmm_dprio_writedata[3:0] = usr_bwctrl_value;
bwctrl_done_d = 1'b1;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
avmm_dprio_writedata[2:0] = usr_cp_current_value;
cp_current_done_d = 1'b1;
end
//if all C_cnt that were changed are done, then assert all_c_cnt_done
if (c_cnt_done_d == c_cnt_changed)
all_c_cnt_done_d = 1'b1;
if (n_cnt_changed & n_cnt_done_d)
dprio_next_state = DPRIO_DONE;
if (any_c_cnt_changed & !all_c_cnt_done_d & !all_c_cnt_done_q)
dprio_next_state = ONE;
else if (m_cnt_changed & !m_cnt_done_d & !m_cnt_done_q)
dprio_next_state = ONE;
else if (dsm_k_changed & !dsm_k_ready_false_done_d)
dprio_next_state = TWO;
else if (dsm_k_changed & !dsm_k_done_q)
dprio_next_state = EIGHT;
else if (bwctrl_changed & !bwctrl_done_d)
dprio_next_state = TWO;
else if (cp_current_changed & !cp_current_done_d)
dprio_next_state = TWO;
else
begin
dprio_next_state = DPRIO_DONE;
dprio_write_done = 1'b1;
end
end
//finish the rest of the DSM reads/writes
//writing k value, writing k_ready to 1.
EIGHT:
begin
dprio_write_done = 0;
dprio_next_state = NINE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_0;
avmm_dprio_writedata[15:0] = usr_k_value[15:0];
end
end
NINE:
begin
dprio_write_done = 0;
dprio_next_state = TEN;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_1;
avmm_dprio_writedata[15:0] = usr_k_value[31:16];
end
end
TEN:
begin
dprio_write_done = 0;
dprio_next_state = ONE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
//already have the readdata for DSM_K_READY_ADDR since we read it
//earlier. Just reuse here
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b1;
dsm_k_done_d = 1'b1;
end
end
DPRIO_DONE:
begin
dprio_write_done = 1'b1;
if (dprio_start) dprio_next_state = DPRIO_IDLE;
else dprio_next_state = DPRIO_DONE;
end
DPRIO_IDLE:
begin
if (dprio_start) dprio_next_state = ONE;
else dprio_next_state = DPRIO_IDLE;
end
default: dprio_next_state = 4'bxxxx;
endcase
end
end
//assert the waitreq signal according to the state of the slave
assign slave_waitrequest = (slave_mode==mode_WR) ? ((locked === 1'b1) ? (((current_state==WAIT_ON_LOCK) & !dprio_write_done) | !dps_done |reset|!dprio_init_done) : 1'b1) : 1'b0;
// Read operations
always @(*)
begin
status = 0;
if (slave_mode == mode_POLL)
//asserting status to 1 if the slave is done.
status = (current_state == LOCKED);
end
//************************************************************//
//************************************************************//
//******************** READ STATE MACHINE ********************//
//************************************************************//
//************************************************************//
reg [1:0] current_read_state;
reg [1:0] next_read_state;
reg [5:0] slave_address_int_d;
reg [5:0] slave_address_int_q;
reg dprio_read_1;
reg [5:0] dprio_address_1;
reg [1:0] dprio_byteen_1;
reg [4:0] usr_cnt_sel_1;
localparam READ = 2'b00, READ_WAIT = 2'b01, READ_IDLE = 2'b10;
always @(posedge clk)
begin
if (reset)
begin
current_read_state <= READ_IDLE;
slave_address_int_q <= 0;
slave_readdata_q <= 0;
end
else
begin
current_read_state <= next_read_state;
slave_address_int_q <= slave_address_int_d;
slave_readdata_q <= slave_readdata_d;
end
end
always @(*)
begin
dprio_read_1 = 0;
dprio_address_1 = 0;
dprio_byteen_1 = 0;
slave_address_int_d = 0;
slave_readdata_d = 0;
status_read = 0;
usr_cnt_sel_1 = 0;
case(current_read_state)
READ_IDLE:
begin
slave_address_int_d = 0;
next_read_state = READ_IDLE;
if ((current_state != WAIT_ON_LOCK) && slave_read)
begin
slave_address_int_d = slave_address;
if ((slave_address >= CNT_BASE) && (slave_address < CNT_BASE+18))
begin
next_read_state = READ_WAIT;
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
usr_cnt_sel_1 = (slave_address[4:0] - CNT_BASE);
if (fpll_1) dprio_address_1 = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - cnt_sel;
else dprio_address_1 = C_CNT_0_DIV_ADDR + cnt_sel;
end
else
begin
case (slave_address)
MODE_REG:
begin
next_read_state = READ_WAIT;
slave_readdata_d = slave_mode;
end
STATUS_REG:
begin
next_read_state = READ_WAIT;
status_read = 1'b1;
slave_readdata_d = status;
end
N_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = N_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
M_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = M_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
BWCTRL_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = BWCTRL_ADDR;
next_read_state = READ_WAIT;
end
CP_CURRENT_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = CP_CURRENT_ADDR;
next_read_state = READ_WAIT;
end
default : next_read_state = READ_IDLE;
endcase
end
end
else
next_read_state = READ_IDLE;
end
READ_WAIT:
begin
next_read_state = READ;
slave_address_int_d = slave_address_int_q;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
endcase
end
READ:
begin
next_read_state = READ_IDLE;
slave_address_int_d = slave_address_int_q;
slave_readdata_d = dprio_readdata;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
BWCTRL_REG:
begin
slave_readdata_d = dprio_readdata[3:0];
end
CP_CURRENT_REG:
begin
slave_readdata_d = dprio_readdata[2:0];
end
endcase
end
default: next_read_state = 2'bxx;
endcase
end
dyn_phase_shift dyn_phase_shift_inst (
.clk(clk),
.reset(reset),
.phase_done(phase_done),
.pll_start_valid(pll_start_valid),
.dps_changed(dps_changed),
.dps_changed_valid(dps_changed_valid),
.dprio_write_done(dprio_write_done),
.usr_num_shifts(usr_num_shifts),
.usr_cnt_sel(usr_cnt_sel|usr_cnt_sel_1),
.usr_up_dn(usr_up_dn),
.locked(locked),
.dps_done(dps_done),
.phase_en(phase_en),
.up_dn(up_dn),
.cnt_sel(cnt_sel));
defparam dyn_phase_shift_inst.device_family = device_family;
assign dprio_clk = clk;
self_reset self_reset_inst (mgmt_reset, clk, reset, dprio_init_reset);
dprio_mux dprio_mux_inst (
.init_dprio_address(init_dprio_address),
.init_dprio_read(init_dprio_read),
.init_dprio_byteen(init_dprio_byteen),
.init_dprio_write(init_dprio_write),
.init_dprio_writedata(init_dprio_writedata),
.init_atpgmode(init_atpgmode),
.init_mdio_dis(init_mdio_dis),
.init_scanen(init_scanen),
.init_ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done),
// Inputs from avmm master
.avmm_dprio_address(avmm_dprio_address | dprio_address_1),
.avmm_dprio_read(avmm_dprio_read | dprio_read_1),
.avmm_dprio_byteen(avmm_dprio_byteen | dprio_byteen_1),
.avmm_dprio_write(avmm_dprio_write),
.avmm_dprio_writedata(avmm_dprio_writedata),
.avmm_atpgmode(avmm_atpgmode),
.avmm_mdio_dis(avmm_mdio_dis),
.avmm_scanen(avmm_scanen),
// Outputs to fpll
.dprio_address(dprio_address),
.dprio_read(dprio_read),
.dprio_byteen(dprio_byteen),
.dprio_write(dprio_write),
.dprio_writedata(dprio_writedata),
.atpgmode(dprio_atpgmode),
.mdio_dis(dprio_mdio_dis),
.scanen(dprio_scanen),
.ser_shift_load(dprio_ser_shift_load)
);
fpll_dprio_init fpll_dprio_init_inst (
.clk(clk),
.reset_n(~reset),
.locked(locked),
//outputs
.dprio_address(init_dprio_address),
.dprio_read(init_dprio_read),
.dprio_byteen(init_dprio_byteen),
.dprio_write(init_dprio_write),
.dprio_writedata(init_dprio_writedata),
.atpgmode(init_atpgmode),
.mdio_dis(init_mdio_dis),
.scanen(init_scanen),
.ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done));
//address luts, to be reconfigged by the Fitter
//FPLL_1 or 0 address lut
generic_lcell_comb lcell_fpll_0_1 (
.dataa(1'b0),
.combout (fpll_1));
defparam lcell_fpll_0_1.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_fpll_0_1.dont_touch = "on";
defparam lcell_fpll_0_1.family = device_family;
wire dprio_read_combout;
generic_lcell_comb lcell_dprio_read (
.dataa(fpll_1),
.datab(dprio_read),
.datac(1'b0),
.datad(1'b0),
.datae(1'b0),
.dataf(1'b0),
.combout (dprio_read_combout));
defparam lcell_dprio_read.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_dprio_read.dont_touch = "on";
defparam lcell_dprio_read.family = device_family;
//assign reconfig_to_pll signals
assign reconfig_to_pll[0] = dprio_clk;
assign reconfig_to_pll[1] = ~dprio_init_reset;
assign reconfig_to_pll[2] = dprio_write;
assign reconfig_to_pll[3] = dprio_read_combout;
assign reconfig_to_pll[9:4] = dprio_address;
assign reconfig_to_pll[25:10] = dprio_writedata;
assign reconfig_to_pll[27:26] = dprio_byteen;
assign reconfig_to_pll[28] = dprio_ser_shift_load;
assign reconfig_to_pll[29] = dprio_mdio_dis;
assign reconfig_to_pll[30] = phase_en;
assign reconfig_to_pll[31] = up_dn;
assign reconfig_to_pll[36:32] = cnt_sel;
assign reconfig_to_pll[37] = dprio_scanen;
assign reconfig_to_pll[38] = dprio_atpgmode;
//assign reconfig_to_pll[40:37] = clken;
assign reconfig_to_pll[63:39] = 0;
//assign reconfig_from_pll signals
assign dprio_readdata = reconfig_from_pll [15:0];
assign locked = reconfig_from_pll [16];
assign phase_done = reconfig_from_pll [17];
endmodule
module self_reset (input wire mgmt_reset, input wire clk, output wire reset, output wire init_reset);
localparam RESET_COUNTER_VALUE = 3'd2;
localparam INITIAL_WAIT_VALUE = 9'd340;
reg [9:0]counter;
reg local_reset;
reg usr_mode_init_wait;
initial
begin
local_reset = 1'b1;
counter = 0;
usr_mode_init_wait = 0;
end
always @(posedge clk)
begin
if (mgmt_reset)
begin
counter <= 0;
end
else
begin
if (!usr_mode_init_wait)
begin
if (counter == INITIAL_WAIT_VALUE)
begin
local_reset <= 0;
usr_mode_init_wait <= 1'b1;
counter <= 0;
end
else
begin
counter <= counter + 1'b1;
end
end
else
begin
if (counter == RESET_COUNTER_VALUE)
local_reset <= 0;
else
counter <= counter + 1'b1;
end
end
end
assign reset = mgmt_reset | local_reset;
assign init_reset = local_reset;
endmodule
module dprio_mux (
// Inputs from init block
input [ 5:0] init_dprio_address,
input init_dprio_read,
input [ 1:0] init_dprio_byteen,
input init_dprio_write,
input [15:0] init_dprio_writedata,
input init_atpgmode,
input init_mdio_dis,
input init_scanen,
input init_ser_shift_load,
input dprio_init_done,
// Inputs from avmm master
input [ 5:0] avmm_dprio_address,
input avmm_dprio_read,
input [ 1:0] avmm_dprio_byteen,
input avmm_dprio_write,
input [15:0] avmm_dprio_writedata,
input avmm_atpgmode,
input avmm_mdio_dis,
input avmm_scanen,
input avmm_ser_shift_load,
// Outputs to fpll
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output atpgmode,
output mdio_dis,
output scanen,
output ser_shift_load
);
assign dprio_address = dprio_init_done ? avmm_dprio_address : init_dprio_address;
assign dprio_read = dprio_init_done ? avmm_dprio_read : init_dprio_read;
assign dprio_byteen = dprio_init_done ? avmm_dprio_byteen : init_dprio_byteen;
assign dprio_write = dprio_init_done ? avmm_dprio_write : init_dprio_write;
assign dprio_writedata = dprio_init_done ? avmm_dprio_writedata : init_dprio_writedata;
assign atpgmode = init_atpgmode;
assign scanen = init_scanen;
assign mdio_dis = init_mdio_dis;
assign ser_shift_load = init_ser_shift_load ;
endmodule
module fpll_dprio_init (
input clk,
input reset_n,
input locked,
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output reg atpgmode,
output reg mdio_dis,
output reg scanen,
output reg ser_shift_load,
output reg dprio_init_done
);
reg [1:0] rst_n = 2'b00;
reg [6:0] count = 7'd0;
reg init_done_forever;
// Internal versions of control signals
wire int_mdio_dis;
wire int_ser_shift_load;
wire int_dprio_init_done;
wire int_atpgmode/*synthesis keep*/;
wire int_scanen/*synthesis keep*/;
assign dprio_address = count[6] ? 5'b0 : count[5:0] ;
assign dprio_byteen = 2'b11; // always enabled
assign dprio_write = ~count[6] & reset_n ; // write for first 64 cycles
assign dprio_read = 1'b0;
assign dprio_writedata = 16'd0;
assign int_ser_shift_load = count[6] ? |count[2:1] : 1'b1;
assign int_mdio_dis = count[6] ? ~count[2] : 1'b1;
assign int_dprio_init_done = ~init_done_forever ? (count[6] ? &count[2:0] : 1'b0)
: 1'b1;
assign int_atpgmode = 0;
assign int_scanen = 0;
initial begin
count = 7'd0;
init_done_forever = 0;
mdio_dis = 1'b1;
ser_shift_load = 1'b1;
dprio_init_done = 1'b0;
scanen = 1'b0;
atpgmode = 1'b0;
end
// reset synch.
always @(posedge clk or negedge reset_n)
if(!reset_n) rst_n <= 2'b00;
else rst_n <= {rst_n[0],1'b1};
// counter
always @(posedge clk)
begin
if (!rst_n[1])
init_done_forever <= 1'b0;
else
begin
if (count[6] && &count[1:0])
init_done_forever <= 1'b1;
end
end
always @(posedge clk or negedge rst_n[1])
begin
if(!rst_n[1])
begin
count <= 7'd0;
end
else if(~int_dprio_init_done)
begin
count <= count + 7'd1;
end
else
begin
count <= count;
end
end
// outputs
always @(posedge clk) begin
mdio_dis <= int_mdio_dis;
ser_shift_load <= int_ser_shift_load;
dprio_init_done <= int_dprio_init_done;
atpgmode <= int_atpgmode;
scanen <= int_scanen;
end
endmodule
module dyn_phase_shift
#(
parameter device_family = "Stratix V"
) (
input wire clk,
input wire reset,
input wire phase_done,
input wire pll_start_valid,
input wire dps_changed,
input wire dprio_write_done,
input wire [15:0] usr_num_shifts,
input wire [4:0] usr_cnt_sel,
input wire usr_up_dn,
input wire locked,
//output
output wire dps_done,
output reg phase_en,
output wire up_dn,
output wire dps_changed_valid,
output wire [4:0] cnt_sel);
reg first_phase_shift_d;
reg first_phase_shift_q;
reg [15:0] phase_en_counter;
reg [3:0] dps_current_state;
reg [3:0] dps_next_state;
localparam DPS_START = 4'd0, DPS_WAIT_PHASE_DONE = 4'd1, DPS_DONE = 4'd2, DPS_WAIT_PHASE_EN = 4'd3, DPS_WAIT_DPRIO_WRITING = 4'd4, DPS_CHANGED = 4'd5;
localparam PHASE_EN_WAIT_COUNTER = 5'd1;
reg [15:0] shifts_done_counter;
reg phase_done_final;
wire gnd /*synthesis keep*/;
//fsm
//always block controlling the state regs
always @(posedge clk)
begin
if (reset)
begin
dps_current_state <= DPS_DONE;
end
else
begin
dps_current_state <= dps_next_state;
end
end
//the combinational part. assigning the next state
//this turns on the phase_done_final signal when phase_done does this:
//_____ ______
// |______|
always @(*)
begin
phase_done_final = 0;
first_phase_shift_d = 0;
phase_en = 0;
dps_next_state = DPS_DONE;
case (dps_current_state)
DPS_START:
begin
phase_en = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
DPS_WAIT_PHASE_EN:
begin
phase_en = 1'b1;
if (first_phase_shift_q)
begin
first_phase_shift_d = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
else
begin
if (phase_en_counter == PHASE_EN_WAIT_COUNTER)
dps_next_state = DPS_WAIT_PHASE_DONE;
else dps_next_state = DPS_WAIT_PHASE_EN;
end
end
DPS_WAIT_PHASE_DONE:
begin
if (!phase_done | !locked)
begin
dps_next_state = DPS_WAIT_PHASE_DONE;
end
else
begin
if ((usr_num_shifts != shifts_done_counter) & (usr_num_shifts != 0))
begin
dps_next_state = DPS_START;
phase_done_final = 1'b1;
end
else
begin
dps_next_state = DPS_DONE;
end
end
end
DPS_DONE:
begin
phase_done_final = 0;
if (dps_changed)
dps_next_state = DPS_CHANGED;
else dps_next_state = DPS_DONE;
end
DPS_CHANGED:
begin
if (pll_start_valid)
dps_next_state = DPS_WAIT_DPRIO_WRITING;
else
dps_next_state = DPS_CHANGED;
end
DPS_WAIT_DPRIO_WRITING:
begin
if (dprio_write_done)
dps_next_state = DPS_START;
else
dps_next_state = DPS_WAIT_DPRIO_WRITING;
end
default: dps_next_state = 4'bxxxx;
endcase
end
always @(posedge clk)
begin
if (dps_current_state == DPS_WAIT_PHASE_DONE)
phase_en_counter <= 0;
else if (dps_current_state == DPS_WAIT_PHASE_EN)
phase_en_counter <= phase_en_counter + 1'b1;
if (reset)
begin
phase_en_counter <= 0;
shifts_done_counter <= 1'b1;
first_phase_shift_q <= 1;
end
else
begin
if (first_phase_shift_d)
first_phase_shift_q <= 0;
if (dps_done)
begin
shifts_done_counter <= 1'b1;
end
else
begin
if (phase_done_final & (dps_next_state!= DPS_DONE))
shifts_done_counter <= shifts_done_counter + 1'b1;
else
shifts_done_counter <= shifts_done_counter;
end
end
end
assign dps_changed_valid = (dps_current_state == DPS_CHANGED);
assign dps_done =(dps_current_state == DPS_DONE) | (dps_current_state == DPS_CHANGED);
assign up_dn = usr_up_dn;
assign gnd = 1'b0;
//cnt select luts (5)
generic_lcell_comb lcell_cnt_sel_0 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[0]));
defparam lcell_cnt_sel_0.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_cnt_sel_0.dont_touch = "on";
defparam lcell_cnt_sel_0.family = device_family;
generic_lcell_comb lcell_cnt_sel_1 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[1]));
defparam lcell_cnt_sel_1.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_cnt_sel_1.dont_touch = "on";
defparam lcell_cnt_sel_1.family = device_family;
generic_lcell_comb lcell_cnt_sel_2 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[2]));
defparam lcell_cnt_sel_2.lut_mask = 64'hF0F0F0F0F0F0F0F0;
defparam lcell_cnt_sel_2.dont_touch = "on";
defparam lcell_cnt_sel_2.family = device_family;
generic_lcell_comb lcell_cnt_sel_3 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[3]));
defparam lcell_cnt_sel_3.lut_mask = 64'hFF00FF00FF00FF00;
defparam lcell_cnt_sel_3.dont_touch = "on";
defparam lcell_cnt_sel_3.family = device_family;
generic_lcell_comb lcell_cnt_sel_4 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[4]));
defparam lcell_cnt_sel_4.lut_mask = 64'hFFFF0000FFFF0000;
defparam lcell_cnt_sel_4.dont_touch = "on";
defparam lcell_cnt_sel_4.family = device_family;
endmodule
module generic_lcell_comb
#(
//parameter
parameter family = "Stratix V",
parameter lut_mask = 64'hAAAAAAAAAAAAAAAA,
parameter dont_touch = "on"
) (
input dataa,
input datab,
input datac,
input datad,
input datae,
input dataf,
output combout
);
generate
if (family == "Stratix V")
begin
stratixv_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V")
begin
arriav_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V GZ")
begin
arriavgz_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Cyclone V")
begin
cyclonev_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
endgenerate
endmodule
|
(** * Extraction: Extracting ML from Coq *)
(** * Basic Extraction *)
(** In its simplest form, program extraction from Coq is completely straightforward. *)
(** First we say what language we want to extract into. Options are OCaml (the
most mature), Haskell (which mostly works), and Scheme (a bit out
of date). *)
Extraction Language Ocaml.
(** Now we load up the Coq environment with some definitions, either
directly or by importing them from other modules. *)
Require Import SfLib.
Require Import ImpCEvalFun.
(** Finally, we tell Coq the name of a definition to extract and the
name of a file to put the extracted code into. *)
Extraction "imp1.ml" ceval_step.
(** When Coq processes this command, it generates a file [imp1.ml]
containing an extracted version of [ceval_step], together with
everything that it recursively depends on. Have a look at this
file now. *)
(* ############################################################## *)
(** * Controlling Extraction of Specific Types *)
(** We can tell Coq to extract certain [Inductive] definitions to
specific OCaml types. For each one, we must say
- how the Coq type itself should be represented in OCaml, and
- how each constructor should be translated. *)
Extract Inductive bool => "bool" [ "true" "false" ].
(** Also, for non-enumeration types (where the constructors take
arguments), we give an OCaml expression that can be used as a
"recursor" over elements of the type. (Think Church numerals.) *)
Extract Inductive nat => "int"
[ "0" "(fun x -> x + 1)" ]
"(fun zero succ n ->
if n=0 then zero () else succ (n-1))".
(** We can also extract defined constants to specific OCaml terms or
operators. *)
Extract Constant plus => "( + )".
Extract Constant mult => "( * )".
Extract Constant beq_nat => "( = )".
(** Important: It is entirely _your responsibility_ to make sure that
the translations you're proving make sense. For example, it might
be tempting to include this one
Extract Constant minus => "( - )".
but doing so could lead to serious confusion! (Why?)
*)
Extraction "imp2.ml" ceval_step.
(** Have a look at the file [imp2.ml]. Notice how the fundamental
definitions have changed from [imp1.ml]. *)
(* ############################################################## *)
(** * A Complete Example *)
(** To use our extracted evaluator to run Imp programs, all we need to
add is a tiny driver program that calls the evaluator and somehow
prints out the result.
For simplicity, we'll print results by dumping out the first four
memory locations in the final state.
Also, to make it easier to type in examples, let's extract a
parser from the [ImpParser] Coq module. To do this, we need a few
more declarations to set up the right correspondence between Coq
strings and lists of OCaml characters. *)
Require Import Ascii String.
Extract Inductive ascii => char
[
"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))"
]
"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))".
Extract Constant zero => "'\000'".
Extract Constant one => "'\001'".
Extract Constant shift =>
"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)".
Extract Inlined Constant ascii_dec => "(=)".
(** We also need one more variant of booleans. *)
Extract Inductive sumbool => "bool" ["true" "false"].
(** The extraction is the same as always. *)
Require Import Imp.
Require Import ImpParser.
Extraction "imp.ml" empty_state ceval_step parse.
(** Now let's run our generated Imp evaluator. First, have a look at
[impdriver.ml]. (This was written by hand, not extracted.)
Next, compile the driver together with the extracted code and
execute it, as follows.
<<
ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml
./impdriver
>>
(The [-w] flags to [ocamlc] are just there to suppress a few
spurious warnings.) *)
(* ############################################################## *)
(** * Discussion *)
(** Since we've proved that the [ceval_step] function behaves the same
as the [ceval] relation in an appropriate sense, the extracted
program can be viewed as a _certified_ Imp interpreter. (Of
course, the parser is not certified in any interesting sense,
since we didn't prove anything about it.) *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * MoreStlc: More on the Simply Typed Lambda-Calculus *)
Require Export Stlc.
(* ###################################################################### *)
(** * Simple Extensions to STLC *)
(** The simply typed lambda-calculus has enough structure to make its
theoretical properties interesting, but it is not much of a
programming language. In this chapter, we begin to close the gap
with real-world languages by introducing a number of familiar
features that have straightforward treatments at the level of
typing. *)
(** ** Numbers *)
(** Adding types, constants, and primitive operations for numbers is
easy -- just a matter of combining the [Types] and [Stlc]
chapters. *)
(** ** [let]-bindings *)
(** When writing a complex expression, it is often useful to give
names to some of its subexpressions: this avoids repetition and
often increases readability. Most languages provide one or more
ways of doing this. In OCaml (and Coq), for example, we can write
[let x=t1 in t2] to mean ``evaluate the expression [t1] and bind
the name [x] to the resulting value while evaluating [t2].''
Our [let]-binder follows OCaml's in choosing a call-by-value
evaluation order, where the [let]-bound term must be fully
evaluated before evaluation of the [let]-body can begin. The
typing rule [T_Let] tells us that the type of a [let] can be
calculated by calculating the type of the [let]-bound term,
extending the context with a binding with this type, and in this
enriched context calculating the type of the body, which is then
the type of the whole [let] expression.
At this point in the course, it's probably easier simply to look
at the rules defining this new feature as to wade through a lot of
english text conveying the same information. Here they are: *)
(** Syntax:
<<
t ::= Terms
| ... (other terms same as before)
| let x=t in t let-binding
>>
*)
(**
Reduction:
t1 ==> t1'
---------------------------------- (ST_Let1)
let x=t1 in t2 ==> let x=t1' in t2
---------------------------- (ST_LetValue)
let x=v1 in t2 ==> [x:=v1]t2
Typing:
Gamma |- t1 : T1 Gamma , x:T1 |- t2 : T2
-------------------------------------------- (T_Let)
Gamma |- let x=t1 in t2 : T2
*)
(** ** Pairs *)
(** Our functional programming examples in Coq have made
frequent use of _pairs_ of values. The type of such pairs is
called a _product type_.
The formalization of pairs is almost too simple to be worth
discussing. However, let's look briefly at the various parts of
the definition to emphasize the common pattern. *)
(** In Coq, the primitive way of extracting the components of a pair
is _pattern matching_. An alternative style is to take [fst] and
[snd] -- the first- and second-projection operators -- as
primitives. Just for fun, let's do our products this way. For
example, here's how we'd write a function that takes a pair of
numbers and returns the pair of their sum and difference:
<<
\x:Nat*Nat.
let sum = x.fst + x.snd in
let diff = x.fst - x.snd in
(sum,diff)
>>
*)
(** Adding pairs to the simply typed lambda-calculus, then, involves
adding two new forms of term -- pairing, written [(t1,t2)], and
projection, written [t.fst] for the first projection from [t] and
[t.snd] for the second projection -- plus one new type constructor,
[T1*T2], called the _product_ of [T1] and [T2]. *)
(** Syntax:
<<
t ::= Terms
| ...
| (t,t) pair
| t.fst first projection
| t.snd second projection
v ::= Values
| ...
| (v,v) pair value
T ::= Types
| ...
| T * T product type
>>
*)
(** For evaluation, we need several new rules specifying how pairs and
projection behave.
t1 ==> t1'
-------------------- (ST_Pair1)
(t1,t2) ==> (t1',t2)
t2 ==> t2'
-------------------- (ST_Pair2)
(v1,t2) ==> (v1,t2')
t1 ==> t1'
------------------ (ST_Fst1)
t1.fst ==> t1'.fst
------------------ (ST_FstPair)
(v1,v2).fst ==> v1
t1 ==> t1'
------------------ (ST_Snd1)
t1.snd ==> t1'.snd
------------------ (ST_SndPair)
(v1,v2).snd ==> v2
*)
(**
Rules [ST_FstPair] and [ST_SndPair] specify that, when a fully
evaluated pair meets a first or second projection, the result is
the appropriate component. The congruence rules [ST_Fst1] and
[ST_Snd1] allow reduction to proceed under projections, when the
term being projected from has not yet been fully evaluated.
[ST_Pair1] and [ST_Pair2] evaluate the parts of pairs: first the
left part, and then -- when a value appears on the left -- the right
part. The ordering arising from the use of the metavariables [v]
and [t] in these rules enforces a left-to-right evaluation
strategy for pairs. (Note the implicit convention that
metavariables like [v] and [v1] can only denote values.) We've
also added a clause to the definition of values, above, specifying
that [(v1,v2)] is a value. The fact that the components of a pair
value must themselves be values ensures that a pair passed as an
argument to a function will be fully evaluated before the function
body starts executing. *)
(** The typing rules for pairs and projections are straightforward.
Gamma |- t1 : T1 Gamma |- t2 : T2
--------------------------------------- (T_Pair)
Gamma |- (t1,t2) : T1*T2
Gamma |- t1 : T11*T12
--------------------- (T_Fst)
Gamma |- t1.fst : T11
Gamma |- t1 : T11*T12
--------------------- (T_Snd)
Gamma |- t1.snd : T12
*)
(** The rule [T_Pair] says that [(t1,t2)] has type [T1*T2] if [t1] has
type [T1] and [t2] has type [T2]. Conversely, the rules [T_Fst]
and [T_Snd] tell us that, if [t1] has a product type
[T11*T12] (i.e., if it will evaluate to a pair), then the types of
the projections from this pair are [T11] and [T12]. *)
(** ** Unit *)
(** Another handy base type, found especially in languages in
the ML family, is the singleton type [Unit]. *)
(** It has a single element -- the term constant [unit] (with a small
[u]) -- and a typing rule making [unit] an element of [Unit]. We
also add [unit] to the set of possible result values of
computations -- indeed, [unit] is the _only_ possible result of
evaluating an expression of type [Unit]. *)
(** Syntax:
<<
t ::= Terms
| ...
| unit unit value
v ::= Values
| ...
| unit unit
T ::= Types
| ...
| Unit Unit type
>>
Typing:
-------------------- (T_Unit)
Gamma |- unit : Unit
*)
(** It may seem a little strange to bother defining a type that
has just one element -- after all, wouldn't every computation
living in such a type be trivial?
This is a fair question, and indeed in the STLC the [Unit] type is
not especially critical (though we'll see two uses for it below).
Where [Unit] really comes in handy is in richer languages with
various sorts of _side effects_ -- e.g., assignment statements
that mutate variables or pointers, exceptions and other sorts of
nonlocal control structures, etc. In such languages, it is
convenient to have a type for the (trivial) result of an
expression that is evaluated only for its effect. *)
(** ** Sums *)
(** Many programs need to deal with values that can take two distinct
forms. For example, we might identify employees in an accounting
application using using _either_ their name _or_ their id number.
A search function might return _either_ a matching value _or_ an
error code.
These are specific examples of a binary _sum type_,
which describes a set of values drawn from exactly two given types, e.g.
<<
Nat + Bool
>>
*)
(** We create elements of these types by _tagging_ elements of
the component types. For example, if [n] is a [Nat] then [inl v]
is an element of [Nat+Bool]; similarly, if [b] is a [Bool] then
[inr b] is a [Nat+Bool]. The names of the tags [inl] and [inr]
arise from thinking of them as functions
<<
inl : Nat -> Nat + Bool
inr : Bool -> Nat + Bool
>>
that "inject" elements of [Nat] or [Bool] into the left and right
components of the sum type [Nat+Bool]. (But note that we don't
actually treat them as functions in the way we formalize them:
[inl] and [inr] are keywords, and [inl t] and [inr t] are primitive
syntactic forms, not function applications. This allows us to give
them their own special typing rules.) *)
(** In general, the elements of a type [T1 + T2] consist of the
elements of [T1] tagged with the token [inl], plus the elements of
[T2] tagged with [inr]. *)
(** One important usage of sums is signaling errors:
<<
div : Nat -> Nat -> (Nat + Unit) =
div =
\x:Nat. \y:Nat.
if iszero y then
inr unit
else
inl ...
>>
The type [Nat + Unit] above is in fact isomorphic to [option nat]
in Coq, and we've already seen how to signal errors with options. *)
(** To _use_ elements of sum types, we introduce a [case]
construct (a very simplified form of Coq's [match]) to destruct
them. For example, the following procedure converts a [Nat+Bool]
into a [Nat]: *)
(**
<<
getNat =
\x:Nat+Bool.
case x of
inl n => n
| inr b => if b then 1 else 0
>>
*)
(** More formally... *)
(** Syntax:
<<
t ::= Terms
| ...
| inl T t tagging (left)
| inr T t tagging (right)
| case t of case
inl x => t
| inr x => t
v ::= Values
| ...
| inl T v tagged value (left)
| inr T v tagged value (right)
T ::= Types
| ...
| T + T sum type
>>
*)
(** Evaluation:
t1 ==> t1'
---------------------- (ST_Inl)
inl T t1 ==> inl T t1'
t1 ==> t1'
---------------------- (ST_Inr)
inr T t1 ==> inr T t1'
t0 ==> t0'
------------------------------------------- (ST_Case)
case t0 of inl x1 => t1 | inr x2 => t2 ==>
case t0' of inl x1 => t1 | inr x2 => t2
---------------------------------------------- (ST_CaseInl)
case (inl T v0) of inl x1 => t1 | inr x2 => t2
==> [x1:=v0]t1
---------------------------------------------- (ST_CaseInr)
case (inr T v0) of inl x1 => t1 | inr x2 => t2
==> [x2:=v0]t2
*)
(** Typing:
Gamma |- t1 : T1
---------------------------- (T_Inl)
Gamma |- inl T2 t1 : T1 + T2
Gamma |- t1 : T2
---------------------------- (T_Inr)
Gamma |- inr T1 t1 : T1 + T2
Gamma |- t0 : T1+T2
Gamma , x1:T1 |- t1 : T
Gamma , x2:T2 |- t2 : T
--------------------------------------------------- (T_Case)
Gamma |- case t0 of inl x1 => t1 | inr x2 => t2 : T
We use the type annotation in [inl] and [inr] to make the typing
simpler, similarly to what we did for functions. *)
(** Without this extra
information, the typing rule [T_Inl], for example, would have to
say that, once we have shown that [t1] is an element of type [T1],
we can derive that [inl t1] is an element of [T1 + T2] for _any_
type T2. For example, we could derive both [inl 5 : Nat + Nat]
and [inl 5 : Nat + Bool] (and infinitely many other types).
This failure of uniqueness of types would mean that we cannot
build a typechecking algorithm simply by "reading the rules from
bottom to top" as we could for all the other features seen so far.
There are various ways to deal with this difficulty. One simple
one -- which we've adopted here -- forces the programmer to
explicitly annotate the "other side" of a sum type when performing
an injection. This is rather heavyweight for programmers (and so
real languages adopt other solutions), but it is easy to
understand and formalize. *)
(** ** Lists *)
(** The typing features we have seen can be classified into _base
types_ like [Bool], and _type constructors_ like [->] and [*] that
build new types from old ones. Another useful type constructor is
[List]. For every type [T], the type [List T] describes
finite-length lists whose elements are drawn from [T].
In principle, we could encode lists using pairs, sums and
_recursive_ types. But giving semantics to recursive types is
non-trivial. Instead, we'll just discuss the special case of lists
directly.
Below we give the syntax, semantics, and typing rules for lists.
Except for the fact that explicit type annotations are mandatory
on [nil] and cannot appear on [cons], these lists are essentially
identical to those we built in Coq. We use [lcase] to destruct
lists, to avoid dealing with questions like "what is the [head] of
the empty list?" *)
(** For example, here is a function that calculates the sum of
the first two elements of a list of numbers:
<<
\x:List Nat.
lcase x of nil -> 0
| a::x' -> lcase x' of nil -> a
| b::x'' -> a+b
>>
*)
(**
Syntax:
<<
t ::= Terms
| ...
| nil T
| cons t t
| lcase t of nil -> t | x::x -> t
v ::= Values
| ...
| nil T nil value
| cons v v cons value
T ::= Types
| ...
| List T list of Ts
>>
*)
(** Reduction:
t1 ==> t1'
-------------------------- (ST_Cons1)
cons t1 t2 ==> cons t1' t2
t2 ==> t2'
-------------------------- (ST_Cons2)
cons v1 t2 ==> cons v1 t2'
t1 ==> t1'
---------------------------------------- (ST_Lcase1)
(lcase t1 of nil -> t2 | xh::xt -> t3) ==>
(lcase t1' of nil -> t2 | xh::xt -> t3)
----------------------------------------- (ST_LcaseNil)
(lcase nil T of nil -> t2 | xh::xt -> t3)
==> t2
----------------------------------------------- (ST_LcaseCons)
(lcase (cons vh vt) of nil -> t2 | xh::xt -> t3)
==> [xh:=vh,xt:=vt]t3
*)
(** Typing:
----------------------- (T_Nil)
Gamma |- nil T : List T
Gamma |- t1 : T Gamma |- t2 : List T
----------------------------------------- (T_Cons)
Gamma |- cons t1 t2: List T
Gamma |- t1 : List T1
Gamma |- t2 : T
Gamma , h:T1, t:List T1 |- t3 : T
------------------------------------------------- (T_Lcase)
Gamma |- (lcase t1 of nil -> t2 | h::t -> t3) : T
*)
(** ** General Recursion *)
(** Another facility found in most programming languages (including
Coq) is the ability to define recursive functions. For example,
we might like to be able to define the factorial function like
this:
<<
fact = \x:Nat.
if x=0 then 1 else x * (fact (pred x)))
>>
But this would require quite a bit of work to formalize: we'd have
to introduce a notion of "function definitions" and carry around an
"environment" of such definitions in the definition of the [step]
relation. *)
(** Here is another way that is straightforward to formalize: instead
of writing recursive definitions where the right-hand side can
contain the identifier being defined, we can define a _fixed-point
operator_ that performs the "unfolding" of the recursive definition
in the right-hand side lazily during reduction.
<<
fact =
fix
(\f:Nat->Nat.
\x:Nat.
if x=0 then 1 else x * (f (pred x)))
>>
*)
(** The intuition is that the higher-order function [f] passed
to [fix] is a _generator_ for the [fact] function: if [fact] is
applied to a function that approximates the desired behavior of
[fact] up to some number [n] (that is, a function that returns
correct results on inputs less than or equal to [n]), then it
returns a better approximation to [fact] -- a function that returns
correct results for inputs up to [n+1]. Applying [fix] to this
generator returns its _fixed point_ -- a function that gives the
desired behavior for all inputs [n].
(The term "fixed point" has exactly the same sense as in ordinary
mathematics, where a fixed point of a function [f] is an input [x]
such that [f(x) = x]. Here, a fixed point of a function [F] of
type (say) [(Nat->Nat)->(Nat->Nat)] is a function [f] such that [F
f] is behaviorally equivalent to [f].) *)
(** Syntax:
<<
t ::= Terms
| ...
| fix t fixed-point operator
>>
Reduction:
t1 ==> t1'
------------------ (ST_Fix1)
fix t1 ==> fix t1'
F = \xf:T1.t2
----------------------- (ST_FixAbs)
fix F ==> [xf:=fix F]t2
Typing:
Gamma |- t1 : T1->T1
-------------------- (T_Fix)
Gamma |- fix t1 : T1
*)
(** Let's see how [ST_FixAbs] works by reducing [fact 3 = fix F 3],
where [F = (\f. \x. if x=0 then 1 else x * (f (pred x)))] (we are
omitting type annotations for brevity here).
<<
fix F 3
>>
[==>] [ST_FixAbs]
<<
(\x. if x=0 then 1 else x * (fix F (pred x))) 3
>>
[==>] [ST_AppAbs]
<<
if 3=0 then 1 else 3 * (fix F (pred 3))
>>
[==>] [ST_If0_Nonzero]
<<
3 * (fix F (pred 3))
>>
[==>] [ST_FixAbs + ST_Mult2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 3))
>>
[==>] [ST_PredNat + ST_Mult2 + ST_App2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 2)
>>
[==>] [ST_AppAbs + ST_Mult2]
<<
3 * (if 2=0 then 1 else 2 * (fix F (pred 2)))
>>
[==>] [ST_If0_Nonzero + ST_Mult2]
<<
3 * (2 * (fix F (pred 2)))
>>
[==>] [ST_FixAbs + 2 x ST_Mult2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 2)))
>>
[==>] [ST_PredNat + 2 x ST_Mult2 + ST_App2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 1))
>>
[==>] [ST_AppAbs + 2 x ST_Mult2]
<<
3 * (2 * (if 1=0 then 1 else 1 * (fix F (pred 1))))
>>
[==>] [ST_If0_Nonzero + 2 x ST_Mult2]
<<
3 * (2 * (1 * (fix F (pred 1))))
>>
[==>] [ST_FixAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 1))))
>>
[==>] [ST_PredNat + 3 x ST_Mult2 + ST_App2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 0)))
>>
[==>] [ST_AppAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * (if 0=0 then 1 else 0 * (fix F (pred 0)))))
>>
[==>] [ST_If0Zero + 3 x ST_Mult2]
<<
3 * (2 * (1 * 1))
>>
[==>] [ST_MultNats + 2 x ST_Mult2]
<<
3 * (2 * 1)
>>
[==>] [ST_MultNats + ST_Mult2]
<<
3 * 2
>>
[==>] [ST_MultNats]
<<
6
>>
*)
(** **** Exercise: 1 star, optional (halve_fix) *)
(** Translate this informal recursive definition into one using [fix]:
<<
halve =
\x:Nat.
if x=0 then 0
else if (pred x)=0 then 0
else 1 + (halve (pred (pred x))))
>>
(* FILL IN HERE *)
[]
*)
(** **** Exercise: 1 star, optional (fact_steps) *)
(** Write down the sequence of steps that the term [fact 1] goes
through to reduce to a normal form (assuming the usual reduction
rules for arithmetic operations).
(* FILL IN HERE *)
[]
*)
(** The ability to form the fixed point of a function of type [T->T]
for any [T] has some surprising consequences. In particular, it
implies that _every_ type is inhabited by some term. To see this,
observe that, for every type [T], we can define the term
fix (\x:T.x)
By [T_Fix] and [T_Abs], this term has type [T]. By [ST_FixAbs]
it reduces to itself, over and over again. Thus it is an
_undefined element_ of [T].
More usefully, here's an example using [fix] to define a
two-argument recursive function:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
And finally, here is an example where [fix] is used to define a
_pair_ of recursive functions (illustrating the fact that the type
[T1] in the rule [T_Fix] need not be a function type):
<<
evenodd =
fix
(\eo: (Nat->Bool * Nat->Bool).
let e = \n:Nat. if n=0 then true else eo.snd (pred n) in
let o = \n:Nat. if n=0 then false else eo.fst (pred n) in
(e,o))
even = evenodd.fst
odd = evenodd.snd
>>
*)
(* ###################################################################### *)
(** ** Records *)
(** As a final example of a basic extension of the STLC, let's
look briefly at how to define _records_ and their types.
Intuitively, records can be obtained from pairs by two kinds of
generalization: they are n-ary products (rather than just binary)
and their fields are accessed by _label_ (rather than position).
Conceptually, this extension is a straightforward generalization
of pairs and product types, but notationally it becomes a little
heavier; for this reason, we postpone its formal treatment to a
separate chapter ([Records]). *)
(** Records are not included in the extended exercise below, but
they will be useful to motivate the [Sub] chapter. *)
(** Syntax:
<<
t ::= Terms
| ...
| {i1=t1, ..., in=tn} record
| t.i projection
v ::= Values
| ...
| {i1=v1, ..., in=vn} record value
T ::= Types
| ...
| {i1:T1, ..., in:Tn} record type
>>
Intuitively, the generalization is pretty obvious. But it's worth
noticing that what we've actually written is rather informal: in
particular, we've written "[...]" in several places to mean "any
number of these," and we've omitted explicit mention of the usual
side-condition that the labels of a record should not contain
repetitions. *)
(** It is possible to devise informal notations that are
more precise, but these tend to be quite heavy and to obscure the
main points of the definitions. So we'll leave these a bit loose
here (they are informal anyway, after all) and do the work of
tightening things up elsewhere (in chapter [Records]). *)
(**
Reduction:
ti ==> ti'
------------------------------------ (ST_Rcd)
{i1=v1, ..., im=vm, in=ti, ...}
==> {i1=v1, ..., im=vm, in=ti', ...}
t1 ==> t1'
-------------- (ST_Proj1)
t1.i ==> t1'.i
------------------------- (ST_ProjRcd)
{..., i=vi, ...}.i ==> vi
Again, these rules are a bit informal. For example, the first rule
is intended to be read "if [ti] is the leftmost field that is not a
value and if [ti] steps to [ti'], then the whole record steps..."
In the last rule, the intention is that there should only be one
field called i, and that all the other fields must contain values. *)
(**
Typing:
Gamma |- t1 : T1 ... Gamma |- tn : Tn
-------------------------------------------------- (T_Rcd)
Gamma |- {i1=t1, ..., in=tn} : {i1:T1, ..., in:Tn}
Gamma |- t : {..., i:Ti, ...}
----------------------------- (T_Proj)
Gamma |- t.i : Ti
*)
(* ###################################################################### *)
(** *** Encoding Records (Optional) *)
(** There are several ways to make the above definitions precise.
- We can directly formalize the syntactic forms and inference
rules, staying as close as possible to the form we've given
them above. This is conceptually straightforward, and it's
probably what we'd want to do if we were building a real
compiler -- in particular, it will allow is to print error
messages in the form that programmers will find easy to
understand. But the formal versions of the rules will not be
pretty at all!
- We could look for a smoother way of presenting records -- for
example, a binary presentation with one constructor for the
empty record and another constructor for adding a single field
to an existing record, instead of a single monolithic
constructor that builds a whole record at once. This is the
right way to go if we are primarily interested in studying the
metatheory of the calculi with records, since it leads to
clean and elegant definitions and proofs. Chapter [Records]
shows how this can be done.
- Alternatively, if we like, we can avoid formalizing records
altogether, by stipulating that record notations are just
informal shorthands for more complex expressions involving
pairs and product types. We sketch this approach here.
First, observe that we can encode arbitrary-size tuples using
nested pairs and the [unit] value. To avoid overloading the pair
notation [(t1,t2)], we'll use curly braces without labels to write
down tuples, so [{}] is the empty tuple, [{5}] is a singleton
tuple, [{5,6}] is a 2-tuple (morally the same as a pair),
[{5,6,7}] is a triple, etc.
<<
{} ----> unit
{t1, t2, ..., tn} ----> (t1, trest)
where {t2, ..., tn} ----> trest
>>
Similarly, we can encode tuple types using nested product types:
<<
{} ----> Unit
{T1, T2, ..., Tn} ----> T1 * TRest
where {T2, ..., Tn} ----> TRest
>>
The operation of projecting a field from a tuple can be encoded
using a sequence of second projections followed by a first projection:
<<
t.0 ----> t.fst
t.(n+1) ----> (t.snd).n
>>
Next, suppose that there is some total ordering on record labels,
so that we can associate each label with a unique natural number.
This number is called the _position_ of the label. For example,
we might assign positions like this:
<<
LABEL POSITION
a 0
b 1
c 2
... ...
foo 1004
... ...
bar 10562
... ...
>>
We use these positions to encode record values as tuples (i.e., as
nested pairs) by sorting the fields according to their positions.
For example:
<<
{a=5, b=6} ----> {5,6}
{a=5, c=7} ----> {5,unit,7}
{c=7, a=5} ----> {5,unit,7}
{c=5, b=3} ----> {unit,3,5}
{f=8,c=5,a=7} ----> {7,unit,5,unit,unit,8}
{f=8,c=5} ----> {unit,unit,5,unit,unit,8}
>>
Note that each field appears in the position associated with its
label, that the size of the tuple is determined by the label with
the highest position, and that we fill in unused positions with
[unit].
We do exactly the same thing with record types:
<<
{a:Nat, b:Nat} ----> {Nat,Nat}
{c:Nat, a:Nat} ----> {Nat,Unit,Nat}
{f:Nat,c:Nat} ----> {Unit,Unit,Nat,Unit,Unit,Nat}
>>
Finally, record projection is encoded as a tuple projection from
the appropriate position:
<<
t.l ----> t.(position of l)
>>
It is not hard to check that all the typing rules for the original
"direct" presentation of records are validated by this
encoding. (The reduction rules are "almost validated" -- not
quite, because the encoding reorders fields.) *)
(** Of course, this encoding will not be very efficient if we
happen to use a record with label [bar]! But things are not
actually as bad as they might seem: for example, if we assume that
our compiler can see the whole program at the same time, we can
_choose_ the numbering of labels so that we assign small positions
to the most frequently used labels. Indeed, there are industrial
compilers that essentially do this! *)
(** *** Variants (Optional Reading) *)
(** Just as products can be generalized to records, sums can be
generalized to n-ary labeled types called _variants_. Instead of
[T1+T2], we can write something like [<l1:T1,l2:T2,...ln:Tn>]
where [l1],[l2],... are field labels which are used both to build
instances and as case arm labels.
These n-ary variants give us almost enough mechanism to build
arbitrary inductive data types like lists and trees from
scratch -- the only thing missing is a way to allow _recursion_ in
type definitions. We won't cover this here, but detailed
treatments can be found in many textbooks -- e.g., Types and
Programming Languages. *)
(* ###################################################################### *)
(** * Exercise: Formalizing the Extensions *)
(** **** Exercise: 4 stars, optional (STLC_extensions) *)
(** In this problem you will formalize a couple of the extensions
described above. We've provided the necessary additions to the
syntax of terms and types, and we've included a few examples that
you can test your definitions with to make sure they are working
as expected. You'll fill in the rest of the definitions and
extend all the proofs accordingly.
To get you started, we've provided implementations for:
- numbers
- pairs and units
- sums
- lists
You need to complete the implementations for:
- let (which involves binding)
- [fix]
A good strategy is to work on the extensions one at a time, in
multiple passes, rather than trying to work through the file from
start to finish in a single pass. For each definition or proof,
begin by reading carefully through the parts that are provided for
you, referring to the text in the [Stlc] chapter for high-level
intuitions and the embedded comments for detailed mechanics.
*)
Module STLCExtended.
(* ###################################################################### *)
(** *** Syntax and Operational Semantics *)
Inductive ty : Type :=
| TArrow : ty -> ty -> ty
| TNat : ty
| TUnit : ty
| TProd : ty -> ty -> ty
| TSum : ty -> ty -> ty
| TList : ty -> ty.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TArrow" | Case_aux c "TNat"
| Case_aux c "TProd" | Case_aux c "TUnit"
| Case_aux c "TSum" | Case_aux c "TList" ].
Inductive tm : Type :=
(* pure STLC *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
(* numbers *)
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm
(* pairs *)
| tpair : tm -> tm -> tm
| tfst : tm -> tm
| tsnd : tm -> tm
(* units *)
| tunit : tm
(* let *)
| tlet : id -> tm -> tm -> tm
(* i.e., [let x = t1 in t2] *)
(* sums *)
| tinl : ty -> tm -> tm
| tinr : ty -> tm -> tm
| tcase : tm -> id -> tm -> id -> tm -> tm
(* i.e., [case t0 of inl x1 => t1 | inr x2 => t2] *)
(* lists *)
| tnil : ty -> tm
| tcons : tm -> tm -> tm
| tlcase : tm -> tm -> id -> id -> tm -> tm
(* i.e., [lcase t1 of | nil -> t2 | x::y -> t3] *)
(* fix *)
| tfix : tm -> tm.
(** Note that, for brevity, we've omitted booleans and instead
provided a single [if0] form combining a zero test and a
conditional. That is, instead of writing
<<
if x = 0 then ... else ...
>>
we'll write this:
<<
if0 x then ... else ...
>>
*)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"
| Case_aux c "tnat" | Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd"
| Case_aux c "tunit" | Case_aux c "tlet"
| Case_aux c "tinl" | Case_aux c "tinr" | Case_aux c "tcase"
| Case_aux c "tnil" | Case_aux c "tcons" | Case_aux c "tlcase"
| Case_aux c "tfix" ].
(* ###################################################################### *)
(** *** Substitution *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tnat n =>
tnat n
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tpair t1 t2 =>
tpair (subst x s t1) (subst x s t2)
| tfst t1 =>
tfst (subst x s t1)
| tsnd t1 =>
tsnd (subst x s t1)
| tunit => tunit
(* FILL IN HERE *)
| tinl T t1 =>
tinl T (subst x s t1)
| tinr T t1 =>
tinr T (subst x s t1)
| tcase t0 y1 t1 y2 t2 =>
tcase (subst x s t0)
y1 (if eq_id_dec x y1 then t1 else (subst x s t1))
y2 (if eq_id_dec x y2 then t2 else (subst x s t2))
| tnil T =>
tnil T
| tcons t1 t2 =>
tcons (subst x s t1) (subst x s t2)
| tlcase t1 t2 y1 y2 t3 =>
tlcase (subst x s t1) (subst x s t2) y1 y2
(if eq_id_dec x y1 then
t3
else if eq_id_dec x y2 then t3
else (subst x s t3))
(* FILL IN HERE *)
| _ => t (* ... and delete this line *)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** *** Reduction *)
(** Next we define the values of our language. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T11 t12,
value (tabs x T11 t12)
(* Numbers are values: *)
| v_nat : forall n1,
value (tnat n1)
(* A pair is a value if both components are: *)
| v_pair : forall v1 v2,
value v1 ->
value v2 ->
value (tpair v1 v2)
(* A unit is always a value *)
| v_unit : value tunit
(* A tagged value is a value: *)
| v_inl : forall v T,
value v ->
value (tinl T v)
| v_inr : forall v T,
value v ->
value (tinr T v)
(* A list is a value iff its head and tail are values: *)
| v_lnil : forall T, value (tnil T)
| v_lcons : forall v1 vl,
value v1 ->
value vl ->
value (tcons v1 vl)
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T11 t12 v2,
value v2 ->
(tapp (tabs x T11 t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
(* nats *)
| ST_Succ1 : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
| ST_SuccNat : forall n1,
(tsucc (tnat n1)) ==> (tnat (S n1))
| ST_Pred : forall t1 t1',
t1 ==> t1' ->
(tpred t1) ==> (tpred t1')
| ST_PredNat : forall n1,
(tpred (tnat n1)) ==> (tnat (pred n1))
| ST_Mult1 : forall t1 t1' t2,
t1 ==> t1' ->
(tmult t1 t2) ==> (tmult t1' t2)
| ST_Mult2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tmult v1 t2) ==> (tmult v1 t2')
| ST_MultNats : forall n1 n2,
(tmult (tnat n1) (tnat n2)) ==> (tnat (mult n1 n2))
| ST_If01 : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif0 t1 t2 t3) ==> (tif0 t1' t2 t3)
| ST_If0Zero : forall t2 t3,
(tif0 (tnat 0) t2 t3) ==> t2
| ST_If0Nonzero : forall n t2 t3,
(tif0 (tnat (S n)) t2 t3) ==> t3
(* pairs *)
| ST_Pair1 : forall t1 t1' t2,
t1 ==> t1' ->
(tpair t1 t2) ==> (tpair t1' t2)
| ST_Pair2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tpair v1 t2) ==> (tpair v1 t2')
| ST_Fst1 : forall t1 t1',
t1 ==> t1' ->
(tfst t1) ==> (tfst t1')
| ST_FstPair : forall v1 v2,
value v1 ->
value v2 ->
(tfst (tpair v1 v2)) ==> v1
| ST_Snd1 : forall t1 t1',
t1 ==> t1' ->
(tsnd t1) ==> (tsnd t1')
| ST_SndPair : forall v1 v2,
value v1 ->
value v2 ->
(tsnd (tpair v1 v2)) ==> v2
(* let *)
(* FILL IN HERE *)
(* sums *)
| ST_Inl : forall t1 t1' T,
t1 ==> t1' ->
(tinl T t1) ==> (tinl T t1')
| ST_Inr : forall t1 t1' T,
t1 ==> t1' ->
(tinr T t1) ==> (tinr T t1')
| ST_Case : forall t0 t0' x1 t1 x2 t2,
t0 ==> t0' ->
(tcase t0 x1 t1 x2 t2) ==> (tcase t0' x1 t1 x2 t2)
| ST_CaseInl : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinl T v0) x1 t1 x2 t2) ==> [x1:=v0]t1
| ST_CaseInr : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinr T v0) x1 t1 x2 t2) ==> [x2:=v0]t2
(* lists *)
| ST_Cons1 : forall t1 t1' t2,
t1 ==> t1' ->
(tcons t1 t2) ==> (tcons t1' t2)
| ST_Cons2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tcons v1 t2) ==> (tcons v1 t2')
| ST_Lcase1 : forall t1 t1' t2 x1 x2 t3,
t1 ==> t1' ->
(tlcase t1 t2 x1 x2 t3) ==> (tlcase t1' t2 x1 x2 t3)
| ST_LcaseNil : forall T t2 x1 x2 t3,
(tlcase (tnil T) t2 x1 x2 t3) ==> t2
| ST_LcaseCons : forall v1 vl t2 x1 x2 t3,
value v1 ->
value vl ->
(tlcase (tcons v1 vl) t2 x1 x2 t3) ==> (subst x2 vl (subst x1 v1 t3))
(* fix *)
(* FILL IN HERE *)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"
| Case_aux c "ST_Succ1" | Case_aux c "ST_SuccNat"
| Case_aux c "ST_Pred1" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_MultNats" | Case_aux c "ST_If01"
| Case_aux c "ST_If0Zero" | Case_aux c "ST_If0Nonzero"
| Case_aux c "ST_Pair1" | Case_aux c "ST_Pair2"
| Case_aux c "ST_Fst1" | Case_aux c "ST_FstPair"
| Case_aux c "ST_Snd1" | Case_aux c "ST_SndPair"
(* FILL IN HERE *)
| Case_aux c "ST_Inl" | Case_aux c "ST_Inr" | Case_aux c "ST_Case"
| Case_aux c "ST_CaseInl" | Case_aux c "ST_CaseInr"
| Case_aux c "ST_Cons1" | Case_aux c "ST_Cons2" | Case_aux c "ST_Lcase1"
| Case_aux c "ST_LcaseNil" | Case_aux c "ST_LcaseCons"
(* FILL IN HERE *)
].
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Hint Constructors step.
(* ###################################################################### *)
(** *** Typing *)
Definition context := partial_map ty.
(** Next we define the typing rules. These are nearly direct
transcriptions of the inference rules shown above. *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Typing rules for proper terms *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
(* nats *)
| T_Nat : forall Gamma n1,
Gamma |- (tnat n1) \in TNat
| T_Succ : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tsucc t1) \in TNat
| T_Pred : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tpred t1) \in TNat
| T_Mult : forall Gamma t1 t2,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in TNat ->
Gamma |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma t1 t2 t3 T1,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in T1 ->
Gamma |- t3 \in T1 ->
Gamma |- (tif0 t1 t2 t3) \in T1
(* pairs *)
| T_Pair : forall Gamma t1 t2 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in T2 ->
Gamma |- (tpair t1 t2) \in (TProd T1 T2)
| T_Fst : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tfst t) \in T1
| T_Snd : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tsnd t) \in T2
(* unit *)
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* let *)
(* FILL IN HERE *)
(* sums *)
| T_Inl : forall Gamma t1 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- (tinl T2 t1) \in (TSum T1 T2)
| T_Inr : forall Gamma t2 T1 T2,
Gamma |- t2 \in T2 ->
Gamma |- (tinr T1 t2) \in (TSum T1 T2)
| T_Case : forall Gamma t0 x1 T1 t1 x2 T2 t2 T,
Gamma |- t0 \in (TSum T1 T2) ->
(extend Gamma x1 T1) |- t1 \in T ->
(extend Gamma x2 T2) |- t2 \in T ->
Gamma |- (tcase t0 x1 t1 x2 t2) \in T
(* lists *)
| T_Nil : forall Gamma T,
Gamma |- (tnil T) \in (TList T)
| T_Cons : forall Gamma t1 t2 T1,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in (TList T1) ->
Gamma |- (tcons t1 t2) \in (TList T1)
| T_Lcase : forall Gamma t1 T1 t2 x1 x2 t3 T2,
Gamma |- t1 \in (TList T1) ->
Gamma |- t2 \in T2 ->
(extend (extend Gamma x2 (TList T1)) x1 T1) |- t3 \in T2 ->
Gamma |- (tlcase t1 t2 x1 x2 t3) \in T2
(* fix *)
(* FILL IN HERE *)
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd"
| Case_aux c "T_Unit"
(* let *)
(* FILL IN HERE *)
| Case_aux c "T_Inl" | Case_aux c "T_Inr" | Case_aux c "T_Case"
| Case_aux c "T_Nil" | Case_aux c "T_Cons" | Case_aux c "T_Lcase"
(* fix *)
(* FILL IN HERE *)
].
(* ###################################################################### *)
(** ** Examples *)
(** This section presents formalized versions of the examples from
above (plus several more). The ones at the beginning focus on
specific features; you can use these to make sure your definition
of a given feature is reasonable before moving on to extending the
proofs later in the file with the cases relating to this feature.
The later examples require all the features together, so you'll
need to come back to these when you've got all the definitions
filled in. *)
Module Examples.
(** *** Preliminaries *)
(** First, let's define a few variable names: *)
Notation a := (Id 0).
Notation f := (Id 1).
Notation g := (Id 2).
Notation l := (Id 3).
Notation k := (Id 6).
Notation i1 := (Id 7).
Notation i2 := (Id 8).
Notation x := (Id 9).
Notation y := (Id 10).
Notation processSum := (Id 11).
Notation n := (Id 12).
Notation eq := (Id 13).
Notation m := (Id 14).
Notation evenodd := (Id 15).
Notation even := (Id 16).
Notation odd := (Id 17).
Notation eo := (Id 18).
(** Next, a bit of Coq hackery to automate searching for typing
derivations. You don't need to understand this bit in detail --
just have a look over it so that you'll know what to look for if
you ever find yourself needing to make custom extensions to
[auto].
The following [Hint] declarations say that, whenever [auto]
arrives at a goal of the form [(Gamma |- (tapp e1 e1) \in T)], it
should consider [eapply T_App], leaving an existential variable
for the middle type T1, and similar for [lcase]. That variable
will then be filled in during the search for type derivations for
[e1] and [e2]. We also include a hint to "try harder" when
solving equality goals; this is useful to automate uses of
[T_Var] (which includes an equality as a precondition). *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
(* You'll want to uncomment the following line once
you've defined the [T_Lcase] constructor for the typing
relation: *)
(*
Hint Extern 2 (has_type _ (tlcase _ _ _ _ _) _) =>
eapply T_Lcase; auto.
*)
Hint Extern 2 (_ = _) => compute; reflexivity.
(** *** Numbers *)
Module Numtest.
(* if0 (pred (succ (pred (2 * 0))) then 5 else 6 *)
Definition test :=
tif0
(tpred
(tsucc
(tpred
(tmult
(tnat 2)
(tnat 0)))))
(tnat 5)
(tnat 6).
(** Remove the comment braces once you've implemented enough of the
definitions that you think this should work. *)
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof.
unfold test.
(* This typing derivation is quite deep, so we need to increase the
max search depth of [auto] from the default 5 to 10. *)
auto 10.
Qed.
Example numtest_reduces :
test ==>* tnat 5.
Proof.
unfold test. normalize.
Qed.
*)
End Numtest.
(** *** Products *)
Module Prodtest.
(* ((5,6),7).fst.snd *)
Definition test :=
tsnd
(tfst
(tpair
(tpair
(tnat 5)
(tnat 6))
(tnat 7))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End Prodtest.
(** *** [let] *)
Module LetTest.
(* let x = pred 6 in succ x *)
Definition test :=
tlet
x
(tpred (tnat 6))
(tsucc (tvar x)).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End LetTest.
(** *** Sums *)
Module Sumtest1.
(* case (inl Nat 5) of
inl x => x
| inr y => y *)
Definition test :=
tcase (tinl TNat (tnat 5))
x (tvar x)
y (tvar y).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tnat 5).
Proof. unfold test. normalize. Qed.
*)
End Sumtest1.
Module Sumtest2.
(* let processSum =
\x:Nat+Nat.
case x of
inl n => n
inr n => if0 n then 1 else 0 in
(processSum (inl Nat 5), processSum (inr Nat 5)) *)
Definition test :=
tlet
processSum
(tabs x (TSum TNat TNat)
(tcase (tvar x)
n (tvar n)
n (tif0 (tvar n) (tnat 1) (tnat 0))))
(tpair
(tapp (tvar processSum) (tinl TNat (tnat 5)))
(tapp (tvar processSum) (tinr TNat (tnat 5)))).
(*
Example typechecks :
(@empty ty) |- test \in (TProd TNat TNat).
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tpair (tnat 5) (tnat 0)).
Proof. unfold test. normalize. Qed.
*)
End Sumtest2.
(** *** Lists *)
Module ListTest.
(* let l = cons 5 (cons 6 (nil Nat)) in
lcase l of
nil => 0
| x::y => x*x *)
Definition test :=
tlet l
(tcons (tnat 5) (tcons (tnat 6) (tnil TNat)))
(tlcase (tvar l)
(tnat 0)
x y (tmult (tvar x) (tvar x))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 20. Qed.
Example reduces :
test ==>* (tnat 25).
Proof. unfold test. normalize. Qed.
*)
End ListTest.
(** *** [fix] *)
Module FixTest1.
(* fact := fix
(\f:nat->nat.
\a:nat.
if a=0 then 1 else a * (f (pred a))) *)
Definition fact :=
tfix
(tabs f (TArrow TNat TNat)
(tabs a TNat
(tif0
(tvar a)
(tnat 1)
(tmult
(tvar a)
(tapp (tvar f) (tpred (tvar a))))))).
(** (Warning: you may be able to typecheck [fact] but still have some
rules wrong!) *)
(*
Example fact_typechecks :
(@empty ty) |- fact \in (TArrow TNat TNat).
Proof. unfold fact. auto 10.
Qed.
*)
(*
Example fact_example:
(tapp fact (tnat 4)) ==>* (tnat 24).
Proof. unfold fact. normalize. Qed.
*)
End FixTest1.
Module FixTest2.
(* map :=
\g:nat->nat.
fix
(\f:[nat]->[nat].
\l:[nat].
case l of
| [] -> []
| x::l -> (g x)::(f l)) *)
Definition map :=
tabs g (TArrow TNat TNat)
(tfix
(tabs f (TArrow (TList TNat) (TList TNat))
(tabs l (TList TNat)
(tlcase (tvar l)
(tnil TNat)
a l (tcons (tapp (tvar g) (tvar a))
(tapp (tvar f) (tvar l))))))).
(*
(* Make sure you've uncommented the last [Hint Extern] above... *)
Example map_typechecks :
empty |- map \in
(TArrow (TArrow TNat TNat)
(TArrow (TList TNat)
(TList TNat))).
Proof. unfold map. auto 10. Qed.
Example map_example :
tapp (tapp map (tabs a TNat (tsucc (tvar a))))
(tcons (tnat 1) (tcons (tnat 2) (tnil TNat)))
==>* (tcons (tnat 2) (tcons (tnat 3) (tnil TNat))).
Proof. unfold map. normalize. Qed.
*)
End FixTest2.
Module FixTest3.
(* equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if0 m then (if0 n then 1 else 0)
else if0 n then 0
else eq (pred m) (pred n)) *)
Definition equal :=
tfix
(tabs eq (TArrow TNat (TArrow TNat TNat))
(tabs m TNat
(tabs n TNat
(tif0 (tvar m)
(tif0 (tvar n) (tnat 1) (tnat 0))
(tif0 (tvar n)
(tnat 0)
(tapp (tapp (tvar eq)
(tpred (tvar m)))
(tpred (tvar n)))))))).
(*
Example equal_typechecks :
(@empty ty) |- equal \in (TArrow TNat (TArrow TNat TNat)).
Proof. unfold equal. auto 10.
Qed.
*)
(*
Example equal_example1:
(tapp (tapp equal (tnat 4)) (tnat 4)) ==>* (tnat 1).
Proof. unfold equal. normalize. Qed.
*)
(*
Example equal_example2:
(tapp (tapp equal (tnat 4)) (tnat 5)) ==>* (tnat 0).
Proof. unfold equal. normalize. Qed.
*)
End FixTest3.
Module FixTest4.
(* let evenodd =
fix
(\eo: (Nat->Nat * Nat->Nat).
let e = \n:Nat. if0 n then 1 else eo.snd (pred n) in
let o = \n:Nat. if0 n then 0 else eo.fst (pred n) in
(e,o)) in
let even = evenodd.fst in
let odd = evenodd.snd in
(even 3, even 4)
*)
Definition eotest :=
tlet evenodd
(tfix
(tabs eo (TProd (TArrow TNat TNat) (TArrow TNat TNat))
(tpair
(tabs n TNat
(tif0 (tvar n)
(tnat 1)
(tapp (tsnd (tvar eo)) (tpred (tvar n)))))
(tabs n TNat
(tif0 (tvar n)
(tnat 0)
(tapp (tfst (tvar eo)) (tpred (tvar n))))))))
(tlet even (tfst (tvar evenodd))
(tlet odd (tsnd (tvar evenodd))
(tpair
(tapp (tvar even) (tnat 3))
(tapp (tvar even) (tnat 4))))).
(*
Example eotest_typechecks :
(@empty ty) |- eotest \in (TProd TNat TNat).
Proof. unfold eotest. eauto 30.
Qed.
*)
(*
Example eotest_example1:
eotest ==>* (tpair (tnat 0) (tnat 1)).
Proof. unfold eotest. normalize. Qed.
*)
End FixTest4.
End Examples.
(* ###################################################################### *)
(** ** Properties of Typing *)
(** The proofs of progress and preservation for this system are
essentially the same (though of course somewhat longer) as for the
pure simply typed lambda-calculus. *)
(* ###################################################################### *)
(** *** Progress *)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
(* Theorem: Suppose empty |- t : T. Then either
1. t is a value, or
2. t ==> t' for some t'.
Proof: By induction on the given typing derivation. *)
intros t T Ht.
remember (@empty ty) as Gamma.
generalize dependent HeqGamma.
has_type_cases (induction Ht) Case; intros HeqGamma; subst.
Case "T_Var".
(* The final rule in the given typing derivation cannot be [T_Var],
since it can never be the case that [empty |- x : T] (since the
context is empty). *)
inversion H.
Case "T_Abs".
(* If the [T_Abs] rule was the last used, then [t = tabs x T11 t12],
which is a value. *)
left...
Case "T_App".
(* If the last rule applied was T_App, then [t = t1 t2], and we know
from the form of the rule that
[empty |- t1 : T1 -> T2]
[empty |- t2 : T1]
By the induction hypothesis, each of t1 and t2 either is a value
or can take a step. *)
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
(* If both [t1] and [t2] are values, then we know that
[t1 = tabs x T11 t12], since abstractions are the only values
that can have an arrow type. But
[(tabs x T11 t12) t2 ==> [x:=t2]t12] by [ST_AppAbs]. *)
inversion H; subst; try (solve by inversion).
exists (subst x t2 t12)...
SSCase "t2 steps".
(* If [t1] is a value and [t2 ==> t2'], then [t1 t2 ==> t1 t2']
by [ST_App2]. *)
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
(* Finally, If [t1 ==> t1'], then [t1 t2 ==> t1' t2] by [ST_App1]. *)
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_Nat".
left...
Case "T_Succ".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (S n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsucc t1')...
Case "T_Pred".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (pred n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tpred t1')...
Case "T_Mult".
right.
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 is a value".
inversion H; subst; try solve by inversion.
inversion H0; subst; try solve by inversion.
exists (tnat (mult n1 n0))...
SSCase "t2 steps".
inversion H0 as [t2' Hstp].
exists (tmult t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tmult t1' t2)...
Case "T_If0".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
destruct n1 as [|n1'].
SSCase "n1=0".
exists t2...
SSCase "n1<>0".
exists t3...
SCase "t1 steps".
inversion H as [t1' H0].
exists (tif0 t1' t2 t3)...
Case "T_Pair".
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 steps".
right. inversion H0 as [t2' Hstp].
exists (tpair t1 t2')...
SCase "t1 steps".
right. inversion H as [t1' Hstp].
exists (tpair t1' t2)...
Case "T_Fst".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v1...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tfst t1')...
Case "T_Snd".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v2...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsnd t1')...
Case "T_Unit".
left...
(* let *)
(* FILL IN HERE *)
Case "T_Inl".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinl _ t1')... *)
Case "T_Inr".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinr _ t1')... *)
Case "T_Case".
right.
destruct IHHt1...
SCase "t0 is a value".
inversion H; subst; try solve by inversion.
SSCase "t0 is inl".
exists ([x1:=v]t1)...
SSCase "t0 is inr".
exists ([x2:=v]t2)...
SCase "t0 steps".
inversion H as [t0' Hstp].
exists (tcase t0' x1 t1 x2 t2)...
Case "T_Nil".
left...
Case "T_Cons".
destruct IHHt1...
SCase "head is a value".
destruct IHHt2...
SSCase "tail steps".
right. inversion H0 as [t2' Hstp].
exists (tcons t1 t2')...
SCase "head steps".
right. inversion H as [t1' Hstp].
exists (tcons t1' t2)...
Case "T_Lcase".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
SSCase "t1=tnil".
exists t2...
SSCase "t1=tcons v1 vl".
exists ([x2:=vl]([x1:=v1]t3))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tlcase t1' t2 x1 x2 t3)...
(* fix *)
(* FILL IN HERE *)
Qed.
(* ###################################################################### *)
(** *** Context Invariance *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
(* nats *)
| afi_succ : forall x t,
appears_free_in x t ->
appears_free_in x (tsucc t)
| afi_pred : forall x t,
appears_free_in x t ->
appears_free_in x (tpred t)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if01 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if02 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if03 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
(* pairs *)
| afi_pair1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tpair t1 t2)
| afi_pair2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tpair t1 t2)
| afi_fst : forall x t,
appears_free_in x t ->
appears_free_in x (tfst t)
| afi_snd : forall x t,
appears_free_in x t ->
appears_free_in x (tsnd t)
(* let *)
(* FILL IN HERE *)
(* sums *)
| afi_inl : forall x t T,
appears_free_in x t ->
appears_free_in x (tinl T t)
| afi_inr : forall x t T,
appears_free_in x t ->
appears_free_in x (tinr T t)
| afi_case0 : forall x t0 x1 t1 x2 t2,
appears_free_in x t0 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case1 : forall x t0 x1 t1 x2 t2,
x1 <> x ->
appears_free_in x t1 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case2 : forall x t0 x1 t1 x2 t2,
x2 <> x ->
appears_free_in x t2 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
(* lists *)
| afi_cons1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tcons t1 t2)
| afi_cons2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tcons t1 t2)
| afi_lcase1 : forall x t1 t2 y1 y2 t3,
appears_free_in x t1 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase2 : forall x t1 t2 y1 y2 t3,
appears_free_in x t2 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase3 : forall x t1 t2 y1 y2 t3,
y1 <> x ->
y2 <> x ->
appears_free_in x t3 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
(* fix *)
(* FILL IN HERE *)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros y Hafi.
unfold extend.
destruct (eq_id_dec x y)...
Case "T_Mult".
apply T_Mult...
Case "T_If0".
apply T_If0...
Case "T_Pair".
apply T_Pair...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
eapply T_Case...
apply IHhas_type2. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x2 y)...
Case "T_Cons".
apply T_Cons...
Case "T_Lcase".
eapply T_Lcase... apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
destruct (eq_id_dec x2 y)...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case; inversion Hafi; subst...
Case "T_Abs".
destruct IHHtyp as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "left".
destruct IHHtyp2 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
SCase "right".
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
Case "T_Lcase".
clear Htyp1 IHHtyp1 Htyp2 IHHtyp2.
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx... rewrite neq_id in Hctx...
Qed.
(* ###################################################################### *)
(** *** Substitution *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
(* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then
Gamma |- [x:=v]t : S. *)
intros Gamma x U v t S Htypt Htypv.
generalize dependent Gamma. generalize dependent S.
(* Proof: By induction on the term t. Most cases follow directly
from the IH, with the exception of tvar and tabs.
The former aren't automatic because we must reason about how the
variables interact. *)
t_cases (induction t) Case;
intros S Gamma Htypt; simpl; inversion Htypt; subst...
Case "tvar".
simpl. rename i into y.
(* If t = y, we know that
[empty |- v : U] and
[Gamma,x:U |- y : S]
and, by inversion, [extend Gamma x U y = Some S]. We want to
show that [Gamma |- [x:=v]y : S].
There are two cases to consider: either [x=y] or [x<>y]. *)
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then we know that [U = S], and that [[x:=v]y = v].
So what we really must show is that if [empty |- v : U] then
[Gamma |- v : U]. We have already proven a more general version
of this theorem, called context invariance. *)
subst.
unfold extend in H1. rewrite eq_id in H1.
inversion H1; subst. clear H1.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
(* If [x <> y], then [Gamma y = Some S] and the substitution has no
effect. We can show that [Gamma |- y : S] by [T_Var]. *)
apply T_Var... unfold extend in H1. rewrite neq_id in H1...
Case "tabs".
rename i into y. rename t into T11.
(* If [t = tabs y T11 t0], then we know that
[Gamma,x:U |- tabs y T11 t0 : T11->T12]
[Gamma,x:U,y:T11 |- t0 : T12]
[empty |- v : U]
As our IH, we know that forall S Gamma,
[Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 : S].
We can calculate that
[x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0)
And we must show that [Gamma |- [x:=v]t : T11->T12]. We know
we will do so using [T_Abs], so it remains to be shown that:
[Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12]
We consider two cases: [x = y] and [x <> y].
*)
apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then the substitution has no effect. Context
invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are
equivalent. Since the former context shows that [t0 : T12], so
does the latter. *)
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
(* If [x <> y], then the IH and context invariance allow us to show that
[Gamma,x:U,y:T11 |- t0 : T12] =>
[Gamma,y:T11,x:U |- t0 : T12] =>
[Gamma,y:T11 |- [x:=v]t0 : T12] *)
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
(* let *)
(* FILL IN HERE *)
Case "tcase".
rename i into x1. rename i0 into x2.
eapply T_Case...
SCase "left arm".
destruct (eq_id_dec x x1).
SSCase "x = x1".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
SSCase "x <> x1".
apply IHt2. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
subst. rewrite neq_id...
SCase "right arm".
destruct (eq_id_dec x x2).
SSCase "x = x2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
SSCase "x <> x2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
subst. rewrite neq_id...
Case "tlcase".
rename i into y1. rename i0 into y2.
eapply T_Lcase...
destruct (eq_id_dec x y1).
SCase "x=y1".
simpl.
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
SCase "x<>y1".
destruct (eq_id_dec x y2).
SSCase "x=y2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y2 z)...
SSCase "x<>y2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
subst. rewrite neq_id...
destruct (eq_id_dec y2 z)...
subst. rewrite neq_id...
Qed.
(* ###################################################################### *)
(** *** Preservation *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
(* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *)
remember (@empty ty) as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
(* Proof: By induction on the given typing derivation. Many cases are
contradictory ([T_Var], [T_Abs]). We show just the interesting ones. *)
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
(* If the last rule used was [T_App], then [t = t1 t2], and three rules
could have been used to show [t ==> t']: [ST_App1], [ST_App2], and
[ST_AppAbs]. In the first two cases, the result follows directly from
the IH. *)
inversion HE; subst...
SCase "ST_AppAbs".
(* For the third case, suppose
[t1 = tabs x T11 t12]
and
[t2 = v2].
We must show that [empty |- [x:=v2]t12 : T2].
We know by assumption that
[empty |- tabs x T11 t12 : T1->T2]
and by inversion
[x:T1 |- t12 : T2]
We have already proven that substitution_preserves_typing and
[empty |- v2 : T1]
by assumption, so we are done. *)
apply substitution_preserves_typing with T1...
inversion HT1...
Case "T_Fst".
inversion HT...
Case "T_Snd".
inversion HT...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "ST_CaseInl".
inversion HT1; subst.
eapply substitution_preserves_typing...
SCase "ST_CaseInr".
inversion HT1; subst.
eapply substitution_preserves_typing...
Case "T_Lcase".
SCase "ST_LcaseCons".
inversion HT1; subst.
apply substitution_preserves_typing with (TList T1)...
apply substitution_preserves_typing with T1...
(* fix *)
(* FILL IN HERE *)
Qed.
(** [] *)
End STLCExtended.
(* $Date: 2014-12-01 15:15:02 -0500 (Mon, 01 Dec 2014) $ *)
|
(** * MoreStlc: More on the Simply Typed Lambda-Calculus *)
Require Export Stlc.
(* ###################################################################### *)
(** * Simple Extensions to STLC *)
(** The simply typed lambda-calculus has enough structure to make its
theoretical properties interesting, but it is not much of a
programming language. In this chapter, we begin to close the gap
with real-world languages by introducing a number of familiar
features that have straightforward treatments at the level of
typing. *)
(** ** Numbers *)
(** Adding types, constants, and primitive operations for numbers is
easy -- just a matter of combining the [Types] and [Stlc]
chapters. *)
(** ** [let]-bindings *)
(** When writing a complex expression, it is often useful to give
names to some of its subexpressions: this avoids repetition and
often increases readability. Most languages provide one or more
ways of doing this. In OCaml (and Coq), for example, we can write
[let x=t1 in t2] to mean ``evaluate the expression [t1] and bind
the name [x] to the resulting value while evaluating [t2].''
Our [let]-binder follows OCaml's in choosing a call-by-value
evaluation order, where the [let]-bound term must be fully
evaluated before evaluation of the [let]-body can begin. The
typing rule [T_Let] tells us that the type of a [let] can be
calculated by calculating the type of the [let]-bound term,
extending the context with a binding with this type, and in this
enriched context calculating the type of the body, which is then
the type of the whole [let] expression.
At this point in the course, it's probably easier simply to look
at the rules defining this new feature as to wade through a lot of
english text conveying the same information. Here they are: *)
(** Syntax:
<<
t ::= Terms
| ... (other terms same as before)
| let x=t in t let-binding
>>
*)
(**
Reduction:
t1 ==> t1'
---------------------------------- (ST_Let1)
let x=t1 in t2 ==> let x=t1' in t2
---------------------------- (ST_LetValue)
let x=v1 in t2 ==> [x:=v1]t2
Typing:
Gamma |- t1 : T1 Gamma , x:T1 |- t2 : T2
-------------------------------------------- (T_Let)
Gamma |- let x=t1 in t2 : T2
*)
(** ** Pairs *)
(** Our functional programming examples in Coq have made
frequent use of _pairs_ of values. The type of such pairs is
called a _product type_.
The formalization of pairs is almost too simple to be worth
discussing. However, let's look briefly at the various parts of
the definition to emphasize the common pattern. *)
(** In Coq, the primitive way of extracting the components of a pair
is _pattern matching_. An alternative style is to take [fst] and
[snd] -- the first- and second-projection operators -- as
primitives. Just for fun, let's do our products this way. For
example, here's how we'd write a function that takes a pair of
numbers and returns the pair of their sum and difference:
<<
\x:Nat*Nat.
let sum = x.fst + x.snd in
let diff = x.fst - x.snd in
(sum,diff)
>>
*)
(** Adding pairs to the simply typed lambda-calculus, then, involves
adding two new forms of term -- pairing, written [(t1,t2)], and
projection, written [t.fst] for the first projection from [t] and
[t.snd] for the second projection -- plus one new type constructor,
[T1*T2], called the _product_ of [T1] and [T2]. *)
(** Syntax:
<<
t ::= Terms
| ...
| (t,t) pair
| t.fst first projection
| t.snd second projection
v ::= Values
| ...
| (v,v) pair value
T ::= Types
| ...
| T * T product type
>>
*)
(** For evaluation, we need several new rules specifying how pairs and
projection behave.
t1 ==> t1'
-------------------- (ST_Pair1)
(t1,t2) ==> (t1',t2)
t2 ==> t2'
-------------------- (ST_Pair2)
(v1,t2) ==> (v1,t2')
t1 ==> t1'
------------------ (ST_Fst1)
t1.fst ==> t1'.fst
------------------ (ST_FstPair)
(v1,v2).fst ==> v1
t1 ==> t1'
------------------ (ST_Snd1)
t1.snd ==> t1'.snd
------------------ (ST_SndPair)
(v1,v2).snd ==> v2
*)
(**
Rules [ST_FstPair] and [ST_SndPair] specify that, when a fully
evaluated pair meets a first or second projection, the result is
the appropriate component. The congruence rules [ST_Fst1] and
[ST_Snd1] allow reduction to proceed under projections, when the
term being projected from has not yet been fully evaluated.
[ST_Pair1] and [ST_Pair2] evaluate the parts of pairs: first the
left part, and then -- when a value appears on the left -- the right
part. The ordering arising from the use of the metavariables [v]
and [t] in these rules enforces a left-to-right evaluation
strategy for pairs. (Note the implicit convention that
metavariables like [v] and [v1] can only denote values.) We've
also added a clause to the definition of values, above, specifying
that [(v1,v2)] is a value. The fact that the components of a pair
value must themselves be values ensures that a pair passed as an
argument to a function will be fully evaluated before the function
body starts executing. *)
(** The typing rules for pairs and projections are straightforward.
Gamma |- t1 : T1 Gamma |- t2 : T2
--------------------------------------- (T_Pair)
Gamma |- (t1,t2) : T1*T2
Gamma |- t1 : T11*T12
--------------------- (T_Fst)
Gamma |- t1.fst : T11
Gamma |- t1 : T11*T12
--------------------- (T_Snd)
Gamma |- t1.snd : T12
*)
(** The rule [T_Pair] says that [(t1,t2)] has type [T1*T2] if [t1] has
type [T1] and [t2] has type [T2]. Conversely, the rules [T_Fst]
and [T_Snd] tell us that, if [t1] has a product type
[T11*T12] (i.e., if it will evaluate to a pair), then the types of
the projections from this pair are [T11] and [T12]. *)
(** ** Unit *)
(** Another handy base type, found especially in languages in
the ML family, is the singleton type [Unit]. *)
(** It has a single element -- the term constant [unit] (with a small
[u]) -- and a typing rule making [unit] an element of [Unit]. We
also add [unit] to the set of possible result values of
computations -- indeed, [unit] is the _only_ possible result of
evaluating an expression of type [Unit]. *)
(** Syntax:
<<
t ::= Terms
| ...
| unit unit value
v ::= Values
| ...
| unit unit
T ::= Types
| ...
| Unit Unit type
>>
Typing:
-------------------- (T_Unit)
Gamma |- unit : Unit
*)
(** It may seem a little strange to bother defining a type that
has just one element -- after all, wouldn't every computation
living in such a type be trivial?
This is a fair question, and indeed in the STLC the [Unit] type is
not especially critical (though we'll see two uses for it below).
Where [Unit] really comes in handy is in richer languages with
various sorts of _side effects_ -- e.g., assignment statements
that mutate variables or pointers, exceptions and other sorts of
nonlocal control structures, etc. In such languages, it is
convenient to have a type for the (trivial) result of an
expression that is evaluated only for its effect. *)
(** ** Sums *)
(** Many programs need to deal with values that can take two distinct
forms. For example, we might identify employees in an accounting
application using using _either_ their name _or_ their id number.
A search function might return _either_ a matching value _or_ an
error code.
These are specific examples of a binary _sum type_,
which describes a set of values drawn from exactly two given types, e.g.
<<
Nat + Bool
>>
*)
(** We create elements of these types by _tagging_ elements of
the component types. For example, if [n] is a [Nat] then [inl v]
is an element of [Nat+Bool]; similarly, if [b] is a [Bool] then
[inr b] is a [Nat+Bool]. The names of the tags [inl] and [inr]
arise from thinking of them as functions
<<
inl : Nat -> Nat + Bool
inr : Bool -> Nat + Bool
>>
that "inject" elements of [Nat] or [Bool] into the left and right
components of the sum type [Nat+Bool]. (But note that we don't
actually treat them as functions in the way we formalize them:
[inl] and [inr] are keywords, and [inl t] and [inr t] are primitive
syntactic forms, not function applications. This allows us to give
them their own special typing rules.) *)
(** In general, the elements of a type [T1 + T2] consist of the
elements of [T1] tagged with the token [inl], plus the elements of
[T2] tagged with [inr]. *)
(** One important usage of sums is signaling errors:
<<
div : Nat -> Nat -> (Nat + Unit) =
div =
\x:Nat. \y:Nat.
if iszero y then
inr unit
else
inl ...
>>
The type [Nat + Unit] above is in fact isomorphic to [option nat]
in Coq, and we've already seen how to signal errors with options. *)
(** To _use_ elements of sum types, we introduce a [case]
construct (a very simplified form of Coq's [match]) to destruct
them. For example, the following procedure converts a [Nat+Bool]
into a [Nat]: *)
(**
<<
getNat =
\x:Nat+Bool.
case x of
inl n => n
| inr b => if b then 1 else 0
>>
*)
(** More formally... *)
(** Syntax:
<<
t ::= Terms
| ...
| inl T t tagging (left)
| inr T t tagging (right)
| case t of case
inl x => t
| inr x => t
v ::= Values
| ...
| inl T v tagged value (left)
| inr T v tagged value (right)
T ::= Types
| ...
| T + T sum type
>>
*)
(** Evaluation:
t1 ==> t1'
---------------------- (ST_Inl)
inl T t1 ==> inl T t1'
t1 ==> t1'
---------------------- (ST_Inr)
inr T t1 ==> inr T t1'
t0 ==> t0'
------------------------------------------- (ST_Case)
case t0 of inl x1 => t1 | inr x2 => t2 ==>
case t0' of inl x1 => t1 | inr x2 => t2
---------------------------------------------- (ST_CaseInl)
case (inl T v0) of inl x1 => t1 | inr x2 => t2
==> [x1:=v0]t1
---------------------------------------------- (ST_CaseInr)
case (inr T v0) of inl x1 => t1 | inr x2 => t2
==> [x2:=v0]t2
*)
(** Typing:
Gamma |- t1 : T1
---------------------------- (T_Inl)
Gamma |- inl T2 t1 : T1 + T2
Gamma |- t1 : T2
---------------------------- (T_Inr)
Gamma |- inr T1 t1 : T1 + T2
Gamma |- t0 : T1+T2
Gamma , x1:T1 |- t1 : T
Gamma , x2:T2 |- t2 : T
--------------------------------------------------- (T_Case)
Gamma |- case t0 of inl x1 => t1 | inr x2 => t2 : T
We use the type annotation in [inl] and [inr] to make the typing
simpler, similarly to what we did for functions. *)
(** Without this extra
information, the typing rule [T_Inl], for example, would have to
say that, once we have shown that [t1] is an element of type [T1],
we can derive that [inl t1] is an element of [T1 + T2] for _any_
type T2. For example, we could derive both [inl 5 : Nat + Nat]
and [inl 5 : Nat + Bool] (and infinitely many other types).
This failure of uniqueness of types would mean that we cannot
build a typechecking algorithm simply by "reading the rules from
bottom to top" as we could for all the other features seen so far.
There are various ways to deal with this difficulty. One simple
one -- which we've adopted here -- forces the programmer to
explicitly annotate the "other side" of a sum type when performing
an injection. This is rather heavyweight for programmers (and so
real languages adopt other solutions), but it is easy to
understand and formalize. *)
(** ** Lists *)
(** The typing features we have seen can be classified into _base
types_ like [Bool], and _type constructors_ like [->] and [*] that
build new types from old ones. Another useful type constructor is
[List]. For every type [T], the type [List T] describes
finite-length lists whose elements are drawn from [T].
In principle, we could encode lists using pairs, sums and
_recursive_ types. But giving semantics to recursive types is
non-trivial. Instead, we'll just discuss the special case of lists
directly.
Below we give the syntax, semantics, and typing rules for lists.
Except for the fact that explicit type annotations are mandatory
on [nil] and cannot appear on [cons], these lists are essentially
identical to those we built in Coq. We use [lcase] to destruct
lists, to avoid dealing with questions like "what is the [head] of
the empty list?" *)
(** For example, here is a function that calculates the sum of
the first two elements of a list of numbers:
<<
\x:List Nat.
lcase x of nil -> 0
| a::x' -> lcase x' of nil -> a
| b::x'' -> a+b
>>
*)
(**
Syntax:
<<
t ::= Terms
| ...
| nil T
| cons t t
| lcase t of nil -> t | x::x -> t
v ::= Values
| ...
| nil T nil value
| cons v v cons value
T ::= Types
| ...
| List T list of Ts
>>
*)
(** Reduction:
t1 ==> t1'
-------------------------- (ST_Cons1)
cons t1 t2 ==> cons t1' t2
t2 ==> t2'
-------------------------- (ST_Cons2)
cons v1 t2 ==> cons v1 t2'
t1 ==> t1'
---------------------------------------- (ST_Lcase1)
(lcase t1 of nil -> t2 | xh::xt -> t3) ==>
(lcase t1' of nil -> t2 | xh::xt -> t3)
----------------------------------------- (ST_LcaseNil)
(lcase nil T of nil -> t2 | xh::xt -> t3)
==> t2
----------------------------------------------- (ST_LcaseCons)
(lcase (cons vh vt) of nil -> t2 | xh::xt -> t3)
==> [xh:=vh,xt:=vt]t3
*)
(** Typing:
----------------------- (T_Nil)
Gamma |- nil T : List T
Gamma |- t1 : T Gamma |- t2 : List T
----------------------------------------- (T_Cons)
Gamma |- cons t1 t2: List T
Gamma |- t1 : List T1
Gamma |- t2 : T
Gamma , h:T1, t:List T1 |- t3 : T
------------------------------------------------- (T_Lcase)
Gamma |- (lcase t1 of nil -> t2 | h::t -> t3) : T
*)
(** ** General Recursion *)
(** Another facility found in most programming languages (including
Coq) is the ability to define recursive functions. For example,
we might like to be able to define the factorial function like
this:
<<
fact = \x:Nat.
if x=0 then 1 else x * (fact (pred x)))
>>
But this would require quite a bit of work to formalize: we'd have
to introduce a notion of "function definitions" and carry around an
"environment" of such definitions in the definition of the [step]
relation. *)
(** Here is another way that is straightforward to formalize: instead
of writing recursive definitions where the right-hand side can
contain the identifier being defined, we can define a _fixed-point
operator_ that performs the "unfolding" of the recursive definition
in the right-hand side lazily during reduction.
<<
fact =
fix
(\f:Nat->Nat.
\x:Nat.
if x=0 then 1 else x * (f (pred x)))
>>
*)
(** The intuition is that the higher-order function [f] passed
to [fix] is a _generator_ for the [fact] function: if [fact] is
applied to a function that approximates the desired behavior of
[fact] up to some number [n] (that is, a function that returns
correct results on inputs less than or equal to [n]), then it
returns a better approximation to [fact] -- a function that returns
correct results for inputs up to [n+1]. Applying [fix] to this
generator returns its _fixed point_ -- a function that gives the
desired behavior for all inputs [n].
(The term "fixed point" has exactly the same sense as in ordinary
mathematics, where a fixed point of a function [f] is an input [x]
such that [f(x) = x]. Here, a fixed point of a function [F] of
type (say) [(Nat->Nat)->(Nat->Nat)] is a function [f] such that [F
f] is behaviorally equivalent to [f].) *)
(** Syntax:
<<
t ::= Terms
| ...
| fix t fixed-point operator
>>
Reduction:
t1 ==> t1'
------------------ (ST_Fix1)
fix t1 ==> fix t1'
F = \xf:T1.t2
----------------------- (ST_FixAbs)
fix F ==> [xf:=fix F]t2
Typing:
Gamma |- t1 : T1->T1
-------------------- (T_Fix)
Gamma |- fix t1 : T1
*)
(** Let's see how [ST_FixAbs] works by reducing [fact 3 = fix F 3],
where [F = (\f. \x. if x=0 then 1 else x * (f (pred x)))] (we are
omitting type annotations for brevity here).
<<
fix F 3
>>
[==>] [ST_FixAbs]
<<
(\x. if x=0 then 1 else x * (fix F (pred x))) 3
>>
[==>] [ST_AppAbs]
<<
if 3=0 then 1 else 3 * (fix F (pred 3))
>>
[==>] [ST_If0_Nonzero]
<<
3 * (fix F (pred 3))
>>
[==>] [ST_FixAbs + ST_Mult2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 3))
>>
[==>] [ST_PredNat + ST_Mult2 + ST_App2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 2)
>>
[==>] [ST_AppAbs + ST_Mult2]
<<
3 * (if 2=0 then 1 else 2 * (fix F (pred 2)))
>>
[==>] [ST_If0_Nonzero + ST_Mult2]
<<
3 * (2 * (fix F (pred 2)))
>>
[==>] [ST_FixAbs + 2 x ST_Mult2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 2)))
>>
[==>] [ST_PredNat + 2 x ST_Mult2 + ST_App2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 1))
>>
[==>] [ST_AppAbs + 2 x ST_Mult2]
<<
3 * (2 * (if 1=0 then 1 else 1 * (fix F (pred 1))))
>>
[==>] [ST_If0_Nonzero + 2 x ST_Mult2]
<<
3 * (2 * (1 * (fix F (pred 1))))
>>
[==>] [ST_FixAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 1))))
>>
[==>] [ST_PredNat + 3 x ST_Mult2 + ST_App2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 0)))
>>
[==>] [ST_AppAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * (if 0=0 then 1 else 0 * (fix F (pred 0)))))
>>
[==>] [ST_If0Zero + 3 x ST_Mult2]
<<
3 * (2 * (1 * 1))
>>
[==>] [ST_MultNats + 2 x ST_Mult2]
<<
3 * (2 * 1)
>>
[==>] [ST_MultNats + ST_Mult2]
<<
3 * 2
>>
[==>] [ST_MultNats]
<<
6
>>
*)
(** **** Exercise: 1 star, optional (halve_fix) *)
(** Translate this informal recursive definition into one using [fix]:
<<
halve =
\x:Nat.
if x=0 then 0
else if (pred x)=0 then 0
else 1 + (halve (pred (pred x))))
>>
(* FILL IN HERE *)
[]
*)
(** **** Exercise: 1 star, optional (fact_steps) *)
(** Write down the sequence of steps that the term [fact 1] goes
through to reduce to a normal form (assuming the usual reduction
rules for arithmetic operations).
(* FILL IN HERE *)
[]
*)
(** The ability to form the fixed point of a function of type [T->T]
for any [T] has some surprising consequences. In particular, it
implies that _every_ type is inhabited by some term. To see this,
observe that, for every type [T], we can define the term
fix (\x:T.x)
By [T_Fix] and [T_Abs], this term has type [T]. By [ST_FixAbs]
it reduces to itself, over and over again. Thus it is an
_undefined element_ of [T].
More usefully, here's an example using [fix] to define a
two-argument recursive function:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
And finally, here is an example where [fix] is used to define a
_pair_ of recursive functions (illustrating the fact that the type
[T1] in the rule [T_Fix] need not be a function type):
<<
evenodd =
fix
(\eo: (Nat->Bool * Nat->Bool).
let e = \n:Nat. if n=0 then true else eo.snd (pred n) in
let o = \n:Nat. if n=0 then false else eo.fst (pred n) in
(e,o))
even = evenodd.fst
odd = evenodd.snd
>>
*)
(* ###################################################################### *)
(** ** Records *)
(** As a final example of a basic extension of the STLC, let's
look briefly at how to define _records_ and their types.
Intuitively, records can be obtained from pairs by two kinds of
generalization: they are n-ary products (rather than just binary)
and their fields are accessed by _label_ (rather than position).
Conceptually, this extension is a straightforward generalization
of pairs and product types, but notationally it becomes a little
heavier; for this reason, we postpone its formal treatment to a
separate chapter ([Records]). *)
(** Records are not included in the extended exercise below, but
they will be useful to motivate the [Sub] chapter. *)
(** Syntax:
<<
t ::= Terms
| ...
| {i1=t1, ..., in=tn} record
| t.i projection
v ::= Values
| ...
| {i1=v1, ..., in=vn} record value
T ::= Types
| ...
| {i1:T1, ..., in:Tn} record type
>>
Intuitively, the generalization is pretty obvious. But it's worth
noticing that what we've actually written is rather informal: in
particular, we've written "[...]" in several places to mean "any
number of these," and we've omitted explicit mention of the usual
side-condition that the labels of a record should not contain
repetitions. *)
(** It is possible to devise informal notations that are
more precise, but these tend to be quite heavy and to obscure the
main points of the definitions. So we'll leave these a bit loose
here (they are informal anyway, after all) and do the work of
tightening things up elsewhere (in chapter [Records]). *)
(**
Reduction:
ti ==> ti'
------------------------------------ (ST_Rcd)
{i1=v1, ..., im=vm, in=ti, ...}
==> {i1=v1, ..., im=vm, in=ti', ...}
t1 ==> t1'
-------------- (ST_Proj1)
t1.i ==> t1'.i
------------------------- (ST_ProjRcd)
{..., i=vi, ...}.i ==> vi
Again, these rules are a bit informal. For example, the first rule
is intended to be read "if [ti] is the leftmost field that is not a
value and if [ti] steps to [ti'], then the whole record steps..."
In the last rule, the intention is that there should only be one
field called i, and that all the other fields must contain values. *)
(**
Typing:
Gamma |- t1 : T1 ... Gamma |- tn : Tn
-------------------------------------------------- (T_Rcd)
Gamma |- {i1=t1, ..., in=tn} : {i1:T1, ..., in:Tn}
Gamma |- t : {..., i:Ti, ...}
----------------------------- (T_Proj)
Gamma |- t.i : Ti
*)
(* ###################################################################### *)
(** *** Encoding Records (Optional) *)
(** There are several ways to make the above definitions precise.
- We can directly formalize the syntactic forms and inference
rules, staying as close as possible to the form we've given
them above. This is conceptually straightforward, and it's
probably what we'd want to do if we were building a real
compiler -- in particular, it will allow is to print error
messages in the form that programmers will find easy to
understand. But the formal versions of the rules will not be
pretty at all!
- We could look for a smoother way of presenting records -- for
example, a binary presentation with one constructor for the
empty record and another constructor for adding a single field
to an existing record, instead of a single monolithic
constructor that builds a whole record at once. This is the
right way to go if we are primarily interested in studying the
metatheory of the calculi with records, since it leads to
clean and elegant definitions and proofs. Chapter [Records]
shows how this can be done.
- Alternatively, if we like, we can avoid formalizing records
altogether, by stipulating that record notations are just
informal shorthands for more complex expressions involving
pairs and product types. We sketch this approach here.
First, observe that we can encode arbitrary-size tuples using
nested pairs and the [unit] value. To avoid overloading the pair
notation [(t1,t2)], we'll use curly braces without labels to write
down tuples, so [{}] is the empty tuple, [{5}] is a singleton
tuple, [{5,6}] is a 2-tuple (morally the same as a pair),
[{5,6,7}] is a triple, etc.
<<
{} ----> unit
{t1, t2, ..., tn} ----> (t1, trest)
where {t2, ..., tn} ----> trest
>>
Similarly, we can encode tuple types using nested product types:
<<
{} ----> Unit
{T1, T2, ..., Tn} ----> T1 * TRest
where {T2, ..., Tn} ----> TRest
>>
The operation of projecting a field from a tuple can be encoded
using a sequence of second projections followed by a first projection:
<<
t.0 ----> t.fst
t.(n+1) ----> (t.snd).n
>>
Next, suppose that there is some total ordering on record labels,
so that we can associate each label with a unique natural number.
This number is called the _position_ of the label. For example,
we might assign positions like this:
<<
LABEL POSITION
a 0
b 1
c 2
... ...
foo 1004
... ...
bar 10562
... ...
>>
We use these positions to encode record values as tuples (i.e., as
nested pairs) by sorting the fields according to their positions.
For example:
<<
{a=5, b=6} ----> {5,6}
{a=5, c=7} ----> {5,unit,7}
{c=7, a=5} ----> {5,unit,7}
{c=5, b=3} ----> {unit,3,5}
{f=8,c=5,a=7} ----> {7,unit,5,unit,unit,8}
{f=8,c=5} ----> {unit,unit,5,unit,unit,8}
>>
Note that each field appears in the position associated with its
label, that the size of the tuple is determined by the label with
the highest position, and that we fill in unused positions with
[unit].
We do exactly the same thing with record types:
<<
{a:Nat, b:Nat} ----> {Nat,Nat}
{c:Nat, a:Nat} ----> {Nat,Unit,Nat}
{f:Nat,c:Nat} ----> {Unit,Unit,Nat,Unit,Unit,Nat}
>>
Finally, record projection is encoded as a tuple projection from
the appropriate position:
<<
t.l ----> t.(position of l)
>>
It is not hard to check that all the typing rules for the original
"direct" presentation of records are validated by this
encoding. (The reduction rules are "almost validated" -- not
quite, because the encoding reorders fields.) *)
(** Of course, this encoding will not be very efficient if we
happen to use a record with label [bar]! But things are not
actually as bad as they might seem: for example, if we assume that
our compiler can see the whole program at the same time, we can
_choose_ the numbering of labels so that we assign small positions
to the most frequently used labels. Indeed, there are industrial
compilers that essentially do this! *)
(** *** Variants (Optional Reading) *)
(** Just as products can be generalized to records, sums can be
generalized to n-ary labeled types called _variants_. Instead of
[T1+T2], we can write something like [<l1:T1,l2:T2,...ln:Tn>]
where [l1],[l2],... are field labels which are used both to build
instances and as case arm labels.
These n-ary variants give us almost enough mechanism to build
arbitrary inductive data types like lists and trees from
scratch -- the only thing missing is a way to allow _recursion_ in
type definitions. We won't cover this here, but detailed
treatments can be found in many textbooks -- e.g., Types and
Programming Languages. *)
(* ###################################################################### *)
(** * Exercise: Formalizing the Extensions *)
(** **** Exercise: 4 stars, optional (STLC_extensions) *)
(** In this problem you will formalize a couple of the extensions
described above. We've provided the necessary additions to the
syntax of terms and types, and we've included a few examples that
you can test your definitions with to make sure they are working
as expected. You'll fill in the rest of the definitions and
extend all the proofs accordingly.
To get you started, we've provided implementations for:
- numbers
- pairs and units
- sums
- lists
You need to complete the implementations for:
- let (which involves binding)
- [fix]
A good strategy is to work on the extensions one at a time, in
multiple passes, rather than trying to work through the file from
start to finish in a single pass. For each definition or proof,
begin by reading carefully through the parts that are provided for
you, referring to the text in the [Stlc] chapter for high-level
intuitions and the embedded comments for detailed mechanics.
*)
Module STLCExtended.
(* ###################################################################### *)
(** *** Syntax and Operational Semantics *)
Inductive ty : Type :=
| TArrow : ty -> ty -> ty
| TNat : ty
| TUnit : ty
| TProd : ty -> ty -> ty
| TSum : ty -> ty -> ty
| TList : ty -> ty.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TArrow" | Case_aux c "TNat"
| Case_aux c "TProd" | Case_aux c "TUnit"
| Case_aux c "TSum" | Case_aux c "TList" ].
Inductive tm : Type :=
(* pure STLC *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
(* numbers *)
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm
(* pairs *)
| tpair : tm -> tm -> tm
| tfst : tm -> tm
| tsnd : tm -> tm
(* units *)
| tunit : tm
(* let *)
| tlet : id -> tm -> tm -> tm
(* i.e., [let x = t1 in t2] *)
(* sums *)
| tinl : ty -> tm -> tm
| tinr : ty -> tm -> tm
| tcase : tm -> id -> tm -> id -> tm -> tm
(* i.e., [case t0 of inl x1 => t1 | inr x2 => t2] *)
(* lists *)
| tnil : ty -> tm
| tcons : tm -> tm -> tm
| tlcase : tm -> tm -> id -> id -> tm -> tm
(* i.e., [lcase t1 of | nil -> t2 | x::y -> t3] *)
(* fix *)
| tfix : tm -> tm.
(** Note that, for brevity, we've omitted booleans and instead
provided a single [if0] form combining a zero test and a
conditional. That is, instead of writing
<<
if x = 0 then ... else ...
>>
we'll write this:
<<
if0 x then ... else ...
>>
*)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"
| Case_aux c "tnat" | Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd"
| Case_aux c "tunit" | Case_aux c "tlet"
| Case_aux c "tinl" | Case_aux c "tinr" | Case_aux c "tcase"
| Case_aux c "tnil" | Case_aux c "tcons" | Case_aux c "tlcase"
| Case_aux c "tfix" ].
(* ###################################################################### *)
(** *** Substitution *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tnat n =>
tnat n
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tpair t1 t2 =>
tpair (subst x s t1) (subst x s t2)
| tfst t1 =>
tfst (subst x s t1)
| tsnd t1 =>
tsnd (subst x s t1)
| tunit => tunit
(* FILL IN HERE *)
| tinl T t1 =>
tinl T (subst x s t1)
| tinr T t1 =>
tinr T (subst x s t1)
| tcase t0 y1 t1 y2 t2 =>
tcase (subst x s t0)
y1 (if eq_id_dec x y1 then t1 else (subst x s t1))
y2 (if eq_id_dec x y2 then t2 else (subst x s t2))
| tnil T =>
tnil T
| tcons t1 t2 =>
tcons (subst x s t1) (subst x s t2)
| tlcase t1 t2 y1 y2 t3 =>
tlcase (subst x s t1) (subst x s t2) y1 y2
(if eq_id_dec x y1 then
t3
else if eq_id_dec x y2 then t3
else (subst x s t3))
(* FILL IN HERE *)
| _ => t (* ... and delete this line *)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** *** Reduction *)
(** Next we define the values of our language. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T11 t12,
value (tabs x T11 t12)
(* Numbers are values: *)
| v_nat : forall n1,
value (tnat n1)
(* A pair is a value if both components are: *)
| v_pair : forall v1 v2,
value v1 ->
value v2 ->
value (tpair v1 v2)
(* A unit is always a value *)
| v_unit : value tunit
(* A tagged value is a value: *)
| v_inl : forall v T,
value v ->
value (tinl T v)
| v_inr : forall v T,
value v ->
value (tinr T v)
(* A list is a value iff its head and tail are values: *)
| v_lnil : forall T, value (tnil T)
| v_lcons : forall v1 vl,
value v1 ->
value vl ->
value (tcons v1 vl)
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T11 t12 v2,
value v2 ->
(tapp (tabs x T11 t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
(* nats *)
| ST_Succ1 : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
| ST_SuccNat : forall n1,
(tsucc (tnat n1)) ==> (tnat (S n1))
| ST_Pred : forall t1 t1',
t1 ==> t1' ->
(tpred t1) ==> (tpred t1')
| ST_PredNat : forall n1,
(tpred (tnat n1)) ==> (tnat (pred n1))
| ST_Mult1 : forall t1 t1' t2,
t1 ==> t1' ->
(tmult t1 t2) ==> (tmult t1' t2)
| ST_Mult2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tmult v1 t2) ==> (tmult v1 t2')
| ST_MultNats : forall n1 n2,
(tmult (tnat n1) (tnat n2)) ==> (tnat (mult n1 n2))
| ST_If01 : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif0 t1 t2 t3) ==> (tif0 t1' t2 t3)
| ST_If0Zero : forall t2 t3,
(tif0 (tnat 0) t2 t3) ==> t2
| ST_If0Nonzero : forall n t2 t3,
(tif0 (tnat (S n)) t2 t3) ==> t3
(* pairs *)
| ST_Pair1 : forall t1 t1' t2,
t1 ==> t1' ->
(tpair t1 t2) ==> (tpair t1' t2)
| ST_Pair2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tpair v1 t2) ==> (tpair v1 t2')
| ST_Fst1 : forall t1 t1',
t1 ==> t1' ->
(tfst t1) ==> (tfst t1')
| ST_FstPair : forall v1 v2,
value v1 ->
value v2 ->
(tfst (tpair v1 v2)) ==> v1
| ST_Snd1 : forall t1 t1',
t1 ==> t1' ->
(tsnd t1) ==> (tsnd t1')
| ST_SndPair : forall v1 v2,
value v1 ->
value v2 ->
(tsnd (tpair v1 v2)) ==> v2
(* let *)
(* FILL IN HERE *)
(* sums *)
| ST_Inl : forall t1 t1' T,
t1 ==> t1' ->
(tinl T t1) ==> (tinl T t1')
| ST_Inr : forall t1 t1' T,
t1 ==> t1' ->
(tinr T t1) ==> (tinr T t1')
| ST_Case : forall t0 t0' x1 t1 x2 t2,
t0 ==> t0' ->
(tcase t0 x1 t1 x2 t2) ==> (tcase t0' x1 t1 x2 t2)
| ST_CaseInl : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinl T v0) x1 t1 x2 t2) ==> [x1:=v0]t1
| ST_CaseInr : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinr T v0) x1 t1 x2 t2) ==> [x2:=v0]t2
(* lists *)
| ST_Cons1 : forall t1 t1' t2,
t1 ==> t1' ->
(tcons t1 t2) ==> (tcons t1' t2)
| ST_Cons2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tcons v1 t2) ==> (tcons v1 t2')
| ST_Lcase1 : forall t1 t1' t2 x1 x2 t3,
t1 ==> t1' ->
(tlcase t1 t2 x1 x2 t3) ==> (tlcase t1' t2 x1 x2 t3)
| ST_LcaseNil : forall T t2 x1 x2 t3,
(tlcase (tnil T) t2 x1 x2 t3) ==> t2
| ST_LcaseCons : forall v1 vl t2 x1 x2 t3,
value v1 ->
value vl ->
(tlcase (tcons v1 vl) t2 x1 x2 t3) ==> (subst x2 vl (subst x1 v1 t3))
(* fix *)
(* FILL IN HERE *)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"
| Case_aux c "ST_Succ1" | Case_aux c "ST_SuccNat"
| Case_aux c "ST_Pred1" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_MultNats" | Case_aux c "ST_If01"
| Case_aux c "ST_If0Zero" | Case_aux c "ST_If0Nonzero"
| Case_aux c "ST_Pair1" | Case_aux c "ST_Pair2"
| Case_aux c "ST_Fst1" | Case_aux c "ST_FstPair"
| Case_aux c "ST_Snd1" | Case_aux c "ST_SndPair"
(* FILL IN HERE *)
| Case_aux c "ST_Inl" | Case_aux c "ST_Inr" | Case_aux c "ST_Case"
| Case_aux c "ST_CaseInl" | Case_aux c "ST_CaseInr"
| Case_aux c "ST_Cons1" | Case_aux c "ST_Cons2" | Case_aux c "ST_Lcase1"
| Case_aux c "ST_LcaseNil" | Case_aux c "ST_LcaseCons"
(* FILL IN HERE *)
].
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Hint Constructors step.
(* ###################################################################### *)
(** *** Typing *)
Definition context := partial_map ty.
(** Next we define the typing rules. These are nearly direct
transcriptions of the inference rules shown above. *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Typing rules for proper terms *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
(* nats *)
| T_Nat : forall Gamma n1,
Gamma |- (tnat n1) \in TNat
| T_Succ : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tsucc t1) \in TNat
| T_Pred : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tpred t1) \in TNat
| T_Mult : forall Gamma t1 t2,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in TNat ->
Gamma |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma t1 t2 t3 T1,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in T1 ->
Gamma |- t3 \in T1 ->
Gamma |- (tif0 t1 t2 t3) \in T1
(* pairs *)
| T_Pair : forall Gamma t1 t2 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in T2 ->
Gamma |- (tpair t1 t2) \in (TProd T1 T2)
| T_Fst : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tfst t) \in T1
| T_Snd : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tsnd t) \in T2
(* unit *)
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* let *)
(* FILL IN HERE *)
(* sums *)
| T_Inl : forall Gamma t1 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- (tinl T2 t1) \in (TSum T1 T2)
| T_Inr : forall Gamma t2 T1 T2,
Gamma |- t2 \in T2 ->
Gamma |- (tinr T1 t2) \in (TSum T1 T2)
| T_Case : forall Gamma t0 x1 T1 t1 x2 T2 t2 T,
Gamma |- t0 \in (TSum T1 T2) ->
(extend Gamma x1 T1) |- t1 \in T ->
(extend Gamma x2 T2) |- t2 \in T ->
Gamma |- (tcase t0 x1 t1 x2 t2) \in T
(* lists *)
| T_Nil : forall Gamma T,
Gamma |- (tnil T) \in (TList T)
| T_Cons : forall Gamma t1 t2 T1,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in (TList T1) ->
Gamma |- (tcons t1 t2) \in (TList T1)
| T_Lcase : forall Gamma t1 T1 t2 x1 x2 t3 T2,
Gamma |- t1 \in (TList T1) ->
Gamma |- t2 \in T2 ->
(extend (extend Gamma x2 (TList T1)) x1 T1) |- t3 \in T2 ->
Gamma |- (tlcase t1 t2 x1 x2 t3) \in T2
(* fix *)
(* FILL IN HERE *)
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd"
| Case_aux c "T_Unit"
(* let *)
(* FILL IN HERE *)
| Case_aux c "T_Inl" | Case_aux c "T_Inr" | Case_aux c "T_Case"
| Case_aux c "T_Nil" | Case_aux c "T_Cons" | Case_aux c "T_Lcase"
(* fix *)
(* FILL IN HERE *)
].
(* ###################################################################### *)
(** ** Examples *)
(** This section presents formalized versions of the examples from
above (plus several more). The ones at the beginning focus on
specific features; you can use these to make sure your definition
of a given feature is reasonable before moving on to extending the
proofs later in the file with the cases relating to this feature.
The later examples require all the features together, so you'll
need to come back to these when you've got all the definitions
filled in. *)
Module Examples.
(** *** Preliminaries *)
(** First, let's define a few variable names: *)
Notation a := (Id 0).
Notation f := (Id 1).
Notation g := (Id 2).
Notation l := (Id 3).
Notation k := (Id 6).
Notation i1 := (Id 7).
Notation i2 := (Id 8).
Notation x := (Id 9).
Notation y := (Id 10).
Notation processSum := (Id 11).
Notation n := (Id 12).
Notation eq := (Id 13).
Notation m := (Id 14).
Notation evenodd := (Id 15).
Notation even := (Id 16).
Notation odd := (Id 17).
Notation eo := (Id 18).
(** Next, a bit of Coq hackery to automate searching for typing
derivations. You don't need to understand this bit in detail --
just have a look over it so that you'll know what to look for if
you ever find yourself needing to make custom extensions to
[auto].
The following [Hint] declarations say that, whenever [auto]
arrives at a goal of the form [(Gamma |- (tapp e1 e1) \in T)], it
should consider [eapply T_App], leaving an existential variable
for the middle type T1, and similar for [lcase]. That variable
will then be filled in during the search for type derivations for
[e1] and [e2]. We also include a hint to "try harder" when
solving equality goals; this is useful to automate uses of
[T_Var] (which includes an equality as a precondition). *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
(* You'll want to uncomment the following line once
you've defined the [T_Lcase] constructor for the typing
relation: *)
(*
Hint Extern 2 (has_type _ (tlcase _ _ _ _ _) _) =>
eapply T_Lcase; auto.
*)
Hint Extern 2 (_ = _) => compute; reflexivity.
(** *** Numbers *)
Module Numtest.
(* if0 (pred (succ (pred (2 * 0))) then 5 else 6 *)
Definition test :=
tif0
(tpred
(tsucc
(tpred
(tmult
(tnat 2)
(tnat 0)))))
(tnat 5)
(tnat 6).
(** Remove the comment braces once you've implemented enough of the
definitions that you think this should work. *)
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof.
unfold test.
(* This typing derivation is quite deep, so we need to increase the
max search depth of [auto] from the default 5 to 10. *)
auto 10.
Qed.
Example numtest_reduces :
test ==>* tnat 5.
Proof.
unfold test. normalize.
Qed.
*)
End Numtest.
(** *** Products *)
Module Prodtest.
(* ((5,6),7).fst.snd *)
Definition test :=
tsnd
(tfst
(tpair
(tpair
(tnat 5)
(tnat 6))
(tnat 7))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End Prodtest.
(** *** [let] *)
Module LetTest.
(* let x = pred 6 in succ x *)
Definition test :=
tlet
x
(tpred (tnat 6))
(tsucc (tvar x)).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End LetTest.
(** *** Sums *)
Module Sumtest1.
(* case (inl Nat 5) of
inl x => x
| inr y => y *)
Definition test :=
tcase (tinl TNat (tnat 5))
x (tvar x)
y (tvar y).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tnat 5).
Proof. unfold test. normalize. Qed.
*)
End Sumtest1.
Module Sumtest2.
(* let processSum =
\x:Nat+Nat.
case x of
inl n => n
inr n => if0 n then 1 else 0 in
(processSum (inl Nat 5), processSum (inr Nat 5)) *)
Definition test :=
tlet
processSum
(tabs x (TSum TNat TNat)
(tcase (tvar x)
n (tvar n)
n (tif0 (tvar n) (tnat 1) (tnat 0))))
(tpair
(tapp (tvar processSum) (tinl TNat (tnat 5)))
(tapp (tvar processSum) (tinr TNat (tnat 5)))).
(*
Example typechecks :
(@empty ty) |- test \in (TProd TNat TNat).
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tpair (tnat 5) (tnat 0)).
Proof. unfold test. normalize. Qed.
*)
End Sumtest2.
(** *** Lists *)
Module ListTest.
(* let l = cons 5 (cons 6 (nil Nat)) in
lcase l of
nil => 0
| x::y => x*x *)
Definition test :=
tlet l
(tcons (tnat 5) (tcons (tnat 6) (tnil TNat)))
(tlcase (tvar l)
(tnat 0)
x y (tmult (tvar x) (tvar x))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 20. Qed.
Example reduces :
test ==>* (tnat 25).
Proof. unfold test. normalize. Qed.
*)
End ListTest.
(** *** [fix] *)
Module FixTest1.
(* fact := fix
(\f:nat->nat.
\a:nat.
if a=0 then 1 else a * (f (pred a))) *)
Definition fact :=
tfix
(tabs f (TArrow TNat TNat)
(tabs a TNat
(tif0
(tvar a)
(tnat 1)
(tmult
(tvar a)
(tapp (tvar f) (tpred (tvar a))))))).
(** (Warning: you may be able to typecheck [fact] but still have some
rules wrong!) *)
(*
Example fact_typechecks :
(@empty ty) |- fact \in (TArrow TNat TNat).
Proof. unfold fact. auto 10.
Qed.
*)
(*
Example fact_example:
(tapp fact (tnat 4)) ==>* (tnat 24).
Proof. unfold fact. normalize. Qed.
*)
End FixTest1.
Module FixTest2.
(* map :=
\g:nat->nat.
fix
(\f:[nat]->[nat].
\l:[nat].
case l of
| [] -> []
| x::l -> (g x)::(f l)) *)
Definition map :=
tabs g (TArrow TNat TNat)
(tfix
(tabs f (TArrow (TList TNat) (TList TNat))
(tabs l (TList TNat)
(tlcase (tvar l)
(tnil TNat)
a l (tcons (tapp (tvar g) (tvar a))
(tapp (tvar f) (tvar l))))))).
(*
(* Make sure you've uncommented the last [Hint Extern] above... *)
Example map_typechecks :
empty |- map \in
(TArrow (TArrow TNat TNat)
(TArrow (TList TNat)
(TList TNat))).
Proof. unfold map. auto 10. Qed.
Example map_example :
tapp (tapp map (tabs a TNat (tsucc (tvar a))))
(tcons (tnat 1) (tcons (tnat 2) (tnil TNat)))
==>* (tcons (tnat 2) (tcons (tnat 3) (tnil TNat))).
Proof. unfold map. normalize. Qed.
*)
End FixTest2.
Module FixTest3.
(* equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if0 m then (if0 n then 1 else 0)
else if0 n then 0
else eq (pred m) (pred n)) *)
Definition equal :=
tfix
(tabs eq (TArrow TNat (TArrow TNat TNat))
(tabs m TNat
(tabs n TNat
(tif0 (tvar m)
(tif0 (tvar n) (tnat 1) (tnat 0))
(tif0 (tvar n)
(tnat 0)
(tapp (tapp (tvar eq)
(tpred (tvar m)))
(tpred (tvar n)))))))).
(*
Example equal_typechecks :
(@empty ty) |- equal \in (TArrow TNat (TArrow TNat TNat)).
Proof. unfold equal. auto 10.
Qed.
*)
(*
Example equal_example1:
(tapp (tapp equal (tnat 4)) (tnat 4)) ==>* (tnat 1).
Proof. unfold equal. normalize. Qed.
*)
(*
Example equal_example2:
(tapp (tapp equal (tnat 4)) (tnat 5)) ==>* (tnat 0).
Proof. unfold equal. normalize. Qed.
*)
End FixTest3.
Module FixTest4.
(* let evenodd =
fix
(\eo: (Nat->Nat * Nat->Nat).
let e = \n:Nat. if0 n then 1 else eo.snd (pred n) in
let o = \n:Nat. if0 n then 0 else eo.fst (pred n) in
(e,o)) in
let even = evenodd.fst in
let odd = evenodd.snd in
(even 3, even 4)
*)
Definition eotest :=
tlet evenodd
(tfix
(tabs eo (TProd (TArrow TNat TNat) (TArrow TNat TNat))
(tpair
(tabs n TNat
(tif0 (tvar n)
(tnat 1)
(tapp (tsnd (tvar eo)) (tpred (tvar n)))))
(tabs n TNat
(tif0 (tvar n)
(tnat 0)
(tapp (tfst (tvar eo)) (tpred (tvar n))))))))
(tlet even (tfst (tvar evenodd))
(tlet odd (tsnd (tvar evenodd))
(tpair
(tapp (tvar even) (tnat 3))
(tapp (tvar even) (tnat 4))))).
(*
Example eotest_typechecks :
(@empty ty) |- eotest \in (TProd TNat TNat).
Proof. unfold eotest. eauto 30.
Qed.
*)
(*
Example eotest_example1:
eotest ==>* (tpair (tnat 0) (tnat 1)).
Proof. unfold eotest. normalize. Qed.
*)
End FixTest4.
End Examples.
(* ###################################################################### *)
(** ** Properties of Typing *)
(** The proofs of progress and preservation for this system are
essentially the same (though of course somewhat longer) as for the
pure simply typed lambda-calculus. *)
(* ###################################################################### *)
(** *** Progress *)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
(* Theorem: Suppose empty |- t : T. Then either
1. t is a value, or
2. t ==> t' for some t'.
Proof: By induction on the given typing derivation. *)
intros t T Ht.
remember (@empty ty) as Gamma.
generalize dependent HeqGamma.
has_type_cases (induction Ht) Case; intros HeqGamma; subst.
Case "T_Var".
(* The final rule in the given typing derivation cannot be [T_Var],
since it can never be the case that [empty |- x : T] (since the
context is empty). *)
inversion H.
Case "T_Abs".
(* If the [T_Abs] rule was the last used, then [t = tabs x T11 t12],
which is a value. *)
left...
Case "T_App".
(* If the last rule applied was T_App, then [t = t1 t2], and we know
from the form of the rule that
[empty |- t1 : T1 -> T2]
[empty |- t2 : T1]
By the induction hypothesis, each of t1 and t2 either is a value
or can take a step. *)
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
(* If both [t1] and [t2] are values, then we know that
[t1 = tabs x T11 t12], since abstractions are the only values
that can have an arrow type. But
[(tabs x T11 t12) t2 ==> [x:=t2]t12] by [ST_AppAbs]. *)
inversion H; subst; try (solve by inversion).
exists (subst x t2 t12)...
SSCase "t2 steps".
(* If [t1] is a value and [t2 ==> t2'], then [t1 t2 ==> t1 t2']
by [ST_App2]. *)
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
(* Finally, If [t1 ==> t1'], then [t1 t2 ==> t1' t2] by [ST_App1]. *)
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_Nat".
left...
Case "T_Succ".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (S n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsucc t1')...
Case "T_Pred".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (pred n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tpred t1')...
Case "T_Mult".
right.
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 is a value".
inversion H; subst; try solve by inversion.
inversion H0; subst; try solve by inversion.
exists (tnat (mult n1 n0))...
SSCase "t2 steps".
inversion H0 as [t2' Hstp].
exists (tmult t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tmult t1' t2)...
Case "T_If0".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
destruct n1 as [|n1'].
SSCase "n1=0".
exists t2...
SSCase "n1<>0".
exists t3...
SCase "t1 steps".
inversion H as [t1' H0].
exists (tif0 t1' t2 t3)...
Case "T_Pair".
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 steps".
right. inversion H0 as [t2' Hstp].
exists (tpair t1 t2')...
SCase "t1 steps".
right. inversion H as [t1' Hstp].
exists (tpair t1' t2)...
Case "T_Fst".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v1...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tfst t1')...
Case "T_Snd".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v2...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsnd t1')...
Case "T_Unit".
left...
(* let *)
(* FILL IN HERE *)
Case "T_Inl".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinl _ t1')... *)
Case "T_Inr".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinr _ t1')... *)
Case "T_Case".
right.
destruct IHHt1...
SCase "t0 is a value".
inversion H; subst; try solve by inversion.
SSCase "t0 is inl".
exists ([x1:=v]t1)...
SSCase "t0 is inr".
exists ([x2:=v]t2)...
SCase "t0 steps".
inversion H as [t0' Hstp].
exists (tcase t0' x1 t1 x2 t2)...
Case "T_Nil".
left...
Case "T_Cons".
destruct IHHt1...
SCase "head is a value".
destruct IHHt2...
SSCase "tail steps".
right. inversion H0 as [t2' Hstp].
exists (tcons t1 t2')...
SCase "head steps".
right. inversion H as [t1' Hstp].
exists (tcons t1' t2)...
Case "T_Lcase".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
SSCase "t1=tnil".
exists t2...
SSCase "t1=tcons v1 vl".
exists ([x2:=vl]([x1:=v1]t3))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tlcase t1' t2 x1 x2 t3)...
(* fix *)
(* FILL IN HERE *)
Qed.
(* ###################################################################### *)
(** *** Context Invariance *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
(* nats *)
| afi_succ : forall x t,
appears_free_in x t ->
appears_free_in x (tsucc t)
| afi_pred : forall x t,
appears_free_in x t ->
appears_free_in x (tpred t)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if01 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if02 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if03 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
(* pairs *)
| afi_pair1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tpair t1 t2)
| afi_pair2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tpair t1 t2)
| afi_fst : forall x t,
appears_free_in x t ->
appears_free_in x (tfst t)
| afi_snd : forall x t,
appears_free_in x t ->
appears_free_in x (tsnd t)
(* let *)
(* FILL IN HERE *)
(* sums *)
| afi_inl : forall x t T,
appears_free_in x t ->
appears_free_in x (tinl T t)
| afi_inr : forall x t T,
appears_free_in x t ->
appears_free_in x (tinr T t)
| afi_case0 : forall x t0 x1 t1 x2 t2,
appears_free_in x t0 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case1 : forall x t0 x1 t1 x2 t2,
x1 <> x ->
appears_free_in x t1 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case2 : forall x t0 x1 t1 x2 t2,
x2 <> x ->
appears_free_in x t2 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
(* lists *)
| afi_cons1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tcons t1 t2)
| afi_cons2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tcons t1 t2)
| afi_lcase1 : forall x t1 t2 y1 y2 t3,
appears_free_in x t1 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase2 : forall x t1 t2 y1 y2 t3,
appears_free_in x t2 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase3 : forall x t1 t2 y1 y2 t3,
y1 <> x ->
y2 <> x ->
appears_free_in x t3 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
(* fix *)
(* FILL IN HERE *)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros y Hafi.
unfold extend.
destruct (eq_id_dec x y)...
Case "T_Mult".
apply T_Mult...
Case "T_If0".
apply T_If0...
Case "T_Pair".
apply T_Pair...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
eapply T_Case...
apply IHhas_type2. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x2 y)...
Case "T_Cons".
apply T_Cons...
Case "T_Lcase".
eapply T_Lcase... apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
destruct (eq_id_dec x2 y)...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case; inversion Hafi; subst...
Case "T_Abs".
destruct IHHtyp as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "left".
destruct IHHtyp2 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
SCase "right".
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
Case "T_Lcase".
clear Htyp1 IHHtyp1 Htyp2 IHHtyp2.
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx... rewrite neq_id in Hctx...
Qed.
(* ###################################################################### *)
(** *** Substitution *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
(* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then
Gamma |- [x:=v]t : S. *)
intros Gamma x U v t S Htypt Htypv.
generalize dependent Gamma. generalize dependent S.
(* Proof: By induction on the term t. Most cases follow directly
from the IH, with the exception of tvar and tabs.
The former aren't automatic because we must reason about how the
variables interact. *)
t_cases (induction t) Case;
intros S Gamma Htypt; simpl; inversion Htypt; subst...
Case "tvar".
simpl. rename i into y.
(* If t = y, we know that
[empty |- v : U] and
[Gamma,x:U |- y : S]
and, by inversion, [extend Gamma x U y = Some S]. We want to
show that [Gamma |- [x:=v]y : S].
There are two cases to consider: either [x=y] or [x<>y]. *)
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then we know that [U = S], and that [[x:=v]y = v].
So what we really must show is that if [empty |- v : U] then
[Gamma |- v : U]. We have already proven a more general version
of this theorem, called context invariance. *)
subst.
unfold extend in H1. rewrite eq_id in H1.
inversion H1; subst. clear H1.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
(* If [x <> y], then [Gamma y = Some S] and the substitution has no
effect. We can show that [Gamma |- y : S] by [T_Var]. *)
apply T_Var... unfold extend in H1. rewrite neq_id in H1...
Case "tabs".
rename i into y. rename t into T11.
(* If [t = tabs y T11 t0], then we know that
[Gamma,x:U |- tabs y T11 t0 : T11->T12]
[Gamma,x:U,y:T11 |- t0 : T12]
[empty |- v : U]
As our IH, we know that forall S Gamma,
[Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 : S].
We can calculate that
[x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0)
And we must show that [Gamma |- [x:=v]t : T11->T12]. We know
we will do so using [T_Abs], so it remains to be shown that:
[Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12]
We consider two cases: [x = y] and [x <> y].
*)
apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then the substitution has no effect. Context
invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are
equivalent. Since the former context shows that [t0 : T12], so
does the latter. *)
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
(* If [x <> y], then the IH and context invariance allow us to show that
[Gamma,x:U,y:T11 |- t0 : T12] =>
[Gamma,y:T11,x:U |- t0 : T12] =>
[Gamma,y:T11 |- [x:=v]t0 : T12] *)
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
(* let *)
(* FILL IN HERE *)
Case "tcase".
rename i into x1. rename i0 into x2.
eapply T_Case...
SCase "left arm".
destruct (eq_id_dec x x1).
SSCase "x = x1".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
SSCase "x <> x1".
apply IHt2. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
subst. rewrite neq_id...
SCase "right arm".
destruct (eq_id_dec x x2).
SSCase "x = x2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
SSCase "x <> x2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
subst. rewrite neq_id...
Case "tlcase".
rename i into y1. rename i0 into y2.
eapply T_Lcase...
destruct (eq_id_dec x y1).
SCase "x=y1".
simpl.
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
SCase "x<>y1".
destruct (eq_id_dec x y2).
SSCase "x=y2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y2 z)...
SSCase "x<>y2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
subst. rewrite neq_id...
destruct (eq_id_dec y2 z)...
subst. rewrite neq_id...
Qed.
(* ###################################################################### *)
(** *** Preservation *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
(* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *)
remember (@empty ty) as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
(* Proof: By induction on the given typing derivation. Many cases are
contradictory ([T_Var], [T_Abs]). We show just the interesting ones. *)
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
(* If the last rule used was [T_App], then [t = t1 t2], and three rules
could have been used to show [t ==> t']: [ST_App1], [ST_App2], and
[ST_AppAbs]. In the first two cases, the result follows directly from
the IH. *)
inversion HE; subst...
SCase "ST_AppAbs".
(* For the third case, suppose
[t1 = tabs x T11 t12]
and
[t2 = v2].
We must show that [empty |- [x:=v2]t12 : T2].
We know by assumption that
[empty |- tabs x T11 t12 : T1->T2]
and by inversion
[x:T1 |- t12 : T2]
We have already proven that substitution_preserves_typing and
[empty |- v2 : T1]
by assumption, so we are done. *)
apply substitution_preserves_typing with T1...
inversion HT1...
Case "T_Fst".
inversion HT...
Case "T_Snd".
inversion HT...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "ST_CaseInl".
inversion HT1; subst.
eapply substitution_preserves_typing...
SCase "ST_CaseInr".
inversion HT1; subst.
eapply substitution_preserves_typing...
Case "T_Lcase".
SCase "ST_LcaseCons".
inversion HT1; subst.
apply substitution_preserves_typing with (TList T1)...
apply substitution_preserves_typing with T1...
(* fix *)
(* FILL IN HERE *)
Qed.
(** [] *)
End STLCExtended.
(* $Date: 2014-12-01 15:15:02 -0500 (Mon, 01 Dec 2014) $ *)
|
(** * MoreStlc: More on the Simply Typed Lambda-Calculus *)
Require Export Stlc.
(* ###################################################################### *)
(** * Simple Extensions to STLC *)
(** The simply typed lambda-calculus has enough structure to make its
theoretical properties interesting, but it is not much of a
programming language. In this chapter, we begin to close the gap
with real-world languages by introducing a number of familiar
features that have straightforward treatments at the level of
typing. *)
(** ** Numbers *)
(** Adding types, constants, and primitive operations for numbers is
easy -- just a matter of combining the [Types] and [Stlc]
chapters. *)
(** ** [let]-bindings *)
(** When writing a complex expression, it is often useful to give
names to some of its subexpressions: this avoids repetition and
often increases readability. Most languages provide one or more
ways of doing this. In OCaml (and Coq), for example, we can write
[let x=t1 in t2] to mean ``evaluate the expression [t1] and bind
the name [x] to the resulting value while evaluating [t2].''
Our [let]-binder follows OCaml's in choosing a call-by-value
evaluation order, where the [let]-bound term must be fully
evaluated before evaluation of the [let]-body can begin. The
typing rule [T_Let] tells us that the type of a [let] can be
calculated by calculating the type of the [let]-bound term,
extending the context with a binding with this type, and in this
enriched context calculating the type of the body, which is then
the type of the whole [let] expression.
At this point in the course, it's probably easier simply to look
at the rules defining this new feature as to wade through a lot of
english text conveying the same information. Here they are: *)
(** Syntax:
<<
t ::= Terms
| ... (other terms same as before)
| let x=t in t let-binding
>>
*)
(**
Reduction:
t1 ==> t1'
---------------------------------- (ST_Let1)
let x=t1 in t2 ==> let x=t1' in t2
---------------------------- (ST_LetValue)
let x=v1 in t2 ==> [x:=v1]t2
Typing:
Gamma |- t1 : T1 Gamma , x:T1 |- t2 : T2
-------------------------------------------- (T_Let)
Gamma |- let x=t1 in t2 : T2
*)
(** ** Pairs *)
(** Our functional programming examples in Coq have made
frequent use of _pairs_ of values. The type of such pairs is
called a _product type_.
The formalization of pairs is almost too simple to be worth
discussing. However, let's look briefly at the various parts of
the definition to emphasize the common pattern. *)
(** In Coq, the primitive way of extracting the components of a pair
is _pattern matching_. An alternative style is to take [fst] and
[snd] -- the first- and second-projection operators -- as
primitives. Just for fun, let's do our products this way. For
example, here's how we'd write a function that takes a pair of
numbers and returns the pair of their sum and difference:
<<
\x:Nat*Nat.
let sum = x.fst + x.snd in
let diff = x.fst - x.snd in
(sum,diff)
>>
*)
(** Adding pairs to the simply typed lambda-calculus, then, involves
adding two new forms of term -- pairing, written [(t1,t2)], and
projection, written [t.fst] for the first projection from [t] and
[t.snd] for the second projection -- plus one new type constructor,
[T1*T2], called the _product_ of [T1] and [T2]. *)
(** Syntax:
<<
t ::= Terms
| ...
| (t,t) pair
| t.fst first projection
| t.snd second projection
v ::= Values
| ...
| (v,v) pair value
T ::= Types
| ...
| T * T product type
>>
*)
(** For evaluation, we need several new rules specifying how pairs and
projection behave.
t1 ==> t1'
-------------------- (ST_Pair1)
(t1,t2) ==> (t1',t2)
t2 ==> t2'
-------------------- (ST_Pair2)
(v1,t2) ==> (v1,t2')
t1 ==> t1'
------------------ (ST_Fst1)
t1.fst ==> t1'.fst
------------------ (ST_FstPair)
(v1,v2).fst ==> v1
t1 ==> t1'
------------------ (ST_Snd1)
t1.snd ==> t1'.snd
------------------ (ST_SndPair)
(v1,v2).snd ==> v2
*)
(**
Rules [ST_FstPair] and [ST_SndPair] specify that, when a fully
evaluated pair meets a first or second projection, the result is
the appropriate component. The congruence rules [ST_Fst1] and
[ST_Snd1] allow reduction to proceed under projections, when the
term being projected from has not yet been fully evaluated.
[ST_Pair1] and [ST_Pair2] evaluate the parts of pairs: first the
left part, and then -- when a value appears on the left -- the right
part. The ordering arising from the use of the metavariables [v]
and [t] in these rules enforces a left-to-right evaluation
strategy for pairs. (Note the implicit convention that
metavariables like [v] and [v1] can only denote values.) We've
also added a clause to the definition of values, above, specifying
that [(v1,v2)] is a value. The fact that the components of a pair
value must themselves be values ensures that a pair passed as an
argument to a function will be fully evaluated before the function
body starts executing. *)
(** The typing rules for pairs and projections are straightforward.
Gamma |- t1 : T1 Gamma |- t2 : T2
--------------------------------------- (T_Pair)
Gamma |- (t1,t2) : T1*T2
Gamma |- t1 : T11*T12
--------------------- (T_Fst)
Gamma |- t1.fst : T11
Gamma |- t1 : T11*T12
--------------------- (T_Snd)
Gamma |- t1.snd : T12
*)
(** The rule [T_Pair] says that [(t1,t2)] has type [T1*T2] if [t1] has
type [T1] and [t2] has type [T2]. Conversely, the rules [T_Fst]
and [T_Snd] tell us that, if [t1] has a product type
[T11*T12] (i.e., if it will evaluate to a pair), then the types of
the projections from this pair are [T11] and [T12]. *)
(** ** Unit *)
(** Another handy base type, found especially in languages in
the ML family, is the singleton type [Unit]. *)
(** It has a single element -- the term constant [unit] (with a small
[u]) -- and a typing rule making [unit] an element of [Unit]. We
also add [unit] to the set of possible result values of
computations -- indeed, [unit] is the _only_ possible result of
evaluating an expression of type [Unit]. *)
(** Syntax:
<<
t ::= Terms
| ...
| unit unit value
v ::= Values
| ...
| unit unit
T ::= Types
| ...
| Unit Unit type
>>
Typing:
-------------------- (T_Unit)
Gamma |- unit : Unit
*)
(** It may seem a little strange to bother defining a type that
has just one element -- after all, wouldn't every computation
living in such a type be trivial?
This is a fair question, and indeed in the STLC the [Unit] type is
not especially critical (though we'll see two uses for it below).
Where [Unit] really comes in handy is in richer languages with
various sorts of _side effects_ -- e.g., assignment statements
that mutate variables or pointers, exceptions and other sorts of
nonlocal control structures, etc. In such languages, it is
convenient to have a type for the (trivial) result of an
expression that is evaluated only for its effect. *)
(** ** Sums *)
(** Many programs need to deal with values that can take two distinct
forms. For example, we might identify employees in an accounting
application using using _either_ their name _or_ their id number.
A search function might return _either_ a matching value _or_ an
error code.
These are specific examples of a binary _sum type_,
which describes a set of values drawn from exactly two given types, e.g.
<<
Nat + Bool
>>
*)
(** We create elements of these types by _tagging_ elements of
the component types. For example, if [n] is a [Nat] then [inl v]
is an element of [Nat+Bool]; similarly, if [b] is a [Bool] then
[inr b] is a [Nat+Bool]. The names of the tags [inl] and [inr]
arise from thinking of them as functions
<<
inl : Nat -> Nat + Bool
inr : Bool -> Nat + Bool
>>
that "inject" elements of [Nat] or [Bool] into the left and right
components of the sum type [Nat+Bool]. (But note that we don't
actually treat them as functions in the way we formalize them:
[inl] and [inr] are keywords, and [inl t] and [inr t] are primitive
syntactic forms, not function applications. This allows us to give
them their own special typing rules.) *)
(** In general, the elements of a type [T1 + T2] consist of the
elements of [T1] tagged with the token [inl], plus the elements of
[T2] tagged with [inr]. *)
(** One important usage of sums is signaling errors:
<<
div : Nat -> Nat -> (Nat + Unit) =
div =
\x:Nat. \y:Nat.
if iszero y then
inr unit
else
inl ...
>>
The type [Nat + Unit] above is in fact isomorphic to [option nat]
in Coq, and we've already seen how to signal errors with options. *)
(** To _use_ elements of sum types, we introduce a [case]
construct (a very simplified form of Coq's [match]) to destruct
them. For example, the following procedure converts a [Nat+Bool]
into a [Nat]: *)
(**
<<
getNat =
\x:Nat+Bool.
case x of
inl n => n
| inr b => if b then 1 else 0
>>
*)
(** More formally... *)
(** Syntax:
<<
t ::= Terms
| ...
| inl T t tagging (left)
| inr T t tagging (right)
| case t of case
inl x => t
| inr x => t
v ::= Values
| ...
| inl T v tagged value (left)
| inr T v tagged value (right)
T ::= Types
| ...
| T + T sum type
>>
*)
(** Evaluation:
t1 ==> t1'
---------------------- (ST_Inl)
inl T t1 ==> inl T t1'
t1 ==> t1'
---------------------- (ST_Inr)
inr T t1 ==> inr T t1'
t0 ==> t0'
------------------------------------------- (ST_Case)
case t0 of inl x1 => t1 | inr x2 => t2 ==>
case t0' of inl x1 => t1 | inr x2 => t2
---------------------------------------------- (ST_CaseInl)
case (inl T v0) of inl x1 => t1 | inr x2 => t2
==> [x1:=v0]t1
---------------------------------------------- (ST_CaseInr)
case (inr T v0) of inl x1 => t1 | inr x2 => t2
==> [x2:=v0]t2
*)
(** Typing:
Gamma |- t1 : T1
---------------------------- (T_Inl)
Gamma |- inl T2 t1 : T1 + T2
Gamma |- t1 : T2
---------------------------- (T_Inr)
Gamma |- inr T1 t1 : T1 + T2
Gamma |- t0 : T1+T2
Gamma , x1:T1 |- t1 : T
Gamma , x2:T2 |- t2 : T
--------------------------------------------------- (T_Case)
Gamma |- case t0 of inl x1 => t1 | inr x2 => t2 : T
We use the type annotation in [inl] and [inr] to make the typing
simpler, similarly to what we did for functions. *)
(** Without this extra
information, the typing rule [T_Inl], for example, would have to
say that, once we have shown that [t1] is an element of type [T1],
we can derive that [inl t1] is an element of [T1 + T2] for _any_
type T2. For example, we could derive both [inl 5 : Nat + Nat]
and [inl 5 : Nat + Bool] (and infinitely many other types).
This failure of uniqueness of types would mean that we cannot
build a typechecking algorithm simply by "reading the rules from
bottom to top" as we could for all the other features seen so far.
There are various ways to deal with this difficulty. One simple
one -- which we've adopted here -- forces the programmer to
explicitly annotate the "other side" of a sum type when performing
an injection. This is rather heavyweight for programmers (and so
real languages adopt other solutions), but it is easy to
understand and formalize. *)
(** ** Lists *)
(** The typing features we have seen can be classified into _base
types_ like [Bool], and _type constructors_ like [->] and [*] that
build new types from old ones. Another useful type constructor is
[List]. For every type [T], the type [List T] describes
finite-length lists whose elements are drawn from [T].
In principle, we could encode lists using pairs, sums and
_recursive_ types. But giving semantics to recursive types is
non-trivial. Instead, we'll just discuss the special case of lists
directly.
Below we give the syntax, semantics, and typing rules for lists.
Except for the fact that explicit type annotations are mandatory
on [nil] and cannot appear on [cons], these lists are essentially
identical to those we built in Coq. We use [lcase] to destruct
lists, to avoid dealing with questions like "what is the [head] of
the empty list?" *)
(** For example, here is a function that calculates the sum of
the first two elements of a list of numbers:
<<
\x:List Nat.
lcase x of nil -> 0
| a::x' -> lcase x' of nil -> a
| b::x'' -> a+b
>>
*)
(**
Syntax:
<<
t ::= Terms
| ...
| nil T
| cons t t
| lcase t of nil -> t | x::x -> t
v ::= Values
| ...
| nil T nil value
| cons v v cons value
T ::= Types
| ...
| List T list of Ts
>>
*)
(** Reduction:
t1 ==> t1'
-------------------------- (ST_Cons1)
cons t1 t2 ==> cons t1' t2
t2 ==> t2'
-------------------------- (ST_Cons2)
cons v1 t2 ==> cons v1 t2'
t1 ==> t1'
---------------------------------------- (ST_Lcase1)
(lcase t1 of nil -> t2 | xh::xt -> t3) ==>
(lcase t1' of nil -> t2 | xh::xt -> t3)
----------------------------------------- (ST_LcaseNil)
(lcase nil T of nil -> t2 | xh::xt -> t3)
==> t2
----------------------------------------------- (ST_LcaseCons)
(lcase (cons vh vt) of nil -> t2 | xh::xt -> t3)
==> [xh:=vh,xt:=vt]t3
*)
(** Typing:
----------------------- (T_Nil)
Gamma |- nil T : List T
Gamma |- t1 : T Gamma |- t2 : List T
----------------------------------------- (T_Cons)
Gamma |- cons t1 t2: List T
Gamma |- t1 : List T1
Gamma |- t2 : T
Gamma , h:T1, t:List T1 |- t3 : T
------------------------------------------------- (T_Lcase)
Gamma |- (lcase t1 of nil -> t2 | h::t -> t3) : T
*)
(** ** General Recursion *)
(** Another facility found in most programming languages (including
Coq) is the ability to define recursive functions. For example,
we might like to be able to define the factorial function like
this:
<<
fact = \x:Nat.
if x=0 then 1 else x * (fact (pred x)))
>>
But this would require quite a bit of work to formalize: we'd have
to introduce a notion of "function definitions" and carry around an
"environment" of such definitions in the definition of the [step]
relation. *)
(** Here is another way that is straightforward to formalize: instead
of writing recursive definitions where the right-hand side can
contain the identifier being defined, we can define a _fixed-point
operator_ that performs the "unfolding" of the recursive definition
in the right-hand side lazily during reduction.
<<
fact =
fix
(\f:Nat->Nat.
\x:Nat.
if x=0 then 1 else x * (f (pred x)))
>>
*)
(** The intuition is that the higher-order function [f] passed
to [fix] is a _generator_ for the [fact] function: if [fact] is
applied to a function that approximates the desired behavior of
[fact] up to some number [n] (that is, a function that returns
correct results on inputs less than or equal to [n]), then it
returns a better approximation to [fact] -- a function that returns
correct results for inputs up to [n+1]. Applying [fix] to this
generator returns its _fixed point_ -- a function that gives the
desired behavior for all inputs [n].
(The term "fixed point" has exactly the same sense as in ordinary
mathematics, where a fixed point of a function [f] is an input [x]
such that [f(x) = x]. Here, a fixed point of a function [F] of
type (say) [(Nat->Nat)->(Nat->Nat)] is a function [f] such that [F
f] is behaviorally equivalent to [f].) *)
(** Syntax:
<<
t ::= Terms
| ...
| fix t fixed-point operator
>>
Reduction:
t1 ==> t1'
------------------ (ST_Fix1)
fix t1 ==> fix t1'
F = \xf:T1.t2
----------------------- (ST_FixAbs)
fix F ==> [xf:=fix F]t2
Typing:
Gamma |- t1 : T1->T1
-------------------- (T_Fix)
Gamma |- fix t1 : T1
*)
(** Let's see how [ST_FixAbs] works by reducing [fact 3 = fix F 3],
where [F = (\f. \x. if x=0 then 1 else x * (f (pred x)))] (we are
omitting type annotations for brevity here).
<<
fix F 3
>>
[==>] [ST_FixAbs]
<<
(\x. if x=0 then 1 else x * (fix F (pred x))) 3
>>
[==>] [ST_AppAbs]
<<
if 3=0 then 1 else 3 * (fix F (pred 3))
>>
[==>] [ST_If0_Nonzero]
<<
3 * (fix F (pred 3))
>>
[==>] [ST_FixAbs + ST_Mult2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 3))
>>
[==>] [ST_PredNat + ST_Mult2 + ST_App2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 2)
>>
[==>] [ST_AppAbs + ST_Mult2]
<<
3 * (if 2=0 then 1 else 2 * (fix F (pred 2)))
>>
[==>] [ST_If0_Nonzero + ST_Mult2]
<<
3 * (2 * (fix F (pred 2)))
>>
[==>] [ST_FixAbs + 2 x ST_Mult2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 2)))
>>
[==>] [ST_PredNat + 2 x ST_Mult2 + ST_App2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 1))
>>
[==>] [ST_AppAbs + 2 x ST_Mult2]
<<
3 * (2 * (if 1=0 then 1 else 1 * (fix F (pred 1))))
>>
[==>] [ST_If0_Nonzero + 2 x ST_Mult2]
<<
3 * (2 * (1 * (fix F (pred 1))))
>>
[==>] [ST_FixAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 1))))
>>
[==>] [ST_PredNat + 3 x ST_Mult2 + ST_App2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 0)))
>>
[==>] [ST_AppAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * (if 0=0 then 1 else 0 * (fix F (pred 0)))))
>>
[==>] [ST_If0Zero + 3 x ST_Mult2]
<<
3 * (2 * (1 * 1))
>>
[==>] [ST_MultNats + 2 x ST_Mult2]
<<
3 * (2 * 1)
>>
[==>] [ST_MultNats + ST_Mult2]
<<
3 * 2
>>
[==>] [ST_MultNats]
<<
6
>>
*)
(** **** Exercise: 1 star, optional (halve_fix) *)
(** Translate this informal recursive definition into one using [fix]:
<<
halve =
\x:Nat.
if x=0 then 0
else if (pred x)=0 then 0
else 1 + (halve (pred (pred x))))
>>
(* FILL IN HERE *)
[]
*)
(** **** Exercise: 1 star, optional (fact_steps) *)
(** Write down the sequence of steps that the term [fact 1] goes
through to reduce to a normal form (assuming the usual reduction
rules for arithmetic operations).
(* FILL IN HERE *)
[]
*)
(** The ability to form the fixed point of a function of type [T->T]
for any [T] has some surprising consequences. In particular, it
implies that _every_ type is inhabited by some term. To see this,
observe that, for every type [T], we can define the term
fix (\x:T.x)
By [T_Fix] and [T_Abs], this term has type [T]. By [ST_FixAbs]
it reduces to itself, over and over again. Thus it is an
_undefined element_ of [T].
More usefully, here's an example using [fix] to define a
two-argument recursive function:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
And finally, here is an example where [fix] is used to define a
_pair_ of recursive functions (illustrating the fact that the type
[T1] in the rule [T_Fix] need not be a function type):
<<
evenodd =
fix
(\eo: (Nat->Bool * Nat->Bool).
let e = \n:Nat. if n=0 then true else eo.snd (pred n) in
let o = \n:Nat. if n=0 then false else eo.fst (pred n) in
(e,o))
even = evenodd.fst
odd = evenodd.snd
>>
*)
(* ###################################################################### *)
(** ** Records *)
(** As a final example of a basic extension of the STLC, let's
look briefly at how to define _records_ and their types.
Intuitively, records can be obtained from pairs by two kinds of
generalization: they are n-ary products (rather than just binary)
and their fields are accessed by _label_ (rather than position).
Conceptually, this extension is a straightforward generalization
of pairs and product types, but notationally it becomes a little
heavier; for this reason, we postpone its formal treatment to a
separate chapter ([Records]). *)
(** Records are not included in the extended exercise below, but
they will be useful to motivate the [Sub] chapter. *)
(** Syntax:
<<
t ::= Terms
| ...
| {i1=t1, ..., in=tn} record
| t.i projection
v ::= Values
| ...
| {i1=v1, ..., in=vn} record value
T ::= Types
| ...
| {i1:T1, ..., in:Tn} record type
>>
Intuitively, the generalization is pretty obvious. But it's worth
noticing that what we've actually written is rather informal: in
particular, we've written "[...]" in several places to mean "any
number of these," and we've omitted explicit mention of the usual
side-condition that the labels of a record should not contain
repetitions. *)
(** It is possible to devise informal notations that are
more precise, but these tend to be quite heavy and to obscure the
main points of the definitions. So we'll leave these a bit loose
here (they are informal anyway, after all) and do the work of
tightening things up elsewhere (in chapter [Records]). *)
(**
Reduction:
ti ==> ti'
------------------------------------ (ST_Rcd)
{i1=v1, ..., im=vm, in=ti, ...}
==> {i1=v1, ..., im=vm, in=ti', ...}
t1 ==> t1'
-------------- (ST_Proj1)
t1.i ==> t1'.i
------------------------- (ST_ProjRcd)
{..., i=vi, ...}.i ==> vi
Again, these rules are a bit informal. For example, the first rule
is intended to be read "if [ti] is the leftmost field that is not a
value and if [ti] steps to [ti'], then the whole record steps..."
In the last rule, the intention is that there should only be one
field called i, and that all the other fields must contain values. *)
(**
Typing:
Gamma |- t1 : T1 ... Gamma |- tn : Tn
-------------------------------------------------- (T_Rcd)
Gamma |- {i1=t1, ..., in=tn} : {i1:T1, ..., in:Tn}
Gamma |- t : {..., i:Ti, ...}
----------------------------- (T_Proj)
Gamma |- t.i : Ti
*)
(* ###################################################################### *)
(** *** Encoding Records (Optional) *)
(** There are several ways to make the above definitions precise.
- We can directly formalize the syntactic forms and inference
rules, staying as close as possible to the form we've given
them above. This is conceptually straightforward, and it's
probably what we'd want to do if we were building a real
compiler -- in particular, it will allow is to print error
messages in the form that programmers will find easy to
understand. But the formal versions of the rules will not be
pretty at all!
- We could look for a smoother way of presenting records -- for
example, a binary presentation with one constructor for the
empty record and another constructor for adding a single field
to an existing record, instead of a single monolithic
constructor that builds a whole record at once. This is the
right way to go if we are primarily interested in studying the
metatheory of the calculi with records, since it leads to
clean and elegant definitions and proofs. Chapter [Records]
shows how this can be done.
- Alternatively, if we like, we can avoid formalizing records
altogether, by stipulating that record notations are just
informal shorthands for more complex expressions involving
pairs and product types. We sketch this approach here.
First, observe that we can encode arbitrary-size tuples using
nested pairs and the [unit] value. To avoid overloading the pair
notation [(t1,t2)], we'll use curly braces without labels to write
down tuples, so [{}] is the empty tuple, [{5}] is a singleton
tuple, [{5,6}] is a 2-tuple (morally the same as a pair),
[{5,6,7}] is a triple, etc.
<<
{} ----> unit
{t1, t2, ..., tn} ----> (t1, trest)
where {t2, ..., tn} ----> trest
>>
Similarly, we can encode tuple types using nested product types:
<<
{} ----> Unit
{T1, T2, ..., Tn} ----> T1 * TRest
where {T2, ..., Tn} ----> TRest
>>
The operation of projecting a field from a tuple can be encoded
using a sequence of second projections followed by a first projection:
<<
t.0 ----> t.fst
t.(n+1) ----> (t.snd).n
>>
Next, suppose that there is some total ordering on record labels,
so that we can associate each label with a unique natural number.
This number is called the _position_ of the label. For example,
we might assign positions like this:
<<
LABEL POSITION
a 0
b 1
c 2
... ...
foo 1004
... ...
bar 10562
... ...
>>
We use these positions to encode record values as tuples (i.e., as
nested pairs) by sorting the fields according to their positions.
For example:
<<
{a=5, b=6} ----> {5,6}
{a=5, c=7} ----> {5,unit,7}
{c=7, a=5} ----> {5,unit,7}
{c=5, b=3} ----> {unit,3,5}
{f=8,c=5,a=7} ----> {7,unit,5,unit,unit,8}
{f=8,c=5} ----> {unit,unit,5,unit,unit,8}
>>
Note that each field appears in the position associated with its
label, that the size of the tuple is determined by the label with
the highest position, and that we fill in unused positions with
[unit].
We do exactly the same thing with record types:
<<
{a:Nat, b:Nat} ----> {Nat,Nat}
{c:Nat, a:Nat} ----> {Nat,Unit,Nat}
{f:Nat,c:Nat} ----> {Unit,Unit,Nat,Unit,Unit,Nat}
>>
Finally, record projection is encoded as a tuple projection from
the appropriate position:
<<
t.l ----> t.(position of l)
>>
It is not hard to check that all the typing rules for the original
"direct" presentation of records are validated by this
encoding. (The reduction rules are "almost validated" -- not
quite, because the encoding reorders fields.) *)
(** Of course, this encoding will not be very efficient if we
happen to use a record with label [bar]! But things are not
actually as bad as they might seem: for example, if we assume that
our compiler can see the whole program at the same time, we can
_choose_ the numbering of labels so that we assign small positions
to the most frequently used labels. Indeed, there are industrial
compilers that essentially do this! *)
(** *** Variants (Optional Reading) *)
(** Just as products can be generalized to records, sums can be
generalized to n-ary labeled types called _variants_. Instead of
[T1+T2], we can write something like [<l1:T1,l2:T2,...ln:Tn>]
where [l1],[l2],... are field labels which are used both to build
instances and as case arm labels.
These n-ary variants give us almost enough mechanism to build
arbitrary inductive data types like lists and trees from
scratch -- the only thing missing is a way to allow _recursion_ in
type definitions. We won't cover this here, but detailed
treatments can be found in many textbooks -- e.g., Types and
Programming Languages. *)
(* ###################################################################### *)
(** * Exercise: Formalizing the Extensions *)
(** **** Exercise: 4 stars, optional (STLC_extensions) *)
(** In this problem you will formalize a couple of the extensions
described above. We've provided the necessary additions to the
syntax of terms and types, and we've included a few examples that
you can test your definitions with to make sure they are working
as expected. You'll fill in the rest of the definitions and
extend all the proofs accordingly.
To get you started, we've provided implementations for:
- numbers
- pairs and units
- sums
- lists
You need to complete the implementations for:
- let (which involves binding)
- [fix]
A good strategy is to work on the extensions one at a time, in
multiple passes, rather than trying to work through the file from
start to finish in a single pass. For each definition or proof,
begin by reading carefully through the parts that are provided for
you, referring to the text in the [Stlc] chapter for high-level
intuitions and the embedded comments for detailed mechanics.
*)
Module STLCExtended.
(* ###################################################################### *)
(** *** Syntax and Operational Semantics *)
Inductive ty : Type :=
| TArrow : ty -> ty -> ty
| TNat : ty
| TUnit : ty
| TProd : ty -> ty -> ty
| TSum : ty -> ty -> ty
| TList : ty -> ty.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TArrow" | Case_aux c "TNat"
| Case_aux c "TProd" | Case_aux c "TUnit"
| Case_aux c "TSum" | Case_aux c "TList" ].
Inductive tm : Type :=
(* pure STLC *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
(* numbers *)
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm
(* pairs *)
| tpair : tm -> tm -> tm
| tfst : tm -> tm
| tsnd : tm -> tm
(* units *)
| tunit : tm
(* let *)
| tlet : id -> tm -> tm -> tm
(* i.e., [let x = t1 in t2] *)
(* sums *)
| tinl : ty -> tm -> tm
| tinr : ty -> tm -> tm
| tcase : tm -> id -> tm -> id -> tm -> tm
(* i.e., [case t0 of inl x1 => t1 | inr x2 => t2] *)
(* lists *)
| tnil : ty -> tm
| tcons : tm -> tm -> tm
| tlcase : tm -> tm -> id -> id -> tm -> tm
(* i.e., [lcase t1 of | nil -> t2 | x::y -> t3] *)
(* fix *)
| tfix : tm -> tm.
(** Note that, for brevity, we've omitted booleans and instead
provided a single [if0] form combining a zero test and a
conditional. That is, instead of writing
<<
if x = 0 then ... else ...
>>
we'll write this:
<<
if0 x then ... else ...
>>
*)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"
| Case_aux c "tnat" | Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd"
| Case_aux c "tunit" | Case_aux c "tlet"
| Case_aux c "tinl" | Case_aux c "tinr" | Case_aux c "tcase"
| Case_aux c "tnil" | Case_aux c "tcons" | Case_aux c "tlcase"
| Case_aux c "tfix" ].
(* ###################################################################### *)
(** *** Substitution *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tnat n =>
tnat n
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tpair t1 t2 =>
tpair (subst x s t1) (subst x s t2)
| tfst t1 =>
tfst (subst x s t1)
| tsnd t1 =>
tsnd (subst x s t1)
| tunit => tunit
(* FILL IN HERE *)
| tinl T t1 =>
tinl T (subst x s t1)
| tinr T t1 =>
tinr T (subst x s t1)
| tcase t0 y1 t1 y2 t2 =>
tcase (subst x s t0)
y1 (if eq_id_dec x y1 then t1 else (subst x s t1))
y2 (if eq_id_dec x y2 then t2 else (subst x s t2))
| tnil T =>
tnil T
| tcons t1 t2 =>
tcons (subst x s t1) (subst x s t2)
| tlcase t1 t2 y1 y2 t3 =>
tlcase (subst x s t1) (subst x s t2) y1 y2
(if eq_id_dec x y1 then
t3
else if eq_id_dec x y2 then t3
else (subst x s t3))
(* FILL IN HERE *)
| _ => t (* ... and delete this line *)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** *** Reduction *)
(** Next we define the values of our language. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T11 t12,
value (tabs x T11 t12)
(* Numbers are values: *)
| v_nat : forall n1,
value (tnat n1)
(* A pair is a value if both components are: *)
| v_pair : forall v1 v2,
value v1 ->
value v2 ->
value (tpair v1 v2)
(* A unit is always a value *)
| v_unit : value tunit
(* A tagged value is a value: *)
| v_inl : forall v T,
value v ->
value (tinl T v)
| v_inr : forall v T,
value v ->
value (tinr T v)
(* A list is a value iff its head and tail are values: *)
| v_lnil : forall T, value (tnil T)
| v_lcons : forall v1 vl,
value v1 ->
value vl ->
value (tcons v1 vl)
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T11 t12 v2,
value v2 ->
(tapp (tabs x T11 t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
(* nats *)
| ST_Succ1 : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
| ST_SuccNat : forall n1,
(tsucc (tnat n1)) ==> (tnat (S n1))
| ST_Pred : forall t1 t1',
t1 ==> t1' ->
(tpred t1) ==> (tpred t1')
| ST_PredNat : forall n1,
(tpred (tnat n1)) ==> (tnat (pred n1))
| ST_Mult1 : forall t1 t1' t2,
t1 ==> t1' ->
(tmult t1 t2) ==> (tmult t1' t2)
| ST_Mult2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tmult v1 t2) ==> (tmult v1 t2')
| ST_MultNats : forall n1 n2,
(tmult (tnat n1) (tnat n2)) ==> (tnat (mult n1 n2))
| ST_If01 : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif0 t1 t2 t3) ==> (tif0 t1' t2 t3)
| ST_If0Zero : forall t2 t3,
(tif0 (tnat 0) t2 t3) ==> t2
| ST_If0Nonzero : forall n t2 t3,
(tif0 (tnat (S n)) t2 t3) ==> t3
(* pairs *)
| ST_Pair1 : forall t1 t1' t2,
t1 ==> t1' ->
(tpair t1 t2) ==> (tpair t1' t2)
| ST_Pair2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tpair v1 t2) ==> (tpair v1 t2')
| ST_Fst1 : forall t1 t1',
t1 ==> t1' ->
(tfst t1) ==> (tfst t1')
| ST_FstPair : forall v1 v2,
value v1 ->
value v2 ->
(tfst (tpair v1 v2)) ==> v1
| ST_Snd1 : forall t1 t1',
t1 ==> t1' ->
(tsnd t1) ==> (tsnd t1')
| ST_SndPair : forall v1 v2,
value v1 ->
value v2 ->
(tsnd (tpair v1 v2)) ==> v2
(* let *)
(* FILL IN HERE *)
(* sums *)
| ST_Inl : forall t1 t1' T,
t1 ==> t1' ->
(tinl T t1) ==> (tinl T t1')
| ST_Inr : forall t1 t1' T,
t1 ==> t1' ->
(tinr T t1) ==> (tinr T t1')
| ST_Case : forall t0 t0' x1 t1 x2 t2,
t0 ==> t0' ->
(tcase t0 x1 t1 x2 t2) ==> (tcase t0' x1 t1 x2 t2)
| ST_CaseInl : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinl T v0) x1 t1 x2 t2) ==> [x1:=v0]t1
| ST_CaseInr : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinr T v0) x1 t1 x2 t2) ==> [x2:=v0]t2
(* lists *)
| ST_Cons1 : forall t1 t1' t2,
t1 ==> t1' ->
(tcons t1 t2) ==> (tcons t1' t2)
| ST_Cons2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tcons v1 t2) ==> (tcons v1 t2')
| ST_Lcase1 : forall t1 t1' t2 x1 x2 t3,
t1 ==> t1' ->
(tlcase t1 t2 x1 x2 t3) ==> (tlcase t1' t2 x1 x2 t3)
| ST_LcaseNil : forall T t2 x1 x2 t3,
(tlcase (tnil T) t2 x1 x2 t3) ==> t2
| ST_LcaseCons : forall v1 vl t2 x1 x2 t3,
value v1 ->
value vl ->
(tlcase (tcons v1 vl) t2 x1 x2 t3) ==> (subst x2 vl (subst x1 v1 t3))
(* fix *)
(* FILL IN HERE *)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"
| Case_aux c "ST_Succ1" | Case_aux c "ST_SuccNat"
| Case_aux c "ST_Pred1" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_MultNats" | Case_aux c "ST_If01"
| Case_aux c "ST_If0Zero" | Case_aux c "ST_If0Nonzero"
| Case_aux c "ST_Pair1" | Case_aux c "ST_Pair2"
| Case_aux c "ST_Fst1" | Case_aux c "ST_FstPair"
| Case_aux c "ST_Snd1" | Case_aux c "ST_SndPair"
(* FILL IN HERE *)
| Case_aux c "ST_Inl" | Case_aux c "ST_Inr" | Case_aux c "ST_Case"
| Case_aux c "ST_CaseInl" | Case_aux c "ST_CaseInr"
| Case_aux c "ST_Cons1" | Case_aux c "ST_Cons2" | Case_aux c "ST_Lcase1"
| Case_aux c "ST_LcaseNil" | Case_aux c "ST_LcaseCons"
(* FILL IN HERE *)
].
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Hint Constructors step.
(* ###################################################################### *)
(** *** Typing *)
Definition context := partial_map ty.
(** Next we define the typing rules. These are nearly direct
transcriptions of the inference rules shown above. *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Typing rules for proper terms *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
(* nats *)
| T_Nat : forall Gamma n1,
Gamma |- (tnat n1) \in TNat
| T_Succ : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tsucc t1) \in TNat
| T_Pred : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tpred t1) \in TNat
| T_Mult : forall Gamma t1 t2,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in TNat ->
Gamma |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma t1 t2 t3 T1,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in T1 ->
Gamma |- t3 \in T1 ->
Gamma |- (tif0 t1 t2 t3) \in T1
(* pairs *)
| T_Pair : forall Gamma t1 t2 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in T2 ->
Gamma |- (tpair t1 t2) \in (TProd T1 T2)
| T_Fst : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tfst t) \in T1
| T_Snd : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tsnd t) \in T2
(* unit *)
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* let *)
(* FILL IN HERE *)
(* sums *)
| T_Inl : forall Gamma t1 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- (tinl T2 t1) \in (TSum T1 T2)
| T_Inr : forall Gamma t2 T1 T2,
Gamma |- t2 \in T2 ->
Gamma |- (tinr T1 t2) \in (TSum T1 T2)
| T_Case : forall Gamma t0 x1 T1 t1 x2 T2 t2 T,
Gamma |- t0 \in (TSum T1 T2) ->
(extend Gamma x1 T1) |- t1 \in T ->
(extend Gamma x2 T2) |- t2 \in T ->
Gamma |- (tcase t0 x1 t1 x2 t2) \in T
(* lists *)
| T_Nil : forall Gamma T,
Gamma |- (tnil T) \in (TList T)
| T_Cons : forall Gamma t1 t2 T1,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in (TList T1) ->
Gamma |- (tcons t1 t2) \in (TList T1)
| T_Lcase : forall Gamma t1 T1 t2 x1 x2 t3 T2,
Gamma |- t1 \in (TList T1) ->
Gamma |- t2 \in T2 ->
(extend (extend Gamma x2 (TList T1)) x1 T1) |- t3 \in T2 ->
Gamma |- (tlcase t1 t2 x1 x2 t3) \in T2
(* fix *)
(* FILL IN HERE *)
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd"
| Case_aux c "T_Unit"
(* let *)
(* FILL IN HERE *)
| Case_aux c "T_Inl" | Case_aux c "T_Inr" | Case_aux c "T_Case"
| Case_aux c "T_Nil" | Case_aux c "T_Cons" | Case_aux c "T_Lcase"
(* fix *)
(* FILL IN HERE *)
].
(* ###################################################################### *)
(** ** Examples *)
(** This section presents formalized versions of the examples from
above (plus several more). The ones at the beginning focus on
specific features; you can use these to make sure your definition
of a given feature is reasonable before moving on to extending the
proofs later in the file with the cases relating to this feature.
The later examples require all the features together, so you'll
need to come back to these when you've got all the definitions
filled in. *)
Module Examples.
(** *** Preliminaries *)
(** First, let's define a few variable names: *)
Notation a := (Id 0).
Notation f := (Id 1).
Notation g := (Id 2).
Notation l := (Id 3).
Notation k := (Id 6).
Notation i1 := (Id 7).
Notation i2 := (Id 8).
Notation x := (Id 9).
Notation y := (Id 10).
Notation processSum := (Id 11).
Notation n := (Id 12).
Notation eq := (Id 13).
Notation m := (Id 14).
Notation evenodd := (Id 15).
Notation even := (Id 16).
Notation odd := (Id 17).
Notation eo := (Id 18).
(** Next, a bit of Coq hackery to automate searching for typing
derivations. You don't need to understand this bit in detail --
just have a look over it so that you'll know what to look for if
you ever find yourself needing to make custom extensions to
[auto].
The following [Hint] declarations say that, whenever [auto]
arrives at a goal of the form [(Gamma |- (tapp e1 e1) \in T)], it
should consider [eapply T_App], leaving an existential variable
for the middle type T1, and similar for [lcase]. That variable
will then be filled in during the search for type derivations for
[e1] and [e2]. We also include a hint to "try harder" when
solving equality goals; this is useful to automate uses of
[T_Var] (which includes an equality as a precondition). *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
(* You'll want to uncomment the following line once
you've defined the [T_Lcase] constructor for the typing
relation: *)
(*
Hint Extern 2 (has_type _ (tlcase _ _ _ _ _) _) =>
eapply T_Lcase; auto.
*)
Hint Extern 2 (_ = _) => compute; reflexivity.
(** *** Numbers *)
Module Numtest.
(* if0 (pred (succ (pred (2 * 0))) then 5 else 6 *)
Definition test :=
tif0
(tpred
(tsucc
(tpred
(tmult
(tnat 2)
(tnat 0)))))
(tnat 5)
(tnat 6).
(** Remove the comment braces once you've implemented enough of the
definitions that you think this should work. *)
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof.
unfold test.
(* This typing derivation is quite deep, so we need to increase the
max search depth of [auto] from the default 5 to 10. *)
auto 10.
Qed.
Example numtest_reduces :
test ==>* tnat 5.
Proof.
unfold test. normalize.
Qed.
*)
End Numtest.
(** *** Products *)
Module Prodtest.
(* ((5,6),7).fst.snd *)
Definition test :=
tsnd
(tfst
(tpair
(tpair
(tnat 5)
(tnat 6))
(tnat 7))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End Prodtest.
(** *** [let] *)
Module LetTest.
(* let x = pred 6 in succ x *)
Definition test :=
tlet
x
(tpred (tnat 6))
(tsucc (tvar x)).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End LetTest.
(** *** Sums *)
Module Sumtest1.
(* case (inl Nat 5) of
inl x => x
| inr y => y *)
Definition test :=
tcase (tinl TNat (tnat 5))
x (tvar x)
y (tvar y).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tnat 5).
Proof. unfold test. normalize. Qed.
*)
End Sumtest1.
Module Sumtest2.
(* let processSum =
\x:Nat+Nat.
case x of
inl n => n
inr n => if0 n then 1 else 0 in
(processSum (inl Nat 5), processSum (inr Nat 5)) *)
Definition test :=
tlet
processSum
(tabs x (TSum TNat TNat)
(tcase (tvar x)
n (tvar n)
n (tif0 (tvar n) (tnat 1) (tnat 0))))
(tpair
(tapp (tvar processSum) (tinl TNat (tnat 5)))
(tapp (tvar processSum) (tinr TNat (tnat 5)))).
(*
Example typechecks :
(@empty ty) |- test \in (TProd TNat TNat).
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tpair (tnat 5) (tnat 0)).
Proof. unfold test. normalize. Qed.
*)
End Sumtest2.
(** *** Lists *)
Module ListTest.
(* let l = cons 5 (cons 6 (nil Nat)) in
lcase l of
nil => 0
| x::y => x*x *)
Definition test :=
tlet l
(tcons (tnat 5) (tcons (tnat 6) (tnil TNat)))
(tlcase (tvar l)
(tnat 0)
x y (tmult (tvar x) (tvar x))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 20. Qed.
Example reduces :
test ==>* (tnat 25).
Proof. unfold test. normalize. Qed.
*)
End ListTest.
(** *** [fix] *)
Module FixTest1.
(* fact := fix
(\f:nat->nat.
\a:nat.
if a=0 then 1 else a * (f (pred a))) *)
Definition fact :=
tfix
(tabs f (TArrow TNat TNat)
(tabs a TNat
(tif0
(tvar a)
(tnat 1)
(tmult
(tvar a)
(tapp (tvar f) (tpred (tvar a))))))).
(** (Warning: you may be able to typecheck [fact] but still have some
rules wrong!) *)
(*
Example fact_typechecks :
(@empty ty) |- fact \in (TArrow TNat TNat).
Proof. unfold fact. auto 10.
Qed.
*)
(*
Example fact_example:
(tapp fact (tnat 4)) ==>* (tnat 24).
Proof. unfold fact. normalize. Qed.
*)
End FixTest1.
Module FixTest2.
(* map :=
\g:nat->nat.
fix
(\f:[nat]->[nat].
\l:[nat].
case l of
| [] -> []
| x::l -> (g x)::(f l)) *)
Definition map :=
tabs g (TArrow TNat TNat)
(tfix
(tabs f (TArrow (TList TNat) (TList TNat))
(tabs l (TList TNat)
(tlcase (tvar l)
(tnil TNat)
a l (tcons (tapp (tvar g) (tvar a))
(tapp (tvar f) (tvar l))))))).
(*
(* Make sure you've uncommented the last [Hint Extern] above... *)
Example map_typechecks :
empty |- map \in
(TArrow (TArrow TNat TNat)
(TArrow (TList TNat)
(TList TNat))).
Proof. unfold map. auto 10. Qed.
Example map_example :
tapp (tapp map (tabs a TNat (tsucc (tvar a))))
(tcons (tnat 1) (tcons (tnat 2) (tnil TNat)))
==>* (tcons (tnat 2) (tcons (tnat 3) (tnil TNat))).
Proof. unfold map. normalize. Qed.
*)
End FixTest2.
Module FixTest3.
(* equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if0 m then (if0 n then 1 else 0)
else if0 n then 0
else eq (pred m) (pred n)) *)
Definition equal :=
tfix
(tabs eq (TArrow TNat (TArrow TNat TNat))
(tabs m TNat
(tabs n TNat
(tif0 (tvar m)
(tif0 (tvar n) (tnat 1) (tnat 0))
(tif0 (tvar n)
(tnat 0)
(tapp (tapp (tvar eq)
(tpred (tvar m)))
(tpred (tvar n)))))))).
(*
Example equal_typechecks :
(@empty ty) |- equal \in (TArrow TNat (TArrow TNat TNat)).
Proof. unfold equal. auto 10.
Qed.
*)
(*
Example equal_example1:
(tapp (tapp equal (tnat 4)) (tnat 4)) ==>* (tnat 1).
Proof. unfold equal. normalize. Qed.
*)
(*
Example equal_example2:
(tapp (tapp equal (tnat 4)) (tnat 5)) ==>* (tnat 0).
Proof. unfold equal. normalize. Qed.
*)
End FixTest3.
Module FixTest4.
(* let evenodd =
fix
(\eo: (Nat->Nat * Nat->Nat).
let e = \n:Nat. if0 n then 1 else eo.snd (pred n) in
let o = \n:Nat. if0 n then 0 else eo.fst (pred n) in
(e,o)) in
let even = evenodd.fst in
let odd = evenodd.snd in
(even 3, even 4)
*)
Definition eotest :=
tlet evenodd
(tfix
(tabs eo (TProd (TArrow TNat TNat) (TArrow TNat TNat))
(tpair
(tabs n TNat
(tif0 (tvar n)
(tnat 1)
(tapp (tsnd (tvar eo)) (tpred (tvar n)))))
(tabs n TNat
(tif0 (tvar n)
(tnat 0)
(tapp (tfst (tvar eo)) (tpred (tvar n))))))))
(tlet even (tfst (tvar evenodd))
(tlet odd (tsnd (tvar evenodd))
(tpair
(tapp (tvar even) (tnat 3))
(tapp (tvar even) (tnat 4))))).
(*
Example eotest_typechecks :
(@empty ty) |- eotest \in (TProd TNat TNat).
Proof. unfold eotest. eauto 30.
Qed.
*)
(*
Example eotest_example1:
eotest ==>* (tpair (tnat 0) (tnat 1)).
Proof. unfold eotest. normalize. Qed.
*)
End FixTest4.
End Examples.
(* ###################################################################### *)
(** ** Properties of Typing *)
(** The proofs of progress and preservation for this system are
essentially the same (though of course somewhat longer) as for the
pure simply typed lambda-calculus. *)
(* ###################################################################### *)
(** *** Progress *)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
(* Theorem: Suppose empty |- t : T. Then either
1. t is a value, or
2. t ==> t' for some t'.
Proof: By induction on the given typing derivation. *)
intros t T Ht.
remember (@empty ty) as Gamma.
generalize dependent HeqGamma.
has_type_cases (induction Ht) Case; intros HeqGamma; subst.
Case "T_Var".
(* The final rule in the given typing derivation cannot be [T_Var],
since it can never be the case that [empty |- x : T] (since the
context is empty). *)
inversion H.
Case "T_Abs".
(* If the [T_Abs] rule was the last used, then [t = tabs x T11 t12],
which is a value. *)
left...
Case "T_App".
(* If the last rule applied was T_App, then [t = t1 t2], and we know
from the form of the rule that
[empty |- t1 : T1 -> T2]
[empty |- t2 : T1]
By the induction hypothesis, each of t1 and t2 either is a value
or can take a step. *)
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
(* If both [t1] and [t2] are values, then we know that
[t1 = tabs x T11 t12], since abstractions are the only values
that can have an arrow type. But
[(tabs x T11 t12) t2 ==> [x:=t2]t12] by [ST_AppAbs]. *)
inversion H; subst; try (solve by inversion).
exists (subst x t2 t12)...
SSCase "t2 steps".
(* If [t1] is a value and [t2 ==> t2'], then [t1 t2 ==> t1 t2']
by [ST_App2]. *)
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
(* Finally, If [t1 ==> t1'], then [t1 t2 ==> t1' t2] by [ST_App1]. *)
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_Nat".
left...
Case "T_Succ".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (S n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsucc t1')...
Case "T_Pred".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (pred n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tpred t1')...
Case "T_Mult".
right.
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 is a value".
inversion H; subst; try solve by inversion.
inversion H0; subst; try solve by inversion.
exists (tnat (mult n1 n0))...
SSCase "t2 steps".
inversion H0 as [t2' Hstp].
exists (tmult t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tmult t1' t2)...
Case "T_If0".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
destruct n1 as [|n1'].
SSCase "n1=0".
exists t2...
SSCase "n1<>0".
exists t3...
SCase "t1 steps".
inversion H as [t1' H0].
exists (tif0 t1' t2 t3)...
Case "T_Pair".
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 steps".
right. inversion H0 as [t2' Hstp].
exists (tpair t1 t2')...
SCase "t1 steps".
right. inversion H as [t1' Hstp].
exists (tpair t1' t2)...
Case "T_Fst".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v1...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tfst t1')...
Case "T_Snd".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v2...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsnd t1')...
Case "T_Unit".
left...
(* let *)
(* FILL IN HERE *)
Case "T_Inl".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinl _ t1')... *)
Case "T_Inr".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinr _ t1')... *)
Case "T_Case".
right.
destruct IHHt1...
SCase "t0 is a value".
inversion H; subst; try solve by inversion.
SSCase "t0 is inl".
exists ([x1:=v]t1)...
SSCase "t0 is inr".
exists ([x2:=v]t2)...
SCase "t0 steps".
inversion H as [t0' Hstp].
exists (tcase t0' x1 t1 x2 t2)...
Case "T_Nil".
left...
Case "T_Cons".
destruct IHHt1...
SCase "head is a value".
destruct IHHt2...
SSCase "tail steps".
right. inversion H0 as [t2' Hstp].
exists (tcons t1 t2')...
SCase "head steps".
right. inversion H as [t1' Hstp].
exists (tcons t1' t2)...
Case "T_Lcase".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
SSCase "t1=tnil".
exists t2...
SSCase "t1=tcons v1 vl".
exists ([x2:=vl]([x1:=v1]t3))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tlcase t1' t2 x1 x2 t3)...
(* fix *)
(* FILL IN HERE *)
Qed.
(* ###################################################################### *)
(** *** Context Invariance *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
(* nats *)
| afi_succ : forall x t,
appears_free_in x t ->
appears_free_in x (tsucc t)
| afi_pred : forall x t,
appears_free_in x t ->
appears_free_in x (tpred t)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if01 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if02 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if03 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
(* pairs *)
| afi_pair1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tpair t1 t2)
| afi_pair2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tpair t1 t2)
| afi_fst : forall x t,
appears_free_in x t ->
appears_free_in x (tfst t)
| afi_snd : forall x t,
appears_free_in x t ->
appears_free_in x (tsnd t)
(* let *)
(* FILL IN HERE *)
(* sums *)
| afi_inl : forall x t T,
appears_free_in x t ->
appears_free_in x (tinl T t)
| afi_inr : forall x t T,
appears_free_in x t ->
appears_free_in x (tinr T t)
| afi_case0 : forall x t0 x1 t1 x2 t2,
appears_free_in x t0 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case1 : forall x t0 x1 t1 x2 t2,
x1 <> x ->
appears_free_in x t1 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case2 : forall x t0 x1 t1 x2 t2,
x2 <> x ->
appears_free_in x t2 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
(* lists *)
| afi_cons1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tcons t1 t2)
| afi_cons2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tcons t1 t2)
| afi_lcase1 : forall x t1 t2 y1 y2 t3,
appears_free_in x t1 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase2 : forall x t1 t2 y1 y2 t3,
appears_free_in x t2 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase3 : forall x t1 t2 y1 y2 t3,
y1 <> x ->
y2 <> x ->
appears_free_in x t3 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
(* fix *)
(* FILL IN HERE *)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros y Hafi.
unfold extend.
destruct (eq_id_dec x y)...
Case "T_Mult".
apply T_Mult...
Case "T_If0".
apply T_If0...
Case "T_Pair".
apply T_Pair...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
eapply T_Case...
apply IHhas_type2. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x2 y)...
Case "T_Cons".
apply T_Cons...
Case "T_Lcase".
eapply T_Lcase... apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
destruct (eq_id_dec x2 y)...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case; inversion Hafi; subst...
Case "T_Abs".
destruct IHHtyp as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "left".
destruct IHHtyp2 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
SCase "right".
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
Case "T_Lcase".
clear Htyp1 IHHtyp1 Htyp2 IHHtyp2.
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx... rewrite neq_id in Hctx...
Qed.
(* ###################################################################### *)
(** *** Substitution *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
(* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then
Gamma |- [x:=v]t : S. *)
intros Gamma x U v t S Htypt Htypv.
generalize dependent Gamma. generalize dependent S.
(* Proof: By induction on the term t. Most cases follow directly
from the IH, with the exception of tvar and tabs.
The former aren't automatic because we must reason about how the
variables interact. *)
t_cases (induction t) Case;
intros S Gamma Htypt; simpl; inversion Htypt; subst...
Case "tvar".
simpl. rename i into y.
(* If t = y, we know that
[empty |- v : U] and
[Gamma,x:U |- y : S]
and, by inversion, [extend Gamma x U y = Some S]. We want to
show that [Gamma |- [x:=v]y : S].
There are two cases to consider: either [x=y] or [x<>y]. *)
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then we know that [U = S], and that [[x:=v]y = v].
So what we really must show is that if [empty |- v : U] then
[Gamma |- v : U]. We have already proven a more general version
of this theorem, called context invariance. *)
subst.
unfold extend in H1. rewrite eq_id in H1.
inversion H1; subst. clear H1.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
(* If [x <> y], then [Gamma y = Some S] and the substitution has no
effect. We can show that [Gamma |- y : S] by [T_Var]. *)
apply T_Var... unfold extend in H1. rewrite neq_id in H1...
Case "tabs".
rename i into y. rename t into T11.
(* If [t = tabs y T11 t0], then we know that
[Gamma,x:U |- tabs y T11 t0 : T11->T12]
[Gamma,x:U,y:T11 |- t0 : T12]
[empty |- v : U]
As our IH, we know that forall S Gamma,
[Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 : S].
We can calculate that
[x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0)
And we must show that [Gamma |- [x:=v]t : T11->T12]. We know
we will do so using [T_Abs], so it remains to be shown that:
[Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12]
We consider two cases: [x = y] and [x <> y].
*)
apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then the substitution has no effect. Context
invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are
equivalent. Since the former context shows that [t0 : T12], so
does the latter. *)
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
(* If [x <> y], then the IH and context invariance allow us to show that
[Gamma,x:U,y:T11 |- t0 : T12] =>
[Gamma,y:T11,x:U |- t0 : T12] =>
[Gamma,y:T11 |- [x:=v]t0 : T12] *)
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
(* let *)
(* FILL IN HERE *)
Case "tcase".
rename i into x1. rename i0 into x2.
eapply T_Case...
SCase "left arm".
destruct (eq_id_dec x x1).
SSCase "x = x1".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
SSCase "x <> x1".
apply IHt2. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
subst. rewrite neq_id...
SCase "right arm".
destruct (eq_id_dec x x2).
SSCase "x = x2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
SSCase "x <> x2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
subst. rewrite neq_id...
Case "tlcase".
rename i into y1. rename i0 into y2.
eapply T_Lcase...
destruct (eq_id_dec x y1).
SCase "x=y1".
simpl.
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
SCase "x<>y1".
destruct (eq_id_dec x y2).
SSCase "x=y2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y2 z)...
SSCase "x<>y2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
subst. rewrite neq_id...
destruct (eq_id_dec y2 z)...
subst. rewrite neq_id...
Qed.
(* ###################################################################### *)
(** *** Preservation *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
(* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *)
remember (@empty ty) as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
(* Proof: By induction on the given typing derivation. Many cases are
contradictory ([T_Var], [T_Abs]). We show just the interesting ones. *)
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
(* If the last rule used was [T_App], then [t = t1 t2], and three rules
could have been used to show [t ==> t']: [ST_App1], [ST_App2], and
[ST_AppAbs]. In the first two cases, the result follows directly from
the IH. *)
inversion HE; subst...
SCase "ST_AppAbs".
(* For the third case, suppose
[t1 = tabs x T11 t12]
and
[t2 = v2].
We must show that [empty |- [x:=v2]t12 : T2].
We know by assumption that
[empty |- tabs x T11 t12 : T1->T2]
and by inversion
[x:T1 |- t12 : T2]
We have already proven that substitution_preserves_typing and
[empty |- v2 : T1]
by assumption, so we are done. *)
apply substitution_preserves_typing with T1...
inversion HT1...
Case "T_Fst".
inversion HT...
Case "T_Snd".
inversion HT...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "ST_CaseInl".
inversion HT1; subst.
eapply substitution_preserves_typing...
SCase "ST_CaseInr".
inversion HT1; subst.
eapply substitution_preserves_typing...
Case "T_Lcase".
SCase "ST_LcaseCons".
inversion HT1; subst.
apply substitution_preserves_typing with (TList T1)...
apply substitution_preserves_typing with T1...
(* fix *)
(* FILL IN HERE *)
Qed.
(** [] *)
End STLCExtended.
(* $Date: 2014-12-01 15:15:02 -0500 (Mon, 01 Dec 2014) $ *)
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_address_to_bankaddress #(
parameter integer ADDRESS_W = 32, // > 0
parameter integer NUM_BANKS = 2, // > 1
parameter integer BANK_SEL_BIT = ADDRESS_W-$clog2(NUM_BANKS)
)
(
input logic [ADDRESS_W-1:0] address,
output logic [NUM_BANKS-1:0] bank_sel, // one-hot
output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] bank_address
);
integer i;
// To support NUM_BANKS=1 we need a wider address
logic [ADDRESS_W:0] wider_address;
assign wider_address = {1'b0,address};
always@*
begin
for (i=0; i<NUM_BANKS; i=i+1)
bank_sel[i] = (wider_address[BANK_SEL_BIT+$clog2(NUM_BANKS)-1 : BANK_SEL_BIT] == i);
end
assign bank_address = ((address>>(BANK_SEL_BIT+$clog2(NUM_BANKS)))<<(BANK_SEL_BIT)) |
// Take address[BANKS_SEL_BIT-1:0] in a manner that allows BANK_SEL_BIT=0
((~({ADDRESS_W{1'b1}}<<BANK_SEL_BIT)) & address);
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_address_to_bankaddress #(
parameter integer ADDRESS_W = 32, // > 0
parameter integer NUM_BANKS = 2, // > 1
parameter integer BANK_SEL_BIT = ADDRESS_W-$clog2(NUM_BANKS)
)
(
input logic [ADDRESS_W-1:0] address,
output logic [NUM_BANKS-1:0] bank_sel, // one-hot
output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] bank_address
);
integer i;
// To support NUM_BANKS=1 we need a wider address
logic [ADDRESS_W:0] wider_address;
assign wider_address = {1'b0,address};
always@*
begin
for (i=0; i<NUM_BANKS; i=i+1)
bank_sel[i] = (wider_address[BANK_SEL_BIT+$clog2(NUM_BANKS)-1 : BANK_SEL_BIT] == i);
end
assign bank_address = ((address>>(BANK_SEL_BIT+$clog2(NUM_BANKS)))<<(BANK_SEL_BIT)) |
// Take address[BANKS_SEL_BIT-1:0] in a manner that allows BANK_SEL_BIT=0
((~({ADDRESS_W{1'b1}}<<BANK_SEL_BIT)) & address);
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2011 by Wilson Snyder.
// bug420
typedef logic [7-1:0] wb_ind_t;
typedef logic [7-1:0] id_t;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [31:0] in = crc[31:0];
/*AUTOWIRE*/
wire [6:0] out = line_wb_ind( in[6:0] );
// Aggregate outputs into a single result vector
wire [63:0] result = {57'h0, out};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'hc918fa0aa882a206
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
function wb_ind_t line_wb_ind( id_t id );
if( id[$bits(id_t)-1] == 0 )
return {2'b00, id[$bits(wb_ind_t)-3:0]};
else
return {2'b01, id[$bits(wb_ind_t)-3:0]};
endfunction // line_wb_ind
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 09:14:57 AM
// Design Name:
// Module Name: FSM_test
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FSM_test
(
input wire clk,
input wire rst,
input wire ready_op,
input wire max_tick_address,
input wire max_tick_ch,
input wire TX_DONE,
output reg beg_op,
output reg ack_op,
output reg load_address,
output reg enab_address,
output reg enab_ch,
output reg load_ch,
output reg TX_START
);
//symbolic state declaration
localparam [3:0] est0 = 4'b0000,
est1 = 4'b0001,
est2 = 4'b0010,
est3 = 4'b0011,
est4 = 4'b0100,
est5 = 4'b0101,
est6 = 4'b0110,
est7 = 4'b0111,
est8 = 4'b1000,
est9 = 4'b1001,
est10 = 4'b1010,
est11 = 4'b1011;
//signal declaration
reg [3:0] state_reg, state_next; // Guardan el estado actual y el estado futuro, respectivamente.
//state register
always @( posedge clk, posedge rst)
begin
if(rst) // Si hay reset, el estado actual es el estado inicial.
state_reg <= est0;
else //Si no hay reset el estado actual es igual al estado siguiente.
state_reg <= state_next;
end
//next-state logic and output logic
always @*
begin
state_next = state_reg; // default state : the same
//declaration of default outputs.
beg_op = 1'b0;
ack_op = 1'b0;
load_address = 1'b0;
enab_address = 1'b0;
enab_ch = 1'b0;
load_ch = 1'b0;
TX_START = 1'b0;
case(state_reg)
est0:
begin
state_next = est1;
end
est1:
begin
load_address = 1'b1;
enab_address = 1'b1;
state_next = est2;
end
est2:
begin
beg_op = 1'b1;
state_next=est3;
end
est3:
begin
beg_op = 1'b1;
enab_ch = 1'b1;
load_ch = 1'b1;
state_next=est4;
end
est4:
begin
if(ready_op)
state_next=est5;
else
state_next=est4;
end
est5:
begin
state_next=est6;
end
est6:
begin
TX_START = 1'b1;
state_next=est7;
end
est7:
begin
if(TX_DONE)
if(max_tick_ch)
state_next=est9;
else
begin
state_next=est8;
end
else
state_next=est7;
end
est8:
begin
enab_ch = 1'b1;
state_next=est5;
end
est9:
begin
if(max_tick_address)
state_next=est11;
else
begin
state_next=est10;
end
end
est10:
begin
enab_address = 1'b1;
ack_op = 1'b1;
state_next=est2;
end
est11:
begin
state_next=est11;
end
default:
state_next=est0;
endcase
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for in-order coalesced memory access.
//
// Properties - Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// (see lsu_top.v for details)
//
// Description: Requests are submitted as soon as possible to memory, stalled
// requests are coalesced with neighbouring requests if they
// access the same page of memory.
// Basic coalesced read unit:
// Accept read requests on the upstream interface. Requests are sent to
// the avalon bus as soon as they are recieved. If the avalon bus is
// stalling, requests to the same global-memory word are coalesced into
// a single request to improve efficiency.
//
// The request FIFO stores the byte-address to select the appropriate word
// out of the response data as well as an extra bit to indicate if the
// request is coalesced with the previous request or if a new request was
// made. The output port looks ahead to the next pending request to
// determine whether the current response data can be thrown away or
// must be kept to service the next coalesced request.
module lsu_basic_coalesced_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Determines the max number of live requests.
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
// Constants
localparam REQUEST_FIFO_DEPTH=2*KERNEL_SIDE_MEM_LATENCY;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire [SEGMENT_SELECT_BITS:0] rf_data_in;
wire [BYTE_SELECT_BITS-1:0] byte_addr;
wire next_new_page;
wire c_stall;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire rf_full;
wire rf_valid;
wire [SEGMENT_SELECT_BITS:0] rf_data;
wire rf_next_valid;
wire [SEGMENT_SELECT_BITS:0] rf_next_data;
wire rf_stall_in;
wire rm_stall;
wire rm_valid;
wire rm_active;
wire [MWIDTH-1:0] rm_data;
wire rm_stall_in;
// Coalescer - Groups subsequent requests together if they are compatible and
// the avalon bus is stalled.
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !rf_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(rm_stall)
);
// Response FIFO - Buffers the requests so they can be extracted from the
// wider memory bus. Stores the segment address to extract the requested
// word from the response data, and a bit indicating if the request comes
// from a new page.
generate if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_addr;
assign segment_addr = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
assign rf_data_in = {c_new_page, segment_addr};
assign byte_addr = (rf_data[SEGMENT_SELECT_BITS-1:0] << ALIGNMENT_ABITS);
end
else
begin
assign rf_data_in = c_new_page;
assign byte_addr = {BYTE_SELECT_BITS{1'b0}};
end
endgenerate
lookahead_fifo #(
.WIDTH( SEGMENT_SELECT_BITS + 1 ),
.DEPTH( REQUEST_FIFO_DEPTH )
) request_fifo (
.clk(clk),
.reset(reset),
.i_data( rf_data_in ),
.i_valid( i_valid && !c_stall ),
.o_full(rf_full),
.i_stall(rf_stall_in),
.o_valid(rf_valid),
.o_data(rf_data),
.o_next_valid(rf_next_valid),
.o_next_data(rf_next_data)
);
// Read master - Handles pipelined read transactions through MM-Avalon.
lsu_pipelined_read #(
.AWIDTH( AWIDTH ),
.WIDTH_BYTES( MWIDTH_BYTES ),
.MWIDTH_BYTES( MWIDTH_BYTES ),
.ALIGNMENT_ABITS( BYTE_SELECT_BITS ),
.KERNEL_SIDE_MEM_LATENCY( KERNEL_SIDE_MEM_LATENCY ),
.USEOUTPUTFIFO(1),
.USEINPUTFIFO( 1 ), // Add the latency adjusting input fifos
.PIPELINE_INPUT( 1 ) // Let's add a pipline input to the input side just to help with Fmax
) read_master (
.clk(clk),
.reset(reset),
.o_stall(rm_stall),
.i_valid(c_req_valid),
.i_address({c_req_addr, {BYTE_SELECT_BITS{1'b0}}}),
.i_stall(rm_stall_in),
.o_valid(rm_valid),
.o_active(rm_active),
.o_readdata(rm_data),
.avm_address(avm_address),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
// Control logic
// Highest bit of rf_next_data indicates whether this is a new avalon request
// (new page) or was coalesced into the previous request.
assign next_new_page = rf_next_data[SEGMENT_SELECT_BITS];
assign rm_stall_in = (!next_new_page && rf_next_valid) || rf_stall_in;
assign rf_stall_in = i_stall || !rm_valid;
// Output MUX
assign o_readdata = rm_data[8*byte_addr +: WIDTH];
// External control signals
assign o_stall = c_stall || rf_full;
assign o_valid = rm_valid && rf_valid;
assign o_active=rf_valid | rm_active;
endmodule
/******************************************************************************/
// Basic coalesced write unit:
// Accept write requests on the upstream interface. The avalon spec does
// not allow a request to change while it is being stalled, so the current
// request is registered in an output register stage and not modified.
// Subsequent requests are coalesced together as long as the output register
// stage is occupied (i.e. the avalon bus is stalling).
//
// TODO: The byte enable format is not actually compliant with the
// Avalon spec. Essentially we should not enable non-adjacent words in a write
// request. This is OK for the DDR Memory Controller as it accepts our
// non-compliant format. This needs to be investigated further.
module lsu_basic_coalesced_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter USE_BYTE_EN;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
// Constants
localparam COUNTER_WIDTH=8; // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
input [WIDTH_BYTES-1:0] i_byteenable;
/***************
* Architecture *
***************/
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [COUNTER_WIDTH-1:0] or_next_counter;
wire [COUNTER_WIDTH-1:0] rf_count;
wire rf_read;
wire rf_empty;
wire rf_full;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire or_ready;
reg or_write;
reg [AWIDTH-1:0] or_address;
reg [MWIDTH-1:0] or_writedata;
reg [MWIDTH_BYTES-1:0] or_byteenable;
wire oc_full;
// Output register stage to store the next request
assign or_ready = !or_write || !avm_waitrequest;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
or_write <= 1'b0;
or_address <= {AWIDTH{1'b0}};
or_writedata <= {MWIDTH{1'b0}};
or_byteenable <= {MWIDTH_BYTES{1'b0}};
or_next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
if(or_ready)
begin
or_write <= c_req_valid;
or_address <= (c_req_addr << BYTE_SELECT_BITS);
or_writedata <= wm_writedata;
or_byteenable <= wm_byteenable;
or_next_counter <= next_counter;
end
end
end
assign avm_address = or_address;
assign avm_write = or_write;
assign avm_writedata = or_writedata;
assign avm_byteenable = or_byteenable;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(!or_ready)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[segment_select*SEGMENT_WIDTH +: WIDTH] = {WIDTH{1'b1}};
end
end
else
begin
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}} ;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = {WIDTH{1'b1}};
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
// Write size tracker - track the number of threads represented by each pending write request
acl_ll_fifo #(
.WIDTH(COUNTER_WIDTH),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) req_fifo (
.clk(clk),
.reset(reset),
.data_in( or_next_counter ),
.data_out( rf_count ),
.write( write_accepted && (!rf_empty || !avm_writeack) ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
assign rf_read = avm_writeack && !rf_empty;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
assign input_accepted = i_valid && !o_stall;
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
occ_counter <= occ_counter + input_accepted - output_acknowledged;
next_counter <= input_accepted + ((c_req_valid & or_ready) ? {COUNTER_WIDTH{1'b0}} : next_counter);
ack_counter <= ack_counter + ({COUNTER_WIDTH{avm_writeack}} & ( rf_empty ? or_next_counter : rf_count )) - output_acknowledged;
end
end
assign oc_full = (occ_counter == {COUNTER_WIDTH{1'b1}});
// Pipeline control signals
assign o_stall = oc_full || c_stall || rf_full;
assign o_valid = (ack_counter > {COUNTER_WIDTH{1'b0}});
assign o_active = (occ_counter != {COUNTER_WIDTH{1'b0}});
endmodule
/******************************************************************************/
/* RESPONSE FIFO */
// lookahead_fifo - A simple sc_fifo instantiation with an additional
// shift-register stage at the end to provide access to the next two data
// items.
module lookahead_fifo
(
clk, reset, i_data, i_valid, o_full, i_stall, o_valid, o_data,
o_next_valid, o_next_data
);
parameter WIDTH=32;
parameter DEPTH=32;
input clk;
input reset;
input [WIDTH-1:0] i_data;
input i_valid;
output o_full;
input i_stall;
output reg o_valid;
output reg [WIDTH-1:0] o_data;
output o_next_valid;
output [WIDTH-1:0] o_next_data;
wire sr_ready;
// Fifo
acl_data_fifo #(
.DATA_WIDTH(WIDTH),
.DEPTH(DEPTH),
.IMPL("ram_plus_reg")
) req_fifo (
.clock(clk),
.resetn(!reset),
.data_in( i_data ),
.data_out( o_next_data ),
.valid_in( i_valid ),
.valid_out( o_next_valid ),
.stall_in( !sr_ready ),
.stall_out( o_full )
);
// Shift-reg
assign sr_ready = !o_valid || !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
o_data <= {WIDTH{1'b0}};
o_valid <= 1'b0;
end
else
begin
o_valid <= sr_ready ? o_next_valid : o_valid;
o_data <= sr_ready ? o_next_data : o_data;
end
end
endmodule
/* BASIC COALESCING MODULE */
// basic_coalescer - Accept new inputs as long as the unit is not stalled,
// or the new request can be coalesced with the pending (stalled) request.
module basic_coalescer
(
clk, reset, i_page_addr, i_valid, o_stall, o_new_page, o_req_addr,
o_req_valid, i_stall
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8; // power of 2
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_valid;
output o_stall;
output o_new_page;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
input i_stall;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
assign timeout = timeout_counter[$clog2(TIMEOUT)];
// Internal signal logic
assign match = (i_page_addr == page_addr);
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
valid <= 1'b0;
timeout_counter <= '0;
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
valid <= ready ? i_valid : valid;
if( i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = i_valid && !match && !ready;
assign o_new_page = ready;
assign o_req_addr = page_addr;
assign o_req_valid = valid && !waiting;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for in-order coalesced memory access.
//
// Properties - Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// (see lsu_top.v for details)
//
// Description: Requests are submitted as soon as possible to memory, stalled
// requests are coalesced with neighbouring requests if they
// access the same page of memory.
// Basic coalesced read unit:
// Accept read requests on the upstream interface. Requests are sent to
// the avalon bus as soon as they are recieved. If the avalon bus is
// stalling, requests to the same global-memory word are coalesced into
// a single request to improve efficiency.
//
// The request FIFO stores the byte-address to select the appropriate word
// out of the response data as well as an extra bit to indicate if the
// request is coalesced with the previous request or if a new request was
// made. The output port looks ahead to the next pending request to
// determine whether the current response data can be thrown away or
// must be kept to service the next coalesced request.
module lsu_basic_coalesced_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Determines the max number of live requests.
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
// Constants
localparam REQUEST_FIFO_DEPTH=2*KERNEL_SIDE_MEM_LATENCY;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire [SEGMENT_SELECT_BITS:0] rf_data_in;
wire [BYTE_SELECT_BITS-1:0] byte_addr;
wire next_new_page;
wire c_stall;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire rf_full;
wire rf_valid;
wire [SEGMENT_SELECT_BITS:0] rf_data;
wire rf_next_valid;
wire [SEGMENT_SELECT_BITS:0] rf_next_data;
wire rf_stall_in;
wire rm_stall;
wire rm_valid;
wire rm_active;
wire [MWIDTH-1:0] rm_data;
wire rm_stall_in;
// Coalescer - Groups subsequent requests together if they are compatible and
// the avalon bus is stalled.
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !rf_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(rm_stall)
);
// Response FIFO - Buffers the requests so they can be extracted from the
// wider memory bus. Stores the segment address to extract the requested
// word from the response data, and a bit indicating if the request comes
// from a new page.
generate if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_addr;
assign segment_addr = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
assign rf_data_in = {c_new_page, segment_addr};
assign byte_addr = (rf_data[SEGMENT_SELECT_BITS-1:0] << ALIGNMENT_ABITS);
end
else
begin
assign rf_data_in = c_new_page;
assign byte_addr = {BYTE_SELECT_BITS{1'b0}};
end
endgenerate
lookahead_fifo #(
.WIDTH( SEGMENT_SELECT_BITS + 1 ),
.DEPTH( REQUEST_FIFO_DEPTH )
) request_fifo (
.clk(clk),
.reset(reset),
.i_data( rf_data_in ),
.i_valid( i_valid && !c_stall ),
.o_full(rf_full),
.i_stall(rf_stall_in),
.o_valid(rf_valid),
.o_data(rf_data),
.o_next_valid(rf_next_valid),
.o_next_data(rf_next_data)
);
// Read master - Handles pipelined read transactions through MM-Avalon.
lsu_pipelined_read #(
.AWIDTH( AWIDTH ),
.WIDTH_BYTES( MWIDTH_BYTES ),
.MWIDTH_BYTES( MWIDTH_BYTES ),
.ALIGNMENT_ABITS( BYTE_SELECT_BITS ),
.KERNEL_SIDE_MEM_LATENCY( KERNEL_SIDE_MEM_LATENCY ),
.USEOUTPUTFIFO(1),
.USEINPUTFIFO( 1 ), // Add the latency adjusting input fifos
.PIPELINE_INPUT( 1 ) // Let's add a pipline input to the input side just to help with Fmax
) read_master (
.clk(clk),
.reset(reset),
.o_stall(rm_stall),
.i_valid(c_req_valid),
.i_address({c_req_addr, {BYTE_SELECT_BITS{1'b0}}}),
.i_stall(rm_stall_in),
.o_valid(rm_valid),
.o_active(rm_active),
.o_readdata(rm_data),
.avm_address(avm_address),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
// Control logic
// Highest bit of rf_next_data indicates whether this is a new avalon request
// (new page) or was coalesced into the previous request.
assign next_new_page = rf_next_data[SEGMENT_SELECT_BITS];
assign rm_stall_in = (!next_new_page && rf_next_valid) || rf_stall_in;
assign rf_stall_in = i_stall || !rm_valid;
// Output MUX
assign o_readdata = rm_data[8*byte_addr +: WIDTH];
// External control signals
assign o_stall = c_stall || rf_full;
assign o_valid = rm_valid && rf_valid;
assign o_active=rf_valid | rm_active;
endmodule
/******************************************************************************/
// Basic coalesced write unit:
// Accept write requests on the upstream interface. The avalon spec does
// not allow a request to change while it is being stalled, so the current
// request is registered in an output register stage and not modified.
// Subsequent requests are coalesced together as long as the output register
// stage is occupied (i.e. the avalon bus is stalling).
//
// TODO: The byte enable format is not actually compliant with the
// Avalon spec. Essentially we should not enable non-adjacent words in a write
// request. This is OK for the DDR Memory Controller as it accepts our
// non-compliant format. This needs to be investigated further.
module lsu_basic_coalesced_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter USE_BYTE_EN;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
// Constants
localparam COUNTER_WIDTH=8; // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
input [WIDTH_BYTES-1:0] i_byteenable;
/***************
* Architecture *
***************/
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [COUNTER_WIDTH-1:0] or_next_counter;
wire [COUNTER_WIDTH-1:0] rf_count;
wire rf_read;
wire rf_empty;
wire rf_full;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire or_ready;
reg or_write;
reg [AWIDTH-1:0] or_address;
reg [MWIDTH-1:0] or_writedata;
reg [MWIDTH_BYTES-1:0] or_byteenable;
wire oc_full;
// Output register stage to store the next request
assign or_ready = !or_write || !avm_waitrequest;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
or_write <= 1'b0;
or_address <= {AWIDTH{1'b0}};
or_writedata <= {MWIDTH{1'b0}};
or_byteenable <= {MWIDTH_BYTES{1'b0}};
or_next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
if(or_ready)
begin
or_write <= c_req_valid;
or_address <= (c_req_addr << BYTE_SELECT_BITS);
or_writedata <= wm_writedata;
or_byteenable <= wm_byteenable;
or_next_counter <= next_counter;
end
end
end
assign avm_address = or_address;
assign avm_write = or_write;
assign avm_writedata = or_writedata;
assign avm_byteenable = or_byteenable;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(!or_ready)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[segment_select*SEGMENT_WIDTH +: WIDTH] = {WIDTH{1'b1}};
end
end
else
begin
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}} ;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = {WIDTH{1'b1}};
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
// Write size tracker - track the number of threads represented by each pending write request
acl_ll_fifo #(
.WIDTH(COUNTER_WIDTH),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) req_fifo (
.clk(clk),
.reset(reset),
.data_in( or_next_counter ),
.data_out( rf_count ),
.write( write_accepted && (!rf_empty || !avm_writeack) ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
assign rf_read = avm_writeack && !rf_empty;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
assign input_accepted = i_valid && !o_stall;
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
occ_counter <= occ_counter + input_accepted - output_acknowledged;
next_counter <= input_accepted + ((c_req_valid & or_ready) ? {COUNTER_WIDTH{1'b0}} : next_counter);
ack_counter <= ack_counter + ({COUNTER_WIDTH{avm_writeack}} & ( rf_empty ? or_next_counter : rf_count )) - output_acknowledged;
end
end
assign oc_full = (occ_counter == {COUNTER_WIDTH{1'b1}});
// Pipeline control signals
assign o_stall = oc_full || c_stall || rf_full;
assign o_valid = (ack_counter > {COUNTER_WIDTH{1'b0}});
assign o_active = (occ_counter != {COUNTER_WIDTH{1'b0}});
endmodule
/******************************************************************************/
/* RESPONSE FIFO */
// lookahead_fifo - A simple sc_fifo instantiation with an additional
// shift-register stage at the end to provide access to the next two data
// items.
module lookahead_fifo
(
clk, reset, i_data, i_valid, o_full, i_stall, o_valid, o_data,
o_next_valid, o_next_data
);
parameter WIDTH=32;
parameter DEPTH=32;
input clk;
input reset;
input [WIDTH-1:0] i_data;
input i_valid;
output o_full;
input i_stall;
output reg o_valid;
output reg [WIDTH-1:0] o_data;
output o_next_valid;
output [WIDTH-1:0] o_next_data;
wire sr_ready;
// Fifo
acl_data_fifo #(
.DATA_WIDTH(WIDTH),
.DEPTH(DEPTH),
.IMPL("ram_plus_reg")
) req_fifo (
.clock(clk),
.resetn(!reset),
.data_in( i_data ),
.data_out( o_next_data ),
.valid_in( i_valid ),
.valid_out( o_next_valid ),
.stall_in( !sr_ready ),
.stall_out( o_full )
);
// Shift-reg
assign sr_ready = !o_valid || !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
o_data <= {WIDTH{1'b0}};
o_valid <= 1'b0;
end
else
begin
o_valid <= sr_ready ? o_next_valid : o_valid;
o_data <= sr_ready ? o_next_data : o_data;
end
end
endmodule
/* BASIC COALESCING MODULE */
// basic_coalescer - Accept new inputs as long as the unit is not stalled,
// or the new request can be coalesced with the pending (stalled) request.
module basic_coalescer
(
clk, reset, i_page_addr, i_valid, o_stall, o_new_page, o_req_addr,
o_req_valid, i_stall
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8; // power of 2
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_valid;
output o_stall;
output o_new_page;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
input i_stall;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
assign timeout = timeout_counter[$clog2(TIMEOUT)];
// Internal signal logic
assign match = (i_page_addr == page_addr);
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
valid <= 1'b0;
timeout_counter <= '0;
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
valid <= ready ? i_valid : valid;
if( i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = i_valid && !match && !ready;
assign o_new_page = ready;
assign o_req_addr = page_addr;
assign o_req_valid = valid && !waiting;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for in-order coalesced memory access.
//
// Properties - Coalesced: Yes, Ordered: Yes, Hazard-Safe: Yes, Pipelined: Yes
// (see lsu_top.v for details)
//
// Description: Requests are submitted as soon as possible to memory, stalled
// requests are coalesced with neighbouring requests if they
// access the same page of memory.
// Basic coalesced read unit:
// Accept read requests on the upstream interface. Requests are sent to
// the avalon bus as soon as they are recieved. If the avalon bus is
// stalling, requests to the same global-memory word are coalesced into
// a single request to improve efficiency.
//
// The request FIFO stores the byte-address to select the appropriate word
// out of the response data as well as an extra bit to indicate if the
// request is coalesced with the previous request or if a new request was
// made. The output port looks ahead to the next pending request to
// determine whether the current response data can be thrown away or
// must be kept to service the next coalesced request.
module lsu_basic_coalesced_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Determines the max number of live requests.
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
// Constants
localparam REQUEST_FIFO_DEPTH=2*KERNEL_SIDE_MEM_LATENCY;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire [SEGMENT_SELECT_BITS:0] rf_data_in;
wire [BYTE_SELECT_BITS-1:0] byte_addr;
wire next_new_page;
wire c_stall;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire rf_full;
wire rf_valid;
wire [SEGMENT_SELECT_BITS:0] rf_data;
wire rf_next_valid;
wire [SEGMENT_SELECT_BITS:0] rf_next_data;
wire rf_stall_in;
wire rm_stall;
wire rm_valid;
wire rm_active;
wire [MWIDTH-1:0] rm_data;
wire rm_stall_in;
// Coalescer - Groups subsequent requests together if they are compatible and
// the avalon bus is stalled.
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !rf_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(rm_stall)
);
// Response FIFO - Buffers the requests so they can be extracted from the
// wider memory bus. Stores the segment address to extract the requested
// word from the response data, and a bit indicating if the request comes
// from a new page.
generate if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_addr;
assign segment_addr = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
assign rf_data_in = {c_new_page, segment_addr};
assign byte_addr = (rf_data[SEGMENT_SELECT_BITS-1:0] << ALIGNMENT_ABITS);
end
else
begin
assign rf_data_in = c_new_page;
assign byte_addr = {BYTE_SELECT_BITS{1'b0}};
end
endgenerate
lookahead_fifo #(
.WIDTH( SEGMENT_SELECT_BITS + 1 ),
.DEPTH( REQUEST_FIFO_DEPTH )
) request_fifo (
.clk(clk),
.reset(reset),
.i_data( rf_data_in ),
.i_valid( i_valid && !c_stall ),
.o_full(rf_full),
.i_stall(rf_stall_in),
.o_valid(rf_valid),
.o_data(rf_data),
.o_next_valid(rf_next_valid),
.o_next_data(rf_next_data)
);
// Read master - Handles pipelined read transactions through MM-Avalon.
lsu_pipelined_read #(
.AWIDTH( AWIDTH ),
.WIDTH_BYTES( MWIDTH_BYTES ),
.MWIDTH_BYTES( MWIDTH_BYTES ),
.ALIGNMENT_ABITS( BYTE_SELECT_BITS ),
.KERNEL_SIDE_MEM_LATENCY( KERNEL_SIDE_MEM_LATENCY ),
.USEOUTPUTFIFO(1),
.USEINPUTFIFO( 1 ), // Add the latency adjusting input fifos
.PIPELINE_INPUT( 1 ) // Let's add a pipline input to the input side just to help with Fmax
) read_master (
.clk(clk),
.reset(reset),
.o_stall(rm_stall),
.i_valid(c_req_valid),
.i_address({c_req_addr, {BYTE_SELECT_BITS{1'b0}}}),
.i_stall(rm_stall_in),
.o_valid(rm_valid),
.o_active(rm_active),
.o_readdata(rm_data),
.avm_address(avm_address),
.avm_read(avm_read),
.avm_readdata(avm_readdata),
.avm_waitrequest(avm_waitrequest),
.avm_byteenable(avm_byteenable),
.avm_readdatavalid(avm_readdatavalid)
);
// Control logic
// Highest bit of rf_next_data indicates whether this is a new avalon request
// (new page) or was coalesced into the previous request.
assign next_new_page = rf_next_data[SEGMENT_SELECT_BITS];
assign rm_stall_in = (!next_new_page && rf_next_valid) || rf_stall_in;
assign rf_stall_in = i_stall || !rm_valid;
// Output MUX
assign o_readdata = rm_data[8*byte_addr +: WIDTH];
// External control signals
assign o_stall = c_stall || rf_full;
assign o_valid = rm_valid && rf_valid;
assign o_active=rf_valid | rm_active;
endmodule
/******************************************************************************/
// Basic coalesced write unit:
// Accept write requests on the upstream interface. The avalon spec does
// not allow a request to change while it is being stalled, so the current
// request is registered in an output register stage and not modified.
// Subsequent requests are coalesced together as long as the output register
// stage is occupied (i.e. the avalon bus is stalling).
//
// TODO: The byte enable format is not actually compliant with the
// Avalon spec. Essentially we should not enable non-adjacent words in a write
// request. This is OK for the DDR Memory Controller as it accepts our
// non-compliant format. This needs to be investigated further.
module lsu_basic_coalesced_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter USE_BYTE_EN;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
// Constants
localparam COUNTER_WIDTH=8; // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
input [WIDTH_BYTES-1:0] i_byteenable;
/***************
* Architecture *
***************/
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [COUNTER_WIDTH-1:0] or_next_counter;
wire [COUNTER_WIDTH-1:0] rf_count;
wire rf_read;
wire rf_empty;
wire rf_full;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire or_ready;
reg or_write;
reg [AWIDTH-1:0] or_address;
reg [MWIDTH-1:0] or_writedata;
reg [MWIDTH_BYTES-1:0] or_byteenable;
wire oc_full;
// Output register stage to store the next request
assign or_ready = !or_write || !avm_waitrequest;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
or_write <= 1'b0;
or_address <= {AWIDTH{1'b0}};
or_writedata <= {MWIDTH{1'b0}};
or_byteenable <= {MWIDTH_BYTES{1'b0}};
or_next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
if(or_ready)
begin
or_write <= c_req_valid;
or_address <= (c_req_addr << BYTE_SELECT_BITS);
or_writedata <= wm_writedata;
or_byteenable <= wm_byteenable;
or_next_counter <= next_counter;
end
end
end
assign avm_address = or_address;
assign avm_write = or_write;
assign avm_writedata = or_writedata;
assign avm_byteenable = or_byteenable;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
basic_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(MWIDTH/WIDTH)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full),
.o_stall(c_stall),
.o_new_page(c_new_page),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(!or_ready)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[segment_select*SEGMENT_WIDTH +: WIDTH] = {WIDTH{1'b1}};
end
end
else
begin
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}} ;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = {WIDTH{1'b1}};
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
// Write size tracker - track the number of threads represented by each pending write request
acl_ll_fifo #(
.WIDTH(COUNTER_WIDTH),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) req_fifo (
.clk(clk),
.reset(reset),
.data_in( or_next_counter ),
.data_out( rf_count ),
.write( write_accepted && (!rf_empty || !avm_writeack) ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
assign rf_read = avm_writeack && !rf_empty;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
assign input_accepted = i_valid && !o_stall;
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
end
else
begin
occ_counter <= occ_counter + input_accepted - output_acknowledged;
next_counter <= input_accepted + ((c_req_valid & or_ready) ? {COUNTER_WIDTH{1'b0}} : next_counter);
ack_counter <= ack_counter + ({COUNTER_WIDTH{avm_writeack}} & ( rf_empty ? or_next_counter : rf_count )) - output_acknowledged;
end
end
assign oc_full = (occ_counter == {COUNTER_WIDTH{1'b1}});
// Pipeline control signals
assign o_stall = oc_full || c_stall || rf_full;
assign o_valid = (ack_counter > {COUNTER_WIDTH{1'b0}});
assign o_active = (occ_counter != {COUNTER_WIDTH{1'b0}});
endmodule
/******************************************************************************/
/* RESPONSE FIFO */
// lookahead_fifo - A simple sc_fifo instantiation with an additional
// shift-register stage at the end to provide access to the next two data
// items.
module lookahead_fifo
(
clk, reset, i_data, i_valid, o_full, i_stall, o_valid, o_data,
o_next_valid, o_next_data
);
parameter WIDTH=32;
parameter DEPTH=32;
input clk;
input reset;
input [WIDTH-1:0] i_data;
input i_valid;
output o_full;
input i_stall;
output reg o_valid;
output reg [WIDTH-1:0] o_data;
output o_next_valid;
output [WIDTH-1:0] o_next_data;
wire sr_ready;
// Fifo
acl_data_fifo #(
.DATA_WIDTH(WIDTH),
.DEPTH(DEPTH),
.IMPL("ram_plus_reg")
) req_fifo (
.clock(clk),
.resetn(!reset),
.data_in( i_data ),
.data_out( o_next_data ),
.valid_in( i_valid ),
.valid_out( o_next_valid ),
.stall_in( !sr_ready ),
.stall_out( o_full )
);
// Shift-reg
assign sr_ready = !o_valid || !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
o_data <= {WIDTH{1'b0}};
o_valid <= 1'b0;
end
else
begin
o_valid <= sr_ready ? o_next_valid : o_valid;
o_data <= sr_ready ? o_next_data : o_data;
end
end
endmodule
/* BASIC COALESCING MODULE */
// basic_coalescer - Accept new inputs as long as the unit is not stalled,
// or the new request can be coalesced with the pending (stalled) request.
module basic_coalescer
(
clk, reset, i_page_addr, i_valid, o_stall, o_new_page, o_req_addr,
o_req_valid, i_stall
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8; // power of 2
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_valid;
output o_stall;
output o_new_page;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
input i_stall;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
assign timeout = timeout_counter[$clog2(TIMEOUT)];
// Internal signal logic
assign match = (i_page_addr == page_addr);
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
valid <= 1'b0;
timeout_counter <= '0;
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
valid <= ready ? i_valid : valid;
if( i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = i_valid && !match && !ready;
assign o_new_page = ready;
assign o_req_addr = page_addr;
assign o_req_valid = valid && !waiting;
endmodule
|
(** * Sub: Subtyping *)
Require Export Types.
(* ###################################################### *)
(** * Concepts *)
(** We now turn to the study of _subtyping_, perhaps the most
characteristic feature of the static type systems of recently
designed programming languages and a key feature needed to support
the object-oriented programming style. *)
(* ###################################################### *)
(** ** A Motivating Example *)
(** Suppose we are writing a program involving two record types
defined as follows:
<<
Person = {name:String, age:Nat}
Student = {name:String, age:Nat, gpa:Nat}
>>
*)
(** In the simply typed lamdba-calculus with records, the term
<<
(\r:Person. (r.age)+1) {name="Pat",age=21,gpa=1}
>>
is not typable: it involves an application of a function that wants
a one-field record to an argument that actually provides two
fields, while the [T_App] rule demands that the domain type of the
function being applied must match the type of the argument
precisely.
But this is silly: we're passing the function a _better_ argument
than it needs! The only thing the body of the function can
possibly do with its record argument [r] is project the field [age]
from it: nothing else is allowed by the type, and the presence or
absence of an extra [gpa] field makes no difference at all. So,
intuitively, it seems that this function should be applicable to
any record value that has at least an [age] field.
Looking at the same thing from another point of view, a record with
more fields is "at least as good in any context" as one with just a
subset of these fields, in the sense that any value belonging to
the longer record type can be used _safely_ in any context
expecting the shorter record type. If the context expects
something with the shorter type but we actually give it something
with the longer type, nothing bad will happen (formally, the
program will not get stuck).
The general principle at work here is called _subtyping_. We say
that "[S] is a subtype of [T]", informally written [S <: T], if a
value of type [S] can safely be used in any context where a value
of type [T] is expected. The idea of subtyping applies not only to
records, but to all of the type constructors in the language --
functions, pairs, etc. *)
(** ** Subtyping and Object-Oriented Languages *)
(** Subtyping plays a fundamental role in many programming
languages -- in particular, it is closely related to the notion of
_subclassing_ in object-oriented languages.
An _object_ in Java, C[#], etc. can be thought of as a record,
some of whose fields are functions ("methods") and some of whose
fields are data values ("fields" or "instance variables").
Invoking a method [m] of an object [o] on some arguments [a1..an]
consists of projecting out the [m] field of [o] and applying it to
[a1..an].
The type of an object can be given as either a _class_ or an
_interface_. Both of these provide a description of which methods
and which data fields the object offers.
Classes and interfaces are related by the _subclass_ and
_subinterface_ relations. An object belonging to a subclass (or
subinterface) is required to provide all the methods and fields of
one belonging to a superclass (or superinterface), plus possibly
some more.
The fact that an object from a subclass (or sub-interface) can be
used in place of one from a superclass (or super-interface)
provides a degree of flexibility that is is extremely handy for
organizing complex libraries. For example, a GUI toolkit like
Java's Swing framework might define an abstract interface
[Component] that collects together the common fields and methods
of all objects having a graphical representation that can be
displayed on the screen and that can interact with the user.
Examples of such object would include the buttons, checkboxes, and
scrollbars of a typical GUI. A method that relies only on this
common interface can now be applied to any of these objects.
Of course, real object-oriented languages include many other
features besides these. For example, fields can be updated.
Fields and methods can be declared [private]. Classes also give
_code_ that is used when constructing objects and implementing
their methods, and the code in subclasses cooperate with code in
superclasses via _inheritance_. Classes can have static methods
and fields, initializers, etc., etc.
To keep things simple here, we won't deal with any of these
issues -- in fact, we won't even talk any more about objects or
classes. (There is a lot of discussion in _Types and Programming
Languages_, if you are interested.) Instead, we'll study the core
concepts behind the subclass / subinterface relation in the
simplified setting of the STLC. *)
(** *** *)
(** Of course, real OO languages have lots of other features...
- mutable fields
- [private] and other visibility modifiers
- method inheritance
- static components
- etc., etc.
We'll ignore all these and focus on core mechanisms. *)
(** ** The Subsumption Rule *)
(** Our goal for this chapter is to add subtyping to the simply typed
lambda-calculus (with some of the basic extensions from [MoreStlc]).
This involves two steps:
- Defining a binary _subtype relation_ between types.
- Enriching the typing relation to take subtyping into account.
The second step is actually very simple. We add just a single rule
to the typing relation: the so-called _rule of subsumption_:
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
This rule says, intuitively, that it is OK to "forget" some of
what we know about a term. *)
(** For example, we may know that [t] is a record with two
fields (e.g., [S = {x:A->A, y:B->B}]), but choose to forget about
one of the fields ([T = {y:B->B}]) so that we can pass [t] to a
function that requires just a single-field record. *)
(** ** The Subtype Relation *)
(** The first step -- the definition of the relation [S <: T] -- is
where all the action is. Let's look at each of the clauses of its
definition. *)
(** *** Structural Rules *)
(** To start off, we impose two "structural rules" that are
independent of any particular type constructor: a rule of
_transitivity_, which says intuitively that, if [S] is better than
[U] and [U] is better than [T], then [S] is better than [T]...
S <: U U <: T
---------------- (S_Trans)
S <: T
... and a rule of _reflexivity_, since certainly any type [T] is
as good as itself:
------ (S_Refl)
T <: T
*)
(** *** Products *)
(** Now we consider the individual type constructors, one by one,
beginning with product types. We consider one pair to be "better
than" another if each of its components is.
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
*)
(** *** Arrows *)
(** Suppose we have two functions [f] and [g] with these types:
f : C -> Student
g : (C->Person) -> D
That is, [f] is a function that yields a record of type [Student],
and [g] is a (higher-order) function that expects its (function)
argument to yield a record of type [Person]. Also suppose, even
though we haven't yet discussed subtyping for records, that
[Student] is a subtype of [Person]. Then the application [g f] is
safe even though their types do not match up precisely, because
the only thing [g] can do with [f] is to apply it to some
argument (of type [C]); the result will actually be a [Student],
while [g] will be expecting a [Person], but this is safe because
the only thing [g] can then do is to project out the two fields
that it knows about ([name] and [age]), and these will certainly
be among the fields that are present.
This example suggests that the subtyping rule for arrow types
should say that two arrow types are in the subtype relation if
their results are:
S2 <: T2
---------------- (S_Arrow_Co)
S1 -> S2 <: S1 -> T2
We can generalize this to allow the arguments of the two arrow
types to be in the subtype relation as well:
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
Notice that the argument types are subtypes "the other way round":
in order to conclude that [S1->S2] to be a subtype of [T1->T2], it
must be the case that [T1] is a subtype of [S1]. The arrow
constructor is said to be _contravariant_ in its first argument
and _covariant_ in its second.
Here is an example that illustrates this:
f : Person -> C
g : (Student -> C) -> D
The application [g f] is safe, because the only thing the body of
[g] can do with [f] is to apply it to some argument of type
[Student]. Since [f] requires records having (at least) the
fields of a [Person], this will always work. So [Person -> C] is a
subtype of [Student -> C] since [Student] is a subtype of
[Person].
The intuition is that, if we have a function [f] of type [S1->S2],
then we know that [f] accepts elements of type [S1]; clearly, [f]
will also accept elements of any subtype [T1] of [S1]. The type of
[f] also tells us that it returns elements of type [S2]; we can
also view these results belonging to any supertype [T2] of
[S2]. That is, any function [f] of type [S1->S2] can also be
viewed as having type [T1->T2].
*)
(** *** Records *)
(** What about subtyping for record types? *)
(** The basic intuition about subtyping for record types is that it is
always safe to use a "bigger" record in place of a "smaller" one.
That is, given a record type, adding extra fields will always
result in a subtype. If some code is expecting a record with
fields [x] and [y], it is perfectly safe for it to receive a record
with fields [x], [y], and [z]; the [z] field will simply be ignored.
For example,
{name:String, age:Nat, gpa:Nat} <: {name:String, age:Nat}
{name:String, age:Nat} <: {name:String}
{name:String} <: {}
This is known as "width subtyping" for records. *)
(** We can also create a subtype of a record type by replacing the type
of one of its fields with a subtype. If some code is expecting a
record with a field [x] of type [T], it will be happy with a record
having a field [x] of type [S] as long as [S] is a subtype of
[T]. For example,
{x:Student} <: {x:Person}
This is known as "depth subtyping". *)
(** Finally, although the fields of a record type are written in a
particular order, the order does not really matter. For example,
{name:String,age:Nat} <: {age:Nat,name:String}
This is known as "permutation subtyping". *)
(** We could formalize these requirements in a single subtyping rule
for records as follows:
for each jk in j1..jn,
exists ip in i1..im, such that
jk=ip and Sp <: Tk
---------------------------------- (S_Rcd)
{i1:S1...im:Sm} <: {j1:T1...jn:Tn}
That is, the record on the left should have all the field labels of
the one on the right (and possibly more), while the types of the
common fields should be in the subtype relation. However, this rule
is rather heavy and hard to read. If we like, we can decompose it
into three simpler rules, which can be combined using [S_Trans] to
achieve all the same effects. *)
(** First, adding fields to the end of a record type gives a subtype:
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
We can use [S_RcdWidth] to drop later fields of a multi-field
record while keeping earlier fields, showing for example that
[{age:Nat,name:String} <: {name:String}]. *)
(** Second, we can apply subtyping inside the components of a compound
record type:
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
For example, we can use [S_RcdDepth] and [S_RcdWidth] together to
show that [{y:Student, x:Nat} <: {y:Person}]. *)
(** Third, we need to be able to reorder fields. For example, we
might expect that [{name:String, gpa:Nat, age:Nat} <: Person]. We
haven't quite achieved this yet: using just [S_RcdDepth] and
[S_RcdWidth] we can only drop fields from the _end_ of a record
type. So we need:
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(** It is worth noting that full-blown language designs may choose not
to adopt all of these subtyping rules. For example, in Java:
- A subclass may not change the argument or result types of a
method of its superclass (i.e., no depth subtyping or no arrow
subtyping, depending how you look at it).
- Each class has just one superclass ("single inheritance" of
classes).
- Each class member (field or method) can be assigned a single
index, adding new indices "on the right" as more members are
added in subclasses (i.e., no permutation for classes).
- A class may implement multiple interfaces -- so-called "multiple
inheritance" of interfaces (i.e., permutation is allowed for
interfaces). *)
(** **** Exercise: 2 stars (arrow_sub_wrong) *)
(** Suppose we had incorrectly defined subtyping as covariant on both
the right and the left of arrow types:
S1 <: T1 S2 <: T2
-------------------- (S_Arrow_wrong)
S1 -> S2 <: T1 -> T2
Give a concrete example of functions [f] and [g] with the following types...
f : Student -> Nat
g : (Person -> Nat) -> Nat
... such that the application [g f] will get stuck during
execution.
[] *)
(** *** Top *)
(** Finally, it is natural to give the subtype relation a maximal
element -- a type that lies above every other type and is
inhabited by all (well-typed) values. We do this by adding to the
language one new type constant, called [Top], together with a
subtyping rule that places it above every other type in the
subtype relation:
-------- (S_Top)
S <: Top
The [Top] type is an analog of the [Object] type in Java and C[#]. *)
(* ############################################### *)
(** *** Summary *)
(** In summary, we form the STLC with subtyping by starting with the
pure STLC (over some set of base types) and...
- adding a base type [Top],
- adding the rule of subsumption
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
to the typing relation, and
- defining a subtype relation as follows:
S <: U U <: T
---------------- (S_Trans)
S <: T
------ (S_Refl)
T <: T
-------- (S_Top)
S <: Top
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(* ############################################### *)
(** ** Exercises *)
(** **** Exercise: 1 star, optional (subtype_instances_tf_1) *)
(** Suppose we have types [S], [T], [U], and [V] with [S <: T]
and [U <: V]. Which of the following subtyping assertions
are then true? Write _true_ or _false_ after each one.
([A], [B], and [C] here are base types.)
- [T->S <: T->S]
- [Top->U <: S->Top]
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
- [T->T->U <: S->S->V]
- [(T->T)->U <: (S->S)->V]
- [((T->S)->T)->U <: ((S->T)->S)->V]
- [S*V <: T*U]
[] *)
(** **** Exercise: 2 stars (subtype_order) *)
(** The following types happen to form a linear order with respect to subtyping:
- [Top]
- [Top -> Student]
- [Student -> Person]
- [Student -> Top]
- [Person -> Student]
Write these types in order from the most specific to the most general.
Where does the type [Top->Top->Student] fit into this order?
*)
(** **** Exercise: 1 star (subtype_instances_tf_2) *)
(** Which of the following statements are true? Write _true_ or
_false_ after each one.
forall S T,
S <: T ->
S->S <: T->T
forall S,
S <: A->A ->
exists T,
S = T->T /\ T <: A
forall S T1 T2,
(S <: T1 -> T2) ->
exists S1 S2,
S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
exists S,
S <: S->S
exists S,
S->S <: S
forall S T1 T2,
S <: T1*T2 ->
exists S1 S2,
S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
[] *)
(** **** Exercise: 1 star (subtype_concepts_tf) *)
(** Which of the following statements are true, and which are false?
- There exists a type that is a supertype of every other type.
- There exists a type that is a subtype of every other type.
- There exists a pair type that is a supertype of every other
pair type.
- There exists a pair type that is a subtype of every other
pair type.
- There exists an arrow type that is a supertype of every other
arrow type.
- There exists an arrow type that is a subtype of every other
arrow type.
- There is an infinite descending chain of distinct types in the
subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a subtype of [Si].
- There is an infinite _ascending_ chain of distinct types in
the subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a supertype of [Si].
[] *)
(** **** Exercise: 2 stars (proper_subtypes) *)
(** Is the following statement true or false? Briefly explain your
answer.
forall T,
~(exists n, T = TBase n) ->
exists S,
S <: T /\ S <> T
]]
[] *)
(** **** Exercise: 2 stars (small_large_1) *)
(**
- What is the _smallest_ type [T] ("smallest" in the subtype
relation) that makes the following assertion true? (Assume we
have [Unit] among the base types and [unit] as a constant of this
type.)
empty |- (\p:T*Top. p.fst) ((\z:A.z), unit) : A->A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_2) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\p:(A->A * B->B). p) ((\z:A.z), (\z:B.z)) : T
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars, optional (small_large_3) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
a:A |- (\p:(A*T). (p.snd) (p.fst)) (a , \z:A.z) : A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_4) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
exists S,
empty |- (\p:(A*T). (p.snd) (p.fst)) : S
- What is the _largest_ type [T] that makes the same
assertion true?
[] *)
(** **** Exercise: 2 stars (smallest_1) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
exists S, exists t,
empty |- (\x:T. x x) t : S
]]
[] *)
(** **** Exercise: 2 stars (smallest_2) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\x:Top. x) ((\z:A.z) , (\z:B.z)) : T
]]
[] *)
(** **** Exercise: 3 stars, optional (count_supertypes) *)
(** How many supertypes does the record type [{x:A, y:C->C}] have? That is,
how many different types [T] are there such that [{x:A, y:C->C} <:
T]? (We consider two types to be different if they are written
differently, even if each is a subtype of the other. For example,
[{x:A,y:B}] and [{y:B,x:A}] are different.)
[] *)
(** **** Exercise: 2 stars (pair_permutation) *)
(** The subtyping rule for product types
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1*S2 <: T1*T2
intuitively corresponds to the "depth" subtyping rule for records. Extending the analogy, we might consider adding a "permutation" rule
--------------
T1*T2 <: T2*T1
for products.
Is this a good idea? Briefly explain why or why not.
[] *)
(* ###################################################### *)
(** * Formal Definitions *)
(** Most of the definitions -- in particular, the syntax and
operational semantics of the language -- are identical to what we
saw in the last chapter. We just need to extend the typing
relation with the subsumption rule and add a new [Inductive]
definition for the subtyping relation. Let's first do the
identical bits. *)
(* ###################################################### *)
(** ** Core Definitions *)
(* ################################### *)
(** *** Syntax *)
(** For the sake of more interesting examples below, we'll allow an
arbitrary set of additional base types like [String], [Float],
etc. We won't bother adding any constants belonging to these
types or any operators on them, but we could easily do so. *)
(** In the rest of the chapter, we formalize just base types,
booleans, arrow types, [Unit], and [Top], omitting record types
and leaving product types as an exercise. *)
Inductive ty : Type :=
| TTop : ty
| TBool : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
| TUnit : ty
.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBool"
| Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TUnit" |
].
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tunit : tm
.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif"
| Case_aux c "tunit"
].
(* ################################### *)
(** *** Substitution *)
(** The definition of substitution remains exactly the same as for the
pure STLC. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
tunit
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
(** Likewise the definitions of the [value] property and the [step]
relation. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse
| v_unit :
value tunit
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
].
Hint Constructors step.
(* ###################################################################### *)
(** ** Subtyping *)
(** Now we come to the most interesting part. We begin by
defining the subtyping relation and developing some of its
important technical properties. *)
(** The definition of subtyping is just what we sketched in the
motivating discussion. *)
Reserved Notation "T '<:' U" (at level 40).
Inductive subtype : ty -> ty -> Prop :=
| S_Refl : forall T,
T <: T
| S_Trans : forall S U T,
S <: U ->
U <: T ->
S <: T
| S_Top : forall S,
S <: TTop
| S_Arrow : forall S1 S2 T1 T2,
T1 <: S1 ->
S2 <: T2 ->
(TArrow S1 S2) <: (TArrow T1 T2)
where "T '<:' U" := (subtype T U).
(** Note that we don't need any special rules for base types: they are
automatically subtypes of themselves (by [S_Refl]) and [Top] (by
[S_Top]), and that's all we want. *)
Hint Constructors subtype.
Tactic Notation "subtype_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "S_Refl" | Case_aux c "S_Trans"
| Case_aux c "S_Top" | Case_aux c "S_Arrow"
].
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Notation String := (TBase (Id 9)).
Notation Float := (TBase (Id 10)).
Notation Integer := (TBase (Id 11)).
(** **** Exercise: 2 stars, optional (subtyping_judgements) *)
(** (Do this exercise after you have added product types to the
language, at least up to this point in the file).
Using the encoding of records into pairs, define pair types
representing the record types
Person := { name : String }
Student := { name : String ;
gpa : Float }
Employee := { name : String ;
ssn : Integer }
Recall that in chapter MoreStlc, the optional subsection "Encoding
Records" describes how records can be encoded as pairs.
*)
Definition Person : ty :=
(* FILL IN HERE *) admit.
Definition Student : ty :=
(* FILL IN HERE *) admit.
Definition Employee : ty :=
(* FILL IN HERE *) admit.
Example sub_student_person :
Student <: Person.
Proof.
(* FILL IN HERE *) Admitted.
Example sub_employee_person :
Employee <: Person.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
Example subtyping_example_0 :
(TArrow C Person) <: (TArrow C TTop).
(* C->Person <: C->Top *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
Qed.
(** The following facts are mostly easy to prove in Coq. To get
full benefit from the exercises, make sure you also
understand how to prove them on paper! *)
(** **** Exercise: 1 star, optional (subtyping_example_1) *)
Example subtyping_example_1 :
(TArrow TTop Student) <: (TArrow (TArrow C C) Person).
(* Top->Student <: (C->C)->Person *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
End Examples.
(* ###################################################################### *)
(** ** Typing *)
(** The only change to the typing relation is the addition of the rule
of subsumption, [T_Sub]. *)
Definition context := id -> (option ty).
Definition empty : context := (fun _ => None).
Definition extend (Gamma : context) (x:id) (T : ty) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Same as before *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- (tif t1 t2 t3) \in T
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* New rule of subsumption *)
| T_Sub : forall Gamma t S T,
Gamma |- t \in S ->
S <: T ->
Gamma |- t \in T
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Unit"
| Case_aux c "T_Sub" ].
(* To make your job simpler, the following hints help construct typing
derivations. *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
Hint Extern 2 (_ = _) => compute; reflexivity.
(* ############################################### *)
(** ** Typing examples *)
Module Examples2.
Import Examples.
(** Do the following exercises after you have added product types to
the language. For each informal typing judgement, write it as a
formal statement in Coq and prove it. *)
(** **** Exercise: 1 star, optional (typing_example_0) *)
(* empty |- ((\z:A.z), (\z:B.z))
: (A->A * B->B) *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_2) *)
(* empty |- (\z:(C->C)->(Top * B->B). (z (\x:C.x)).snd)
(\z:C->C. ((\z:A.z), (\z:B.z)))
: B->B *)
(* FILL IN HERE *)
(** [] *)
End Examples2.
(* ###################################################################### *)
(** * Properties *)
(** The fundamental properties of the system that we want to check are
the same as always: progress and preservation. Unlike the
extension of the STLC with references, we don't need to change the
_statements_ of these properties to take subtyping into account.
However, their proofs do become a little bit more involved. *)
(* ###################################################################### *)
(** ** Inversion Lemmas for Subtyping *)
(** Before we look at the properties of the typing relation, we need
to record a couple of critical structural properties of the subtype
relation:
- [Bool] is the only subtype of [Bool]
- every subtype of an arrow type is itself an arrow type. *)
(** These are called _inversion lemmas_ because they play the same
role in later proofs as the built-in [inversion] tactic: given a
hypothesis that there exists a derivation of some subtyping
statement [S <: T] and some constraints on the shape of [S] and/or
[T], each one reasons about what this derivation must look like to
tell us something further about the shapes of [S] and [T] and the
existence of subtype relations between their parts. *)
(** **** Exercise: 2 stars, optional (sub_inversion_Bool) *)
Lemma sub_inversion_Bool : forall U,
U <: TBool ->
U = TBool.
Proof with auto.
intros U Hs.
remember TBool as V.
(* FILL IN HERE *) Admitted.
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
U <: (TArrow V1 V2) ->
exists U1, exists U2,
U = (TArrow U1 U2) /\ (V1 <: U1) /\ (U2 <: V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ########################################## *)
(** ** Canonical Forms *)
(** We'll see first that the proof of the progress theorem doesn't
change too much -- we just need one small refinement. When we're
considering the case where the term in question is an application
[t1 t2] where both [t1] and [t2] are values, we need to know that
[t1] has the _form_ of a lambda-abstraction, so that we can apply
the [ST_AppAbs] reduction rule. In the ordinary STLC, this is
obvious: we know that [t1] has a function type [T11->T12], and
there is only one rule that can be used to give a function type to
a value -- rule [T_Abs] -- and the form of the conclusion of this
rule forces [t1] to be an abstraction.
In the STLC with subtyping, this reasoning doesn't quite work
because there's another rule that can be used to show that a value
has a function type: subsumption. Fortunately, this possibility
doesn't change things much: if the last rule used to show [Gamma
|- t1 : T11->T12] is subsumption, then there is some
_sub_-derivation whose subject is also [t1], and we can reason by
induction until we finally bottom out at a use of [T_Abs].
This bit of reasoning is packaged up in the following lemma, which
tells us the possible "canonical forms" (i.e. values) of function
type. *)
(** **** Exercise: 3 stars, optional (canonical_forms_of_arrow_types) *)
Lemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,
Gamma |- s \in (TArrow T1 T2) ->
value s ->
exists x, exists S1, exists s2,
s = tabs x S1 s2.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Similarly, the canonical forms of type [Bool] are the constants
[true] and [false]. *)
Lemma canonical_forms_of_Bool : forall Gamma s,
Gamma |- s \in TBool ->
value s ->
(s = ttrue \/ s = tfalse).
Proof with eauto.
intros Gamma s Hty Hv.
remember TBool as T.
has_type_cases (induction Hty) Case; try solve by inversion...
Case "T_Sub".
subst. apply sub_inversion_Bool in H. subst...
Qed.
(* ########################################## *)
(** ** Progress *)
(** The proof of progress proceeds like the one for the pure
STLC, except that in several places we invoke canonical forms
lemmas... *)
(** _Theorem_ (Progress): For any term [t] and type [T], if [empty |-
t : T] then [t] is a value or [t ==> t'] for some term [t'].
_Proof_: Let [t] and [T] be given, with [empty |- t : T]. Proceed
by induction on the typing derivation.
The cases for [T_Abs], [T_Unit], [T_True] and [T_False] are
immediate because abstractions, [unit], [true], and [false] are
already values. The [T_Var] case is vacuous because variables
cannot be typed in the empty context. The remaining cases are
more interesting:
- If the last step in the typing derivation uses rule [T_App],
then there are terms [t1] [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and [empty |-
t2 : T1]. Moreover, by the induction hypothesis, either [t1] is
a value or it steps, and either [t2] is a value or it steps.
There are three possibilities to consider:
- Suppose [t1 ==> t1'] for some term [t1']. Then [t1 t2 ==> t1' t2]
by [ST_App1].
- Suppose [t1] is a value and [t2 ==> t2'] for some term [t2'].
Then [t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a
value.
- Finally, suppose [t1] and [t2] are both values. By Lemma
[canonical_forms_for_arrow_types], we know that [t1] has the
form [\x:S1.s2] for some [x], [S1], and [s2]. But then
[(\x:S1.s2) t2 ==> [x:=t2]s2] by [ST_AppAbs], since [t2] is a
value.
- If the final step of the derivation uses rule [T_If], then there
are terms [t1], [t2], and [t3] such that [t = if t1 then t2 else
t3], with [empty |- t1 : Bool] and with [empty |- t2 : T] and
[empty |- t3 : T]. Moreover, by the induction hypothesis,
either [t1] is a value or it steps.
- If [t1] is a value, then by the canonical forms lemma for
booleans, either [t1 = true] or [t1 = false]. In either
case, [t] can step, using rule [ST_IfTrue] or [ST_IfFalse].
- If [t1] can step, then so can [t], by rule [ST_If].
- If the final step of the derivation is by [T_Sub], then there is
a type [S] such that [S <: T] and [empty |- t : S]. The desired
result is exactly the induction hypothesis for the typing
subderivation.
*)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
intros t T Ht.
remember empty as Gamma.
revert HeqGamma.
has_type_cases (induction Ht) Case;
intros HeqGamma; subst...
Case "T_Var".
inversion H.
Case "T_App".
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
destruct (canonical_forms_of_arrow_types empty t1 T1 T2)
as [x [S1 [t12 Heqt1]]]...
subst. exists ([x:=t2]t12)...
SSCase "t2 steps".
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_If".
right.
destruct IHHt1.
SCase "t1 is a value"...
assert (t1 = ttrue \/ t1 = tfalse)
by (eapply canonical_forms_of_Bool; eauto).
inversion H0; subst...
inversion H. rename x into t1'. eauto.
Qed.
(* ########################################## *)
(** ** Inversion Lemmas for Typing *)
(** The proof of the preservation theorem also becomes a little more
complex with the addition of subtyping. The reason is that, as
with the "inversion lemmas for subtyping" above, there are a
number of facts about the typing relation that are "obvious from
the definition" in the pure STLC (and hence can be obtained
directly from the [inversion] tactic) but that require real proofs
in the presence of subtyping because there are multiple ways to
derive the same [has_type] statement.
The following "inversion lemma" tells us that, if we have a
derivation of some typing statement [Gamma |- \x:S1.t2 : T] whose
subject is an abstraction, then there must be some subderivation
giving a type to the body [t2]. *)
(** _Lemma_: If [Gamma |- \x:S1.t2 : T], then there is a type [S2]
such that [Gamma, x:S1 |- t2 : S2] and [S1 -> S2 <: T].
(Notice that the lemma does _not_ say, "then [T] itself is an arrow
type" -- this is tempting, but false!)
_Proof_: Let [Gamma], [x], [S1], [t2] and [T] be given as
described. Proceed by induction on the derivation of [Gamma |-
\x:S1.t2 : T]. Cases [T_Var], [T_App], are vacuous as those
rules cannot be used to give a type to a syntactic abstraction.
- If the last step of the derivation is a use of [T_Abs] then
there is a type [T12] such that [T = S1 -> T12] and [Gamma,
x:S1 |- t2 : T12]. Picking [T12] for [S2] gives us what we
need: [S1 -> T12 <: S1 -> T12] follows from [S_Refl].
- If the last step of the derivation is a use of [T_Sub] then
there is a type [S] such that [S <: T] and [Gamma |- \x:S1.t2 :
S]. The IH for the typing subderivation tell us that there is
some type [S2] with [S1 -> S2 <: S] and [Gamma, x:S1 |- t2 :
S2]. Picking type [S2] gives us what we need, since [S1 -> S2
<: T] then follows by [S_Trans]. *)
Lemma typing_inversion_abs : forall Gamma x S1 t2 T,
Gamma |- (tabs x S1 t2) \in T ->
(exists S2, (TArrow S1 S2) <: T
/\ (extend Gamma x S1) |- t2 \in S2).
Proof with eauto.
intros Gamma x S1 t2 T H.
remember (tabs x S1 t2) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Abs".
exists T12...
Case "T_Sub".
destruct IHhas_type as [S2 [Hsub Hty]]...
Qed.
(** Similarly... *)
Lemma typing_inversion_var : forall Gamma x T,
Gamma |- (tvar x) \in T ->
exists S,
Gamma x = Some S /\ S <: T.
Proof with eauto.
intros Gamma x T Hty.
remember (tvar x) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_Var".
exists T...
Case "T_Sub".
destruct IHHty as [U [Hctx HsubU]]... Qed.
Lemma typing_inversion_app : forall Gamma t1 t2 T2,
Gamma |- (tapp t1 t2) \in T2 ->
exists T1,
Gamma |- t1 \in (TArrow T1 T2) /\
Gamma |- t2 \in T1.
Proof with eauto.
intros Gamma t1 t2 T2 Hty.
remember (tapp t1 t2) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_App".
exists T1...
Case "T_Sub".
destruct IHHty as [U1 [Hty1 Hty2]]...
Qed.
Lemma typing_inversion_true : forall Gamma T,
Gamma |- ttrue \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember ttrue as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_false : forall Gamma T,
Gamma |- tfalse \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember tfalse as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_if : forall Gamma t1 t2 t3 T,
Gamma |- (tif t1 t2 t3) \in T ->
Gamma |- t1 \in TBool
/\ Gamma |- t2 \in T
/\ Gamma |- t3 \in T.
Proof with eauto.
intros Gamma t1 t2 t3 T Hty.
remember (tif t1 t2 t3) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_If".
auto.
Case "T_Sub".
destruct (IHHty H0) as [H1 [H2 H3]]...
Qed.
Lemma typing_inversion_unit : forall Gamma T,
Gamma |- tunit \in T ->
TUnit <: T.
Proof with eauto.
intros Gamma T Htyp. remember tunit as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
(** The inversion lemmas for typing and for subtyping between arrow
types can be packaged up as a useful "combination lemma" telling
us exactly what we'll actually require below. *)
Lemma abs_arrow : forall x S1 s2 T1 T2,
empty |- (tabs x S1 s2) \in (TArrow T1 T2) ->
T1 <: S1
/\ (extend empty x S1) |- s2 \in T2.
Proof with eauto.
intros x S1 s2 T1 T2 Hty.
apply typing_inversion_abs in Hty.
inversion Hty as [S2 [Hsub Hty1]].
apply sub_inversion_arrow in Hsub.
inversion Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].
inversion Heq; subst... Qed.
(* ########################################## *)
(** ** Context Invariance *)
(** The context invariance lemma follows the same pattern as in the
pure STLC. *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_if1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif t1 t2 t3)
| afi_if2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif t1 t2 t3)
| afi_if3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif t1 t2 t3)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros x0 Hafi.
unfold extend. destruct (eq_id_dec x x0)...
Case "T_If".
apply T_If...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case;
subst; inversion Hafi; subst...
Case "T_Abs".
destruct (IHHtyp H4) as [T Hctx]. exists T.
unfold extend in Hctx. rewrite neq_id in Hctx... Qed.
(* ########################################## *)
(** ** Substitution *)
(** The _substitution lemma_ is proved along the same lines as
for the pure STLC. The only significant change is that there are
several places where, instead of the built-in [inversion] tactic,
we need to use the inversion lemmas that we proved above to
extract structural information from assumptions about the
well-typedness of subterms. *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
intros Gamma x U v t S Htypt Htypv.
generalize dependent S. generalize dependent Gamma.
t_cases (induction t) Case; intros; simpl.
Case "tvar".
rename i into y.
destruct (typing_inversion_var _ _ _ Htypt)
as [T [Hctx Hsub]].
unfold extend in Hctx.
destruct (eq_id_dec x y)...
SCase "x=y".
subst.
inversion Hctx; subst. clear Hctx.
apply context_invariance with empty...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra)
as [T' HT']...
inversion HT'.
Case "tapp".
destruct (typing_inversion_app _ _ _ _ Htypt)
as [T1 [Htypt1 Htypt2]].
eapply T_App...
Case "tabs".
rename i into y. rename t into T1.
destruct (typing_inversion_abs _ _ _ _ _ Htypt)
as [T2 [Hsub Htypt2]].
apply T_Sub with (TArrow T1 T2)... apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
Case "ttrue".
assert (TBool <: S)
by apply (typing_inversion_true _ _ Htypt)...
Case "tfalse".
assert (TBool <: S)
by apply (typing_inversion_false _ _ Htypt)...
Case "tif".
assert ((extend Gamma x U) |- t1 \in TBool
/\ (extend Gamma x U) |- t2 \in S
/\ (extend Gamma x U) |- t3 \in S)
by apply (typing_inversion_if _ _ _ _ _ Htypt).
inversion H as [H1 [H2 H3]].
apply IHt1 in H1. apply IHt2 in H2. apply IHt3 in H3.
auto.
Case "tunit".
assert (TUnit <: S)
by apply (typing_inversion_unit _ _ Htypt)...
Qed.
(* ########################################## *)
(** ** Preservation *)
(** The proof of preservation now proceeds pretty much as in earlier
chapters, using the substitution lemma at the appropriate point
and again using inversion lemmas from above to extract structural
information from typing assumptions. *)
(** _Theorem_ (Preservation): If [t], [t'] are terms and [T] is a type
such that [empty |- t : T] and [t ==> t'], then [empty |- t' :
T].
_Proof_: Let [t] and [T] be given such that [empty |- t : T]. We
proceed by induction on the structure of this typing derivation,
leaving [t'] general. The cases [T_Abs], [T_Unit], [T_True], and
[T_False] cases are vacuous because abstractions and constants
don't step. Case [T_Var] is vacuous as well, since the context is
empty.
- If the final step of the derivation is by [T_App], then there
are terms [t1] and [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and
[empty |- t2 : T1].
By the definition of the step relation, there are three ways
[t1 t2] can step. Cases [ST_App1] and [ST_App2] follow
immediately by the induction hypotheses for the typing
subderivations and a use of [T_App].
Suppose instead [t1 t2] steps by [ST_AppAbs]. Then [t1 =
\x:S.t12] for some type [S] and term [t12], and [t' =
[x:=t2]t12].
By lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].
It then follows by the substitution lemma
([substitution_preserves_typing]) that [empty |- [x:=t2]
t12 : T2] as desired.
- If the final step of the derivation uses rule [T_If], then
there are terms [t1], [t2], and [t3] such that [t = if t1 then
t2 else t3], with [empty |- t1 : Bool] and with [empty |- t2 :
T] and [empty |- t3 : T]. Moreover, by the induction
hypothesis, if [t1] steps to [t1'] then [empty |- t1' : Bool].
There are three cases to consider, depending on which rule was
used to show [t ==> t'].
- If [t ==> t'] by rule [ST_If], then [t' = if t1' then t2
else t3] with [t1 ==> t1']. By the induction hypothesis,
[empty |- t1' : Bool], and so [empty |- t' : T] by [T_If].
- If [t ==> t'] by rule [ST_IfTrue] or [ST_IfFalse], then
either [t' = t2] or [t' = t3], and [empty |- t' : T]
follows by assumption.
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
result is immediate by the induction hypothesis for the typing
subderivation and an application of [T_Sub]. [] *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
remember empty as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
inversion HE; subst...
SCase "ST_AppAbs".
destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].
apply substitution_preserves_typing with T...
Qed.
(** ** Records, via Products and Top *)
(** This formalization of the STLC with subtyping has omitted record
types, for brevity. If we want to deal with them more seriously,
we have two choices.
First, we can treat them as part of the core language, writing
down proper syntax, typing, and subtyping rules for them. Chapter
[RecordSub] shows how this extension works.
On the other hand, if we are treating them as a derived form that
is desugared in the parser, then we shouldn't need any new rules:
we should just check that the existing rules for subtyping product
and [Unit] types give rise to reasonable rules for record
subtyping via this encoding. To do this, we just need to make one
small change to the encoding described earlier: instead of using
[Unit] as the base case in the encoding of tuples and the "don't
care" placeholder in the encoding of records, we use [Top]. So:
<<
{a:Nat, b:Nat} ----> {Nat,Nat} i.e. (Nat,(Nat,Top))
{c:Nat, a:Nat} ----> {Nat,Top,Nat} i.e. (Nat,(Top,(Nat,Top)))
>>
The encoding of record values doesn't change at all. It is
easy (and instructive) to check that the subtyping rules above are
validated by the encoding. For the rest of this chapter, we'll
follow this encoding-based approach. *)
(* ###################################################### *)
(** ** Exercises *)
(** **** Exercise: 2 stars (variations) *)
(** Each part of this problem suggests a different way of
changing the definition of the STLC with Unit and
subtyping. (These changes are not cumulative: each part
starts from the original language.) In each part, list which
properties (Progress, Preservation, both, or neither) become
false. If a property becomes false, give a counterexample.
- Suppose we add the following typing rule:
Gamma |- t : S1->S2
S1 <: T1 T1 <: S1 S2 <: T2
----------------------------------- (T_Funny1)
Gamma |- t : T1->T2
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
unit ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
Unit <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: Unit
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
- Suppose we add the same evaluation rule _and_ a new typing rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
---------------------- (T_Funny6)
empty |- Unit : Top->Top
- Suppose we _change_ the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
[] *)
(* ###################################################################### *)
(** * Exercise: Adding Products *)
(** **** Exercise: 4 stars (products) *)
(** Adding pairs, projections, and product types to the system we have
defined is a relatively straightforward matter. Carry out this
extension:
- Add constructors for pairs, first and second projections, and
product types to the definitions of [ty] and [tm]. (Don't
forget to add corresponding cases to [T_cases] and [t_cases].)
- Extend the substitution function and value relation as in
MoreSTLC.
- Extend the operational semantics with the same reduction rules
as in MoreSTLC.
- Extend the subtyping relation with this rule:
S1 <: T1 S2 <: T2
--------------------- (Sub_Prod)
S1 * S2 <: T1 * T2
- Extend the typing relation with the same rules for pairs and
projections as in MoreSTLC.
- Extend the proofs of progress, preservation, and all their
supporting lemmas to deal with the new constructs. (You'll also
need to add some completely new lemmas.)
[] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Sub: Subtyping *)
Require Export Types.
(* ###################################################### *)
(** * Concepts *)
(** We now turn to the study of _subtyping_, perhaps the most
characteristic feature of the static type systems of recently
designed programming languages and a key feature needed to support
the object-oriented programming style. *)
(* ###################################################### *)
(** ** A Motivating Example *)
(** Suppose we are writing a program involving two record types
defined as follows:
<<
Person = {name:String, age:Nat}
Student = {name:String, age:Nat, gpa:Nat}
>>
*)
(** In the simply typed lamdba-calculus with records, the term
<<
(\r:Person. (r.age)+1) {name="Pat",age=21,gpa=1}
>>
is not typable: it involves an application of a function that wants
a one-field record to an argument that actually provides two
fields, while the [T_App] rule demands that the domain type of the
function being applied must match the type of the argument
precisely.
But this is silly: we're passing the function a _better_ argument
than it needs! The only thing the body of the function can
possibly do with its record argument [r] is project the field [age]
from it: nothing else is allowed by the type, and the presence or
absence of an extra [gpa] field makes no difference at all. So,
intuitively, it seems that this function should be applicable to
any record value that has at least an [age] field.
Looking at the same thing from another point of view, a record with
more fields is "at least as good in any context" as one with just a
subset of these fields, in the sense that any value belonging to
the longer record type can be used _safely_ in any context
expecting the shorter record type. If the context expects
something with the shorter type but we actually give it something
with the longer type, nothing bad will happen (formally, the
program will not get stuck).
The general principle at work here is called _subtyping_. We say
that "[S] is a subtype of [T]", informally written [S <: T], if a
value of type [S] can safely be used in any context where a value
of type [T] is expected. The idea of subtyping applies not only to
records, but to all of the type constructors in the language --
functions, pairs, etc. *)
(** ** Subtyping and Object-Oriented Languages *)
(** Subtyping plays a fundamental role in many programming
languages -- in particular, it is closely related to the notion of
_subclassing_ in object-oriented languages.
An _object_ in Java, C[#], etc. can be thought of as a record,
some of whose fields are functions ("methods") and some of whose
fields are data values ("fields" or "instance variables").
Invoking a method [m] of an object [o] on some arguments [a1..an]
consists of projecting out the [m] field of [o] and applying it to
[a1..an].
The type of an object can be given as either a _class_ or an
_interface_. Both of these provide a description of which methods
and which data fields the object offers.
Classes and interfaces are related by the _subclass_ and
_subinterface_ relations. An object belonging to a subclass (or
subinterface) is required to provide all the methods and fields of
one belonging to a superclass (or superinterface), plus possibly
some more.
The fact that an object from a subclass (or sub-interface) can be
used in place of one from a superclass (or super-interface)
provides a degree of flexibility that is is extremely handy for
organizing complex libraries. For example, a GUI toolkit like
Java's Swing framework might define an abstract interface
[Component] that collects together the common fields and methods
of all objects having a graphical representation that can be
displayed on the screen and that can interact with the user.
Examples of such object would include the buttons, checkboxes, and
scrollbars of a typical GUI. A method that relies only on this
common interface can now be applied to any of these objects.
Of course, real object-oriented languages include many other
features besides these. For example, fields can be updated.
Fields and methods can be declared [private]. Classes also give
_code_ that is used when constructing objects and implementing
their methods, and the code in subclasses cooperate with code in
superclasses via _inheritance_. Classes can have static methods
and fields, initializers, etc., etc.
To keep things simple here, we won't deal with any of these
issues -- in fact, we won't even talk any more about objects or
classes. (There is a lot of discussion in _Types and Programming
Languages_, if you are interested.) Instead, we'll study the core
concepts behind the subclass / subinterface relation in the
simplified setting of the STLC. *)
(** *** *)
(** Of course, real OO languages have lots of other features...
- mutable fields
- [private] and other visibility modifiers
- method inheritance
- static components
- etc., etc.
We'll ignore all these and focus on core mechanisms. *)
(** ** The Subsumption Rule *)
(** Our goal for this chapter is to add subtyping to the simply typed
lambda-calculus (with some of the basic extensions from [MoreStlc]).
This involves two steps:
- Defining a binary _subtype relation_ between types.
- Enriching the typing relation to take subtyping into account.
The second step is actually very simple. We add just a single rule
to the typing relation: the so-called _rule of subsumption_:
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
This rule says, intuitively, that it is OK to "forget" some of
what we know about a term. *)
(** For example, we may know that [t] is a record with two
fields (e.g., [S = {x:A->A, y:B->B}]), but choose to forget about
one of the fields ([T = {y:B->B}]) so that we can pass [t] to a
function that requires just a single-field record. *)
(** ** The Subtype Relation *)
(** The first step -- the definition of the relation [S <: T] -- is
where all the action is. Let's look at each of the clauses of its
definition. *)
(** *** Structural Rules *)
(** To start off, we impose two "structural rules" that are
independent of any particular type constructor: a rule of
_transitivity_, which says intuitively that, if [S] is better than
[U] and [U] is better than [T], then [S] is better than [T]...
S <: U U <: T
---------------- (S_Trans)
S <: T
... and a rule of _reflexivity_, since certainly any type [T] is
as good as itself:
------ (S_Refl)
T <: T
*)
(** *** Products *)
(** Now we consider the individual type constructors, one by one,
beginning with product types. We consider one pair to be "better
than" another if each of its components is.
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
*)
(** *** Arrows *)
(** Suppose we have two functions [f] and [g] with these types:
f : C -> Student
g : (C->Person) -> D
That is, [f] is a function that yields a record of type [Student],
and [g] is a (higher-order) function that expects its (function)
argument to yield a record of type [Person]. Also suppose, even
though we haven't yet discussed subtyping for records, that
[Student] is a subtype of [Person]. Then the application [g f] is
safe even though their types do not match up precisely, because
the only thing [g] can do with [f] is to apply it to some
argument (of type [C]); the result will actually be a [Student],
while [g] will be expecting a [Person], but this is safe because
the only thing [g] can then do is to project out the two fields
that it knows about ([name] and [age]), and these will certainly
be among the fields that are present.
This example suggests that the subtyping rule for arrow types
should say that two arrow types are in the subtype relation if
their results are:
S2 <: T2
---------------- (S_Arrow_Co)
S1 -> S2 <: S1 -> T2
We can generalize this to allow the arguments of the two arrow
types to be in the subtype relation as well:
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
Notice that the argument types are subtypes "the other way round":
in order to conclude that [S1->S2] to be a subtype of [T1->T2], it
must be the case that [T1] is a subtype of [S1]. The arrow
constructor is said to be _contravariant_ in its first argument
and _covariant_ in its second.
Here is an example that illustrates this:
f : Person -> C
g : (Student -> C) -> D
The application [g f] is safe, because the only thing the body of
[g] can do with [f] is to apply it to some argument of type
[Student]. Since [f] requires records having (at least) the
fields of a [Person], this will always work. So [Person -> C] is a
subtype of [Student -> C] since [Student] is a subtype of
[Person].
The intuition is that, if we have a function [f] of type [S1->S2],
then we know that [f] accepts elements of type [S1]; clearly, [f]
will also accept elements of any subtype [T1] of [S1]. The type of
[f] also tells us that it returns elements of type [S2]; we can
also view these results belonging to any supertype [T2] of
[S2]. That is, any function [f] of type [S1->S2] can also be
viewed as having type [T1->T2].
*)
(** *** Records *)
(** What about subtyping for record types? *)
(** The basic intuition about subtyping for record types is that it is
always safe to use a "bigger" record in place of a "smaller" one.
That is, given a record type, adding extra fields will always
result in a subtype. If some code is expecting a record with
fields [x] and [y], it is perfectly safe for it to receive a record
with fields [x], [y], and [z]; the [z] field will simply be ignored.
For example,
{name:String, age:Nat, gpa:Nat} <: {name:String, age:Nat}
{name:String, age:Nat} <: {name:String}
{name:String} <: {}
This is known as "width subtyping" for records. *)
(** We can also create a subtype of a record type by replacing the type
of one of its fields with a subtype. If some code is expecting a
record with a field [x] of type [T], it will be happy with a record
having a field [x] of type [S] as long as [S] is a subtype of
[T]. For example,
{x:Student} <: {x:Person}
This is known as "depth subtyping". *)
(** Finally, although the fields of a record type are written in a
particular order, the order does not really matter. For example,
{name:String,age:Nat} <: {age:Nat,name:String}
This is known as "permutation subtyping". *)
(** We could formalize these requirements in a single subtyping rule
for records as follows:
for each jk in j1..jn,
exists ip in i1..im, such that
jk=ip and Sp <: Tk
---------------------------------- (S_Rcd)
{i1:S1...im:Sm} <: {j1:T1...jn:Tn}
That is, the record on the left should have all the field labels of
the one on the right (and possibly more), while the types of the
common fields should be in the subtype relation. However, this rule
is rather heavy and hard to read. If we like, we can decompose it
into three simpler rules, which can be combined using [S_Trans] to
achieve all the same effects. *)
(** First, adding fields to the end of a record type gives a subtype:
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
We can use [S_RcdWidth] to drop later fields of a multi-field
record while keeping earlier fields, showing for example that
[{age:Nat,name:String} <: {name:String}]. *)
(** Second, we can apply subtyping inside the components of a compound
record type:
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
For example, we can use [S_RcdDepth] and [S_RcdWidth] together to
show that [{y:Student, x:Nat} <: {y:Person}]. *)
(** Third, we need to be able to reorder fields. For example, we
might expect that [{name:String, gpa:Nat, age:Nat} <: Person]. We
haven't quite achieved this yet: using just [S_RcdDepth] and
[S_RcdWidth] we can only drop fields from the _end_ of a record
type. So we need:
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(** It is worth noting that full-blown language designs may choose not
to adopt all of these subtyping rules. For example, in Java:
- A subclass may not change the argument or result types of a
method of its superclass (i.e., no depth subtyping or no arrow
subtyping, depending how you look at it).
- Each class has just one superclass ("single inheritance" of
classes).
- Each class member (field or method) can be assigned a single
index, adding new indices "on the right" as more members are
added in subclasses (i.e., no permutation for classes).
- A class may implement multiple interfaces -- so-called "multiple
inheritance" of interfaces (i.e., permutation is allowed for
interfaces). *)
(** **** Exercise: 2 stars (arrow_sub_wrong) *)
(** Suppose we had incorrectly defined subtyping as covariant on both
the right and the left of arrow types:
S1 <: T1 S2 <: T2
-------------------- (S_Arrow_wrong)
S1 -> S2 <: T1 -> T2
Give a concrete example of functions [f] and [g] with the following types...
f : Student -> Nat
g : (Person -> Nat) -> Nat
... such that the application [g f] will get stuck during
execution.
[] *)
(** *** Top *)
(** Finally, it is natural to give the subtype relation a maximal
element -- a type that lies above every other type and is
inhabited by all (well-typed) values. We do this by adding to the
language one new type constant, called [Top], together with a
subtyping rule that places it above every other type in the
subtype relation:
-------- (S_Top)
S <: Top
The [Top] type is an analog of the [Object] type in Java and C[#]. *)
(* ############################################### *)
(** *** Summary *)
(** In summary, we form the STLC with subtyping by starting with the
pure STLC (over some set of base types) and...
- adding a base type [Top],
- adding the rule of subsumption
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
to the typing relation, and
- defining a subtype relation as follows:
S <: U U <: T
---------------- (S_Trans)
S <: T
------ (S_Refl)
T <: T
-------- (S_Top)
S <: Top
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(* ############################################### *)
(** ** Exercises *)
(** **** Exercise: 1 star, optional (subtype_instances_tf_1) *)
(** Suppose we have types [S], [T], [U], and [V] with [S <: T]
and [U <: V]. Which of the following subtyping assertions
are then true? Write _true_ or _false_ after each one.
([A], [B], and [C] here are base types.)
- [T->S <: T->S]
- [Top->U <: S->Top]
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
- [T->T->U <: S->S->V]
- [(T->T)->U <: (S->S)->V]
- [((T->S)->T)->U <: ((S->T)->S)->V]
- [S*V <: T*U]
[] *)
(** **** Exercise: 2 stars (subtype_order) *)
(** The following types happen to form a linear order with respect to subtyping:
- [Top]
- [Top -> Student]
- [Student -> Person]
- [Student -> Top]
- [Person -> Student]
Write these types in order from the most specific to the most general.
Where does the type [Top->Top->Student] fit into this order?
*)
(** **** Exercise: 1 star (subtype_instances_tf_2) *)
(** Which of the following statements are true? Write _true_ or
_false_ after each one.
forall S T,
S <: T ->
S->S <: T->T
forall S,
S <: A->A ->
exists T,
S = T->T /\ T <: A
forall S T1 T2,
(S <: T1 -> T2) ->
exists S1 S2,
S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
exists S,
S <: S->S
exists S,
S->S <: S
forall S T1 T2,
S <: T1*T2 ->
exists S1 S2,
S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
[] *)
(** **** Exercise: 1 star (subtype_concepts_tf) *)
(** Which of the following statements are true, and which are false?
- There exists a type that is a supertype of every other type.
- There exists a type that is a subtype of every other type.
- There exists a pair type that is a supertype of every other
pair type.
- There exists a pair type that is a subtype of every other
pair type.
- There exists an arrow type that is a supertype of every other
arrow type.
- There exists an arrow type that is a subtype of every other
arrow type.
- There is an infinite descending chain of distinct types in the
subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a subtype of [Si].
- There is an infinite _ascending_ chain of distinct types in
the subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a supertype of [Si].
[] *)
(** **** Exercise: 2 stars (proper_subtypes) *)
(** Is the following statement true or false? Briefly explain your
answer.
forall T,
~(exists n, T = TBase n) ->
exists S,
S <: T /\ S <> T
]]
[] *)
(** **** Exercise: 2 stars (small_large_1) *)
(**
- What is the _smallest_ type [T] ("smallest" in the subtype
relation) that makes the following assertion true? (Assume we
have [Unit] among the base types and [unit] as a constant of this
type.)
empty |- (\p:T*Top. p.fst) ((\z:A.z), unit) : A->A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_2) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\p:(A->A * B->B). p) ((\z:A.z), (\z:B.z)) : T
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars, optional (small_large_3) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
a:A |- (\p:(A*T). (p.snd) (p.fst)) (a , \z:A.z) : A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_4) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
exists S,
empty |- (\p:(A*T). (p.snd) (p.fst)) : S
- What is the _largest_ type [T] that makes the same
assertion true?
[] *)
(** **** Exercise: 2 stars (smallest_1) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
exists S, exists t,
empty |- (\x:T. x x) t : S
]]
[] *)
(** **** Exercise: 2 stars (smallest_2) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\x:Top. x) ((\z:A.z) , (\z:B.z)) : T
]]
[] *)
(** **** Exercise: 3 stars, optional (count_supertypes) *)
(** How many supertypes does the record type [{x:A, y:C->C}] have? That is,
how many different types [T] are there such that [{x:A, y:C->C} <:
T]? (We consider two types to be different if they are written
differently, even if each is a subtype of the other. For example,
[{x:A,y:B}] and [{y:B,x:A}] are different.)
[] *)
(** **** Exercise: 2 stars (pair_permutation) *)
(** The subtyping rule for product types
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1*S2 <: T1*T2
intuitively corresponds to the "depth" subtyping rule for records. Extending the analogy, we might consider adding a "permutation" rule
--------------
T1*T2 <: T2*T1
for products.
Is this a good idea? Briefly explain why or why not.
[] *)
(* ###################################################### *)
(** * Formal Definitions *)
(** Most of the definitions -- in particular, the syntax and
operational semantics of the language -- are identical to what we
saw in the last chapter. We just need to extend the typing
relation with the subsumption rule and add a new [Inductive]
definition for the subtyping relation. Let's first do the
identical bits. *)
(* ###################################################### *)
(** ** Core Definitions *)
(* ################################### *)
(** *** Syntax *)
(** For the sake of more interesting examples below, we'll allow an
arbitrary set of additional base types like [String], [Float],
etc. We won't bother adding any constants belonging to these
types or any operators on them, but we could easily do so. *)
(** In the rest of the chapter, we formalize just base types,
booleans, arrow types, [Unit], and [Top], omitting record types
and leaving product types as an exercise. *)
Inductive ty : Type :=
| TTop : ty
| TBool : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
| TUnit : ty
.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBool"
| Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TUnit" |
].
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tunit : tm
.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif"
| Case_aux c "tunit"
].
(* ################################### *)
(** *** Substitution *)
(** The definition of substitution remains exactly the same as for the
pure STLC. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
tunit
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
(** Likewise the definitions of the [value] property and the [step]
relation. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse
| v_unit :
value tunit
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
].
Hint Constructors step.
(* ###################################################################### *)
(** ** Subtyping *)
(** Now we come to the most interesting part. We begin by
defining the subtyping relation and developing some of its
important technical properties. *)
(** The definition of subtyping is just what we sketched in the
motivating discussion. *)
Reserved Notation "T '<:' U" (at level 40).
Inductive subtype : ty -> ty -> Prop :=
| S_Refl : forall T,
T <: T
| S_Trans : forall S U T,
S <: U ->
U <: T ->
S <: T
| S_Top : forall S,
S <: TTop
| S_Arrow : forall S1 S2 T1 T2,
T1 <: S1 ->
S2 <: T2 ->
(TArrow S1 S2) <: (TArrow T1 T2)
where "T '<:' U" := (subtype T U).
(** Note that we don't need any special rules for base types: they are
automatically subtypes of themselves (by [S_Refl]) and [Top] (by
[S_Top]), and that's all we want. *)
Hint Constructors subtype.
Tactic Notation "subtype_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "S_Refl" | Case_aux c "S_Trans"
| Case_aux c "S_Top" | Case_aux c "S_Arrow"
].
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Notation String := (TBase (Id 9)).
Notation Float := (TBase (Id 10)).
Notation Integer := (TBase (Id 11)).
(** **** Exercise: 2 stars, optional (subtyping_judgements) *)
(** (Do this exercise after you have added product types to the
language, at least up to this point in the file).
Using the encoding of records into pairs, define pair types
representing the record types
Person := { name : String }
Student := { name : String ;
gpa : Float }
Employee := { name : String ;
ssn : Integer }
Recall that in chapter MoreStlc, the optional subsection "Encoding
Records" describes how records can be encoded as pairs.
*)
Definition Person : ty :=
(* FILL IN HERE *) admit.
Definition Student : ty :=
(* FILL IN HERE *) admit.
Definition Employee : ty :=
(* FILL IN HERE *) admit.
Example sub_student_person :
Student <: Person.
Proof.
(* FILL IN HERE *) Admitted.
Example sub_employee_person :
Employee <: Person.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
Example subtyping_example_0 :
(TArrow C Person) <: (TArrow C TTop).
(* C->Person <: C->Top *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
Qed.
(** The following facts are mostly easy to prove in Coq. To get
full benefit from the exercises, make sure you also
understand how to prove them on paper! *)
(** **** Exercise: 1 star, optional (subtyping_example_1) *)
Example subtyping_example_1 :
(TArrow TTop Student) <: (TArrow (TArrow C C) Person).
(* Top->Student <: (C->C)->Person *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
End Examples.
(* ###################################################################### *)
(** ** Typing *)
(** The only change to the typing relation is the addition of the rule
of subsumption, [T_Sub]. *)
Definition context := id -> (option ty).
Definition empty : context := (fun _ => None).
Definition extend (Gamma : context) (x:id) (T : ty) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Same as before *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- (tif t1 t2 t3) \in T
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* New rule of subsumption *)
| T_Sub : forall Gamma t S T,
Gamma |- t \in S ->
S <: T ->
Gamma |- t \in T
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Unit"
| Case_aux c "T_Sub" ].
(* To make your job simpler, the following hints help construct typing
derivations. *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
Hint Extern 2 (_ = _) => compute; reflexivity.
(* ############################################### *)
(** ** Typing examples *)
Module Examples2.
Import Examples.
(** Do the following exercises after you have added product types to
the language. For each informal typing judgement, write it as a
formal statement in Coq and prove it. *)
(** **** Exercise: 1 star, optional (typing_example_0) *)
(* empty |- ((\z:A.z), (\z:B.z))
: (A->A * B->B) *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_2) *)
(* empty |- (\z:(C->C)->(Top * B->B). (z (\x:C.x)).snd)
(\z:C->C. ((\z:A.z), (\z:B.z)))
: B->B *)
(* FILL IN HERE *)
(** [] *)
End Examples2.
(* ###################################################################### *)
(** * Properties *)
(** The fundamental properties of the system that we want to check are
the same as always: progress and preservation. Unlike the
extension of the STLC with references, we don't need to change the
_statements_ of these properties to take subtyping into account.
However, their proofs do become a little bit more involved. *)
(* ###################################################################### *)
(** ** Inversion Lemmas for Subtyping *)
(** Before we look at the properties of the typing relation, we need
to record a couple of critical structural properties of the subtype
relation:
- [Bool] is the only subtype of [Bool]
- every subtype of an arrow type is itself an arrow type. *)
(** These are called _inversion lemmas_ because they play the same
role in later proofs as the built-in [inversion] tactic: given a
hypothesis that there exists a derivation of some subtyping
statement [S <: T] and some constraints on the shape of [S] and/or
[T], each one reasons about what this derivation must look like to
tell us something further about the shapes of [S] and [T] and the
existence of subtype relations between their parts. *)
(** **** Exercise: 2 stars, optional (sub_inversion_Bool) *)
Lemma sub_inversion_Bool : forall U,
U <: TBool ->
U = TBool.
Proof with auto.
intros U Hs.
remember TBool as V.
(* FILL IN HERE *) Admitted.
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
U <: (TArrow V1 V2) ->
exists U1, exists U2,
U = (TArrow U1 U2) /\ (V1 <: U1) /\ (U2 <: V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ########################################## *)
(** ** Canonical Forms *)
(** We'll see first that the proof of the progress theorem doesn't
change too much -- we just need one small refinement. When we're
considering the case where the term in question is an application
[t1 t2] where both [t1] and [t2] are values, we need to know that
[t1] has the _form_ of a lambda-abstraction, so that we can apply
the [ST_AppAbs] reduction rule. In the ordinary STLC, this is
obvious: we know that [t1] has a function type [T11->T12], and
there is only one rule that can be used to give a function type to
a value -- rule [T_Abs] -- and the form of the conclusion of this
rule forces [t1] to be an abstraction.
In the STLC with subtyping, this reasoning doesn't quite work
because there's another rule that can be used to show that a value
has a function type: subsumption. Fortunately, this possibility
doesn't change things much: if the last rule used to show [Gamma
|- t1 : T11->T12] is subsumption, then there is some
_sub_-derivation whose subject is also [t1], and we can reason by
induction until we finally bottom out at a use of [T_Abs].
This bit of reasoning is packaged up in the following lemma, which
tells us the possible "canonical forms" (i.e. values) of function
type. *)
(** **** Exercise: 3 stars, optional (canonical_forms_of_arrow_types) *)
Lemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,
Gamma |- s \in (TArrow T1 T2) ->
value s ->
exists x, exists S1, exists s2,
s = tabs x S1 s2.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Similarly, the canonical forms of type [Bool] are the constants
[true] and [false]. *)
Lemma canonical_forms_of_Bool : forall Gamma s,
Gamma |- s \in TBool ->
value s ->
(s = ttrue \/ s = tfalse).
Proof with eauto.
intros Gamma s Hty Hv.
remember TBool as T.
has_type_cases (induction Hty) Case; try solve by inversion...
Case "T_Sub".
subst. apply sub_inversion_Bool in H. subst...
Qed.
(* ########################################## *)
(** ** Progress *)
(** The proof of progress proceeds like the one for the pure
STLC, except that in several places we invoke canonical forms
lemmas... *)
(** _Theorem_ (Progress): For any term [t] and type [T], if [empty |-
t : T] then [t] is a value or [t ==> t'] for some term [t'].
_Proof_: Let [t] and [T] be given, with [empty |- t : T]. Proceed
by induction on the typing derivation.
The cases for [T_Abs], [T_Unit], [T_True] and [T_False] are
immediate because abstractions, [unit], [true], and [false] are
already values. The [T_Var] case is vacuous because variables
cannot be typed in the empty context. The remaining cases are
more interesting:
- If the last step in the typing derivation uses rule [T_App],
then there are terms [t1] [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and [empty |-
t2 : T1]. Moreover, by the induction hypothesis, either [t1] is
a value or it steps, and either [t2] is a value or it steps.
There are three possibilities to consider:
- Suppose [t1 ==> t1'] for some term [t1']. Then [t1 t2 ==> t1' t2]
by [ST_App1].
- Suppose [t1] is a value and [t2 ==> t2'] for some term [t2'].
Then [t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a
value.
- Finally, suppose [t1] and [t2] are both values. By Lemma
[canonical_forms_for_arrow_types], we know that [t1] has the
form [\x:S1.s2] for some [x], [S1], and [s2]. But then
[(\x:S1.s2) t2 ==> [x:=t2]s2] by [ST_AppAbs], since [t2] is a
value.
- If the final step of the derivation uses rule [T_If], then there
are terms [t1], [t2], and [t3] such that [t = if t1 then t2 else
t3], with [empty |- t1 : Bool] and with [empty |- t2 : T] and
[empty |- t3 : T]. Moreover, by the induction hypothesis,
either [t1] is a value or it steps.
- If [t1] is a value, then by the canonical forms lemma for
booleans, either [t1 = true] or [t1 = false]. In either
case, [t] can step, using rule [ST_IfTrue] or [ST_IfFalse].
- If [t1] can step, then so can [t], by rule [ST_If].
- If the final step of the derivation is by [T_Sub], then there is
a type [S] such that [S <: T] and [empty |- t : S]. The desired
result is exactly the induction hypothesis for the typing
subderivation.
*)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
intros t T Ht.
remember empty as Gamma.
revert HeqGamma.
has_type_cases (induction Ht) Case;
intros HeqGamma; subst...
Case "T_Var".
inversion H.
Case "T_App".
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
destruct (canonical_forms_of_arrow_types empty t1 T1 T2)
as [x [S1 [t12 Heqt1]]]...
subst. exists ([x:=t2]t12)...
SSCase "t2 steps".
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_If".
right.
destruct IHHt1.
SCase "t1 is a value"...
assert (t1 = ttrue \/ t1 = tfalse)
by (eapply canonical_forms_of_Bool; eauto).
inversion H0; subst...
inversion H. rename x into t1'. eauto.
Qed.
(* ########################################## *)
(** ** Inversion Lemmas for Typing *)
(** The proof of the preservation theorem also becomes a little more
complex with the addition of subtyping. The reason is that, as
with the "inversion lemmas for subtyping" above, there are a
number of facts about the typing relation that are "obvious from
the definition" in the pure STLC (and hence can be obtained
directly from the [inversion] tactic) but that require real proofs
in the presence of subtyping because there are multiple ways to
derive the same [has_type] statement.
The following "inversion lemma" tells us that, if we have a
derivation of some typing statement [Gamma |- \x:S1.t2 : T] whose
subject is an abstraction, then there must be some subderivation
giving a type to the body [t2]. *)
(** _Lemma_: If [Gamma |- \x:S1.t2 : T], then there is a type [S2]
such that [Gamma, x:S1 |- t2 : S2] and [S1 -> S2 <: T].
(Notice that the lemma does _not_ say, "then [T] itself is an arrow
type" -- this is tempting, but false!)
_Proof_: Let [Gamma], [x], [S1], [t2] and [T] be given as
described. Proceed by induction on the derivation of [Gamma |-
\x:S1.t2 : T]. Cases [T_Var], [T_App], are vacuous as those
rules cannot be used to give a type to a syntactic abstraction.
- If the last step of the derivation is a use of [T_Abs] then
there is a type [T12] such that [T = S1 -> T12] and [Gamma,
x:S1 |- t2 : T12]. Picking [T12] for [S2] gives us what we
need: [S1 -> T12 <: S1 -> T12] follows from [S_Refl].
- If the last step of the derivation is a use of [T_Sub] then
there is a type [S] such that [S <: T] and [Gamma |- \x:S1.t2 :
S]. The IH for the typing subderivation tell us that there is
some type [S2] with [S1 -> S2 <: S] and [Gamma, x:S1 |- t2 :
S2]. Picking type [S2] gives us what we need, since [S1 -> S2
<: T] then follows by [S_Trans]. *)
Lemma typing_inversion_abs : forall Gamma x S1 t2 T,
Gamma |- (tabs x S1 t2) \in T ->
(exists S2, (TArrow S1 S2) <: T
/\ (extend Gamma x S1) |- t2 \in S2).
Proof with eauto.
intros Gamma x S1 t2 T H.
remember (tabs x S1 t2) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Abs".
exists T12...
Case "T_Sub".
destruct IHhas_type as [S2 [Hsub Hty]]...
Qed.
(** Similarly... *)
Lemma typing_inversion_var : forall Gamma x T,
Gamma |- (tvar x) \in T ->
exists S,
Gamma x = Some S /\ S <: T.
Proof with eauto.
intros Gamma x T Hty.
remember (tvar x) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_Var".
exists T...
Case "T_Sub".
destruct IHHty as [U [Hctx HsubU]]... Qed.
Lemma typing_inversion_app : forall Gamma t1 t2 T2,
Gamma |- (tapp t1 t2) \in T2 ->
exists T1,
Gamma |- t1 \in (TArrow T1 T2) /\
Gamma |- t2 \in T1.
Proof with eauto.
intros Gamma t1 t2 T2 Hty.
remember (tapp t1 t2) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_App".
exists T1...
Case "T_Sub".
destruct IHHty as [U1 [Hty1 Hty2]]...
Qed.
Lemma typing_inversion_true : forall Gamma T,
Gamma |- ttrue \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember ttrue as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_false : forall Gamma T,
Gamma |- tfalse \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember tfalse as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_if : forall Gamma t1 t2 t3 T,
Gamma |- (tif t1 t2 t3) \in T ->
Gamma |- t1 \in TBool
/\ Gamma |- t2 \in T
/\ Gamma |- t3 \in T.
Proof with eauto.
intros Gamma t1 t2 t3 T Hty.
remember (tif t1 t2 t3) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_If".
auto.
Case "T_Sub".
destruct (IHHty H0) as [H1 [H2 H3]]...
Qed.
Lemma typing_inversion_unit : forall Gamma T,
Gamma |- tunit \in T ->
TUnit <: T.
Proof with eauto.
intros Gamma T Htyp. remember tunit as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
(** The inversion lemmas for typing and for subtyping between arrow
types can be packaged up as a useful "combination lemma" telling
us exactly what we'll actually require below. *)
Lemma abs_arrow : forall x S1 s2 T1 T2,
empty |- (tabs x S1 s2) \in (TArrow T1 T2) ->
T1 <: S1
/\ (extend empty x S1) |- s2 \in T2.
Proof with eauto.
intros x S1 s2 T1 T2 Hty.
apply typing_inversion_abs in Hty.
inversion Hty as [S2 [Hsub Hty1]].
apply sub_inversion_arrow in Hsub.
inversion Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].
inversion Heq; subst... Qed.
(* ########################################## *)
(** ** Context Invariance *)
(** The context invariance lemma follows the same pattern as in the
pure STLC. *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_if1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif t1 t2 t3)
| afi_if2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif t1 t2 t3)
| afi_if3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif t1 t2 t3)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros x0 Hafi.
unfold extend. destruct (eq_id_dec x x0)...
Case "T_If".
apply T_If...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case;
subst; inversion Hafi; subst...
Case "T_Abs".
destruct (IHHtyp H4) as [T Hctx]. exists T.
unfold extend in Hctx. rewrite neq_id in Hctx... Qed.
(* ########################################## *)
(** ** Substitution *)
(** The _substitution lemma_ is proved along the same lines as
for the pure STLC. The only significant change is that there are
several places where, instead of the built-in [inversion] tactic,
we need to use the inversion lemmas that we proved above to
extract structural information from assumptions about the
well-typedness of subterms. *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
intros Gamma x U v t S Htypt Htypv.
generalize dependent S. generalize dependent Gamma.
t_cases (induction t) Case; intros; simpl.
Case "tvar".
rename i into y.
destruct (typing_inversion_var _ _ _ Htypt)
as [T [Hctx Hsub]].
unfold extend in Hctx.
destruct (eq_id_dec x y)...
SCase "x=y".
subst.
inversion Hctx; subst. clear Hctx.
apply context_invariance with empty...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra)
as [T' HT']...
inversion HT'.
Case "tapp".
destruct (typing_inversion_app _ _ _ _ Htypt)
as [T1 [Htypt1 Htypt2]].
eapply T_App...
Case "tabs".
rename i into y. rename t into T1.
destruct (typing_inversion_abs _ _ _ _ _ Htypt)
as [T2 [Hsub Htypt2]].
apply T_Sub with (TArrow T1 T2)... apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
Case "ttrue".
assert (TBool <: S)
by apply (typing_inversion_true _ _ Htypt)...
Case "tfalse".
assert (TBool <: S)
by apply (typing_inversion_false _ _ Htypt)...
Case "tif".
assert ((extend Gamma x U) |- t1 \in TBool
/\ (extend Gamma x U) |- t2 \in S
/\ (extend Gamma x U) |- t3 \in S)
by apply (typing_inversion_if _ _ _ _ _ Htypt).
inversion H as [H1 [H2 H3]].
apply IHt1 in H1. apply IHt2 in H2. apply IHt3 in H3.
auto.
Case "tunit".
assert (TUnit <: S)
by apply (typing_inversion_unit _ _ Htypt)...
Qed.
(* ########################################## *)
(** ** Preservation *)
(** The proof of preservation now proceeds pretty much as in earlier
chapters, using the substitution lemma at the appropriate point
and again using inversion lemmas from above to extract structural
information from typing assumptions. *)
(** _Theorem_ (Preservation): If [t], [t'] are terms and [T] is a type
such that [empty |- t : T] and [t ==> t'], then [empty |- t' :
T].
_Proof_: Let [t] and [T] be given such that [empty |- t : T]. We
proceed by induction on the structure of this typing derivation,
leaving [t'] general. The cases [T_Abs], [T_Unit], [T_True], and
[T_False] cases are vacuous because abstractions and constants
don't step. Case [T_Var] is vacuous as well, since the context is
empty.
- If the final step of the derivation is by [T_App], then there
are terms [t1] and [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and
[empty |- t2 : T1].
By the definition of the step relation, there are three ways
[t1 t2] can step. Cases [ST_App1] and [ST_App2] follow
immediately by the induction hypotheses for the typing
subderivations and a use of [T_App].
Suppose instead [t1 t2] steps by [ST_AppAbs]. Then [t1 =
\x:S.t12] for some type [S] and term [t12], and [t' =
[x:=t2]t12].
By lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].
It then follows by the substitution lemma
([substitution_preserves_typing]) that [empty |- [x:=t2]
t12 : T2] as desired.
- If the final step of the derivation uses rule [T_If], then
there are terms [t1], [t2], and [t3] such that [t = if t1 then
t2 else t3], with [empty |- t1 : Bool] and with [empty |- t2 :
T] and [empty |- t3 : T]. Moreover, by the induction
hypothesis, if [t1] steps to [t1'] then [empty |- t1' : Bool].
There are three cases to consider, depending on which rule was
used to show [t ==> t'].
- If [t ==> t'] by rule [ST_If], then [t' = if t1' then t2
else t3] with [t1 ==> t1']. By the induction hypothesis,
[empty |- t1' : Bool], and so [empty |- t' : T] by [T_If].
- If [t ==> t'] by rule [ST_IfTrue] or [ST_IfFalse], then
either [t' = t2] or [t' = t3], and [empty |- t' : T]
follows by assumption.
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
result is immediate by the induction hypothesis for the typing
subderivation and an application of [T_Sub]. [] *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
remember empty as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
inversion HE; subst...
SCase "ST_AppAbs".
destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].
apply substitution_preserves_typing with T...
Qed.
(** ** Records, via Products and Top *)
(** This formalization of the STLC with subtyping has omitted record
types, for brevity. If we want to deal with them more seriously,
we have two choices.
First, we can treat them as part of the core language, writing
down proper syntax, typing, and subtyping rules for them. Chapter
[RecordSub] shows how this extension works.
On the other hand, if we are treating them as a derived form that
is desugared in the parser, then we shouldn't need any new rules:
we should just check that the existing rules for subtyping product
and [Unit] types give rise to reasonable rules for record
subtyping via this encoding. To do this, we just need to make one
small change to the encoding described earlier: instead of using
[Unit] as the base case in the encoding of tuples and the "don't
care" placeholder in the encoding of records, we use [Top]. So:
<<
{a:Nat, b:Nat} ----> {Nat,Nat} i.e. (Nat,(Nat,Top))
{c:Nat, a:Nat} ----> {Nat,Top,Nat} i.e. (Nat,(Top,(Nat,Top)))
>>
The encoding of record values doesn't change at all. It is
easy (and instructive) to check that the subtyping rules above are
validated by the encoding. For the rest of this chapter, we'll
follow this encoding-based approach. *)
(* ###################################################### *)
(** ** Exercises *)
(** **** Exercise: 2 stars (variations) *)
(** Each part of this problem suggests a different way of
changing the definition of the STLC with Unit and
subtyping. (These changes are not cumulative: each part
starts from the original language.) In each part, list which
properties (Progress, Preservation, both, or neither) become
false. If a property becomes false, give a counterexample.
- Suppose we add the following typing rule:
Gamma |- t : S1->S2
S1 <: T1 T1 <: S1 S2 <: T2
----------------------------------- (T_Funny1)
Gamma |- t : T1->T2
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
unit ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
Unit <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: Unit
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
- Suppose we add the same evaluation rule _and_ a new typing rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
---------------------- (T_Funny6)
empty |- Unit : Top->Top
- Suppose we _change_ the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
[] *)
(* ###################################################################### *)
(** * Exercise: Adding Products *)
(** **** Exercise: 4 stars (products) *)
(** Adding pairs, projections, and product types to the system we have
defined is a relatively straightforward matter. Carry out this
extension:
- Add constructors for pairs, first and second projections, and
product types to the definitions of [ty] and [tm]. (Don't
forget to add corresponding cases to [T_cases] and [t_cases].)
- Extend the substitution function and value relation as in
MoreSTLC.
- Extend the operational semantics with the same reduction rules
as in MoreSTLC.
- Extend the subtyping relation with this rule:
S1 <: T1 S2 <: T2
--------------------- (Sub_Prod)
S1 * S2 <: T1 * T2
- Extend the typing relation with the same rules for pairs and
projections as in MoreSTLC.
- Extend the proofs of progress, preservation, and all their
supporting lemmas to deal with the new constructs. (You'll also
need to add some completely new lemmas.)
[] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Sub: Subtyping *)
Require Export Types.
(* ###################################################### *)
(** * Concepts *)
(** We now turn to the study of _subtyping_, perhaps the most
characteristic feature of the static type systems of recently
designed programming languages and a key feature needed to support
the object-oriented programming style. *)
(* ###################################################### *)
(** ** A Motivating Example *)
(** Suppose we are writing a program involving two record types
defined as follows:
<<
Person = {name:String, age:Nat}
Student = {name:String, age:Nat, gpa:Nat}
>>
*)
(** In the simply typed lamdba-calculus with records, the term
<<
(\r:Person. (r.age)+1) {name="Pat",age=21,gpa=1}
>>
is not typable: it involves an application of a function that wants
a one-field record to an argument that actually provides two
fields, while the [T_App] rule demands that the domain type of the
function being applied must match the type of the argument
precisely.
But this is silly: we're passing the function a _better_ argument
than it needs! The only thing the body of the function can
possibly do with its record argument [r] is project the field [age]
from it: nothing else is allowed by the type, and the presence or
absence of an extra [gpa] field makes no difference at all. So,
intuitively, it seems that this function should be applicable to
any record value that has at least an [age] field.
Looking at the same thing from another point of view, a record with
more fields is "at least as good in any context" as one with just a
subset of these fields, in the sense that any value belonging to
the longer record type can be used _safely_ in any context
expecting the shorter record type. If the context expects
something with the shorter type but we actually give it something
with the longer type, nothing bad will happen (formally, the
program will not get stuck).
The general principle at work here is called _subtyping_. We say
that "[S] is a subtype of [T]", informally written [S <: T], if a
value of type [S] can safely be used in any context where a value
of type [T] is expected. The idea of subtyping applies not only to
records, but to all of the type constructors in the language --
functions, pairs, etc. *)
(** ** Subtyping and Object-Oriented Languages *)
(** Subtyping plays a fundamental role in many programming
languages -- in particular, it is closely related to the notion of
_subclassing_ in object-oriented languages.
An _object_ in Java, C[#], etc. can be thought of as a record,
some of whose fields are functions ("methods") and some of whose
fields are data values ("fields" or "instance variables").
Invoking a method [m] of an object [o] on some arguments [a1..an]
consists of projecting out the [m] field of [o] and applying it to
[a1..an].
The type of an object can be given as either a _class_ or an
_interface_. Both of these provide a description of which methods
and which data fields the object offers.
Classes and interfaces are related by the _subclass_ and
_subinterface_ relations. An object belonging to a subclass (or
subinterface) is required to provide all the methods and fields of
one belonging to a superclass (or superinterface), plus possibly
some more.
The fact that an object from a subclass (or sub-interface) can be
used in place of one from a superclass (or super-interface)
provides a degree of flexibility that is is extremely handy for
organizing complex libraries. For example, a GUI toolkit like
Java's Swing framework might define an abstract interface
[Component] that collects together the common fields and methods
of all objects having a graphical representation that can be
displayed on the screen and that can interact with the user.
Examples of such object would include the buttons, checkboxes, and
scrollbars of a typical GUI. A method that relies only on this
common interface can now be applied to any of these objects.
Of course, real object-oriented languages include many other
features besides these. For example, fields can be updated.
Fields and methods can be declared [private]. Classes also give
_code_ that is used when constructing objects and implementing
their methods, and the code in subclasses cooperate with code in
superclasses via _inheritance_. Classes can have static methods
and fields, initializers, etc., etc.
To keep things simple here, we won't deal with any of these
issues -- in fact, we won't even talk any more about objects or
classes. (There is a lot of discussion in _Types and Programming
Languages_, if you are interested.) Instead, we'll study the core
concepts behind the subclass / subinterface relation in the
simplified setting of the STLC. *)
(** *** *)
(** Of course, real OO languages have lots of other features...
- mutable fields
- [private] and other visibility modifiers
- method inheritance
- static components
- etc., etc.
We'll ignore all these and focus on core mechanisms. *)
(** ** The Subsumption Rule *)
(** Our goal for this chapter is to add subtyping to the simply typed
lambda-calculus (with some of the basic extensions from [MoreStlc]).
This involves two steps:
- Defining a binary _subtype relation_ between types.
- Enriching the typing relation to take subtyping into account.
The second step is actually very simple. We add just a single rule
to the typing relation: the so-called _rule of subsumption_:
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
This rule says, intuitively, that it is OK to "forget" some of
what we know about a term. *)
(** For example, we may know that [t] is a record with two
fields (e.g., [S = {x:A->A, y:B->B}]), but choose to forget about
one of the fields ([T = {y:B->B}]) so that we can pass [t] to a
function that requires just a single-field record. *)
(** ** The Subtype Relation *)
(** The first step -- the definition of the relation [S <: T] -- is
where all the action is. Let's look at each of the clauses of its
definition. *)
(** *** Structural Rules *)
(** To start off, we impose two "structural rules" that are
independent of any particular type constructor: a rule of
_transitivity_, which says intuitively that, if [S] is better than
[U] and [U] is better than [T], then [S] is better than [T]...
S <: U U <: T
---------------- (S_Trans)
S <: T
... and a rule of _reflexivity_, since certainly any type [T] is
as good as itself:
------ (S_Refl)
T <: T
*)
(** *** Products *)
(** Now we consider the individual type constructors, one by one,
beginning with product types. We consider one pair to be "better
than" another if each of its components is.
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
*)
(** *** Arrows *)
(** Suppose we have two functions [f] and [g] with these types:
f : C -> Student
g : (C->Person) -> D
That is, [f] is a function that yields a record of type [Student],
and [g] is a (higher-order) function that expects its (function)
argument to yield a record of type [Person]. Also suppose, even
though we haven't yet discussed subtyping for records, that
[Student] is a subtype of [Person]. Then the application [g f] is
safe even though their types do not match up precisely, because
the only thing [g] can do with [f] is to apply it to some
argument (of type [C]); the result will actually be a [Student],
while [g] will be expecting a [Person], but this is safe because
the only thing [g] can then do is to project out the two fields
that it knows about ([name] and [age]), and these will certainly
be among the fields that are present.
This example suggests that the subtyping rule for arrow types
should say that two arrow types are in the subtype relation if
their results are:
S2 <: T2
---------------- (S_Arrow_Co)
S1 -> S2 <: S1 -> T2
We can generalize this to allow the arguments of the two arrow
types to be in the subtype relation as well:
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
Notice that the argument types are subtypes "the other way round":
in order to conclude that [S1->S2] to be a subtype of [T1->T2], it
must be the case that [T1] is a subtype of [S1]. The arrow
constructor is said to be _contravariant_ in its first argument
and _covariant_ in its second.
Here is an example that illustrates this:
f : Person -> C
g : (Student -> C) -> D
The application [g f] is safe, because the only thing the body of
[g] can do with [f] is to apply it to some argument of type
[Student]. Since [f] requires records having (at least) the
fields of a [Person], this will always work. So [Person -> C] is a
subtype of [Student -> C] since [Student] is a subtype of
[Person].
The intuition is that, if we have a function [f] of type [S1->S2],
then we know that [f] accepts elements of type [S1]; clearly, [f]
will also accept elements of any subtype [T1] of [S1]. The type of
[f] also tells us that it returns elements of type [S2]; we can
also view these results belonging to any supertype [T2] of
[S2]. That is, any function [f] of type [S1->S2] can also be
viewed as having type [T1->T2].
*)
(** *** Records *)
(** What about subtyping for record types? *)
(** The basic intuition about subtyping for record types is that it is
always safe to use a "bigger" record in place of a "smaller" one.
That is, given a record type, adding extra fields will always
result in a subtype. If some code is expecting a record with
fields [x] and [y], it is perfectly safe for it to receive a record
with fields [x], [y], and [z]; the [z] field will simply be ignored.
For example,
{name:String, age:Nat, gpa:Nat} <: {name:String, age:Nat}
{name:String, age:Nat} <: {name:String}
{name:String} <: {}
This is known as "width subtyping" for records. *)
(** We can also create a subtype of a record type by replacing the type
of one of its fields with a subtype. If some code is expecting a
record with a field [x] of type [T], it will be happy with a record
having a field [x] of type [S] as long as [S] is a subtype of
[T]. For example,
{x:Student} <: {x:Person}
This is known as "depth subtyping". *)
(** Finally, although the fields of a record type are written in a
particular order, the order does not really matter. For example,
{name:String,age:Nat} <: {age:Nat,name:String}
This is known as "permutation subtyping". *)
(** We could formalize these requirements in a single subtyping rule
for records as follows:
for each jk in j1..jn,
exists ip in i1..im, such that
jk=ip and Sp <: Tk
---------------------------------- (S_Rcd)
{i1:S1...im:Sm} <: {j1:T1...jn:Tn}
That is, the record on the left should have all the field labels of
the one on the right (and possibly more), while the types of the
common fields should be in the subtype relation. However, this rule
is rather heavy and hard to read. If we like, we can decompose it
into three simpler rules, which can be combined using [S_Trans] to
achieve all the same effects. *)
(** First, adding fields to the end of a record type gives a subtype:
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
We can use [S_RcdWidth] to drop later fields of a multi-field
record while keeping earlier fields, showing for example that
[{age:Nat,name:String} <: {name:String}]. *)
(** Second, we can apply subtyping inside the components of a compound
record type:
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
For example, we can use [S_RcdDepth] and [S_RcdWidth] together to
show that [{y:Student, x:Nat} <: {y:Person}]. *)
(** Third, we need to be able to reorder fields. For example, we
might expect that [{name:String, gpa:Nat, age:Nat} <: Person]. We
haven't quite achieved this yet: using just [S_RcdDepth] and
[S_RcdWidth] we can only drop fields from the _end_ of a record
type. So we need:
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(** It is worth noting that full-blown language designs may choose not
to adopt all of these subtyping rules. For example, in Java:
- A subclass may not change the argument or result types of a
method of its superclass (i.e., no depth subtyping or no arrow
subtyping, depending how you look at it).
- Each class has just one superclass ("single inheritance" of
classes).
- Each class member (field or method) can be assigned a single
index, adding new indices "on the right" as more members are
added in subclasses (i.e., no permutation for classes).
- A class may implement multiple interfaces -- so-called "multiple
inheritance" of interfaces (i.e., permutation is allowed for
interfaces). *)
(** **** Exercise: 2 stars (arrow_sub_wrong) *)
(** Suppose we had incorrectly defined subtyping as covariant on both
the right and the left of arrow types:
S1 <: T1 S2 <: T2
-------------------- (S_Arrow_wrong)
S1 -> S2 <: T1 -> T2
Give a concrete example of functions [f] and [g] with the following types...
f : Student -> Nat
g : (Person -> Nat) -> Nat
... such that the application [g f] will get stuck during
execution.
[] *)
(** *** Top *)
(** Finally, it is natural to give the subtype relation a maximal
element -- a type that lies above every other type and is
inhabited by all (well-typed) values. We do this by adding to the
language one new type constant, called [Top], together with a
subtyping rule that places it above every other type in the
subtype relation:
-------- (S_Top)
S <: Top
The [Top] type is an analog of the [Object] type in Java and C[#]. *)
(* ############################################### *)
(** *** Summary *)
(** In summary, we form the STLC with subtyping by starting with the
pure STLC (over some set of base types) and...
- adding a base type [Top],
- adding the rule of subsumption
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
to the typing relation, and
- defining a subtype relation as follows:
S <: U U <: T
---------------- (S_Trans)
S <: T
------ (S_Refl)
T <: T
-------- (S_Top)
S <: Top
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(* ############################################### *)
(** ** Exercises *)
(** **** Exercise: 1 star, optional (subtype_instances_tf_1) *)
(** Suppose we have types [S], [T], [U], and [V] with [S <: T]
and [U <: V]. Which of the following subtyping assertions
are then true? Write _true_ or _false_ after each one.
([A], [B], and [C] here are base types.)
- [T->S <: T->S]
- [Top->U <: S->Top]
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
- [T->T->U <: S->S->V]
- [(T->T)->U <: (S->S)->V]
- [((T->S)->T)->U <: ((S->T)->S)->V]
- [S*V <: T*U]
[] *)
(** **** Exercise: 2 stars (subtype_order) *)
(** The following types happen to form a linear order with respect to subtyping:
- [Top]
- [Top -> Student]
- [Student -> Person]
- [Student -> Top]
- [Person -> Student]
Write these types in order from the most specific to the most general.
Where does the type [Top->Top->Student] fit into this order?
*)
(** **** Exercise: 1 star (subtype_instances_tf_2) *)
(** Which of the following statements are true? Write _true_ or
_false_ after each one.
forall S T,
S <: T ->
S->S <: T->T
forall S,
S <: A->A ->
exists T,
S = T->T /\ T <: A
forall S T1 T2,
(S <: T1 -> T2) ->
exists S1 S2,
S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
exists S,
S <: S->S
exists S,
S->S <: S
forall S T1 T2,
S <: T1*T2 ->
exists S1 S2,
S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
[] *)
(** **** Exercise: 1 star (subtype_concepts_tf) *)
(** Which of the following statements are true, and which are false?
- There exists a type that is a supertype of every other type.
- There exists a type that is a subtype of every other type.
- There exists a pair type that is a supertype of every other
pair type.
- There exists a pair type that is a subtype of every other
pair type.
- There exists an arrow type that is a supertype of every other
arrow type.
- There exists an arrow type that is a subtype of every other
arrow type.
- There is an infinite descending chain of distinct types in the
subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a subtype of [Si].
- There is an infinite _ascending_ chain of distinct types in
the subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a supertype of [Si].
[] *)
(** **** Exercise: 2 stars (proper_subtypes) *)
(** Is the following statement true or false? Briefly explain your
answer.
forall T,
~(exists n, T = TBase n) ->
exists S,
S <: T /\ S <> T
]]
[] *)
(** **** Exercise: 2 stars (small_large_1) *)
(**
- What is the _smallest_ type [T] ("smallest" in the subtype
relation) that makes the following assertion true? (Assume we
have [Unit] among the base types and [unit] as a constant of this
type.)
empty |- (\p:T*Top. p.fst) ((\z:A.z), unit) : A->A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_2) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\p:(A->A * B->B). p) ((\z:A.z), (\z:B.z)) : T
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars, optional (small_large_3) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
a:A |- (\p:(A*T). (p.snd) (p.fst)) (a , \z:A.z) : A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_4) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
exists S,
empty |- (\p:(A*T). (p.snd) (p.fst)) : S
- What is the _largest_ type [T] that makes the same
assertion true?
[] *)
(** **** Exercise: 2 stars (smallest_1) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
exists S, exists t,
empty |- (\x:T. x x) t : S
]]
[] *)
(** **** Exercise: 2 stars (smallest_2) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\x:Top. x) ((\z:A.z) , (\z:B.z)) : T
]]
[] *)
(** **** Exercise: 3 stars, optional (count_supertypes) *)
(** How many supertypes does the record type [{x:A, y:C->C}] have? That is,
how many different types [T] are there such that [{x:A, y:C->C} <:
T]? (We consider two types to be different if they are written
differently, even if each is a subtype of the other. For example,
[{x:A,y:B}] and [{y:B,x:A}] are different.)
[] *)
(** **** Exercise: 2 stars (pair_permutation) *)
(** The subtyping rule for product types
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1*S2 <: T1*T2
intuitively corresponds to the "depth" subtyping rule for records. Extending the analogy, we might consider adding a "permutation" rule
--------------
T1*T2 <: T2*T1
for products.
Is this a good idea? Briefly explain why or why not.
[] *)
(* ###################################################### *)
(** * Formal Definitions *)
(** Most of the definitions -- in particular, the syntax and
operational semantics of the language -- are identical to what we
saw in the last chapter. We just need to extend the typing
relation with the subsumption rule and add a new [Inductive]
definition for the subtyping relation. Let's first do the
identical bits. *)
(* ###################################################### *)
(** ** Core Definitions *)
(* ################################### *)
(** *** Syntax *)
(** For the sake of more interesting examples below, we'll allow an
arbitrary set of additional base types like [String], [Float],
etc. We won't bother adding any constants belonging to these
types or any operators on them, but we could easily do so. *)
(** In the rest of the chapter, we formalize just base types,
booleans, arrow types, [Unit], and [Top], omitting record types
and leaving product types as an exercise. *)
Inductive ty : Type :=
| TTop : ty
| TBool : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
| TUnit : ty
.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBool"
| Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TUnit" |
].
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tunit : tm
.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif"
| Case_aux c "tunit"
].
(* ################################### *)
(** *** Substitution *)
(** The definition of substitution remains exactly the same as for the
pure STLC. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
tunit
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
(** Likewise the definitions of the [value] property and the [step]
relation. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse
| v_unit :
value tunit
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
].
Hint Constructors step.
(* ###################################################################### *)
(** ** Subtyping *)
(** Now we come to the most interesting part. We begin by
defining the subtyping relation and developing some of its
important technical properties. *)
(** The definition of subtyping is just what we sketched in the
motivating discussion. *)
Reserved Notation "T '<:' U" (at level 40).
Inductive subtype : ty -> ty -> Prop :=
| S_Refl : forall T,
T <: T
| S_Trans : forall S U T,
S <: U ->
U <: T ->
S <: T
| S_Top : forall S,
S <: TTop
| S_Arrow : forall S1 S2 T1 T2,
T1 <: S1 ->
S2 <: T2 ->
(TArrow S1 S2) <: (TArrow T1 T2)
where "T '<:' U" := (subtype T U).
(** Note that we don't need any special rules for base types: they are
automatically subtypes of themselves (by [S_Refl]) and [Top] (by
[S_Top]), and that's all we want. *)
Hint Constructors subtype.
Tactic Notation "subtype_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "S_Refl" | Case_aux c "S_Trans"
| Case_aux c "S_Top" | Case_aux c "S_Arrow"
].
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Notation String := (TBase (Id 9)).
Notation Float := (TBase (Id 10)).
Notation Integer := (TBase (Id 11)).
(** **** Exercise: 2 stars, optional (subtyping_judgements) *)
(** (Do this exercise after you have added product types to the
language, at least up to this point in the file).
Using the encoding of records into pairs, define pair types
representing the record types
Person := { name : String }
Student := { name : String ;
gpa : Float }
Employee := { name : String ;
ssn : Integer }
Recall that in chapter MoreStlc, the optional subsection "Encoding
Records" describes how records can be encoded as pairs.
*)
Definition Person : ty :=
(* FILL IN HERE *) admit.
Definition Student : ty :=
(* FILL IN HERE *) admit.
Definition Employee : ty :=
(* FILL IN HERE *) admit.
Example sub_student_person :
Student <: Person.
Proof.
(* FILL IN HERE *) Admitted.
Example sub_employee_person :
Employee <: Person.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
Example subtyping_example_0 :
(TArrow C Person) <: (TArrow C TTop).
(* C->Person <: C->Top *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
Qed.
(** The following facts are mostly easy to prove in Coq. To get
full benefit from the exercises, make sure you also
understand how to prove them on paper! *)
(** **** Exercise: 1 star, optional (subtyping_example_1) *)
Example subtyping_example_1 :
(TArrow TTop Student) <: (TArrow (TArrow C C) Person).
(* Top->Student <: (C->C)->Person *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
End Examples.
(* ###################################################################### *)
(** ** Typing *)
(** The only change to the typing relation is the addition of the rule
of subsumption, [T_Sub]. *)
Definition context := id -> (option ty).
Definition empty : context := (fun _ => None).
Definition extend (Gamma : context) (x:id) (T : ty) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Same as before *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- (tif t1 t2 t3) \in T
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* New rule of subsumption *)
| T_Sub : forall Gamma t S T,
Gamma |- t \in S ->
S <: T ->
Gamma |- t \in T
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Unit"
| Case_aux c "T_Sub" ].
(* To make your job simpler, the following hints help construct typing
derivations. *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
Hint Extern 2 (_ = _) => compute; reflexivity.
(* ############################################### *)
(** ** Typing examples *)
Module Examples2.
Import Examples.
(** Do the following exercises after you have added product types to
the language. For each informal typing judgement, write it as a
formal statement in Coq and prove it. *)
(** **** Exercise: 1 star, optional (typing_example_0) *)
(* empty |- ((\z:A.z), (\z:B.z))
: (A->A * B->B) *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_2) *)
(* empty |- (\z:(C->C)->(Top * B->B). (z (\x:C.x)).snd)
(\z:C->C. ((\z:A.z), (\z:B.z)))
: B->B *)
(* FILL IN HERE *)
(** [] *)
End Examples2.
(* ###################################################################### *)
(** * Properties *)
(** The fundamental properties of the system that we want to check are
the same as always: progress and preservation. Unlike the
extension of the STLC with references, we don't need to change the
_statements_ of these properties to take subtyping into account.
However, their proofs do become a little bit more involved. *)
(* ###################################################################### *)
(** ** Inversion Lemmas for Subtyping *)
(** Before we look at the properties of the typing relation, we need
to record a couple of critical structural properties of the subtype
relation:
- [Bool] is the only subtype of [Bool]
- every subtype of an arrow type is itself an arrow type. *)
(** These are called _inversion lemmas_ because they play the same
role in later proofs as the built-in [inversion] tactic: given a
hypothesis that there exists a derivation of some subtyping
statement [S <: T] and some constraints on the shape of [S] and/or
[T], each one reasons about what this derivation must look like to
tell us something further about the shapes of [S] and [T] and the
existence of subtype relations between their parts. *)
(** **** Exercise: 2 stars, optional (sub_inversion_Bool) *)
Lemma sub_inversion_Bool : forall U,
U <: TBool ->
U = TBool.
Proof with auto.
intros U Hs.
remember TBool as V.
(* FILL IN HERE *) Admitted.
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
U <: (TArrow V1 V2) ->
exists U1, exists U2,
U = (TArrow U1 U2) /\ (V1 <: U1) /\ (U2 <: V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ########################################## *)
(** ** Canonical Forms *)
(** We'll see first that the proof of the progress theorem doesn't
change too much -- we just need one small refinement. When we're
considering the case where the term in question is an application
[t1 t2] where both [t1] and [t2] are values, we need to know that
[t1] has the _form_ of a lambda-abstraction, so that we can apply
the [ST_AppAbs] reduction rule. In the ordinary STLC, this is
obvious: we know that [t1] has a function type [T11->T12], and
there is only one rule that can be used to give a function type to
a value -- rule [T_Abs] -- and the form of the conclusion of this
rule forces [t1] to be an abstraction.
In the STLC with subtyping, this reasoning doesn't quite work
because there's another rule that can be used to show that a value
has a function type: subsumption. Fortunately, this possibility
doesn't change things much: if the last rule used to show [Gamma
|- t1 : T11->T12] is subsumption, then there is some
_sub_-derivation whose subject is also [t1], and we can reason by
induction until we finally bottom out at a use of [T_Abs].
This bit of reasoning is packaged up in the following lemma, which
tells us the possible "canonical forms" (i.e. values) of function
type. *)
(** **** Exercise: 3 stars, optional (canonical_forms_of_arrow_types) *)
Lemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,
Gamma |- s \in (TArrow T1 T2) ->
value s ->
exists x, exists S1, exists s2,
s = tabs x S1 s2.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Similarly, the canonical forms of type [Bool] are the constants
[true] and [false]. *)
Lemma canonical_forms_of_Bool : forall Gamma s,
Gamma |- s \in TBool ->
value s ->
(s = ttrue \/ s = tfalse).
Proof with eauto.
intros Gamma s Hty Hv.
remember TBool as T.
has_type_cases (induction Hty) Case; try solve by inversion...
Case "T_Sub".
subst. apply sub_inversion_Bool in H. subst...
Qed.
(* ########################################## *)
(** ** Progress *)
(** The proof of progress proceeds like the one for the pure
STLC, except that in several places we invoke canonical forms
lemmas... *)
(** _Theorem_ (Progress): For any term [t] and type [T], if [empty |-
t : T] then [t] is a value or [t ==> t'] for some term [t'].
_Proof_: Let [t] and [T] be given, with [empty |- t : T]. Proceed
by induction on the typing derivation.
The cases for [T_Abs], [T_Unit], [T_True] and [T_False] are
immediate because abstractions, [unit], [true], and [false] are
already values. The [T_Var] case is vacuous because variables
cannot be typed in the empty context. The remaining cases are
more interesting:
- If the last step in the typing derivation uses rule [T_App],
then there are terms [t1] [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and [empty |-
t2 : T1]. Moreover, by the induction hypothesis, either [t1] is
a value or it steps, and either [t2] is a value or it steps.
There are three possibilities to consider:
- Suppose [t1 ==> t1'] for some term [t1']. Then [t1 t2 ==> t1' t2]
by [ST_App1].
- Suppose [t1] is a value and [t2 ==> t2'] for some term [t2'].
Then [t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a
value.
- Finally, suppose [t1] and [t2] are both values. By Lemma
[canonical_forms_for_arrow_types], we know that [t1] has the
form [\x:S1.s2] for some [x], [S1], and [s2]. But then
[(\x:S1.s2) t2 ==> [x:=t2]s2] by [ST_AppAbs], since [t2] is a
value.
- If the final step of the derivation uses rule [T_If], then there
are terms [t1], [t2], and [t3] such that [t = if t1 then t2 else
t3], with [empty |- t1 : Bool] and with [empty |- t2 : T] and
[empty |- t3 : T]. Moreover, by the induction hypothesis,
either [t1] is a value or it steps.
- If [t1] is a value, then by the canonical forms lemma for
booleans, either [t1 = true] or [t1 = false]. In either
case, [t] can step, using rule [ST_IfTrue] or [ST_IfFalse].
- If [t1] can step, then so can [t], by rule [ST_If].
- If the final step of the derivation is by [T_Sub], then there is
a type [S] such that [S <: T] and [empty |- t : S]. The desired
result is exactly the induction hypothesis for the typing
subderivation.
*)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
intros t T Ht.
remember empty as Gamma.
revert HeqGamma.
has_type_cases (induction Ht) Case;
intros HeqGamma; subst...
Case "T_Var".
inversion H.
Case "T_App".
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
destruct (canonical_forms_of_arrow_types empty t1 T1 T2)
as [x [S1 [t12 Heqt1]]]...
subst. exists ([x:=t2]t12)...
SSCase "t2 steps".
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_If".
right.
destruct IHHt1.
SCase "t1 is a value"...
assert (t1 = ttrue \/ t1 = tfalse)
by (eapply canonical_forms_of_Bool; eauto).
inversion H0; subst...
inversion H. rename x into t1'. eauto.
Qed.
(* ########################################## *)
(** ** Inversion Lemmas for Typing *)
(** The proof of the preservation theorem also becomes a little more
complex with the addition of subtyping. The reason is that, as
with the "inversion lemmas for subtyping" above, there are a
number of facts about the typing relation that are "obvious from
the definition" in the pure STLC (and hence can be obtained
directly from the [inversion] tactic) but that require real proofs
in the presence of subtyping because there are multiple ways to
derive the same [has_type] statement.
The following "inversion lemma" tells us that, if we have a
derivation of some typing statement [Gamma |- \x:S1.t2 : T] whose
subject is an abstraction, then there must be some subderivation
giving a type to the body [t2]. *)
(** _Lemma_: If [Gamma |- \x:S1.t2 : T], then there is a type [S2]
such that [Gamma, x:S1 |- t2 : S2] and [S1 -> S2 <: T].
(Notice that the lemma does _not_ say, "then [T] itself is an arrow
type" -- this is tempting, but false!)
_Proof_: Let [Gamma], [x], [S1], [t2] and [T] be given as
described. Proceed by induction on the derivation of [Gamma |-
\x:S1.t2 : T]. Cases [T_Var], [T_App], are vacuous as those
rules cannot be used to give a type to a syntactic abstraction.
- If the last step of the derivation is a use of [T_Abs] then
there is a type [T12] such that [T = S1 -> T12] and [Gamma,
x:S1 |- t2 : T12]. Picking [T12] for [S2] gives us what we
need: [S1 -> T12 <: S1 -> T12] follows from [S_Refl].
- If the last step of the derivation is a use of [T_Sub] then
there is a type [S] such that [S <: T] and [Gamma |- \x:S1.t2 :
S]. The IH for the typing subderivation tell us that there is
some type [S2] with [S1 -> S2 <: S] and [Gamma, x:S1 |- t2 :
S2]. Picking type [S2] gives us what we need, since [S1 -> S2
<: T] then follows by [S_Trans]. *)
Lemma typing_inversion_abs : forall Gamma x S1 t2 T,
Gamma |- (tabs x S1 t2) \in T ->
(exists S2, (TArrow S1 S2) <: T
/\ (extend Gamma x S1) |- t2 \in S2).
Proof with eauto.
intros Gamma x S1 t2 T H.
remember (tabs x S1 t2) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Abs".
exists T12...
Case "T_Sub".
destruct IHhas_type as [S2 [Hsub Hty]]...
Qed.
(** Similarly... *)
Lemma typing_inversion_var : forall Gamma x T,
Gamma |- (tvar x) \in T ->
exists S,
Gamma x = Some S /\ S <: T.
Proof with eauto.
intros Gamma x T Hty.
remember (tvar x) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_Var".
exists T...
Case "T_Sub".
destruct IHHty as [U [Hctx HsubU]]... Qed.
Lemma typing_inversion_app : forall Gamma t1 t2 T2,
Gamma |- (tapp t1 t2) \in T2 ->
exists T1,
Gamma |- t1 \in (TArrow T1 T2) /\
Gamma |- t2 \in T1.
Proof with eauto.
intros Gamma t1 t2 T2 Hty.
remember (tapp t1 t2) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_App".
exists T1...
Case "T_Sub".
destruct IHHty as [U1 [Hty1 Hty2]]...
Qed.
Lemma typing_inversion_true : forall Gamma T,
Gamma |- ttrue \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember ttrue as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_false : forall Gamma T,
Gamma |- tfalse \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember tfalse as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_if : forall Gamma t1 t2 t3 T,
Gamma |- (tif t1 t2 t3) \in T ->
Gamma |- t1 \in TBool
/\ Gamma |- t2 \in T
/\ Gamma |- t3 \in T.
Proof with eauto.
intros Gamma t1 t2 t3 T Hty.
remember (tif t1 t2 t3) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_If".
auto.
Case "T_Sub".
destruct (IHHty H0) as [H1 [H2 H3]]...
Qed.
Lemma typing_inversion_unit : forall Gamma T,
Gamma |- tunit \in T ->
TUnit <: T.
Proof with eauto.
intros Gamma T Htyp. remember tunit as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
(** The inversion lemmas for typing and for subtyping between arrow
types can be packaged up as a useful "combination lemma" telling
us exactly what we'll actually require below. *)
Lemma abs_arrow : forall x S1 s2 T1 T2,
empty |- (tabs x S1 s2) \in (TArrow T1 T2) ->
T1 <: S1
/\ (extend empty x S1) |- s2 \in T2.
Proof with eauto.
intros x S1 s2 T1 T2 Hty.
apply typing_inversion_abs in Hty.
inversion Hty as [S2 [Hsub Hty1]].
apply sub_inversion_arrow in Hsub.
inversion Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].
inversion Heq; subst... Qed.
(* ########################################## *)
(** ** Context Invariance *)
(** The context invariance lemma follows the same pattern as in the
pure STLC. *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_if1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif t1 t2 t3)
| afi_if2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif t1 t2 t3)
| afi_if3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif t1 t2 t3)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros x0 Hafi.
unfold extend. destruct (eq_id_dec x x0)...
Case "T_If".
apply T_If...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case;
subst; inversion Hafi; subst...
Case "T_Abs".
destruct (IHHtyp H4) as [T Hctx]. exists T.
unfold extend in Hctx. rewrite neq_id in Hctx... Qed.
(* ########################################## *)
(** ** Substitution *)
(** The _substitution lemma_ is proved along the same lines as
for the pure STLC. The only significant change is that there are
several places where, instead of the built-in [inversion] tactic,
we need to use the inversion lemmas that we proved above to
extract structural information from assumptions about the
well-typedness of subterms. *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
intros Gamma x U v t S Htypt Htypv.
generalize dependent S. generalize dependent Gamma.
t_cases (induction t) Case; intros; simpl.
Case "tvar".
rename i into y.
destruct (typing_inversion_var _ _ _ Htypt)
as [T [Hctx Hsub]].
unfold extend in Hctx.
destruct (eq_id_dec x y)...
SCase "x=y".
subst.
inversion Hctx; subst. clear Hctx.
apply context_invariance with empty...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra)
as [T' HT']...
inversion HT'.
Case "tapp".
destruct (typing_inversion_app _ _ _ _ Htypt)
as [T1 [Htypt1 Htypt2]].
eapply T_App...
Case "tabs".
rename i into y. rename t into T1.
destruct (typing_inversion_abs _ _ _ _ _ Htypt)
as [T2 [Hsub Htypt2]].
apply T_Sub with (TArrow T1 T2)... apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
Case "ttrue".
assert (TBool <: S)
by apply (typing_inversion_true _ _ Htypt)...
Case "tfalse".
assert (TBool <: S)
by apply (typing_inversion_false _ _ Htypt)...
Case "tif".
assert ((extend Gamma x U) |- t1 \in TBool
/\ (extend Gamma x U) |- t2 \in S
/\ (extend Gamma x U) |- t3 \in S)
by apply (typing_inversion_if _ _ _ _ _ Htypt).
inversion H as [H1 [H2 H3]].
apply IHt1 in H1. apply IHt2 in H2. apply IHt3 in H3.
auto.
Case "tunit".
assert (TUnit <: S)
by apply (typing_inversion_unit _ _ Htypt)...
Qed.
(* ########################################## *)
(** ** Preservation *)
(** The proof of preservation now proceeds pretty much as in earlier
chapters, using the substitution lemma at the appropriate point
and again using inversion lemmas from above to extract structural
information from typing assumptions. *)
(** _Theorem_ (Preservation): If [t], [t'] are terms and [T] is a type
such that [empty |- t : T] and [t ==> t'], then [empty |- t' :
T].
_Proof_: Let [t] and [T] be given such that [empty |- t : T]. We
proceed by induction on the structure of this typing derivation,
leaving [t'] general. The cases [T_Abs], [T_Unit], [T_True], and
[T_False] cases are vacuous because abstractions and constants
don't step. Case [T_Var] is vacuous as well, since the context is
empty.
- If the final step of the derivation is by [T_App], then there
are terms [t1] and [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and
[empty |- t2 : T1].
By the definition of the step relation, there are three ways
[t1 t2] can step. Cases [ST_App1] and [ST_App2] follow
immediately by the induction hypotheses for the typing
subderivations and a use of [T_App].
Suppose instead [t1 t2] steps by [ST_AppAbs]. Then [t1 =
\x:S.t12] for some type [S] and term [t12], and [t' =
[x:=t2]t12].
By lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].
It then follows by the substitution lemma
([substitution_preserves_typing]) that [empty |- [x:=t2]
t12 : T2] as desired.
- If the final step of the derivation uses rule [T_If], then
there are terms [t1], [t2], and [t3] such that [t = if t1 then
t2 else t3], with [empty |- t1 : Bool] and with [empty |- t2 :
T] and [empty |- t3 : T]. Moreover, by the induction
hypothesis, if [t1] steps to [t1'] then [empty |- t1' : Bool].
There are three cases to consider, depending on which rule was
used to show [t ==> t'].
- If [t ==> t'] by rule [ST_If], then [t' = if t1' then t2
else t3] with [t1 ==> t1']. By the induction hypothesis,
[empty |- t1' : Bool], and so [empty |- t' : T] by [T_If].
- If [t ==> t'] by rule [ST_IfTrue] or [ST_IfFalse], then
either [t' = t2] or [t' = t3], and [empty |- t' : T]
follows by assumption.
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
result is immediate by the induction hypothesis for the typing
subderivation and an application of [T_Sub]. [] *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
remember empty as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
inversion HE; subst...
SCase "ST_AppAbs".
destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].
apply substitution_preserves_typing with T...
Qed.
(** ** Records, via Products and Top *)
(** This formalization of the STLC with subtyping has omitted record
types, for brevity. If we want to deal with them more seriously,
we have two choices.
First, we can treat them as part of the core language, writing
down proper syntax, typing, and subtyping rules for them. Chapter
[RecordSub] shows how this extension works.
On the other hand, if we are treating them as a derived form that
is desugared in the parser, then we shouldn't need any new rules:
we should just check that the existing rules for subtyping product
and [Unit] types give rise to reasonable rules for record
subtyping via this encoding. To do this, we just need to make one
small change to the encoding described earlier: instead of using
[Unit] as the base case in the encoding of tuples and the "don't
care" placeholder in the encoding of records, we use [Top]. So:
<<
{a:Nat, b:Nat} ----> {Nat,Nat} i.e. (Nat,(Nat,Top))
{c:Nat, a:Nat} ----> {Nat,Top,Nat} i.e. (Nat,(Top,(Nat,Top)))
>>
The encoding of record values doesn't change at all. It is
easy (and instructive) to check that the subtyping rules above are
validated by the encoding. For the rest of this chapter, we'll
follow this encoding-based approach. *)
(* ###################################################### *)
(** ** Exercises *)
(** **** Exercise: 2 stars (variations) *)
(** Each part of this problem suggests a different way of
changing the definition of the STLC with Unit and
subtyping. (These changes are not cumulative: each part
starts from the original language.) In each part, list which
properties (Progress, Preservation, both, or neither) become
false. If a property becomes false, give a counterexample.
- Suppose we add the following typing rule:
Gamma |- t : S1->S2
S1 <: T1 T1 <: S1 S2 <: T2
----------------------------------- (T_Funny1)
Gamma |- t : T1->T2
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
unit ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
Unit <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: Unit
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
- Suppose we add the same evaluation rule _and_ a new typing rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
---------------------- (T_Funny6)
empty |- Unit : Top->Top
- Suppose we _change_ the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
[] *)
(* ###################################################################### *)
(** * Exercise: Adding Products *)
(** **** Exercise: 4 stars (products) *)
(** Adding pairs, projections, and product types to the system we have
defined is a relatively straightforward matter. Carry out this
extension:
- Add constructors for pairs, first and second projections, and
product types to the definitions of [ty] and [tm]. (Don't
forget to add corresponding cases to [T_cases] and [t_cases].)
- Extend the substitution function and value relation as in
MoreSTLC.
- Extend the operational semantics with the same reduction rules
as in MoreSTLC.
- Extend the subtyping relation with this rule:
S1 <: T1 S2 <: T2
--------------------- (Sub_Prod)
S1 * S2 <: T1 * T2
- Extend the typing relation with the same rules for pairs and
projections as in MoreSTLC.
- Extend the proofs of progress, preservation, and all their
supporting lemmas to deal with the new constructs. (You'll also
need to add some completely new lemmas.)
[] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * RecordSub: Subtyping with Records *)
Require Export MoreStlc.
(* ###################################################### *)
(** * Core Definitions *)
(* ################################### *)
(** *** Syntax *)
Inductive ty : Type :=
(* proper types *)
| TTop : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
(* record types *)
| TRNil : ty
| TRCons : id -> ty -> ty -> ty.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TRNil" | Case_aux c "TRCons" ].
Inductive tm : Type :=
(* proper terms *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tproj : tm -> id -> tm
(* record terms *)
| trnil : tm
| trcons : id -> tm -> tm -> tm.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"
| Case_aux c "tproj" | Case_aux c "trnil" | Case_aux c "trcons" ].
(* ################################### *)
(** *** Well-Formedness *)
Inductive record_ty : ty -> Prop :=
| RTnil :
record_ty TRNil
| RTcons : forall i T1 T2,
record_ty (TRCons i T1 T2).
Inductive record_tm : tm -> Prop :=
| rtnil :
record_tm trnil
| rtcons : forall i t1 t2,
record_tm (trcons i t1 t2).
Inductive well_formed_ty : ty -> Prop :=
| wfTTop :
well_formed_ty TTop
| wfTBase : forall i,
well_formed_ty (TBase i)
| wfTArrow : forall T1 T2,
well_formed_ty T1 ->
well_formed_ty T2 ->
well_formed_ty (TArrow T1 T2)
| wfTRNil :
well_formed_ty TRNil
| wfTRCons : forall i T1 T2,
well_formed_ty T1 ->
well_formed_ty T2 ->
record_ty T2 ->
well_formed_ty (TRCons i T1 T2).
Hint Constructors record_ty record_tm well_formed_ty.
(* ################################### *)
(** *** Substitution *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y => if eq_id_dec x y then s else t
| tabs y T t1 => tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 => tapp (subst x s t1) (subst x s t2)
| tproj t1 i => tproj (subst x s t1) i
| trnil => trnil
| trcons i t1 tr2 => trcons i (subst x s t1) (subst x s tr2)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_rnil : value trnil
| v_rcons : forall i v vr,
value v ->
value vr ->
value (trcons i v vr).
Hint Constructors value.
Fixpoint Tlookup (i:id) (Tr:ty) : option ty :=
match Tr with
| TRCons i' T Tr' => if eq_id_dec i i' then Some T else Tlookup i Tr'
| _ => None
end.
Fixpoint tlookup (i:id) (tr:tm) : option tm :=
match tr with
| trcons i' t tr' => if eq_id_dec i i' then Some t else tlookup i tr'
| _ => None
end.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
| ST_Proj1 : forall tr tr' i,
tr ==> tr' ->
(tproj tr i) ==> (tproj tr' i)
| ST_ProjRcd : forall tr i vi,
value tr ->
tlookup i tr = Some vi ->
(tproj tr i) ==> vi
| ST_Rcd_Head : forall i t1 t1' tr2,
t1 ==> t1' ->
(trcons i t1 tr2) ==> (trcons i t1' tr2)
| ST_Rcd_Tail : forall i v1 tr2 tr2',
value v1 ->
tr2 ==> tr2' ->
(trcons i v1 tr2) ==> (trcons i v1 tr2')
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"
| Case_aux c "ST_Proj1" | Case_aux c "ST_ProjRcd" | Case_aux c "ST_Rcd"
| Case_aux c "ST_Rcd_Head" | Case_aux c "ST_Rcd_Tail" ].
Hint Constructors step.
(* ###################################################################### *)
(** * Subtyping *)
(** Now we come to the interesting part. We begin by defining
the subtyping relation and developing some of its important
technical properties. *)
(* ################################### *)
(** ** Definition *)
(** The definition of subtyping is essentially just what we
sketched in the motivating discussion, but we need to add
well-formedness side conditions to some of the rules. *)
Inductive subtype : ty -> ty -> Prop :=
(* Subtyping between proper types *)
| S_Refl : forall T,
well_formed_ty T ->
subtype T T
| S_Trans : forall S U T,
subtype S U ->
subtype U T ->
subtype S T
| S_Top : forall S,
well_formed_ty S ->
subtype S TTop
| S_Arrow : forall S1 S2 T1 T2,
subtype T1 S1 ->
subtype S2 T2 ->
subtype (TArrow S1 S2) (TArrow T1 T2)
(* Subtyping between record types *)
| S_RcdWidth : forall i T1 T2,
well_formed_ty (TRCons i T1 T2) ->
subtype (TRCons i T1 T2) TRNil
| S_RcdDepth : forall i S1 T1 Sr2 Tr2,
subtype S1 T1 ->
subtype Sr2 Tr2 ->
record_ty Sr2 ->
record_ty Tr2 ->
subtype (TRCons i S1 Sr2) (TRCons i T1 Tr2)
| S_RcdPerm : forall i1 i2 T1 T2 Tr3,
well_formed_ty (TRCons i1 T1 (TRCons i2 T2 Tr3)) ->
i1 <> i2 ->
subtype (TRCons i1 T1 (TRCons i2 T2 Tr3))
(TRCons i2 T2 (TRCons i1 T1 Tr3)).
Hint Constructors subtype.
Tactic Notation "subtype_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "S_Refl" | Case_aux c "S_Trans" | Case_aux c "S_Top"
| Case_aux c "S_Arrow" | Case_aux c "S_RcdWidth"
| Case_aux c "S_RcdDepth" | Case_aux c "S_RcdPerm" ].
(* ############################################### *)
(** ** Subtyping Examples and Exercises *)
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation j := (Id 3).
Notation k := (Id 4).
Notation i := (Id 5).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Definition TRcd_j :=
(TRCons j (TArrow B B) TRNil). (* {j:B->B} *)
Definition TRcd_kj :=
TRCons k (TArrow A A) TRcd_j. (* {k:C->C,j:B->B} *)
Example subtyping_example_0 :
subtype (TArrow C TRcd_kj)
(TArrow C TRNil).
(* C->{k:A->A,j:B->B} <: C->{} *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
unfold TRcd_kj, TRcd_j. apply S_RcdWidth; auto.
Qed.
(** The following facts are mostly easy to prove in Coq. To get
full benefit from the exercises, make sure you also
understand how to prove them on paper! *)
(** **** Exercise: 2 stars *)
Example subtyping_example_1 :
subtype TRcd_kj TRcd_j.
(* {k:A->A,j:B->B} <: {j:B->B} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star *)
Example subtyping_example_2 :
subtype (TArrow TTop TRcd_kj)
(TArrow (TArrow C C) TRcd_j).
(* Top->{k:A->A,j:B->B} <: (C->C)->{j:B->B} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star *)
Example subtyping_example_3 :
subtype (TArrow TRNil (TRCons j A TRNil))
(TArrow (TRCons k B TRNil) TRNil).
(* {}->{j:A} <: {k:B}->{} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars *)
Example subtyping_example_4 :
subtype (TRCons x A (TRCons y B (TRCons z C TRNil)))
(TRCons z C (TRCons y B (TRCons x A TRNil))).
(* {x:A,y:B,z:C} <: {z:C,y:B,x:A} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
Definition trcd_kj :=
(trcons k (tabs z A (tvar z))
(trcons j (tabs z B (tvar z))
trnil)).
End Examples.
(* ###################################################################### *)
(** ** Properties of Subtyping *)
(** *** Well-Formedness *)
Lemma subtype__wf : forall S T,
subtype S T ->
well_formed_ty T /\ well_formed_ty S.
Proof with eauto.
intros S T Hsub.
subtype_cases (induction Hsub) Case;
intros; try (destruct IHHsub1; destruct IHHsub2)...
Case "S_RcdPerm".
split... inversion H. subst. inversion H5... Qed.
Lemma wf_rcd_lookup : forall i T Ti,
well_formed_ty T ->
Tlookup i T = Some Ti ->
well_formed_ty Ti.
Proof with eauto.
intros i T.
T_cases (induction T) Case; intros; try solve by inversion.
Case "TRCons".
inversion H. subst. unfold Tlookup in H0.
destruct (eq_id_dec i i0)... inversion H0; subst... Qed.
(** *** Field Lookup *)
(** Our record matching lemmas get a little more complicated in
the presence of subtyping for two reasons: First, record
types no longer necessarily describe the exact structure of
corresponding terms. Second, reasoning by induction on
[has_type] derivations becomes harder in general, because
[has_type] is no longer syntax directed. *)
Lemma rcd_types_match : forall S T i Ti,
subtype S T ->
Tlookup i T = Some Ti ->
exists Si, Tlookup i S = Some Si /\ subtype Si Ti.
Proof with (eauto using wf_rcd_lookup).
intros S T i Ti Hsub Hget. generalize dependent Ti.
subtype_cases (induction Hsub) Case; intros Ti Hget;
try solve by inversion.
Case "S_Refl".
exists Ti...
Case "S_Trans".
destruct (IHHsub2 Ti) as [Ui Hui]... destruct Hui.
destruct (IHHsub1 Ui) as [Si Hsi]... destruct Hsi.
exists Si...
Case "S_RcdDepth".
rename i0 into k.
unfold Tlookup. unfold Tlookup in Hget.
destruct (eq_id_dec i k)...
SCase "i = k -- we're looking up the first field".
inversion Hget. subst. exists S1...
Case "S_RcdPerm".
exists Ti. split.
SCase "lookup".
unfold Tlookup. unfold Tlookup in Hget.
destruct (eq_id_dec i i1)...
SSCase "i = i1 -- we're looking up the first field".
destruct (eq_id_dec i i2)...
SSSCase "i = i2 - -contradictory".
destruct H0.
subst...
SCase "subtype".
inversion H. subst. inversion H5. subst... Qed.
(** **** Exercise: 3 stars (rcd_types_match_informal) *)
(** Write a careful informal proof of the [rcd_types_match]
lemma. *)
(* FILL IN HERE *)
(** [] *)
(** *** Inversion Lemmas *)
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
subtype U (TArrow V1 V2) ->
exists U1, exists U2,
(U=(TArrow U1 U2)) /\ (subtype V1 U1) /\ (subtype U2 V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** * Typing *)
Definition context := id -> (option ty).
Definition empty : context := (fun _ => None).
Definition extend (Gamma : context) (x:id) (T : ty) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
| T_Var : forall Gamma x T,
Gamma x = Some T ->
well_formed_ty T ->
has_type Gamma (tvar x) T
| T_Abs : forall Gamma x T11 T12 t12,
well_formed_ty T11 ->
has_type (extend Gamma x T11) t12 T12 ->
has_type Gamma (tabs x T11 t12) (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
has_type Gamma t1 (TArrow T1 T2) ->
has_type Gamma t2 T1 ->
has_type Gamma (tapp t1 t2) T2
| T_Proj : forall Gamma i t T Ti,
has_type Gamma t T ->
Tlookup i T = Some Ti ->
has_type Gamma (tproj t i) Ti
(* Subsumption *)
| T_Sub : forall Gamma t S T,
has_type Gamma t S ->
subtype S T ->
has_type Gamma t T
(* Rules for record terms *)
| T_RNil : forall Gamma,
has_type Gamma trnil TRNil
| T_RCons : forall Gamma i t T tr Tr,
has_type Gamma t T ->
has_type Gamma tr Tr ->
record_ty Tr ->
record_tm tr ->
has_type Gamma (trcons i t tr) (TRCons i T Tr)
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Proj" | Case_aux c "T_Sub"
| Case_aux c "T_RNil" | Case_aux c "T_RCons" ].
(* ############################################### *)
(** ** Typing Examples *)
Module Examples2.
Import Examples.
(** **** Exercise: 1 star *)
Example typing_example_0 :
has_type empty
(trcons k (tabs z A (tvar z))
(trcons j (tabs z B (tvar z))
trnil))
TRcd_kj.
(* empty |- {k=(\z:A.z), j=(\z:B.z)} : {k:A->A,j:B->B} *)
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars *)
Example typing_example_1 :
has_type empty
(tapp (tabs x TRcd_j (tproj (tvar x) j))
(trcd_kj))
(TArrow B B).
(* empty |- (\x:{k:A->A,j:B->B}. x.j) {k=(\z:A.z), j=(\z:B.z)} : B->B *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
Example typing_example_2 :
has_type empty
(tapp (tabs z (TArrow (TArrow C C) TRcd_j)
(tproj (tapp (tvar z)
(tabs x C (tvar x)))
j))
(tabs z (TArrow C C) trcd_kj))
(TArrow B B).
(* empty |- (\z:(C->C)->{j:B->B}. (z (\x:C.x)).j)
(\z:C->C. {k=(\z:A.z), j=(\z:B.z)})
: B->B *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
End Examples2.
(* ###################################################################### *)
(** ** Properties of Typing *)
(** *** Well-Formedness *)
Lemma has_type__wf : forall Gamma t T,
has_type Gamma t T -> well_formed_ty T.
Proof with eauto.
intros Gamma t T Htyp.
has_type_cases (induction Htyp) Case...
Case "T_App".
inversion IHHtyp1...
Case "T_Proj".
eapply wf_rcd_lookup...
Case "T_Sub".
apply subtype__wf in H.
destruct H...
Qed.
Lemma step_preserves_record_tm : forall tr tr',
record_tm tr ->
tr ==> tr' ->
record_tm tr'.
Proof.
intros tr tr' Hrt Hstp.
inversion Hrt; subst; inversion Hstp; subst; eauto.
Qed.
(** *** Field Lookup *)
Lemma lookup_field_in_value : forall v T i Ti,
value v ->
has_type empty v T ->
Tlookup i T = Some Ti ->
exists vi, tlookup i v = Some vi /\ has_type empty vi Ti.
Proof with eauto.
remember empty as Gamma.
intros t T i Ti Hval Htyp. revert Ti HeqGamma Hval.
has_type_cases (induction Htyp) Case; intros; subst; try solve by inversion.
Case "T_Sub".
apply (rcd_types_match S) in H0... destruct H0 as [Si [HgetSi Hsub]].
destruct (IHHtyp Si) as [vi [Hget Htyvi]]...
Case "T_RCons".
simpl in H0. simpl. simpl in H1.
destruct (eq_id_dec i i0).
SCase "i is first".
inversion H1. subst. exists t...
SCase "i in tail".
destruct (IHHtyp2 Ti) as [vi [get Htyvi]]...
inversion Hval... Qed.
(* ########################################## *)
(** *** Progress *)
(** **** Exercise: 3 stars (canonical_forms_of_arrow_types) *)
Lemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,
has_type Gamma s (TArrow T1 T2) ->
value s ->
exists x, exists S1, exists s2,
s = tabs x S1 s2.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
Theorem progress : forall t T,
has_type empty t T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
intros t T Ht.
remember empty as Gamma.
revert HeqGamma.
has_type_cases (induction Ht) Case;
intros HeqGamma; subst...
Case "T_Var".
inversion H.
Case "T_App".
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
destruct (canonical_forms_of_arrow_types empty t1 T1 T2)
as [x [S1 [t12 Heqt1]]]...
subst. exists ([x:=t2]t12)...
SSCase "t2 steps".
destruct H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
destruct H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_Proj".
right. destruct IHHt...
SCase "rcd is value".
destruct (lookup_field_in_value t T i Ti) as [t' [Hget Ht']]...
SCase "rcd_steps".
destruct H0 as [t' Hstp]. exists (tproj t' i)...
Case "T_RCons".
destruct IHHt1...
SCase "head is a value".
destruct IHHt2...
SSCase "tail steps".
right. destruct H2 as [tr' Hstp].
exists (trcons i t tr')...
SCase "head steps".
right. destruct H1 as [t' Hstp].
exists (trcons i t' tr)... Qed.
(** Informal proof of progress:
Theorem : For any term [t] and type [T], if [empty |- t : T]
then [t] is a value or [t ==> t'] for some term [t'].
Proof : Let [t] and [T] be given such that [empty |- t : T]. We go
by induction on the typing derivation. Cases [T_Abs] and
[T_RNil] are immediate because abstractions and [{}] are always
values. Case [T_Var] is vacuous because variables cannot be
typed in the empty context.
- If the last step in the typing derivation is by [T_App], then
there are terms [t1] [t2] and types [T1] [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2] and
[empty |- t2 : T1].
The induction hypotheses for these typing derivations yield
that [t1] is a value or steps, and that [t2] is a value or
steps. We consider each case:
- Suppose [t1 ==> t1'] for some term [t1']. Then
[t1 t2 ==> t1' t2] by [ST_App1].
- Otherwise [t1] is a value.
- Suppose [t2 ==> t2'] for some term [t2']. Then
[t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a value.
- Otherwise, [t2] is a value. By lemma
[canonical_forms_for_arrow_types], [t1 = \x:S1.s2] for some
[x], [S1], and [s2]. And [(\x:S1.s2) t2 ==> [x:=t2]s2] by
[ST_AppAbs], since [t2] is a value.
- If the last step of the derivation is by [T_Proj], then there
is a term [tr], type [Tr] and label [i] such that [t = tr.i],
[empty |- tr : Tr], and [Tlookup i Tr = Some T].
The IH for the typing subderivation gives us that either [tr]
is a value or it steps. If [tr ==> tr'] for some term [tr'],
then [tr.i ==> tr'.i] by rule [ST_Proj1].
Otherwise, [tr] is a value. In this case, lemma
[lookup_field_in_value] yields that there is a term [ti] such
that [tlookup i tr = Some ti]. It follows that [tr.i ==> ti]
by rule [ST_ProjRcd].
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
desired result is exactly the induction hypothesis for the
typing subderivation.
- If the final step of the derivation is by [T_RCons], then there
exist some terms [t1] [tr], types [T1 Tr] and a label [t] such
that [t = {i=t1, tr}], [T = {i:T1, Tr}], [record_tm tr],
[record_tm Tr], [empty |- t1 : T1] and [empty |- tr : Tr].
The induction hypotheses for these typing derivations yield
that [t1] is a value or steps, and that [tr] is a value or
steps. We consider each case:
- Suppose [t1 ==> t1'] for some term [t1']. Then
[{i=t1, tr} ==> {i=t1', tr}] by rule [ST_Rcd_Head].
- Otherwise [t1] is a value.
- Suppose [tr ==> tr'] for some term [tr']. Then
[{i=t1, tr} ==> {i=t1, tr'}] by rule [ST_Rcd_Tail],
since [t1] is a value.
- Otherwise, [tr] is also a value. So, [{i=t1, tr}] is a
value by [v_rcons]. *)
(* ########################################## *)
(** *** Inversion Lemmas *)
Lemma typing_inversion_var : forall Gamma x T,
has_type Gamma (tvar x) T ->
exists S,
Gamma x = Some S /\ subtype S T.
Proof with eauto.
intros Gamma x T Hty.
remember (tvar x) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_Var".
exists T...
Case "T_Sub".
destruct IHHty as [U [Hctx HsubU]]... Qed.
Lemma typing_inversion_app : forall Gamma t1 t2 T2,
has_type Gamma (tapp t1 t2) T2 ->
exists T1,
has_type Gamma t1 (TArrow T1 T2) /\
has_type Gamma t2 T1.
Proof with eauto.
intros Gamma t1 t2 T2 Hty.
remember (tapp t1 t2) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_App".
exists T1...
Case "T_Sub".
destruct IHHty as [U1 [Hty1 Hty2]]...
assert (Hwf := has_type__wf _ _ _ Hty2).
exists U1... Qed.
Lemma typing_inversion_abs : forall Gamma x S1 t2 T,
has_type Gamma (tabs x S1 t2) T ->
(exists S2, subtype (TArrow S1 S2) T
/\ has_type (extend Gamma x S1) t2 S2).
Proof with eauto.
intros Gamma x S1 t2 T H.
remember (tabs x S1 t2) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Abs".
assert (Hwf := has_type__wf _ _ _ H0).
exists T12...
Case "T_Sub".
destruct IHhas_type as [S2 [Hsub Hty]]...
Qed.
Lemma typing_inversion_proj : forall Gamma i t1 Ti,
has_type Gamma (tproj t1 i) Ti ->
exists T, exists Si,
Tlookup i T = Some Si /\ subtype Si Ti /\ has_type Gamma t1 T.
Proof with eauto.
intros Gamma i t1 Ti H.
remember (tproj t1 i) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Proj".
assert (well_formed_ty Ti) as Hwf.
SCase "pf of assertion".
apply (wf_rcd_lookup i T Ti)...
apply has_type__wf in H...
exists T. exists Ti...
Case "T_Sub".
destruct IHhas_type as [U [Ui [Hget [Hsub Hty]]]]...
exists U. exists Ui... Qed.
Lemma typing_inversion_rcons : forall Gamma i ti tr T,
has_type Gamma (trcons i ti tr) T ->
exists Si, exists Sr,
subtype (TRCons i Si Sr) T /\ has_type Gamma ti Si /\
record_tm tr /\ has_type Gamma tr Sr.
Proof with eauto.
intros Gamma i ti tr T Hty.
remember (trcons i ti tr) as t.
has_type_cases (induction Hty) Case;
inversion Heqt; subst...
Case "T_Sub".
apply IHHty in H0.
destruct H0 as [Ri [Rr [HsubRS [HtypRi HtypRr]]]].
exists Ri. exists Rr...
Case "T_RCons".
assert (well_formed_ty (TRCons i T Tr)) as Hwf.
SCase "pf of assertion".
apply has_type__wf in Hty1.
apply has_type__wf in Hty2...
exists T. exists Tr... Qed.
Lemma abs_arrow : forall x S1 s2 T1 T2,
has_type empty (tabs x S1 s2) (TArrow T1 T2) ->
subtype T1 S1
/\ has_type (extend empty x S1) s2 T2.
Proof with eauto.
intros x S1 s2 T1 T2 Hty.
apply typing_inversion_abs in Hty.
destruct Hty as [S2 [Hsub Hty]].
apply sub_inversion_arrow in Hsub.
destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].
inversion Heq; subst... Qed.
(* ########################################## *)
(** *** Context Invariance *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_proj : forall x t i,
appears_free_in x t ->
appears_free_in x (tproj t i)
| afi_rhead : forall x i t tr,
appears_free_in x t ->
appears_free_in x (trcons i t tr)
| afi_rtail : forall x i t tr,
appears_free_in x tr ->
appears_free_in x (trcons i t tr).
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
has_type Gamma t S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
has_type Gamma' t S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros x0 Hafi.
unfold extend. destruct (eq_id_dec x x0)...
Case "T_App".
apply T_App with T1...
Case "T_RCons".
apply T_RCons... Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
has_type Gamma t T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case; subst; inversion Hafi; subst...
Case "T_Abs".
destruct (IHHtyp H5) as [T Hctx]. exists T.
unfold extend in Hctx. rewrite neq_id in Hctx... Qed.
(* ########################################## *)
(** *** Preservation *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
has_type (extend Gamma x U) t S ->
has_type empty v U ->
has_type Gamma ([x:=v]t) S.
Proof with eauto.
intros Gamma x U v t S Htypt Htypv.
generalize dependent S. generalize dependent Gamma.
t_cases (induction t) Case; intros; simpl.
Case "tvar".
rename i into y.
destruct (typing_inversion_var _ _ _ Htypt) as [T [Hctx Hsub]].
unfold extend in Hctx.
destruct (eq_id_dec x y)...
SCase "x=y".
subst.
inversion Hctx; subst. clear Hctx.
apply context_invariance with empty...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
destruct (subtype__wf _ _ Hsub)...
Case "tapp".
destruct (typing_inversion_app _ _ _ _ Htypt) as [T1 [Htypt1 Htypt2]].
eapply T_App...
Case "tabs".
rename i into y. rename t into T1.
destruct (typing_inversion_abs _ _ _ _ _ Htypt)
as [T2 [Hsub Htypt2]].
destruct (subtype__wf _ _ Hsub) as [Hwf1 Hwf2].
inversion Hwf2. subst.
apply T_Sub with (TArrow T1 T2)... apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
Case "tproj".
destruct (typing_inversion_proj _ _ _ _ Htypt)
as [T [Ti [Hget [Hsub Htypt1]]]]...
Case "trnil".
eapply context_invariance...
intros y Hcontra. inversion Hcontra.
Case "trcons".
destruct (typing_inversion_rcons _ _ _ _ _ Htypt) as
[Ti [Tr [Hsub [HtypTi [Hrcdt2 HtypTr]]]]].
apply T_Sub with (TRCons i Ti Tr)...
apply T_RCons...
SCase "record_ty Tr".
apply subtype__wf in Hsub. destruct Hsub. inversion H0...
SCase "record_tm ([x:=v]t2)".
inversion Hrcdt2; subst; simpl... Qed.
Theorem preservation : forall t t' T,
has_type empty t T ->
t ==> t' ->
has_type empty t' T.
Proof with eauto.
intros t t' T HT.
remember empty as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
inversion HE; subst...
SCase "ST_AppAbs".
destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].
apply substitution_preserves_typing with T...
Case "T_Proj".
destruct (lookup_field_in_value _ _ _ _ H2 HT H)
as [vi [Hget Hty]].
rewrite H4 in Hget. inversion Hget. subst...
Case "T_RCons".
eauto using step_preserves_record_tm. Qed.
(** Informal proof of [preservation]:
Theorem: If [t], [t'] are terms and [T] is a type such that
[empty |- t : T] and [t ==> t'], then [empty |- t' : T].
Proof: Let [t] and [T] be given such that [empty |- t : T]. We go
by induction on the structure of this typing derivation, leaving
[t'] general. Cases [T_Abs] and [T_RNil] are vacuous because
abstractions and {} don't step. Case [T_Var] is vacuous as well,
since the context is empty.
- If the final step of the derivation is by [T_App], then there
are terms [t1] [t2] and types [T1] [T2] such that [t = t1 t2],
[T = T2], [empty |- t1 : T1 -> T2] and [empty |- t2 : T1].
By inspection of the definition of the step relation, there are
three ways [t1 t2] can step. Cases [ST_App1] and [ST_App2]
follow immediately by the induction hypotheses for the typing
subderivations and a use of [T_App].
Suppose instead [t1 t2] steps by [ST_AppAbs]. Then
[t1 = \x:S.t12] for some type [S] and term [t12], and
[t' = [x:=t2]t12].
By Lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].
It then follows by lemma [substitution_preserves_typing] that
[empty |- [x:=t2] t12 : T2] as desired.
- If the final step of the derivation is by [T_Proj], then there
is a term [tr], type [Tr] and label [i] such that [t = tr.i],
[empty |- tr : Tr], and [Tlookup i Tr = Some T].
The IH for the typing derivation gives us that, for any term
[tr'], if [tr ==> tr'] then [empty |- tr' Tr]. Inspection of
the definition of the step relation reveals that there are two
ways a projection can step. Case [ST_Proj1] follows
immediately by the IH.
Instead suppose [tr.i] steps by [ST_ProjRcd]. Then [tr] is a
value and there is some term [vi] such that
[tlookup i tr = Some vi] and [t' = vi]. But by lemma
[lookup_field_in_value], [empty |- vi : Ti] as desired.
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
result is immediate by the induction hypothesis for the typing
subderivation and an application of [T_Sub].
- If the final step of the derivation is by [T_RCons], then there
exist some terms [t1] [tr], types [T1 Tr] and a label [t] such
that [t = {i=t1, tr}], [T = {i:T1, Tr}], [record_tm tr],
[record_tm Tr], [empty |- t1 : T1] and [empty |- tr : Tr].
By the definition of the step relation, [t] must have stepped
by [ST_Rcd_Head] or [ST_Rcd_Tail]. In the first case, the
result follows by the IH for [t1]'s typing derivation and
[T_RCons]. In the second case, the result follows by the IH
for [tr]'s typing derivation, [T_RCons], and a use of the
[step_preserves_record_tm] lemma. *)
(* ###################################################### *)
(** ** Exercises on Typing *)
(** **** Exercise: 2 stars, optional (variations) *)
(** Each part of this problem suggests a different way of
changing the definition of the STLC with records and
subtyping. (These changes are not cumulative: each part
starts from the original language.) In each part, list which
properties (Progress, Preservation, both, or neither) become
false. If a property becomes false, give a counterexample.
- Suppose we add the following typing rule:
Gamma |- t : S1->S2
S1 <: T1 T1 <: S1 S2 <: T2
----------------------------------- (T_Funny1)
Gamma |- t : T1->T2
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
{} ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
{} <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: {}
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
({} t) ==> (t {})
- Suppose we add the same evaluation rule *and* a new typing rule:
----------------- (ST_Funny5)
({} t) ==> (t {})
---------------------- (T_Funny6)
empty |- {} : Top->Top
- Suppose we *change* the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
(** [] *)
*)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * RecordSub: Subtyping with Records *)
Require Export MoreStlc.
(* ###################################################### *)
(** * Core Definitions *)
(* ################################### *)
(** *** Syntax *)
Inductive ty : Type :=
(* proper types *)
| TTop : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
(* record types *)
| TRNil : ty
| TRCons : id -> ty -> ty -> ty.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TRNil" | Case_aux c "TRCons" ].
Inductive tm : Type :=
(* proper terms *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tproj : tm -> id -> tm
(* record terms *)
| trnil : tm
| trcons : id -> tm -> tm -> tm.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"
| Case_aux c "tproj" | Case_aux c "trnil" | Case_aux c "trcons" ].
(* ################################### *)
(** *** Well-Formedness *)
Inductive record_ty : ty -> Prop :=
| RTnil :
record_ty TRNil
| RTcons : forall i T1 T2,
record_ty (TRCons i T1 T2).
Inductive record_tm : tm -> Prop :=
| rtnil :
record_tm trnil
| rtcons : forall i t1 t2,
record_tm (trcons i t1 t2).
Inductive well_formed_ty : ty -> Prop :=
| wfTTop :
well_formed_ty TTop
| wfTBase : forall i,
well_formed_ty (TBase i)
| wfTArrow : forall T1 T2,
well_formed_ty T1 ->
well_formed_ty T2 ->
well_formed_ty (TArrow T1 T2)
| wfTRNil :
well_formed_ty TRNil
| wfTRCons : forall i T1 T2,
well_formed_ty T1 ->
well_formed_ty T2 ->
record_ty T2 ->
well_formed_ty (TRCons i T1 T2).
Hint Constructors record_ty record_tm well_formed_ty.
(* ################################### *)
(** *** Substitution *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y => if eq_id_dec x y then s else t
| tabs y T t1 => tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 => tapp (subst x s t1) (subst x s t2)
| tproj t1 i => tproj (subst x s t1) i
| trnil => trnil
| trcons i t1 tr2 => trcons i (subst x s t1) (subst x s tr2)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_rnil : value trnil
| v_rcons : forall i v vr,
value v ->
value vr ->
value (trcons i v vr).
Hint Constructors value.
Fixpoint Tlookup (i:id) (Tr:ty) : option ty :=
match Tr with
| TRCons i' T Tr' => if eq_id_dec i i' then Some T else Tlookup i Tr'
| _ => None
end.
Fixpoint tlookup (i:id) (tr:tm) : option tm :=
match tr with
| trcons i' t tr' => if eq_id_dec i i' then Some t else tlookup i tr'
| _ => None
end.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
| ST_Proj1 : forall tr tr' i,
tr ==> tr' ->
(tproj tr i) ==> (tproj tr' i)
| ST_ProjRcd : forall tr i vi,
value tr ->
tlookup i tr = Some vi ->
(tproj tr i) ==> vi
| ST_Rcd_Head : forall i t1 t1' tr2,
t1 ==> t1' ->
(trcons i t1 tr2) ==> (trcons i t1' tr2)
| ST_Rcd_Tail : forall i v1 tr2 tr2',
value v1 ->
tr2 ==> tr2' ->
(trcons i v1 tr2) ==> (trcons i v1 tr2')
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"
| Case_aux c "ST_Proj1" | Case_aux c "ST_ProjRcd" | Case_aux c "ST_Rcd"
| Case_aux c "ST_Rcd_Head" | Case_aux c "ST_Rcd_Tail" ].
Hint Constructors step.
(* ###################################################################### *)
(** * Subtyping *)
(** Now we come to the interesting part. We begin by defining
the subtyping relation and developing some of its important
technical properties. *)
(* ################################### *)
(** ** Definition *)
(** The definition of subtyping is essentially just what we
sketched in the motivating discussion, but we need to add
well-formedness side conditions to some of the rules. *)
Inductive subtype : ty -> ty -> Prop :=
(* Subtyping between proper types *)
| S_Refl : forall T,
well_formed_ty T ->
subtype T T
| S_Trans : forall S U T,
subtype S U ->
subtype U T ->
subtype S T
| S_Top : forall S,
well_formed_ty S ->
subtype S TTop
| S_Arrow : forall S1 S2 T1 T2,
subtype T1 S1 ->
subtype S2 T2 ->
subtype (TArrow S1 S2) (TArrow T1 T2)
(* Subtyping between record types *)
| S_RcdWidth : forall i T1 T2,
well_formed_ty (TRCons i T1 T2) ->
subtype (TRCons i T1 T2) TRNil
| S_RcdDepth : forall i S1 T1 Sr2 Tr2,
subtype S1 T1 ->
subtype Sr2 Tr2 ->
record_ty Sr2 ->
record_ty Tr2 ->
subtype (TRCons i S1 Sr2) (TRCons i T1 Tr2)
| S_RcdPerm : forall i1 i2 T1 T2 Tr3,
well_formed_ty (TRCons i1 T1 (TRCons i2 T2 Tr3)) ->
i1 <> i2 ->
subtype (TRCons i1 T1 (TRCons i2 T2 Tr3))
(TRCons i2 T2 (TRCons i1 T1 Tr3)).
Hint Constructors subtype.
Tactic Notation "subtype_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "S_Refl" | Case_aux c "S_Trans" | Case_aux c "S_Top"
| Case_aux c "S_Arrow" | Case_aux c "S_RcdWidth"
| Case_aux c "S_RcdDepth" | Case_aux c "S_RcdPerm" ].
(* ############################################### *)
(** ** Subtyping Examples and Exercises *)
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation j := (Id 3).
Notation k := (Id 4).
Notation i := (Id 5).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Definition TRcd_j :=
(TRCons j (TArrow B B) TRNil). (* {j:B->B} *)
Definition TRcd_kj :=
TRCons k (TArrow A A) TRcd_j. (* {k:C->C,j:B->B} *)
Example subtyping_example_0 :
subtype (TArrow C TRcd_kj)
(TArrow C TRNil).
(* C->{k:A->A,j:B->B} <: C->{} *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
unfold TRcd_kj, TRcd_j. apply S_RcdWidth; auto.
Qed.
(** The following facts are mostly easy to prove in Coq. To get
full benefit from the exercises, make sure you also
understand how to prove them on paper! *)
(** **** Exercise: 2 stars *)
Example subtyping_example_1 :
subtype TRcd_kj TRcd_j.
(* {k:A->A,j:B->B} <: {j:B->B} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star *)
Example subtyping_example_2 :
subtype (TArrow TTop TRcd_kj)
(TArrow (TArrow C C) TRcd_j).
(* Top->{k:A->A,j:B->B} <: (C->C)->{j:B->B} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star *)
Example subtyping_example_3 :
subtype (TArrow TRNil (TRCons j A TRNil))
(TArrow (TRCons k B TRNil) TRNil).
(* {}->{j:A} <: {k:B}->{} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars *)
Example subtyping_example_4 :
subtype (TRCons x A (TRCons y B (TRCons z C TRNil)))
(TRCons z C (TRCons y B (TRCons x A TRNil))).
(* {x:A,y:B,z:C} <: {z:C,y:B,x:A} *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
Definition trcd_kj :=
(trcons k (tabs z A (tvar z))
(trcons j (tabs z B (tvar z))
trnil)).
End Examples.
(* ###################################################################### *)
(** ** Properties of Subtyping *)
(** *** Well-Formedness *)
Lemma subtype__wf : forall S T,
subtype S T ->
well_formed_ty T /\ well_formed_ty S.
Proof with eauto.
intros S T Hsub.
subtype_cases (induction Hsub) Case;
intros; try (destruct IHHsub1; destruct IHHsub2)...
Case "S_RcdPerm".
split... inversion H. subst. inversion H5... Qed.
Lemma wf_rcd_lookup : forall i T Ti,
well_formed_ty T ->
Tlookup i T = Some Ti ->
well_formed_ty Ti.
Proof with eauto.
intros i T.
T_cases (induction T) Case; intros; try solve by inversion.
Case "TRCons".
inversion H. subst. unfold Tlookup in H0.
destruct (eq_id_dec i i0)... inversion H0; subst... Qed.
(** *** Field Lookup *)
(** Our record matching lemmas get a little more complicated in
the presence of subtyping for two reasons: First, record
types no longer necessarily describe the exact structure of
corresponding terms. Second, reasoning by induction on
[has_type] derivations becomes harder in general, because
[has_type] is no longer syntax directed. *)
Lemma rcd_types_match : forall S T i Ti,
subtype S T ->
Tlookup i T = Some Ti ->
exists Si, Tlookup i S = Some Si /\ subtype Si Ti.
Proof with (eauto using wf_rcd_lookup).
intros S T i Ti Hsub Hget. generalize dependent Ti.
subtype_cases (induction Hsub) Case; intros Ti Hget;
try solve by inversion.
Case "S_Refl".
exists Ti...
Case "S_Trans".
destruct (IHHsub2 Ti) as [Ui Hui]... destruct Hui.
destruct (IHHsub1 Ui) as [Si Hsi]... destruct Hsi.
exists Si...
Case "S_RcdDepth".
rename i0 into k.
unfold Tlookup. unfold Tlookup in Hget.
destruct (eq_id_dec i k)...
SCase "i = k -- we're looking up the first field".
inversion Hget. subst. exists S1...
Case "S_RcdPerm".
exists Ti. split.
SCase "lookup".
unfold Tlookup. unfold Tlookup in Hget.
destruct (eq_id_dec i i1)...
SSCase "i = i1 -- we're looking up the first field".
destruct (eq_id_dec i i2)...
SSSCase "i = i2 - -contradictory".
destruct H0.
subst...
SCase "subtype".
inversion H. subst. inversion H5. subst... Qed.
(** **** Exercise: 3 stars (rcd_types_match_informal) *)
(** Write a careful informal proof of the [rcd_types_match]
lemma. *)
(* FILL IN HERE *)
(** [] *)
(** *** Inversion Lemmas *)
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
subtype U (TArrow V1 V2) ->
exists U1, exists U2,
(U=(TArrow U1 U2)) /\ (subtype V1 U1) /\ (subtype U2 V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** * Typing *)
Definition context := id -> (option ty).
Definition empty : context := (fun _ => None).
Definition extend (Gamma : context) (x:id) (T : ty) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
| T_Var : forall Gamma x T,
Gamma x = Some T ->
well_formed_ty T ->
has_type Gamma (tvar x) T
| T_Abs : forall Gamma x T11 T12 t12,
well_formed_ty T11 ->
has_type (extend Gamma x T11) t12 T12 ->
has_type Gamma (tabs x T11 t12) (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
has_type Gamma t1 (TArrow T1 T2) ->
has_type Gamma t2 T1 ->
has_type Gamma (tapp t1 t2) T2
| T_Proj : forall Gamma i t T Ti,
has_type Gamma t T ->
Tlookup i T = Some Ti ->
has_type Gamma (tproj t i) Ti
(* Subsumption *)
| T_Sub : forall Gamma t S T,
has_type Gamma t S ->
subtype S T ->
has_type Gamma t T
(* Rules for record terms *)
| T_RNil : forall Gamma,
has_type Gamma trnil TRNil
| T_RCons : forall Gamma i t T tr Tr,
has_type Gamma t T ->
has_type Gamma tr Tr ->
record_ty Tr ->
record_tm tr ->
has_type Gamma (trcons i t tr) (TRCons i T Tr)
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Proj" | Case_aux c "T_Sub"
| Case_aux c "T_RNil" | Case_aux c "T_RCons" ].
(* ############################################### *)
(** ** Typing Examples *)
Module Examples2.
Import Examples.
(** **** Exercise: 1 star *)
Example typing_example_0 :
has_type empty
(trcons k (tabs z A (tvar z))
(trcons j (tabs z B (tvar z))
trnil))
TRcd_kj.
(* empty |- {k=(\z:A.z), j=(\z:B.z)} : {k:A->A,j:B->B} *)
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars *)
Example typing_example_1 :
has_type empty
(tapp (tabs x TRcd_j (tproj (tvar x) j))
(trcd_kj))
(TArrow B B).
(* empty |- (\x:{k:A->A,j:B->B}. x.j) {k=(\z:A.z), j=(\z:B.z)} : B->B *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, optional *)
Example typing_example_2 :
has_type empty
(tapp (tabs z (TArrow (TArrow C C) TRcd_j)
(tproj (tapp (tvar z)
(tabs x C (tvar x)))
j))
(tabs z (TArrow C C) trcd_kj))
(TArrow B B).
(* empty |- (\z:(C->C)->{j:B->B}. (z (\x:C.x)).j)
(\z:C->C. {k=(\z:A.z), j=(\z:B.z)})
: B->B *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
End Examples2.
(* ###################################################################### *)
(** ** Properties of Typing *)
(** *** Well-Formedness *)
Lemma has_type__wf : forall Gamma t T,
has_type Gamma t T -> well_formed_ty T.
Proof with eauto.
intros Gamma t T Htyp.
has_type_cases (induction Htyp) Case...
Case "T_App".
inversion IHHtyp1...
Case "T_Proj".
eapply wf_rcd_lookup...
Case "T_Sub".
apply subtype__wf in H.
destruct H...
Qed.
Lemma step_preserves_record_tm : forall tr tr',
record_tm tr ->
tr ==> tr' ->
record_tm tr'.
Proof.
intros tr tr' Hrt Hstp.
inversion Hrt; subst; inversion Hstp; subst; eauto.
Qed.
(** *** Field Lookup *)
Lemma lookup_field_in_value : forall v T i Ti,
value v ->
has_type empty v T ->
Tlookup i T = Some Ti ->
exists vi, tlookup i v = Some vi /\ has_type empty vi Ti.
Proof with eauto.
remember empty as Gamma.
intros t T i Ti Hval Htyp. revert Ti HeqGamma Hval.
has_type_cases (induction Htyp) Case; intros; subst; try solve by inversion.
Case "T_Sub".
apply (rcd_types_match S) in H0... destruct H0 as [Si [HgetSi Hsub]].
destruct (IHHtyp Si) as [vi [Hget Htyvi]]...
Case "T_RCons".
simpl in H0. simpl. simpl in H1.
destruct (eq_id_dec i i0).
SCase "i is first".
inversion H1. subst. exists t...
SCase "i in tail".
destruct (IHHtyp2 Ti) as [vi [get Htyvi]]...
inversion Hval... Qed.
(* ########################################## *)
(** *** Progress *)
(** **** Exercise: 3 stars (canonical_forms_of_arrow_types) *)
Lemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,
has_type Gamma s (TArrow T1 T2) ->
value s ->
exists x, exists S1, exists s2,
s = tabs x S1 s2.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
Theorem progress : forall t T,
has_type empty t T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
intros t T Ht.
remember empty as Gamma.
revert HeqGamma.
has_type_cases (induction Ht) Case;
intros HeqGamma; subst...
Case "T_Var".
inversion H.
Case "T_App".
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
destruct (canonical_forms_of_arrow_types empty t1 T1 T2)
as [x [S1 [t12 Heqt1]]]...
subst. exists ([x:=t2]t12)...
SSCase "t2 steps".
destruct H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
destruct H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_Proj".
right. destruct IHHt...
SCase "rcd is value".
destruct (lookup_field_in_value t T i Ti) as [t' [Hget Ht']]...
SCase "rcd_steps".
destruct H0 as [t' Hstp]. exists (tproj t' i)...
Case "T_RCons".
destruct IHHt1...
SCase "head is a value".
destruct IHHt2...
SSCase "tail steps".
right. destruct H2 as [tr' Hstp].
exists (trcons i t tr')...
SCase "head steps".
right. destruct H1 as [t' Hstp].
exists (trcons i t' tr)... Qed.
(** Informal proof of progress:
Theorem : For any term [t] and type [T], if [empty |- t : T]
then [t] is a value or [t ==> t'] for some term [t'].
Proof : Let [t] and [T] be given such that [empty |- t : T]. We go
by induction on the typing derivation. Cases [T_Abs] and
[T_RNil] are immediate because abstractions and [{}] are always
values. Case [T_Var] is vacuous because variables cannot be
typed in the empty context.
- If the last step in the typing derivation is by [T_App], then
there are terms [t1] [t2] and types [T1] [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2] and
[empty |- t2 : T1].
The induction hypotheses for these typing derivations yield
that [t1] is a value or steps, and that [t2] is a value or
steps. We consider each case:
- Suppose [t1 ==> t1'] for some term [t1']. Then
[t1 t2 ==> t1' t2] by [ST_App1].
- Otherwise [t1] is a value.
- Suppose [t2 ==> t2'] for some term [t2']. Then
[t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a value.
- Otherwise, [t2] is a value. By lemma
[canonical_forms_for_arrow_types], [t1 = \x:S1.s2] for some
[x], [S1], and [s2]. And [(\x:S1.s2) t2 ==> [x:=t2]s2] by
[ST_AppAbs], since [t2] is a value.
- If the last step of the derivation is by [T_Proj], then there
is a term [tr], type [Tr] and label [i] such that [t = tr.i],
[empty |- tr : Tr], and [Tlookup i Tr = Some T].
The IH for the typing subderivation gives us that either [tr]
is a value or it steps. If [tr ==> tr'] for some term [tr'],
then [tr.i ==> tr'.i] by rule [ST_Proj1].
Otherwise, [tr] is a value. In this case, lemma
[lookup_field_in_value] yields that there is a term [ti] such
that [tlookup i tr = Some ti]. It follows that [tr.i ==> ti]
by rule [ST_ProjRcd].
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
desired result is exactly the induction hypothesis for the
typing subderivation.
- If the final step of the derivation is by [T_RCons], then there
exist some terms [t1] [tr], types [T1 Tr] and a label [t] such
that [t = {i=t1, tr}], [T = {i:T1, Tr}], [record_tm tr],
[record_tm Tr], [empty |- t1 : T1] and [empty |- tr : Tr].
The induction hypotheses for these typing derivations yield
that [t1] is a value or steps, and that [tr] is a value or
steps. We consider each case:
- Suppose [t1 ==> t1'] for some term [t1']. Then
[{i=t1, tr} ==> {i=t1', tr}] by rule [ST_Rcd_Head].
- Otherwise [t1] is a value.
- Suppose [tr ==> tr'] for some term [tr']. Then
[{i=t1, tr} ==> {i=t1, tr'}] by rule [ST_Rcd_Tail],
since [t1] is a value.
- Otherwise, [tr] is also a value. So, [{i=t1, tr}] is a
value by [v_rcons]. *)
(* ########################################## *)
(** *** Inversion Lemmas *)
Lemma typing_inversion_var : forall Gamma x T,
has_type Gamma (tvar x) T ->
exists S,
Gamma x = Some S /\ subtype S T.
Proof with eauto.
intros Gamma x T Hty.
remember (tvar x) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_Var".
exists T...
Case "T_Sub".
destruct IHHty as [U [Hctx HsubU]]... Qed.
Lemma typing_inversion_app : forall Gamma t1 t2 T2,
has_type Gamma (tapp t1 t2) T2 ->
exists T1,
has_type Gamma t1 (TArrow T1 T2) /\
has_type Gamma t2 T1.
Proof with eauto.
intros Gamma t1 t2 T2 Hty.
remember (tapp t1 t2) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_App".
exists T1...
Case "T_Sub".
destruct IHHty as [U1 [Hty1 Hty2]]...
assert (Hwf := has_type__wf _ _ _ Hty2).
exists U1... Qed.
Lemma typing_inversion_abs : forall Gamma x S1 t2 T,
has_type Gamma (tabs x S1 t2) T ->
(exists S2, subtype (TArrow S1 S2) T
/\ has_type (extend Gamma x S1) t2 S2).
Proof with eauto.
intros Gamma x S1 t2 T H.
remember (tabs x S1 t2) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Abs".
assert (Hwf := has_type__wf _ _ _ H0).
exists T12...
Case "T_Sub".
destruct IHhas_type as [S2 [Hsub Hty]]...
Qed.
Lemma typing_inversion_proj : forall Gamma i t1 Ti,
has_type Gamma (tproj t1 i) Ti ->
exists T, exists Si,
Tlookup i T = Some Si /\ subtype Si Ti /\ has_type Gamma t1 T.
Proof with eauto.
intros Gamma i t1 Ti H.
remember (tproj t1 i) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Proj".
assert (well_formed_ty Ti) as Hwf.
SCase "pf of assertion".
apply (wf_rcd_lookup i T Ti)...
apply has_type__wf in H...
exists T. exists Ti...
Case "T_Sub".
destruct IHhas_type as [U [Ui [Hget [Hsub Hty]]]]...
exists U. exists Ui... Qed.
Lemma typing_inversion_rcons : forall Gamma i ti tr T,
has_type Gamma (trcons i ti tr) T ->
exists Si, exists Sr,
subtype (TRCons i Si Sr) T /\ has_type Gamma ti Si /\
record_tm tr /\ has_type Gamma tr Sr.
Proof with eauto.
intros Gamma i ti tr T Hty.
remember (trcons i ti tr) as t.
has_type_cases (induction Hty) Case;
inversion Heqt; subst...
Case "T_Sub".
apply IHHty in H0.
destruct H0 as [Ri [Rr [HsubRS [HtypRi HtypRr]]]].
exists Ri. exists Rr...
Case "T_RCons".
assert (well_formed_ty (TRCons i T Tr)) as Hwf.
SCase "pf of assertion".
apply has_type__wf in Hty1.
apply has_type__wf in Hty2...
exists T. exists Tr... Qed.
Lemma abs_arrow : forall x S1 s2 T1 T2,
has_type empty (tabs x S1 s2) (TArrow T1 T2) ->
subtype T1 S1
/\ has_type (extend empty x S1) s2 T2.
Proof with eauto.
intros x S1 s2 T1 T2 Hty.
apply typing_inversion_abs in Hty.
destruct Hty as [S2 [Hsub Hty]].
apply sub_inversion_arrow in Hsub.
destruct Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].
inversion Heq; subst... Qed.
(* ########################################## *)
(** *** Context Invariance *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_proj : forall x t i,
appears_free_in x t ->
appears_free_in x (tproj t i)
| afi_rhead : forall x i t tr,
appears_free_in x t ->
appears_free_in x (trcons i t tr)
| afi_rtail : forall x i t tr,
appears_free_in x tr ->
appears_free_in x (trcons i t tr).
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
has_type Gamma t S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
has_type Gamma' t S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros x0 Hafi.
unfold extend. destruct (eq_id_dec x x0)...
Case "T_App".
apply T_App with T1...
Case "T_RCons".
apply T_RCons... Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
has_type Gamma t T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case; subst; inversion Hafi; subst...
Case "T_Abs".
destruct (IHHtyp H5) as [T Hctx]. exists T.
unfold extend in Hctx. rewrite neq_id in Hctx... Qed.
(* ########################################## *)
(** *** Preservation *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
has_type (extend Gamma x U) t S ->
has_type empty v U ->
has_type Gamma ([x:=v]t) S.
Proof with eauto.
intros Gamma x U v t S Htypt Htypv.
generalize dependent S. generalize dependent Gamma.
t_cases (induction t) Case; intros; simpl.
Case "tvar".
rename i into y.
destruct (typing_inversion_var _ _ _ Htypt) as [T [Hctx Hsub]].
unfold extend in Hctx.
destruct (eq_id_dec x y)...
SCase "x=y".
subst.
inversion Hctx; subst. clear Hctx.
apply context_invariance with empty...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
destruct (subtype__wf _ _ Hsub)...
Case "tapp".
destruct (typing_inversion_app _ _ _ _ Htypt) as [T1 [Htypt1 Htypt2]].
eapply T_App...
Case "tabs".
rename i into y. rename t into T1.
destruct (typing_inversion_abs _ _ _ _ _ Htypt)
as [T2 [Hsub Htypt2]].
destruct (subtype__wf _ _ Hsub) as [Hwf1 Hwf2].
inversion Hwf2. subst.
apply T_Sub with (TArrow T1 T2)... apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
Case "tproj".
destruct (typing_inversion_proj _ _ _ _ Htypt)
as [T [Ti [Hget [Hsub Htypt1]]]]...
Case "trnil".
eapply context_invariance...
intros y Hcontra. inversion Hcontra.
Case "trcons".
destruct (typing_inversion_rcons _ _ _ _ _ Htypt) as
[Ti [Tr [Hsub [HtypTi [Hrcdt2 HtypTr]]]]].
apply T_Sub with (TRCons i Ti Tr)...
apply T_RCons...
SCase "record_ty Tr".
apply subtype__wf in Hsub. destruct Hsub. inversion H0...
SCase "record_tm ([x:=v]t2)".
inversion Hrcdt2; subst; simpl... Qed.
Theorem preservation : forall t t' T,
has_type empty t T ->
t ==> t' ->
has_type empty t' T.
Proof with eauto.
intros t t' T HT.
remember empty as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
inversion HE; subst...
SCase "ST_AppAbs".
destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].
apply substitution_preserves_typing with T...
Case "T_Proj".
destruct (lookup_field_in_value _ _ _ _ H2 HT H)
as [vi [Hget Hty]].
rewrite H4 in Hget. inversion Hget. subst...
Case "T_RCons".
eauto using step_preserves_record_tm. Qed.
(** Informal proof of [preservation]:
Theorem: If [t], [t'] are terms and [T] is a type such that
[empty |- t : T] and [t ==> t'], then [empty |- t' : T].
Proof: Let [t] and [T] be given such that [empty |- t : T]. We go
by induction on the structure of this typing derivation, leaving
[t'] general. Cases [T_Abs] and [T_RNil] are vacuous because
abstractions and {} don't step. Case [T_Var] is vacuous as well,
since the context is empty.
- If the final step of the derivation is by [T_App], then there
are terms [t1] [t2] and types [T1] [T2] such that [t = t1 t2],
[T = T2], [empty |- t1 : T1 -> T2] and [empty |- t2 : T1].
By inspection of the definition of the step relation, there are
three ways [t1 t2] can step. Cases [ST_App1] and [ST_App2]
follow immediately by the induction hypotheses for the typing
subderivations and a use of [T_App].
Suppose instead [t1 t2] steps by [ST_AppAbs]. Then
[t1 = \x:S.t12] for some type [S] and term [t12], and
[t' = [x:=t2]t12].
By Lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].
It then follows by lemma [substitution_preserves_typing] that
[empty |- [x:=t2] t12 : T2] as desired.
- If the final step of the derivation is by [T_Proj], then there
is a term [tr], type [Tr] and label [i] such that [t = tr.i],
[empty |- tr : Tr], and [Tlookup i Tr = Some T].
The IH for the typing derivation gives us that, for any term
[tr'], if [tr ==> tr'] then [empty |- tr' Tr]. Inspection of
the definition of the step relation reveals that there are two
ways a projection can step. Case [ST_Proj1] follows
immediately by the IH.
Instead suppose [tr.i] steps by [ST_ProjRcd]. Then [tr] is a
value and there is some term [vi] such that
[tlookup i tr = Some vi] and [t' = vi]. But by lemma
[lookup_field_in_value], [empty |- vi : Ti] as desired.
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
result is immediate by the induction hypothesis for the typing
subderivation and an application of [T_Sub].
- If the final step of the derivation is by [T_RCons], then there
exist some terms [t1] [tr], types [T1 Tr] and a label [t] such
that [t = {i=t1, tr}], [T = {i:T1, Tr}], [record_tm tr],
[record_tm Tr], [empty |- t1 : T1] and [empty |- tr : Tr].
By the definition of the step relation, [t] must have stepped
by [ST_Rcd_Head] or [ST_Rcd_Tail]. In the first case, the
result follows by the IH for [t1]'s typing derivation and
[T_RCons]. In the second case, the result follows by the IH
for [tr]'s typing derivation, [T_RCons], and a use of the
[step_preserves_record_tm] lemma. *)
(* ###################################################### *)
(** ** Exercises on Typing *)
(** **** Exercise: 2 stars, optional (variations) *)
(** Each part of this problem suggests a different way of
changing the definition of the STLC with records and
subtyping. (These changes are not cumulative: each part
starts from the original language.) In each part, list which
properties (Progress, Preservation, both, or neither) become
false. If a property becomes false, give a counterexample.
- Suppose we add the following typing rule:
Gamma |- t : S1->S2
S1 <: T1 T1 <: S1 S2 <: T2
----------------------------------- (T_Funny1)
Gamma |- t : T1->T2
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
{} ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
{} <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: {}
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
({} t) ==> (t {})
- Suppose we add the same evaluation rule *and* a new typing rule:
----------------- (ST_Funny5)
({} t) ==> (t {})
---------------------- (T_Funny6)
empty |- {} : Top->Top
- Suppose we *change* the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
(** [] *)
*)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
`timescale 1ps/1ps
module altera_pll_reconfig_mif_reader
#(
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter MIF_ADDR_WIDTH = 6,
parameter ROM_ADDR_WIDTH = 9, // 512 words x
parameter ROM_DATA_WIDTH = 32, // 32 bits per word = 20kB
parameter ROM_NUM_WORDS = 512, // Default 512 32-bit words = 1 M20K
parameter DEVICE_FAMILY = "Stratix V",
parameter ENABLE_MIF = 0,
parameter MIF_FILE_NAME = ""
) (
// Inputs
input wire mif_clk,
input wire mif_rst,
// Reconfig Module interface for internal register mapping
input wire reconfig_busy, // waitrequest
input wire [RECONFIG_DATA_WIDTH-1:0] reconfig_read_data,
output reg [RECONFIG_DATA_WIDTH-1:0] reconfig_write_data,
output reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_addr,
output reg reconfig_write,
output reg reconfig_read,
// MIF Controller Interface
input wire [ROM_ADDR_WIDTH-1:0] mif_base_addr,
input wire mif_start,
output wire mif_busy
);
// NOTE: Assumes settings opcodes/registers are continguous and OP_MODE is 0
// ROM Interface ctlr states
localparam NUM_STATES = 5;
localparam STATE_REG_WIDTH = 32;
localparam MIF_IDLE = 32'd0;
localparam SET_INSTR_ADDR = 32'd1;
localparam FETCH_INSTR = 32'd2;
localparam WAIT_FOR_ROM_INSTR = 32'd3;
localparam STORE_INSTR = 32'd4;
localparam DECODE_ROM_INSTR = 32'd5;
localparam SET_DATA_ADDR = 32'd6;
localparam SET_DATA_ADDR_DLY = 32'd34;
localparam FETCH_DATA = 32'd7;
localparam WAIT_FOR_ROM_DATA = 32'd8;
localparam STORE_DATA = 32'd9;
localparam SET_INDEX = 32'd35;
localparam CHANGE_SETTINGS_REG = 32'd10;
localparam SET_MODE_REG_INFO = 32'd11;
localparam WAIT_MODE_REG = 32'd12;
localparam SAVE_MODE_REG = 32'd13;
localparam SET_WR_MODE = 32'd14;
localparam WAIT_WRITE_MODE = 32'd15;
localparam INIT_RECONFIG_PARAMS = 32'd16;
localparam CHECK_RECONFIG_SETTING = 32'd17;
localparam WRITE_RECONFIG_SETTING = 32'd18;
localparam DECREMENT_SETTING_NUM = 32'd19;
localparam CHECK_C_SETTINGS = 32'd20;
localparam WRITE_C_SETTINGS = 32'd21;
localparam DECREMENT_C_NUM = 32'd22;
localparam CHECK_DPS_SETTINGS = 32'd23;
localparam WRITE_DPS_SETTINGS = 32'd24;
localparam DECREMENT_DPS_NUM = 32'd25;
localparam START_RECONFIG_CHANGE = 32'd26;
localparam START_RECONFIG_DELAY = 32'd27;
localparam START_RECONFIG_DELAY2 = 32'd28;
localparam WAIT_DONE_SIGNAL = 32'd29;
localparam SET_MODE_REG = 32'd30;
localparam WRITE_FINAL_MODE = 32'd31;
localparam WAIT_FINAL_MODE = 32'd32;
localparam MIF_STREAMING_DONE = 32'd33;
// MIF Opcodes
// Addresses for settings from PLL Reconfig module
localparam OP_MODE = 6'b000000;
localparam OP_STATUS = 6'b000001; // Read only
localparam OP_START = 6'b000010;
localparam OP_N = 6'b000011;
localparam OP_M = 6'b000100;
localparam OP_C_COUNTERS = 6'b000101;
localparam OP_DPS = 6'b000110;
localparam OP_DSM = 6'b000111;
localparam OP_BWCTRL = 6'b001000;
localparam OP_CP_CURRENT = 6'b001001;
localparam OP_SOM = 6'b111110;
localparam OP_EOM = 6'b111111;
localparam INVAL_SETTING = 6'b111100;
localparam MODE_WR = 1'b0;
localparam MODE_POLL = 1'b1;
// Total MIF changeable settings = 8
// + Total non-MIF changeable settings = 2 (status, start)
// + StartOfMif, EndOfMif, Invalid = 3
// = 13 total settings
localparam NUM_SETTINGS = 6'd13;
localparam NUM_MIF_SETTINGS = 6'd10; // Mode = 0.. CP_Current=9
localparam LOG2NUM_SETTINGS = 6; // Consistent with Reconfig addr width
localparam NUM_C_COUNTERS = 5'd18;
localparam LOG2NUM_C_COUNTERS = 3'd5;
localparam NUM_DPS_COUNTERS = 6'd32;
localparam LOG2NUM_DPS_COUNTERS = 3'd6;
// Reconfig Module parameters
localparam WAITREQUEST_MODE = 1'b1;
// Control flow registers
reg [STATE_REG_WIDTH-1:0] mif_curstate;
reg [STATE_REG_WIDTH-1:0] mif_nextstate;
wire is_done;
// Internal data registers
reg [ROM_ADDR_WIDTH-1:0] reg_mif_base_addr;
reg [LOG2NUM_SETTINGS-1:0] reg_instr;
reg [RECONFIG_DATA_WIDTH-1:0] reg_data;
reg [RECONFIG_DATA_WIDTH-1:0] settings_reg [NUM_MIF_SETTINGS-1:0];
reg [RECONFIG_DATA_WIDTH-1:0] c_settings_reg [NUM_C_COUNTERS-1:0];
reg [RECONFIG_DATA_WIDTH-1:0] dps_settings_reg [NUM_DPS_COUNTERS-1:0];
reg [4:0] c_cntr_index; // C cntr is data[22:18];
reg [4:0] dps_index; // DPS is data[20:16];
reg [NUM_SETTINGS-1:0] is_setting_changed; // 1 bit per setting
reg [NUM_C_COUNTERS-1:0] is_c_cntr_changed;
reg [NUM_DPS_COUNTERS-1:0] is_dps_changed;
reg user_mode_setting; // 0 for waitrequest mode, 1 for polling
reg mif_started;
reg saved_mode;
reg mode_reg;
reg [RECONFIG_ADDR_WIDTH-1:0] setting_number;
reg [LOG2NUM_C_COUNTERS-1:0] c_cntr_number;
reg [LOG2NUM_DPS_COUNTERS-1:0] dps_number;
reg c_done;
reg dps_done;
reg is_mode_changed;
// ROM Interface
wire [ROM_DATA_WIDTH-1:0] rom_q;
reg [ROM_ADDR_WIDTH-1:0] rom_addr;
assign mif_busy = (is_done) ? 1'b0 : 1'b1;
// mif_started register
always @(posedge mif_clk)
begin
if (mif_curstate == MIF_IDLE)
mif_started <= 0;
else if (reg_instr == OP_SOM && mif_curstate == DECODE_ROM_INSTR)
mif_started <= 1;
else
mif_started <= mif_started;
end
// is_done logic
assign is_done = (mif_curstate == MIF_IDLE && mif_nextstate == MIF_IDLE) ? 1'b1 : 1'b0;
// State register
always @(posedge mif_clk)
begin
if (mif_rst)
mif_curstate <= MIF_IDLE;
else
mif_curstate <= mif_nextstate;
end
// Next state logic
always @(*)
begin
case (mif_curstate)
MIF_IDLE:
begin
if (mif_start)
mif_nextstate = SET_INSTR_ADDR;
else
mif_nextstate = MIF_IDLE;
end
// Set address for instruction to be fetched from ROM
SET_INSTR_ADDR: // SET_ROM_INFO
begin
mif_nextstate = FETCH_INSTR;
end
FETCH_INSTR:
begin
mif_nextstate = WAIT_FOR_ROM_INSTR;
end
WAIT_FOR_ROM_INSTR:
begin
mif_nextstate = STORE_INSTR;
end
STORE_INSTR:
begin
mif_nextstate = DECODE_ROM_INSTR;
end
DECODE_ROM_INSTR:
begin
if (reg_instr == OP_SOM)
mif_nextstate = SET_INSTR_ADDR;
else if (reg_instr == OP_EOM)
mif_nextstate = SET_MODE_REG_INFO; // Done reading MIF, send it to reconfig module
else
mif_nextstate = SET_DATA_ADDR;
end
SET_DATA_ADDR:
begin
mif_nextstate = SET_DATA_ADDR_DLY;
end
SET_DATA_ADDR_DLY:
begin
mif_nextstate = FETCH_DATA;
end
FETCH_DATA:
begin
mif_nextstate = WAIT_FOR_ROM_DATA;
end
WAIT_FOR_ROM_DATA:
begin
mif_nextstate = STORE_DATA;
end
STORE_DATA:
begin
mif_nextstate = SET_INDEX;
end
SET_INDEX:
begin
mif_nextstate = CHANGE_SETTINGS_REG;
end
CHANGE_SETTINGS_REG:
begin
mif_nextstate = SET_INSTR_ADDR; // Loop back to read rest of MIF file
end
// --- CHANGE RECONFIG REGISTERS --- //
// GENERAL STEPS FOR MANAGING WITH RECONFIG MODULE:
// 1) Save user's configured mode register,
// 2) Change mode to waitrequest mode,
// 3) Send all settings that have changed to
// 4) Start reconfig
// 5) Wait till PLL has locked again.
// 6) Restore user's mode register
SET_MODE_REG_INFO:
begin
mif_nextstate = WAIT_MODE_REG;
end
WAIT_MODE_REG:
begin
mif_nextstate = SAVE_MODE_REG;
end
SAVE_MODE_REG:
begin
mif_nextstate = SET_WR_MODE;
end
SET_WR_MODE:
begin
mif_nextstate = WAIT_WRITE_MODE;
end
WAIT_WRITE_MODE:
begin
mif_nextstate = INIT_RECONFIG_PARAMS;
end
INIT_RECONFIG_PARAMS:
begin
mif_nextstate = CHECK_RECONFIG_SETTING;
end
// PARENT LOOP (writing to reconfig)
CHECK_RECONFIG_SETTING: // Loop over changed settings until setting_num = 0 = MODE
begin
// Don't write the user's mode reg just yet
// Stay in WR mode till we're done with reconfig IP
// then restore the user's old mode/the new mode
// they wrote in the MIF
if (setting_number == 6'b0)
mif_nextstate = START_RECONFIG_CHANGE;
else
begin
if(is_setting_changed[setting_number])
// C and DPS settings are different,
// since multiple can be reconfigured in
// one MIF. If they are changed, check them all.
// In their respective loops
if (setting_number == OP_C_COUNTERS)
begin
mif_nextstate = DECREMENT_C_NUM;
end
else if (setting_number == OP_DPS)
begin
mif_nextstate = DECREMENT_DPS_NUM;
end
else
begin
mif_nextstate = WRITE_RECONFIG_SETTING;
end
else
mif_nextstate = DECREMENT_SETTING_NUM;
end
end
// C LOOP
// We need to check the 0th setting always (unlike the parent loop) so decrement first.
DECREMENT_C_NUM:
begin
if (c_done)
begin
// Done checking and writing C counters
// check next setting in parent loop
mif_nextstate = DECREMENT_SETTING_NUM;
end
else
mif_nextstate = CHECK_C_SETTINGS;
end
CHECK_C_SETTINGS:
begin
if (is_c_cntr_changed[c_cntr_number])
mif_nextstate = WRITE_C_SETTINGS;
else
mif_nextstate = DECREMENT_C_NUM;
end
WRITE_C_SETTINGS:
begin
mif_nextstate = DECREMENT_C_NUM;
end
//End C Loop
// DPS LOOP
// Same as C loop, decrement first.
DECREMENT_DPS_NUM:
begin
if (dps_done)
begin
// Done checking and writing DPS counters
// check next setting in parent loop
mif_nextstate = DECREMENT_SETTING_NUM;
end
else
mif_nextstate = CHECK_DPS_SETTINGS; // Check next DPS setting
end
CHECK_DPS_SETTINGS:
begin
if(is_dps_changed[dps_number])
mif_nextstate = WRITE_DPS_SETTINGS;
else
mif_nextstate = DECREMENT_DPS_NUM;
end
WRITE_DPS_SETTINGS:
begin
mif_nextstate = DECREMENT_DPS_NUM;
end
//End DPS Loop
WRITE_RECONFIG_SETTING:
begin
mif_nextstate = DECREMENT_SETTING_NUM;
end
DECREMENT_SETTING_NUM:
begin
mif_nextstate = CHECK_RECONFIG_SETTING; // Loop back
end
// --- DONE CHANGING SETTINGS, START RECONFIG --- //
START_RECONFIG_CHANGE:
begin
mif_nextstate = START_RECONFIG_DELAY;
end
START_RECONFIG_DELAY:
begin
mif_nextstate = START_RECONFIG_DELAY2;
end
START_RECONFIG_DELAY2: // register at top level before we mux into reconfig
begin
mif_nextstate = WAIT_DONE_SIGNAL;
end
WAIT_DONE_SIGNAL:
begin
if (reconfig_busy)
mif_nextstate = WAIT_DONE_SIGNAL;
else
mif_nextstate = SET_MODE_REG;
end
SET_MODE_REG:
begin
mif_nextstate = WRITE_FINAL_MODE;
end
WRITE_FINAL_MODE:
begin
mif_nextstate = WAIT_FINAL_MODE;
end
WAIT_FINAL_MODE:
begin
mif_nextstate = MIF_STREAMING_DONE;
end
MIF_STREAMING_DONE:
begin
mif_nextstate = MIF_IDLE;
end
default:
begin
mif_nextstate = MIF_IDLE;
end
endcase
end
// Data flow
reg [LOG2NUM_SETTINGS-1:0] i;
reg [LOG2NUM_C_COUNTERS-1:0] j;
reg [LOG2NUM_DPS_COUNTERS-1:0] k;
always @(posedge mif_clk)
begin
if (mif_rst)
begin
reg_mif_base_addr <= 0;
is_setting_changed <= 0;
is_c_cntr_changed <= 0;
is_dps_changed <= 0;
rom_addr <= 0;
reg_instr <= 0;
reg_data <= 0;
for (i = 0; i < NUM_MIF_SETTINGS; i = i + 1'b1)
begin
settings_reg [i] <= 0;
end
for (j = 0; j < NUM_C_COUNTERS; j = j + 1'b1)
begin
c_settings_reg [j] <= 0;
end
for (k = 0; k < NUM_DPS_COUNTERS; k = k + 1'b1)
begin
dps_settings_reg [k] <= 0;
end
setting_number <= 0;
c_cntr_number <= 0;
dps_number <= 0;
c_done <= 0;
dps_done <= 0;
c_cntr_index <= 0;
dps_index <= 0;
reconfig_write_data <= 0;
reconfig_addr <= 0;
reconfig_write <= 0;
reconfig_read <= 0;
end
else
begin
case (mif_curstate)
MIF_IDLE:
begin
reg_mif_base_addr <= mif_base_addr;
is_setting_changed <= 0;
is_c_cntr_changed <= 0;
is_dps_changed <= 0;
rom_addr <= 0;
reg_instr <= 0;
reg_data <= 0;
for (i = 0; i < NUM_MIF_SETTINGS; i = i + 1'b1)
begin
settings_reg [i] <= 0;
end
for (j = 0; j < NUM_C_COUNTERS; j = j + 1'b1)
begin
c_settings_reg [j] <= 0;
end
for (k = 0; k < NUM_DPS_COUNTERS; k = k + 1'b1)
begin
dps_settings_reg [k] <= 0;
end
setting_number <= 0;
c_cntr_number <= 0;
dps_number <= 0;
c_done <= 0;
dps_done <= 0;
c_cntr_index <= 0;
dps_index <= 0;
reconfig_write_data <= 0;
reconfig_addr <= 0;
reconfig_write <= 0;
reconfig_read <= 0;
end
// ----- ROM FLOW ----- //
SET_INSTR_ADDR: rom_addr <= (mif_started) ? rom_addr + 9'd1 : reg_mif_base_addr; // ROM_ADDR_WIDTH = 9
FETCH_INSTR: ;
WAIT_FOR_ROM_INSTR: ;
STORE_INSTR: reg_instr <= rom_q [LOG2NUM_SETTINGS-1:0]; // Only the last 6 bits are instr bits, rest is reserved
DECODE_ROM_INSTR: ;
SET_DATA_ADDR: rom_addr <= rom_addr + 9'd1; // ROM_ADDR_WIDTH = 9
SET_DATA_ADDR_DLY: ;
FETCH_DATA: ;
WAIT_FOR_ROM_DATA: ;
STORE_DATA: reg_data <= rom_q; // Data is 32 bits
SET_INDEX:
begin
c_cntr_index <= reg_data[22:18];
dps_index <= reg_data[20:16];
end
CHANGE_SETTINGS_REG:
begin
if (reg_instr == OP_C_COUNTERS)
begin
c_settings_reg [c_cntr_index] <= reg_data; //22:18 is c cnt number
is_c_cntr_changed [c_cntr_index] <= 1'b1;
end
else if (reg_instr == OP_DPS)
begin
dps_settings_reg [dps_index] <= reg_data; //20:16 is DPS number
is_dps_changed [dps_index] <= 1'b1;
end
else
begin
c_settings_reg [c_cntr_index] <= c_settings_reg [c_cntr_index];
is_c_cntr_changed [c_cntr_index] <= is_c_cntr_changed[c_cntr_index];
dps_settings_reg [dps_index] <= dps_settings_reg [dps_index];
is_dps_changed [dps_index] <= is_dps_changed [dps_index];
end
settings_reg [reg_instr] <= reg_data;
is_setting_changed [reg_instr] <= 1'b1;
end
// ---------- RECONFIG FLOW ---------- //
// Reading/writing mode takes only one cycle
// (we don't know what mode its in initally)
SET_MODE_REG_INFO:
begin
reconfig_addr <= OP_MODE;
reconfig_read <= 1'b1;
reconfig_write <= 1'b0;
reconfig_write_data <= 0;
end
WAIT_MODE_REG: reconfig_read <= 1'b0;
SAVE_MODE_REG: saved_mode <= reconfig_read_data[0];
SET_WR_MODE:
begin
reconfig_addr <= OP_MODE;
reconfig_write <= 1'b1;
reconfig_write_data[0] <= MODE_WR; // Want WaitRequest Mode while MIF reader changes Reconfig regs
end
WAIT_WRITE_MODE: reconfig_write <= 1'b0;
// Done saving the mode reg, start writing the reconfig regs
// Start with the highest setting and work our way down
INIT_RECONFIG_PARAMS:
begin
setting_number <= NUM_MIF_SETTINGS - 6'd1;
c_cntr_number <= NUM_C_COUNTERS;
dps_number <= NUM_DPS_COUNTERS;
end
CHECK_RECONFIG_SETTING: ;
// C LOOP
DECREMENT_C_NUM:
begin
c_cntr_number <= c_cntr_number - 5'd1;
reconfig_write <= 1'b0;
end
CHECK_C_SETTINGS:
begin
if (c_cntr_number == 5'b0)
c_done <= 1'b1;
else
c_done <= c_done;
end
WRITE_C_SETTINGS:
begin
reconfig_addr <= OP_C_COUNTERS;
reconfig_write_data <= c_settings_reg[c_cntr_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
//End C Loop
// DPS LOOP
DECREMENT_DPS_NUM:
begin
dps_number <= dps_number - 5'd1;
reconfig_write <= 1'b0;
end
CHECK_DPS_SETTINGS:
begin
if (dps_number == 5'b0)
dps_done <= 1'b1;
else
dps_done <= dps_done;
end
WRITE_DPS_SETTINGS:
begin
reconfig_addr <= OP_DPS;
reconfig_write_data <= dps_settings_reg[dps_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
//End DPS Loop
WRITE_RECONFIG_SETTING:
begin
reconfig_addr <= setting_number; // setting_number = OP_CODE
reconfig_write_data <= settings_reg[setting_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
DECREMENT_SETTING_NUM:
begin
reconfig_write <= 1'b0;
setting_number <= setting_number - 6'd1; // Decrement for looping back
end
// --- Wrote all the changed settings to the Reconfig IP except MODE
// --- Start the Reconfig process (write to start reg) and wait for
// --- waitrequest signal to deassert
START_RECONFIG_CHANGE:
begin
reconfig_addr <= OP_START;
reconfig_write_data <= 1;
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
START_RECONFIG_DELAY:
begin
reconfig_write <= 1'b0;
end
WAIT_DONE_SIGNAL: ;
// --- Restore saved MODE reg ONLY if mode hasn't been changed by MIF
SET_MODE_REG:
mode_reg <= (is_setting_changed[OP_MODE]) ? settings_reg [OP_MODE][0] : saved_mode;
WRITE_FINAL_MODE:
begin
reconfig_addr <= OP_MODE;
reconfig_write_data[0] <= mode_reg;
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
WAIT_FINAL_MODE:
begin
reconfig_write <= 1'b0;
end
MIF_STREAMING_DONE: ;
default : ;
endcase
end
end
// RAM block
altsyncram altsyncram_component (
.address_a (rom_addr),
.clock0 (mif_clk),
.q_a (rom_q),
.aclr0 (1'b0),
.aclr1 (1'b0),
.address_b (1'b1),
.addressstall_a (1'b0),
.addressstall_b (1'b0),
.byteena_a (1'b1),
.byteena_b (1'b1),
.clock1 (1'b1),
.clocken0 (1'b1),
.clocken1 (1'b1),
.clocken2 (1'b1),
.clocken3 (1'b1),
.data_a ({32{1'b1}}),
.data_b (1'b1),
.eccstatus (),
.q_b (),
.rden_a (1'b1),
.rden_b (1'b1),
.wren_a (1'b0),
.wren_b (1'b0));
defparam
altsyncram_component.address_aclr_a = "NONE",
altsyncram_component.clock_enable_input_a = "BYPASS",
altsyncram_component.clock_enable_output_a = "BYPASS",
altsyncram_component.init_file = MIF_FILE_NAME,
altsyncram_component.intended_device_family = "Stratix V",
altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=NO",
altsyncram_component.lpm_type = "altsyncram",
altsyncram_component.numwords_a = ROM_NUM_WORDS,
altsyncram_component.operation_mode = "ROM",
altsyncram_component.outdata_aclr_a = "NONE",
altsyncram_component.outdata_reg_a = "CLOCK0",
altsyncram_component.widthad_a = ROM_ADDR_WIDTH,
altsyncram_component.width_a = ROM_DATA_WIDTH,
altsyncram_component.width_byteena_a = 1;
endmodule // mif_reader
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_to_avm #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer ID_W = 1
)
(
// AVM interface
output logic avm_read,
output logic avm_write,
output logic [DATA_W-1:0] avm_writedata,
output logic [BURSTCOUNT_W-1:0] avm_burstcount,
output logic [ADDRESS_W-1:0] avm_address,
output logic [BYTEENA_W-1:0] avm_byteenable,
input logic avm_waitrequest,
input logic avm_readdatavalid,
input logic [DATA_W-1:0] avm_readdata,
input logic avm_writeack, // not a true Avalon signal, so ignore this
// IC interface
input logic ic_arb_request,
input logic ic_arb_read,
input logic ic_arb_write,
input logic [DATA_W-1:0] ic_arb_writedata,
input logic [BURSTCOUNT_W-1:0] ic_arb_burstcount,
input logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address,
input logic [BYTEENA_W-1:0] ic_arb_byteenable,
input logic [ID_W-1:0] ic_arb_id,
output logic ic_arb_stall,
output logic ic_wrp_ack,
output logic ic_rrp_datavalid,
output logic [DATA_W-1:0] ic_rrp_data
);
assign avm_read = ic_arb_read;
assign avm_write = ic_arb_write;
assign avm_writedata = ic_arb_writedata;
assign avm_burstcount = ic_arb_burstcount;
assign avm_address = {ic_arb_address, {$clog2(DATA_W / 8){1'b0}}};
assign avm_byteenable = ic_arb_byteenable;
assign ic_arb_stall = avm_waitrequest;
assign ic_rrp_datavalid = avm_readdatavalid;
assign ic_rrp_data = avm_readdata;
//assign ic_wrp_ack = avm_writeack;
assign ic_wrp_ack = avm_write & ~avm_waitrequest;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_to_avm #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer ID_W = 1
)
(
// AVM interface
output logic avm_read,
output logic avm_write,
output logic [DATA_W-1:0] avm_writedata,
output logic [BURSTCOUNT_W-1:0] avm_burstcount,
output logic [ADDRESS_W-1:0] avm_address,
output logic [BYTEENA_W-1:0] avm_byteenable,
input logic avm_waitrequest,
input logic avm_readdatavalid,
input logic [DATA_W-1:0] avm_readdata,
input logic avm_writeack, // not a true Avalon signal, so ignore this
// IC interface
input logic ic_arb_request,
input logic ic_arb_read,
input logic ic_arb_write,
input logic [DATA_W-1:0] ic_arb_writedata,
input logic [BURSTCOUNT_W-1:0] ic_arb_burstcount,
input logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address,
input logic [BYTEENA_W-1:0] ic_arb_byteenable,
input logic [ID_W-1:0] ic_arb_id,
output logic ic_arb_stall,
output logic ic_wrp_ack,
output logic ic_rrp_datavalid,
output logic [DATA_W-1:0] ic_rrp_data
);
assign avm_read = ic_arb_read;
assign avm_write = ic_arb_write;
assign avm_writedata = ic_arb_writedata;
assign avm_burstcount = ic_arb_burstcount;
assign avm_address = {ic_arb_address, {$clog2(DATA_W / 8){1'b0}}};
assign avm_byteenable = ic_arb_byteenable;
assign ic_arb_stall = avm_waitrequest;
assign ic_rrp_datavalid = avm_readdatavalid;
assign ic_rrp_data = avm_readdata;
//assign ic_wrp_ack = avm_writeack;
assign ic_wrp_ack = avm_write & ~avm_waitrequest;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_to_avm #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer ID_W = 1
)
(
// AVM interface
output logic avm_read,
output logic avm_write,
output logic [DATA_W-1:0] avm_writedata,
output logic [BURSTCOUNT_W-1:0] avm_burstcount,
output logic [ADDRESS_W-1:0] avm_address,
output logic [BYTEENA_W-1:0] avm_byteenable,
input logic avm_waitrequest,
input logic avm_readdatavalid,
input logic [DATA_W-1:0] avm_readdata,
input logic avm_writeack, // not a true Avalon signal, so ignore this
// IC interface
input logic ic_arb_request,
input logic ic_arb_read,
input logic ic_arb_write,
input logic [DATA_W-1:0] ic_arb_writedata,
input logic [BURSTCOUNT_W-1:0] ic_arb_burstcount,
input logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address,
input logic [BYTEENA_W-1:0] ic_arb_byteenable,
input logic [ID_W-1:0] ic_arb_id,
output logic ic_arb_stall,
output logic ic_wrp_ack,
output logic ic_rrp_datavalid,
output logic [DATA_W-1:0] ic_rrp_data
);
assign avm_read = ic_arb_read;
assign avm_write = ic_arb_write;
assign avm_writedata = ic_arb_writedata;
assign avm_burstcount = ic_arb_burstcount;
assign avm_address = {ic_arb_address, {$clog2(DATA_W / 8){1'b0}}};
assign avm_byteenable = ic_arb_byteenable;
assign ic_arb_stall = avm_waitrequest;
assign ic_rrp_datavalid = avm_readdatavalid;
assign ic_rrp_data = avm_readdata;
//assign ic_wrp_ack = avm_writeack;
assign ic_wrp_ack = avm_write & ~avm_waitrequest;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_to_avm #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer ID_W = 1
)
(
// AVM interface
output logic avm_read,
output logic avm_write,
output logic [DATA_W-1:0] avm_writedata,
output logic [BURSTCOUNT_W-1:0] avm_burstcount,
output logic [ADDRESS_W-1:0] avm_address,
output logic [BYTEENA_W-1:0] avm_byteenable,
input logic avm_waitrequest,
input logic avm_readdatavalid,
input logic [DATA_W-1:0] avm_readdata,
input logic avm_writeack, // not a true Avalon signal, so ignore this
// IC interface
input logic ic_arb_request,
input logic ic_arb_read,
input logic ic_arb_write,
input logic [DATA_W-1:0] ic_arb_writedata,
input logic [BURSTCOUNT_W-1:0] ic_arb_burstcount,
input logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address,
input logic [BYTEENA_W-1:0] ic_arb_byteenable,
input logic [ID_W-1:0] ic_arb_id,
output logic ic_arb_stall,
output logic ic_wrp_ack,
output logic ic_rrp_datavalid,
output logic [DATA_W-1:0] ic_rrp_data
);
assign avm_read = ic_arb_read;
assign avm_write = ic_arb_write;
assign avm_writedata = ic_arb_writedata;
assign avm_burstcount = ic_arb_burstcount;
assign avm_address = {ic_arb_address, {$clog2(DATA_W / 8){1'b0}}};
assign avm_byteenable = ic_arb_byteenable;
assign ic_arb_stall = avm_waitrequest;
assign ic_rrp_datavalid = avm_readdatavalid;
assign ic_rrp_data = avm_readdata;
//assign ic_wrp_ack = avm_writeack;
assign ic_wrp_ack = avm_write & ~avm_waitrequest;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2006 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
// verilator lint_off MULTIDRIVEN
wire [31:0] outb0c0;
wire [31:0] outb0c1;
wire [31:0] outb1c0;
wire [31:0] outb1c1;
reg [7:0] lclmem [7:0];
ma ma0 (.outb0c0(outb0c0), .outb0c1(outb0c1),
.outb1c0(outb1c0), .outb1c1(outb1c1)
);
global_mod #(32'hf00d) global_cell ();
global_mod #(32'hf22d) global_cell2 ();
input clk;
integer cyc=1;
always @ (posedge clk) begin
cyc <= cyc + 1;
`ifdef TEST_VERBOSE
$write("[%0t] cyc%0d: %0x %0x %0x %0x\n", $time, cyc, outb0c0, outb0c1, outb1c0, outb1c1);
`endif
if (cyc==2) begin
if (global_cell.globali != 32'hf00d) $stop;
if (global_cell2.globali != 32'hf22d) $stop;
if (outb0c0 != 32'h00) $stop;
if (outb0c1 != 32'h01) $stop;
if (outb1c0 != 32'h10) $stop;
if (outb1c1 != 32'h11) $stop;
end
if (cyc==3) begin
// Can we scope down and read and write vars?
ma0.mb0.mc0.out <= ma0.mb0.mc0.out + 32'h100;
ma0.mb0.mc1.out <= ma0.mb0.mc1.out + 32'h100;
ma0.mb1.mc0.out <= ma0.mb1.mc0.out + 32'h100;
ma0.mb1.mc1.out <= ma0.mb1.mc1.out + 32'h100;
end
if (cyc==4) begin
// Can we do dotted's inside array sels?
ma0.rmtmem[ma0.mb0.mc0.out[2:0]] = 8'h12;
lclmem[ma0.mb0.mc0.out[2:0]] = 8'h24;
if (outb0c0 != 32'h100) $stop;
if (outb0c1 != 32'h101) $stop;
if (outb1c0 != 32'h110) $stop;
if (outb1c1 != 32'h111) $stop;
end
if (cyc==5) begin
if (ma0.rmtmem[ma0.mb0.mc0.out[2:0]] != 8'h12) $stop;
if (lclmem[ma0.mb0.mc0.out[2:0]] != 8'h24) $stop;
if (outb0c0 != 32'h1100) $stop;
if (outb0c1 != 32'h2101) $stop;
if (outb1c0 != 32'h2110) $stop;
if (outb1c1 != 32'h3111) $stop;
end
if (cyc==6) begin
if (outb0c0 != 32'h31100) $stop;
if (outb0c1 != 32'h02101) $stop;
if (outb1c0 != 32'h42110) $stop;
if (outb1c1 != 32'h03111) $stop;
end
if (cyc==9) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`ifdef USE_INLINE_MID
`define INLINE_MODULE /*verilator inline_module*/
`define INLINE_MID_MODULE /*verilator no_inline_module*/
`else
`ifdef USE_INLINE
`define INLINE_MODULE /*verilator inline_module*/
`define INLINE_MID_MODULE /*verilator inline_module*/
`else
`define INLINE_MODULE /*verilator public_module*/
`define INLINE_MID_MODULE /*verilator public_module*/
`endif
`endif
module global_mod;
`INLINE_MODULE
parameter INITVAL = 0;
integer globali;
initial globali = INITVAL;
endmodule
module ma (
output wire [31:0] outb0c0,
output wire [31:0] outb0c1,
output wire [31:0] outb1c0,
output wire [31:0] outb1c1
);
`INLINE_MODULE
reg [7:0] rmtmem [7:0];
mb #(0) mb0 (.outc0(outb0c0), .outc1(outb0c1));
mb #(1) mb1 (.outc0(outb1c0), .outc1(outb1c1));
endmodule
module mb (
output wire [31:0] outc0,
output wire [31:0] outc1
);
`INLINE_MID_MODULE
parameter P2 = 0;
mc #(P2,0) mc0 (.out(outc0));
mc #(P2,1) mc1 (.out(outc1));
global_mod #(32'hf33d) global_cell2 ();
wire reach_up_clk = t.clk;
always @(reach_up_clk) begin
if (P2==0) begin // Only for mb0
if (outc0 !== t.ma0.mb0.mc0.out) $stop; // Top module name and lower instances
if (outc0 !== ma0.mb0.mc0.out) $stop; // Upper module name and lower instances
if (outc0 !== ma .mb0.mc0.out) $stop; // Upper module name and lower instances
if (outc0 !== mb.mc0.out) $stop; // This module name and lower instances
if (outc0 !== mb0.mc0.out) $stop; // Upper instance name and lower instances
if (outc0 !== mc0.out) $stop; // Lower instances
if (outc1 !== t.ma0.mb0.mc1.out) $stop; // Top module name and lower instances
if (outc1 !== ma0.mb0.mc1.out) $stop; // Upper module name and lower instances
if (outc1 !== ma .mb0.mc1.out) $stop; // Upper module name and lower instances
if (outc1 !== mb.mc1.out) $stop; // This module name and lower instances
if (outc1 !== mb0.mc1.out) $stop; // Upper instance name and lower instances
if (outc1 !== mc1.out) $stop; // Lower instances
end
end
endmodule
module mc (output reg [31:0] out);
`INLINE_MODULE
parameter P2 = 0;
parameter P3 = 0;
initial begin
out = {24'h0,P2[3:0],P3[3:0]};
//$write("%m P2=%0x p3=%0x out=%x\n",P2, P3, out);
end
// Can we look from the top module name down?
wire [31:0] reach_up_cyc = t.cyc;
always @ (posedge t.clk) begin
//$write("[%0t] %m: Got reachup, cyc=%0d\n", $time, reach_up_cyc);
if (reach_up_cyc==2) begin
if (global_cell.globali != 32'hf00d) $stop;
if (global_cell2.globali != 32'hf33d) $stop;
end
if (reach_up_cyc==4) begin
out[15:12] <= {P2[3:0]+P3[3:0]+4'd1};
end
if (reach_up_cyc==5) begin
// Can we set another instance?
if (P3==1) begin // Without this, there are two possible correct answers...
mc0.out[19:16] <= {mc0.out[19:16]+P2[3:0]+P3[3:0]+4'd2};
$display("%m Set %x->%x %x %x %x %x",mc0.out, {mc0.out[19:16]+P2[3:0]+P3[3:0]+4'd2}, mc0.out[19:16],P2[3:0],P3[3:0],4'd2);
end
end
end
endmodule
|
////////////////////////////////////////////////////////////////////////////////
// //
// This file is placed into the Public Domain, for any use, without warranty. //
// 2012 by Iztok Jeras //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// //
// This testbench contains a bus source and a bus drain. The source creates //
// address and data bus values, while the drain is the final destination of //
// such pairs. All source and drain transfers are logged into memories, which //
// are used at the end of simulation to check for data transfer correctness. //
// Inside the RLT wrapper there is a multiplexer and a demultiplexer, they //
// bus transfers into a 8bit data stream and back. Both stream input and //
// output are exposed, they are connected together into a loopback. //
// //
// ----------- --------------------- //
// | bso_mem | | wrap | //
// ----------- | | //
// ----------- | | ----------- | //
// | bsi src | ------------> | -> | mux | -> | -> - sto //
// ----------- | ----------- | \ //
// | | | loopback //
// ----------- | ----------- | / //
// | bso drn | <------------ | <- | demux | <- | <- - sti //
// ----------- | | ----------- | //
// ----------- | | //
// | bso_mem | | | //
// ----------- --------------------- //
// //
// PROTOCOL: //
// //
// The 'vld' signal is driven by the source to indicate valid data is //
// available, 'rdy' is used by the drain to indicate is is ready to accept //
// valid data. A data transfer only happens if both 'vld' & 'rdy' are active. //
// //
////////////////////////////////////////////////////////////////////////////////
`timescale 1ns/1ps
// include RTL files
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_def.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_demux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_mux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_wrap.sv"
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
parameter SIZ = 10;
// system signals
//logic clk = 1'b1; // clock
logic rst = 1'b1; // reset
integer rst_cnt = 0;
// input bus
logic bsi_vld; // valid (chip select)
logic [31:0] bsi_adr; // address
logic [31:0] bsi_dat; // data
logic bsi_rdy; // ready (acknowledge)
logic bsi_trn; // data transfer
logic [31:0] bsi_mem [SIZ];
// output stream
logic sto_vld; // valid (chip select)
logic [7:0] sto_bus; // data bus
logic sto_rdy; // ready (acknowledge)
// input stream
logic sti_vld; // valid (chip select)
logic [7:0] sti_bus; // data bus
logic sti_rdy; // ready (acknowledge)
// output bus
logic bso_vld; // valid (chip select)
logic [31:0] bso_adr; // address
logic [31:0] bso_dat; // data
logic bso_rdy; // ready (acknowledge)
logic bso_trn; // data transfer
logic [31:0] bso_mem [SIZ];
integer bso_cnt = 0;
////////////////////////////////////////////////////////////////////////////////
// clock and reset
////////////////////////////////////////////////////////////////////////////////
// clock toggling
//always #5 clk = ~clk;
// reset is removed after a delay
always @ (posedge clk)
begin
rst_cnt <= rst_cnt + 1;
rst <= rst_cnt <= 3;
end
// reset is removed after a delay
always @ (posedge clk)
if (bso_cnt == SIZ) begin
if (bsi_mem === bso_mem) begin $write("*-* All Finished *-*\n"); $finish(); end
else begin $display ("FAILED"); $stop(); end
end
////////////////////////////////////////////////////////////////////////////////
// input data generator
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bsi_trn = bsi_vld & bsi_rdy;
// valid (for SIZ transfers)
always @ (posedge clk, posedge rst)
if (rst) bsi_vld = 1'b0;
else bsi_vld = (bsi_adr < SIZ);
// address (increments every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_adr <= 32'h00000000;
else if (bsi_trn) bsi_adr <= bsi_adr + 'd1;
// data (new random value generated after every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_dat <= 32'h00000000;
else if (bsi_trn) bsi_dat <= $random();
// storing transferred data into memory for final check
always @ (posedge clk)
if (bsi_trn) bsi_mem [bsi_adr] <= bsi_dat;
////////////////////////////////////////////////////////////////////////////////
// RTL instance
////////////////////////////////////////////////////////////////////////////////
sv_bus_mux_demux_wrap wrap (
// system signals
.clk (clk),
.rst (rst),
// input bus
.bsi_vld (bsi_vld),
.bsi_adr (bsi_adr),
.bsi_dat (bsi_dat),
.bsi_rdy (bsi_rdy),
// output stream
.sto_vld (sto_vld),
.sto_bus (sto_bus),
.sto_rdy (sto_rdy),
// input stream
.sti_vld (sti_vld),
.sti_bus (sti_bus),
.sti_rdy (sti_rdy),
// output bus
.bso_vld (bso_vld),
.bso_adr (bso_adr),
.bso_dat (bso_dat),
.bso_rdy (bso_rdy)
);
// stream output from mux is looped back into stream input for demux
assign sti_vld = sto_vld;
assign sti_bus = sto_bus;
assign sto_rdy = sti_rdy;
////////////////////////////////////////////////////////////////////////////////
// output data monitor
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bso_trn = bso_vld & bso_rdy;
// output transfer counter used to end the test
always @ (posedge clk, posedge rst)
if (rst) bso_cnt <= 0;
else if (bso_trn) bso_cnt <= bso_cnt + 1;
// storing transferred data into memory for final check
always @ (posedge clk)
if (bso_trn) bso_mem [bso_adr] <= bso_dat;
// every output transfer against expected value stored in memory
always @ (posedge clk)
if (bso_trn && (bsi_mem [bso_adr] !== bso_dat))
$display ("@%08h i:%08h o:%08h", bso_adr, bsi_mem [bso_adr], bso_dat);
// ready is active for SIZ transfers
always @ (posedge clk, posedge rst)
if (rst) bso_rdy = 1'b0;
else bso_rdy = 1'b1;
endmodule : sv_bus_mux_demux_tb
|
////////////////////////////////////////////////////////////////////////////////
// //
// This file is placed into the Public Domain, for any use, without warranty. //
// 2012 by Iztok Jeras //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// //
// This testbench contains a bus source and a bus drain. The source creates //
// address and data bus values, while the drain is the final destination of //
// such pairs. All source and drain transfers are logged into memories, which //
// are used at the end of simulation to check for data transfer correctness. //
// Inside the RLT wrapper there is a multiplexer and a demultiplexer, they //
// bus transfers into a 8bit data stream and back. Both stream input and //
// output are exposed, they are connected together into a loopback. //
// //
// ----------- --------------------- //
// | bso_mem | | wrap | //
// ----------- | | //
// ----------- | | ----------- | //
// | bsi src | ------------> | -> | mux | -> | -> - sto //
// ----------- | ----------- | \ //
// | | | loopback //
// ----------- | ----------- | / //
// | bso drn | <------------ | <- | demux | <- | <- - sti //
// ----------- | | ----------- | //
// ----------- | | //
// | bso_mem | | | //
// ----------- --------------------- //
// //
// PROTOCOL: //
// //
// The 'vld' signal is driven by the source to indicate valid data is //
// available, 'rdy' is used by the drain to indicate is is ready to accept //
// valid data. A data transfer only happens if both 'vld' & 'rdy' are active. //
// //
////////////////////////////////////////////////////////////////////////////////
`timescale 1ns/1ps
// include RTL files
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_def.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_demux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_mux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_wrap.sv"
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
parameter SIZ = 10;
// system signals
//logic clk = 1'b1; // clock
logic rst = 1'b1; // reset
integer rst_cnt = 0;
// input bus
logic bsi_vld; // valid (chip select)
logic [31:0] bsi_adr; // address
logic [31:0] bsi_dat; // data
logic bsi_rdy; // ready (acknowledge)
logic bsi_trn; // data transfer
logic [31:0] bsi_mem [SIZ];
// output stream
logic sto_vld; // valid (chip select)
logic [7:0] sto_bus; // data bus
logic sto_rdy; // ready (acknowledge)
// input stream
logic sti_vld; // valid (chip select)
logic [7:0] sti_bus; // data bus
logic sti_rdy; // ready (acknowledge)
// output bus
logic bso_vld; // valid (chip select)
logic [31:0] bso_adr; // address
logic [31:0] bso_dat; // data
logic bso_rdy; // ready (acknowledge)
logic bso_trn; // data transfer
logic [31:0] bso_mem [SIZ];
integer bso_cnt = 0;
////////////////////////////////////////////////////////////////////////////////
// clock and reset
////////////////////////////////////////////////////////////////////////////////
// clock toggling
//always #5 clk = ~clk;
// reset is removed after a delay
always @ (posedge clk)
begin
rst_cnt <= rst_cnt + 1;
rst <= rst_cnt <= 3;
end
// reset is removed after a delay
always @ (posedge clk)
if (bso_cnt == SIZ) begin
if (bsi_mem === bso_mem) begin $write("*-* All Finished *-*\n"); $finish(); end
else begin $display ("FAILED"); $stop(); end
end
////////////////////////////////////////////////////////////////////////////////
// input data generator
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bsi_trn = bsi_vld & bsi_rdy;
// valid (for SIZ transfers)
always @ (posedge clk, posedge rst)
if (rst) bsi_vld = 1'b0;
else bsi_vld = (bsi_adr < SIZ);
// address (increments every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_adr <= 32'h00000000;
else if (bsi_trn) bsi_adr <= bsi_adr + 'd1;
// data (new random value generated after every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_dat <= 32'h00000000;
else if (bsi_trn) bsi_dat <= $random();
// storing transferred data into memory for final check
always @ (posedge clk)
if (bsi_trn) bsi_mem [bsi_adr] <= bsi_dat;
////////////////////////////////////////////////////////////////////////////////
// RTL instance
////////////////////////////////////////////////////////////////////////////////
sv_bus_mux_demux_wrap wrap (
// system signals
.clk (clk),
.rst (rst),
// input bus
.bsi_vld (bsi_vld),
.bsi_adr (bsi_adr),
.bsi_dat (bsi_dat),
.bsi_rdy (bsi_rdy),
// output stream
.sto_vld (sto_vld),
.sto_bus (sto_bus),
.sto_rdy (sto_rdy),
// input stream
.sti_vld (sti_vld),
.sti_bus (sti_bus),
.sti_rdy (sti_rdy),
// output bus
.bso_vld (bso_vld),
.bso_adr (bso_adr),
.bso_dat (bso_dat),
.bso_rdy (bso_rdy)
);
// stream output from mux is looped back into stream input for demux
assign sti_vld = sto_vld;
assign sti_bus = sto_bus;
assign sto_rdy = sti_rdy;
////////////////////////////////////////////////////////////////////////////////
// output data monitor
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bso_trn = bso_vld & bso_rdy;
// output transfer counter used to end the test
always @ (posedge clk, posedge rst)
if (rst) bso_cnt <= 0;
else if (bso_trn) bso_cnt <= bso_cnt + 1;
// storing transferred data into memory for final check
always @ (posedge clk)
if (bso_trn) bso_mem [bso_adr] <= bso_dat;
// every output transfer against expected value stored in memory
always @ (posedge clk)
if (bso_trn && (bsi_mem [bso_adr] !== bso_dat))
$display ("@%08h i:%08h o:%08h", bso_adr, bsi_mem [bso_adr], bso_dat);
// ready is active for SIZ transfers
always @ (posedge clk, posedge rst)
if (rst) bso_rdy = 1'b0;
else bso_rdy = 1'b1;
endmodule : sv_bus_mux_demux_tb
|
////////////////////////////////////////////////////////////////////////////////
// //
// This file is placed into the Public Domain, for any use, without warranty. //
// 2012 by Iztok Jeras //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// //
// This testbench contains a bus source and a bus drain. The source creates //
// address and data bus values, while the drain is the final destination of //
// such pairs. All source and drain transfers are logged into memories, which //
// are used at the end of simulation to check for data transfer correctness. //
// Inside the RLT wrapper there is a multiplexer and a demultiplexer, they //
// bus transfers into a 8bit data stream and back. Both stream input and //
// output are exposed, they are connected together into a loopback. //
// //
// ----------- --------------------- //
// | bso_mem | | wrap | //
// ----------- | | //
// ----------- | | ----------- | //
// | bsi src | ------------> | -> | mux | -> | -> - sto //
// ----------- | ----------- | \ //
// | | | loopback //
// ----------- | ----------- | / //
// | bso drn | <------------ | <- | demux | <- | <- - sti //
// ----------- | | ----------- | //
// ----------- | | //
// | bso_mem | | | //
// ----------- --------------------- //
// //
// PROTOCOL: //
// //
// The 'vld' signal is driven by the source to indicate valid data is //
// available, 'rdy' is used by the drain to indicate is is ready to accept //
// valid data. A data transfer only happens if both 'vld' & 'rdy' are active. //
// //
////////////////////////////////////////////////////////////////////////////////
`timescale 1ns/1ps
// include RTL files
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_def.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_demux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_mux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_wrap.sv"
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
parameter SIZ = 10;
// system signals
//logic clk = 1'b1; // clock
logic rst = 1'b1; // reset
integer rst_cnt = 0;
// input bus
logic bsi_vld; // valid (chip select)
logic [31:0] bsi_adr; // address
logic [31:0] bsi_dat; // data
logic bsi_rdy; // ready (acknowledge)
logic bsi_trn; // data transfer
logic [31:0] bsi_mem [SIZ];
// output stream
logic sto_vld; // valid (chip select)
logic [7:0] sto_bus; // data bus
logic sto_rdy; // ready (acknowledge)
// input stream
logic sti_vld; // valid (chip select)
logic [7:0] sti_bus; // data bus
logic sti_rdy; // ready (acknowledge)
// output bus
logic bso_vld; // valid (chip select)
logic [31:0] bso_adr; // address
logic [31:0] bso_dat; // data
logic bso_rdy; // ready (acknowledge)
logic bso_trn; // data transfer
logic [31:0] bso_mem [SIZ];
integer bso_cnt = 0;
////////////////////////////////////////////////////////////////////////////////
// clock and reset
////////////////////////////////////////////////////////////////////////////////
// clock toggling
//always #5 clk = ~clk;
// reset is removed after a delay
always @ (posedge clk)
begin
rst_cnt <= rst_cnt + 1;
rst <= rst_cnt <= 3;
end
// reset is removed after a delay
always @ (posedge clk)
if (bso_cnt == SIZ) begin
if (bsi_mem === bso_mem) begin $write("*-* All Finished *-*\n"); $finish(); end
else begin $display ("FAILED"); $stop(); end
end
////////////////////////////////////////////////////////////////////////////////
// input data generator
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bsi_trn = bsi_vld & bsi_rdy;
// valid (for SIZ transfers)
always @ (posedge clk, posedge rst)
if (rst) bsi_vld = 1'b0;
else bsi_vld = (bsi_adr < SIZ);
// address (increments every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_adr <= 32'h00000000;
else if (bsi_trn) bsi_adr <= bsi_adr + 'd1;
// data (new random value generated after every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_dat <= 32'h00000000;
else if (bsi_trn) bsi_dat <= $random();
// storing transferred data into memory for final check
always @ (posedge clk)
if (bsi_trn) bsi_mem [bsi_adr] <= bsi_dat;
////////////////////////////////////////////////////////////////////////////////
// RTL instance
////////////////////////////////////////////////////////////////////////////////
sv_bus_mux_demux_wrap wrap (
// system signals
.clk (clk),
.rst (rst),
// input bus
.bsi_vld (bsi_vld),
.bsi_adr (bsi_adr),
.bsi_dat (bsi_dat),
.bsi_rdy (bsi_rdy),
// output stream
.sto_vld (sto_vld),
.sto_bus (sto_bus),
.sto_rdy (sto_rdy),
// input stream
.sti_vld (sti_vld),
.sti_bus (sti_bus),
.sti_rdy (sti_rdy),
// output bus
.bso_vld (bso_vld),
.bso_adr (bso_adr),
.bso_dat (bso_dat),
.bso_rdy (bso_rdy)
);
// stream output from mux is looped back into stream input for demux
assign sti_vld = sto_vld;
assign sti_bus = sto_bus;
assign sto_rdy = sti_rdy;
////////////////////////////////////////////////////////////////////////////////
// output data monitor
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bso_trn = bso_vld & bso_rdy;
// output transfer counter used to end the test
always @ (posedge clk, posedge rst)
if (rst) bso_cnt <= 0;
else if (bso_trn) bso_cnt <= bso_cnt + 1;
// storing transferred data into memory for final check
always @ (posedge clk)
if (bso_trn) bso_mem [bso_adr] <= bso_dat;
// every output transfer against expected value stored in memory
always @ (posedge clk)
if (bso_trn && (bsi_mem [bso_adr] !== bso_dat))
$display ("@%08h i:%08h o:%08h", bso_adr, bsi_mem [bso_adr], bso_dat);
// ready is active for SIZ transfers
always @ (posedge clk, posedge rst)
if (rst) bso_rdy = 1'b0;
else bso_rdy = 1'b1;
endmodule : sv_bus_mux_demux_tb
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// Low-latency RAM-based FIFO. Uses a low-latency register-based FIFO to
// mask the latency of the RAM-based FIFO.
//
// This FIFO uses additional area beyond the FIFO capacity and
// counters in order to compensate for the latency in a normal RAM FIFO.
//
//===----------------------------------------------------------------------===//
module acl_ll_ram_fifo
#(
parameter integer DATA_WIDTH = 32, // >0
parameter integer DEPTH = 32 // >3
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in,
output logic [DATA_WIDTH-1:0] data_out,
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
output logic empty,
output logic full
);
localparam SEL_RAM = 0;
localparam SEL_LL = 1;
// Three FIFOs:
// 1. data - RAM FIFO (normal latency)
// 2. data - LL REG FIFO
// 3. selector - LL REG FIFO
//
// Selector determines which of the two data FIFOs to select the current
// output from.
//
// TODO Implementation note:
// It's probably possible to use a more compact storage mechanism than
// a FIFO for the selector because the sequence of selector values
// should be highly compressible (e.g. long sequences of SEL_RAM). The
// selector FIFO can probably be replaced with a small number of counters.
// A future enhancement.
logic [DATA_WIDTH-1:0] ram_data_in, ram_data_out;
logic ram_valid_in, ram_valid_out, ram_stall_in, ram_stall_out;
logic [DATA_WIDTH-1:0] ll_data_in, ll_data_out;
logic ll_valid_in, ll_valid_out, ll_stall_in, ll_stall_out;
logic sel_data_in, sel_data_out;
logic sel_valid_in, sel_valid_out, sel_stall_in, sel_stall_out;
// Top-level outputs.
assign data_out = sel_data_out == SEL_LL ? ll_data_out : ram_data_out;
assign valid_out = sel_valid_out; // the required ll_valid_out/ram_valid_out must also be asserted
assign stall_out = sel_stall_out;
// RAM FIFO.
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH - 3),
.IMPL("ram")
)
ram_fifo (
.clock(clock),
.resetn(resetn),
.data_in(ram_data_in),
.data_out(ram_data_out),
.valid_in(ram_valid_in),
.valid_out(ram_valid_out),
.stall_in(ram_stall_in),
.stall_out(ram_stall_out)
);
assign ram_data_in = data_in;
assign ram_valid_in = valid_in & ll_stall_out; // only write to RAM FIFO if LL FIFO is stalled
assign ram_stall_in = (sel_data_out != SEL_RAM) | stall_in;
// Low-latency FIFO.
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(3),
.IMPL("ll_reg")
)
ll_fifo (
.clock(clock),
.resetn(resetn),
.data_in(ll_data_in),
.data_out(ll_data_out),
.valid_in(ll_valid_in),
.valid_out(ll_valid_out),
.stall_in(ll_stall_in),
.stall_out(ll_stall_out)
);
assign ll_data_in = data_in;
assign ll_valid_in = valid_in & ~ll_stall_out; // write to LL FIFO if it is not stalled
assign ll_stall_in = (sel_data_out != SEL_LL) | stall_in;
// Selector FIFO.
acl_data_fifo #(
.DATA_WIDTH(1),
.DEPTH(DEPTH),
.IMPL("ll_reg")
)
sel_fifo (
.clock(clock),
.resetn(resetn),
.data_in(sel_data_in),
.data_out(sel_data_out),
.valid_in(sel_valid_in),
.valid_out(sel_valid_out),
.stall_in(sel_stall_in),
.stall_out(sel_stall_out),
.empty(empty),
.full(full)
);
assign sel_data_in = ll_valid_in ? SEL_LL : SEL_RAM;
assign sel_valid_in = valid_in;
assign sel_stall_in = stall_in;
endmodule
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.