text
stringlengths 938
1.05M
|
---|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California 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.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// 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 REGENTS OF THE
// UNIVERSITY OF CALIFORNIA 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.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: ff.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: A D/Q flip flop.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`timescale 1ns/1ns
module ff
(
input CLK,
input D,
output reg Q
);
always @ (posedge CLK) begin
Q <= #1 D;
end
endmodule
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(** Base-2 Logarithm *)
Require Import NZAxioms NZMulOrder NZPow.
(** Interface of a log2 function, then its specification on naturals *)
Module Type Log2 (Import A : Typ).
Parameter Inline log2 : t -> t.
End Log2.
Module Type NZLog2Spec (A : NZOrdAxiomsSig')(B : Pow' A)(C : Log2 A).
Import A B C.
Axiom log2_spec : forall a, 0<a -> 2^(log2 a) <= a < 2^(S (log2 a)).
Axiom log2_nonpos : forall a, a<=0 -> log2 a == 0.
End NZLog2Spec.
Module Type NZLog2 (A : NZOrdAxiomsSig)(B : Pow A) := Log2 A <+ NZLog2Spec A B.
(** Derived properties of logarithm *)
Module Type NZLog2Prop
(Import A : NZOrdAxiomsSig')
(Import B : NZPow' A)
(Import C : NZLog2 A B)
(Import D : NZMulOrderProp A)
(Import E : NZPowProp A B D).
(** log2 is always non-negative *)
Lemma log2_nonneg : forall a, 0 <= log2 a.
Proof.
intros a. destruct (le_gt_cases a 0) as [Ha|Ha].
now rewrite log2_nonpos.
destruct (log2_spec a Ha) as (_,LT).
apply lt_succ_r, (pow_gt_1 2). order'.
rewrite <- le_succ_l, <- one_succ in Ha. order.
Qed.
(** A tactic for proving positivity and non-negativity *)
Ltac order_pos :=
((apply add_pos_pos || apply add_nonneg_nonneg ||
apply mul_pos_pos || apply mul_nonneg_nonneg ||
apply pow_nonneg || apply pow_pos_nonneg ||
apply log2_nonneg || apply (le_le_succ_r 0));
order_pos) (* in case of success of an apply, we recurse *)
|| order'. (* otherwise *)
(** The spec of log2 indeed determines it *)
Lemma log2_unique : forall a b, 0<=b -> 2^b<=a<2^(S b) -> log2 a == b.
Proof.
intros a b Hb (LEb,LTb).
assert (Ha : 0 < a).
apply lt_le_trans with (2^b); trivial.
apply pow_pos_nonneg; order'.
assert (Hc := log2_nonneg a).
destruct (log2_spec a Ha) as (LEc,LTc).
assert (log2 a <= b).
apply lt_succ_r, (pow_lt_mono_r_iff 2); try order'.
now apply le_le_succ_r.
assert (b <= log2 a).
apply lt_succ_r, (pow_lt_mono_r_iff 2); try order'.
now apply le_le_succ_r.
order.
Qed.
(** Hence log2 is a morphism. *)
Instance log2_wd : Proper (eq==>eq) log2.
Proof.
intros x x' Hx.
destruct (le_gt_cases x 0).
rewrite 2 log2_nonpos; trivial. reflexivity. now rewrite <- Hx.
apply log2_unique. apply log2_nonneg.
rewrite Hx in *. now apply log2_spec.
Qed.
(** An alternate specification *)
Lemma log2_spec_alt : forall a, 0<a -> exists r,
a == 2^(log2 a) + r /\ 0 <= r < 2^(log2 a).
Proof.
intros a Ha.
destruct (log2_spec _ Ha) as (LE,LT).
destruct (le_exists_sub _ _ LE) as (r & Hr & Hr').
exists r.
split. now rewrite add_comm.
split. trivial.
apply (add_lt_mono_r _ _ (2^log2 a)).
rewrite <- Hr. generalize LT.
rewrite pow_succ_r by order_pos.
rewrite two_succ at 1. now nzsimpl.
Qed.
Lemma log2_unique' : forall a b c, 0<=b -> 0<=c<2^b ->
a == 2^b + c -> log2 a == b.
Proof.
intros a b c Hb (Hc,H) EQ.
apply log2_unique. trivial.
rewrite EQ.
split.
rewrite <- add_0_r at 1. now apply add_le_mono_l.
rewrite pow_succ_r by order.
rewrite two_succ at 2. nzsimpl. now apply add_lt_mono_l.
Qed.
(** log2 is exact on powers of 2 *)
Lemma log2_pow2 : forall a, 0<=a -> log2 (2^a) == a.
Proof.
intros a Ha.
apply log2_unique' with 0; trivial.
split; order_pos. now nzsimpl.
Qed.
(** log2 and predecessors of powers of 2 *)
Lemma log2_pred_pow2 : forall a, 0<a -> log2 (P (2^a)) == P a.
Proof.
intros a Ha.
assert (Ha' : S (P a) == a) by (now rewrite lt_succ_pred with 0).
apply log2_unique.
apply lt_succ_r; order.
rewrite <-le_succ_l, <-lt_succ_r, Ha'.
rewrite lt_succ_pred with 0.
split; try easy. apply pow_lt_mono_r_iff; try order'.
rewrite succ_lt_mono, Ha'. apply lt_succ_diag_r.
apply pow_pos_nonneg; order'.
Qed.
(** log2 and basic constants *)
Lemma log2_1 : log2 1 == 0.
Proof.
rewrite <- (pow_0_r 2). now apply log2_pow2.
Qed.
Lemma log2_2 : log2 2 == 1.
Proof.
rewrite <- (pow_1_r 2). apply log2_pow2; order'.
Qed.
(** log2 n is strictly positive for 1<n *)
Lemma log2_pos : forall a, 1<a -> 0 < log2 a.
Proof.
intros a Ha.
assert (Ha' : 0 < a) by order'.
assert (H := log2_nonneg a). le_elim H; trivial.
generalize (log2_spec a Ha'). rewrite <- H in *. nzsimpl; try order.
intros (_,H'). rewrite two_succ in H'. apply lt_succ_r in H'; order.
Qed.
(** Said otherwise, log2 is null only below 1 *)
Lemma log2_null : forall a, log2 a == 0 <-> a <= 1.
Proof.
intros a. split; intros H.
destruct (le_gt_cases a 1) as [Ha|Ha]; trivial.
generalize (log2_pos a Ha); order.
le_elim H.
apply log2_nonpos. apply lt_succ_r. now rewrite <- one_succ.
rewrite H. apply log2_1.
Qed.
(** log2 is a monotone function (but not a strict one) *)
Lemma log2_le_mono : forall a b, a<=b -> log2 a <= log2 b.
Proof.
intros a b H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite log2_nonpos; order_pos.
assert (Hb : 0 < b) by order.
destruct (log2_spec a Ha) as (LEa,_).
destruct (log2_spec b Hb) as (_,LTb).
apply lt_succ_r, (pow_lt_mono_r_iff 2); order_pos.
Qed.
(** No reverse result for <=, consider for instance log2 3 <= log2 2 *)
Lemma log2_lt_cancel : forall a b, log2 a < log2 b -> a < b.
Proof.
intros a b H.
destruct (le_gt_cases b 0) as [Hb|Hb].
rewrite (log2_nonpos b) in H; trivial.
generalize (log2_nonneg a); order.
destruct (le_gt_cases a 0) as [Ha|Ha]. order.
destruct (log2_spec a Ha) as (_,LTa).
destruct (log2_spec b Hb) as (LEb,_).
apply le_succ_l in H.
apply (pow_le_mono_r_iff 2) in H; order_pos.
Qed.
(** When left side is a power of 2, we have an equivalence for <= *)
Lemma log2_le_pow2 : forall a b, 0<a -> (2^b<=a <-> b <= log2 a).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_nonneg a); order.
rewrite <- (log2_pow2 b); trivial. now apply log2_le_mono.
transitivity (2^(log2 a)).
apply pow_le_mono_r; order'.
now destruct (log2_spec a Ha).
Qed.
(** When right side is a square, we have an equivalence for < *)
Lemma log2_lt_pow2 : forall a b, 0<a -> (a<2^b <-> log2 a < b).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
rewrite pow_neg_r in H; order.
apply (pow_lt_mono_r_iff 2); try order_pos.
apply le_lt_trans with a; trivial.
now destruct (log2_spec a Ha).
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_nonneg a); order.
apply log2_lt_cancel; try order.
now rewrite log2_pow2.
Qed.
(** Comparing log2 and identity *)
Lemma log2_lt_lin : forall a, 0<a -> log2 a < a.
Proof.
intros a Ha.
apply (pow_lt_mono_r_iff 2); try order_pos.
apply le_lt_trans with a.
now destruct (log2_spec a Ha).
apply pow_gt_lin_r; order'.
Qed.
Lemma log2_le_lin : forall a, 0<=a -> log2 a <= a.
Proof.
intros a Ha.
le_elim Ha.
now apply lt_le_incl, log2_lt_lin.
rewrite <- Ha, log2_nonpos; order.
Qed.
(** Log2 and multiplication. *)
(** Due to rounding error, we don't have the usual
[log2 (a*b) = log2 a + log2 b] but we may be off by 1 at most *)
Lemma log2_mul_below : forall a b, 0<a -> 0<b ->
log2 a + log2 b <= log2 (a*b).
Proof.
intros a b Ha Hb.
apply log2_le_pow2; try order_pos.
rewrite pow_add_r by order_pos.
apply mul_le_mono_nonneg; try apply log2_spec; order_pos.
Qed.
Lemma log2_mul_above : forall a b, 0<=a -> 0<=b ->
log2 (a*b) <= log2 a + log2 b + 1.
Proof.
intros a b Ha Hb.
le_elim Ha.
le_elim Hb.
apply lt_succ_r.
rewrite add_1_r, <- add_succ_r, <- add_succ_l.
apply log2_lt_pow2; try order_pos.
rewrite pow_add_r by order_pos.
apply mul_lt_mono_nonneg; try order; now apply log2_spec.
rewrite <- Hb. nzsimpl. rewrite log2_nonpos; order_pos.
rewrite <- Ha. nzsimpl. rewrite log2_nonpos; order_pos.
Qed.
(** And we can't find better approximations in general.
- The lower bound is exact for powers of 2.
- Concerning the upper bound, for any c>1, take a=b=2^c-1,
then log2 (a*b) = c+c -1 while (log2 a) = (log2 b) = c-1
*)
(** At least, we get back the usual equation when we multiply by 2 (or 2^k) *)
Lemma log2_mul_pow2 : forall a b, 0<a -> 0<=b -> log2 (a*2^b) == b + log2 a.
Proof.
intros a b Ha Hb.
apply log2_unique; try order_pos. split.
rewrite pow_add_r, mul_comm; try order_pos.
apply mul_le_mono_nonneg_r. order_pos. now apply log2_spec.
rewrite <-add_succ_r, pow_add_r, mul_comm; try order_pos.
apply mul_lt_mono_pos_l. order_pos. now apply log2_spec.
Qed.
Lemma log2_double : forall a, 0<a -> log2 (2*a) == S (log2 a).
Proof.
intros a Ha. generalize (log2_mul_pow2 a 1 Ha le_0_1). now nzsimpl'.
Qed.
(** Two numbers with same log2 cannot be far away. *)
Lemma log2_same : forall a b, 0<a -> 0<b -> log2 a == log2 b -> a < 2*b.
Proof.
intros a b Ha Hb H.
apply log2_lt_cancel. rewrite log2_double, H by trivial.
apply lt_succ_diag_r.
Qed.
(** Log2 and successor :
- the log2 function climbs by at most 1 at a time
- otherwise it stays at the same value
- the +1 steps occur for powers of two
*)
Lemma log2_succ_le : forall a, log2 (S a) <= S (log2 a).
Proof.
intros a.
destruct (lt_trichotomy 0 a) as [LT|[EQ|LT]].
apply (pow_le_mono_r_iff 2); try order_pos.
transitivity (S a).
apply log2_spec.
apply lt_succ_r; order.
now apply le_succ_l, log2_spec.
rewrite <- EQ, <- one_succ, log2_1; order_pos.
rewrite 2 log2_nonpos. order_pos. order'. now rewrite le_succ_l.
Qed.
Lemma log2_succ_or : forall a,
log2 (S a) == S (log2 a) \/ log2 (S a) == log2 a.
Proof.
intros.
destruct (le_gt_cases (log2 (S a)) (log2 a)) as [H|H].
right. generalize (log2_le_mono _ _ (le_succ_diag_r a)); order.
left. apply le_succ_l in H. generalize (log2_succ_le a); order.
Qed.
Lemma log2_eq_succ_is_pow2 : forall a,
log2 (S a) == S (log2 a) -> exists b, S a == 2^b.
Proof.
intros a H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite 2 (proj2 (log2_null _)) in H. generalize (lt_succ_diag_r 0); order.
order'. apply le_succ_l. order'.
assert (Ha' : 0 < S a) by (apply lt_succ_r; order).
exists (log2 (S a)).
generalize (proj1 (log2_spec (S a) Ha')) (proj2 (log2_spec a Ha)).
rewrite <- le_succ_l, <- H. order.
Qed.
Lemma log2_eq_succ_iff_pow2 : forall a, 0<a ->
(log2 (S a) == S (log2 a) <-> exists b, S a == 2^b).
Proof.
intros a Ha.
split. apply log2_eq_succ_is_pow2.
intros (b,Hb).
assert (Hb' : 0 < b).
apply (pow_gt_1 2); try order'; now rewrite <- Hb, one_succ, <- succ_lt_mono.
rewrite Hb, log2_pow2; try order'.
setoid_replace a with (P (2^b)). rewrite log2_pred_pow2; trivial.
symmetry; now apply lt_succ_pred with 0.
apply succ_inj. rewrite Hb. symmetry. apply lt_succ_pred with 0.
rewrite <- Hb, lt_succ_r; order.
Qed.
Lemma log2_succ_double : forall a, 0<a -> log2 (2*a+1) == S (log2 a).
Proof.
intros a Ha.
rewrite add_1_r.
destruct (log2_succ_or (2*a)) as [H|H]; [exfalso|now rewrite H, log2_double].
apply log2_eq_succ_is_pow2 in H. destruct H as (b,H).
destruct (lt_trichotomy b 0) as [LT|[EQ|LT]].
rewrite pow_neg_r in H; trivial.
apply (mul_pos_pos 2), succ_lt_mono in Ha; try order'.
rewrite <- one_succ in Ha. order'.
rewrite EQ, pow_0_r in H.
apply (mul_pos_pos 2), succ_lt_mono in Ha; try order'.
rewrite <- one_succ in Ha. order'.
assert (EQ:=lt_succ_pred 0 b LT).
rewrite <- EQ, pow_succ_r in H; [|now rewrite <- lt_succ_r, EQ].
destruct (lt_ge_cases a (2^(P b))) as [LT'|LE'].
generalize (mul_2_mono_l _ _ LT'). rewrite add_1_l. order.
rewrite (mul_le_mono_pos_l _ _ 2) in LE'; try order'.
rewrite <- H in LE'. apply le_succ_l in LE'. order.
Qed.
(** Log2 and addition *)
Lemma log2_add_le : forall a b, a~=1 -> b~=1 -> log2 (a+b) <= log2 a + log2 b.
Proof.
intros a b Ha Hb.
destruct (lt_trichotomy a 1) as [Ha'|[Ha'|Ha']]; [|order|].
rewrite one_succ, lt_succ_r in Ha'.
rewrite (log2_nonpos a); trivial. nzsimpl. apply log2_le_mono.
rewrite <- (add_0_l b) at 2. now apply add_le_mono.
destruct (lt_trichotomy b 1) as [Hb'|[Hb'|Hb']]; [|order|].
rewrite one_succ, lt_succ_r in Hb'.
rewrite (log2_nonpos b); trivial. nzsimpl. apply log2_le_mono.
rewrite <- (add_0_r a) at 2. now apply add_le_mono.
clear Ha Hb.
apply lt_succ_r.
apply log2_lt_pow2; try order_pos.
rewrite pow_succ_r by order_pos.
rewrite two_succ, one_succ at 1. nzsimpl.
apply add_lt_mono.
apply lt_le_trans with (2^(S (log2 a))). apply log2_spec; order'.
apply pow_le_mono_r. order'. rewrite <- add_1_r. apply add_le_mono_l.
rewrite one_succ; now apply le_succ_l, log2_pos.
apply lt_le_trans with (2^(S (log2 b))). apply log2_spec; order'.
apply pow_le_mono_r. order'. rewrite <- add_1_l. apply add_le_mono_r.
rewrite one_succ; now apply le_succ_l, log2_pos.
Qed.
(** The sum of two log2 is less than twice the log2 of the sum.
The large inequality is obvious thanks to monotonicity.
The strict one requires some more work. This is almost
a convexity inequality for points [2a], [2b] and their middle [a+b] :
ideally, we would have [2*log(a+b) >= log(2a)+log(2b) = 2+log a+log b].
Here, we cannot do better: consider for instance a=2 b=4, then 1+2<2*2
*)
Lemma add_log2_lt : forall a b, 0<a -> 0<b ->
log2 a + log2 b < 2 * log2 (a+b).
Proof.
intros a b Ha Hb. nzsimpl'.
assert (H : log2 a <= log2 (a+b)).
apply log2_le_mono. rewrite <- (add_0_r a) at 1. apply add_le_mono; order.
assert (H' : log2 b <= log2 (a+b)).
apply log2_le_mono. rewrite <- (add_0_l b) at 1. apply add_le_mono; order.
le_elim H.
apply lt_le_trans with (log2 (a+b) + log2 b).
now apply add_lt_mono_r. now apply add_le_mono_l.
rewrite <- H at 1. apply add_lt_mono_l.
le_elim H'; trivial.
symmetry in H. apply log2_same in H; try order_pos.
symmetry in H'. apply log2_same in H'; try order_pos.
revert H H'. nzsimpl'. rewrite <- add_lt_mono_l, <- add_lt_mono_r; order.
Qed.
End NZLog2Prop.
Module NZLog2UpProp
(Import A : NZDecOrdAxiomsSig')
(Import B : NZPow' A)
(Import C : NZLog2 A B)
(Import D : NZMulOrderProp A)
(Import E : NZPowProp A B D)
(Import F : NZLog2Prop A B C D E).
(** * [log2_up] : a binary logarithm that rounds up instead of down *)
(** For once, we define instead of axiomatizing, thanks to log2 *)
Definition log2_up a :=
match compare 1 a with
| Lt => S (log2 (P a))
| _ => 0
end.
Lemma log2_up_eqn0 : forall a, a<=1 -> log2_up a == 0.
Proof.
intros a Ha. unfold log2_up. case compare_spec; try order.
Qed.
Lemma log2_up_eqn : forall a, 1<a -> log2_up a == S (log2 (P a)).
Proof.
intros a Ha. unfold log2_up. case compare_spec; try order.
Qed.
Lemma log2_up_spec : forall a, 1<a ->
2^(P (log2_up a)) < a <= 2^(log2_up a).
Proof.
intros a Ha.
rewrite log2_up_eqn; trivial.
rewrite pred_succ.
rewrite <- (lt_succ_pred 1 a Ha) at 2 3.
rewrite lt_succ_r, le_succ_l.
apply log2_spec.
apply succ_lt_mono. now rewrite (lt_succ_pred 1 a Ha), <- one_succ.
Qed.
Lemma log2_up_nonpos : forall a, a<=0 -> log2_up a == 0.
Proof.
intros. apply log2_up_eqn0. order'.
Qed.
Instance log2_up_wd : Proper (eq==>eq) log2_up.
Proof.
assert (Proper (eq==>eq==>Logic.eq) compare).
repeat red; intros; do 2 case compare_spec; trivial; order.
intros a a' Ha. unfold log2_up. rewrite Ha at 1.
case compare; now rewrite ?Ha.
Qed.
(** [log2_up] is always non-negative *)
Lemma log2_up_nonneg : forall a, 0 <= log2_up a.
Proof.
intros a. unfold log2_up. case compare_spec; try order.
intros. apply le_le_succ_r, log2_nonneg.
Qed.
(** The spec of [log2_up] indeed determines it *)
Lemma log2_up_unique : forall a b, 0<b -> 2^(P b)<a<=2^b -> log2_up a == b.
Proof.
intros a b Hb (LEb,LTb).
assert (Ha : 1 < a).
apply le_lt_trans with (2^(P b)); trivial.
rewrite one_succ. apply le_succ_l.
apply pow_pos_nonneg. order'. apply lt_succ_r.
now rewrite (lt_succ_pred 0 b Hb).
assert (Hc := log2_up_nonneg a).
destruct (log2_up_spec a Ha) as (LTc,LEc).
assert (b <= log2_up a).
apply lt_succ_r. rewrite <- (lt_succ_pred 0 b Hb).
rewrite <- succ_lt_mono.
apply (pow_lt_mono_r_iff 2); try order'.
assert (Hc' : 0 < log2_up a) by order.
assert (log2_up a <= b).
apply lt_succ_r. rewrite <- (lt_succ_pred 0 _ Hc').
rewrite <- succ_lt_mono.
apply (pow_lt_mono_r_iff 2); try order'.
order.
Qed.
(** [log2_up] is exact on powers of 2 *)
Lemma log2_up_pow2 : forall a, 0<=a -> log2_up (2^a) == a.
Proof.
intros a Ha.
le_elim Ha.
apply log2_up_unique; trivial.
split; try order.
apply pow_lt_mono_r; try order'.
rewrite <- (lt_succ_pred 0 a Ha) at 2.
now apply lt_succ_r.
now rewrite <- Ha, pow_0_r, log2_up_eqn0.
Qed.
(** [log2_up] and successors of powers of 2 *)
Lemma log2_up_succ_pow2 : forall a, 0<=a -> log2_up (S (2^a)) == S a.
Proof.
intros a Ha.
rewrite log2_up_eqn, pred_succ, log2_pow2; try easy.
rewrite one_succ, <- succ_lt_mono. apply pow_pos_nonneg; order'.
Qed.
(** Basic constants *)
Lemma log2_up_1 : log2_up 1 == 0.
Proof.
now apply log2_up_eqn0.
Qed.
Lemma log2_up_2 : log2_up 2 == 1.
Proof.
rewrite <- (pow_1_r 2). apply log2_up_pow2; order'.
Qed.
(** Links between log2 and [log2_up] *)
Lemma le_log2_log2_up : forall a, log2 a <= log2_up a.
Proof.
intros a. unfold log2_up. case compare_spec; intros H.
rewrite <- H, log2_1. order.
rewrite <- (lt_succ_pred 1 a H) at 1. apply log2_succ_le.
rewrite log2_nonpos. order. now rewrite <-lt_succ_r, <-one_succ.
Qed.
Lemma le_log2_up_succ_log2 : forall a, log2_up a <= S (log2 a).
Proof.
intros a. unfold log2_up. case compare_spec; intros H; try order_pos.
rewrite <- succ_le_mono. apply log2_le_mono.
rewrite <- (lt_succ_pred 1 a H) at 2. apply le_succ_diag_r.
Qed.
Lemma log2_log2_up_spec : forall a, 0<a ->
2^log2 a <= a <= 2^log2_up a.
Proof.
intros a H. split.
now apply log2_spec.
rewrite <-le_succ_l, <-one_succ in H. le_elim H.
now apply log2_up_spec.
now rewrite <-H, log2_up_1, pow_0_r.
Qed.
Lemma log2_log2_up_exact :
forall a, 0<a -> (log2 a == log2_up a <-> exists b, a == 2^b).
Proof.
intros a Ha.
split. intros. exists (log2 a).
generalize (log2_log2_up_spec a Ha). rewrite <-H.
destruct 1; order.
intros (b,Hb). rewrite Hb.
destruct (le_gt_cases 0 b).
now rewrite log2_pow2, log2_up_pow2.
rewrite pow_neg_r; trivial. now rewrite log2_nonpos, log2_up_nonpos.
Qed.
(** [log2_up] n is strictly positive for 1<n *)
Lemma log2_up_pos : forall a, 1<a -> 0 < log2_up a.
Proof.
intros. rewrite log2_up_eqn; trivial. apply lt_succ_r; order_pos.
Qed.
(** Said otherwise, [log2_up] is null only below 1 *)
Lemma log2_up_null : forall a, log2_up a == 0 <-> a <= 1.
Proof.
intros a. split; intros H.
destruct (le_gt_cases a 1) as [Ha|Ha]; trivial.
generalize (log2_up_pos a Ha); order.
now apply log2_up_eqn0.
Qed.
(** [log2_up] is a monotone function (but not a strict one) *)
Lemma log2_up_le_mono : forall a b, a<=b -> log2_up a <= log2_up b.
Proof.
intros a b H.
destruct (le_gt_cases a 1) as [Ha|Ha].
rewrite log2_up_eqn0; trivial. apply log2_up_nonneg.
rewrite 2 log2_up_eqn; try order.
rewrite <- succ_le_mono. apply log2_le_mono, succ_le_mono.
rewrite 2 lt_succ_pred with 1; order.
Qed.
(** No reverse result for <=, consider for instance log2_up 4 <= log2_up 3 *)
Lemma log2_up_lt_cancel : forall a b, log2_up a < log2_up b -> a < b.
Proof.
intros a b H.
destruct (le_gt_cases b 1) as [Hb|Hb].
rewrite (log2_up_eqn0 b) in H; trivial.
generalize (log2_up_nonneg a); order.
destruct (le_gt_cases a 1) as [Ha|Ha]. order.
rewrite 2 log2_up_eqn in H; try order.
rewrite <- succ_lt_mono in H. apply log2_lt_cancel, succ_lt_mono in H.
rewrite 2 lt_succ_pred with 1 in H; order.
Qed.
(** When left side is a power of 2, we have an equivalence for < *)
Lemma log2_up_lt_pow2 : forall a b, 0<a -> (2^b<a <-> b < log2_up a).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_up_nonneg a); order.
apply (pow_lt_mono_r_iff 2). order'. apply log2_up_nonneg.
apply lt_le_trans with a; trivial.
apply (log2_up_spec a).
apply le_lt_trans with (2^b); trivial.
rewrite one_succ, le_succ_l. apply pow_pos_nonneg; order'.
destruct (lt_ge_cases b 0) as [Hb|Hb].
now rewrite pow_neg_r.
rewrite <- (log2_up_pow2 b) in H; trivial. now apply log2_up_lt_cancel.
Qed.
(** When right side is a square, we have an equivalence for <= *)
Lemma log2_up_le_pow2 : forall a b, 0<a -> (a<=2^b <-> log2_up a <= b).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
rewrite pow_neg_r in H; order.
rewrite <- (log2_up_pow2 b); trivial. now apply log2_up_le_mono.
transitivity (2^(log2_up a)).
now apply log2_log2_up_spec.
apply pow_le_mono_r; order'.
Qed.
(** Comparing [log2_up] and identity *)
Lemma log2_up_lt_lin : forall a, 0<a -> log2_up a < a.
Proof.
intros a Ha.
assert (H : S (P a) == a) by (now apply lt_succ_pred with 0).
rewrite <- H at 2. apply lt_succ_r. apply log2_up_le_pow2; trivial.
rewrite <- H at 1. apply le_succ_l.
apply pow_gt_lin_r. order'. apply lt_succ_r; order.
Qed.
Lemma log2_up_le_lin : forall a, 0<=a -> log2_up a <= a.
Proof.
intros a Ha.
le_elim Ha.
now apply lt_le_incl, log2_up_lt_lin.
rewrite <- Ha, log2_up_nonpos; order.
Qed.
(** [log2_up] and multiplication. *)
(** Due to rounding error, we don't have the usual
[log2_up (a*b) = log2_up a + log2_up b] but we may be off by 1 at most *)
Lemma log2_up_mul_above : forall a b, 0<=a -> 0<=b ->
log2_up (a*b) <= log2_up a + log2_up b.
Proof.
intros a b Ha Hb.
assert (Ha':=log2_up_nonneg a).
assert (Hb':=log2_up_nonneg b).
le_elim Ha.
le_elim Hb.
apply log2_up_le_pow2; try order_pos.
rewrite pow_add_r; trivial.
apply mul_le_mono_nonneg; try apply log2_log2_up_spec; order'.
rewrite <- Hb. nzsimpl. rewrite log2_up_nonpos; order_pos.
rewrite <- Ha. nzsimpl. rewrite log2_up_nonpos; order_pos.
Qed.
Lemma log2_up_mul_below : forall a b, 0<a -> 0<b ->
log2_up a + log2_up b <= S (log2_up (a*b)).
Proof.
intros a b Ha Hb.
rewrite <-le_succ_l, <-one_succ in Ha. le_elim Ha.
rewrite <-le_succ_l, <-one_succ in Hb. le_elim Hb.
assert (Ha' : 0 < log2_up a) by (apply log2_up_pos; trivial).
assert (Hb' : 0 < log2_up b) by (apply log2_up_pos; trivial).
rewrite <- (lt_succ_pred 0 (log2_up a)); trivial.
rewrite <- (lt_succ_pred 0 (log2_up b)); trivial.
nzsimpl. rewrite <- succ_le_mono, le_succ_l.
apply (pow_lt_mono_r_iff 2). order'. apply log2_up_nonneg.
rewrite pow_add_r; try (apply lt_succ_r; rewrite (lt_succ_pred 0); trivial).
apply lt_le_trans with (a*b).
apply mul_lt_mono_nonneg; try order_pos; try now apply log2_up_spec.
apply log2_up_spec.
setoid_replace 1 with (1*1) by now nzsimpl.
apply mul_lt_mono_nonneg; order'.
rewrite <- Hb, log2_up_1; nzsimpl. apply le_succ_diag_r.
rewrite <- Ha, log2_up_1; nzsimpl. apply le_succ_diag_r.
Qed.
(** And we can't find better approximations in general.
- The upper bound is exact for powers of 2.
- Concerning the lower bound, for any c>1, take a=b=2^c+1,
then [log2_up (a*b) = c+c +1] while [(log2_up a) = (log2_up b) = c+1]
*)
(** At least, we get back the usual equation when we multiply by 2 (or 2^k) *)
Lemma log2_up_mul_pow2 : forall a b, 0<a -> 0<=b ->
log2_up (a*2^b) == b + log2_up a.
Proof.
intros a b Ha Hb.
rewrite <- le_succ_l, <- one_succ in Ha; le_elim Ha.
apply log2_up_unique. apply add_nonneg_pos; trivial. now apply log2_up_pos.
split.
assert (EQ := lt_succ_pred 0 _ (log2_up_pos _ Ha)).
rewrite <- EQ. nzsimpl. rewrite pow_add_r, mul_comm; trivial.
apply mul_lt_mono_pos_r. order_pos. now apply log2_up_spec.
rewrite <- lt_succ_r, EQ. now apply log2_up_pos.
rewrite pow_add_r, mul_comm; trivial.
apply mul_le_mono_nonneg_l. order_pos. now apply log2_up_spec.
apply log2_up_nonneg.
now rewrite <- Ha, mul_1_l, log2_up_1, add_0_r, log2_up_pow2.
Qed.
Lemma log2_up_double : forall a, 0<a -> log2_up (2*a) == S (log2_up a).
Proof.
intros a Ha. generalize (log2_up_mul_pow2 a 1 Ha le_0_1). now nzsimpl'.
Qed.
(** Two numbers with same [log2_up] cannot be far away. *)
Lemma log2_up_same : forall a b, 0<a -> 0<b -> log2_up a == log2_up b -> a < 2*b.
Proof.
intros a b Ha Hb H.
apply log2_up_lt_cancel. rewrite log2_up_double, H by trivial.
apply lt_succ_diag_r.
Qed.
(** [log2_up] and successor :
- the [log2_up] function climbs by at most 1 at a time
- otherwise it stays at the same value
- the +1 steps occur after powers of two
*)
Lemma log2_up_succ_le : forall a, log2_up (S a) <= S (log2_up a).
Proof.
intros a.
destruct (lt_trichotomy 1 a) as [LT|[EQ|LT]].
rewrite 2 log2_up_eqn; trivial.
rewrite pred_succ, <- succ_le_mono. rewrite <-(lt_succ_pred 1 a LT) at 1.
apply log2_succ_le.
apply lt_succ_r; order.
rewrite <- EQ, <- two_succ, log2_up_1, log2_up_2. now nzsimpl'.
rewrite 2 log2_up_eqn0. order_pos. order'. now rewrite le_succ_l.
Qed.
Lemma log2_up_succ_or : forall a,
log2_up (S a) == S (log2_up a) \/ log2_up (S a) == log2_up a.
Proof.
intros.
destruct (le_gt_cases (log2_up (S a)) (log2_up a)).
right. generalize (log2_up_le_mono _ _ (le_succ_diag_r a)); order.
left. apply le_succ_l in H. generalize (log2_up_succ_le a); order.
Qed.
Lemma log2_up_eq_succ_is_pow2 : forall a,
log2_up (S a) == S (log2_up a) -> exists b, a == 2^b.
Proof.
intros a H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite 2 (proj2 (log2_up_null _)) in H. generalize (lt_succ_diag_r 0); order.
order'. apply le_succ_l. order'.
assert (Ha' : 1 < S a) by (now rewrite one_succ, <- succ_lt_mono).
exists (log2_up a).
generalize (proj1 (log2_up_spec (S a) Ha')) (proj2 (log2_log2_up_spec a Ha)).
rewrite H, pred_succ, lt_succ_r. order.
Qed.
Lemma log2_up_eq_succ_iff_pow2 : forall a, 0<a ->
(log2_up (S a) == S (log2_up a) <-> exists b, a == 2^b).
Proof.
intros a Ha.
split. apply log2_up_eq_succ_is_pow2.
intros (b,Hb).
destruct (lt_ge_cases b 0) as [Hb'|Hb'].
rewrite pow_neg_r in Hb; order.
rewrite Hb, log2_up_pow2; try order'.
now rewrite log2_up_succ_pow2.
Qed.
Lemma log2_up_succ_double : forall a, 0<a ->
log2_up (2*a+1) == 2 + log2 a.
Proof.
intros a Ha.
rewrite log2_up_eqn. rewrite add_1_r, pred_succ, log2_double; now nzsimpl'.
apply le_lt_trans with (0+1). now nzsimpl'.
apply add_lt_mono_r. order_pos.
Qed.
(** [log2_up] and addition *)
Lemma log2_up_add_le : forall a b, a~=1 -> b~=1 ->
log2_up (a+b) <= log2_up a + log2_up b.
Proof.
intros a b Ha Hb.
destruct (lt_trichotomy a 1) as [Ha'|[Ha'|Ha']]; [|order|].
rewrite (log2_up_eqn0 a) by order. nzsimpl. apply log2_up_le_mono.
rewrite one_succ, lt_succ_r in Ha'.
rewrite <- (add_0_l b) at 2. now apply add_le_mono.
destruct (lt_trichotomy b 1) as [Hb'|[Hb'|Hb']]; [|order|].
rewrite (log2_up_eqn0 b) by order. nzsimpl. apply log2_up_le_mono.
rewrite one_succ, lt_succ_r in Hb'.
rewrite <- (add_0_r a) at 2. now apply add_le_mono.
clear Ha Hb.
transitivity (log2_up (a*b)).
now apply log2_up_le_mono, add_le_mul.
apply log2_up_mul_above; order'.
Qed.
(** The sum of two [log2_up] is less than twice the [log2_up] of the sum.
The large inequality is obvious thanks to monotonicity.
The strict one requires some more work. This is almost
a convexity inequality for points [2a], [2b] and their middle [a+b] :
ideally, we would have [2*log(a+b) >= log(2a)+log(2b) = 2+log a+log b].
Here, we cannot do better: consider for instance a=3 b=5, then 2+3<2*3
*)
Lemma add_log2_up_lt : forall a b, 0<a -> 0<b ->
log2_up a + log2_up b < 2 * log2_up (a+b).
Proof.
intros a b Ha Hb. nzsimpl'.
assert (H : log2_up a <= log2_up (a+b)).
apply log2_up_le_mono. rewrite <- (add_0_r a) at 1. apply add_le_mono; order.
assert (H' : log2_up b <= log2_up (a+b)).
apply log2_up_le_mono. rewrite <- (add_0_l b) at 1. apply add_le_mono; order.
le_elim H.
apply lt_le_trans with (log2_up (a+b) + log2_up b).
now apply add_lt_mono_r. now apply add_le_mono_l.
rewrite <- H at 1. apply add_lt_mono_l.
le_elim H'. trivial.
symmetry in H. apply log2_up_same in H; try order_pos.
symmetry in H'. apply log2_up_same in H'; try order_pos.
revert H H'. nzsimpl'. rewrite <- add_lt_mono_l, <- add_lt_mono_r; order.
Qed.
End NZLog2UpProp.
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(** Base-2 Logarithm *)
Require Import NZAxioms NZMulOrder NZPow.
(** Interface of a log2 function, then its specification on naturals *)
Module Type Log2 (Import A : Typ).
Parameter Inline log2 : t -> t.
End Log2.
Module Type NZLog2Spec (A : NZOrdAxiomsSig')(B : Pow' A)(C : Log2 A).
Import A B C.
Axiom log2_spec : forall a, 0<a -> 2^(log2 a) <= a < 2^(S (log2 a)).
Axiom log2_nonpos : forall a, a<=0 -> log2 a == 0.
End NZLog2Spec.
Module Type NZLog2 (A : NZOrdAxiomsSig)(B : Pow A) := Log2 A <+ NZLog2Spec A B.
(** Derived properties of logarithm *)
Module Type NZLog2Prop
(Import A : NZOrdAxiomsSig')
(Import B : NZPow' A)
(Import C : NZLog2 A B)
(Import D : NZMulOrderProp A)
(Import E : NZPowProp A B D).
(** log2 is always non-negative *)
Lemma log2_nonneg : forall a, 0 <= log2 a.
Proof.
intros a. destruct (le_gt_cases a 0) as [Ha|Ha].
now rewrite log2_nonpos.
destruct (log2_spec a Ha) as (_,LT).
apply lt_succ_r, (pow_gt_1 2). order'.
rewrite <- le_succ_l, <- one_succ in Ha. order.
Qed.
(** A tactic for proving positivity and non-negativity *)
Ltac order_pos :=
((apply add_pos_pos || apply add_nonneg_nonneg ||
apply mul_pos_pos || apply mul_nonneg_nonneg ||
apply pow_nonneg || apply pow_pos_nonneg ||
apply log2_nonneg || apply (le_le_succ_r 0));
order_pos) (* in case of success of an apply, we recurse *)
|| order'. (* otherwise *)
(** The spec of log2 indeed determines it *)
Lemma log2_unique : forall a b, 0<=b -> 2^b<=a<2^(S b) -> log2 a == b.
Proof.
intros a b Hb (LEb,LTb).
assert (Ha : 0 < a).
apply lt_le_trans with (2^b); trivial.
apply pow_pos_nonneg; order'.
assert (Hc := log2_nonneg a).
destruct (log2_spec a Ha) as (LEc,LTc).
assert (log2 a <= b).
apply lt_succ_r, (pow_lt_mono_r_iff 2); try order'.
now apply le_le_succ_r.
assert (b <= log2 a).
apply lt_succ_r, (pow_lt_mono_r_iff 2); try order'.
now apply le_le_succ_r.
order.
Qed.
(** Hence log2 is a morphism. *)
Instance log2_wd : Proper (eq==>eq) log2.
Proof.
intros x x' Hx.
destruct (le_gt_cases x 0).
rewrite 2 log2_nonpos; trivial. reflexivity. now rewrite <- Hx.
apply log2_unique. apply log2_nonneg.
rewrite Hx in *. now apply log2_spec.
Qed.
(** An alternate specification *)
Lemma log2_spec_alt : forall a, 0<a -> exists r,
a == 2^(log2 a) + r /\ 0 <= r < 2^(log2 a).
Proof.
intros a Ha.
destruct (log2_spec _ Ha) as (LE,LT).
destruct (le_exists_sub _ _ LE) as (r & Hr & Hr').
exists r.
split. now rewrite add_comm.
split. trivial.
apply (add_lt_mono_r _ _ (2^log2 a)).
rewrite <- Hr. generalize LT.
rewrite pow_succ_r by order_pos.
rewrite two_succ at 1. now nzsimpl.
Qed.
Lemma log2_unique' : forall a b c, 0<=b -> 0<=c<2^b ->
a == 2^b + c -> log2 a == b.
Proof.
intros a b c Hb (Hc,H) EQ.
apply log2_unique. trivial.
rewrite EQ.
split.
rewrite <- add_0_r at 1. now apply add_le_mono_l.
rewrite pow_succ_r by order.
rewrite two_succ at 2. nzsimpl. now apply add_lt_mono_l.
Qed.
(** log2 is exact on powers of 2 *)
Lemma log2_pow2 : forall a, 0<=a -> log2 (2^a) == a.
Proof.
intros a Ha.
apply log2_unique' with 0; trivial.
split; order_pos. now nzsimpl.
Qed.
(** log2 and predecessors of powers of 2 *)
Lemma log2_pred_pow2 : forall a, 0<a -> log2 (P (2^a)) == P a.
Proof.
intros a Ha.
assert (Ha' : S (P a) == a) by (now rewrite lt_succ_pred with 0).
apply log2_unique.
apply lt_succ_r; order.
rewrite <-le_succ_l, <-lt_succ_r, Ha'.
rewrite lt_succ_pred with 0.
split; try easy. apply pow_lt_mono_r_iff; try order'.
rewrite succ_lt_mono, Ha'. apply lt_succ_diag_r.
apply pow_pos_nonneg; order'.
Qed.
(** log2 and basic constants *)
Lemma log2_1 : log2 1 == 0.
Proof.
rewrite <- (pow_0_r 2). now apply log2_pow2.
Qed.
Lemma log2_2 : log2 2 == 1.
Proof.
rewrite <- (pow_1_r 2). apply log2_pow2; order'.
Qed.
(** log2 n is strictly positive for 1<n *)
Lemma log2_pos : forall a, 1<a -> 0 < log2 a.
Proof.
intros a Ha.
assert (Ha' : 0 < a) by order'.
assert (H := log2_nonneg a). le_elim H; trivial.
generalize (log2_spec a Ha'). rewrite <- H in *. nzsimpl; try order.
intros (_,H'). rewrite two_succ in H'. apply lt_succ_r in H'; order.
Qed.
(** Said otherwise, log2 is null only below 1 *)
Lemma log2_null : forall a, log2 a == 0 <-> a <= 1.
Proof.
intros a. split; intros H.
destruct (le_gt_cases a 1) as [Ha|Ha]; trivial.
generalize (log2_pos a Ha); order.
le_elim H.
apply log2_nonpos. apply lt_succ_r. now rewrite <- one_succ.
rewrite H. apply log2_1.
Qed.
(** log2 is a monotone function (but not a strict one) *)
Lemma log2_le_mono : forall a b, a<=b -> log2 a <= log2 b.
Proof.
intros a b H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite log2_nonpos; order_pos.
assert (Hb : 0 < b) by order.
destruct (log2_spec a Ha) as (LEa,_).
destruct (log2_spec b Hb) as (_,LTb).
apply lt_succ_r, (pow_lt_mono_r_iff 2); order_pos.
Qed.
(** No reverse result for <=, consider for instance log2 3 <= log2 2 *)
Lemma log2_lt_cancel : forall a b, log2 a < log2 b -> a < b.
Proof.
intros a b H.
destruct (le_gt_cases b 0) as [Hb|Hb].
rewrite (log2_nonpos b) in H; trivial.
generalize (log2_nonneg a); order.
destruct (le_gt_cases a 0) as [Ha|Ha]. order.
destruct (log2_spec a Ha) as (_,LTa).
destruct (log2_spec b Hb) as (LEb,_).
apply le_succ_l in H.
apply (pow_le_mono_r_iff 2) in H; order_pos.
Qed.
(** When left side is a power of 2, we have an equivalence for <= *)
Lemma log2_le_pow2 : forall a b, 0<a -> (2^b<=a <-> b <= log2 a).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_nonneg a); order.
rewrite <- (log2_pow2 b); trivial. now apply log2_le_mono.
transitivity (2^(log2 a)).
apply pow_le_mono_r; order'.
now destruct (log2_spec a Ha).
Qed.
(** When right side is a square, we have an equivalence for < *)
Lemma log2_lt_pow2 : forall a b, 0<a -> (a<2^b <-> log2 a < b).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
rewrite pow_neg_r in H; order.
apply (pow_lt_mono_r_iff 2); try order_pos.
apply le_lt_trans with a; trivial.
now destruct (log2_spec a Ha).
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_nonneg a); order.
apply log2_lt_cancel; try order.
now rewrite log2_pow2.
Qed.
(** Comparing log2 and identity *)
Lemma log2_lt_lin : forall a, 0<a -> log2 a < a.
Proof.
intros a Ha.
apply (pow_lt_mono_r_iff 2); try order_pos.
apply le_lt_trans with a.
now destruct (log2_spec a Ha).
apply pow_gt_lin_r; order'.
Qed.
Lemma log2_le_lin : forall a, 0<=a -> log2 a <= a.
Proof.
intros a Ha.
le_elim Ha.
now apply lt_le_incl, log2_lt_lin.
rewrite <- Ha, log2_nonpos; order.
Qed.
(** Log2 and multiplication. *)
(** Due to rounding error, we don't have the usual
[log2 (a*b) = log2 a + log2 b] but we may be off by 1 at most *)
Lemma log2_mul_below : forall a b, 0<a -> 0<b ->
log2 a + log2 b <= log2 (a*b).
Proof.
intros a b Ha Hb.
apply log2_le_pow2; try order_pos.
rewrite pow_add_r by order_pos.
apply mul_le_mono_nonneg; try apply log2_spec; order_pos.
Qed.
Lemma log2_mul_above : forall a b, 0<=a -> 0<=b ->
log2 (a*b) <= log2 a + log2 b + 1.
Proof.
intros a b Ha Hb.
le_elim Ha.
le_elim Hb.
apply lt_succ_r.
rewrite add_1_r, <- add_succ_r, <- add_succ_l.
apply log2_lt_pow2; try order_pos.
rewrite pow_add_r by order_pos.
apply mul_lt_mono_nonneg; try order; now apply log2_spec.
rewrite <- Hb. nzsimpl. rewrite log2_nonpos; order_pos.
rewrite <- Ha. nzsimpl. rewrite log2_nonpos; order_pos.
Qed.
(** And we can't find better approximations in general.
- The lower bound is exact for powers of 2.
- Concerning the upper bound, for any c>1, take a=b=2^c-1,
then log2 (a*b) = c+c -1 while (log2 a) = (log2 b) = c-1
*)
(** At least, we get back the usual equation when we multiply by 2 (or 2^k) *)
Lemma log2_mul_pow2 : forall a b, 0<a -> 0<=b -> log2 (a*2^b) == b + log2 a.
Proof.
intros a b Ha Hb.
apply log2_unique; try order_pos. split.
rewrite pow_add_r, mul_comm; try order_pos.
apply mul_le_mono_nonneg_r. order_pos. now apply log2_spec.
rewrite <-add_succ_r, pow_add_r, mul_comm; try order_pos.
apply mul_lt_mono_pos_l. order_pos. now apply log2_spec.
Qed.
Lemma log2_double : forall a, 0<a -> log2 (2*a) == S (log2 a).
Proof.
intros a Ha. generalize (log2_mul_pow2 a 1 Ha le_0_1). now nzsimpl'.
Qed.
(** Two numbers with same log2 cannot be far away. *)
Lemma log2_same : forall a b, 0<a -> 0<b -> log2 a == log2 b -> a < 2*b.
Proof.
intros a b Ha Hb H.
apply log2_lt_cancel. rewrite log2_double, H by trivial.
apply lt_succ_diag_r.
Qed.
(** Log2 and successor :
- the log2 function climbs by at most 1 at a time
- otherwise it stays at the same value
- the +1 steps occur for powers of two
*)
Lemma log2_succ_le : forall a, log2 (S a) <= S (log2 a).
Proof.
intros a.
destruct (lt_trichotomy 0 a) as [LT|[EQ|LT]].
apply (pow_le_mono_r_iff 2); try order_pos.
transitivity (S a).
apply log2_spec.
apply lt_succ_r; order.
now apply le_succ_l, log2_spec.
rewrite <- EQ, <- one_succ, log2_1; order_pos.
rewrite 2 log2_nonpos. order_pos. order'. now rewrite le_succ_l.
Qed.
Lemma log2_succ_or : forall a,
log2 (S a) == S (log2 a) \/ log2 (S a) == log2 a.
Proof.
intros.
destruct (le_gt_cases (log2 (S a)) (log2 a)) as [H|H].
right. generalize (log2_le_mono _ _ (le_succ_diag_r a)); order.
left. apply le_succ_l in H. generalize (log2_succ_le a); order.
Qed.
Lemma log2_eq_succ_is_pow2 : forall a,
log2 (S a) == S (log2 a) -> exists b, S a == 2^b.
Proof.
intros a H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite 2 (proj2 (log2_null _)) in H. generalize (lt_succ_diag_r 0); order.
order'. apply le_succ_l. order'.
assert (Ha' : 0 < S a) by (apply lt_succ_r; order).
exists (log2 (S a)).
generalize (proj1 (log2_spec (S a) Ha')) (proj2 (log2_spec a Ha)).
rewrite <- le_succ_l, <- H. order.
Qed.
Lemma log2_eq_succ_iff_pow2 : forall a, 0<a ->
(log2 (S a) == S (log2 a) <-> exists b, S a == 2^b).
Proof.
intros a Ha.
split. apply log2_eq_succ_is_pow2.
intros (b,Hb).
assert (Hb' : 0 < b).
apply (pow_gt_1 2); try order'; now rewrite <- Hb, one_succ, <- succ_lt_mono.
rewrite Hb, log2_pow2; try order'.
setoid_replace a with (P (2^b)). rewrite log2_pred_pow2; trivial.
symmetry; now apply lt_succ_pred with 0.
apply succ_inj. rewrite Hb. symmetry. apply lt_succ_pred with 0.
rewrite <- Hb, lt_succ_r; order.
Qed.
Lemma log2_succ_double : forall a, 0<a -> log2 (2*a+1) == S (log2 a).
Proof.
intros a Ha.
rewrite add_1_r.
destruct (log2_succ_or (2*a)) as [H|H]; [exfalso|now rewrite H, log2_double].
apply log2_eq_succ_is_pow2 in H. destruct H as (b,H).
destruct (lt_trichotomy b 0) as [LT|[EQ|LT]].
rewrite pow_neg_r in H; trivial.
apply (mul_pos_pos 2), succ_lt_mono in Ha; try order'.
rewrite <- one_succ in Ha. order'.
rewrite EQ, pow_0_r in H.
apply (mul_pos_pos 2), succ_lt_mono in Ha; try order'.
rewrite <- one_succ in Ha. order'.
assert (EQ:=lt_succ_pred 0 b LT).
rewrite <- EQ, pow_succ_r in H; [|now rewrite <- lt_succ_r, EQ].
destruct (lt_ge_cases a (2^(P b))) as [LT'|LE'].
generalize (mul_2_mono_l _ _ LT'). rewrite add_1_l. order.
rewrite (mul_le_mono_pos_l _ _ 2) in LE'; try order'.
rewrite <- H in LE'. apply le_succ_l in LE'. order.
Qed.
(** Log2 and addition *)
Lemma log2_add_le : forall a b, a~=1 -> b~=1 -> log2 (a+b) <= log2 a + log2 b.
Proof.
intros a b Ha Hb.
destruct (lt_trichotomy a 1) as [Ha'|[Ha'|Ha']]; [|order|].
rewrite one_succ, lt_succ_r in Ha'.
rewrite (log2_nonpos a); trivial. nzsimpl. apply log2_le_mono.
rewrite <- (add_0_l b) at 2. now apply add_le_mono.
destruct (lt_trichotomy b 1) as [Hb'|[Hb'|Hb']]; [|order|].
rewrite one_succ, lt_succ_r in Hb'.
rewrite (log2_nonpos b); trivial. nzsimpl. apply log2_le_mono.
rewrite <- (add_0_r a) at 2. now apply add_le_mono.
clear Ha Hb.
apply lt_succ_r.
apply log2_lt_pow2; try order_pos.
rewrite pow_succ_r by order_pos.
rewrite two_succ, one_succ at 1. nzsimpl.
apply add_lt_mono.
apply lt_le_trans with (2^(S (log2 a))). apply log2_spec; order'.
apply pow_le_mono_r. order'. rewrite <- add_1_r. apply add_le_mono_l.
rewrite one_succ; now apply le_succ_l, log2_pos.
apply lt_le_trans with (2^(S (log2 b))). apply log2_spec; order'.
apply pow_le_mono_r. order'. rewrite <- add_1_l. apply add_le_mono_r.
rewrite one_succ; now apply le_succ_l, log2_pos.
Qed.
(** The sum of two log2 is less than twice the log2 of the sum.
The large inequality is obvious thanks to monotonicity.
The strict one requires some more work. This is almost
a convexity inequality for points [2a], [2b] and their middle [a+b] :
ideally, we would have [2*log(a+b) >= log(2a)+log(2b) = 2+log a+log b].
Here, we cannot do better: consider for instance a=2 b=4, then 1+2<2*2
*)
Lemma add_log2_lt : forall a b, 0<a -> 0<b ->
log2 a + log2 b < 2 * log2 (a+b).
Proof.
intros a b Ha Hb. nzsimpl'.
assert (H : log2 a <= log2 (a+b)).
apply log2_le_mono. rewrite <- (add_0_r a) at 1. apply add_le_mono; order.
assert (H' : log2 b <= log2 (a+b)).
apply log2_le_mono. rewrite <- (add_0_l b) at 1. apply add_le_mono; order.
le_elim H.
apply lt_le_trans with (log2 (a+b) + log2 b).
now apply add_lt_mono_r. now apply add_le_mono_l.
rewrite <- H at 1. apply add_lt_mono_l.
le_elim H'; trivial.
symmetry in H. apply log2_same in H; try order_pos.
symmetry in H'. apply log2_same in H'; try order_pos.
revert H H'. nzsimpl'. rewrite <- add_lt_mono_l, <- add_lt_mono_r; order.
Qed.
End NZLog2Prop.
Module NZLog2UpProp
(Import A : NZDecOrdAxiomsSig')
(Import B : NZPow' A)
(Import C : NZLog2 A B)
(Import D : NZMulOrderProp A)
(Import E : NZPowProp A B D)
(Import F : NZLog2Prop A B C D E).
(** * [log2_up] : a binary logarithm that rounds up instead of down *)
(** For once, we define instead of axiomatizing, thanks to log2 *)
Definition log2_up a :=
match compare 1 a with
| Lt => S (log2 (P a))
| _ => 0
end.
Lemma log2_up_eqn0 : forall a, a<=1 -> log2_up a == 0.
Proof.
intros a Ha. unfold log2_up. case compare_spec; try order.
Qed.
Lemma log2_up_eqn : forall a, 1<a -> log2_up a == S (log2 (P a)).
Proof.
intros a Ha. unfold log2_up. case compare_spec; try order.
Qed.
Lemma log2_up_spec : forall a, 1<a ->
2^(P (log2_up a)) < a <= 2^(log2_up a).
Proof.
intros a Ha.
rewrite log2_up_eqn; trivial.
rewrite pred_succ.
rewrite <- (lt_succ_pred 1 a Ha) at 2 3.
rewrite lt_succ_r, le_succ_l.
apply log2_spec.
apply succ_lt_mono. now rewrite (lt_succ_pred 1 a Ha), <- one_succ.
Qed.
Lemma log2_up_nonpos : forall a, a<=0 -> log2_up a == 0.
Proof.
intros. apply log2_up_eqn0. order'.
Qed.
Instance log2_up_wd : Proper (eq==>eq) log2_up.
Proof.
assert (Proper (eq==>eq==>Logic.eq) compare).
repeat red; intros; do 2 case compare_spec; trivial; order.
intros a a' Ha. unfold log2_up. rewrite Ha at 1.
case compare; now rewrite ?Ha.
Qed.
(** [log2_up] is always non-negative *)
Lemma log2_up_nonneg : forall a, 0 <= log2_up a.
Proof.
intros a. unfold log2_up. case compare_spec; try order.
intros. apply le_le_succ_r, log2_nonneg.
Qed.
(** The spec of [log2_up] indeed determines it *)
Lemma log2_up_unique : forall a b, 0<b -> 2^(P b)<a<=2^b -> log2_up a == b.
Proof.
intros a b Hb (LEb,LTb).
assert (Ha : 1 < a).
apply le_lt_trans with (2^(P b)); trivial.
rewrite one_succ. apply le_succ_l.
apply pow_pos_nonneg. order'. apply lt_succ_r.
now rewrite (lt_succ_pred 0 b Hb).
assert (Hc := log2_up_nonneg a).
destruct (log2_up_spec a Ha) as (LTc,LEc).
assert (b <= log2_up a).
apply lt_succ_r. rewrite <- (lt_succ_pred 0 b Hb).
rewrite <- succ_lt_mono.
apply (pow_lt_mono_r_iff 2); try order'.
assert (Hc' : 0 < log2_up a) by order.
assert (log2_up a <= b).
apply lt_succ_r. rewrite <- (lt_succ_pred 0 _ Hc').
rewrite <- succ_lt_mono.
apply (pow_lt_mono_r_iff 2); try order'.
order.
Qed.
(** [log2_up] is exact on powers of 2 *)
Lemma log2_up_pow2 : forall a, 0<=a -> log2_up (2^a) == a.
Proof.
intros a Ha.
le_elim Ha.
apply log2_up_unique; trivial.
split; try order.
apply pow_lt_mono_r; try order'.
rewrite <- (lt_succ_pred 0 a Ha) at 2.
now apply lt_succ_r.
now rewrite <- Ha, pow_0_r, log2_up_eqn0.
Qed.
(** [log2_up] and successors of powers of 2 *)
Lemma log2_up_succ_pow2 : forall a, 0<=a -> log2_up (S (2^a)) == S a.
Proof.
intros a Ha.
rewrite log2_up_eqn, pred_succ, log2_pow2; try easy.
rewrite one_succ, <- succ_lt_mono. apply pow_pos_nonneg; order'.
Qed.
(** Basic constants *)
Lemma log2_up_1 : log2_up 1 == 0.
Proof.
now apply log2_up_eqn0.
Qed.
Lemma log2_up_2 : log2_up 2 == 1.
Proof.
rewrite <- (pow_1_r 2). apply log2_up_pow2; order'.
Qed.
(** Links between log2 and [log2_up] *)
Lemma le_log2_log2_up : forall a, log2 a <= log2_up a.
Proof.
intros a. unfold log2_up. case compare_spec; intros H.
rewrite <- H, log2_1. order.
rewrite <- (lt_succ_pred 1 a H) at 1. apply log2_succ_le.
rewrite log2_nonpos. order. now rewrite <-lt_succ_r, <-one_succ.
Qed.
Lemma le_log2_up_succ_log2 : forall a, log2_up a <= S (log2 a).
Proof.
intros a. unfold log2_up. case compare_spec; intros H; try order_pos.
rewrite <- succ_le_mono. apply log2_le_mono.
rewrite <- (lt_succ_pred 1 a H) at 2. apply le_succ_diag_r.
Qed.
Lemma log2_log2_up_spec : forall a, 0<a ->
2^log2 a <= a <= 2^log2_up a.
Proof.
intros a H. split.
now apply log2_spec.
rewrite <-le_succ_l, <-one_succ in H. le_elim H.
now apply log2_up_spec.
now rewrite <-H, log2_up_1, pow_0_r.
Qed.
Lemma log2_log2_up_exact :
forall a, 0<a -> (log2 a == log2_up a <-> exists b, a == 2^b).
Proof.
intros a Ha.
split. intros. exists (log2 a).
generalize (log2_log2_up_spec a Ha). rewrite <-H.
destruct 1; order.
intros (b,Hb). rewrite Hb.
destruct (le_gt_cases 0 b).
now rewrite log2_pow2, log2_up_pow2.
rewrite pow_neg_r; trivial. now rewrite log2_nonpos, log2_up_nonpos.
Qed.
(** [log2_up] n is strictly positive for 1<n *)
Lemma log2_up_pos : forall a, 1<a -> 0 < log2_up a.
Proof.
intros. rewrite log2_up_eqn; trivial. apply lt_succ_r; order_pos.
Qed.
(** Said otherwise, [log2_up] is null only below 1 *)
Lemma log2_up_null : forall a, log2_up a == 0 <-> a <= 1.
Proof.
intros a. split; intros H.
destruct (le_gt_cases a 1) as [Ha|Ha]; trivial.
generalize (log2_up_pos a Ha); order.
now apply log2_up_eqn0.
Qed.
(** [log2_up] is a monotone function (but not a strict one) *)
Lemma log2_up_le_mono : forall a b, a<=b -> log2_up a <= log2_up b.
Proof.
intros a b H.
destruct (le_gt_cases a 1) as [Ha|Ha].
rewrite log2_up_eqn0; trivial. apply log2_up_nonneg.
rewrite 2 log2_up_eqn; try order.
rewrite <- succ_le_mono. apply log2_le_mono, succ_le_mono.
rewrite 2 lt_succ_pred with 1; order.
Qed.
(** No reverse result for <=, consider for instance log2_up 4 <= log2_up 3 *)
Lemma log2_up_lt_cancel : forall a b, log2_up a < log2_up b -> a < b.
Proof.
intros a b H.
destruct (le_gt_cases b 1) as [Hb|Hb].
rewrite (log2_up_eqn0 b) in H; trivial.
generalize (log2_up_nonneg a); order.
destruct (le_gt_cases a 1) as [Ha|Ha]. order.
rewrite 2 log2_up_eqn in H; try order.
rewrite <- succ_lt_mono in H. apply log2_lt_cancel, succ_lt_mono in H.
rewrite 2 lt_succ_pred with 1 in H; order.
Qed.
(** When left side is a power of 2, we have an equivalence for < *)
Lemma log2_up_lt_pow2 : forall a b, 0<a -> (2^b<a <-> b < log2_up a).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
generalize (log2_up_nonneg a); order.
apply (pow_lt_mono_r_iff 2). order'. apply log2_up_nonneg.
apply lt_le_trans with a; trivial.
apply (log2_up_spec a).
apply le_lt_trans with (2^b); trivial.
rewrite one_succ, le_succ_l. apply pow_pos_nonneg; order'.
destruct (lt_ge_cases b 0) as [Hb|Hb].
now rewrite pow_neg_r.
rewrite <- (log2_up_pow2 b) in H; trivial. now apply log2_up_lt_cancel.
Qed.
(** When right side is a square, we have an equivalence for <= *)
Lemma log2_up_le_pow2 : forall a b, 0<a -> (a<=2^b <-> log2_up a <= b).
Proof.
intros a b Ha.
split; intros H.
destruct (lt_ge_cases b 0) as [Hb|Hb].
rewrite pow_neg_r in H; order.
rewrite <- (log2_up_pow2 b); trivial. now apply log2_up_le_mono.
transitivity (2^(log2_up a)).
now apply log2_log2_up_spec.
apply pow_le_mono_r; order'.
Qed.
(** Comparing [log2_up] and identity *)
Lemma log2_up_lt_lin : forall a, 0<a -> log2_up a < a.
Proof.
intros a Ha.
assert (H : S (P a) == a) by (now apply lt_succ_pred with 0).
rewrite <- H at 2. apply lt_succ_r. apply log2_up_le_pow2; trivial.
rewrite <- H at 1. apply le_succ_l.
apply pow_gt_lin_r. order'. apply lt_succ_r; order.
Qed.
Lemma log2_up_le_lin : forall a, 0<=a -> log2_up a <= a.
Proof.
intros a Ha.
le_elim Ha.
now apply lt_le_incl, log2_up_lt_lin.
rewrite <- Ha, log2_up_nonpos; order.
Qed.
(** [log2_up] and multiplication. *)
(** Due to rounding error, we don't have the usual
[log2_up (a*b) = log2_up a + log2_up b] but we may be off by 1 at most *)
Lemma log2_up_mul_above : forall a b, 0<=a -> 0<=b ->
log2_up (a*b) <= log2_up a + log2_up b.
Proof.
intros a b Ha Hb.
assert (Ha':=log2_up_nonneg a).
assert (Hb':=log2_up_nonneg b).
le_elim Ha.
le_elim Hb.
apply log2_up_le_pow2; try order_pos.
rewrite pow_add_r; trivial.
apply mul_le_mono_nonneg; try apply log2_log2_up_spec; order'.
rewrite <- Hb. nzsimpl. rewrite log2_up_nonpos; order_pos.
rewrite <- Ha. nzsimpl. rewrite log2_up_nonpos; order_pos.
Qed.
Lemma log2_up_mul_below : forall a b, 0<a -> 0<b ->
log2_up a + log2_up b <= S (log2_up (a*b)).
Proof.
intros a b Ha Hb.
rewrite <-le_succ_l, <-one_succ in Ha. le_elim Ha.
rewrite <-le_succ_l, <-one_succ in Hb. le_elim Hb.
assert (Ha' : 0 < log2_up a) by (apply log2_up_pos; trivial).
assert (Hb' : 0 < log2_up b) by (apply log2_up_pos; trivial).
rewrite <- (lt_succ_pred 0 (log2_up a)); trivial.
rewrite <- (lt_succ_pred 0 (log2_up b)); trivial.
nzsimpl. rewrite <- succ_le_mono, le_succ_l.
apply (pow_lt_mono_r_iff 2). order'. apply log2_up_nonneg.
rewrite pow_add_r; try (apply lt_succ_r; rewrite (lt_succ_pred 0); trivial).
apply lt_le_trans with (a*b).
apply mul_lt_mono_nonneg; try order_pos; try now apply log2_up_spec.
apply log2_up_spec.
setoid_replace 1 with (1*1) by now nzsimpl.
apply mul_lt_mono_nonneg; order'.
rewrite <- Hb, log2_up_1; nzsimpl. apply le_succ_diag_r.
rewrite <- Ha, log2_up_1; nzsimpl. apply le_succ_diag_r.
Qed.
(** And we can't find better approximations in general.
- The upper bound is exact for powers of 2.
- Concerning the lower bound, for any c>1, take a=b=2^c+1,
then [log2_up (a*b) = c+c +1] while [(log2_up a) = (log2_up b) = c+1]
*)
(** At least, we get back the usual equation when we multiply by 2 (or 2^k) *)
Lemma log2_up_mul_pow2 : forall a b, 0<a -> 0<=b ->
log2_up (a*2^b) == b + log2_up a.
Proof.
intros a b Ha Hb.
rewrite <- le_succ_l, <- one_succ in Ha; le_elim Ha.
apply log2_up_unique. apply add_nonneg_pos; trivial. now apply log2_up_pos.
split.
assert (EQ := lt_succ_pred 0 _ (log2_up_pos _ Ha)).
rewrite <- EQ. nzsimpl. rewrite pow_add_r, mul_comm; trivial.
apply mul_lt_mono_pos_r. order_pos. now apply log2_up_spec.
rewrite <- lt_succ_r, EQ. now apply log2_up_pos.
rewrite pow_add_r, mul_comm; trivial.
apply mul_le_mono_nonneg_l. order_pos. now apply log2_up_spec.
apply log2_up_nonneg.
now rewrite <- Ha, mul_1_l, log2_up_1, add_0_r, log2_up_pow2.
Qed.
Lemma log2_up_double : forall a, 0<a -> log2_up (2*a) == S (log2_up a).
Proof.
intros a Ha. generalize (log2_up_mul_pow2 a 1 Ha le_0_1). now nzsimpl'.
Qed.
(** Two numbers with same [log2_up] cannot be far away. *)
Lemma log2_up_same : forall a b, 0<a -> 0<b -> log2_up a == log2_up b -> a < 2*b.
Proof.
intros a b Ha Hb H.
apply log2_up_lt_cancel. rewrite log2_up_double, H by trivial.
apply lt_succ_diag_r.
Qed.
(** [log2_up] and successor :
- the [log2_up] function climbs by at most 1 at a time
- otherwise it stays at the same value
- the +1 steps occur after powers of two
*)
Lemma log2_up_succ_le : forall a, log2_up (S a) <= S (log2_up a).
Proof.
intros a.
destruct (lt_trichotomy 1 a) as [LT|[EQ|LT]].
rewrite 2 log2_up_eqn; trivial.
rewrite pred_succ, <- succ_le_mono. rewrite <-(lt_succ_pred 1 a LT) at 1.
apply log2_succ_le.
apply lt_succ_r; order.
rewrite <- EQ, <- two_succ, log2_up_1, log2_up_2. now nzsimpl'.
rewrite 2 log2_up_eqn0. order_pos. order'. now rewrite le_succ_l.
Qed.
Lemma log2_up_succ_or : forall a,
log2_up (S a) == S (log2_up a) \/ log2_up (S a) == log2_up a.
Proof.
intros.
destruct (le_gt_cases (log2_up (S a)) (log2_up a)).
right. generalize (log2_up_le_mono _ _ (le_succ_diag_r a)); order.
left. apply le_succ_l in H. generalize (log2_up_succ_le a); order.
Qed.
Lemma log2_up_eq_succ_is_pow2 : forall a,
log2_up (S a) == S (log2_up a) -> exists b, a == 2^b.
Proof.
intros a H.
destruct (le_gt_cases a 0) as [Ha|Ha].
rewrite 2 (proj2 (log2_up_null _)) in H. generalize (lt_succ_diag_r 0); order.
order'. apply le_succ_l. order'.
assert (Ha' : 1 < S a) by (now rewrite one_succ, <- succ_lt_mono).
exists (log2_up a).
generalize (proj1 (log2_up_spec (S a) Ha')) (proj2 (log2_log2_up_spec a Ha)).
rewrite H, pred_succ, lt_succ_r. order.
Qed.
Lemma log2_up_eq_succ_iff_pow2 : forall a, 0<a ->
(log2_up (S a) == S (log2_up a) <-> exists b, a == 2^b).
Proof.
intros a Ha.
split. apply log2_up_eq_succ_is_pow2.
intros (b,Hb).
destruct (lt_ge_cases b 0) as [Hb'|Hb'].
rewrite pow_neg_r in Hb; order.
rewrite Hb, log2_up_pow2; try order'.
now rewrite log2_up_succ_pow2.
Qed.
Lemma log2_up_succ_double : forall a, 0<a ->
log2_up (2*a+1) == 2 + log2 a.
Proof.
intros a Ha.
rewrite log2_up_eqn. rewrite add_1_r, pred_succ, log2_double; now nzsimpl'.
apply le_lt_trans with (0+1). now nzsimpl'.
apply add_lt_mono_r. order_pos.
Qed.
(** [log2_up] and addition *)
Lemma log2_up_add_le : forall a b, a~=1 -> b~=1 ->
log2_up (a+b) <= log2_up a + log2_up b.
Proof.
intros a b Ha Hb.
destruct (lt_trichotomy a 1) as [Ha'|[Ha'|Ha']]; [|order|].
rewrite (log2_up_eqn0 a) by order. nzsimpl. apply log2_up_le_mono.
rewrite one_succ, lt_succ_r in Ha'.
rewrite <- (add_0_l b) at 2. now apply add_le_mono.
destruct (lt_trichotomy b 1) as [Hb'|[Hb'|Hb']]; [|order|].
rewrite (log2_up_eqn0 b) by order. nzsimpl. apply log2_up_le_mono.
rewrite one_succ, lt_succ_r in Hb'.
rewrite <- (add_0_r a) at 2. now apply add_le_mono.
clear Ha Hb.
transitivity (log2_up (a*b)).
now apply log2_up_le_mono, add_le_mul.
apply log2_up_mul_above; order'.
Qed.
(** The sum of two [log2_up] is less than twice the [log2_up] of the sum.
The large inequality is obvious thanks to monotonicity.
The strict one requires some more work. This is almost
a convexity inequality for points [2a], [2b] and their middle [a+b] :
ideally, we would have [2*log(a+b) >= log(2a)+log(2b) = 2+log a+log b].
Here, we cannot do better: consider for instance a=3 b=5, then 2+3<2*3
*)
Lemma add_log2_up_lt : forall a b, 0<a -> 0<b ->
log2_up a + log2_up b < 2 * log2_up (a+b).
Proof.
intros a b Ha Hb. nzsimpl'.
assert (H : log2_up a <= log2_up (a+b)).
apply log2_up_le_mono. rewrite <- (add_0_r a) at 1. apply add_le_mono; order.
assert (H' : log2_up b <= log2_up (a+b)).
apply log2_up_le_mono. rewrite <- (add_0_l b) at 1. apply add_le_mono; order.
le_elim H.
apply lt_le_trans with (log2_up (a+b) + log2_up b).
now apply add_lt_mono_r. now apply add_le_mono_l.
rewrite <- H at 1. apply add_lt_mono_l.
le_elim H'. trivial.
symmetry in H. apply log2_up_same in H; try order_pos.
symmetry in H'. apply log2_up_same in H'; try order_pos.
revert H H'. nzsimpl'. rewrite <- add_lt_mono_l, <- add_lt_mono_r; order.
Qed.
End NZLog2UpProp.
|
// ----------------------------------------------------------------------
// Copyright (c) 2016, The Regents of the University of California 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.
//
// * Neither the name of The Regents of the University of California
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// 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 REGENTS OF THE
// UNIVERSITY OF CALIFORNIA 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.
// ----------------------------------------------------------------------
//----------------------------------------------------------------------------
// Filename: interrupt.v
// Version: 1.00.a
// Verilog Standard: Verilog-2001
// Description: Manages the interrupt vector and sends interrupts.
// Author: Matt Jacobsen
// History: @mattj: Version 2.0
//-----------------------------------------------------------------------------
`define S_INTR_IDLE 2'd0
`define S_INTR_INTR 2'd1
`define S_INTR_CLR_0 2'd2
`define S_INTR_CLR_1 2'd3
`timescale 1ns/1ns
module interrupt #(
parameter C_NUM_CHNL = 4'd12
)
(
input CLK,
input RST,
input [C_NUM_CHNL-1:0] RX_SG_BUF_RECVD, // The scatter gather data for a rx_port transaction has been read
input [C_NUM_CHNL-1:0] RX_TXN_DONE, // The rx_port transaction is done
input [C_NUM_CHNL-1:0] TX_TXN, // New tx_port transaction
input [C_NUM_CHNL-1:0] TX_SG_BUF_RECVD, // The scatter gather data for a tx_port transaction has been read
input [C_NUM_CHNL-1:0] TX_TXN_DONE, // The tx_port transaction is done
input VECT_0_RST, // Interrupt vector 0 reset
input VECT_1_RST, // Interrupt vector 1 reset
input [31:0] VECT_RST, // Interrupt vector reset value
output [31:0] VECT_0, // Interrupt vector 0
output [31:0] VECT_1, // Interrupt vector 1
input INTR_LEGACY_CLR, // Pulsed high to ack the legacy interrupt and clear it
input CONFIG_INTERRUPT_MSIENABLE, // 1 if MSI interrupts are enable, 0 if only legacy are supported
input INTR_MSI_RDY, // High when interrupt is able to be sent
output INTR_MSI_REQUEST // High to request interrupt, when both INTR_MSI_RDY and INTR_MSI_REQUEST are high, interrupt is sent
);
reg [1:0] rState=0;
reg [31:0] rVect0=0;
reg [31:0] rVect1=0;
wire [31:0] wVect0;
wire [31:0] wVect1;
wire wIntr = (rState == `S_INTR_INTR);
wire wIntrDone;
assign VECT_0 = rVect0;
assign VECT_1 = rVect1;
// Align the input signals to the interrupt vector.
// VECT_0/VECT_1 are organized from right to left (LSB to MSB) as:
// [ 0] TX_TXN for channel 0 in VECT_0, channel 6 in VECT_1
// [ 1] TX_SG_BUF_RECVD for channel 0 in VECT_0, channel 6 in VECT_1
// [ 2] TX_TXN_DONE for channel 0 in VECT_0, channel 6 in VECT_1
// [ 3] RX_SG_BUF_RECVD for channel 0 in VECT_0, channel 6 in VECT_1
// [ 4] RX_TXN_DONE for channel 0 in VECT_0, channel 6 in VECT_1
// ...
// [25] TX_TXN for channel 5 in VECT_0, channel 11 in VECT_1
// [26] TX_SG_BUF_RECVD for channel 5 in VECT_0, channel 11 in VECT_1
// [27] TX_TXN_DONE for channel 5 in VECT_0, channel 11 in VECT_1
// [28] RX_SG_BUF_RECVD for channel 5 in VECT_0, channel 11 in VECT_1
// [29] RX_TXN_DONE for channel 5 in VECT_0, channel 11 in VECT_1
// Positions 30 - 31 in both VECT_0 and VECT_1 are zero.
genvar i;
generate
for (i = 0; i < C_NUM_CHNL; i = i + 1) begin: vectMap
if (i < 6) begin : vectMap0
assign wVect0[(5*i)+0] = TX_TXN[i];
assign wVect0[(5*i)+1] = TX_SG_BUF_RECVD[i];
assign wVect0[(5*i)+2] = TX_TXN_DONE[i];
assign wVect0[(5*i)+3] = RX_SG_BUF_RECVD[i];
assign wVect0[(5*i)+4] = RX_TXN_DONE[i];
end
else begin : vectMap1
assign wVect1[(5*(i-6))+0] = TX_TXN[i];
assign wVect1[(5*(i-6))+1] = TX_SG_BUF_RECVD[i];
assign wVect1[(5*(i-6))+2] = TX_TXN_DONE[i];
assign wVect1[(5*(i-6))+3] = RX_SG_BUF_RECVD[i];
assign wVect1[(5*(i-6))+4] = RX_TXN_DONE[i];
end
end
for (i = C_NUM_CHNL; i < 12; i = i + 1) begin: vectZero
if (i < 6) begin : vectZero0
assign wVect0[(5*i)+0] = 1'b0;
assign wVect0[(5*i)+1] = 1'b0;
assign wVect0[(5*i)+2] = 1'b0;
assign wVect0[(5*i)+3] = 1'b0;
assign wVect0[(5*i)+4] = 1'b0;
end
else begin : vectZero1
assign wVect1[(5*(i-6))+0] = 1'b0;
assign wVect1[(5*(i-6))+1] = 1'b0;
assign wVect1[(5*(i-6))+2] = 1'b0;
assign wVect1[(5*(i-6))+3] = 1'b0;
assign wVect1[(5*(i-6))+4] = 1'b0;
end
end
assign wVect0[30] = 1'b0;
assign wVect0[31] = 1'b0;
assign wVect1[30] = 1'b0;
assign wVect1[31] = 1'b0;
endgenerate
// Interrupt controller
interrupt_controller intrCtlr (
.CLK(CLK),
.RST(RST),
.INTR(wIntr),
.INTR_LEGACY_CLR(INTR_LEGACY_CLR),
.INTR_DONE(wIntrDone),
.CFG_INTERRUPT_ASSERT(),
.CONFIG_INTERRUPT_MSIENABLE(CONFIG_INTERRUPT_MSIENABLE),
.INTR_MSI_RDY(INTR_MSI_RDY),
.INTR_MSI_REQUEST(INTR_MSI_REQUEST)
);
// Update the interrupt vector when new signals come in (pulse in) and on reset.
always @(posedge CLK) begin
if (RST) begin
rVect0 <= #1 0;
rVect1 <= #1 0;
end
else begin
if (VECT_0_RST) begin
rVect0 <= #1 (wVect0 | (rVect0 & ~VECT_RST));
rVect1 <= #1 (wVect1 | rVect1);
end
else if (VECT_1_RST) begin
rVect0 <= #1 (wVect0 | rVect0);
rVect1 <= #1 (wVect1 | (rVect1 & ~VECT_RST));
end
else begin
rVect0 <= #1 (wVect0 | rVect0);
rVect1 <= #1 (wVect1 | rVect1);
end
end
end
// Fire the interrupt when we have a non-zero vector.
always @(posedge CLK) begin
if (RST) begin
rState <= #1 `S_INTR_IDLE;
end
else begin
case (rState)
`S_INTR_IDLE : rState <= #1 ((rVect0 | rVect1) == 0 ? `S_INTR_IDLE : `S_INTR_INTR);
`S_INTR_INTR : rState <= #1 (wIntrDone ? `S_INTR_CLR_0 : `S_INTR_INTR);
`S_INTR_CLR_0 : rState <= #1 (VECT_0_RST ? (C_NUM_CHNL > 6 ? `S_INTR_CLR_1 : `S_INTR_IDLE) : `S_INTR_CLR_0);
`S_INTR_CLR_1 : rState <= #1 (VECT_1_RST ? `S_INTR_IDLE : `S_INTR_CLR_1);
endcase
end
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.
//bug456
typedef logic signed [34:0] rc_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 [34:0] rc = crc[34:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic o; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.o (o),
// Inputs
.rc (rc),
.clk (clk));
// Aggregate outputs into a single result vector
wire [63:0] result = {63'h0, o};
// 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==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'h7211d24a17b25ec9
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test( output logic o,
input rc_t rc,
input logic clk);
localparam RATIO = 2;
rc_t rc_d[RATIO:1];
always_ff @(posedge clk) begin
integer k;
rc_d[1] <= rc;
for( k=2; k<RATIO+1; k++ ) begin
rc_d[k] <= rc_d[k-1];
end
end // always_ff @
assign o = rc_d[RATIO] < 0;
endmodule
// Local Variables:
// verilog-typedef-regexp: "_t$"
// End:
|
// (C) 2001-2015 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.
// $File: //acds/rel/15.1/ip/avalon_st/altera_avalon_st_handshake_clock_crosser/altera_avalon_st_handshake_clock_crosser.v $
// $Revision: #1 $
// $Date: 2015/08/09 $
// $Author: swbranch $
//------------------------------------------------------------------------------
// Clock crosser module with handshaking mechanism
//------------------------------------------------------------------------------
`timescale 1ns / 1ns
module altera_avalon_st_handshake_clock_crosser
#(
parameter DATA_WIDTH = 8,
BITS_PER_SYMBOL = 8,
USE_PACKETS = 0,
// ------------------------------
// Optional signal widths
// ------------------------------
USE_CHANNEL = 0,
CHANNEL_WIDTH = 1,
USE_ERROR = 0,
ERROR_WIDTH = 1,
VALID_SYNC_DEPTH = 2,
READY_SYNC_DEPTH = 2,
USE_OUTPUT_PIPELINE = 1,
// ------------------------------
// Derived parameters
// ------------------------------
SYMBOLS_PER_BEAT = DATA_WIDTH / BITS_PER_SYMBOL,
EMPTY_WIDTH = log2ceil(SYMBOLS_PER_BEAT)
)
(
input in_clk,
input in_reset,
input out_clk,
input out_reset,
output in_ready,
input in_valid,
input [DATA_WIDTH - 1 : 0] in_data,
input [CHANNEL_WIDTH - 1 : 0] in_channel,
input [ERROR_WIDTH - 1 : 0] in_error,
input in_startofpacket,
input in_endofpacket,
input [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] in_empty,
input out_ready,
output out_valid,
output [DATA_WIDTH - 1 : 0] out_data,
output [CHANNEL_WIDTH - 1 : 0] out_channel,
output [ERROR_WIDTH - 1 : 0] out_error,
output out_startofpacket,
output out_endofpacket,
output [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] out_empty
);
// ------------------------------
// Payload-specific widths
// ------------------------------
localparam PACKET_WIDTH = (USE_PACKETS) ? 2 + EMPTY_WIDTH : 0;
localparam PCHANNEL_W = (USE_CHANNEL) ? CHANNEL_WIDTH : 0;
localparam PERROR_W = (USE_ERROR) ? ERROR_WIDTH : 0;
localparam PAYLOAD_WIDTH = DATA_WIDTH +
PACKET_WIDTH +
PCHANNEL_W +
EMPTY_WIDTH +
PERROR_W;
wire [PAYLOAD_WIDTH - 1: 0] in_payload;
wire [PAYLOAD_WIDTH - 1: 0] out_payload;
// ------------------------------
// Assign in_data and other optional sink interface
// signals to in_payload.
// ------------------------------
assign in_payload[DATA_WIDTH - 1 : 0] = in_data;
generate
// optional packet inputs
if (PACKET_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH - 1 :
DATA_WIDTH
] = {in_startofpacket, in_endofpacket};
end
// optional channel input
if (USE_CHANNEL) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
] = in_channel;
end
// optional empty input
if (EMPTY_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
] = in_empty;
end
// optional error input
if (USE_ERROR) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
] = in_error;
end
endgenerate
// --------------------------------------------------
// Pipe the input payload to our inner module which handles the
// actual clock crossing
// --------------------------------------------------
altera_avalon_st_clock_crosser
#(
.SYMBOLS_PER_BEAT (1),
.BITS_PER_SYMBOL (PAYLOAD_WIDTH),
.FORWARD_SYNC_DEPTH (VALID_SYNC_DEPTH),
.BACKWARD_SYNC_DEPTH (READY_SYNC_DEPTH),
.USE_OUTPUT_PIPELINE (USE_OUTPUT_PIPELINE)
) clock_xer (
.in_clk (in_clk ),
.in_reset (in_reset ),
.in_ready (in_ready ),
.in_valid (in_valid ),
.in_data (in_payload ),
.out_clk (out_clk ),
.out_reset (out_reset ),
.out_ready (out_ready ),
.out_valid (out_valid ),
.out_data (out_payload )
);
// --------------------------------------------------
// Split out_payload into the output signals.
// --------------------------------------------------
assign out_data = out_payload[DATA_WIDTH - 1 : 0];
generate
// optional packet outputs
if (USE_PACKETS) begin
assign {out_startofpacket, out_endofpacket} =
out_payload[DATA_WIDTH + PACKET_WIDTH - 1 : DATA_WIDTH];
end else begin
// avoid a "has no driver" warning.
assign {out_startofpacket, out_endofpacket} = 2'b0;
end
// optional channel output
if (USE_CHANNEL) begin
assign out_channel = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_channel = 1'b0;
end
// optional empty output
if (EMPTY_WIDTH) begin
assign out_empty = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
];
end else begin
// avoid a "has no driver" warning.
assign out_empty = 1'b0;
end
// optional error output
if (USE_ERROR) begin
assign out_error = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_error = 1'b0;
end
endgenerate
// --------------------------------------------------
// Calculates the log2ceil of the input value.
// --------------------------------------------------
function integer log2ceil;
input integer val;
integer i;
begin
i = 1;
log2ceil = 0;
while (i < val) begin
log2ceil = log2ceil + 1;
i = i << 1;
end
end
endfunction
endmodule
|
// (C) 2001-2015 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.
// $File: //acds/rel/15.1/ip/avalon_st/altera_avalon_st_handshake_clock_crosser/altera_avalon_st_handshake_clock_crosser.v $
// $Revision: #1 $
// $Date: 2015/08/09 $
// $Author: swbranch $
//------------------------------------------------------------------------------
// Clock crosser module with handshaking mechanism
//------------------------------------------------------------------------------
`timescale 1ns / 1ns
module altera_avalon_st_handshake_clock_crosser
#(
parameter DATA_WIDTH = 8,
BITS_PER_SYMBOL = 8,
USE_PACKETS = 0,
// ------------------------------
// Optional signal widths
// ------------------------------
USE_CHANNEL = 0,
CHANNEL_WIDTH = 1,
USE_ERROR = 0,
ERROR_WIDTH = 1,
VALID_SYNC_DEPTH = 2,
READY_SYNC_DEPTH = 2,
USE_OUTPUT_PIPELINE = 1,
// ------------------------------
// Derived parameters
// ------------------------------
SYMBOLS_PER_BEAT = DATA_WIDTH / BITS_PER_SYMBOL,
EMPTY_WIDTH = log2ceil(SYMBOLS_PER_BEAT)
)
(
input in_clk,
input in_reset,
input out_clk,
input out_reset,
output in_ready,
input in_valid,
input [DATA_WIDTH - 1 : 0] in_data,
input [CHANNEL_WIDTH - 1 : 0] in_channel,
input [ERROR_WIDTH - 1 : 0] in_error,
input in_startofpacket,
input in_endofpacket,
input [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] in_empty,
input out_ready,
output out_valid,
output [DATA_WIDTH - 1 : 0] out_data,
output [CHANNEL_WIDTH - 1 : 0] out_channel,
output [ERROR_WIDTH - 1 : 0] out_error,
output out_startofpacket,
output out_endofpacket,
output [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] out_empty
);
// ------------------------------
// Payload-specific widths
// ------------------------------
localparam PACKET_WIDTH = (USE_PACKETS) ? 2 + EMPTY_WIDTH : 0;
localparam PCHANNEL_W = (USE_CHANNEL) ? CHANNEL_WIDTH : 0;
localparam PERROR_W = (USE_ERROR) ? ERROR_WIDTH : 0;
localparam PAYLOAD_WIDTH = DATA_WIDTH +
PACKET_WIDTH +
PCHANNEL_W +
EMPTY_WIDTH +
PERROR_W;
wire [PAYLOAD_WIDTH - 1: 0] in_payload;
wire [PAYLOAD_WIDTH - 1: 0] out_payload;
// ------------------------------
// Assign in_data and other optional sink interface
// signals to in_payload.
// ------------------------------
assign in_payload[DATA_WIDTH - 1 : 0] = in_data;
generate
// optional packet inputs
if (PACKET_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH - 1 :
DATA_WIDTH
] = {in_startofpacket, in_endofpacket};
end
// optional channel input
if (USE_CHANNEL) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
] = in_channel;
end
// optional empty input
if (EMPTY_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
] = in_empty;
end
// optional error input
if (USE_ERROR) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
] = in_error;
end
endgenerate
// --------------------------------------------------
// Pipe the input payload to our inner module which handles the
// actual clock crossing
// --------------------------------------------------
altera_avalon_st_clock_crosser
#(
.SYMBOLS_PER_BEAT (1),
.BITS_PER_SYMBOL (PAYLOAD_WIDTH),
.FORWARD_SYNC_DEPTH (VALID_SYNC_DEPTH),
.BACKWARD_SYNC_DEPTH (READY_SYNC_DEPTH),
.USE_OUTPUT_PIPELINE (USE_OUTPUT_PIPELINE)
) clock_xer (
.in_clk (in_clk ),
.in_reset (in_reset ),
.in_ready (in_ready ),
.in_valid (in_valid ),
.in_data (in_payload ),
.out_clk (out_clk ),
.out_reset (out_reset ),
.out_ready (out_ready ),
.out_valid (out_valid ),
.out_data (out_payload )
);
// --------------------------------------------------
// Split out_payload into the output signals.
// --------------------------------------------------
assign out_data = out_payload[DATA_WIDTH - 1 : 0];
generate
// optional packet outputs
if (USE_PACKETS) begin
assign {out_startofpacket, out_endofpacket} =
out_payload[DATA_WIDTH + PACKET_WIDTH - 1 : DATA_WIDTH];
end else begin
// avoid a "has no driver" warning.
assign {out_startofpacket, out_endofpacket} = 2'b0;
end
// optional channel output
if (USE_CHANNEL) begin
assign out_channel = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_channel = 1'b0;
end
// optional empty output
if (EMPTY_WIDTH) begin
assign out_empty = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
];
end else begin
// avoid a "has no driver" warning.
assign out_empty = 1'b0;
end
// optional error output
if (USE_ERROR) begin
assign out_error = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_error = 1'b0;
end
endgenerate
// --------------------------------------------------
// Calculates the log2ceil of the input value.
// --------------------------------------------------
function integer log2ceil;
input integer val;
integer i;
begin
i = 1;
log2ceil = 0;
while (i < val) begin
log2ceil = log2ceil + 1;
i = i << 1;
end
end
endfunction
endmodule
|
// (C) 2001-2015 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.
// $File: //acds/rel/15.1/ip/avalon_st/altera_avalon_st_handshake_clock_crosser/altera_avalon_st_handshake_clock_crosser.v $
// $Revision: #1 $
// $Date: 2015/08/09 $
// $Author: swbranch $
//------------------------------------------------------------------------------
// Clock crosser module with handshaking mechanism
//------------------------------------------------------------------------------
`timescale 1ns / 1ns
module altera_avalon_st_handshake_clock_crosser
#(
parameter DATA_WIDTH = 8,
BITS_PER_SYMBOL = 8,
USE_PACKETS = 0,
// ------------------------------
// Optional signal widths
// ------------------------------
USE_CHANNEL = 0,
CHANNEL_WIDTH = 1,
USE_ERROR = 0,
ERROR_WIDTH = 1,
VALID_SYNC_DEPTH = 2,
READY_SYNC_DEPTH = 2,
USE_OUTPUT_PIPELINE = 1,
// ------------------------------
// Derived parameters
// ------------------------------
SYMBOLS_PER_BEAT = DATA_WIDTH / BITS_PER_SYMBOL,
EMPTY_WIDTH = log2ceil(SYMBOLS_PER_BEAT)
)
(
input in_clk,
input in_reset,
input out_clk,
input out_reset,
output in_ready,
input in_valid,
input [DATA_WIDTH - 1 : 0] in_data,
input [CHANNEL_WIDTH - 1 : 0] in_channel,
input [ERROR_WIDTH - 1 : 0] in_error,
input in_startofpacket,
input in_endofpacket,
input [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] in_empty,
input out_ready,
output out_valid,
output [DATA_WIDTH - 1 : 0] out_data,
output [CHANNEL_WIDTH - 1 : 0] out_channel,
output [ERROR_WIDTH - 1 : 0] out_error,
output out_startofpacket,
output out_endofpacket,
output [(EMPTY_WIDTH ? (EMPTY_WIDTH - 1) : 0) : 0] out_empty
);
// ------------------------------
// Payload-specific widths
// ------------------------------
localparam PACKET_WIDTH = (USE_PACKETS) ? 2 + EMPTY_WIDTH : 0;
localparam PCHANNEL_W = (USE_CHANNEL) ? CHANNEL_WIDTH : 0;
localparam PERROR_W = (USE_ERROR) ? ERROR_WIDTH : 0;
localparam PAYLOAD_WIDTH = DATA_WIDTH +
PACKET_WIDTH +
PCHANNEL_W +
EMPTY_WIDTH +
PERROR_W;
wire [PAYLOAD_WIDTH - 1: 0] in_payload;
wire [PAYLOAD_WIDTH - 1: 0] out_payload;
// ------------------------------
// Assign in_data and other optional sink interface
// signals to in_payload.
// ------------------------------
assign in_payload[DATA_WIDTH - 1 : 0] = in_data;
generate
// optional packet inputs
if (PACKET_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH - 1 :
DATA_WIDTH
] = {in_startofpacket, in_endofpacket};
end
// optional channel input
if (USE_CHANNEL) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
] = in_channel;
end
// optional empty input
if (EMPTY_WIDTH) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
] = in_empty;
end
// optional error input
if (USE_ERROR) begin
assign in_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
] = in_error;
end
endgenerate
// --------------------------------------------------
// Pipe the input payload to our inner module which handles the
// actual clock crossing
// --------------------------------------------------
altera_avalon_st_clock_crosser
#(
.SYMBOLS_PER_BEAT (1),
.BITS_PER_SYMBOL (PAYLOAD_WIDTH),
.FORWARD_SYNC_DEPTH (VALID_SYNC_DEPTH),
.BACKWARD_SYNC_DEPTH (READY_SYNC_DEPTH),
.USE_OUTPUT_PIPELINE (USE_OUTPUT_PIPELINE)
) clock_xer (
.in_clk (in_clk ),
.in_reset (in_reset ),
.in_ready (in_ready ),
.in_valid (in_valid ),
.in_data (in_payload ),
.out_clk (out_clk ),
.out_reset (out_reset ),
.out_ready (out_ready ),
.out_valid (out_valid ),
.out_data (out_payload )
);
// --------------------------------------------------
// Split out_payload into the output signals.
// --------------------------------------------------
assign out_data = out_payload[DATA_WIDTH - 1 : 0];
generate
// optional packet outputs
if (USE_PACKETS) begin
assign {out_startofpacket, out_endofpacket} =
out_payload[DATA_WIDTH + PACKET_WIDTH - 1 : DATA_WIDTH];
end else begin
// avoid a "has no driver" warning.
assign {out_startofpacket, out_endofpacket} = 2'b0;
end
// optional channel output
if (USE_CHANNEL) begin
assign out_channel = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W - 1 :
DATA_WIDTH + PACKET_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_channel = 1'b0;
end
// optional empty output
if (EMPTY_WIDTH) begin
assign out_empty = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W
];
end else begin
// avoid a "has no driver" warning.
assign out_empty = 1'b0;
end
// optional error output
if (USE_ERROR) begin
assign out_error = out_payload[
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH + PERROR_W - 1 :
DATA_WIDTH + PACKET_WIDTH + PCHANNEL_W + EMPTY_WIDTH
];
end else begin
// avoid a "has no driver" warning.
assign out_error = 1'b0;
end
endgenerate
// --------------------------------------------------
// Calculates the log2ceil of the input value.
// --------------------------------------------------
function integer log2ceil;
input integer val;
integer i;
begin
i = 1;
log2ceil = 0;
while (i < val) begin
log2ceil = log2ceil + 1;
i = i << 1;
end
end
endfunction
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 17:39:29 10/01/2015
// Design Name:
// Module Name: Zero_InfMult_Unit
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Zero_InfMult_Unit
//SINGLE PRECISION PARAMETERS
# (parameter W = 32)
//DOUBLE PRECISION PARAMETERS
/* # (parameter W = 64) */
(
input wire clk,
input wire rst,
input wire load,
input wire [W-2:0] Data_A,
input wire [W-2:0] Data_B,
output wire zero_m_flag
);
//Wires/////////////////////
wire or_1, or_2;
wire [W-2:0] zero_comp;
wire zero_reg;
////////////////////////////
Comparator_Equal #(.S(W-1)) Data_A_Comp (
.Data_A(Data_A),
.Data_B(zero_comp),
.equal_sgn(or_1)
);
Comparator_Equal #(.S(W-1)) Data_B_Comp (
.Data_A(zero_comp),
.Data_B(Data_B),
.equal_sgn(or_2)
);
RegisterAdd #(.W(1)) Zero_Info_Mult ( //Data X input register
.clk(clk),
.rst(rst),
.load(load),
.D(zero_reg),
.Q(zero_m_flag)
);
assign zero_reg = or_1 || or_2;
generate
if (W == 32)
assign zero_comp = 31'd0;
else
assign zero_comp = 63'd0;
endgenerate
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 17:39:29 10/01/2015
// Design Name:
// Module Name: Zero_InfMult_Unit
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Zero_InfMult_Unit
//SINGLE PRECISION PARAMETERS
# (parameter W = 32)
//DOUBLE PRECISION PARAMETERS
/* # (parameter W = 64) */
(
input wire clk,
input wire rst,
input wire load,
input wire [W-2:0] Data_A,
input wire [W-2:0] Data_B,
output wire zero_m_flag
);
//Wires/////////////////////
wire or_1, or_2;
wire [W-2:0] zero_comp;
wire zero_reg;
////////////////////////////
Comparator_Equal #(.S(W-1)) Data_A_Comp (
.Data_A(Data_A),
.Data_B(zero_comp),
.equal_sgn(or_1)
);
Comparator_Equal #(.S(W-1)) Data_B_Comp (
.Data_A(zero_comp),
.Data_B(Data_B),
.equal_sgn(or_2)
);
RegisterAdd #(.W(1)) Zero_Info_Mult ( //Data X input register
.clk(clk),
.rst(rst),
.load(load),
.D(zero_reg),
.Q(zero_m_flag)
);
assign zero_reg = or_1 || or_2;
generate
if (W == 32)
assign zero_comp = 31'd0;
else
assign zero_comp = 63'd0;
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Test of gated clock detection
//
// The code as shown generates a result by a delayed assignment from PC. The
// creation of the result is from a clock gated from the clock that sets
// PC. Howevever since they are essentially the same clock, the result should
// be delayed by one cycle.
//
// Standard Verilator treats them as different clocks, so the result stays in
// step with the PC. An event drive simulator always allows the clock to win.
//
// The problem is caused by the extra loop added by Verilator to the
// evaluation of all internally generated clocks (effectively removed by
// marking the clock enable).
//
// This test is added to facilitate experiments with solutions.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Jeremy Bennett <[email protected]>.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg gated_clk_en = 1'b0 ;
reg [1:0] pc = 2'b0;
reg [1:0] res = 2'b0;
wire gated_clk = gated_clk_en & clk;
always @(posedge clk) begin
pc <= pc + 1;
gated_clk_en <= 1'b1;
end
always @(posedge gated_clk) begin
res <= pc;
end
always @(posedge clk) begin
if (pc == 2'b11) begin
// Correct behaviour is that res should be lagging pc in the count
// by one cycle
if (res == 2'b10) begin
$write("*-* All Finished *-*\n");
$finish;
end
else begin
$stop;
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Test of gated clock detection
//
// The code as shown generates a result by a delayed assignment from PC. The
// creation of the result is from a clock gated from the clock that sets
// PC. Howevever since they are essentially the same clock, the result should
// be delayed by one cycle.
//
// Standard Verilator treats them as different clocks, so the result stays in
// step with the PC. An event drive simulator always allows the clock to win.
//
// The problem is caused by the extra loop added by Verilator to the
// evaluation of all internally generated clocks (effectively removed by
// marking the clock enable).
//
// This test is added to facilitate experiments with solutions.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Jeremy Bennett <[email protected]>.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg gated_clk_en = 1'b0 ;
reg [1:0] pc = 2'b0;
reg [1:0] res = 2'b0;
wire gated_clk = gated_clk_en & clk;
always @(posedge clk) begin
pc <= pc + 1;
gated_clk_en <= 1'b1;
end
always @(posedge gated_clk) begin
res <= pc;
end
always @(posedge clk) begin
if (pc == 2'b11) begin
// Correct behaviour is that res should be lagging pc in the count
// by one cycle
if (res == 2'b10) begin
$write("*-* All Finished *-*\n");
$finish;
end
else begin
$stop;
end
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.
// overall latency of this IP
`define IP_PIPELINE_LATENCY_PLUS1 5
// to support the 0-latency stall free entry, add one more valid bit
`define ZERO_LATENCY_OFFSET 1
module acl_stall_free_sink
#(
parameter integer DATA_WIDTH = 32,
parameter integer PIPELINE_DEPTH = 32,
parameter integer SHARINGII = 1,
parameter integer SCHEDULEII = 1
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in,
output logic [DATA_WIDTH-1:0] data_out,
input logic input_accepted,
output logic valid_out,
input logic stall_in,
output logic stall_entry,
output logic [PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1+`ZERO_LATENCY_OFFSET:0] valids,
output logic [SHARINGII-1:0] IIphases,
input logic inc_pipelined_thread,
input logic dec_pipelined_thread
);
(* altera_attribute = "-name auto_shift_register_recognition OFF" *) reg [PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1:0] shift_reg;
reg [DATA_WIDTH-1:0] reg_data_in;
localparam FIFO_DEPTH_LOG2 = CLogB2(PIPELINE_DEPTH);
localparam FIFO_DEPTH = 1 << FIFO_DEPTH_LOG2;
reg [FIFO_DEPTH_LOG2:0] counter;
reg [SHARINGII-1:0] IIshreg;
wire output_accepted;
wire staging_reg_stall;
wire fifo_valid;
wire [DATA_WIDTH-1:0] fifo_data;
wire throttle_pipelined_iterations;
assign stall_entry = counter[FIFO_DEPTH_LOG2] | (!IIshreg[0]) | throttle_pipelined_iterations;
assign output_accepted = fifo_valid & ~staging_reg_stall;
assign valids = {shift_reg, input_accepted};
assign IIphases = IIshreg;
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
IIshreg <= {{(SHARINGII - 1){1'b0}},1'b1};
end
else
begin
IIshreg <= {IIshreg,IIshreg[SHARINGII-1]};
end
end
reg[$clog2(SCHEDULEII):0] IIschedcount;
reg[$clog2(SCHEDULEII):0] threads_count;
always @(posedge clock or negedge resetn)
begin
if (!resetn) begin
IIschedcount <= 0;
threads_count <= 0;
end else begin
if (IIshreg[0]) begin
// do not increase the counter if a thread is exiting
// increasing threads_count is already decreasing the window
// increasing IIschedcount ends up accepting the next thread too early
IIschedcount <= (input_accepted && dec_pipelined_thread) ? IIschedcount : (IIschedcount == (SCHEDULEII - 1) ? 0 : (IIschedcount + 1));
end
if (input_accepted) begin
threads_count <= threads_count + inc_pipelined_thread - dec_pipelined_thread;
end
end
end
// allow threads in a window of the II cycles
// this prevents the next iteration from entering too early
assign throttle_pipelined_iterations = (IIschedcount >= (threads_count > 0 ? threads_count : 1));
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
shift_reg <= {(PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1-1){1'b0}};
counter <= {(FIFO_DEPTH_LOG2+1){1'b0}};
reg_data_in <= 'x;
end
else
begin
shift_reg <= { shift_reg[PIPELINE_DEPTH-(`IP_PIPELINE_LATENCY_PLUS1+1):0], input_accepted };
counter <= counter + input_accepted - output_accepted;
reg_data_in <= data_in;
end
end
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(FIFO_DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(reg_data_in),
.data_out(fifo_data),
.valid_in(shift_reg[PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1]),
.valid_out(fifo_valid),
.stall_in(staging_reg_stall)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_data),
.i_valid(fifo_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
//ceil of the log base 2
function integer CLogB2;
input [31:0] Depth;
integer i;
begin
i = Depth;
for(CLogB2 = 0; i > 0; CLogB2 = CLogB2 + 1)
i = i >> 1;
end
endfunction
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.
// overall latency of this IP
`define IP_PIPELINE_LATENCY_PLUS1 5
// to support the 0-latency stall free entry, add one more valid bit
`define ZERO_LATENCY_OFFSET 1
module acl_stall_free_sink
#(
parameter integer DATA_WIDTH = 32,
parameter integer PIPELINE_DEPTH = 32,
parameter integer SHARINGII = 1,
parameter integer SCHEDULEII = 1
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in,
output logic [DATA_WIDTH-1:0] data_out,
input logic input_accepted,
output logic valid_out,
input logic stall_in,
output logic stall_entry,
output logic [PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1+`ZERO_LATENCY_OFFSET:0] valids,
output logic [SHARINGII-1:0] IIphases,
input logic inc_pipelined_thread,
input logic dec_pipelined_thread
);
(* altera_attribute = "-name auto_shift_register_recognition OFF" *) reg [PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1:0] shift_reg;
reg [DATA_WIDTH-1:0] reg_data_in;
localparam FIFO_DEPTH_LOG2 = CLogB2(PIPELINE_DEPTH);
localparam FIFO_DEPTH = 1 << FIFO_DEPTH_LOG2;
reg [FIFO_DEPTH_LOG2:0] counter;
reg [SHARINGII-1:0] IIshreg;
wire output_accepted;
wire staging_reg_stall;
wire fifo_valid;
wire [DATA_WIDTH-1:0] fifo_data;
wire throttle_pipelined_iterations;
assign stall_entry = counter[FIFO_DEPTH_LOG2] | (!IIshreg[0]) | throttle_pipelined_iterations;
assign output_accepted = fifo_valid & ~staging_reg_stall;
assign valids = {shift_reg, input_accepted};
assign IIphases = IIshreg;
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
IIshreg <= {{(SHARINGII - 1){1'b0}},1'b1};
end
else
begin
IIshreg <= {IIshreg,IIshreg[SHARINGII-1]};
end
end
reg[$clog2(SCHEDULEII):0] IIschedcount;
reg[$clog2(SCHEDULEII):0] threads_count;
always @(posedge clock or negedge resetn)
begin
if (!resetn) begin
IIschedcount <= 0;
threads_count <= 0;
end else begin
if (IIshreg[0]) begin
// do not increase the counter if a thread is exiting
// increasing threads_count is already decreasing the window
// increasing IIschedcount ends up accepting the next thread too early
IIschedcount <= (input_accepted && dec_pipelined_thread) ? IIschedcount : (IIschedcount == (SCHEDULEII - 1) ? 0 : (IIschedcount + 1));
end
if (input_accepted) begin
threads_count <= threads_count + inc_pipelined_thread - dec_pipelined_thread;
end
end
end
// allow threads in a window of the II cycles
// this prevents the next iteration from entering too early
assign throttle_pipelined_iterations = (IIschedcount >= (threads_count > 0 ? threads_count : 1));
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
shift_reg <= {(PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1-1){1'b0}};
counter <= {(FIFO_DEPTH_LOG2+1){1'b0}};
reg_data_in <= 'x;
end
else
begin
shift_reg <= { shift_reg[PIPELINE_DEPTH-(`IP_PIPELINE_LATENCY_PLUS1+1):0], input_accepted };
counter <= counter + input_accepted - output_accepted;
reg_data_in <= data_in;
end
end
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(FIFO_DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(reg_data_in),
.data_out(fifo_data),
.valid_in(shift_reg[PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1]),
.valid_out(fifo_valid),
.stall_in(staging_reg_stall)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_data),
.i_valid(fifo_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
//ceil of the log base 2
function integer CLogB2;
input [31:0] Depth;
integer i;
begin
i = Depth;
for(CLogB2 = 0; i > 0; CLogB2 = CLogB2 + 1)
i = i >> 1;
end
endfunction
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.
// overall latency of this IP
`define IP_PIPELINE_LATENCY_PLUS1 5
// to support the 0-latency stall free entry, add one more valid bit
`define ZERO_LATENCY_OFFSET 1
module acl_stall_free_sink
#(
parameter integer DATA_WIDTH = 32,
parameter integer PIPELINE_DEPTH = 32,
parameter integer SHARINGII = 1,
parameter integer SCHEDULEII = 1
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in,
output logic [DATA_WIDTH-1:0] data_out,
input logic input_accepted,
output logic valid_out,
input logic stall_in,
output logic stall_entry,
output logic [PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1+`ZERO_LATENCY_OFFSET:0] valids,
output logic [SHARINGII-1:0] IIphases,
input logic inc_pipelined_thread,
input logic dec_pipelined_thread
);
(* altera_attribute = "-name auto_shift_register_recognition OFF" *) reg [PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1:0] shift_reg;
reg [DATA_WIDTH-1:0] reg_data_in;
localparam FIFO_DEPTH_LOG2 = CLogB2(PIPELINE_DEPTH);
localparam FIFO_DEPTH = 1 << FIFO_DEPTH_LOG2;
reg [FIFO_DEPTH_LOG2:0] counter;
reg [SHARINGII-1:0] IIshreg;
wire output_accepted;
wire staging_reg_stall;
wire fifo_valid;
wire [DATA_WIDTH-1:0] fifo_data;
wire throttle_pipelined_iterations;
assign stall_entry = counter[FIFO_DEPTH_LOG2] | (!IIshreg[0]) | throttle_pipelined_iterations;
assign output_accepted = fifo_valid & ~staging_reg_stall;
assign valids = {shift_reg, input_accepted};
assign IIphases = IIshreg;
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
IIshreg <= {{(SHARINGII - 1){1'b0}},1'b1};
end
else
begin
IIshreg <= {IIshreg,IIshreg[SHARINGII-1]};
end
end
reg[$clog2(SCHEDULEII):0] IIschedcount;
reg[$clog2(SCHEDULEII):0] threads_count;
always @(posedge clock or negedge resetn)
begin
if (!resetn) begin
IIschedcount <= 0;
threads_count <= 0;
end else begin
if (IIshreg[0]) begin
// do not increase the counter if a thread is exiting
// increasing threads_count is already decreasing the window
// increasing IIschedcount ends up accepting the next thread too early
IIschedcount <= (input_accepted && dec_pipelined_thread) ? IIschedcount : (IIschedcount == (SCHEDULEII - 1) ? 0 : (IIschedcount + 1));
end
if (input_accepted) begin
threads_count <= threads_count + inc_pipelined_thread - dec_pipelined_thread;
end
end
end
// allow threads in a window of the II cycles
// this prevents the next iteration from entering too early
assign throttle_pipelined_iterations = (IIschedcount >= (threads_count > 0 ? threads_count : 1));
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
shift_reg <= {(PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1-1){1'b0}};
counter <= {(FIFO_DEPTH_LOG2+1){1'b0}};
reg_data_in <= 'x;
end
else
begin
shift_reg <= { shift_reg[PIPELINE_DEPTH-(`IP_PIPELINE_LATENCY_PLUS1+1):0], input_accepted };
counter <= counter + input_accepted - output_accepted;
reg_data_in <= data_in;
end
end
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(FIFO_DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(reg_data_in),
.data_out(fifo_data),
.valid_in(shift_reg[PIPELINE_DEPTH-`IP_PIPELINE_LATENCY_PLUS1]),
.valid_out(fifo_valid),
.stall_in(staging_reg_stall)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_data),
.i_valid(fifo_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
//ceil of the log base 2
function integer CLogB2;
input [31:0] Depth;
integer i;
begin
i = Depth;
for(CLogB2 = 0; i > 0; CLogB2 = CLogB2 + 1)
i = i >> 1;
end
endfunction
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2009 by Wilson Snyder.
package defs;
function automatic integer max;
input integer a;
input integer b;
max = (a > b) ? a : b;
endfunction
function automatic integer log2;
input integer value;
value = value >> 1;
for (log2 = 0; value > 0; log2 = log2 + 1)
value = value >> 1;
endfunction
function automatic integer ceil_log2;
input integer value;
value = value - 1;
for (ceil_log2 = 0; value > 0; ceil_log2 = ceil_log2 + 1)
value = value >> 1;
endfunction
endpackage
module sub();
import defs::*;
parameter RAND_NUM_MAX = "";
localparam DATA_RANGE = RAND_NUM_MAX + 1;
localparam DATA_WIDTH = ceil_log2(DATA_RANGE);
localparam WIDTH = max(4, ceil_log2(DATA_RANGE + 1));
endmodule
module t(/*AUTOARG*/
// Inputs
clk
);
import defs::*;
parameter WHICH = 0;
parameter MAX_COUNT = 10;
localparam MAX_EXPONENT = log2(MAX_COUNT);
localparam EXPONENT_WIDTH = ceil_log2(MAX_EXPONENT + 1);
input clk;
generate
if (WHICH == 1)
begin : which_true
sub sub_true();
defparam sub_true.RAND_NUM_MAX = MAX_EXPONENT;
end
else
begin : which_false
sub sub_false();
defparam sub_false.RAND_NUM_MAX = MAX_COUNT;
end
endgenerate
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 lf_edge_detect
`include "lf_edge_detect.v"
`define FIN "tb_tmp/data.filtered.gold"
`define FOUT_MIN "tb_tmp/data.min"
`define FOUT_MAX "tb_tmp/data.max"
`define FOUT_STATE "tb_tmp/data.state"
`define FOUT_TOGGLE "tb_tmp/data.toggle"
`define FOUT_HIGH "tb_tmp/data.high"
`define FOUT_HIGHZ "tb_tmp/data.highz"
`define FOUT_LOWZ "tb_tmp/data.lowz"
`define FOUT_LOW "tb_tmp/data.low"
module lf_edge_detect_tb;
integer fin, fout_state, fout_toggle;
integer fout_high, fout_highz, fout_lowz, fout_low, fout_min, fout_max;
integer r;
reg clk = 0;
reg [7:0] adc_d;
wire adc_clk;
wire data_rdy;
wire edge_state;
wire edge_toggle;
wire [7:0] high_threshold;
wire [7:0] highz_threshold;
wire [7:0] lowz_threshold;
wire [7:0] low_threshold;
wire [7:0] max;
wire [7:0] min;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout_min = $fopen(`FOUT_MIN, "w+");
fout_max = $fopen(`FOUT_MAX, "w+");
fout_state = $fopen(`FOUT_STATE, "w+");
fout_toggle = $fopen(`FOUT_TOGGLE, "w+");
fout_high = $fopen(`FOUT_HIGH, "w+");
fout_highz = $fopen(`FOUT_HIGHZ, "w+");
fout_lowz = $fopen(`FOUT_LOWZ, "w+");
fout_low = $fopen(`FOUT_LOW, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
// input
initial
begin
while (!$feof(fin)) begin
@(negedge clk) adc_d <= $fgetc(fin);
end
if ($feof(fin))
begin
# 3 $fclose(fin);
$fclose(fout_state);
$fclose(fout_toggle);
$fclose(fout_high);
$fclose(fout_highz);
$fclose(fout_lowz);
$fclose(fout_low);
$fclose(fout_min);
$fclose(fout_max);
$finish;
end
end
initial
begin
// $monitor("%d\t S: %b, E: %b", $time, edge_state, edge_toggle);
end
// output
always @(negedge clk)
if ($time > 2) begin
r = $fputc(min, fout_min);
r = $fputc(max, fout_max);
r = $fputc(edge_state, fout_state);
r = $fputc(edge_toggle, fout_toggle);
r = $fputc(high_threshold, fout_high);
r = $fputc(highz_threshold, fout_highz);
r = $fputc(lowz_threshold, fout_lowz);
r = $fputc(low_threshold, fout_low);
end
// module to test
lf_edge_detect detect(clk, adc_d, 8'd127,
max, min,
high_threshold, highz_threshold,
lowz_threshold, low_threshold,
edge_state, edge_toggle);
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 lf_edge_detect
`include "lf_edge_detect.v"
`define FIN "tb_tmp/data.filtered.gold"
`define FOUT_MIN "tb_tmp/data.min"
`define FOUT_MAX "tb_tmp/data.max"
`define FOUT_STATE "tb_tmp/data.state"
`define FOUT_TOGGLE "tb_tmp/data.toggle"
`define FOUT_HIGH "tb_tmp/data.high"
`define FOUT_HIGHZ "tb_tmp/data.highz"
`define FOUT_LOWZ "tb_tmp/data.lowz"
`define FOUT_LOW "tb_tmp/data.low"
module lf_edge_detect_tb;
integer fin, fout_state, fout_toggle;
integer fout_high, fout_highz, fout_lowz, fout_low, fout_min, fout_max;
integer r;
reg clk = 0;
reg [7:0] adc_d;
wire adc_clk;
wire data_rdy;
wire edge_state;
wire edge_toggle;
wire [7:0] high_threshold;
wire [7:0] highz_threshold;
wire [7:0] lowz_threshold;
wire [7:0] low_threshold;
wire [7:0] max;
wire [7:0] min;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout_min = $fopen(`FOUT_MIN, "w+");
fout_max = $fopen(`FOUT_MAX, "w+");
fout_state = $fopen(`FOUT_STATE, "w+");
fout_toggle = $fopen(`FOUT_TOGGLE, "w+");
fout_high = $fopen(`FOUT_HIGH, "w+");
fout_highz = $fopen(`FOUT_HIGHZ, "w+");
fout_lowz = $fopen(`FOUT_LOWZ, "w+");
fout_low = $fopen(`FOUT_LOW, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
// input
initial
begin
while (!$feof(fin)) begin
@(negedge clk) adc_d <= $fgetc(fin);
end
if ($feof(fin))
begin
# 3 $fclose(fin);
$fclose(fout_state);
$fclose(fout_toggle);
$fclose(fout_high);
$fclose(fout_highz);
$fclose(fout_lowz);
$fclose(fout_low);
$fclose(fout_min);
$fclose(fout_max);
$finish;
end
end
initial
begin
// $monitor("%d\t S: %b, E: %b", $time, edge_state, edge_toggle);
end
// output
always @(negedge clk)
if ($time > 2) begin
r = $fputc(min, fout_min);
r = $fputc(max, fout_max);
r = $fputc(edge_state, fout_state);
r = $fputc(edge_toggle, fout_toggle);
r = $fputc(high_threshold, fout_high);
r = $fputc(highz_threshold, fout_highz);
r = $fputc(lowz_threshold, fout_lowz);
r = $fputc(low_threshold, fout_low);
end
// module to test
lf_edge_detect detect(clk, adc_d, 8'd127,
max, min,
high_threshold, highz_threshold,
lowz_threshold, low_threshold,
edge_state, edge_toggle);
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 lf_edge_detect
`include "lf_edge_detect.v"
`define FIN "tb_tmp/data.filtered.gold"
`define FOUT_MIN "tb_tmp/data.min"
`define FOUT_MAX "tb_tmp/data.max"
`define FOUT_STATE "tb_tmp/data.state"
`define FOUT_TOGGLE "tb_tmp/data.toggle"
`define FOUT_HIGH "tb_tmp/data.high"
`define FOUT_HIGHZ "tb_tmp/data.highz"
`define FOUT_LOWZ "tb_tmp/data.lowz"
`define FOUT_LOW "tb_tmp/data.low"
module lf_edge_detect_tb;
integer fin, fout_state, fout_toggle;
integer fout_high, fout_highz, fout_lowz, fout_low, fout_min, fout_max;
integer r;
reg clk = 0;
reg [7:0] adc_d;
wire adc_clk;
wire data_rdy;
wire edge_state;
wire edge_toggle;
wire [7:0] high_threshold;
wire [7:0] highz_threshold;
wire [7:0] lowz_threshold;
wire [7:0] low_threshold;
wire [7:0] max;
wire [7:0] min;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout_min = $fopen(`FOUT_MIN, "w+");
fout_max = $fopen(`FOUT_MAX, "w+");
fout_state = $fopen(`FOUT_STATE, "w+");
fout_toggle = $fopen(`FOUT_TOGGLE, "w+");
fout_high = $fopen(`FOUT_HIGH, "w+");
fout_highz = $fopen(`FOUT_HIGHZ, "w+");
fout_lowz = $fopen(`FOUT_LOWZ, "w+");
fout_low = $fopen(`FOUT_LOW, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
// input
initial
begin
while (!$feof(fin)) begin
@(negedge clk) adc_d <= $fgetc(fin);
end
if ($feof(fin))
begin
# 3 $fclose(fin);
$fclose(fout_state);
$fclose(fout_toggle);
$fclose(fout_high);
$fclose(fout_highz);
$fclose(fout_lowz);
$fclose(fout_low);
$fclose(fout_min);
$fclose(fout_max);
$finish;
end
end
initial
begin
// $monitor("%d\t S: %b, E: %b", $time, edge_state, edge_toggle);
end
// output
always @(negedge clk)
if ($time > 2) begin
r = $fputc(min, fout_min);
r = $fputc(max, fout_max);
r = $fputc(edge_state, fout_state);
r = $fputc(edge_toggle, fout_toggle);
r = $fputc(high_threshold, fout_high);
r = $fputc(highz_threshold, fout_highz);
r = $fputc(lowz_threshold, fout_lowz);
r = $fputc(low_threshold, fout_low);
end
// module to test
lf_edge_detect detect(clk, adc_d, 8'd127,
max, min,
high_threshold, highz_threshold,
lowz_threshold, low_threshold,
edge_state, edge_toggle);
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;
integer cyc=0;
genvar g;
integer i;
reg [31:0] v;
reg [31:0] gen_pre_PLUSPLUS = 32'h0;
reg [31:0] gen_pre_MINUSMINUS = 32'h0;
reg [31:0] gen_post_PLUSPLUS = 32'h0;
reg [31:0] gen_post_MINUSMINUS = 32'h0;
reg [31:0] gen_PLUSEQ = 32'h0;
reg [31:0] gen_MINUSEQ = 32'h0;
reg [31:0] gen_TIMESEQ = 32'h0;
reg [31:0] gen_DIVEQ = 32'h0;
reg [31:0] gen_MODEQ = 32'h0;
reg [31:0] gen_ANDEQ = 32'h0;
reg [31:0] gen_OREQ = 32'h0;
reg [31:0] gen_XOREQ = 32'h0;
reg [31:0] gen_SLEFTEQ = 32'h0;
reg [31:0] gen_SRIGHTEQ = 32'h0;
reg [31:0] gen_SSRIGHTEQ = 32'h0;
generate
for (g=8; g<=16; ++g) always @(posedge clk) gen_pre_PLUSPLUS[g] = 1'b1;
for (g=16; g>=8; --g) always @(posedge clk) gen_pre_MINUSMINUS[g] = 1'b1;
for (g=8; g<=16; g++) always @(posedge clk) gen_post_PLUSPLUS[g] = 1'b1;
for (g=16; g>=8; g--) always @(posedge clk) gen_post_MINUSMINUS[g] = 1'b1;
for (g=8; g<=16; g+=2) always @(posedge clk) gen_PLUSEQ[g] = 1'b1;
for (g=16; g>=8; g-=2) always @(posedge clk) gen_MINUSEQ[g] = 1'b1;
`ifndef verilator //UNSUPPORTED
for (g=8; g<=16; g*=2) always @(posedge clk) gen_TIMESEQ[g] = 1'b1;
for (g=16; g>=8; g/=2) always @(posedge clk) gen_DIVEQ[g] = 1'b1;
for (g=15; g>8; g%=8) always @(posedge clk) gen_MODEQ[g] = 1'b1;
for (g=7; g>4; g&=4) always @(posedge clk) gen_ANDEQ[g] = 1'b1;
for (g=1; g<=1; g|=2) always @(posedge clk) gen_OREQ[g] = 1'b1;
for (g=7; g==7; g^=2) always @(posedge clk) gen_XOREQ[g] = 1'b1;
for (g=8; g<=16; g<<=2) always @(posedge clk) gen_SLEFTEQ[g] = 1'b1;
for (g=16; g>=8; g>>=2) always @(posedge clk) gen_SRIGHTEQ[g] = 1'b1;
for (g=16; g>=8; g>>>=2) always @(posedge clk) gen_SSRIGHTEQ[g] = 1'b1;
`endif
endgenerate
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc == 3) begin
`ifdef TEST_VERBOSE
$write("gen_pre_PLUSPLUS %b\n", gen_pre_PLUSPLUS);
$write("gen_pre_MINUSMINUS %b\n", gen_pre_MINUSMINUS);
$write("gen_post_PLUSPLUS %b\n", gen_post_PLUSPLUS);
$write("gen_post_MINUSMINUS %b\n", gen_post_MINUSMINUS);
$write("gen_PLUSEQ %b\n", gen_PLUSEQ);
$write("gen_MINUSEQ %b\n", gen_MINUSEQ);
$write("gen_TIMESEQ %b\n", gen_TIMESEQ);
$write("gen_DIVEQ %b\n", gen_DIVEQ);
$write("gen_MODEQ %b\n", gen_MODEQ);
$write("gen_ANDEQ %b\n", gen_ANDEQ);
$write("gen_OREQ %b\n", gen_OREQ);
$write("gen_XOREQ %b\n", gen_XOREQ);
$write("gen_SLEFTEQ %b\n", gen_SLEFTEQ);
$write("gen_SRIGHTEQ %b\n", gen_SRIGHTEQ);
$write("gen_SSRIGHTEQ %b\n", gen_SSRIGHTEQ);
`endif
if (gen_pre_PLUSPLUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_pre_MINUSMINUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_post_PLUSPLUS !== 32'b00000000000000011111111100000000) $stop;
if (gen_post_MINUSMINUS!== 32'b00000000000000011111111100000000) $stop;
if (gen_PLUSEQ !== 32'b00000000000000010101010100000000) $stop;
if (gen_MINUSEQ !== 32'b00000000000000010101010100000000) $stop;
`ifndef verilator //UNSUPPORTED
if (gen_TIMESEQ !== 32'b00000000000000010000000100000000) $stop;
if (gen_DIVEQ !== 32'b00000000000000010000000100000000) $stop;
if (gen_MODEQ !== 32'b00000000000000001000000000000000) $stop;
if (gen_ANDEQ !== 32'b00000000000000000000000010000000) $stop;
if (gen_OREQ !== 32'b00000000000000000000000000000010) $stop;
if (gen_XOREQ !== 32'b00000000000000000000000010000000) $stop;
if (gen_SLEFTEQ !== 32'b00000000000000000000000100000000) $stop;
if (gen_SRIGHTEQ !== 32'b00000000000000010000000000000000) $stop;
if (gen_SSRIGHTEQ !== 32'b00000000000000010000000000000000) $stop;
`endif
v=0; for (i=8; i<=16; ++i) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=16; i>=8; --i) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=8; i<=16; i++) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=16; i>=8; i--) v[i] = 1'b1; if (v !== 32'b00000000000000011111111100000000) $stop;
v=0; for (i=8; i<=16; i+=2) v[i] = 1'b1; if (v !== 32'b00000000000000010101010100000000) $stop;
v=0; for (i=16; i>=8; i-=2) v[i] = 1'b1; if (v !== 32'b00000000000000010101010100000000) $stop;
`ifndef verilator //UNSUPPORTED
v=0; for (i=8; i<=16; i*=2) v[i] = 1'b1; if (v !== 32'b00000000000000010000000100000000) $stop;
v=0; for (i=16; i>=8; i/=2) v[i] = 1'b1; if (v !== 32'b00000000000000010000000100000000) $stop;
v=0; for (i=15; i>8; i%=8) v[i] = 1'b1; if (v !== 32'b00000000000000001000000000000000) $stop;
v=0; for (i=7; i>4; i&=4) v[i] = 1'b1; if (v !== 32'b00000000000000000000000010000000) $stop;
v=0; for (i=1; i<=1; i|=2) v[i] = 1'b1; if (v !== 32'b00000000000000000000000000000010) $stop;
v=0; for (i=7; i==7; i^=2) v[i] = 1'b1; if (v !== 32'b00000000000000000000000010000000) $stop;
v=0; for (i=8; i<=16; i<<=2) v[i] =1'b1; if (v !== 32'b00000000000000000000000100000000) $stop;
v=0; for (i=16; i>=8; i>>=2) v[i] =1'b1; if (v !== 32'b00000000000000010000000000000000) $stop;
v=0; for (i=16; i>=8; i>>>=2) v[i]=1'b1; if (v !== 32'b00000000000000010000000000000000) $stop;
`endif
$write("*-* All Finished *-*\n");
$finish;
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.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
module RCB_FRL_CRC_gen ( D, NewCRC);
input [47:0] D;
output [7:0] NewCRC;
assign NewCRC[0] = D[46] ^ D[42] ^ D[41] ^ D[37] ^ D[36] ^ D[35] ^ D[34] ^
D[33] ^ D[31] ^ D[30] ^ D[29] ^ D[27] ^ D[26] ^ D[24] ^
D[20] ^ D[18] ^ D[17] ^ D[16] ^ D[15] ^ D[14] ^ D[13] ^
D[8] ^ D[7] ^ D[6] ^ D[3] ^ D[1] ^ D[0];
assign NewCRC[1] = D[47] ^ D[43] ^ D[42] ^ D[38] ^ D[37] ^ D[36] ^ D[35] ^
D[34] ^ D[32] ^ D[31] ^ D[30] ^ D[28] ^ D[27] ^ D[25] ^
D[21] ^ D[19] ^ D[18] ^ D[17] ^ D[16] ^ D[15] ^ D[14] ^
D[9] ^ D[8] ^ D[7] ^ D[4] ^ D[2] ^ D[1];
assign NewCRC[2] = D[46] ^ D[44] ^ D[43] ^ D[42] ^ D[41] ^ D[39] ^ D[38] ^
D[34] ^ D[32] ^ D[30] ^ D[28] ^ D[27] ^ D[24] ^ D[22] ^
D[19] ^ D[14] ^ D[13] ^ D[10] ^ D[9] ^ D[7] ^ D[6] ^
D[5] ^ D[2] ^ D[1] ^ D[0];
assign NewCRC[3] = D[47] ^ D[45] ^ D[44] ^ D[43] ^ D[42] ^ D[40] ^ D[39] ^
D[35] ^ D[33] ^ D[31] ^ D[29] ^ D[28] ^ D[25] ^ D[23] ^
D[20] ^ D[15] ^ D[14] ^ D[11] ^ D[10] ^ D[8] ^ D[7] ^
D[6] ^ D[3] ^ D[2] ^ D[1];
assign NewCRC[4] = D[45] ^ D[44] ^ D[43] ^ D[42] ^ D[40] ^ D[37] ^ D[35] ^
D[33] ^ D[32] ^ D[31] ^ D[27] ^ D[21] ^ D[20] ^ D[18] ^
D[17] ^ D[14] ^ D[13] ^ D[12] ^ D[11] ^ D[9] ^ D[6] ^
D[4] ^ D[2] ^ D[1] ^ D[0];
assign NewCRC[5] = D[46] ^ D[45] ^ D[44] ^ D[43] ^ D[41] ^ D[38] ^ D[36] ^
D[34] ^ D[33] ^ D[32] ^ D[28] ^ D[22] ^ D[21] ^ D[19] ^
D[18] ^ D[15] ^ D[14] ^ D[13] ^ D[12] ^ D[10] ^ D[7] ^
D[5] ^ D[3] ^ D[2] ^ D[1];
assign NewCRC[6] = D[47] ^ D[45] ^ D[44] ^ D[41] ^ D[39] ^ D[36] ^ D[31] ^
D[30] ^ D[27] ^ D[26] ^ D[24] ^ D[23] ^ D[22] ^ D[19] ^
D[18] ^ D[17] ^ D[11] ^ D[7] ^ D[4] ^ D[2] ^ D[1] ^
D[0];
assign NewCRC[7] = D[45] ^ D[41] ^ D[40] ^ D[36] ^ D[35] ^ D[34] ^ D[33] ^
D[32] ^ D[30] ^ D[29] ^ D[28] ^ D[26] ^ D[25] ^ D[23] ^
D[19] ^ D[17] ^ D[16] ^ D[15] ^ D[14] ^ D[13] ^ D[12] ^
D[7] ^ D[6] ^ D[5] ^ D[2] ^ D[0];
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013.
// bug648
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 [7:0] datai = crc[7:0];
wire enable = crc[8];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [7:0] datao; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.datao (datao[7:0]),
// Inputs
.clk (clk),
.datai (datai[7:0]),
.enable (enable));
// Aggregate outputs into a single result vector
wire [63:0] result = {56'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'h9d550d82d38926fa
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`define FAIL 1
module Nested
(
input logic clk,
input logic x,
output logic y
);
logic t;
always_comb t = x ^ 1'b1;
always_ff @(posedge clk) begin
if (clk)
y <= t;
end
endmodule
module Test
(
input logic clk,
input logic [7:0] datai,
input logic enable,
output logic [7:0] datao
);
// verilator lint_off BLKANDNBLK
logic [7:0] datat;
// verilator lint_on BLKANDNBLK
for (genvar i = 0; i < 8; i++) begin
if (i%4 != 3) begin
`ifndef FAIL
logic t;
always_comb begin
t = datai[i] ^ 1'b1;
end
always_ff @(posedge clk) begin
if (clk)
datat[i] <= t;
end
`else
Nested nested_i
(
.clk(clk),
.x(datai[i]),
.y(datat[i]) //<== via Vcellout wire
);
`endif
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i];
1'b0: datao[i] = '0;
default: datao[i] = 'x;
endcase
end
end
else begin
always_ff @(posedge clk) begin
if (clk)
datat[i] <= 0; //<== assign delayed
end
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i] ^ 1'b1;
1'b0: datao[i] = '1;
default: datao[i] = 'x;
endcase
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013.
// bug648
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 [7:0] datai = crc[7:0];
wire enable = crc[8];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [7:0] datao; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.datao (datao[7:0]),
// Inputs
.clk (clk),
.datai (datai[7:0]),
.enable (enable));
// Aggregate outputs into a single result vector
wire [63:0] result = {56'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'h9d550d82d38926fa
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`define FAIL 1
module Nested
(
input logic clk,
input logic x,
output logic y
);
logic t;
always_comb t = x ^ 1'b1;
always_ff @(posedge clk) begin
if (clk)
y <= t;
end
endmodule
module Test
(
input logic clk,
input logic [7:0] datai,
input logic enable,
output logic [7:0] datao
);
// verilator lint_off BLKANDNBLK
logic [7:0] datat;
// verilator lint_on BLKANDNBLK
for (genvar i = 0; i < 8; i++) begin
if (i%4 != 3) begin
`ifndef FAIL
logic t;
always_comb begin
t = datai[i] ^ 1'b1;
end
always_ff @(posedge clk) begin
if (clk)
datat[i] <= t;
end
`else
Nested nested_i
(
.clk(clk),
.x(datai[i]),
.y(datat[i]) //<== via Vcellout wire
);
`endif
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i];
1'b0: datao[i] = '0;
default: datao[i] = 'x;
endcase
end
end
else begin
always_ff @(posedge clk) begin
if (clk)
datat[i] <= 0; //<== assign delayed
end
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i] ^ 1'b1;
1'b0: datao[i] = '1;
default: datao[i] = 'x;
endcase
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013.
// bug648
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 [7:0] datai = crc[7:0];
wire enable = crc[8];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [7:0] datao; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.datao (datao[7:0]),
// Inputs
.clk (clk),
.datai (datai[7:0]),
.enable (enable));
// Aggregate outputs into a single result vector
wire [63:0] result = {56'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'h9d550d82d38926fa
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`define FAIL 1
module Nested
(
input logic clk,
input logic x,
output logic y
);
logic t;
always_comb t = x ^ 1'b1;
always_ff @(posedge clk) begin
if (clk)
y <= t;
end
endmodule
module Test
(
input logic clk,
input logic [7:0] datai,
input logic enable,
output logic [7:0] datao
);
// verilator lint_off BLKANDNBLK
logic [7:0] datat;
// verilator lint_on BLKANDNBLK
for (genvar i = 0; i < 8; i++) begin
if (i%4 != 3) begin
`ifndef FAIL
logic t;
always_comb begin
t = datai[i] ^ 1'b1;
end
always_ff @(posedge clk) begin
if (clk)
datat[i] <= t;
end
`else
Nested nested_i
(
.clk(clk),
.x(datai[i]),
.y(datat[i]) //<== via Vcellout wire
);
`endif
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i];
1'b0: datao[i] = '0;
default: datao[i] = 'x;
endcase
end
end
else begin
always_ff @(posedge clk) begin
if (clk)
datat[i] <= 0; //<== assign delayed
end
always_comb begin
casez (enable)
1'b1: datao[i] = datat[i] ^ 1'b1;
1'b0: datao[i] = '1;
default: datao[i] = 'x;
endcase
end
end
end
endmodule
|
//wishbone_arbiter.v
/*
Distributed under the MIT licesnse.
Copyright (c) 2011 Dave McCoy ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
`timescale 1 ns/1 ps
module arbiter_2_masters (
//control signals
input clk,
input rst,
//wishbone master ports
input i_m0_we,
input i_m0_cyc,
input i_m0_stb,
input [3:0] i_m0_sel,
output o_m0_ack,
input [31:0] i_m0_dat,
output [31:0] o_m0_dat,
input [31:0] i_m0_adr,
output o_m0_int,
input i_m1_we,
input i_m1_cyc,
input i_m1_stb,
input [3:0] i_m1_sel,
output o_m1_ack,
input [31:0] i_m1_dat,
output [31:0] o_m1_dat,
input [31:0] i_m1_adr,
output o_m1_int,
//wishbone slave signals
output o_s_we,
output o_s_stb,
output o_s_cyc,
output [3:0] o_s_sel,
output [31:0] o_s_adr,
output [31:0] o_s_dat,
input [31:0] i_s_dat,
input i_s_ack,
input i_s_int
);
localparam MASTER_COUNT = 2;
//registers/wires
//this should be parameterized
reg [7:0] master_select;
reg [7:0] priority_select;
wire o_master_we [MASTER_COUNT - 1:0];
wire o_master_stb [MASTER_COUNT - 1:0];
wire o_master_cyc [MASTER_COUNT - 1:0];
wire [3:0] o_master_sel [MASTER_COUNT - 1:0];
wire [31:0] o_master_adr [MASTER_COUNT - 1:0];
wire [31:0] o_master_dat [MASTER_COUNT - 1:0];
//master select block
localparam MASTER_NO_SEL = 8'hFF;
localparam MASTER_0 = 0;
localparam MASTER_1 = 1;
always @ (posedge clk) begin
if (rst) begin
master_select <= MASTER_NO_SEL;
end
else begin
case (master_select)
MASTER_0: begin
if (!i_m0_cyc && !i_s_ack) begin
master_select <= MASTER_NO_SEL;
end
end
MASTER_1: begin
if (!i_m1_cyc && !i_s_ack) begin
master_select <= MASTER_NO_SEL;
end
end
default: begin
//nothing selected
if (i_m0_cyc) begin
master_select <= MASTER_0;
end
else if (i_m1_cyc) begin
master_select <= MASTER_1;
end
end
endcase
if ((master_select != MASTER_NO_SEL) && (priority_select < master_select) && (!o_s_stb && !i_s_ack))begin
master_select <= MASTER_NO_SEL;
end
end
end
//priority select
always @ (posedge clk) begin
if (rst) begin
priority_select <= MASTER_NO_SEL;
end
else begin
//find the highest priority
if (i_m0_cyc) begin
priority_select <= MASTER_0;
end
else if (i_m1_cyc) begin
priority_select <= MASTER_1;
end
else begin
priority_select <= MASTER_NO_SEL;
end
end
end
//slave assignments
assign o_s_we = (master_select != MASTER_NO_SEL) ? o_master_we[master_select] : 0;
assign o_s_stb = (master_select != MASTER_NO_SEL) ? o_master_stb[master_select] : 0;
assign o_s_cyc = (master_select != MASTER_NO_SEL) ? o_master_cyc[master_select] : 0;
assign o_s_sel = (master_select != MASTER_NO_SEL) ? o_master_sel[master_select] : 0;
assign o_s_adr = (master_select != MASTER_NO_SEL) ? o_master_adr[master_select] : 0;
assign o_s_dat = (master_select != MASTER_NO_SEL) ? o_master_dat[master_select] : 0;
//write select block
assign o_master_we[MASTER_0] = i_m0_we;
assign o_master_we[MASTER_1] = i_m1_we;
//strobe select block
assign o_master_stb[MASTER_0] = i_m0_stb;
assign o_master_stb[MASTER_1] = i_m1_stb;
//cycle select block
assign o_master_cyc[MASTER_0] = i_m0_cyc;
assign o_master_cyc[MASTER_1] = i_m1_cyc;
//select select block
assign o_master_sel[MASTER_0] = i_m0_sel;
assign o_master_sel[MASTER_1] = i_m1_sel;
//address seelct block
assign o_master_adr[MASTER_0] = i_m0_adr;
assign o_master_adr[MASTER_1] = i_m1_adr;
//data select block
assign o_master_dat[MASTER_0] = i_m0_dat;
assign o_master_dat[MASTER_1] = i_m1_dat;
//assign block
assign o_m0_ack = (master_select == MASTER_0) ? i_s_ack : 0;
assign o_m0_dat = i_s_dat;
assign o_m0_int = (master_select == MASTER_0) ? i_s_int : 0;
assign o_m1_ack = (master_select == MASTER_1) ? i_s_ack : 0;
assign o_m1_dat = i_s_dat;
assign o_m1_int = (master_select == MASTER_1) ? i_s_int : 0;
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
//////////////////////////////////////////////////////////////////////////////////
// Company: Microsoft Research Asia
// Engineer: Jiansong Zhang
//
// Create Date: 12:17:59 11/12/2009
// Design Name:
// Module Name: performance_counter
// Project Name: Sora
// Target Devices: LX50T1136-1
// Tool versions: ISE 10.02
// Description: We measure the durations in this module (1) from TX_des request sent to tx_engine to new des
// received (2) from transfer start to transfer done.
// A counter (125MHz or 250MHz depends on DMA clock) is implemeted.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module performance_counter(
input clk,
input rst,
input transferstart_one,
input rd_dma_done_one,
input new_des_one,
output reg [23:0] round_trip_latency,
output reg [23:0] transfer_duration
);
reg [39:0] counter; /// free run 40bits counter, more than two hours per cycle on 125MHz clock
reg [23:0] snapshot_transferstart; /// record the lower 24 bit of counter when transferstart, more than 100ms per cycle on 125MHz clock
/// counter
always@(posedge clk) begin
if(rst)
counter <= 40'h00_0000_0000;
else
counter <= counter + 40'h00_0000_0001;
end
/// snapshot_transferstart
always@(posedge clk) begin
if(rst)
snapshot_transferstart <= 24'h00_0000;
else if (transferstart_one)
snapshot_transferstart <= counter[23:0];
else
snapshot_transferstart <= snapshot_transferstart;
end
/// round_trip_latency
always@(posedge clk) begin
if (rst)
round_trip_latency <= 24'h00_0000;
else if (new_des_one)
round_trip_latency <= counter[23:0] + (~snapshot_transferstart) + 24'h00_0001;
else
round_trip_latency <= round_trip_latency;
end
/// transfer_duration
always@(posedge clk) begin
if (rst)
transfer_duration <= 24'h00_0000;
else if (rd_dma_done_one)
transfer_duration <= counter[23:0] + (~snapshot_transferstart) + 24'h00_0001;
else
transfer_duration <= transfer_duration;
end
endmodule
|
(** * Hoare2: Hoare Logic, Part II *)
Require Export Hoare.
(* ####################################################### *)
(** * Decorated Programs *)
(** The beauty of Hoare Logic is that it is _compositional_ --
the structure of proofs exactly follows the structure of programs.
This suggests that we can record the essential ideas of a proof
informally (leaving out some low-level calculational details) by
decorating programs with appropriate assertions around each
statement. Such a _decorated program_ carries with it
an (informal) proof of its own correctness. *)
(** For example, here is a complete decorated program: *)
(**
{{ True }} ->>
{{ m = m }}
X ::= m;;
{{ X = m }} ->>
{{ X = m /\ p = p }}
Z ::= p;
{{ X = m /\ Z = p }} ->>
{{ Z - X = p - m }}
WHILE X <> 0 DO
{{ Z - X = p - m /\ X <> 0 }} ->>
{{ (Z - 1) - (X - 1) = p - m }}
Z ::= Z - 1;;
{{ Z - (X - 1) = p - m }}
X ::= X - 1
{{ Z - X = p - m }}
END;
{{ Z - X = p - m /\ ~ (X <> 0) }} ->>
{{ Z = p - m }}
*)
(** Concretely, a decorated program consists of the program text
interleaved with assertions. To check that a decorated program
represents a valid proof, we check that each individual command is
_locally consistent_ with its accompanying assertions in the
following sense: *)
(**
- [SKIP] is locally consistent if its precondition and
postcondition are the same:
{{ P }}
SKIP
{{ P }}
*)
(**
- The sequential composition of [c1] and [c2] is locally
consistent (with respect to assertions [P] and [R]) if [c1] is
locally consistent (with respect to [P] and [Q]) and [c2] is
locally consistent (with respect to [Q] and [R]):
{{ P }}
c1;;
{{ Q }}
c2
{{ R }}
*)
(**
- An assignment is locally consistent if its precondition is
the appropriate substitution of its postcondition:
{{ P [X |-> a] }}
X ::= a
{{ P }}
*)
(**
- A conditional is locally consistent (with respect to assertions
[P] and [Q]) if the assertions at the top of its "then" and
"else" branches are exactly [P /\ b] and [P /\ ~b] and if its "then"
branch is locally consistent (with respect to [P /\ b] and [Q])
and its "else" branch is locally consistent (with respect to
[P /\ ~b] and [Q]):
{{ P }}
IFB b THEN
{{ P /\ b }}
c1
{{ Q }}
ELSE
{{ P /\ ~b }}
c2
{{ Q }}
FI
{{ Q }}
*)
(**
- A while loop with precondition [P] is locally consistent if its
postcondition is [P /\ ~b] and if the pre- and postconditions of
its body are exactly [P /\ b] and [P]:
{{ P }}
WHILE b DO
{{ P /\ b }}
c1
{{ P }}
END
{{ P /\ ~b }}
*)
(**
- A pair of assertions separated by [->>] is locally consistent if
the first implies the second (in all states):
{{ P }} ->>
{{ P' }}
This corresponds to the application of [hoare_consequence] and
is the only place in a decorated program where checking if
decorations are correct is not fully mechanical and syntactic,
but involves logical and/or arithmetic reasoning.
*)
(** We have seen above how _verifying_ the correctness of a
given proof involves checking that every single command is locally
consistent with the accompanying assertions. If we are instead
interested in _finding_ a proof for a given specification we need
to discover the right assertions. This can be done in an almost
automatic way, with the exception of finding loop invariants,
which is the subject of in the next section. In the reminder of
this section we explain in detail how to construct decorations for
several simple programs that don't involve non-trivial loop
invariants. *)
(* ####################################################### *)
(** ** Example: Swapping Using Addition and Subtraction *)
(** Here is a program that swaps the values of two variables using
addition and subtraction (instead of by assigning to a temporary
variable).
X ::= X + Y;;
Y ::= X - Y;;
X ::= X - Y
We can prove using decorations that this program is correct --
i.e., it always swaps the values of variables [X] and [Y]. *)
(**
(1) {{ X = m /\ Y = n }} ->>
(2) {{ (X + Y) - ((X + Y) - Y) = n /\ (X + Y) - Y = m }}
X ::= X + Y;;
(3) {{ X - (X - Y) = n /\ X - Y = m }}
Y ::= X - Y;;
(4) {{ X - Y = n /\ Y = m }}
X ::= X - Y
(5) {{ X = n /\ Y = m }}
The decorations were constructed as follows:
- We begin with the undecorated program (the unnumbered lines).
- We then add the specification -- i.e., the outer
precondition (1) and postcondition (5). In the precondition we
use auxiliary variables (parameters) [m] and [n] to remember
the initial values of variables [X] and respectively [Y], so
that we can refer to them in the postcondition (5).
- We work backwards mechanically starting from (5) all the way
to (2). At each step, we obtain the precondition of the
assignment from its postcondition by substituting the assigned
variable with the right-hand-side of the assignment. For
instance, we obtain (4) by substituting [X] with [X - Y]
in (5), and (3) by substituting [Y] with [X - Y] in (4).
- Finally, we verify that (1) logically implies (2) -- i.e.,
that the step from (1) to (2) is a valid use of the law of
consequence. For this we substitute [X] by [m] and [Y] by [n]
and calculate as follows:
(m + n) - ((m + n) - n) = n /\ (m + n) - n = m
(m + n) - m = n /\ m = m
n = n /\ m = m
(Note that, since we are working with natural numbers, not
fixed-size machine integers, we don't need to worry about the
possibility of arithmetic overflow anywhere in this argument.)
*)
(* ####################################################### *)
(** ** Example: Simple Conditionals *)
(** Here is a simple decorated program using conditionals:
(1) {{True}}
IFB X <= Y THEN
(2) {{True /\ X <= Y}} ->>
(3) {{(Y - X) + X = Y \/ (Y - X) + Y = X}}
Z ::= Y - X
(4) {{Z + X = Y \/ Z + Y = X}}
ELSE
(5) {{True /\ ~(X <= Y) }} ->>
(6) {{(X - Y) + X = Y \/ (X - Y) + Y = X}}
Z ::= X - Y
(7) {{Z + X = Y \/ Z + Y = X}}
FI
(8) {{Z + X = Y \/ Z + Y = X}}
These decorations were constructed as follows:
- We start with the outer precondition (1) and postcondition (8).
- We follow the format dictated by the [hoare_if] rule and copy the
postcondition (8) to (4) and (7). We conjoin the precondition (1)
with the guard of the conditional to obtain (2). We conjoin (1)
with the negated guard of the conditional to obtain (5).
- In order to use the assignment rule and obtain (3), we substitute
[Z] by [Y - X] in (4). To obtain (6) we substitute [Z] by [X - Y]
in (7).
- Finally, we verify that (2) implies (3) and (5) implies (6). Both
of these implications crucially depend on the ordering of [X] and
[Y] obtained from the guard. For instance, knowing that [X <= Y]
ensures that subtracting [X] from [Y] and then adding back [X]
produces [Y], as required by the first disjunct of (3). Similarly,
knowing that [~(X <= Y)] ensures that subtracting [Y] from [X] and
then adding back [Y] produces [X], as needed by the second
disjunct of (6). Note that [n - m + m = n] does _not_ hold for
arbitrary natural numbers [n] and [m] (for example, [3 - 5 + 5 =
5]). *)
(** **** Exercise: 2 stars (if_minus_plus_reloaded) *)
(** Fill in valid decorations for the following program:
{{ True }}
IFB X <= Y THEN
{{ }} ->>
{{ }}
Z ::= Y - X
{{ }}
ELSE
{{ }} ->>
{{ }}
Y ::= X + Z
{{ }}
FI
{{ Y = X + Z }}
*)
(** [] *)
(* ####################################################### *)
(** ** Example: Reduce to Zero (Trivial Loop) *)
(** Here is a [WHILE] loop that is so simple it needs no
invariant (i.e., the invariant [True] will do the job).
(1) {{ True }}
WHILE X <> 0 DO
(2) {{ True /\ X <> 0 }} ->>
(3) {{ True }}
X ::= X - 1
(4) {{ True }}
END
(5) {{ True /\ X = 0 }} ->>
(6) {{ X = 0 }}
The decorations can be constructed as follows:
- Start with the outer precondition (1) and postcondition (6).
- Following the format dictated by the [hoare_while] rule, we copy
(1) to (4). We conjoin (1) with the guard to obtain (2) and with
the negation of the guard to obtain (5). Note that, because the
outer postcondition (6) does not syntactically match (5), we need a
trivial use of the consequence rule from (5) to (6).
- Assertion (3) is the same as (4), because [X] does not appear in
[4], so the substitution in the assignment rule is trivial.
- Finally, the implication between (2) and (3) is also trivial.
*)
(** From this informal proof, it is easy to read off a formal proof
using the Coq versions of the Hoare rules. Note that we do _not_
unfold the definition of [hoare_triple] anywhere in this proof --
the idea is to use the Hoare rules as a "self-contained" logic for
reasoning about programs. *)
Definition reduce_to_zero' : com :=
WHILE BNot (BEq (AId X) (ANum 0)) DO
X ::= AMinus (AId X) (ANum 1)
END.
Theorem reduce_to_zero_correct' :
{{fun st => True}}
reduce_to_zero'
{{fun st => st X = 0}}.
Proof.
unfold reduce_to_zero'.
(* First we need to transform the postcondition so
that hoare_while will apply. *)
eapply hoare_consequence_post.
apply hoare_while.
Case "Loop body preserves invariant".
(* Need to massage precondition before [hoare_asgn] applies *)
eapply hoare_consequence_pre. apply hoare_asgn.
(* Proving trivial implication (2) ->> (3) *)
intros st [HT Hbp]. unfold assn_sub. apply I.
Case "Invariant and negated guard imply postcondition".
intros st [Inv GuardFalse].
unfold bassn in GuardFalse. simpl in GuardFalse.
(* SearchAbout helps to find the right lemmas *)
SearchAbout [not true].
rewrite not_true_iff_false in GuardFalse.
SearchAbout [negb false].
rewrite negb_false_iff in GuardFalse.
SearchAbout [beq_nat true].
apply beq_nat_true in GuardFalse.
apply GuardFalse. Qed.
(* ####################################################### *)
(** ** Example: Division *)
(** The following Imp program calculates the integer division and
remainder of two numbers [m] and [n] that are arbitrary constants
in the program.
X ::= m;;
Y ::= 0;;
WHILE n <= X DO
X ::= X - n;;
Y ::= Y + 1
END;
In other words, if we replace [m] and [n] by concrete numbers and
execute the program, it will terminate with the variable [X] set
to the remainder when [m] is divided by [n] and [Y] set to the
quotient. *)
(** In order to give a specification to this program we need to
remember that dividing [m] by [n] produces a reminder [X] and a
quotient [Y] so that [n * Y + X = m /\ X < n].
It turns out that we get lucky with this program and don't have to
think very hard about the loop invariant: the invariant is the
just first conjunct [n * Y + X = m], so we use that to decorate
the program.
(1) {{ True }} ->>
(2) {{ n * 0 + m = m }}
X ::= m;;
(3) {{ n * 0 + X = m }}
Y ::= 0;;
(4) {{ n * Y + X = m }}
WHILE n <= X DO
(5) {{ n * Y + X = m /\ n <= X }} ->>
(6) {{ n * (Y + 1) + (X - n) = m }}
X ::= X - n;;
(7) {{ n * (Y + 1) + X = m }}
Y ::= Y + 1
(8) {{ n * Y + X = m }}
END
(9) {{ n * Y + X = m /\ X < n }}
Assertions (4), (5), (8), and (9) are derived mechanically from
the invariant and the loop's guard. Assertions (8), (7), and (6)
are derived using the assignment rule going backwards from (8) to
(6). Assertions (4), (3), and (2) are again backwards applications
of the assignment rule.
Now that we've decorated the program it only remains to check that
the two uses of the consequence rule are correct -- i.e., that (1)
implies (2) and that (5) implies (6). This is indeed the case, so
we have a valid decorated program.
*)
(* ####################################################### *)
(** * Finding Loop Invariants *)
(** Once the outermost precondition and postcondition are chosen, the
only creative part in verifying programs with Hoare Logic is
finding the right loop invariants. The reason this is difficult
is the same as the reason that doing inductive mathematical proofs
requires creativity: strengthening the loop invariant (or the
induction hypothesis) means that you have a stronger assumption to
work with when trying to establish the postcondition of the loop
body (complete the induction step of the proof), but it also means
that the loop body postcondition itself is harder to prove!
This section is dedicated to teaching you how to approach the
challenge of finding loop invariants using a series of examples
and exercises. *)
(** ** Example: Slow Subtraction *)
(** The following program subtracts the value of [X] from the value of
[Y] by repeatedly decrementing both [X] and [Y]. We want to verify its
correctness with respect to the following specification:
{{ X = m /\ Y = n }}
WHILE X <> 0 DO
Y ::= Y - 1;;
X ::= X - 1
END
{{ Y = n - m }}
To verify this program we need to find an invariant [I] for the
loop. As a first step we can leave [I] as an unknown and build a
_skeleton_ for the proof by applying backward the rules for local
consistency. This process leads to the following skeleton:
(1) {{ X = m /\ Y = n }} ->> (a)
(2) {{ I }}
WHILE X <> 0 DO
(3) {{ I /\ X <> 0 }} ->> (c)
(4) {{ I[X |-> X-1][Y |-> Y-1] }}
Y ::= Y - 1;;
(5) {{ I[X |-> X-1] }}
X ::= X - 1
(6) {{ I }}
END
(7) {{ I /\ ~(X <> 0) }} ->> (b)
(8) {{ Y = n - m }}
By examining this skeleton, we can see that any valid [I] will
have to respect three conditions:
- (a) it must be weak enough to be implied by the loop's
precondition, i.e. (1) must imply (2);
- (b) it must be strong enough to imply the loop's postcondition,
i.e. (7) must imply (8);
- (c) it must be preserved by one iteration of the loop, i.e. (3)
must imply (4). *)
(** These conditions are actually independent of the particular
program and specification we are considering. Indeed, every loop
invariant has to satisfy them. One way to find an invariant that
simultaneously satisfies these three conditions is by using an
iterative process: start with a "candidate" invariant (e.g. a
guess or a heuristic choice) and check the three conditions above;
if any of the checks fails, try to use the information that we get
from the failure to produce another (hopefully better) candidate
invariant, and repeat the process.
For instance, in the reduce-to-zero example above, we saw that,
for a very simple loop, choosing [True] as an invariant did the
job. So let's try it again here! I.e., let's instantiate [I] with
[True] in the skeleton above see what we get...
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ True }}
WHILE X <> 0 DO
(3) {{ True /\ X <> 0 }} ->> (c - OK)
(4) {{ True }}
Y ::= Y - 1;;
(5) {{ True }}
X ::= X - 1
(6) {{ True }}
END
(7) {{ True /\ X = 0 }} ->> (b - WRONG!)
(8) {{ Y = n - m }}
While conditions (a) and (c) are trivially satisfied,
condition (b) is wrong, i.e. it is not the case that (7) [True /\
X = 0] implies (8) [Y = n - m]. In fact, the two assertions are
completely unrelated and it is easy to find a counterexample (say,
[Y = X = m = 0] and [n = 1]).
If we want (b) to hold, we need to strengthen the invariant so
that it implies the postcondition (8). One very simple way to do
this is to let the invariant _be_ the postcondition. So let's
return to our skeleton, instantiate [I] with [Y = n - m], and
check conditions (a) to (c) again.
(1) {{ X = m /\ Y = n }} ->> (a - WRONG!)
(2) {{ Y = n - m }}
WHILE X <> 0 DO
(3) {{ Y = n - m /\ X <> 0 }} ->> (c - WRONG!)
(4) {{ Y - 1 = n - m }}
Y ::= Y - 1;;
(5) {{ Y = n - m }}
X ::= X - 1
(6) {{ Y = n - m }}
END
(7) {{ Y = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
This time, condition (b) holds trivially, but (a) and (c) are
broken. Condition (a) requires that (1) [X = m /\ Y = n]
implies (2) [Y = n - m]. If we substitute [Y] by [n] we have to
show that [n = n - m] for arbitrary [m] and [n], which does not
hold (for instance, when [m = n = 1]). Condition (c) requires that
[n - m - 1 = n - m], which fails, for instance, for [n = 1] and [m =
0]. So, although [Y = n - m] holds at the end of the loop, it does
not hold from the start, and it doesn't hold on each iteration;
it is not a correct invariant.
This failure is not very surprising: the variable [Y] changes
during the loop, while [m] and [n] are constant, so the assertion
we chose didn't have much chance of being an invariant!
To do better, we need to generalize (8) to some statement that is
equivalent to (8) when [X] is [0], since this will be the case
when the loop terminates, and that "fills the gap" in some
appropriate way when [X] is nonzero. Looking at how the loop
works, we can observe that [X] and [Y] are decremented together
until [X] reaches [0]. So, if [X = 2] and [Y = 5] initially,
after one iteration of the loop we obtain [X = 1] and [Y = 4];
after two iterations [X = 0] and [Y = 3]; and then the loop stops.
Notice that the difference between [Y] and [X] stays constant
between iterations; initially, [Y = n] and [X = m], so this
difference is always [n - m]. So let's try instantiating [I] in
the skeleton above with [Y - X = n - m].
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ Y - X = n - m }}
WHILE X <> 0 DO
(3) {{ Y - X = n - m /\ X <> 0 }} ->> (c - OK)
(4) {{ (Y - 1) - (X - 1) = n - m }}
Y ::= Y - 1;;
(5) {{ Y - (X - 1) = n - m }}
X ::= X - 1
(6) {{ Y - X = n - m }}
END
(7) {{ Y - X = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
Success! Conditions (a), (b) and (c) all hold now. (To
verify (c), we need to check that, under the assumption that [X <>
0], we have [Y - X = (Y - 1) - (X - 1)]; this holds for all
natural numbers [X] and [Y].) *)
(* ####################################################### *)
(** ** Exercise: Slow Assignment *)
(** **** Exercise: 2 stars (slow_assignment) *)
(** A roundabout way of assigning a number currently stored in [X] to
the variable [Y] is to start [Y] at [0], then decrement [X] until
it hits [0], incrementing [Y] at each step. Here is a program that
implements this idea:
{{ X = m }}
Y ::= 0;;
WHILE X <> 0 DO
X ::= X - 1;;
Y ::= Y + 1
END
{{ Y = m }}
Write an informal decorated program showing that this is correct. *)
(* FILL IN HERE *)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Slow Addition *)
(** **** Exercise: 3 stars, optional (add_slowly_decoration) *)
(** The following program adds the variable X into the variable Z
by repeatedly decrementing X and incrementing Z.
WHILE X <> 0 DO
Z ::= Z + 1;;
X ::= X - 1
END
Following the pattern of the [subtract_slowly] example above, pick
a precondition and postcondition that give an appropriate
specification of [add_slowly]; then (informally) decorate the
program accordingly. *)
(* FILL IN HERE *)
(** [] *)
(* ####################################################### *)
(** ** Example: Parity *)
(** Here is a cute little program for computing the parity of the
value initially stored in [X] (due to Daniel Cristofani).
{{ X = m }}
WHILE 2 <= X DO
X ::= X - 2
END
{{ X = parity m }}
The mathematical [parity] function used in the specification is
defined in Coq as follows: *)
Fixpoint parity x :=
match x with
| 0 => 0
| 1 => 1
| S (S x') => parity x'
end.
(** The postcondition does not hold at the beginning of the loop,
since [m = parity m] does not hold for an arbitrary [m], so we
cannot use that as an invariant. To find an invariant that works,
let's think a bit about what this loop does. On each iteration it
decrements [X] by [2], which preserves the parity of [X]. So the
parity of [X] does not change, i.e. it is invariant. The initial
value of [X] is [m], so the parity of [X] is always equal to the
parity of [m]. Using [parity X = parity m] as an invariant we
obtain the following decorated program:
{{ X = m }} ->> (a - OK)
{{ parity X = parity m }}
WHILE 2 <= X DO
{{ parity X = parity m /\ 2 <= X }} ->> (c - OK)
{{ parity (X-2) = parity m }}
X ::= X - 2
{{ parity X = parity m }}
END
{{ parity X = parity m /\ X < 2 }} ->> (b - OK)
{{ X = parity m }}
With this invariant, conditions (a), (b), and (c) are all
satisfied. For verifying (b), we observe that, when [X < 2], we
have [parity X = X] (we can easily see this in the definition of
[parity]). For verifying (c), we observe that, when [2 <= X], we
have [parity X = parity (X-2)]. *)
(** **** Exercise: 3 stars, optional (parity_formal) *)
(** Translate this proof to Coq. Refer to the reduce-to-zero example
for ideas. You may find the following two lemmas useful: *)
Lemma parity_ge_2 : forall x,
2 <= x ->
parity (x - 2) = parity x.
Proof.
induction x; intro. reflexivity.
destruct x. inversion H. inversion H1.
simpl. rewrite <- minus_n_O. reflexivity.
Qed.
Lemma parity_lt_2 : forall x,
~ 2 <= x ->
parity (x) = x.
Proof.
intros. induction x. reflexivity. destruct x. reflexivity.
apply ex_falso_quodlibet. apply H. omega.
Qed.
Theorem parity_correct : forall m,
{{ fun st => st X = m }}
WHILE BLe (ANum 2) (AId X) DO
X ::= AMinus (AId X) (ANum 2)
END
{{ fun st => st X = parity m }}.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ####################################################### *)
(** ** Example: Finding Square Roots *)
(** The following program computes the square root of [X]
by naive iteration:
{{ X=m }}
Z ::= 0;;
WHILE (Z+1)*(Z+1) <= X DO
Z ::= Z+1
END
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
*)
(** As above, we can try to use the postcondition as a candidate
invariant, obtaining the following decorated program:
(1) {{ X=m }} ->> (a - second conjunct of (2) WRONG!)
(2) {{ 0*0 <= m /\ m<1*1 }}
Z ::= 0;;
(3) {{ Z*Z <= m /\ m<(Z+1)*(Z+1) }}
WHILE (Z+1)*(Z+1) <= X DO
(4) {{ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - WRONG!)
(5) {{ (Z+1)*(Z+1)<=m /\ m<(Z+2)*(Z+2) }}
Z ::= Z+1
(6) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
END
(7) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
(8) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This didn't work very well: both conditions (a) and (c) failed.
Looking at condition (c), we see that the second conjunct of (4)
is almost the same as the first conjunct of (5), except that (4)
mentions [X] while (5) mentions [m]. But note that [X] is never
assigned in this program, so we should have [X=m], but we didn't
propagate this information from (1) into the loop invariant.
Also, looking at the second conjunct of (8), it seems quite
hopeless as an invariant -- and we don't even need it, since we
can obtain it from the negation of the guard (third conjunct
in (7)), again under the assumption that [X=m].
So we now try [X=m /\ Z*Z <= m] as the loop invariant:
{{ X=m }} ->> (a - OK)
{{ X=m /\ 0*0 <= m }}
Z ::= 0;
{{ X=m /\ Z*Z <= m }}
WHILE (Z+1)*(Z+1) <= X DO
{{ X=m /\ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - OK)
{{ X=m /\ (Z+1)*(Z+1)<=m }}
Z ::= Z+1
{{ X=m /\ Z*Z<=m }}
END
{{ X=m /\ Z*Z<=m /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This works, since conditions (a), (b), and (c) are now all
trivially satisfied.
Very often, if a variable is used in a loop in a read-only
fashion (i.e., it is referred to by the program or by the
specification and it is not changed by the loop) it is necessary
to add the fact that it doesn't change to the loop invariant. *)
(* ####################################################### *)
(** ** Example: Squaring *)
(** Here is a program that squares [X] by repeated addition:
{{ X = m }}
Y ::= 0;;
Z ::= 0;;
WHILE Y <> X DO
Z ::= Z + X;;
Y ::= Y + 1
END
{{ Z = m*m }}
*)
(** The first thing to note is that the loop reads [X] but doesn't
change its value. As we saw in the previous example, in such cases
it is a good idea to add [X = m] to the invariant. The other thing
we often use in the invariant is the postcondition, so let's add
that too, leading to the invariant candidate [Z = m * m /\ X = m].
{{ X = m }} ->> (a - WRONG)
{{ 0 = m*m /\ X = m }}
Y ::= 0;;
{{ 0 = m*m /\ X = m }}
Z ::= 0;;
{{ Z = m*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - WRONG)
{{ Z+X = m*m /\ X = m }}
Z ::= Z + X;;
{{ Z = m*m /\ X = m }}
Y ::= Y + 1
{{ Z = m*m /\ X = m }}
END
{{ Z = m*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
Conditions (a) and (c) fail because of the [Z = m*m] part. While
[Z] starts at [0] and works itself up to [m*m], we can't expect
[Z] to be [m*m] from the start. If we look at how [Z] progesses
in the loop, after the 1st iteration [Z = m], after the 2nd
iteration [Z = 2*m], and at the end [Z = m*m]. Since the variable
[Y] tracks how many times we go through the loop, we derive the
new invariant candidate [Z = Y*m /\ X = m].
{{ X = m }} ->> (a - OK)
{{ 0 = 0*m /\ X = m }}
Y ::= 0;;
{{ 0 = Y*m /\ X = m }}
Z ::= 0;;
{{ Z = Y*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - OK)
{{ Z+X = (Y+1)*m /\ X = m }}
Z ::= Z + X;
{{ Z = (Y+1)*m /\ X = m }}
Y ::= Y + 1
{{ Z = Y*m /\ X = m }}
END
{{ Z = Y*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
This new invariant makes the proof go through: all three
conditions are easy to check.
It is worth comparing the postcondition [Z = m*m] and the [Z =
Y*m] conjunct of the invariant. It is often the case that one has
to replace auxiliary variabes (parameters) with variables -- or
with expressions involving both variables and parameters (like
[m - Y]) -- when going from postconditions to invariants. *)
(* ####################################################### *)
(** ** Exercise: Factorial *)
(** **** Exercise: 3 stars (factorial) *)
(** Recall that [n!] denotes the factorial of [n] (i.e. [n! =
1*2*...*n]). Here is an Imp program that calculates the factorial
of the number initially stored in the variable [X] and puts it in
the variable [Y]:
{{ X = m }}
Y ::= 1 ;;
WHILE X <> 0
DO
Y ::= Y * X ;;
X ::= X - 1
END
{{ Y = m! }}
Fill in the blanks in following decorated program:
{{ X = m }} ->>
{{ }}
Y ::= 1;;
{{ }}
WHILE X <> 0
DO {{ }} ->>
{{ }}
Y ::= Y * X;;
{{ }}
X ::= X - 1
{{ }}
END
{{ }} ->>
{{ Y = m! }}
*)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Min *)
(** **** Exercise: 3 stars (Min_Hoare) *)
(** Fill in valid decorations for the following program.
For the => steps in your annotations, you may rely (silently) on the
following facts about min
Lemma lemma1 : forall x y,
(x=0 \/ y=0) -> min x y = 0.
Lemma lemma2 : forall x y,
min (x-1) (y-1) = (min x y) - 1.
plus, as usual, standard high-school algebra.
{{ True }} ->>
{{ }}
X ::= a;;
{{ }}
Y ::= b;;
{{ }}
Z ::= 0;;
{{ }}
WHILE (X <> 0 /\ Y <> 0) DO
{{ }} ->>
{{ }}
X := X - 1;;
{{ }}
Y := Y - 1;;
{{ }}
Z := Z + 1
{{ }}
END
{{ }} ->>
{{ Z = min a b }}
*)
(** [] *)
(** **** Exercise: 3 stars (two_loops) *)
(** Here is a very inefficient way of adding 3 numbers:
X ::= 0;;
Y ::= 0;;
Z ::= c;;
WHILE X <> a DO
X ::= X + 1;;
Z ::= Z + 1
END;;
WHILE Y <> b DO
Y ::= Y + 1;;
Z ::= Z + 1
END
Show that it does what it should by filling in the blanks in the
following decorated program.
{{ True }} ->>
{{ }}
X ::= 0;;
{{ }}
Y ::= 0;;
{{ }}
Z ::= c;;
{{ }}
WHILE X <> a DO
{{ }} ->>
{{ }}
X ::= X + 1;;
{{ }}
Z ::= Z + 1
{{ }}
END;;
{{ }} ->>
{{ }}
WHILE Y <> b DO
{{ }} ->>
{{ }}
Y ::= Y + 1;;
{{ }}
Z ::= Z + 1
{{ }}
END
{{ }} ->>
{{ Z = a + b + c }}
*)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Power Series *)
(** **** Exercise: 4 stars, optional (dpow2_down) *)
(** Here is a program that computes the series:
[1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1]
X ::= 0;;
Y ::= 1;;
Z ::= 1;;
WHILE X <> m DO
Z ::= 2 * Z;;
Y ::= Y + Z;;
X ::= X + 1
END
Write a decorated program for this. *)
(* FILL IN HERE *)
(* ####################################################### *)
(** * Weakest Preconditions (Advanced) *)
(** Some Hoare triples are more interesting than others.
For example,
{{ False }} X ::= Y + 1 {{ X <= 5 }}
is _not_ very interesting: although it is perfectly valid, it
tells us nothing useful. Since the precondition isn't satisfied
by any state, it doesn't describe any situations where we can use
the command [X ::= Y + 1] to achieve the postcondition [X <= 5].
By contrast,
{{ Y <= 4 /\ Z = 0 }} X ::= Y + 1 {{ X <= 5 }}
is useful: it tells us that, if we can somehow create a situation
in which we know that [Y <= 4 /\ Z = 0], then running this command
will produce a state satisfying the postcondition. However, this
triple is still not as useful as it could be, because the [Z = 0]
clause in the precondition actually has nothing to do with the
postcondition [X <= 5]. The _most_ useful triple (for a given
command and postcondition) is this one:
{{ Y <= 4 }} X ::= Y + 1 {{ X <= 5 }}
In other words, [Y <= 4] is the _weakest_ valid precondition of
the command [X ::= Y + 1] for the postcondition [X <= 5]. *)
(** In general, we say that "[P] is the weakest precondition of
command [c] for postcondition [Q]" if [{{P}} c {{Q}}] and if,
whenever [P'] is an assertion such that [{{P'}} c {{Q}}], we have
[P' st] implies [P st] for all states [st]. *)
Definition is_wp P c Q :=
{{P}} c {{Q}} /\
forall P', {{P'}} c {{Q}} -> (P' ->> P).
(** That is, [P] is the weakest precondition of [c] for [Q]
if (a) [P] _is_ a precondition for [Q] and [c], and (b) [P] is the
_weakest_ (easiest to satisfy) assertion that guarantees [Q] after
executing [c]. *)
(** **** Exercise: 1 star, optional (wp) *)
(** What are the weakest preconditions of the following commands
for the following postconditions?
1) {{ ? }} SKIP {{ X = 5 }}
2) {{ ? }} X ::= Y + Z {{ X = 5 }}
3) {{ ? }} X ::= Y {{ X = Y }}
4) {{ ? }}
IFB X == 0 THEN Y ::= Z + 1 ELSE Y ::= W + 2 FI
{{ Y = 5 }}
5) {{ ? }}
X ::= 5
{{ X = 0 }}
6) {{ ? }}
WHILE True DO X ::= 0 END
{{ X = 0 }}
*)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 3 stars, advanced, optional (is_wp_formal) *)
(** Prove formally using the definition of [hoare_triple] that [Y <= 4]
is indeed the weakest precondition of [X ::= Y + 1] with respect to
postcondition [X <= 5]. *)
Theorem is_wp_example :
is_wp (fun st => st Y <= 4)
(X ::= APlus (AId Y) (ANum 1)) (fun st => st X <= 5).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, advanced (hoare_asgn_weakest) *)
(** Show that the precondition in the rule [hoare_asgn] is in fact the
weakest precondition. *)
Theorem hoare_asgn_weakest : forall Q X a,
is_wp (Q [X |-> a]) (X ::= a) Q.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, advanced, optional (hoare_havoc_weakest) *)
(** Show that your [havoc_pre] rule from the [himp_hoare] exercise
in the [Hoare] chapter returns the weakest precondition. *)
Module Himp2.
Import Himp.
Lemma hoare_havoc_weakest : forall (P Q : Assertion) (X : id),
{{ P }} HAVOC X {{ Q }} ->
P ->> havoc_pre X Q.
Proof.
(* FILL IN HERE *) Admitted.
End Himp2.
(** [] *)
(* ####################################################### *)
(** * Formal Decorated Programs (Advanced) *)
(** The informal conventions for decorated programs amount to a way of
displaying Hoare triples in which commands are annotated with
enough embedded assertions that checking the validity of the
triple is reduced to simple logical and algebraic calculations
showing that some assertions imply others. In this section, we
show that this informal presentation style can actually be made
completely formal and indeed that checking the validity of
decorated programs can mostly be automated. *)
(** ** Syntax *)
(** The first thing we need to do is to formalize a variant of the
syntax of commands with embedded assertions. We call the new
commands _decorated commands_, or [dcom]s. *)
Inductive dcom : Type :=
| DCSkip : Assertion -> dcom
| DCSeq : dcom -> dcom -> dcom
| DCAsgn : id -> aexp -> Assertion -> dcom
| DCIf : bexp -> Assertion -> dcom -> Assertion -> dcom
-> Assertion-> dcom
| DCWhile : bexp -> Assertion -> dcom -> Assertion -> dcom
| DCPre : Assertion -> dcom -> dcom
| DCPost : dcom -> Assertion -> dcom.
Tactic Notation "dcom_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "Skip" | Case_aux c "Seq" | Case_aux c "Asgn"
| Case_aux c "If" | Case_aux c "While"
| Case_aux c "Pre" | Case_aux c "Post" ].
Notation "'SKIP' {{ P }}"
:= (DCSkip P)
(at level 10) : dcom_scope.
Notation "l '::=' a {{ P }}"
:= (DCAsgn l a P)
(at level 60, a at next level) : dcom_scope.
Notation "'WHILE' b 'DO' {{ Pbody }} d 'END' {{ Ppost }}"
:= (DCWhile b Pbody d Ppost)
(at level 80, right associativity) : dcom_scope.
Notation "'IFB' b 'THEN' {{ P }} d 'ELSE' {{ P' }} d' 'FI' {{ Q }}"
:= (DCIf b P d P' d' Q)
(at level 80, right associativity) : dcom_scope.
Notation "'->>' {{ P }} d"
:= (DCPre P d)
(at level 90, right associativity) : dcom_scope.
Notation "{{ P }} d"
:= (DCPre P d)
(at level 90) : dcom_scope.
Notation "d '->>' {{ P }}"
:= (DCPost d P)
(at level 80, right associativity) : dcom_scope.
Notation " d ;; d' "
:= (DCSeq d d')
(at level 80, right associativity) : dcom_scope.
Delimit Scope dcom_scope with dcom.
(** To avoid clashing with the existing [Notation] definitions
for ordinary [com]mands, we introduce these notations in a special
scope called [dcom_scope], and we wrap examples with the
declaration [% dcom] to signal that we want the notations to be
interpreted in this scope.
Careful readers will note that we've defined two notations for the
[DCPre] constructor, one with and one without a [->>]. The
"without" version is intended to be used to supply the initial
precondition at the very top of the program. *)
Example dec_while : dcom := (
{{ fun st => True }}
WHILE (BNot (BEq (AId X) (ANum 0)))
DO
{{ fun st => True /\ st X <> 0}}
X ::= (AMinus (AId X) (ANum 1))
{{ fun _ => True }}
END
{{ fun st => True /\ st X = 0}} ->>
{{ fun st => st X = 0 }}
) % dcom.
(** It is easy to go from a [dcom] to a [com] by erasing all
annotations. *)
Fixpoint extract (d:dcom) : com :=
match d with
| DCSkip _ => SKIP
| DCSeq d1 d2 => (extract d1 ;; extract d2)
| DCAsgn X a _ => X ::= a
| DCIf b _ d1 _ d2 _ => IFB b THEN extract d1 ELSE extract d2 FI
| DCWhile b _ d _ => WHILE b DO extract d END
| DCPre _ d => extract d
| DCPost d _ => extract d
end.
(** The choice of exactly where to put assertions in the definition of
[dcom] is a bit subtle. The simplest thing to do would be to
annotate every [dcom] with a precondition and postcondition. But
this would result in very verbose programs with a lot of repeated
annotations: for example, a program like [SKIP;SKIP] would have to
be annotated as
{{P}} ({{P}} SKIP {{P}}) ;; ({{P}} SKIP {{P}}) {{P}},
with pre- and post-conditions on each [SKIP], plus identical pre-
and post-conditions on the semicolon!
Instead, the rule we've followed is this:
- The _post_-condition expected by each [dcom] [d] is embedded in [d]
- The _pre_-condition is supplied by the context. *)
(** In other words, the invariant of the representation is that a
[dcom] [d] together with a precondition [P] determines a Hoare
triple [{{P}} (extract d) {{post d}}], where [post] is defined as
follows: *)
Fixpoint post (d:dcom) : Assertion :=
match d with
| DCSkip P => P
| DCSeq d1 d2 => post d2
| DCAsgn X a Q => Q
| DCIf _ _ d1 _ d2 Q => Q
| DCWhile b Pbody c Ppost => Ppost
| DCPre _ d => post d
| DCPost c Q => Q
end.
(** Similarly, we can extract the "initial precondition" from a
decorated program. *)
Fixpoint pre (d:dcom) : Assertion :=
match d with
| DCSkip P => fun st => True
| DCSeq c1 c2 => pre c1
| DCAsgn X a Q => fun st => True
| DCIf _ _ t _ e _ => fun st => True
| DCWhile b Pbody c Ppost => fun st => True
| DCPre P c => P
| DCPost c Q => pre c
end.
(** This function is not doing anything sophisticated like calculating
a weakest precondition; it just recursively searches for an
explicit annotation at the very beginning of the program,
returning default answers for programs that lack an explicit
precondition (like a bare assignment or [SKIP]). *)
(** Using [pre] and [post], and assuming that we adopt the convention
of always supplying an explicit precondition annotation at the
very beginning of our decorated programs, we can express what it
means for a decorated program to be correct as follows: *)
Definition dec_correct (d:dcom) :=
{{pre d}} (extract d) {{post d}}.
(** To check whether this Hoare triple is _valid_, we need a way to
extract the "proof obligations" from a decorated program. These
obligations are often called _verification conditions_, because
they are the facts that must be verified to see that the
decorations are logically consistent and thus add up to a complete
proof of correctness. *)
(** ** Extracting Verification Conditions *)
(** The function [verification_conditions] takes a [dcom] [d] together
with a precondition [P] and returns a _proposition_ that, if it
can be proved, implies that the triple [{{P}} (extract d) {{post d}}]
is valid. *)
(** It does this by walking over [d] and generating a big
conjunction including all the "local checks" that we listed when
we described the informal rules for decorated programs. (Strictly
speaking, we need to massage the informal rules a little bit to
add some uses of the rule of consequence, but the correspondence
should be clear.) *)
Fixpoint verification_conditions (P : Assertion) (d:dcom) : Prop :=
match d with
| DCSkip Q =>
(P ->> Q)
| DCSeq d1 d2 =>
verification_conditions P d1
/\ verification_conditions (post d1) d2
| DCAsgn X a Q =>
(P ->> Q [X |-> a])
| DCIf b P1 d1 P2 d2 Q =>
((fun st => P st /\ bassn b st) ->> P1)
/\ ((fun st => P st /\ ~ (bassn b st)) ->> P2)
/\ (Q <<->> post d1) /\ (Q <<->> post d2)
/\ verification_conditions P1 d1
/\ verification_conditions P2 d2
| DCWhile b Pbody d Ppost =>
(* post d is the loop invariant and the initial precondition *)
(P ->> post d)
/\ (Pbody <<->> (fun st => post d st /\ bassn b st))
/\ (Ppost <<->> (fun st => post d st /\ ~(bassn b st)))
/\ verification_conditions Pbody d
| DCPre P' d =>
(P ->> P') /\ verification_conditions P' d
| DCPost d Q =>
verification_conditions P d /\ (post d ->> Q)
end.
(** And now, the key theorem, which states that
[verification_conditions] does its job correctly. Not
surprisingly, we need to use each of the Hoare Logic rules at some
point in the proof. *)
(** We have used _in_ variants of several tactics before to
apply them to values in the context rather than the goal. An
extension of this idea is the syntax [tactic in *], which applies
[tactic] in the goal and every hypothesis in the context. We most
commonly use this facility in conjunction with the [simpl] tactic,
as below. *)
Theorem verification_correct : forall d P,
verification_conditions P d -> {{P}} (extract d) {{post d}}.
Proof.
dcom_cases (induction d) Case; intros P H; simpl in *.
Case "Skip".
eapply hoare_consequence_pre.
apply hoare_skip.
assumption.
Case "Seq".
inversion H as [H1 H2]. clear H.
eapply hoare_seq.
apply IHd2. apply H2.
apply IHd1. apply H1.
Case "Asgn".
eapply hoare_consequence_pre.
apply hoare_asgn.
assumption.
Case "If".
inversion H as [HPre1 [HPre2 [[Hd11 Hd12]
[[Hd21 Hd22] [HThen HElse]]]]].
clear H.
apply IHd1 in HThen. clear IHd1.
apply IHd2 in HElse. clear IHd2.
apply hoare_if.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
Case "While".
inversion H as [Hpre [[Hbody1 Hbody2] [[Hpost1 Hpost2] Hd]]];
subst; clear H.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
apply hoare_while.
eapply hoare_consequence_pre; eauto.
Case "Pre".
inversion H as [HP Hd]; clear H.
eapply hoare_consequence_pre. apply IHd. apply Hd. assumption.
Case "Post".
inversion H as [Hd HQ]; clear H.
eapply hoare_consequence_post. apply IHd. apply Hd. assumption.
Qed.
(** ** Examples *)
(** The propositions generated by [verification_conditions] are fairly
big, and they contain many conjuncts that are essentially trivial. *)
Eval simpl in (verification_conditions (fun st => True) dec_while).
(**
==>
(((fun _ : state => True) ->> (fun _ : state => True)) /\
((fun _ : state => True) ->> (fun _ : state => True)) /\
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) =
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) =
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun _ : state => True) [X |-> AMinus (AId X) (ANum 1)]) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun st : state => st X = 0)
*)
(** In principle, we could certainly work with them using just the
tactics we have so far, but we can make things much smoother with
a bit of automation. We first define a custom [verify] tactic
that applies splitting repeatedly to turn all the conjunctions
into separate subgoals and then uses [omega] and [eauto] (a handy
general-purpose automation tactic that we'll discuss in detail
later) to deal with as many of them as possible. *)
Lemma ble_nat_true_iff : forall n m : nat,
ble_nat n m = true <-> n <= m.
Proof.
intros n m. split. apply ble_nat_true.
generalize dependent m. induction n; intros m H. reflexivity.
simpl. destruct m. inversion H.
apply le_S_n in H. apply IHn. assumption.
Qed.
Lemma ble_nat_false_iff : forall n m : nat,
ble_nat n m = false <-> ~(n <= m).
Proof.
intros n m. split. apply ble_nat_false.
generalize dependent m. induction n; intros m H.
apply ex_falso_quodlibet. apply H. apply le_0_n.
simpl. destruct m. reflexivity.
apply IHn. intro Hc. apply H. apply le_n_S. assumption.
Qed.
Tactic Notation "verify" :=
apply verification_correct;
repeat split;
simpl; unfold assert_implies;
unfold bassn in *; unfold beval in *; unfold aeval in *;
unfold assn_sub; intros;
repeat rewrite update_eq;
repeat (rewrite update_neq; [| (intro X; inversion X)]);
simpl in *;
repeat match goal with [H : _ /\ _ |- _] => destruct H end;
repeat rewrite not_true_iff_false in *;
repeat rewrite not_false_iff_true in *;
repeat rewrite negb_true_iff in *;
repeat rewrite negb_false_iff in *;
repeat rewrite beq_nat_true_iff in *;
repeat rewrite beq_nat_false_iff in *;
repeat rewrite ble_nat_true_iff in *;
repeat rewrite ble_nat_false_iff in *;
try subst;
repeat
match goal with
[st : state |- _] =>
match goal with
[H : st _ = _ |- _] => rewrite -> H in *; clear H
| [H : _ = st _ |- _] => rewrite <- H in *; clear H
end
end;
try eauto; try omega.
(** What's left after [verify] does its thing is "just the interesting
parts" of checking that the decorations are correct. For very
simple examples [verify] immediately solves the goal (provided
that the annotations are correct). *)
Theorem dec_while_correct :
dec_correct dec_while.
Proof. verify. Qed.
(** Another example (formalizing a decorated program we've seen
before): *)
Example subtract_slowly_dec (m:nat) (p:nat) : dcom := (
{{ fun st => st X = m /\ st Z = p }} ->>
{{ fun st => st Z - st X = p - m }}
WHILE BNot (BEq (AId X) (ANum 0))
DO {{ fun st => st Z - st X = p - m /\ st X <> 0 }} ->>
{{ fun st => (st Z - 1) - (st X - 1) = p - m }}
Z ::= AMinus (AId Z) (ANum 1)
{{ fun st => st Z - (st X - 1) = p - m }} ;;
X ::= AMinus (AId X) (ANum 1)
{{ fun st => st Z - st X = p - m }}
END
{{ fun st => st Z - st X = p - m /\ st X = 0 }} ->>
{{ fun st => st Z = p - m }}
) % dcom.
Theorem subtract_slowly_dec_correct : forall m p,
dec_correct (subtract_slowly_dec m p).
Proof. intros m p. verify. (* this grinds for a bit! *) Qed.
(** **** Exercise: 3 stars, advanced (slow_assignment_dec) *)
(** In the [slow_assignment] exercise above, we saw a roundabout way
of assigning a number currently stored in [X] to the variable [Y]:
start [Y] at [0], then decrement [X] until it hits [0],
incrementing [Y] at each step.
Write a _formal_ version of this decorated program and prove it
correct. *)
Example slow_assignment_dec (m:nat) : dcom :=
(* FILL IN HERE *) admit.
Theorem slow_assignment_dec_correct : forall m,
dec_correct (slow_assignment_dec m).
Proof. (* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 4 stars, advanced (factorial_dec) *)
(** Remember the factorial function we worked with before: *)
Fixpoint real_fact (n:nat) : nat :=
match n with
| O => 1
| S n' => n * (real_fact n')
end.
(** Following the pattern of [subtract_slowly_dec], write a decorated
program [factorial_dec] that implements the factorial function and
prove it correct as [factorial_dec_correct]. *)
(* FILL IN HERE *)
(** [] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Hoare2: Hoare Logic, Part II *)
Require Export Hoare.
(* ####################################################### *)
(** * Decorated Programs *)
(** The beauty of Hoare Logic is that it is _compositional_ --
the structure of proofs exactly follows the structure of programs.
This suggests that we can record the essential ideas of a proof
informally (leaving out some low-level calculational details) by
decorating programs with appropriate assertions around each
statement. Such a _decorated program_ carries with it
an (informal) proof of its own correctness. *)
(** For example, here is a complete decorated program: *)
(**
{{ True }} ->>
{{ m = m }}
X ::= m;;
{{ X = m }} ->>
{{ X = m /\ p = p }}
Z ::= p;
{{ X = m /\ Z = p }} ->>
{{ Z - X = p - m }}
WHILE X <> 0 DO
{{ Z - X = p - m /\ X <> 0 }} ->>
{{ (Z - 1) - (X - 1) = p - m }}
Z ::= Z - 1;;
{{ Z - (X - 1) = p - m }}
X ::= X - 1
{{ Z - X = p - m }}
END;
{{ Z - X = p - m /\ ~ (X <> 0) }} ->>
{{ Z = p - m }}
*)
(** Concretely, a decorated program consists of the program text
interleaved with assertions. To check that a decorated program
represents a valid proof, we check that each individual command is
_locally consistent_ with its accompanying assertions in the
following sense: *)
(**
- [SKIP] is locally consistent if its precondition and
postcondition are the same:
{{ P }}
SKIP
{{ P }}
*)
(**
- The sequential composition of [c1] and [c2] is locally
consistent (with respect to assertions [P] and [R]) if [c1] is
locally consistent (with respect to [P] and [Q]) and [c2] is
locally consistent (with respect to [Q] and [R]):
{{ P }}
c1;;
{{ Q }}
c2
{{ R }}
*)
(**
- An assignment is locally consistent if its precondition is
the appropriate substitution of its postcondition:
{{ P [X |-> a] }}
X ::= a
{{ P }}
*)
(**
- A conditional is locally consistent (with respect to assertions
[P] and [Q]) if the assertions at the top of its "then" and
"else" branches are exactly [P /\ b] and [P /\ ~b] and if its "then"
branch is locally consistent (with respect to [P /\ b] and [Q])
and its "else" branch is locally consistent (with respect to
[P /\ ~b] and [Q]):
{{ P }}
IFB b THEN
{{ P /\ b }}
c1
{{ Q }}
ELSE
{{ P /\ ~b }}
c2
{{ Q }}
FI
{{ Q }}
*)
(**
- A while loop with precondition [P] is locally consistent if its
postcondition is [P /\ ~b] and if the pre- and postconditions of
its body are exactly [P /\ b] and [P]:
{{ P }}
WHILE b DO
{{ P /\ b }}
c1
{{ P }}
END
{{ P /\ ~b }}
*)
(**
- A pair of assertions separated by [->>] is locally consistent if
the first implies the second (in all states):
{{ P }} ->>
{{ P' }}
This corresponds to the application of [hoare_consequence] and
is the only place in a decorated program where checking if
decorations are correct is not fully mechanical and syntactic,
but involves logical and/or arithmetic reasoning.
*)
(** We have seen above how _verifying_ the correctness of a
given proof involves checking that every single command is locally
consistent with the accompanying assertions. If we are instead
interested in _finding_ a proof for a given specification we need
to discover the right assertions. This can be done in an almost
automatic way, with the exception of finding loop invariants,
which is the subject of in the next section. In the reminder of
this section we explain in detail how to construct decorations for
several simple programs that don't involve non-trivial loop
invariants. *)
(* ####################################################### *)
(** ** Example: Swapping Using Addition and Subtraction *)
(** Here is a program that swaps the values of two variables using
addition and subtraction (instead of by assigning to a temporary
variable).
X ::= X + Y;;
Y ::= X - Y;;
X ::= X - Y
We can prove using decorations that this program is correct --
i.e., it always swaps the values of variables [X] and [Y]. *)
(**
(1) {{ X = m /\ Y = n }} ->>
(2) {{ (X + Y) - ((X + Y) - Y) = n /\ (X + Y) - Y = m }}
X ::= X + Y;;
(3) {{ X - (X - Y) = n /\ X - Y = m }}
Y ::= X - Y;;
(4) {{ X - Y = n /\ Y = m }}
X ::= X - Y
(5) {{ X = n /\ Y = m }}
The decorations were constructed as follows:
- We begin with the undecorated program (the unnumbered lines).
- We then add the specification -- i.e., the outer
precondition (1) and postcondition (5). In the precondition we
use auxiliary variables (parameters) [m] and [n] to remember
the initial values of variables [X] and respectively [Y], so
that we can refer to them in the postcondition (5).
- We work backwards mechanically starting from (5) all the way
to (2). At each step, we obtain the precondition of the
assignment from its postcondition by substituting the assigned
variable with the right-hand-side of the assignment. For
instance, we obtain (4) by substituting [X] with [X - Y]
in (5), and (3) by substituting [Y] with [X - Y] in (4).
- Finally, we verify that (1) logically implies (2) -- i.e.,
that the step from (1) to (2) is a valid use of the law of
consequence. For this we substitute [X] by [m] and [Y] by [n]
and calculate as follows:
(m + n) - ((m + n) - n) = n /\ (m + n) - n = m
(m + n) - m = n /\ m = m
n = n /\ m = m
(Note that, since we are working with natural numbers, not
fixed-size machine integers, we don't need to worry about the
possibility of arithmetic overflow anywhere in this argument.)
*)
(* ####################################################### *)
(** ** Example: Simple Conditionals *)
(** Here is a simple decorated program using conditionals:
(1) {{True}}
IFB X <= Y THEN
(2) {{True /\ X <= Y}} ->>
(3) {{(Y - X) + X = Y \/ (Y - X) + Y = X}}
Z ::= Y - X
(4) {{Z + X = Y \/ Z + Y = X}}
ELSE
(5) {{True /\ ~(X <= Y) }} ->>
(6) {{(X - Y) + X = Y \/ (X - Y) + Y = X}}
Z ::= X - Y
(7) {{Z + X = Y \/ Z + Y = X}}
FI
(8) {{Z + X = Y \/ Z + Y = X}}
These decorations were constructed as follows:
- We start with the outer precondition (1) and postcondition (8).
- We follow the format dictated by the [hoare_if] rule and copy the
postcondition (8) to (4) and (7). We conjoin the precondition (1)
with the guard of the conditional to obtain (2). We conjoin (1)
with the negated guard of the conditional to obtain (5).
- In order to use the assignment rule and obtain (3), we substitute
[Z] by [Y - X] in (4). To obtain (6) we substitute [Z] by [X - Y]
in (7).
- Finally, we verify that (2) implies (3) and (5) implies (6). Both
of these implications crucially depend on the ordering of [X] and
[Y] obtained from the guard. For instance, knowing that [X <= Y]
ensures that subtracting [X] from [Y] and then adding back [X]
produces [Y], as required by the first disjunct of (3). Similarly,
knowing that [~(X <= Y)] ensures that subtracting [Y] from [X] and
then adding back [Y] produces [X], as needed by the second
disjunct of (6). Note that [n - m + m = n] does _not_ hold for
arbitrary natural numbers [n] and [m] (for example, [3 - 5 + 5 =
5]). *)
(** **** Exercise: 2 stars (if_minus_plus_reloaded) *)
(** Fill in valid decorations for the following program:
{{ True }}
IFB X <= Y THEN
{{ }} ->>
{{ }}
Z ::= Y - X
{{ }}
ELSE
{{ }} ->>
{{ }}
Y ::= X + Z
{{ }}
FI
{{ Y = X + Z }}
*)
(** [] *)
(* ####################################################### *)
(** ** Example: Reduce to Zero (Trivial Loop) *)
(** Here is a [WHILE] loop that is so simple it needs no
invariant (i.e., the invariant [True] will do the job).
(1) {{ True }}
WHILE X <> 0 DO
(2) {{ True /\ X <> 0 }} ->>
(3) {{ True }}
X ::= X - 1
(4) {{ True }}
END
(5) {{ True /\ X = 0 }} ->>
(6) {{ X = 0 }}
The decorations can be constructed as follows:
- Start with the outer precondition (1) and postcondition (6).
- Following the format dictated by the [hoare_while] rule, we copy
(1) to (4). We conjoin (1) with the guard to obtain (2) and with
the negation of the guard to obtain (5). Note that, because the
outer postcondition (6) does not syntactically match (5), we need a
trivial use of the consequence rule from (5) to (6).
- Assertion (3) is the same as (4), because [X] does not appear in
[4], so the substitution in the assignment rule is trivial.
- Finally, the implication between (2) and (3) is also trivial.
*)
(** From this informal proof, it is easy to read off a formal proof
using the Coq versions of the Hoare rules. Note that we do _not_
unfold the definition of [hoare_triple] anywhere in this proof --
the idea is to use the Hoare rules as a "self-contained" logic for
reasoning about programs. *)
Definition reduce_to_zero' : com :=
WHILE BNot (BEq (AId X) (ANum 0)) DO
X ::= AMinus (AId X) (ANum 1)
END.
Theorem reduce_to_zero_correct' :
{{fun st => True}}
reduce_to_zero'
{{fun st => st X = 0}}.
Proof.
unfold reduce_to_zero'.
(* First we need to transform the postcondition so
that hoare_while will apply. *)
eapply hoare_consequence_post.
apply hoare_while.
Case "Loop body preserves invariant".
(* Need to massage precondition before [hoare_asgn] applies *)
eapply hoare_consequence_pre. apply hoare_asgn.
(* Proving trivial implication (2) ->> (3) *)
intros st [HT Hbp]. unfold assn_sub. apply I.
Case "Invariant and negated guard imply postcondition".
intros st [Inv GuardFalse].
unfold bassn in GuardFalse. simpl in GuardFalse.
(* SearchAbout helps to find the right lemmas *)
SearchAbout [not true].
rewrite not_true_iff_false in GuardFalse.
SearchAbout [negb false].
rewrite negb_false_iff in GuardFalse.
SearchAbout [beq_nat true].
apply beq_nat_true in GuardFalse.
apply GuardFalse. Qed.
(* ####################################################### *)
(** ** Example: Division *)
(** The following Imp program calculates the integer division and
remainder of two numbers [m] and [n] that are arbitrary constants
in the program.
X ::= m;;
Y ::= 0;;
WHILE n <= X DO
X ::= X - n;;
Y ::= Y + 1
END;
In other words, if we replace [m] and [n] by concrete numbers and
execute the program, it will terminate with the variable [X] set
to the remainder when [m] is divided by [n] and [Y] set to the
quotient. *)
(** In order to give a specification to this program we need to
remember that dividing [m] by [n] produces a reminder [X] and a
quotient [Y] so that [n * Y + X = m /\ X < n].
It turns out that we get lucky with this program and don't have to
think very hard about the loop invariant: the invariant is the
just first conjunct [n * Y + X = m], so we use that to decorate
the program.
(1) {{ True }} ->>
(2) {{ n * 0 + m = m }}
X ::= m;;
(3) {{ n * 0 + X = m }}
Y ::= 0;;
(4) {{ n * Y + X = m }}
WHILE n <= X DO
(5) {{ n * Y + X = m /\ n <= X }} ->>
(6) {{ n * (Y + 1) + (X - n) = m }}
X ::= X - n;;
(7) {{ n * (Y + 1) + X = m }}
Y ::= Y + 1
(8) {{ n * Y + X = m }}
END
(9) {{ n * Y + X = m /\ X < n }}
Assertions (4), (5), (8), and (9) are derived mechanically from
the invariant and the loop's guard. Assertions (8), (7), and (6)
are derived using the assignment rule going backwards from (8) to
(6). Assertions (4), (3), and (2) are again backwards applications
of the assignment rule.
Now that we've decorated the program it only remains to check that
the two uses of the consequence rule are correct -- i.e., that (1)
implies (2) and that (5) implies (6). This is indeed the case, so
we have a valid decorated program.
*)
(* ####################################################### *)
(** * Finding Loop Invariants *)
(** Once the outermost precondition and postcondition are chosen, the
only creative part in verifying programs with Hoare Logic is
finding the right loop invariants. The reason this is difficult
is the same as the reason that doing inductive mathematical proofs
requires creativity: strengthening the loop invariant (or the
induction hypothesis) means that you have a stronger assumption to
work with when trying to establish the postcondition of the loop
body (complete the induction step of the proof), but it also means
that the loop body postcondition itself is harder to prove!
This section is dedicated to teaching you how to approach the
challenge of finding loop invariants using a series of examples
and exercises. *)
(** ** Example: Slow Subtraction *)
(** The following program subtracts the value of [X] from the value of
[Y] by repeatedly decrementing both [X] and [Y]. We want to verify its
correctness with respect to the following specification:
{{ X = m /\ Y = n }}
WHILE X <> 0 DO
Y ::= Y - 1;;
X ::= X - 1
END
{{ Y = n - m }}
To verify this program we need to find an invariant [I] for the
loop. As a first step we can leave [I] as an unknown and build a
_skeleton_ for the proof by applying backward the rules for local
consistency. This process leads to the following skeleton:
(1) {{ X = m /\ Y = n }} ->> (a)
(2) {{ I }}
WHILE X <> 0 DO
(3) {{ I /\ X <> 0 }} ->> (c)
(4) {{ I[X |-> X-1][Y |-> Y-1] }}
Y ::= Y - 1;;
(5) {{ I[X |-> X-1] }}
X ::= X - 1
(6) {{ I }}
END
(7) {{ I /\ ~(X <> 0) }} ->> (b)
(8) {{ Y = n - m }}
By examining this skeleton, we can see that any valid [I] will
have to respect three conditions:
- (a) it must be weak enough to be implied by the loop's
precondition, i.e. (1) must imply (2);
- (b) it must be strong enough to imply the loop's postcondition,
i.e. (7) must imply (8);
- (c) it must be preserved by one iteration of the loop, i.e. (3)
must imply (4). *)
(** These conditions are actually independent of the particular
program and specification we are considering. Indeed, every loop
invariant has to satisfy them. One way to find an invariant that
simultaneously satisfies these three conditions is by using an
iterative process: start with a "candidate" invariant (e.g. a
guess or a heuristic choice) and check the three conditions above;
if any of the checks fails, try to use the information that we get
from the failure to produce another (hopefully better) candidate
invariant, and repeat the process.
For instance, in the reduce-to-zero example above, we saw that,
for a very simple loop, choosing [True] as an invariant did the
job. So let's try it again here! I.e., let's instantiate [I] with
[True] in the skeleton above see what we get...
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ True }}
WHILE X <> 0 DO
(3) {{ True /\ X <> 0 }} ->> (c - OK)
(4) {{ True }}
Y ::= Y - 1;;
(5) {{ True }}
X ::= X - 1
(6) {{ True }}
END
(7) {{ True /\ X = 0 }} ->> (b - WRONG!)
(8) {{ Y = n - m }}
While conditions (a) and (c) are trivially satisfied,
condition (b) is wrong, i.e. it is not the case that (7) [True /\
X = 0] implies (8) [Y = n - m]. In fact, the two assertions are
completely unrelated and it is easy to find a counterexample (say,
[Y = X = m = 0] and [n = 1]).
If we want (b) to hold, we need to strengthen the invariant so
that it implies the postcondition (8). One very simple way to do
this is to let the invariant _be_ the postcondition. So let's
return to our skeleton, instantiate [I] with [Y = n - m], and
check conditions (a) to (c) again.
(1) {{ X = m /\ Y = n }} ->> (a - WRONG!)
(2) {{ Y = n - m }}
WHILE X <> 0 DO
(3) {{ Y = n - m /\ X <> 0 }} ->> (c - WRONG!)
(4) {{ Y - 1 = n - m }}
Y ::= Y - 1;;
(5) {{ Y = n - m }}
X ::= X - 1
(6) {{ Y = n - m }}
END
(7) {{ Y = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
This time, condition (b) holds trivially, but (a) and (c) are
broken. Condition (a) requires that (1) [X = m /\ Y = n]
implies (2) [Y = n - m]. If we substitute [Y] by [n] we have to
show that [n = n - m] for arbitrary [m] and [n], which does not
hold (for instance, when [m = n = 1]). Condition (c) requires that
[n - m - 1 = n - m], which fails, for instance, for [n = 1] and [m =
0]. So, although [Y = n - m] holds at the end of the loop, it does
not hold from the start, and it doesn't hold on each iteration;
it is not a correct invariant.
This failure is not very surprising: the variable [Y] changes
during the loop, while [m] and [n] are constant, so the assertion
we chose didn't have much chance of being an invariant!
To do better, we need to generalize (8) to some statement that is
equivalent to (8) when [X] is [0], since this will be the case
when the loop terminates, and that "fills the gap" in some
appropriate way when [X] is nonzero. Looking at how the loop
works, we can observe that [X] and [Y] are decremented together
until [X] reaches [0]. So, if [X = 2] and [Y = 5] initially,
after one iteration of the loop we obtain [X = 1] and [Y = 4];
after two iterations [X = 0] and [Y = 3]; and then the loop stops.
Notice that the difference between [Y] and [X] stays constant
between iterations; initially, [Y = n] and [X = m], so this
difference is always [n - m]. So let's try instantiating [I] in
the skeleton above with [Y - X = n - m].
(1) {{ X = m /\ Y = n }} ->> (a - OK)
(2) {{ Y - X = n - m }}
WHILE X <> 0 DO
(3) {{ Y - X = n - m /\ X <> 0 }} ->> (c - OK)
(4) {{ (Y - 1) - (X - 1) = n - m }}
Y ::= Y - 1;;
(5) {{ Y - (X - 1) = n - m }}
X ::= X - 1
(6) {{ Y - X = n - m }}
END
(7) {{ Y - X = n - m /\ X = 0 }} ->> (b - OK)
(8) {{ Y = n - m }}
Success! Conditions (a), (b) and (c) all hold now. (To
verify (c), we need to check that, under the assumption that [X <>
0], we have [Y - X = (Y - 1) - (X - 1)]; this holds for all
natural numbers [X] and [Y].) *)
(* ####################################################### *)
(** ** Exercise: Slow Assignment *)
(** **** Exercise: 2 stars (slow_assignment) *)
(** A roundabout way of assigning a number currently stored in [X] to
the variable [Y] is to start [Y] at [0], then decrement [X] until
it hits [0], incrementing [Y] at each step. Here is a program that
implements this idea:
{{ X = m }}
Y ::= 0;;
WHILE X <> 0 DO
X ::= X - 1;;
Y ::= Y + 1
END
{{ Y = m }}
Write an informal decorated program showing that this is correct. *)
(* FILL IN HERE *)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Slow Addition *)
(** **** Exercise: 3 stars, optional (add_slowly_decoration) *)
(** The following program adds the variable X into the variable Z
by repeatedly decrementing X and incrementing Z.
WHILE X <> 0 DO
Z ::= Z + 1;;
X ::= X - 1
END
Following the pattern of the [subtract_slowly] example above, pick
a precondition and postcondition that give an appropriate
specification of [add_slowly]; then (informally) decorate the
program accordingly. *)
(* FILL IN HERE *)
(** [] *)
(* ####################################################### *)
(** ** Example: Parity *)
(** Here is a cute little program for computing the parity of the
value initially stored in [X] (due to Daniel Cristofani).
{{ X = m }}
WHILE 2 <= X DO
X ::= X - 2
END
{{ X = parity m }}
The mathematical [parity] function used in the specification is
defined in Coq as follows: *)
Fixpoint parity x :=
match x with
| 0 => 0
| 1 => 1
| S (S x') => parity x'
end.
(** The postcondition does not hold at the beginning of the loop,
since [m = parity m] does not hold for an arbitrary [m], so we
cannot use that as an invariant. To find an invariant that works,
let's think a bit about what this loop does. On each iteration it
decrements [X] by [2], which preserves the parity of [X]. So the
parity of [X] does not change, i.e. it is invariant. The initial
value of [X] is [m], so the parity of [X] is always equal to the
parity of [m]. Using [parity X = parity m] as an invariant we
obtain the following decorated program:
{{ X = m }} ->> (a - OK)
{{ parity X = parity m }}
WHILE 2 <= X DO
{{ parity X = parity m /\ 2 <= X }} ->> (c - OK)
{{ parity (X-2) = parity m }}
X ::= X - 2
{{ parity X = parity m }}
END
{{ parity X = parity m /\ X < 2 }} ->> (b - OK)
{{ X = parity m }}
With this invariant, conditions (a), (b), and (c) are all
satisfied. For verifying (b), we observe that, when [X < 2], we
have [parity X = X] (we can easily see this in the definition of
[parity]). For verifying (c), we observe that, when [2 <= X], we
have [parity X = parity (X-2)]. *)
(** **** Exercise: 3 stars, optional (parity_formal) *)
(** Translate this proof to Coq. Refer to the reduce-to-zero example
for ideas. You may find the following two lemmas useful: *)
Lemma parity_ge_2 : forall x,
2 <= x ->
parity (x - 2) = parity x.
Proof.
induction x; intro. reflexivity.
destruct x. inversion H. inversion H1.
simpl. rewrite <- minus_n_O. reflexivity.
Qed.
Lemma parity_lt_2 : forall x,
~ 2 <= x ->
parity (x) = x.
Proof.
intros. induction x. reflexivity. destruct x. reflexivity.
apply ex_falso_quodlibet. apply H. omega.
Qed.
Theorem parity_correct : forall m,
{{ fun st => st X = m }}
WHILE BLe (ANum 2) (AId X) DO
X ::= AMinus (AId X) (ANum 2)
END
{{ fun st => st X = parity m }}.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ####################################################### *)
(** ** Example: Finding Square Roots *)
(** The following program computes the square root of [X]
by naive iteration:
{{ X=m }}
Z ::= 0;;
WHILE (Z+1)*(Z+1) <= X DO
Z ::= Z+1
END
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
*)
(** As above, we can try to use the postcondition as a candidate
invariant, obtaining the following decorated program:
(1) {{ X=m }} ->> (a - second conjunct of (2) WRONG!)
(2) {{ 0*0 <= m /\ m<1*1 }}
Z ::= 0;;
(3) {{ Z*Z <= m /\ m<(Z+1)*(Z+1) }}
WHILE (Z+1)*(Z+1) <= X DO
(4) {{ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - WRONG!)
(5) {{ (Z+1)*(Z+1)<=m /\ m<(Z+2)*(Z+2) }}
Z ::= Z+1
(6) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
END
(7) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
(8) {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This didn't work very well: both conditions (a) and (c) failed.
Looking at condition (c), we see that the second conjunct of (4)
is almost the same as the first conjunct of (5), except that (4)
mentions [X] while (5) mentions [m]. But note that [X] is never
assigned in this program, so we should have [X=m], but we didn't
propagate this information from (1) into the loop invariant.
Also, looking at the second conjunct of (8), it seems quite
hopeless as an invariant -- and we don't even need it, since we
can obtain it from the negation of the guard (third conjunct
in (7)), again under the assumption that [X=m].
So we now try [X=m /\ Z*Z <= m] as the loop invariant:
{{ X=m }} ->> (a - OK)
{{ X=m /\ 0*0 <= m }}
Z ::= 0;
{{ X=m /\ Z*Z <= m }}
WHILE (Z+1)*(Z+1) <= X DO
{{ X=m /\ Z*Z<=m /\ (Z+1)*(Z+1)<=X }} ->> (c - OK)
{{ X=m /\ (Z+1)*(Z+1)<=m }}
Z ::= Z+1
{{ X=m /\ Z*Z<=m }}
END
{{ X=m /\ Z*Z<=m /\ X<(Z+1)*(Z+1) }} ->> (b - OK)
{{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
This works, since conditions (a), (b), and (c) are now all
trivially satisfied.
Very often, if a variable is used in a loop in a read-only
fashion (i.e., it is referred to by the program or by the
specification and it is not changed by the loop) it is necessary
to add the fact that it doesn't change to the loop invariant. *)
(* ####################################################### *)
(** ** Example: Squaring *)
(** Here is a program that squares [X] by repeated addition:
{{ X = m }}
Y ::= 0;;
Z ::= 0;;
WHILE Y <> X DO
Z ::= Z + X;;
Y ::= Y + 1
END
{{ Z = m*m }}
*)
(** The first thing to note is that the loop reads [X] but doesn't
change its value. As we saw in the previous example, in such cases
it is a good idea to add [X = m] to the invariant. The other thing
we often use in the invariant is the postcondition, so let's add
that too, leading to the invariant candidate [Z = m * m /\ X = m].
{{ X = m }} ->> (a - WRONG)
{{ 0 = m*m /\ X = m }}
Y ::= 0;;
{{ 0 = m*m /\ X = m }}
Z ::= 0;;
{{ Z = m*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - WRONG)
{{ Z+X = m*m /\ X = m }}
Z ::= Z + X;;
{{ Z = m*m /\ X = m }}
Y ::= Y + 1
{{ Z = m*m /\ X = m }}
END
{{ Z = m*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
Conditions (a) and (c) fail because of the [Z = m*m] part. While
[Z] starts at [0] and works itself up to [m*m], we can't expect
[Z] to be [m*m] from the start. If we look at how [Z] progesses
in the loop, after the 1st iteration [Z = m], after the 2nd
iteration [Z = 2*m], and at the end [Z = m*m]. Since the variable
[Y] tracks how many times we go through the loop, we derive the
new invariant candidate [Z = Y*m /\ X = m].
{{ X = m }} ->> (a - OK)
{{ 0 = 0*m /\ X = m }}
Y ::= 0;;
{{ 0 = Y*m /\ X = m }}
Z ::= 0;;
{{ Z = Y*m /\ X = m }}
WHILE Y <> X DO
{{ Z = Y*m /\ X = m /\ Y <> X }} ->> (c - OK)
{{ Z+X = (Y+1)*m /\ X = m }}
Z ::= Z + X;
{{ Z = (Y+1)*m /\ X = m }}
Y ::= Y + 1
{{ Z = Y*m /\ X = m }}
END
{{ Z = Y*m /\ X = m /\ Y = X }} ->> (b - OK)
{{ Z = m*m }}
This new invariant makes the proof go through: all three
conditions are easy to check.
It is worth comparing the postcondition [Z = m*m] and the [Z =
Y*m] conjunct of the invariant. It is often the case that one has
to replace auxiliary variabes (parameters) with variables -- or
with expressions involving both variables and parameters (like
[m - Y]) -- when going from postconditions to invariants. *)
(* ####################################################### *)
(** ** Exercise: Factorial *)
(** **** Exercise: 3 stars (factorial) *)
(** Recall that [n!] denotes the factorial of [n] (i.e. [n! =
1*2*...*n]). Here is an Imp program that calculates the factorial
of the number initially stored in the variable [X] and puts it in
the variable [Y]:
{{ X = m }}
Y ::= 1 ;;
WHILE X <> 0
DO
Y ::= Y * X ;;
X ::= X - 1
END
{{ Y = m! }}
Fill in the blanks in following decorated program:
{{ X = m }} ->>
{{ }}
Y ::= 1;;
{{ }}
WHILE X <> 0
DO {{ }} ->>
{{ }}
Y ::= Y * X;;
{{ }}
X ::= X - 1
{{ }}
END
{{ }} ->>
{{ Y = m! }}
*)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Min *)
(** **** Exercise: 3 stars (Min_Hoare) *)
(** Fill in valid decorations for the following program.
For the => steps in your annotations, you may rely (silently) on the
following facts about min
Lemma lemma1 : forall x y,
(x=0 \/ y=0) -> min x y = 0.
Lemma lemma2 : forall x y,
min (x-1) (y-1) = (min x y) - 1.
plus, as usual, standard high-school algebra.
{{ True }} ->>
{{ }}
X ::= a;;
{{ }}
Y ::= b;;
{{ }}
Z ::= 0;;
{{ }}
WHILE (X <> 0 /\ Y <> 0) DO
{{ }} ->>
{{ }}
X := X - 1;;
{{ }}
Y := Y - 1;;
{{ }}
Z := Z + 1
{{ }}
END
{{ }} ->>
{{ Z = min a b }}
*)
(** [] *)
(** **** Exercise: 3 stars (two_loops) *)
(** Here is a very inefficient way of adding 3 numbers:
X ::= 0;;
Y ::= 0;;
Z ::= c;;
WHILE X <> a DO
X ::= X + 1;;
Z ::= Z + 1
END;;
WHILE Y <> b DO
Y ::= Y + 1;;
Z ::= Z + 1
END
Show that it does what it should by filling in the blanks in the
following decorated program.
{{ True }} ->>
{{ }}
X ::= 0;;
{{ }}
Y ::= 0;;
{{ }}
Z ::= c;;
{{ }}
WHILE X <> a DO
{{ }} ->>
{{ }}
X ::= X + 1;;
{{ }}
Z ::= Z + 1
{{ }}
END;;
{{ }} ->>
{{ }}
WHILE Y <> b DO
{{ }} ->>
{{ }}
Y ::= Y + 1;;
{{ }}
Z ::= Z + 1
{{ }}
END
{{ }} ->>
{{ Z = a + b + c }}
*)
(** [] *)
(* ####################################################### *)
(** ** Exercise: Power Series *)
(** **** Exercise: 4 stars, optional (dpow2_down) *)
(** Here is a program that computes the series:
[1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1]
X ::= 0;;
Y ::= 1;;
Z ::= 1;;
WHILE X <> m DO
Z ::= 2 * Z;;
Y ::= Y + Z;;
X ::= X + 1
END
Write a decorated program for this. *)
(* FILL IN HERE *)
(* ####################################################### *)
(** * Weakest Preconditions (Advanced) *)
(** Some Hoare triples are more interesting than others.
For example,
{{ False }} X ::= Y + 1 {{ X <= 5 }}
is _not_ very interesting: although it is perfectly valid, it
tells us nothing useful. Since the precondition isn't satisfied
by any state, it doesn't describe any situations where we can use
the command [X ::= Y + 1] to achieve the postcondition [X <= 5].
By contrast,
{{ Y <= 4 /\ Z = 0 }} X ::= Y + 1 {{ X <= 5 }}
is useful: it tells us that, if we can somehow create a situation
in which we know that [Y <= 4 /\ Z = 0], then running this command
will produce a state satisfying the postcondition. However, this
triple is still not as useful as it could be, because the [Z = 0]
clause in the precondition actually has nothing to do with the
postcondition [X <= 5]. The _most_ useful triple (for a given
command and postcondition) is this one:
{{ Y <= 4 }} X ::= Y + 1 {{ X <= 5 }}
In other words, [Y <= 4] is the _weakest_ valid precondition of
the command [X ::= Y + 1] for the postcondition [X <= 5]. *)
(** In general, we say that "[P] is the weakest precondition of
command [c] for postcondition [Q]" if [{{P}} c {{Q}}] and if,
whenever [P'] is an assertion such that [{{P'}} c {{Q}}], we have
[P' st] implies [P st] for all states [st]. *)
Definition is_wp P c Q :=
{{P}} c {{Q}} /\
forall P', {{P'}} c {{Q}} -> (P' ->> P).
(** That is, [P] is the weakest precondition of [c] for [Q]
if (a) [P] _is_ a precondition for [Q] and [c], and (b) [P] is the
_weakest_ (easiest to satisfy) assertion that guarantees [Q] after
executing [c]. *)
(** **** Exercise: 1 star, optional (wp) *)
(** What are the weakest preconditions of the following commands
for the following postconditions?
1) {{ ? }} SKIP {{ X = 5 }}
2) {{ ? }} X ::= Y + Z {{ X = 5 }}
3) {{ ? }} X ::= Y {{ X = Y }}
4) {{ ? }}
IFB X == 0 THEN Y ::= Z + 1 ELSE Y ::= W + 2 FI
{{ Y = 5 }}
5) {{ ? }}
X ::= 5
{{ X = 0 }}
6) {{ ? }}
WHILE True DO X ::= 0 END
{{ X = 0 }}
*)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 3 stars, advanced, optional (is_wp_formal) *)
(** Prove formally using the definition of [hoare_triple] that [Y <= 4]
is indeed the weakest precondition of [X ::= Y + 1] with respect to
postcondition [X <= 5]. *)
Theorem is_wp_example :
is_wp (fun st => st Y <= 4)
(X ::= APlus (AId Y) (ANum 1)) (fun st => st X <= 5).
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, advanced (hoare_asgn_weakest) *)
(** Show that the precondition in the rule [hoare_asgn] is in fact the
weakest precondition. *)
Theorem hoare_asgn_weakest : forall Q X a,
is_wp (Q [X |-> a]) (X ::= a) Q.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 2 stars, advanced, optional (hoare_havoc_weakest) *)
(** Show that your [havoc_pre] rule from the [himp_hoare] exercise
in the [Hoare] chapter returns the weakest precondition. *)
Module Himp2.
Import Himp.
Lemma hoare_havoc_weakest : forall (P Q : Assertion) (X : id),
{{ P }} HAVOC X {{ Q }} ->
P ->> havoc_pre X Q.
Proof.
(* FILL IN HERE *) Admitted.
End Himp2.
(** [] *)
(* ####################################################### *)
(** * Formal Decorated Programs (Advanced) *)
(** The informal conventions for decorated programs amount to a way of
displaying Hoare triples in which commands are annotated with
enough embedded assertions that checking the validity of the
triple is reduced to simple logical and algebraic calculations
showing that some assertions imply others. In this section, we
show that this informal presentation style can actually be made
completely formal and indeed that checking the validity of
decorated programs can mostly be automated. *)
(** ** Syntax *)
(** The first thing we need to do is to formalize a variant of the
syntax of commands with embedded assertions. We call the new
commands _decorated commands_, or [dcom]s. *)
Inductive dcom : Type :=
| DCSkip : Assertion -> dcom
| DCSeq : dcom -> dcom -> dcom
| DCAsgn : id -> aexp -> Assertion -> dcom
| DCIf : bexp -> Assertion -> dcom -> Assertion -> dcom
-> Assertion-> dcom
| DCWhile : bexp -> Assertion -> dcom -> Assertion -> dcom
| DCPre : Assertion -> dcom -> dcom
| DCPost : dcom -> Assertion -> dcom.
Tactic Notation "dcom_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "Skip" | Case_aux c "Seq" | Case_aux c "Asgn"
| Case_aux c "If" | Case_aux c "While"
| Case_aux c "Pre" | Case_aux c "Post" ].
Notation "'SKIP' {{ P }}"
:= (DCSkip P)
(at level 10) : dcom_scope.
Notation "l '::=' a {{ P }}"
:= (DCAsgn l a P)
(at level 60, a at next level) : dcom_scope.
Notation "'WHILE' b 'DO' {{ Pbody }} d 'END' {{ Ppost }}"
:= (DCWhile b Pbody d Ppost)
(at level 80, right associativity) : dcom_scope.
Notation "'IFB' b 'THEN' {{ P }} d 'ELSE' {{ P' }} d' 'FI' {{ Q }}"
:= (DCIf b P d P' d' Q)
(at level 80, right associativity) : dcom_scope.
Notation "'->>' {{ P }} d"
:= (DCPre P d)
(at level 90, right associativity) : dcom_scope.
Notation "{{ P }} d"
:= (DCPre P d)
(at level 90) : dcom_scope.
Notation "d '->>' {{ P }}"
:= (DCPost d P)
(at level 80, right associativity) : dcom_scope.
Notation " d ;; d' "
:= (DCSeq d d')
(at level 80, right associativity) : dcom_scope.
Delimit Scope dcom_scope with dcom.
(** To avoid clashing with the existing [Notation] definitions
for ordinary [com]mands, we introduce these notations in a special
scope called [dcom_scope], and we wrap examples with the
declaration [% dcom] to signal that we want the notations to be
interpreted in this scope.
Careful readers will note that we've defined two notations for the
[DCPre] constructor, one with and one without a [->>]. The
"without" version is intended to be used to supply the initial
precondition at the very top of the program. *)
Example dec_while : dcom := (
{{ fun st => True }}
WHILE (BNot (BEq (AId X) (ANum 0)))
DO
{{ fun st => True /\ st X <> 0}}
X ::= (AMinus (AId X) (ANum 1))
{{ fun _ => True }}
END
{{ fun st => True /\ st X = 0}} ->>
{{ fun st => st X = 0 }}
) % dcom.
(** It is easy to go from a [dcom] to a [com] by erasing all
annotations. *)
Fixpoint extract (d:dcom) : com :=
match d with
| DCSkip _ => SKIP
| DCSeq d1 d2 => (extract d1 ;; extract d2)
| DCAsgn X a _ => X ::= a
| DCIf b _ d1 _ d2 _ => IFB b THEN extract d1 ELSE extract d2 FI
| DCWhile b _ d _ => WHILE b DO extract d END
| DCPre _ d => extract d
| DCPost d _ => extract d
end.
(** The choice of exactly where to put assertions in the definition of
[dcom] is a bit subtle. The simplest thing to do would be to
annotate every [dcom] with a precondition and postcondition. But
this would result in very verbose programs with a lot of repeated
annotations: for example, a program like [SKIP;SKIP] would have to
be annotated as
{{P}} ({{P}} SKIP {{P}}) ;; ({{P}} SKIP {{P}}) {{P}},
with pre- and post-conditions on each [SKIP], plus identical pre-
and post-conditions on the semicolon!
Instead, the rule we've followed is this:
- The _post_-condition expected by each [dcom] [d] is embedded in [d]
- The _pre_-condition is supplied by the context. *)
(** In other words, the invariant of the representation is that a
[dcom] [d] together with a precondition [P] determines a Hoare
triple [{{P}} (extract d) {{post d}}], where [post] is defined as
follows: *)
Fixpoint post (d:dcom) : Assertion :=
match d with
| DCSkip P => P
| DCSeq d1 d2 => post d2
| DCAsgn X a Q => Q
| DCIf _ _ d1 _ d2 Q => Q
| DCWhile b Pbody c Ppost => Ppost
| DCPre _ d => post d
| DCPost c Q => Q
end.
(** Similarly, we can extract the "initial precondition" from a
decorated program. *)
Fixpoint pre (d:dcom) : Assertion :=
match d with
| DCSkip P => fun st => True
| DCSeq c1 c2 => pre c1
| DCAsgn X a Q => fun st => True
| DCIf _ _ t _ e _ => fun st => True
| DCWhile b Pbody c Ppost => fun st => True
| DCPre P c => P
| DCPost c Q => pre c
end.
(** This function is not doing anything sophisticated like calculating
a weakest precondition; it just recursively searches for an
explicit annotation at the very beginning of the program,
returning default answers for programs that lack an explicit
precondition (like a bare assignment or [SKIP]). *)
(** Using [pre] and [post], and assuming that we adopt the convention
of always supplying an explicit precondition annotation at the
very beginning of our decorated programs, we can express what it
means for a decorated program to be correct as follows: *)
Definition dec_correct (d:dcom) :=
{{pre d}} (extract d) {{post d}}.
(** To check whether this Hoare triple is _valid_, we need a way to
extract the "proof obligations" from a decorated program. These
obligations are often called _verification conditions_, because
they are the facts that must be verified to see that the
decorations are logically consistent and thus add up to a complete
proof of correctness. *)
(** ** Extracting Verification Conditions *)
(** The function [verification_conditions] takes a [dcom] [d] together
with a precondition [P] and returns a _proposition_ that, if it
can be proved, implies that the triple [{{P}} (extract d) {{post d}}]
is valid. *)
(** It does this by walking over [d] and generating a big
conjunction including all the "local checks" that we listed when
we described the informal rules for decorated programs. (Strictly
speaking, we need to massage the informal rules a little bit to
add some uses of the rule of consequence, but the correspondence
should be clear.) *)
Fixpoint verification_conditions (P : Assertion) (d:dcom) : Prop :=
match d with
| DCSkip Q =>
(P ->> Q)
| DCSeq d1 d2 =>
verification_conditions P d1
/\ verification_conditions (post d1) d2
| DCAsgn X a Q =>
(P ->> Q [X |-> a])
| DCIf b P1 d1 P2 d2 Q =>
((fun st => P st /\ bassn b st) ->> P1)
/\ ((fun st => P st /\ ~ (bassn b st)) ->> P2)
/\ (Q <<->> post d1) /\ (Q <<->> post d2)
/\ verification_conditions P1 d1
/\ verification_conditions P2 d2
| DCWhile b Pbody d Ppost =>
(* post d is the loop invariant and the initial precondition *)
(P ->> post d)
/\ (Pbody <<->> (fun st => post d st /\ bassn b st))
/\ (Ppost <<->> (fun st => post d st /\ ~(bassn b st)))
/\ verification_conditions Pbody d
| DCPre P' d =>
(P ->> P') /\ verification_conditions P' d
| DCPost d Q =>
verification_conditions P d /\ (post d ->> Q)
end.
(** And now, the key theorem, which states that
[verification_conditions] does its job correctly. Not
surprisingly, we need to use each of the Hoare Logic rules at some
point in the proof. *)
(** We have used _in_ variants of several tactics before to
apply them to values in the context rather than the goal. An
extension of this idea is the syntax [tactic in *], which applies
[tactic] in the goal and every hypothesis in the context. We most
commonly use this facility in conjunction with the [simpl] tactic,
as below. *)
Theorem verification_correct : forall d P,
verification_conditions P d -> {{P}} (extract d) {{post d}}.
Proof.
dcom_cases (induction d) Case; intros P H; simpl in *.
Case "Skip".
eapply hoare_consequence_pre.
apply hoare_skip.
assumption.
Case "Seq".
inversion H as [H1 H2]. clear H.
eapply hoare_seq.
apply IHd2. apply H2.
apply IHd1. apply H1.
Case "Asgn".
eapply hoare_consequence_pre.
apply hoare_asgn.
assumption.
Case "If".
inversion H as [HPre1 [HPre2 [[Hd11 Hd12]
[[Hd21 Hd22] [HThen HElse]]]]].
clear H.
apply IHd1 in HThen. clear IHd1.
apply IHd2 in HElse. clear IHd2.
apply hoare_if.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
Case "While".
inversion H as [Hpre [[Hbody1 Hbody2] [[Hpost1 Hpost2] Hd]]];
subst; clear H.
eapply hoare_consequence_pre; eauto.
eapply hoare_consequence_post; eauto.
apply hoare_while.
eapply hoare_consequence_pre; eauto.
Case "Pre".
inversion H as [HP Hd]; clear H.
eapply hoare_consequence_pre. apply IHd. apply Hd. assumption.
Case "Post".
inversion H as [Hd HQ]; clear H.
eapply hoare_consequence_post. apply IHd. apply Hd. assumption.
Qed.
(** ** Examples *)
(** The propositions generated by [verification_conditions] are fairly
big, and they contain many conjuncts that are essentially trivial. *)
Eval simpl in (verification_conditions (fun st => True) dec_while).
(**
==>
(((fun _ : state => True) ->> (fun _ : state => True)) /\
((fun _ : state => True) ->> (fun _ : state => True)) /\
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) =
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) =
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
(fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun _ : state => True) [X |-> AMinus (AId X) (ANum 1)]) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun st : state => st X = 0)
*)
(** In principle, we could certainly work with them using just the
tactics we have so far, but we can make things much smoother with
a bit of automation. We first define a custom [verify] tactic
that applies splitting repeatedly to turn all the conjunctions
into separate subgoals and then uses [omega] and [eauto] (a handy
general-purpose automation tactic that we'll discuss in detail
later) to deal with as many of them as possible. *)
Lemma ble_nat_true_iff : forall n m : nat,
ble_nat n m = true <-> n <= m.
Proof.
intros n m. split. apply ble_nat_true.
generalize dependent m. induction n; intros m H. reflexivity.
simpl. destruct m. inversion H.
apply le_S_n in H. apply IHn. assumption.
Qed.
Lemma ble_nat_false_iff : forall n m : nat,
ble_nat n m = false <-> ~(n <= m).
Proof.
intros n m. split. apply ble_nat_false.
generalize dependent m. induction n; intros m H.
apply ex_falso_quodlibet. apply H. apply le_0_n.
simpl. destruct m. reflexivity.
apply IHn. intro Hc. apply H. apply le_n_S. assumption.
Qed.
Tactic Notation "verify" :=
apply verification_correct;
repeat split;
simpl; unfold assert_implies;
unfold bassn in *; unfold beval in *; unfold aeval in *;
unfold assn_sub; intros;
repeat rewrite update_eq;
repeat (rewrite update_neq; [| (intro X; inversion X)]);
simpl in *;
repeat match goal with [H : _ /\ _ |- _] => destruct H end;
repeat rewrite not_true_iff_false in *;
repeat rewrite not_false_iff_true in *;
repeat rewrite negb_true_iff in *;
repeat rewrite negb_false_iff in *;
repeat rewrite beq_nat_true_iff in *;
repeat rewrite beq_nat_false_iff in *;
repeat rewrite ble_nat_true_iff in *;
repeat rewrite ble_nat_false_iff in *;
try subst;
repeat
match goal with
[st : state |- _] =>
match goal with
[H : st _ = _ |- _] => rewrite -> H in *; clear H
| [H : _ = st _ |- _] => rewrite <- H in *; clear H
end
end;
try eauto; try omega.
(** What's left after [verify] does its thing is "just the interesting
parts" of checking that the decorations are correct. For very
simple examples [verify] immediately solves the goal (provided
that the annotations are correct). *)
Theorem dec_while_correct :
dec_correct dec_while.
Proof. verify. Qed.
(** Another example (formalizing a decorated program we've seen
before): *)
Example subtract_slowly_dec (m:nat) (p:nat) : dcom := (
{{ fun st => st X = m /\ st Z = p }} ->>
{{ fun st => st Z - st X = p - m }}
WHILE BNot (BEq (AId X) (ANum 0))
DO {{ fun st => st Z - st X = p - m /\ st X <> 0 }} ->>
{{ fun st => (st Z - 1) - (st X - 1) = p - m }}
Z ::= AMinus (AId Z) (ANum 1)
{{ fun st => st Z - (st X - 1) = p - m }} ;;
X ::= AMinus (AId X) (ANum 1)
{{ fun st => st Z - st X = p - m }}
END
{{ fun st => st Z - st X = p - m /\ st X = 0 }} ->>
{{ fun st => st Z = p - m }}
) % dcom.
Theorem subtract_slowly_dec_correct : forall m p,
dec_correct (subtract_slowly_dec m p).
Proof. intros m p. verify. (* this grinds for a bit! *) Qed.
(** **** Exercise: 3 stars, advanced (slow_assignment_dec) *)
(** In the [slow_assignment] exercise above, we saw a roundabout way
of assigning a number currently stored in [X] to the variable [Y]:
start [Y] at [0], then decrement [X] until it hits [0],
incrementing [Y] at each step.
Write a _formal_ version of this decorated program and prove it
correct. *)
Example slow_assignment_dec (m:nat) : dcom :=
(* FILL IN HERE *) admit.
Theorem slow_assignment_dec_correct : forall m,
dec_correct (slow_assignment_dec m).
Proof. (* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 4 stars, advanced (factorial_dec) *)
(** Remember the factorial function we worked with before: *)
Fixpoint real_fact (n:nat) : nat :=
match n with
| O => 1
| S n' => n * (real_fact n')
end.
(** Following the pattern of [subtract_slowly_dec], write a decorated
program [factorial_dec] that implements the factorial function and
prove it correct as [factorial_dec_correct]. *)
(* FILL IN HERE *)
(** [] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
//-----------------------------------------------------------------------------
// The way that we connect things in low-frequency read mode. In this case
// we are generating the unmodulated low frequency carrier.
// The A/D samples at that same rate and the result is serialized.
//
// Jonathan Westhues, April 2006
// iZsh <izsh at fail0verflow.com>, June 2014
//-----------------------------------------------------------------------------
module lo_read(
input pck0, input [7:0] pck_cnt, input pck_divclk,
output pwr_lo, output pwr_hi,
output pwr_oe1, output pwr_oe2, output pwr_oe3, output pwr_oe4,
input [7:0] adc_d, output adc_clk,
output ssp_frame, output ssp_din, output ssp_clk,
output dbg,
input lf_field
);
reg [7:0] to_arm_shiftreg;
// this task also runs at pck0 frequency (24Mhz) and is used to serialize
// the ADC output which is then clocked into the ARM SSP.
// because pck_divclk always transitions when pck_cnt = 0 we use the
// pck_div counter to sync our other signals off it
// we read the ADC value when pck_cnt=7 and shift it out on counts 8..15
always @(posedge pck0)
begin
if((pck_cnt == 8'd7) && !pck_divclk)
to_arm_shiftreg <= adc_d;
else begin
to_arm_shiftreg[7:1] <= to_arm_shiftreg[6:0];
// simulation showed a glitch occuring due to the LSB of the shifter
// not being set as we shift bits out
// this ensures the ssp_din remains low after a transfer and suppresses
// the glitch that would occur when the last data shifted out ended in
// a 1 bit and the next data shifted out started with a 0 bit
to_arm_shiftreg[0] <= 1'b0;
end
end
// ADC samples on falling edge of adc_clk, data available on the rising edge
// example of ssp transfer of binary value 1100101
// start of transfer is indicated by the rise of the ssp_frame signal
// ssp_din changes on the rising edge of the ssp_clk clock and is clocked into
// the ARM by the falling edge of ssp_clk
// _______________________________
// ssp_frame__| |__
// _______ ___ ___
// ssp_din __| |_______| |___| |______
// _ _ _ _ _ _ _ _ _ _
// ssp_clk |_| |_| |_| |_| |_| |_| |_| |_| |_| |_
// serialized SSP data is gated by ant_lo to suppress unwanted signal
assign ssp_din = to_arm_shiftreg[7] && !pck_divclk;
// SSP clock always runs at 24Mhz
assign ssp_clk = pck0;
// SSP frame is gated by ant_lo and goes high when pck_divider=8..15
assign ssp_frame = (pck_cnt[7:3] == 5'd1) && !pck_divclk;
// unused signals tied low
assign pwr_hi = 1'b0;
assign pwr_oe1 = 1'b0;
assign pwr_oe2 = 1'b0;
assign pwr_oe3 = 1'b0;
assign pwr_oe4 = 1'b0;
// this is the antenna driver signal
assign pwr_lo = lf_field & pck_divclk;
// ADC clock out of phase with antenna driver
assign adc_clk = ~pck_divclk;
// ADC clock also routed to debug pin
assign dbg = adc_clk;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// A test of the +1364-1995ext+ and +systemverilogext+ flags.
//
// This source code contains constructs that are valid in SystemVerilog 2009
// but not in Verilog 1995. So it should fail if we set the language to be
// Verilog 1995, but not SystemVerilog 2009.
//
// Compile only test, so no need for "All Finished" output.
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Jeremy Bennett.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg [1:0] res;
// Instantiate the test
test test_i (/*AUTOINST*/
// Outputs
.res (res),
// Inputs
.clk (clk),
.in (1'b1));
endmodule
module test (// Outputs
res,
// Inputs
clk,
in
);
output [1:0] res;
input clk;
input in;
// This is a SystemVerilog 2009 only test
generate
genvar i;
for (i=0; i<2; i=i+1) begin
always @(posedge clk) begin
unique0 case (i)
0: res[0:0] <= in;
1: res[1:1] <= in;
endcase
end
end
endgenerate
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 11:05:40 09/06/2015
// Design Name:
// Module Name: Deco_Round_Mult
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Deco_Round_Mult(
input wire [1:0] round_mode,
input wire or_info, //23 less significant bits from the product of significands
input wire xor_info, //Brings information about the sign of the operation
output reg ctrl //control signal mux --- control of the rounded significand
);
always @*
case ({xor_info,or_info,round_mode})
// Round to infinity - (Round down)
//1'b0: Let pass the significand without rounding
//1'b1: Let pass the rounded significand
//Round towards - infinity
//0: positive number ; 01: Round towards - inifnity ; XX rounding bits
//Positive Number
//xor, or, round
4'b0101: ctrl <= 1'b0;
//Negative Number
4'b1101: ctrl <= 1'b1;
//Round towards + infinity
//Positive Number
4'b0110: ctrl <= 1'b1;
//Negative Number
4'b1110: ctrl <= 1'b0;
default: ctrl <= 1'b0; //Truncation
endcase
endmodule |
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 11:05:40 09/06/2015
// Design Name:
// Module Name: Deco_Round_Mult
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Deco_Round_Mult(
input wire [1:0] round_mode,
input wire or_info, //23 less significant bits from the product of significands
input wire xor_info, //Brings information about the sign of the operation
output reg ctrl //control signal mux --- control of the rounded significand
);
always @*
case ({xor_info,or_info,round_mode})
// Round to infinity - (Round down)
//1'b0: Let pass the significand without rounding
//1'b1: Let pass the rounded significand
//Round towards - infinity
//0: positive number ; 01: Round towards - inifnity ; XX rounding bits
//Positive Number
//xor, or, round
4'b0101: ctrl <= 1'b0;
//Negative Number
4'b1101: ctrl <= 1'b1;
//Round towards + infinity
//Positive Number
4'b0110: ctrl <= 1'b1;
//Negative Number
4'b1110: ctrl <= 1'b0;
default: ctrl <= 1'b0; //Truncation
endcase
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.out_modport),
.clk);
sub cb (.isub(itopb.out_modport),
.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.out_modport),
.clk);
sub cb (.isub(itopb.out_modport),
.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.out_modport),
.clk);
sub cb (.isub(itopb.out_modport),
.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.out_modport),
.clk);
sub cb (.isub(itopb.out_modport),
.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, 2012 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
`define checkh(gotv,expv) do if ((gotv) !== (expv)) begin $write("%%Error: %s:%0d: got='h%x exp='h%x\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
`define checkr(gotv,expv) do if ((gotv) != (expv)) begin $write("%%Error: %s:%0d: got=%g exp=%g\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
// IEEE: integer_atom_type
wire byte w_byte;
wire shortint w_shortint;
wire int w_int;
wire longint w_longint;
wire integer w_integer;
// IEEE: integer_atom_type
wire bit w_bit;
wire logic w_logic;
wire bit [1:0] w_bit2;
wire logic [1:0] w_logic2;
// IEEE: non_integer_type
//UNSUP shortreal w_shortreal;
wire real w_real;
assign w_byte = 8'h12;
assign w_shortint = 16'h1234;
assign w_int = -123456;
assign w_longint = -1234567;
assign w_integer = -123456;
assign w_bit = 1'b1;
assign w_logic = 1'b1;
assign w_bit2 = 2'b10;
assign w_logic2 = 2'b10;
assign w_real = 3.14;
always @ (posedge clk) begin
`checkh(w_byte, 8'h12);
`checkh(w_shortint, 16'h1234);
`checkh(w_int, -123456);
`checkh(w_longint, -1234567);
`checkh(w_integer, -123456);
`checkh(w_bit, 1'b1);
`checkh(w_logic, 1'b1);
`checkh(w_bit2, 2'b10);
`checkh(w_logic2, 2'b10);
`checkr(w_real, 3.14);
$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.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
`define checkh(gotv,expv) do if ((gotv) !== (expv)) begin $write("%%Error: %s:%0d: got='h%x exp='h%x\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
`define checkr(gotv,expv) do if ((gotv) != (expv)) begin $write("%%Error: %s:%0d: got=%g exp=%g\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
// IEEE: integer_atom_type
wire byte w_byte;
wire shortint w_shortint;
wire int w_int;
wire longint w_longint;
wire integer w_integer;
// IEEE: integer_atom_type
wire bit w_bit;
wire logic w_logic;
wire bit [1:0] w_bit2;
wire logic [1:0] w_logic2;
// IEEE: non_integer_type
//UNSUP shortreal w_shortreal;
wire real w_real;
assign w_byte = 8'h12;
assign w_shortint = 16'h1234;
assign w_int = -123456;
assign w_longint = -1234567;
assign w_integer = -123456;
assign w_bit = 1'b1;
assign w_logic = 1'b1;
assign w_bit2 = 2'b10;
assign w_logic2 = 2'b10;
assign w_real = 3.14;
always @ (posedge clk) begin
`checkh(w_byte, 8'h12);
`checkh(w_shortint, 16'h1234);
`checkh(w_int, -123456);
`checkh(w_longint, -1234567);
`checkh(w_integer, -123456);
`checkh(w_bit, 1'b1);
`checkh(w_logic, 1'b1);
`checkh(w_bit2, 2'b10);
`checkh(w_logic2, 2'b10);
`checkr(w_real, 3.14);
$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.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
`define checkh(gotv,expv) do if ((gotv) !== (expv)) begin $write("%%Error: %s:%0d: got='h%x exp='h%x\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
`define checkr(gotv,expv) do if ((gotv) != (expv)) begin $write("%%Error: %s:%0d: got=%g exp=%g\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
// IEEE: integer_atom_type
wire byte w_byte;
wire shortint w_shortint;
wire int w_int;
wire longint w_longint;
wire integer w_integer;
// IEEE: integer_atom_type
wire bit w_bit;
wire logic w_logic;
wire bit [1:0] w_bit2;
wire logic [1:0] w_logic2;
// IEEE: non_integer_type
//UNSUP shortreal w_shortreal;
wire real w_real;
assign w_byte = 8'h12;
assign w_shortint = 16'h1234;
assign w_int = -123456;
assign w_longint = -1234567;
assign w_integer = -123456;
assign w_bit = 1'b1;
assign w_logic = 1'b1;
assign w_bit2 = 2'b10;
assign w_logic2 = 2'b10;
assign w_real = 3.14;
always @ (posedge clk) begin
`checkh(w_byte, 8'h12);
`checkh(w_shortint, 16'h1234);
`checkh(w_int, -123456);
`checkh(w_longint, -1234567);
`checkh(w_integer, -123456);
`checkh(w_bit, 1'b1);
`checkh(w_logic, 1'b1);
`checkh(w_bit2, 2'b10);
`checkh(w_logic2, 2'b10);
`checkr(w_real, 3.14);
$write("*-* All Finished *-*\n");
$finish;
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: Posted Packet Builder module. This module takes the
// length info from the Posted Packet Slicer, and requests a tag from
// the Tag Generator and uses that info to build a posted memory write header
// which it writes into a FIFO
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module posted_pkt_builder(
input clk,
input rst,
input [15:0] req_id, //from pcie block
//to/from posted_pkt_slicer
input posted_fifo_full,
input go,
output reg ack,
input [63:0] dmawad,
input [9:0] length,
//to posted_pkt_header_fifo
output reg [63:0] header_data_out,
output reg header_data_wren
);
//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 MWr = 5'b00000; //format for memory write 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'b00; //no snoop or relaxed-ordering
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] dmawad_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] = (dmawad_reg[63:32] == 0) ? 2'b10 : 2'b11;
//if the posted_pkt_slicer asserts "go" then register the dma write params
always@(posedge clk)begin
if(rst_reg)begin
dmawad_reg[63:0] <= 0;
end else if(go)begin
dmawad_reg <= dmawad;
end
end
// State machine
// Builds headers for posted memory writes
// 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;
state <= IDLE;
end else begin
case (state)
IDLE : begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
if(go & ~posted_fifo_full) // Jiansong: prevent p_hdr_fifo overflow
state<= HEAD1;
else
state<= IDLE;
end
HEAD1 : begin
//write the first 64-bits of a posted header into the
//posted fifo
header_data_out <= {rsvd,fmt[1:0],MWr,rsvd,TC,rsvd,rsvd,rsvd,rsvd,
TD,EP,ATTR,rsvd,rsvd,length[9:0],req_id[15:0],
8'b00000000 ,LastBE,FirstBE};
ack <= 0;
header_data_wren <= 1'b1;
state <= HEAD2;
end
HEAD2 : begin
//write the next 32 or 64 bits of a posted header to the
//posted header fifo (32 if 3DW - 64 if 4DW header)
header_data_out <= (fmt[0]==1'b1)
? {dmawad_reg[63:2],2'b00}
: {dmawad_reg[31:2], 2'b00, dmawad_reg[63:32]};
header_data_wren <= 1'b1;
ack <= 1'b1; //acknowledge to the posted_packet_slicer that
//the packet has been queued up for transmission
state <= WAIT_FOR_GO_DEASSERT;
end
WAIT_FOR_GO_DEASSERT: begin
//ack causes "go" to deassert but we need to give the
//posted_pkt_slicer a chance to deassert "go" before returning
//to IDLE
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
state <= IDLE;
end
default : begin
header_data_out <= 0;
header_data_wren <= 1'b0;
ack <= 1'b0;
state <= IDLE;
end
endcase
end
end
endmodule
|
// DESCRIPTION: Verilator: System Verilog test of enumerated type methods
//
// This code exercises the various enumeration methods
//
// 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.
// **** Pin Identifiers ****
typedef enum int
{
PINID_A0 = 32'd0, // MUST BE ZERO!
// - Standard Ports -
PINID_A1, PINID_A2, PINID_A3, PINID_A4, PINID_A5, PINID_A6, PINID_A7,
PINID_B0, PINID_B1, PINID_B2, PINID_B3, PINID_B4, PINID_B5, PINID_B6, PINID_B7,
PINID_C0, PINID_C1, PINID_C2, PINID_C3, PINID_C4, PINID_C5, PINID_C6, PINID_C7,
PINID_D0, PINID_D1, PINID_D2, PINID_D3, PINID_D4, PINID_D5, PINID_D6, PINID_D7,
PINID_E0, PINID_E1, PINID_E2, PINID_E3, PINID_E4, PINID_E5, PINID_E6, PINID_E7,
PINID_F0, PINID_F1, PINID_F2, PINID_F3, PINID_F4, PINID_F5, PINID_F6, PINID_F7,
PINID_G0, PINID_G1, PINID_G2, PINID_G3, PINID_G4, PINID_G5, PINID_G6, PINID_G7,
PINID_H0, PINID_H1, PINID_H2, PINID_H3, PINID_H4, PINID_H5, PINID_H6, PINID_H7,
// PINID_I0, PINID_I1, PINID_I2, PINID_I3, PINID_I4, PINID_I5, PINID_I6, PINID_I7,-> DO NOT USE!!!! I == 1
PINID_J0, PINID_J1, PINID_J2, PINID_J3, PINID_J4, PINID_J5, PINID_J6, PINID_J7,
PINID_K0, PINID_K1, PINID_K2, PINID_K3, PINID_K4, PINID_K5, PINID_K6, PINID_K7,
PINID_L0, PINID_L1, PINID_L2, PINID_L3, PINID_L4, PINID_L5, PINID_L6, PINID_L7,
PINID_M0, PINID_M1, PINID_M2, PINID_M3, PINID_M4, PINID_M5, PINID_M6, PINID_M7,
PINID_N0, PINID_N1, PINID_N2, PINID_N3, PINID_N4, PINID_N5, PINID_N6, PINID_N7,
// PINID_O0, PINID_O1, PINID_O2, PINID_O3, PINID_O4, PINID_O5, PINID_O6, PINID_O7,-> DO NOT USE!!!! O == 0
PINID_P0, PINID_P1, PINID_P2, PINID_P3, PINID_P4, PINID_P5, PINID_P6, PINID_P7,
PINID_Q0, PINID_Q1, PINID_Q2, PINID_Q3, PINID_Q4, PINID_Q5, PINID_Q6, PINID_Q7,
PINID_R0, PINID_R1, PINID_R2, PINID_R3, PINID_R4, PINID_R5, PINID_R6, PINID_R7,
// - AUX Port (Custom) -
PINID_X0, PINID_X1, PINID_X2, PINID_X3, PINID_X4, PINID_X5, PINID_X6, PINID_X7,
// - PDI Port -
PINID_D2W_DAT, PINID_D2W_CLK,
// - Power Pins -
PINID_VDD0, PINID_VDD1, PINID_VDD2, PINID_VDD3,
PINID_GND0, PINID_GND1, PINID_GND2, PINID_GND3,
// - Maximum number of pins -
PINID_MAX
} t_pinid;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire a = clk;
wire b = 1'b0;
reg c;
test test_i (/*AUTOINST*/
// Inputs
.clk (clk));
// This is a compile time only test. Immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module test (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Use the enumeration size to initialize a dynamic array
t_pinid e;
int myarray1 [] = new [e.num];
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Enumeration has %d members\n", e.num);
`endif
e = e.first;
forever begin
myarray1[e] <= e.prev;
`ifdef TEST_VERBOSE
$write ("myarray1[%d] (enum %s) = %d\n", e, e.name, myarray1[e]);
`endif
if (e == e.last) begin
break;
end
else begin
e = e.next;
end
end
end
endmodule
|
// DESCRIPTION: Verilator: System Verilog test of enumerated type methods
//
// This code exercises the various enumeration methods
//
// 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.
// **** Pin Identifiers ****
typedef enum int
{
PINID_A0 = 32'd0, // MUST BE ZERO!
// - Standard Ports -
PINID_A1, PINID_A2, PINID_A3, PINID_A4, PINID_A5, PINID_A6, PINID_A7,
PINID_B0, PINID_B1, PINID_B2, PINID_B3, PINID_B4, PINID_B5, PINID_B6, PINID_B7,
PINID_C0, PINID_C1, PINID_C2, PINID_C3, PINID_C4, PINID_C5, PINID_C6, PINID_C7,
PINID_D0, PINID_D1, PINID_D2, PINID_D3, PINID_D4, PINID_D5, PINID_D6, PINID_D7,
PINID_E0, PINID_E1, PINID_E2, PINID_E3, PINID_E4, PINID_E5, PINID_E6, PINID_E7,
PINID_F0, PINID_F1, PINID_F2, PINID_F3, PINID_F4, PINID_F5, PINID_F6, PINID_F7,
PINID_G0, PINID_G1, PINID_G2, PINID_G3, PINID_G4, PINID_G5, PINID_G6, PINID_G7,
PINID_H0, PINID_H1, PINID_H2, PINID_H3, PINID_H4, PINID_H5, PINID_H6, PINID_H7,
// PINID_I0, PINID_I1, PINID_I2, PINID_I3, PINID_I4, PINID_I5, PINID_I6, PINID_I7,-> DO NOT USE!!!! I == 1
PINID_J0, PINID_J1, PINID_J2, PINID_J3, PINID_J4, PINID_J5, PINID_J6, PINID_J7,
PINID_K0, PINID_K1, PINID_K2, PINID_K3, PINID_K4, PINID_K5, PINID_K6, PINID_K7,
PINID_L0, PINID_L1, PINID_L2, PINID_L3, PINID_L4, PINID_L5, PINID_L6, PINID_L7,
PINID_M0, PINID_M1, PINID_M2, PINID_M3, PINID_M4, PINID_M5, PINID_M6, PINID_M7,
PINID_N0, PINID_N1, PINID_N2, PINID_N3, PINID_N4, PINID_N5, PINID_N6, PINID_N7,
// PINID_O0, PINID_O1, PINID_O2, PINID_O3, PINID_O4, PINID_O5, PINID_O6, PINID_O7,-> DO NOT USE!!!! O == 0
PINID_P0, PINID_P1, PINID_P2, PINID_P3, PINID_P4, PINID_P5, PINID_P6, PINID_P7,
PINID_Q0, PINID_Q1, PINID_Q2, PINID_Q3, PINID_Q4, PINID_Q5, PINID_Q6, PINID_Q7,
PINID_R0, PINID_R1, PINID_R2, PINID_R3, PINID_R4, PINID_R5, PINID_R6, PINID_R7,
// - AUX Port (Custom) -
PINID_X0, PINID_X1, PINID_X2, PINID_X3, PINID_X4, PINID_X5, PINID_X6, PINID_X7,
// - PDI Port -
PINID_D2W_DAT, PINID_D2W_CLK,
// - Power Pins -
PINID_VDD0, PINID_VDD1, PINID_VDD2, PINID_VDD3,
PINID_GND0, PINID_GND1, PINID_GND2, PINID_GND3,
// - Maximum number of pins -
PINID_MAX
} t_pinid;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire a = clk;
wire b = 1'b0;
reg c;
test test_i (/*AUTOINST*/
// Inputs
.clk (clk));
// This is a compile time only test. Immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module test (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Use the enumeration size to initialize a dynamic array
t_pinid e;
int myarray1 [] = new [e.num];
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Enumeration has %d members\n", e.num);
`endif
e = e.first;
forever begin
myarray1[e] <= e.prev;
`ifdef TEST_VERBOSE
$write ("myarray1[%d] (enum %s) = %d\n", e, e.name, myarray1[e]);
`endif
if (e == e.last) begin
break;
end
else begin
e = e.next;
end
end
end
endmodule
|
// DESCRIPTION: Verilator: System Verilog test of enumerated type methods
//
// This code exercises the various enumeration methods
//
// 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.
// **** Pin Identifiers ****
typedef enum int
{
PINID_A0 = 32'd0, // MUST BE ZERO!
// - Standard Ports -
PINID_A1, PINID_A2, PINID_A3, PINID_A4, PINID_A5, PINID_A6, PINID_A7,
PINID_B0, PINID_B1, PINID_B2, PINID_B3, PINID_B4, PINID_B5, PINID_B6, PINID_B7,
PINID_C0, PINID_C1, PINID_C2, PINID_C3, PINID_C4, PINID_C5, PINID_C6, PINID_C7,
PINID_D0, PINID_D1, PINID_D2, PINID_D3, PINID_D4, PINID_D5, PINID_D6, PINID_D7,
PINID_E0, PINID_E1, PINID_E2, PINID_E3, PINID_E4, PINID_E5, PINID_E6, PINID_E7,
PINID_F0, PINID_F1, PINID_F2, PINID_F3, PINID_F4, PINID_F5, PINID_F6, PINID_F7,
PINID_G0, PINID_G1, PINID_G2, PINID_G3, PINID_G4, PINID_G5, PINID_G6, PINID_G7,
PINID_H0, PINID_H1, PINID_H2, PINID_H3, PINID_H4, PINID_H5, PINID_H6, PINID_H7,
// PINID_I0, PINID_I1, PINID_I2, PINID_I3, PINID_I4, PINID_I5, PINID_I6, PINID_I7,-> DO NOT USE!!!! I == 1
PINID_J0, PINID_J1, PINID_J2, PINID_J3, PINID_J4, PINID_J5, PINID_J6, PINID_J7,
PINID_K0, PINID_K1, PINID_K2, PINID_K3, PINID_K4, PINID_K5, PINID_K6, PINID_K7,
PINID_L0, PINID_L1, PINID_L2, PINID_L3, PINID_L4, PINID_L5, PINID_L6, PINID_L7,
PINID_M0, PINID_M1, PINID_M2, PINID_M3, PINID_M4, PINID_M5, PINID_M6, PINID_M7,
PINID_N0, PINID_N1, PINID_N2, PINID_N3, PINID_N4, PINID_N5, PINID_N6, PINID_N7,
// PINID_O0, PINID_O1, PINID_O2, PINID_O3, PINID_O4, PINID_O5, PINID_O6, PINID_O7,-> DO NOT USE!!!! O == 0
PINID_P0, PINID_P1, PINID_P2, PINID_P3, PINID_P4, PINID_P5, PINID_P6, PINID_P7,
PINID_Q0, PINID_Q1, PINID_Q2, PINID_Q3, PINID_Q4, PINID_Q5, PINID_Q6, PINID_Q7,
PINID_R0, PINID_R1, PINID_R2, PINID_R3, PINID_R4, PINID_R5, PINID_R6, PINID_R7,
// - AUX Port (Custom) -
PINID_X0, PINID_X1, PINID_X2, PINID_X3, PINID_X4, PINID_X5, PINID_X6, PINID_X7,
// - PDI Port -
PINID_D2W_DAT, PINID_D2W_CLK,
// - Power Pins -
PINID_VDD0, PINID_VDD1, PINID_VDD2, PINID_VDD3,
PINID_GND0, PINID_GND1, PINID_GND2, PINID_GND3,
// - Maximum number of pins -
PINID_MAX
} t_pinid;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire a = clk;
wire b = 1'b0;
reg c;
test test_i (/*AUTOINST*/
// Inputs
.clk (clk));
// This is a compile time only test. Immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module test (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Use the enumeration size to initialize a dynamic array
t_pinid e;
int myarray1 [] = new [e.num];
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Enumeration has %d members\n", e.num);
`endif
e = e.first;
forever begin
myarray1[e] <= e.prev;
`ifdef TEST_VERBOSE
$write ("myarray1[%d] (enum %s) = %d\n", e, e.name, myarray1[e]);
`endif
if (e == e.last) begin
break;
end
else begin
e = e.next;
end
end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2003-2007 by Wilson Snyder.
`define zednkw 200
module BreadAddrDP (zfghtn, cjtmau, vipmpg, knquim, kqxkkr);
input zfghtn;
input [4:0] cjtmau;
input vipmpg;
input [7:0] knquim;
input [7:0] kqxkkr;
reg covfok;
reg [15:0] xwieqw;
reg [2:0] ofnjjt;
reg [37:0] hdsejo[1:0];
reg wxxzgd, tceppr, ratebp, fjizkr, iwwrnq;
reg vrqrih, ryyjxy;
reg fgzsox;
wire xdjikl = ~wxxzgd & ~tceppr & ~ratebp & fjizkr;
wire iytyol = ~wxxzgd & ~tceppr & ratebp & ~fjizkr & ~xwieqw[10];
wire dywooz = ~wxxzgd & ~tceppr & ratebp & ~fjizkr & xwieqw[10];
wire qnpfus = ~wxxzgd & ~tceppr & ratebp & fjizkr;
wire fqlkrg = ~wxxzgd & tceppr & ~ratebp & ~fjizkr;
wire ktsveg = hdsejo[0][6] | (hdsejo[0][37:34] == 4'h1);
wire smxixw = vrqrih | (ryyjxy & ktsveg);
wire [7:0] grvsrs, kyxrft, uxhkka;
wire [7:0] eianuv = 8'h01 << ofnjjt;
wire [7:0] jvpnxn = {8{qnpfus}} & eianuv;
wire [7:0] zlnzlj = {8{fqlkrg}} & eianuv;
wire [7:0] nahzat = {8{iytyol}} & eianuv;
genvar i;
generate
for (i=0;i<8;i=i+1)
begin : dnlpyw
DecCountReg4 bzpytc (zfghtn, fgzsox, zlnzlj[i],
knquim[3:0], covfok, grvsrs[i]);
DecCountReg4 oghukp (zfghtn, fgzsox, zlnzlj[i],
knquim[7:4], covfok, kyxrft[i]);
DecCountReg4 ttvjoo (zfghtn, fgzsox, nahzat[i],
kqxkkr[3:0], covfok, uxhkka[i]);
end
endgenerate
endmodule
module DecCountReg4 (clk, fgzsox, fckiyr, uezcjy, covfok, juvlsh);
input clk, fgzsox, fckiyr, covfok;
input [3:0] uezcjy;
output juvlsh;
task Xinit;
begin
`ifdef TEST_HARNESS
khgawe = 1'b0;
`endif
end
endtask
function X;
input vrdejo;
begin
`ifdef TEST_HARNESS
if ((vrdejo & ~vrdejo) !== 1'h0) khgawe = 1'b1;
`endif
X = vrdejo;
end
endfunction
task Xcheck;
input vzpwwy;
begin
end
endtask
reg [3:0] udbvtl;
assign juvlsh = |udbvtl;
wire [3:0] mppedc = {4{fgzsox}} & (fckiyr ? uezcjy : (udbvtl - 4'h1));
wire qqibou = ((juvlsh | fckiyr) & covfok) | ~fgzsox;
always @(posedge clk)
begin
Xinit;
if (X(qqibou))
udbvtl <= #`zednkw mppedc;
Xcheck(fgzsox);
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2003-2007 by Wilson Snyder.
`define zednkw 200
module BreadAddrDP (zfghtn, cjtmau, vipmpg, knquim, kqxkkr);
input zfghtn;
input [4:0] cjtmau;
input vipmpg;
input [7:0] knquim;
input [7:0] kqxkkr;
reg covfok;
reg [15:0] xwieqw;
reg [2:0] ofnjjt;
reg [37:0] hdsejo[1:0];
reg wxxzgd, tceppr, ratebp, fjizkr, iwwrnq;
reg vrqrih, ryyjxy;
reg fgzsox;
wire xdjikl = ~wxxzgd & ~tceppr & ~ratebp & fjizkr;
wire iytyol = ~wxxzgd & ~tceppr & ratebp & ~fjizkr & ~xwieqw[10];
wire dywooz = ~wxxzgd & ~tceppr & ratebp & ~fjizkr & xwieqw[10];
wire qnpfus = ~wxxzgd & ~tceppr & ratebp & fjizkr;
wire fqlkrg = ~wxxzgd & tceppr & ~ratebp & ~fjizkr;
wire ktsveg = hdsejo[0][6] | (hdsejo[0][37:34] == 4'h1);
wire smxixw = vrqrih | (ryyjxy & ktsveg);
wire [7:0] grvsrs, kyxrft, uxhkka;
wire [7:0] eianuv = 8'h01 << ofnjjt;
wire [7:0] jvpnxn = {8{qnpfus}} & eianuv;
wire [7:0] zlnzlj = {8{fqlkrg}} & eianuv;
wire [7:0] nahzat = {8{iytyol}} & eianuv;
genvar i;
generate
for (i=0;i<8;i=i+1)
begin : dnlpyw
DecCountReg4 bzpytc (zfghtn, fgzsox, zlnzlj[i],
knquim[3:0], covfok, grvsrs[i]);
DecCountReg4 oghukp (zfghtn, fgzsox, zlnzlj[i],
knquim[7:4], covfok, kyxrft[i]);
DecCountReg4 ttvjoo (zfghtn, fgzsox, nahzat[i],
kqxkkr[3:0], covfok, uxhkka[i]);
end
endgenerate
endmodule
module DecCountReg4 (clk, fgzsox, fckiyr, uezcjy, covfok, juvlsh);
input clk, fgzsox, fckiyr, covfok;
input [3:0] uezcjy;
output juvlsh;
task Xinit;
begin
`ifdef TEST_HARNESS
khgawe = 1'b0;
`endif
end
endtask
function X;
input vrdejo;
begin
`ifdef TEST_HARNESS
if ((vrdejo & ~vrdejo) !== 1'h0) khgawe = 1'b1;
`endif
X = vrdejo;
end
endfunction
task Xcheck;
input vzpwwy;
begin
end
endtask
reg [3:0] udbvtl;
assign juvlsh = |udbvtl;
wire [3:0] mppedc = {4{fgzsox}} & (fckiyr ? uezcjy : (udbvtl - 4'h1));
wire qqibou = ((juvlsh | fckiyr) & covfok) | ~fgzsox;
always @(posedge clk)
begin
Xinit;
if (X(qqibou))
udbvtl <= #`zednkw mppedc;
Xcheck(fgzsox);
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: Detects rising edge of input signal and outputs a single-shot
// signal upon detection
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module rising_edge_detect(
input clk,
input rst,
input in,
output one_shot_out);
reg in_reg;
//register the input
always@(posedge clk)begin
if(rst)begin
in_reg <= 1'b0;
end else begin
in_reg <= in;
end
end
//detect the rising edge
assign one_shot_out = ~in_reg & in;
endmodule
|
// DESCRIPTION: Verilator: Test generate index usage.
//
// The code illustrates a problem in Verilator's handling of constant
// expressions inside generate indexes.
//
// This is a regression test against issue 517.
//
// **If you do not wish for your code to be released to the public
// please note it here, otherwise:**
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Jeremy Bennett.
`define START 8
`define SIZE 4
`define END (`START + `SIZE)
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg [`END-1:0] y;
wire [`END-1:0] x;
foo foo_i (.y (y),
.x (x),
.clk (clk));
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule // t
module foo(output wire [`END-1:0] y,
input wire [`END-1:0] x,
input wire clk);
function peek_bar;
peek_bar = bar_inst[`START].i_bar.r; // this is ok
peek_bar = bar_inst[`START + 1].i_bar.r; // this fails, should not.
endfunction
genvar g;
generate
for (g = `START; g < `END; g = g + 1) begin: bar_inst
bar i_bar(.x (x[g]),
.y (y[g]),
.clk (clk));
end
endgenerate
endmodule : foo
module bar(output wire y,
input wire x,
input wire clk);
reg r = 0;
assign y = r;
always @(posedge clk) begin
r = x ? ~x : y;
end
endmodule : bar
|
// DESCRIPTION::Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
module t;
`define checkh(gotv,expv) do if ((gotv) !== (expv)) begin $write("%%Error: %s:%0d: got='h%x exp='h%x\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
typedef enum logic [1:0]
{ ZERO = 2'd0,
ONE = 2'd1,
TWO = 2'd2,
THREE = 2'd3,
XXX = 2'dx
} num_t;
function automatic logic is_odd;
input en;
input num_t number;
case (en)
1'b1: begin
unique if (number inside {ONE, THREE})
is_odd = 1'b1;
else if (number inside {ZERO, TWO})
is_odd = 1'b0;
else
is_odd = 1'bx;
end
1'b0: is_odd = 1'bx;
default: is_odd = 1'bx;
endcase
endfunction
initial begin
`checkh ((4'd4 inside {4'd1,4'd5}), 1'b0);
`checkh ((4'd4 inside {4'd1,4'd4}), 1'b1);
//
`checkh ((4'b1011 inside {4'b1001}), 1'b0);
`checkh ((4'b1011 inside {4'b1xx1}), 1'b1); // Uses ==?
`checkh ((4'b1001 inside {4'b1xx1}), 1'b1); // Uses ==?
`checkh ((4'b1001 inside {4'b1??1}), 1'b1);
`ifndef VERILATOR
`checkh ((4'b1z11 inside {4'b11?1, 4'b1011}),1'bx);
`endif
// Range
`checkh ((4'd4 inside {[4'd5:4'd3], [4'd10:4'd8]}), 1'b0); // If left of colon < never matches
`checkh ((4'd3 inside {[4'd1:4'd2], [4'd3:4'd5]}), 1'b1);
`checkh ((4'd4 inside {[4'd1:4'd2], [4'd3:4'd5]}), 1'b1);
`checkh ((4'd5 inside {[4'd1:4'd2], [4'd3:4'd5]}), 1'b1);
//
// Unsupported $ bound
//
// Unsupported if unpacked array, elements tranversed
//int unpackedarray [$] = '{8,9};
//( expr inside {2, 3, unpackedarray}) // { 2,3,8,9}
//
`checkh (is_odd(1'b1, ZERO), 1'd0);
`checkh (is_odd(1'b1, ONE), 1'd1);
`checkh (is_odd(1'b1, TWO), 1'd0);
`checkh (is_odd(1'b1, THREE),1'd1);
`ifndef VERILATOR
`checkh (is_odd(1'b1, XXX), 1'dx);
`endif
//
$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, 2013 by Alex Solomatnikov.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
logic [6-1:0] foo[4-1:0];
//initial $display("%m: %p\n", foo);
//initial $display("%m: %p\n", foo[3:0]); // VCS not supported %p with slice
//logic [6-1:0] foo2[4-1:0][5:6];
//initial $display("%m: %p\n", foo2[3:0][5:6]); // This is not legal
dut #(.W(6),
.D(4)) udut(.clk(clk),
.foo(foo[4-1:0]));
endmodule
module dut
#(parameter W = 1,
parameter D = 1)
(input logic clk,
input logic [W-1:0] foo[D-1:0]);
genvar i, j;
generate
for (j = 0; j < D; j++) begin
for (i = 0; i < W; i++) begin
suba ua(.clk(clk), .foo(foo[j][i]));
end
end
endgenerate
endmodule
module suba
(input logic clk,
input logic foo);
always @(posedge clk) begin
$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, 2013 by Alex Solomatnikov.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
logic [6-1:0] foo[4-1:0];
//initial $display("%m: %p\n", foo);
//initial $display("%m: %p\n", foo[3:0]); // VCS not supported %p with slice
//logic [6-1:0] foo2[4-1:0][5:6];
//initial $display("%m: %p\n", foo2[3:0][5:6]); // This is not legal
dut #(.W(6),
.D(4)) udut(.clk(clk),
.foo(foo[4-1:0]));
endmodule
module dut
#(parameter W = 1,
parameter D = 1)
(input logic clk,
input logic [W-1:0] foo[D-1:0]);
genvar i, j;
generate
for (j = 0; j < D; j++) begin
for (i = 0; i < W; i++) begin
suba ua(.clk(clk), .foo(foo[j][i]));
end
end
endgenerate
endmodule
module suba
(input logic clk,
input logic foo);
always @(posedge clk) begin
$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, 2013 by Wilson Snyder.
module t (/*AUTOARG*/);
typedef struct packed {
logic [3:2] a;
logic [5:4][3:2] b;
} ab_t;
typedef ab_t [7:6] c_t; // array of structs
typedef struct packed {
c_t [17:16] d;
} e_t;
`define checkb(gotv,expv) do if ((gotv) !== (expv)) begin $write("%%Error: %s:%0d: got='b%x exp='b%x\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
`define checkh(gotv,expv) do if ((gotv) !== (expv)) begin $write("%%Error: %s:%0d: got='h%x exp='h%x\n", `__FILE__,`__LINE__, (gotv), (expv)); $stop; end while(0);
initial begin
e_t e;
`checkh($bits(ab_t),6);
`checkh($bits(c_t),12);
`checkh($bits(e_t),24);
`checkh($bits(e), 24);
`checkh($bits(e.d[17]),12);
`checkh($bits(e.d[16][6]),6);
`checkh($bits(e.d[16][6].b[5]),2);
`checkh($bits(e.d[16][6].b[5][2]), 1);
//
e = 24'b101101010111010110101010;
`checkb(e, 24'b101101010111010110101010);
e.d[17] = 12'b111110011011;
`checkb(e, 24'b111110011011010110101010);
e.d[16][6] = 6'b010101;
`checkb(e, 24'b111110011011010110010101);
e.d[16][6].b[5] = 2'b10;
`checkb(e, 24'b111110011011010110011001);
e.d[16][6].b[5][2] = 1'b1;
//
$write("*-* All Finished *-*\n");
$finish;
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.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 14:54:18 08/11/2009
// Design Name:
// Module Name: STATUS_OUT
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////
///// Generate four patterns for specific states
///// Idle 00000000
///// Reset 01010101
///// FIFO full 00001111
///// Training_done 00110011
/////
/////////////////////////////////////////////////////////////////////////////////
module RCB_FRL_STATUS_OUT( CLK,
RESET, // input indicating whether channel is reset, reset pulse of the whole lvds channel
MODULE_RST, // reset pulse for this module only, should be shorter than RESET
FIFO_FULL, // input indicating whether FIFO is FULL
TRAINING_DONE, // input indicating whether TRAINING is done
STATUS,
INT_SAT // coded status output
);
/////////////////////////////////////////////////////////////////////////////////
input CLK;
input MODULE_RST;
input RESET,
FIFO_FULL,
TRAINING_DONE;
output STATUS;
/////////////////////////////////////////////////////////////////////////////////
reg STATUS;
output reg [1:0] INT_SAT;
parameter RST = 2'b00;
parameter FULL = 2'b01;
parameter DONE = 2'b10;
parameter IDLE = 2'b11;
reg [2:0] counter;
wire MODULE_RST_one;
rising_edge_detect MODULE_RESET_one_inst(
.clk(CLK),
.rst(1'b0),
.in(MODULE_RST),
.one_shot_out(MODULE_RST_one)
);
/////////////////////////////////////////////////////////////////////////////////
/// Determine which state it is
always @ ( posedge CLK ) begin
if ( counter == 3'b000 ) begin
if ( RESET == 1'b1 ) begin
INT_SAT <= RST;
end
else if ( FIFO_FULL == 1'b1 & TRAINING_DONE == 1'b1 ) begin
INT_SAT <= FULL;
end
else if ( TRAINING_DONE == 1'b1 ) begin
INT_SAT <= DONE;
end
else begin
INT_SAT <= IDLE;
end
end
end
/////////////////////////////////////////////////////////////////////////////////
/// Counter runs
always @ ( posedge CLK ) begin
// if ( MODULE_RST == 1'b1 ) begin // Jiansong: how can it send out reset status
if ( MODULE_RST_one == 1'b1 ) begin
counter <= 3'b000;
end
else begin
counter <= counter + 3'b001;
end
end
/////////////////////////////////////////////////////////////////////////////////
/// pattern encode
/// Idle 00000000
/// Reset 01010101
/// FIFO_full 00001111
/// Train Done 00110011
always @ ( posedge CLK) begin
if ( INT_SAT == RST ) begin
if ( counter == 3'b000 | counter == 3'b010 | counter == 3'b100 | counter == 3'b110 ) begin
STATUS <= 1'b0;
end
else if (counter == 3'b001 | counter == 3'b011 | counter == 3'b101 | counter == 3'b111 ) begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == FULL) begin
if (counter == 3'b000 | counter == 3'b001 | counter == 3'b010 | counter == 3'b011 ) begin
STATUS <= 1'b0;
end
else if ( counter == 3'b100 | counter == 3'b101 | counter == 3'b110 | counter == 3'b111 ) begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == DONE) begin
if ( counter == 3'b000 | counter == 3'b001 | counter == 3'b100 | counter == 3'b101 ) begin
STATUS <= 1'b0;
end
else if ( counter == 3'b010 | counter == 3'b011 | counter == 3'b110 | counter == 3'b111 )begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == IDLE) begin
STATUS <= 1'b0;
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.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 14:54:18 08/11/2009
// Design Name:
// Module Name: STATUS_OUT
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////
///// Generate four patterns for specific states
///// Idle 00000000
///// Reset 01010101
///// FIFO full 00001111
///// Training_done 00110011
/////
/////////////////////////////////////////////////////////////////////////////////
module RCB_FRL_STATUS_OUT( CLK,
RESET, // input indicating whether channel is reset, reset pulse of the whole lvds channel
MODULE_RST, // reset pulse for this module only, should be shorter than RESET
FIFO_FULL, // input indicating whether FIFO is FULL
TRAINING_DONE, // input indicating whether TRAINING is done
STATUS,
INT_SAT // coded status output
);
/////////////////////////////////////////////////////////////////////////////////
input CLK;
input MODULE_RST;
input RESET,
FIFO_FULL,
TRAINING_DONE;
output STATUS;
/////////////////////////////////////////////////////////////////////////////////
reg STATUS;
output reg [1:0] INT_SAT;
parameter RST = 2'b00;
parameter FULL = 2'b01;
parameter DONE = 2'b10;
parameter IDLE = 2'b11;
reg [2:0] counter;
wire MODULE_RST_one;
rising_edge_detect MODULE_RESET_one_inst(
.clk(CLK),
.rst(1'b0),
.in(MODULE_RST),
.one_shot_out(MODULE_RST_one)
);
/////////////////////////////////////////////////////////////////////////////////
/// Determine which state it is
always @ ( posedge CLK ) begin
if ( counter == 3'b000 ) begin
if ( RESET == 1'b1 ) begin
INT_SAT <= RST;
end
else if ( FIFO_FULL == 1'b1 & TRAINING_DONE == 1'b1 ) begin
INT_SAT <= FULL;
end
else if ( TRAINING_DONE == 1'b1 ) begin
INT_SAT <= DONE;
end
else begin
INT_SAT <= IDLE;
end
end
end
/////////////////////////////////////////////////////////////////////////////////
/// Counter runs
always @ ( posedge CLK ) begin
// if ( MODULE_RST == 1'b1 ) begin // Jiansong: how can it send out reset status
if ( MODULE_RST_one == 1'b1 ) begin
counter <= 3'b000;
end
else begin
counter <= counter + 3'b001;
end
end
/////////////////////////////////////////////////////////////////////////////////
/// pattern encode
/// Idle 00000000
/// Reset 01010101
/// FIFO_full 00001111
/// Train Done 00110011
always @ ( posedge CLK) begin
if ( INT_SAT == RST ) begin
if ( counter == 3'b000 | counter == 3'b010 | counter == 3'b100 | counter == 3'b110 ) begin
STATUS <= 1'b0;
end
else if (counter == 3'b001 | counter == 3'b011 | counter == 3'b101 | counter == 3'b111 ) begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == FULL) begin
if (counter == 3'b000 | counter == 3'b001 | counter == 3'b010 | counter == 3'b011 ) begin
STATUS <= 1'b0;
end
else if ( counter == 3'b100 | counter == 3'b101 | counter == 3'b110 | counter == 3'b111 ) begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == DONE) begin
if ( counter == 3'b000 | counter == 3'b001 | counter == 3'b100 | counter == 3'b101 ) begin
STATUS <= 1'b0;
end
else if ( counter == 3'b010 | counter == 3'b011 | counter == 3'b110 | counter == 3'b111 )begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == IDLE) begin
STATUS <= 1'b0;
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.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 14:54:18 08/11/2009
// Design Name:
// Module Name: STATUS_OUT
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////
///// Generate four patterns for specific states
///// Idle 00000000
///// Reset 01010101
///// FIFO full 00001111
///// Training_done 00110011
/////
/////////////////////////////////////////////////////////////////////////////////
module RCB_FRL_STATUS_OUT( CLK,
RESET, // input indicating whether channel is reset, reset pulse of the whole lvds channel
MODULE_RST, // reset pulse for this module only, should be shorter than RESET
FIFO_FULL, // input indicating whether FIFO is FULL
TRAINING_DONE, // input indicating whether TRAINING is done
STATUS,
INT_SAT // coded status output
);
/////////////////////////////////////////////////////////////////////////////////
input CLK;
input MODULE_RST;
input RESET,
FIFO_FULL,
TRAINING_DONE;
output STATUS;
/////////////////////////////////////////////////////////////////////////////////
reg STATUS;
output reg [1:0] INT_SAT;
parameter RST = 2'b00;
parameter FULL = 2'b01;
parameter DONE = 2'b10;
parameter IDLE = 2'b11;
reg [2:0] counter;
wire MODULE_RST_one;
rising_edge_detect MODULE_RESET_one_inst(
.clk(CLK),
.rst(1'b0),
.in(MODULE_RST),
.one_shot_out(MODULE_RST_one)
);
/////////////////////////////////////////////////////////////////////////////////
/// Determine which state it is
always @ ( posedge CLK ) begin
if ( counter == 3'b000 ) begin
if ( RESET == 1'b1 ) begin
INT_SAT <= RST;
end
else if ( FIFO_FULL == 1'b1 & TRAINING_DONE == 1'b1 ) begin
INT_SAT <= FULL;
end
else if ( TRAINING_DONE == 1'b1 ) begin
INT_SAT <= DONE;
end
else begin
INT_SAT <= IDLE;
end
end
end
/////////////////////////////////////////////////////////////////////////////////
/// Counter runs
always @ ( posedge CLK ) begin
// if ( MODULE_RST == 1'b1 ) begin // Jiansong: how can it send out reset status
if ( MODULE_RST_one == 1'b1 ) begin
counter <= 3'b000;
end
else begin
counter <= counter + 3'b001;
end
end
/////////////////////////////////////////////////////////////////////////////////
/// pattern encode
/// Idle 00000000
/// Reset 01010101
/// FIFO_full 00001111
/// Train Done 00110011
always @ ( posedge CLK) begin
if ( INT_SAT == RST ) begin
if ( counter == 3'b000 | counter == 3'b010 | counter == 3'b100 | counter == 3'b110 ) begin
STATUS <= 1'b0;
end
else if (counter == 3'b001 | counter == 3'b011 | counter == 3'b101 | counter == 3'b111 ) begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == FULL) begin
if (counter == 3'b000 | counter == 3'b001 | counter == 3'b010 | counter == 3'b011 ) begin
STATUS <= 1'b0;
end
else if ( counter == 3'b100 | counter == 3'b101 | counter == 3'b110 | counter == 3'b111 ) begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == DONE) begin
if ( counter == 3'b000 | counter == 3'b001 | counter == 3'b100 | counter == 3'b101 ) begin
STATUS <= 1'b0;
end
else if ( counter == 3'b010 | counter == 3'b011 | counter == 3'b110 | counter == 3'b111 )begin
STATUS <= 1'b1;
end
end
else if ( INT_SAT == IDLE) begin
STATUS <= 1'b0;
end
end
endmodule
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Lane Brooks
module t (clk);
input clk;
reg [31:0] state; initial state=0;
wire A = state[0];
wire OE = state[1];
wire Z1, Z2, Z3, Z4, Z5, Z6, Z7, Z8, Z9;
wire [3:0] Z10;
wire Z11;
Test1 test1(/*AUTOINST*/
// Inouts
.Z1 (Z1),
// Inputs
.OE (OE),
.A (A));
Test2 test2(/*AUTOINST*/
// Inouts
.Z2 (Z2),
// Inputs
.OE (OE),
.A (A));
Test3 test3(/*AUTOINST*/
// Inouts
.Z3 (Z3),
// Inputs
.OE (OE),
.A (A));
Test4 test4(/*AUTOINST*/
// Outputs
.Z4 (Z4),
// Inouts
.Z5 (Z5));
Test5 test5(/*AUTOINST*/
// Inouts
.Z6 (Z6),
.Z7 (Z7),
.Z8 (Z8),
.Z9 (Z9),
// Inputs
.OE (OE));
Test6 test6(/*AUTOINST*/
// Inouts
.Z10 (Z10[3:0]),
// Inputs
.OE (OE));
Test7 test7(/*AUTOINST*/
// Outputs
.Z11 (Z11),
// Inputs
.state (state[2:0]));
always @(posedge clk) begin
state <= state + 1;
`ifdef TEST_VERBOSE
$write("[%0t] state=%d Z1=%b 2=%b 3=%b 4=%b 5=%b 6=%b 7=%b 8=%b 9=%b 10=%b 11=%b\n",
$time, state, Z1,Z2,Z3,Z4,Z5,Z6,Z7,Z8,Z9,Z10,Z11);
`endif
if(state == 0) begin
if(Z1 !== 1'b1) $stop; // tests pullups
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b1) $stop;
if(Z7 !== 1'b0) $stop;
if(Z8 !== 1'b0) $stop;
if(Z9 !== 1'b1) $stop;
if(Z10 !== 4'b0001) $stop;
if(Z11 !== 1'b0) $stop;
end
else if(state == 1) begin
if(Z1 !== 1'b1) $stop; // tests pullup
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b1) $stop;
if(Z7 !== 1'b0) $stop;
if(Z8 !== 1'b0) $stop;
if(Z9 !== 1'b1) $stop;
if(Z10 !== 4'b0001) $stop;
if(Z11 !== 1'b1) $stop;
end
else if(state == 2) begin
if(Z1 !== 1'b0) $stop; // tests output driver low
if(Z2 !== 1'b0) $stop;
if(Z3 !== 1'b1 && Z3 !== 1'bx) $stop; // Conflicts
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b0) $stop;
if(Z7 !== 1'b1) $stop;
if(Z8 !== 1'b1) $stop;
if(Z9 !== 1'b0) $stop;
if(Z10 !== 4'b0010) $stop;
//if(Z11 !== 1'bx) $stop; // Doesn't matter
end
else if(state == 3) begin
if(Z1 !== 1'b1) $stop; // tests output driver high
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b0) $stop;
if(Z7 !== 1'b1) $stop;
if(Z8 !== 1'b1) $stop;
if(Z9 !== 1'b0) $stop;
if(Z10 !== 4'b0010) $stop;
if(Z11 !== 1'b1) $stop;
end
else if(state == 4) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
pullup(Z1);
pullup(Z2);
pullup(Z3);
pullup(Z4);
pullup(Z5);
pullup(Z6);
pulldown(Z7);
pullup(Z8);
pulldown(Z9);
pulldown pd10[3:0] (Z10);
endmodule
module Test1(input OE, input A, inout Z1);
assign Z1 = (OE) ? A : 1'bz;
endmodule
module Test2(input OE, input A, inout Z2);
assign Z2 = (OE) ? A : 1'bz;
endmodule
// mixed low-Z and tristate
module Test3(input OE, input A, inout Z3);
assign Z3 = (OE) ? A : 1'bz;
assign Z3 = 1'b1;
endmodule
// floating output and inout
`ifndef VERILATOR
// Note verilator doesn't know to make Z4 a tristate unless marked an inout
`endif
module Test4(output Z4, inout Z5);
endmodule
// AND gate tristates
module Test5(input OE, inout Z6, inout Z7, inout Z8, inout Z9);
assign Z6 = (OE) ? 1'b0 : 1'bz;
assign Z7 = (OE) ? 1'b1 : 1'bz;
assign Z8 = (OE) ? 1'bz : 1'b0;
assign Z9 = (OE) ? 1'bz : 1'b1;
endmodule
// AND gate tristates
module Test6(input OE, inout [3:0] Z10);
wire [1:0] i;
Test6a a (.OE(OE), .Z({Z10[0],Z10[1]}));
Test6a b (.OE(~OE), .Z({Z10[2],Z10[0]}));
endmodule
module Test6a(input OE, inout [1:0] Z);
assign Z = (OE) ? 2'b01 : 2'bzz;
endmodule
module Test7(input [2:0] state, output reg Z11);
always @(*) begin
casez (state)
3'b000: Z11 = 1'b0;
3'b0?1: Z11 = 1'b1;
default: Z11 = 1'bx;
endcase
end
endmodule
// This is not implemented yet
//module Test3(input OE, input A, inout Z3);
// always @(*) begin
// if(OE) begin
// Z3 = A;
// end else begin
// Z3 = 1'bz;
// end
// end
//endmodule
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Lane Brooks
module t (clk);
input clk;
reg [31:0] state; initial state=0;
wire A = state[0];
wire OE = state[1];
wire Z1, Z2, Z3, Z4, Z5, Z6, Z7, Z8, Z9;
wire [3:0] Z10;
wire Z11;
Test1 test1(/*AUTOINST*/
// Inouts
.Z1 (Z1),
// Inputs
.OE (OE),
.A (A));
Test2 test2(/*AUTOINST*/
// Inouts
.Z2 (Z2),
// Inputs
.OE (OE),
.A (A));
Test3 test3(/*AUTOINST*/
// Inouts
.Z3 (Z3),
// Inputs
.OE (OE),
.A (A));
Test4 test4(/*AUTOINST*/
// Outputs
.Z4 (Z4),
// Inouts
.Z5 (Z5));
Test5 test5(/*AUTOINST*/
// Inouts
.Z6 (Z6),
.Z7 (Z7),
.Z8 (Z8),
.Z9 (Z9),
// Inputs
.OE (OE));
Test6 test6(/*AUTOINST*/
// Inouts
.Z10 (Z10[3:0]),
// Inputs
.OE (OE));
Test7 test7(/*AUTOINST*/
// Outputs
.Z11 (Z11),
// Inputs
.state (state[2:0]));
always @(posedge clk) begin
state <= state + 1;
`ifdef TEST_VERBOSE
$write("[%0t] state=%d Z1=%b 2=%b 3=%b 4=%b 5=%b 6=%b 7=%b 8=%b 9=%b 10=%b 11=%b\n",
$time, state, Z1,Z2,Z3,Z4,Z5,Z6,Z7,Z8,Z9,Z10,Z11);
`endif
if(state == 0) begin
if(Z1 !== 1'b1) $stop; // tests pullups
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b1) $stop;
if(Z7 !== 1'b0) $stop;
if(Z8 !== 1'b0) $stop;
if(Z9 !== 1'b1) $stop;
if(Z10 !== 4'b0001) $stop;
if(Z11 !== 1'b0) $stop;
end
else if(state == 1) begin
if(Z1 !== 1'b1) $stop; // tests pullup
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b1) $stop;
if(Z7 !== 1'b0) $stop;
if(Z8 !== 1'b0) $stop;
if(Z9 !== 1'b1) $stop;
if(Z10 !== 4'b0001) $stop;
if(Z11 !== 1'b1) $stop;
end
else if(state == 2) begin
if(Z1 !== 1'b0) $stop; // tests output driver low
if(Z2 !== 1'b0) $stop;
if(Z3 !== 1'b1 && Z3 !== 1'bx) $stop; // Conflicts
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b0) $stop;
if(Z7 !== 1'b1) $stop;
if(Z8 !== 1'b1) $stop;
if(Z9 !== 1'b0) $stop;
if(Z10 !== 4'b0010) $stop;
//if(Z11 !== 1'bx) $stop; // Doesn't matter
end
else if(state == 3) begin
if(Z1 !== 1'b1) $stop; // tests output driver high
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b0) $stop;
if(Z7 !== 1'b1) $stop;
if(Z8 !== 1'b1) $stop;
if(Z9 !== 1'b0) $stop;
if(Z10 !== 4'b0010) $stop;
if(Z11 !== 1'b1) $stop;
end
else if(state == 4) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
pullup(Z1);
pullup(Z2);
pullup(Z3);
pullup(Z4);
pullup(Z5);
pullup(Z6);
pulldown(Z7);
pullup(Z8);
pulldown(Z9);
pulldown pd10[3:0] (Z10);
endmodule
module Test1(input OE, input A, inout Z1);
assign Z1 = (OE) ? A : 1'bz;
endmodule
module Test2(input OE, input A, inout Z2);
assign Z2 = (OE) ? A : 1'bz;
endmodule
// mixed low-Z and tristate
module Test3(input OE, input A, inout Z3);
assign Z3 = (OE) ? A : 1'bz;
assign Z3 = 1'b1;
endmodule
// floating output and inout
`ifndef VERILATOR
// Note verilator doesn't know to make Z4 a tristate unless marked an inout
`endif
module Test4(output Z4, inout Z5);
endmodule
// AND gate tristates
module Test5(input OE, inout Z6, inout Z7, inout Z8, inout Z9);
assign Z6 = (OE) ? 1'b0 : 1'bz;
assign Z7 = (OE) ? 1'b1 : 1'bz;
assign Z8 = (OE) ? 1'bz : 1'b0;
assign Z9 = (OE) ? 1'bz : 1'b1;
endmodule
// AND gate tristates
module Test6(input OE, inout [3:0] Z10);
wire [1:0] i;
Test6a a (.OE(OE), .Z({Z10[0],Z10[1]}));
Test6a b (.OE(~OE), .Z({Z10[2],Z10[0]}));
endmodule
module Test6a(input OE, inout [1:0] Z);
assign Z = (OE) ? 2'b01 : 2'bzz;
endmodule
module Test7(input [2:0] state, output reg Z11);
always @(*) begin
casez (state)
3'b000: Z11 = 1'b0;
3'b0?1: Z11 = 1'b1;
default: Z11 = 1'bx;
endcase
end
endmodule
// This is not implemented yet
//module Test3(input OE, input A, inout Z3);
// always @(*) begin
// if(OE) begin
// Z3 = A;
// end else begin
// Z3 = 1'bz;
// end
// end
//endmodule
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Lane Brooks
module t (clk);
input clk;
reg [31:0] state; initial state=0;
wire A = state[0];
wire OE = state[1];
wire Z1, Z2, Z3, Z4, Z5, Z6, Z7, Z8, Z9;
wire [3:0] Z10;
wire Z11;
Test1 test1(/*AUTOINST*/
// Inouts
.Z1 (Z1),
// Inputs
.OE (OE),
.A (A));
Test2 test2(/*AUTOINST*/
// Inouts
.Z2 (Z2),
// Inputs
.OE (OE),
.A (A));
Test3 test3(/*AUTOINST*/
// Inouts
.Z3 (Z3),
// Inputs
.OE (OE),
.A (A));
Test4 test4(/*AUTOINST*/
// Outputs
.Z4 (Z4),
// Inouts
.Z5 (Z5));
Test5 test5(/*AUTOINST*/
// Inouts
.Z6 (Z6),
.Z7 (Z7),
.Z8 (Z8),
.Z9 (Z9),
// Inputs
.OE (OE));
Test6 test6(/*AUTOINST*/
// Inouts
.Z10 (Z10[3:0]),
// Inputs
.OE (OE));
Test7 test7(/*AUTOINST*/
// Outputs
.Z11 (Z11),
// Inputs
.state (state[2:0]));
always @(posedge clk) begin
state <= state + 1;
`ifdef TEST_VERBOSE
$write("[%0t] state=%d Z1=%b 2=%b 3=%b 4=%b 5=%b 6=%b 7=%b 8=%b 9=%b 10=%b 11=%b\n",
$time, state, Z1,Z2,Z3,Z4,Z5,Z6,Z7,Z8,Z9,Z10,Z11);
`endif
if(state == 0) begin
if(Z1 !== 1'b1) $stop; // tests pullups
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b1) $stop;
if(Z7 !== 1'b0) $stop;
if(Z8 !== 1'b0) $stop;
if(Z9 !== 1'b1) $stop;
if(Z10 !== 4'b0001) $stop;
if(Z11 !== 1'b0) $stop;
end
else if(state == 1) begin
if(Z1 !== 1'b1) $stop; // tests pullup
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b1) $stop;
if(Z7 !== 1'b0) $stop;
if(Z8 !== 1'b0) $stop;
if(Z9 !== 1'b1) $stop;
if(Z10 !== 4'b0001) $stop;
if(Z11 !== 1'b1) $stop;
end
else if(state == 2) begin
if(Z1 !== 1'b0) $stop; // tests output driver low
if(Z2 !== 1'b0) $stop;
if(Z3 !== 1'b1 && Z3 !== 1'bx) $stop; // Conflicts
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b0) $stop;
if(Z7 !== 1'b1) $stop;
if(Z8 !== 1'b1) $stop;
if(Z9 !== 1'b0) $stop;
if(Z10 !== 4'b0010) $stop;
//if(Z11 !== 1'bx) $stop; // Doesn't matter
end
else if(state == 3) begin
if(Z1 !== 1'b1) $stop; // tests output driver high
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b0) $stop;
if(Z7 !== 1'b1) $stop;
if(Z8 !== 1'b1) $stop;
if(Z9 !== 1'b0) $stop;
if(Z10 !== 4'b0010) $stop;
if(Z11 !== 1'b1) $stop;
end
else if(state == 4) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
pullup(Z1);
pullup(Z2);
pullup(Z3);
pullup(Z4);
pullup(Z5);
pullup(Z6);
pulldown(Z7);
pullup(Z8);
pulldown(Z9);
pulldown pd10[3:0] (Z10);
endmodule
module Test1(input OE, input A, inout Z1);
assign Z1 = (OE) ? A : 1'bz;
endmodule
module Test2(input OE, input A, inout Z2);
assign Z2 = (OE) ? A : 1'bz;
endmodule
// mixed low-Z and tristate
module Test3(input OE, input A, inout Z3);
assign Z3 = (OE) ? A : 1'bz;
assign Z3 = 1'b1;
endmodule
// floating output and inout
`ifndef VERILATOR
// Note verilator doesn't know to make Z4 a tristate unless marked an inout
`endif
module Test4(output Z4, inout Z5);
endmodule
// AND gate tristates
module Test5(input OE, inout Z6, inout Z7, inout Z8, inout Z9);
assign Z6 = (OE) ? 1'b0 : 1'bz;
assign Z7 = (OE) ? 1'b1 : 1'bz;
assign Z8 = (OE) ? 1'bz : 1'b0;
assign Z9 = (OE) ? 1'bz : 1'b1;
endmodule
// AND gate tristates
module Test6(input OE, inout [3:0] Z10);
wire [1:0] i;
Test6a a (.OE(OE), .Z({Z10[0],Z10[1]}));
Test6a b (.OE(~OE), .Z({Z10[2],Z10[0]}));
endmodule
module Test6a(input OE, inout [1:0] Z);
assign Z = (OE) ? 2'b01 : 2'bzz;
endmodule
module Test7(input [2:0] state, output reg Z11);
always @(*) begin
casez (state)
3'b000: Z11 = 1'b0;
3'b0?1: Z11 = 1'b1;
default: Z11 = 1'bx;
endcase
end
endmodule
// This is not implemented yet
//module Test3(input OE, input A, inout Z3);
// always @(*) begin
// if(OE) begin
// Z3 = A;
// end else begin
// Z3 = 1'bz;
// end
// end
//endmodule
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Lane Brooks
module t (clk);
input clk;
reg [31:0] state; initial state=0;
wire A = state[0];
wire OE = state[1];
wire Z1, Z2, Z3, Z4, Z5, Z6, Z7, Z8, Z9;
wire [3:0] Z10;
wire Z11;
Test1 test1(/*AUTOINST*/
// Inouts
.Z1 (Z1),
// Inputs
.OE (OE),
.A (A));
Test2 test2(/*AUTOINST*/
// Inouts
.Z2 (Z2),
// Inputs
.OE (OE),
.A (A));
Test3 test3(/*AUTOINST*/
// Inouts
.Z3 (Z3),
// Inputs
.OE (OE),
.A (A));
Test4 test4(/*AUTOINST*/
// Outputs
.Z4 (Z4),
// Inouts
.Z5 (Z5));
Test5 test5(/*AUTOINST*/
// Inouts
.Z6 (Z6),
.Z7 (Z7),
.Z8 (Z8),
.Z9 (Z9),
// Inputs
.OE (OE));
Test6 test6(/*AUTOINST*/
// Inouts
.Z10 (Z10[3:0]),
// Inputs
.OE (OE));
Test7 test7(/*AUTOINST*/
// Outputs
.Z11 (Z11),
// Inputs
.state (state[2:0]));
always @(posedge clk) begin
state <= state + 1;
`ifdef TEST_VERBOSE
$write("[%0t] state=%d Z1=%b 2=%b 3=%b 4=%b 5=%b 6=%b 7=%b 8=%b 9=%b 10=%b 11=%b\n",
$time, state, Z1,Z2,Z3,Z4,Z5,Z6,Z7,Z8,Z9,Z10,Z11);
`endif
if(state == 0) begin
if(Z1 !== 1'b1) $stop; // tests pullups
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b1) $stop;
if(Z7 !== 1'b0) $stop;
if(Z8 !== 1'b0) $stop;
if(Z9 !== 1'b1) $stop;
if(Z10 !== 4'b0001) $stop;
if(Z11 !== 1'b0) $stop;
end
else if(state == 1) begin
if(Z1 !== 1'b1) $stop; // tests pullup
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b1) $stop;
if(Z7 !== 1'b0) $stop;
if(Z8 !== 1'b0) $stop;
if(Z9 !== 1'b1) $stop;
if(Z10 !== 4'b0001) $stop;
if(Z11 !== 1'b1) $stop;
end
else if(state == 2) begin
if(Z1 !== 1'b0) $stop; // tests output driver low
if(Z2 !== 1'b0) $stop;
if(Z3 !== 1'b1 && Z3 !== 1'bx) $stop; // Conflicts
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b0) $stop;
if(Z7 !== 1'b1) $stop;
if(Z8 !== 1'b1) $stop;
if(Z9 !== 1'b0) $stop;
if(Z10 !== 4'b0010) $stop;
//if(Z11 !== 1'bx) $stop; // Doesn't matter
end
else if(state == 3) begin
if(Z1 !== 1'b1) $stop; // tests output driver high
if(Z2 !== 1'b1) $stop;
if(Z3 !== 1'b1) $stop;
`ifndef VERILATOR
if(Z4 !== 1'b1) $stop;
`endif
if(Z5 !== 1'b1) $stop;
if(Z6 !== 1'b0) $stop;
if(Z7 !== 1'b1) $stop;
if(Z8 !== 1'b1) $stop;
if(Z9 !== 1'b0) $stop;
if(Z10 !== 4'b0010) $stop;
if(Z11 !== 1'b1) $stop;
end
else if(state == 4) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
pullup(Z1);
pullup(Z2);
pullup(Z3);
pullup(Z4);
pullup(Z5);
pullup(Z6);
pulldown(Z7);
pullup(Z8);
pulldown(Z9);
pulldown pd10[3:0] (Z10);
endmodule
module Test1(input OE, input A, inout Z1);
assign Z1 = (OE) ? A : 1'bz;
endmodule
module Test2(input OE, input A, inout Z2);
assign Z2 = (OE) ? A : 1'bz;
endmodule
// mixed low-Z and tristate
module Test3(input OE, input A, inout Z3);
assign Z3 = (OE) ? A : 1'bz;
assign Z3 = 1'b1;
endmodule
// floating output and inout
`ifndef VERILATOR
// Note verilator doesn't know to make Z4 a tristate unless marked an inout
`endif
module Test4(output Z4, inout Z5);
endmodule
// AND gate tristates
module Test5(input OE, inout Z6, inout Z7, inout Z8, inout Z9);
assign Z6 = (OE) ? 1'b0 : 1'bz;
assign Z7 = (OE) ? 1'b1 : 1'bz;
assign Z8 = (OE) ? 1'bz : 1'b0;
assign Z9 = (OE) ? 1'bz : 1'b1;
endmodule
// AND gate tristates
module Test6(input OE, inout [3:0] Z10);
wire [1:0] i;
Test6a a (.OE(OE), .Z({Z10[0],Z10[1]}));
Test6a b (.OE(~OE), .Z({Z10[2],Z10[0]}));
endmodule
module Test6a(input OE, inout [1:0] Z);
assign Z = (OE) ? 2'b01 : 2'bzz;
endmodule
module Test7(input [2:0] state, output reg Z11);
always @(*) begin
casez (state)
3'b000: Z11 = 1'b0;
3'b0?1: Z11 = 1'b1;
default: Z11 = 1'bx;
endcase
end
endmodule
// This is not implemented yet
//module Test3(input OE, input A, inout Z3);
// always @(*) begin
// if(OE) begin
// Z3 = A;
// end else begin
// Z3 = 1'bz;
// 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: Contains 25 ms timers for each outstanding read request. If any
// timer reaches 0 than completion timeout is signalled.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module completion_timeout(
input clk,
input rst,
input [31:0] pending_req,
output reg comp_timeout
);
`ifdef ML505
reg [15:0] count;
`else
reg [17:0] count; //free running counter creates 1.048576 ms timer
`endif
wire [31:0] pending_req_rise;
wire [31:0] pending_req_fall;
reg [31:0] shift_in = 0;
reg [4:0] reset_count[31:0];
wire [31:0] srl_reset;
wire [31:0] comp_timeout_vector;
reg [31:0] comp_timeout_vector_d1;
wire comp_timeout_or;
wire comp_timeout_one;
reg comp_timeout_d1;
always@(posedge clk)begin
if(rst)
count <= 0;
else
count <= count + 1;
end
//timer is asserted every 1.045876 ms
assign timer = (count == 0) ? 1'b1 : 1'b0;
//create 32 shift register instances and associated logic
genvar i;
generate
for(i=0;i<32;i=i+1)begin: replicate
edge_detect edge_detect_inst(
.clk(clk),
.rst(rst),
.in(pending_req[i]),
.rise_out(pending_req_rise[i]),
.fall_out(pending_req_fall[i])
);
//pending req logic
//create a signal that sets when pending req is high and resets
//timer pulses. Pending req gets priority over timer if both
//signals occur simultaneously
always@(posedge clk)begin
if(pending_req_rise[i]) //set latch
shift_in[i] <= 1'b1;
else if(timer || pending_req_fall[i]) //reset latch
shift_in[i] <= 1'b0;
end
always@(posedge clk)begin
if(rst)
reset_count[i][4:0] <= 5'b00000;
else if (pending_req_fall[i] == 1'b1)
reset_count[i][4:0] <= 5'b11001;
else if (reset_count[i][4:0] == 5'b00000)
reset_count[i][4:0] <= 5'b00000;
else
reset_count[i][4:0] <= reset_count[i][4:0] - 1;
end
assign srl_reset[i] = | reset_count[i][4:0];
SRLC32E #(
.INIT(32'h00000000)
) SRLC32E_inst (
.Q(comp_timeout_vector[i]), // SRL data output
.Q31(), // SRL cascade output pin
.A(5'b11000), // 5-bit shift depth select input
.CE((srl_reset[i]) ? srl_reset[i] : timer), // Clock enable input
.CLK(clk), // Clock input
.D((srl_reset[i]) ? ~srl_reset[i] : shift_in[i]) // SRL data input
);
end
endgenerate
always@(posedge clk)begin
comp_timeout_vector_d1[31:0] <= comp_timeout_vector[31:0];
end
assign comp_timeout_or = |comp_timeout_vector_d1[31:0];
rising_edge_detect comp_timeout_one_inst(
.clk(clk),
.rst(rst),
.in(comp_timeout_or),
.one_shot_out(comp_timeout_one)
);
always@(posedge clk)begin
comp_timeout_d1 <= comp_timeout_one;
comp_timeout <= comp_timeout_d1;
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: Contains 25 ms timers for each outstanding read request. If any
// timer reaches 0 than completion timeout is signalled.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module completion_timeout(
input clk,
input rst,
input [31:0] pending_req,
output reg comp_timeout
);
`ifdef ML505
reg [15:0] count;
`else
reg [17:0] count; //free running counter creates 1.048576 ms timer
`endif
wire [31:0] pending_req_rise;
wire [31:0] pending_req_fall;
reg [31:0] shift_in = 0;
reg [4:0] reset_count[31:0];
wire [31:0] srl_reset;
wire [31:0] comp_timeout_vector;
reg [31:0] comp_timeout_vector_d1;
wire comp_timeout_or;
wire comp_timeout_one;
reg comp_timeout_d1;
always@(posedge clk)begin
if(rst)
count <= 0;
else
count <= count + 1;
end
//timer is asserted every 1.045876 ms
assign timer = (count == 0) ? 1'b1 : 1'b0;
//create 32 shift register instances and associated logic
genvar i;
generate
for(i=0;i<32;i=i+1)begin: replicate
edge_detect edge_detect_inst(
.clk(clk),
.rst(rst),
.in(pending_req[i]),
.rise_out(pending_req_rise[i]),
.fall_out(pending_req_fall[i])
);
//pending req logic
//create a signal that sets when pending req is high and resets
//timer pulses. Pending req gets priority over timer if both
//signals occur simultaneously
always@(posedge clk)begin
if(pending_req_rise[i]) //set latch
shift_in[i] <= 1'b1;
else if(timer || pending_req_fall[i]) //reset latch
shift_in[i] <= 1'b0;
end
always@(posedge clk)begin
if(rst)
reset_count[i][4:0] <= 5'b00000;
else if (pending_req_fall[i] == 1'b1)
reset_count[i][4:0] <= 5'b11001;
else if (reset_count[i][4:0] == 5'b00000)
reset_count[i][4:0] <= 5'b00000;
else
reset_count[i][4:0] <= reset_count[i][4:0] - 1;
end
assign srl_reset[i] = | reset_count[i][4:0];
SRLC32E #(
.INIT(32'h00000000)
) SRLC32E_inst (
.Q(comp_timeout_vector[i]), // SRL data output
.Q31(), // SRL cascade output pin
.A(5'b11000), // 5-bit shift depth select input
.CE((srl_reset[i]) ? srl_reset[i] : timer), // Clock enable input
.CLK(clk), // Clock input
.D((srl_reset[i]) ? ~srl_reset[i] : shift_in[i]) // SRL data input
);
end
endgenerate
always@(posedge clk)begin
comp_timeout_vector_d1[31:0] <= comp_timeout_vector[31:0];
end
assign comp_timeout_or = |comp_timeout_vector_d1[31:0];
rising_edge_detect comp_timeout_one_inst(
.clk(clk),
.rst(rst),
.in(comp_timeout_or),
.one_shot_out(comp_timeout_one)
);
always@(posedge clk)begin
comp_timeout_d1 <= comp_timeout_one;
comp_timeout <= comp_timeout_d1;
end
endmodule
|
// -----------------------------------------------------------
// Legal Notice: (C)2007 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 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.
//
// Description: Single clock Avalon-ST FIFO.
// -----------------------------------------------------------
`timescale 1 ns / 1 ns
//altera message_off 10036
module altera_avalon_sc_fifo
#(
// --------------------------------------------------
// Parameters
// --------------------------------------------------
parameter SYMBOLS_PER_BEAT = 1,
parameter BITS_PER_SYMBOL = 8,
parameter FIFO_DEPTH = 16,
parameter CHANNEL_WIDTH = 0,
parameter ERROR_WIDTH = 0,
parameter USE_PACKETS = 0,
parameter USE_FILL_LEVEL = 0,
parameter USE_STORE_FORWARD = 0,
parameter USE_ALMOST_FULL_IF = 0,
parameter USE_ALMOST_EMPTY_IF = 0,
// --------------------------------------------------
// Empty latency is defined as the number of cycles
// required for a write to deassert the empty flag.
// For example, a latency of 1 means that the empty
// flag is deasserted on the cycle after a write.
//
// Another way to think of it is the latency for a
// write to propagate to the output.
//
// An empty latency of 0 implies lookahead, which is
// only implemented for the register-based FIFO.
// --------------------------------------------------
parameter EMPTY_LATENCY = 3,
parameter USE_MEMORY_BLOCKS = 1,
// --------------------------------------------------
// Internal Parameters
// --------------------------------------------------
parameter DATA_WIDTH = SYMBOLS_PER_BEAT * BITS_PER_SYMBOL,
parameter EMPTY_WIDTH = log2ceil(SYMBOLS_PER_BEAT)
)
(
// --------------------------------------------------
// Ports
// --------------------------------------------------
input clk,
input reset,
input [DATA_WIDTH-1: 0] in_data,
input in_valid,
input in_startofpacket,
input in_endofpacket,
input [((EMPTY_WIDTH>0) ? (EMPTY_WIDTH-1):0) : 0] in_empty,
input [((ERROR_WIDTH>0) ? (ERROR_WIDTH-1):0) : 0] in_error,
input [((CHANNEL_WIDTH>0) ? (CHANNEL_WIDTH-1):0): 0] in_channel,
output in_ready,
output [DATA_WIDTH-1 : 0] out_data,
output reg out_valid,
output out_startofpacket,
output out_endofpacket,
output [((EMPTY_WIDTH>0) ? (EMPTY_WIDTH-1):0) : 0] out_empty,
output [((ERROR_WIDTH>0) ? (ERROR_WIDTH-1):0) : 0] out_error,
output [((CHANNEL_WIDTH>0) ? (CHANNEL_WIDTH-1):0): 0] out_channel,
input out_ready,
input [(USE_STORE_FORWARD ? 2 : 1) : 0] csr_address,
input csr_write,
input csr_read,
input [31 : 0] csr_writedata,
output reg [31 : 0] csr_readdata,
output wire almost_full_data,
output wire almost_empty_data
);
// --------------------------------------------------
// Local Parameters
// --------------------------------------------------
localparam ADDR_WIDTH = log2ceil(FIFO_DEPTH);
localparam DEPTH = FIFO_DEPTH;
localparam PKT_SIGNALS_WIDTH = 2 + EMPTY_WIDTH;
localparam PAYLOAD_WIDTH = (USE_PACKETS == 1) ?
2 + EMPTY_WIDTH + DATA_WIDTH + ERROR_WIDTH + CHANNEL_WIDTH:
DATA_WIDTH + ERROR_WIDTH + CHANNEL_WIDTH;
// --------------------------------------------------
// Internal Signals
// --------------------------------------------------
genvar i;
reg [PAYLOAD_WIDTH-1 : 0] mem [DEPTH-1 : 0];
reg [ADDR_WIDTH-1 : 0] wr_ptr;
reg [ADDR_WIDTH-1 : 0] rd_ptr;
reg [DEPTH-1 : 0] mem_used;
wire [ADDR_WIDTH-1 : 0] next_wr_ptr;
wire [ADDR_WIDTH-1 : 0] next_rd_ptr;
wire [ADDR_WIDTH-1 : 0] incremented_wr_ptr;
wire [ADDR_WIDTH-1 : 0] incremented_rd_ptr;
wire [ADDR_WIDTH-1 : 0] mem_rd_ptr;
wire read;
wire write;
reg empty;
reg next_empty;
reg full;
reg next_full;
wire [PKT_SIGNALS_WIDTH-1 : 0] in_packet_signals;
wire [PKT_SIGNALS_WIDTH-1 : 0] out_packet_signals;
wire [PAYLOAD_WIDTH-1 : 0] in_payload;
reg [PAYLOAD_WIDTH-1 : 0] internal_out_payload;
reg [PAYLOAD_WIDTH-1 : 0] out_payload;
reg internal_out_valid;
wire internal_out_ready;
reg [ADDR_WIDTH : 0] fifo_fill_level;
reg [ADDR_WIDTH : 0] fill_level;
reg [ADDR_WIDTH-1 : 0] sop_ptr = 0;
reg [23:0] almost_full_threshold;
reg [23:0] almost_empty_threshold;
reg [23:0] cut_through_threshold;
reg [15:0] pkt_cnt;
reg [15:0] pkt_cnt_r;
reg [15:0] pkt_cnt_plusone;
reg [15:0] pkt_cnt_minusone;
reg drop_on_error_en;
reg error_in_pkt;
reg pkt_has_started;
reg sop_has_left_fifo;
reg fifo_too_small_r;
reg pkt_cnt_eq_zero;
reg pkt_cnt_eq_one;
reg pkt_cnt_changed;
wire wait_for_threshold;
reg pkt_mode;
wire wait_for_pkt;
wire ok_to_forward;
wire in_pkt_eop_arrive;
wire out_pkt_leave;
wire in_pkt_start;
wire in_pkt_error;
wire drop_on_error;
wire fifo_too_small;
wire out_pkt_sop_leave;
wire [31:0] max_fifo_size;
reg fifo_fill_level_lt_cut_through_threshold;
// --------------------------------------------------
// Define Payload
//
// Icky part where we decide which signals form the
// payload to the FIFO with generate blocks.
// --------------------------------------------------
generate
if (EMPTY_WIDTH > 0) begin
assign in_packet_signals = {in_startofpacket, in_endofpacket, in_empty};
assign {out_startofpacket, out_endofpacket, out_empty} = out_packet_signals;
end
else begin
assign out_empty = in_error;
assign in_packet_signals = {in_startofpacket, in_endofpacket};
assign {out_startofpacket, out_endofpacket} = out_packet_signals;
end
endgenerate
generate
if (USE_PACKETS) begin
if (ERROR_WIDTH > 0) begin
if (CHANNEL_WIDTH > 0) begin
assign in_payload = {in_packet_signals, in_data, in_error, in_channel};
assign {out_packet_signals, out_data, out_error, out_channel} = out_payload;
end
else begin
assign out_channel = in_channel;
assign in_payload = {in_packet_signals, in_data, in_error};
assign {out_packet_signals, out_data, out_error} = out_payload;
end
end
else begin
assign out_error = in_error;
if (CHANNEL_WIDTH > 0) begin
assign in_payload = {in_packet_signals, in_data, in_channel};
assign {out_packet_signals, out_data, out_channel} = out_payload;
end
else begin
assign out_channel = in_channel;
assign in_payload = {in_packet_signals, in_data};
assign {out_packet_signals, out_data} = out_payload;
end
end
end
else begin
assign out_packet_signals = 0;
if (ERROR_WIDTH > 0) begin
if (CHANNEL_WIDTH > 0) begin
assign in_payload = {in_data, in_error, in_channel};
assign {out_data, out_error, out_channel} = out_payload;
end
else begin
assign out_channel = in_channel;
assign in_payload = {in_data, in_error};
assign {out_data, out_error} = out_payload;
end
end
else begin
assign out_error = in_error;
if (CHANNEL_WIDTH > 0) begin
assign in_payload = {in_data, in_channel};
assign {out_data, out_channel} = out_payload;
end
else begin
assign out_channel = in_channel;
assign in_payload = in_data;
assign out_data = out_payload;
end
end
end
endgenerate
// --------------------------------------------------
// Memory-based FIFO storage
//
// To allow a ready latency of 0, the read index is
// obtained from the next read pointer and memory
// outputs are unregistered.
//
// If the empty latency is 1, we infer bypass logic
// around the memory so writes propagate to the
// outputs on the next cycle.
//
// Do not change the way this is coded: Quartus needs
// a perfect match to the template, and any attempt to
// refactor the two always blocks into one will break
// memory inference.
// --------------------------------------------------
generate if (USE_MEMORY_BLOCKS == 1) begin
if (EMPTY_LATENCY == 1) begin
always @(posedge clk) begin
if (in_valid && in_ready)
mem[wr_ptr] = in_payload;
internal_out_payload = mem[mem_rd_ptr];
end
end else begin
always @(posedge clk) begin
if (in_valid && in_ready)
mem[wr_ptr] <= in_payload;
internal_out_payload <= mem[mem_rd_ptr];
end
end
assign mem_rd_ptr = next_rd_ptr;
end else begin
// --------------------------------------------------
// Register-based FIFO storage
//
// Uses a shift register as the storage element. Each
// shift register slot has a bit which indicates if
// the slot is occupied (credit to Sam H for the idea).
// The occupancy bits are contiguous and start from the
// lsb, so 0000, 0001, 0011, 0111, 1111 for a 4-deep
// FIFO.
//
// Each slot is enabled during a read or when it
// is unoccupied. New data is always written to every
// going-to-be-empty slot (we keep track of which ones
// are actually useful with the occupancy bits). On a
// read we shift occupied slots.
//
// The exception is the last slot, which always gets
// new data when it is unoccupied.
// --------------------------------------------------
for (i = 0; i < DEPTH-1; i = i + 1) begin : shift_reg
always @(posedge clk or posedge reset) begin
if (reset) begin
mem[i] <= 0;
end
else if (read || !mem_used[i]) begin
if (!mem_used[i+1])
mem[i] <= in_payload;
else
mem[i] <= mem[i+1];
end
end
end
always @(posedge clk, posedge reset) begin
if (reset) begin
mem[DEPTH-1] <= 0;
end
else begin
if (!mem_used[DEPTH-1])
mem[DEPTH-1] <= in_payload;
if (DEPTH == 1) begin
if (write)
mem[DEPTH-1] <= in_payload;
end
end
end
end
endgenerate
assign read = internal_out_ready && internal_out_valid && ok_to_forward;
assign write = in_ready && in_valid;
// --------------------------------------------------
// Pointer Management
// --------------------------------------------------
generate if (USE_MEMORY_BLOCKS == 1) begin
assign incremented_wr_ptr = wr_ptr + 1'b1;
assign incremented_rd_ptr = rd_ptr + 1'b1;
assign next_wr_ptr = drop_on_error ? sop_ptr : write ? incremented_wr_ptr : wr_ptr;
assign next_rd_ptr = (read) ? incremented_rd_ptr : rd_ptr;
always @(posedge clk or posedge reset) begin
if (reset) begin
wr_ptr <= 0;
rd_ptr <= 0;
end
else begin
wr_ptr <= next_wr_ptr;
rd_ptr <= next_rd_ptr;
end
end
end else begin
// --------------------------------------------------
// Shift Register Occupancy Bits
//
// Consider a 4-deep FIFO with 2 entries: 0011
// On a read and write, do not modify the bits.
// On a write, left-shift the bits to get 0111.
// On a read, right-shift the bits to get 0001.
//
// Also, on a write we set bit0 (the head), while
// clearing the tail on a read.
// --------------------------------------------------
always @(posedge clk or posedge reset) begin
if (reset) begin
mem_used[0] <= 0;
end
else begin
if (write ^ read) begin
if (read) begin
if (DEPTH > 1)
mem_used[0] <= mem_used[1];
else
mem_used[0] <= 0;
end
if (write)
mem_used[0] <= 1;
end
end
end
if (DEPTH > 1) begin
always @(posedge clk or posedge reset) begin
if (reset) begin
mem_used[DEPTH-1] <= 0;
end
else begin
if (write ^ read) begin
mem_used[DEPTH-1] <= 0;
if (write)
mem_used[DEPTH-1] <= mem_used[DEPTH-2];
end
end
end
end
for (i = 1; i < DEPTH-1; i = i + 1) begin : storage_logic
always @(posedge clk, posedge reset) begin
if (reset) begin
mem_used[i] <= 0;
end
else begin
if (write ^ read) begin
if (read)
mem_used[i] <= mem_used[i+1];
if (write)
mem_used[i] <= mem_used[i-1];
end
end
end
end
end
endgenerate
// --------------------------------------------------
// Memory FIFO Status Management
//
// Generates the full and empty signals from the
// pointers. The FIFO is full when the next write
// pointer will be equal to the read pointer after
// a write. Reading from a FIFO clears full.
//
// The FIFO is empty when the next read pointer will
// be equal to the write pointer after a read. Writing
// to a FIFO clears empty.
//
// A simultaneous read and write must not change any of
// the empty or full flags unless there is a drop on error event.
// --------------------------------------------------
generate if (USE_MEMORY_BLOCKS == 1) begin
always @* begin
next_full = full;
next_empty = empty;
if (read && !write) begin
next_full = 1'b0;
if (incremented_rd_ptr == wr_ptr)
next_empty = 1'b1;
end
if (write && !read) begin
if (!drop_on_error)
next_empty = 1'b0;
else if (sop_ptr == rd_ptr) // drop on error and only 1 pkt in fifo
next_empty = 1'b1;
if (incremented_wr_ptr == rd_ptr && !drop_on_error)
next_full = 1'b1;
end
if (write && read && drop_on_error) begin
if (sop_ptr == next_rd_ptr)
next_empty = 1'b1;
end
end
always @(posedge clk or posedge reset) begin
if (reset) begin
empty <= 1;
full <= 0;
end
else begin
empty <= next_empty;
full <= next_full;
end
end
end else begin
// --------------------------------------------------
// Register FIFO Status Management
//
// Full when the tail occupancy bit is 1. Empty when
// the head occupancy bit is 0.
// --------------------------------------------------
always @* begin
full = mem_used[DEPTH-1];
empty = !mem_used[0];
// ------------------------------------------
// For a single slot FIFO, reading clears the
// full status immediately.
// ------------------------------------------
if (DEPTH == 1)
full = mem_used[0] && !read;
internal_out_payload = mem[0];
// ------------------------------------------
// Writes clear empty immediately for lookahead modes.
// Note that we use in_valid instead of write to avoid
// combinational loops (in lookahead mode, qualifying
// with in_ready is meaningless).
//
// In a 1-deep FIFO, a possible combinational loop runs
// from write -> out_valid -> out_ready -> write
// ------------------------------------------
if (EMPTY_LATENCY == 0) begin
empty = !mem_used[0] && !in_valid;
if (!mem_used[0] && in_valid)
internal_out_payload = in_payload;
end
end
end
endgenerate
// --------------------------------------------------
// Avalon-ST Signals
//
// The in_ready signal is straightforward.
//
// To match memory latency when empty latency > 1,
// out_valid assertions must be delayed by one clock
// cycle.
//
// Note: out_valid deassertions must not be delayed or
// the FIFO will underflow.
// --------------------------------------------------
assign in_ready = !full;
assign internal_out_ready = out_ready || !out_valid;
generate if (EMPTY_LATENCY > 1) begin
always @(posedge clk or posedge reset) begin
if (reset)
internal_out_valid <= 0;
else begin
internal_out_valid <= !empty & ok_to_forward & ~drop_on_error;
if (read) begin
if (incremented_rd_ptr == wr_ptr)
internal_out_valid <= 1'b0;
end
end
end
end else begin
always @* begin
internal_out_valid = !empty & ok_to_forward;
end
end
endgenerate
// --------------------------------------------------
// Single Output Pipeline Stage
//
// This output pipeline stage is enabled if the FIFO's
// empty latency is set to 3 (default). It is disabled
// for all other allowed latencies.
//
// Reason: The memory outputs are unregistered, so we have to
// register the output or fmax will drop if combinatorial
// logic is present on the output datapath.
//
// Q: The Avalon-ST spec says that I have to register my outputs
// But isn't the memory counted as a register?
// A: The path from the address lookup to the memory output is
// slow. Registering the memory outputs is a good idea.
//
// The registers get packed into the memory by the fitter
// which means minimal resources are consumed (the result
// is a altsyncram with registered outputs, available on
// all modern Altera devices).
//
// This output stage acts as an extra slot in the FIFO,
// and complicates the fill level.
// --------------------------------------------------
generate if (EMPTY_LATENCY == 3) begin
always @(posedge clk or posedge reset) begin
if (reset) begin
out_valid <= 0;
out_payload <= 0;
end
else begin
if (internal_out_ready) begin
out_valid <= internal_out_valid & ok_to_forward;
out_payload <= internal_out_payload;
end
end
end
end
else begin
always @* begin
out_valid = internal_out_valid;
out_payload = internal_out_payload;
end
end
endgenerate
// --------------------------------------------------
// Fill Level
//
// The fill level is calculated from the next write
// and read pointers to avoid unnecessary latency.
//
// If the output pipeline is enabled, the fill level
// must account for it, or we'll always be off by one.
// This may, or may not be important depending on the
// application.
//
// For now, we'll always calculate the exact fill level
// at the cost of an extra adder when the output stage
// is enabled.
// --------------------------------------------------
generate if (USE_FILL_LEVEL) begin
wire [31:0] depth32;
assign depth32 = DEPTH;
always @(posedge clk or posedge reset) begin
if (reset)
fifo_fill_level <= 0;
else if (next_full & !drop_on_error)
fifo_fill_level <= depth32[ADDR_WIDTH:0];
else begin
fifo_fill_level[ADDR_WIDTH] <= 1'b0;
fifo_fill_level[ADDR_WIDTH-1 : 0] <= next_wr_ptr - next_rd_ptr;
end
end
always @* begin
fill_level = fifo_fill_level;
if (EMPTY_LATENCY == 3)
fill_level = fifo_fill_level + {{ADDR_WIDTH{1'b0}}, out_valid};
end
end
else begin
always @* begin
fill_level = 0;
end
end
endgenerate
generate if (USE_ALMOST_FULL_IF) begin
assign almost_full_data = (fill_level >= almost_full_threshold);
end
else
assign almost_full_data = 0;
endgenerate
generate if (USE_ALMOST_EMPTY_IF) begin
assign almost_empty_data = (fill_level <= almost_empty_threshold);
end
else
assign almost_empty_data = 0;
endgenerate
// --------------------------------------------------
// Avalon-MM Status & Control Connection Point
//
// Register map:
//
// | Addr | RW | 31 - 0 |
// | 0 | R | Fill level |
//
// The registering of this connection point means
// that there is a cycle of latency between
// reads/writes and the updating of the fill level.
// --------------------------------------------------
generate if (USE_STORE_FORWARD) begin
assign max_fifo_size = FIFO_DEPTH - 1;
always @(posedge clk or posedge reset) begin
if (reset) begin
almost_full_threshold <= max_fifo_size[23 : 0];
almost_empty_threshold <= 0;
cut_through_threshold <= 0;
drop_on_error_en <= 0;
csr_readdata <= 0;
pkt_mode <= 1'b1;
end
else begin
if (csr_write) begin
if(csr_address == 3'b010)
almost_full_threshold <= csr_writedata[23:0];
if(csr_address == 3'b011)
almost_empty_threshold <= csr_writedata[23:0];
if(csr_address == 3'b100) begin
cut_through_threshold <= csr_writedata[23:0];
pkt_mode <= (csr_writedata[23:0] == 0);
end
if(csr_address == 3'b101)
drop_on_error_en <= csr_writedata[0];
end
if (csr_read) begin
csr_readdata <= 32'b0;
if (csr_address == 0)
csr_readdata <= {{(31 - ADDR_WIDTH){1'b0}}, fill_level};
if (csr_address == 2)
csr_readdata <= {8'b0, almost_full_threshold};
if (csr_address == 3)
csr_readdata <= {8'b0, almost_empty_threshold};
if (csr_address == 4)
csr_readdata <= {8'b0, cut_through_threshold};
if (csr_address == 5)
csr_readdata <= {31'b0, drop_on_error_en};
end
end
end
end
else if (USE_ALMOST_FULL_IF || USE_ALMOST_EMPTY_IF) begin
assign max_fifo_size = FIFO_DEPTH - 1;
always @(posedge clk or posedge reset) begin
if (reset) begin
almost_full_threshold <= max_fifo_size[23 : 0];
almost_empty_threshold <= 0;
csr_readdata <= 0;
end
else begin
if (csr_write) begin
if(csr_address == 3'b010)
almost_full_threshold <= csr_writedata[23:0];
if(csr_address == 3'b011)
almost_empty_threshold <= csr_writedata[23:0];
end
if (csr_read) begin
csr_readdata <= 32'b0;
if (csr_address == 0)
csr_readdata <= {{(31 - ADDR_WIDTH){1'b0}}, fill_level};
if (csr_address == 2)
csr_readdata <= {8'b0, almost_full_threshold};
if (csr_address == 3)
csr_readdata <= {8'b0, almost_empty_threshold};
end
end
end
end
else begin
always @(posedge clk or posedge reset) begin
if (reset) begin
csr_readdata <= 0;
end
else if (csr_read) begin
csr_readdata <= 0;
if (csr_address == 0)
csr_readdata <= fill_level;
end
end
end
endgenerate
// --------------------------------------------------
// Store and forward logic
// --------------------------------------------------
// if the fifo gets full before the entire packet or the
// cut-threshold condition is met then start sending out
// data in order to avoid dead-lock situation
generate if (USE_STORE_FORWARD) begin
assign wait_for_threshold = (fifo_fill_level_lt_cut_through_threshold) & wait_for_pkt ;
assign wait_for_pkt = pkt_cnt_eq_zero | (pkt_cnt_eq_one & out_pkt_leave);
assign ok_to_forward = (pkt_mode ? (~wait_for_pkt | ~pkt_has_started) :
~wait_for_threshold) | fifo_too_small_r;
assign in_pkt_eop_arrive = in_valid & in_ready & in_endofpacket;
assign in_pkt_start = in_valid & in_ready & in_startofpacket;
assign in_pkt_error = in_valid & in_ready & |in_error;
assign out_pkt_sop_leave = out_valid & out_ready & out_startofpacket;
assign out_pkt_leave = out_valid & out_ready & out_endofpacket;
assign fifo_too_small = (pkt_mode ? wait_for_pkt : wait_for_threshold) & full & out_ready;
// count packets coming and going into the fifo
always @(posedge clk or posedge reset) begin
if (reset) begin
pkt_cnt <= 0;
pkt_cnt_r <= 0;
pkt_cnt_plusone <= 1;
pkt_cnt_minusone <= 0;
pkt_cnt_changed <= 0;
pkt_has_started <= 0;
sop_has_left_fifo <= 0;
fifo_too_small_r <= 0;
pkt_cnt_eq_zero <= 1'b1;
pkt_cnt_eq_one <= 1'b0;
fifo_fill_level_lt_cut_through_threshold <= 1'b1;
end
else begin
fifo_fill_level_lt_cut_through_threshold <= fifo_fill_level < cut_through_threshold;
fifo_too_small_r <= fifo_too_small;
pkt_cnt_plusone <= pkt_cnt + 1'b1;
pkt_cnt_minusone <= pkt_cnt - 1'b1;
pkt_cnt_r <= pkt_cnt;
pkt_cnt_changed <= 1'b0;
if( in_pkt_eop_arrive )
sop_has_left_fifo <= 1'b0;
else if (out_pkt_sop_leave & pkt_cnt_eq_zero )
sop_has_left_fifo <= 1'b1;
if (in_pkt_eop_arrive & ~out_pkt_leave & ~drop_on_error ) begin
pkt_cnt_changed <= 1'b1;
pkt_cnt <= pkt_cnt_changed ? pkt_cnt_r : pkt_cnt_plusone;
pkt_cnt_eq_zero <= 0;
if (pkt_cnt == 0)
pkt_cnt_eq_one <= 1'b1;
else
pkt_cnt_eq_one <= 1'b0;
end
else if((~in_pkt_eop_arrive | drop_on_error) & out_pkt_leave) begin
pkt_cnt_changed <= 1'b1;
pkt_cnt <= pkt_cnt_changed ? pkt_cnt_r : pkt_cnt_minusone;
if (pkt_cnt == 1)
pkt_cnt_eq_zero <= 1'b1;
else
pkt_cnt_eq_zero <= 1'b0;
if (pkt_cnt == 2)
pkt_cnt_eq_one <= 1'b1;
else
pkt_cnt_eq_one <= 1'b0;
end
if (in_pkt_start)
pkt_has_started <= 1'b1;
else if (in_pkt_eop_arrive)
pkt_has_started <= 1'b0;
end
end
// drop on error logic
always @(posedge clk or posedge reset) begin
if (reset) begin
sop_ptr <= 0;
error_in_pkt <= 0;
end
else begin
// save the location of the SOP
if ( in_pkt_start )
sop_ptr <= wr_ptr;
// remember if error in pkt
// log error only if packet has already started
if (in_pkt_eop_arrive)
error_in_pkt <= 1'b0;
else if ( in_pkt_error & (pkt_has_started | in_pkt_start))
error_in_pkt <= 1'b1;
end
end
assign drop_on_error = drop_on_error_en & (error_in_pkt | in_pkt_error) & in_pkt_eop_arrive &
~sop_has_left_fifo & ~(out_pkt_sop_leave & pkt_cnt_eq_zero);
end
else begin
assign ok_to_forward = 1'b1;
assign drop_on_error = 1'b0;
end
endgenerate
// --------------------------------------------------
// Calculates the log2ceil of the input value
// --------------------------------------------------
function integer log2ceil;
input integer val;
integer i;
begin
i = 1;
log2ceil = 0;
while (i < val) begin
log2ceil = log2ceil + 1;
i = i << 1;
end
end
endfunction
endmodule
|
// -----------------------------------------------------------
// Legal Notice: (C)2007 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 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.
//
// Description: Single clock Avalon-ST FIFO.
// -----------------------------------------------------------
`timescale 1 ns / 1 ns
//altera message_off 10036
module altera_avalon_sc_fifo
#(
// --------------------------------------------------
// Parameters
// --------------------------------------------------
parameter SYMBOLS_PER_BEAT = 1,
parameter BITS_PER_SYMBOL = 8,
parameter FIFO_DEPTH = 16,
parameter CHANNEL_WIDTH = 0,
parameter ERROR_WIDTH = 0,
parameter USE_PACKETS = 0,
parameter USE_FILL_LEVEL = 0,
parameter USE_STORE_FORWARD = 0,
parameter USE_ALMOST_FULL_IF = 0,
parameter USE_ALMOST_EMPTY_IF = 0,
// --------------------------------------------------
// Empty latency is defined as the number of cycles
// required for a write to deassert the empty flag.
// For example, a latency of 1 means that the empty
// flag is deasserted on the cycle after a write.
//
// Another way to think of it is the latency for a
// write to propagate to the output.
//
// An empty latency of 0 implies lookahead, which is
// only implemented for the register-based FIFO.
// --------------------------------------------------
parameter EMPTY_LATENCY = 3,
parameter USE_MEMORY_BLOCKS = 1,
// --------------------------------------------------
// Internal Parameters
// --------------------------------------------------
parameter DATA_WIDTH = SYMBOLS_PER_BEAT * BITS_PER_SYMBOL,
parameter EMPTY_WIDTH = log2ceil(SYMBOLS_PER_BEAT)
)
(
// --------------------------------------------------
// Ports
// --------------------------------------------------
input clk,
input reset,
input [DATA_WIDTH-1: 0] in_data,
input in_valid,
input in_startofpacket,
input in_endofpacket,
input [((EMPTY_WIDTH>0) ? (EMPTY_WIDTH-1):0) : 0] in_empty,
input [((ERROR_WIDTH>0) ? (ERROR_WIDTH-1):0) : 0] in_error,
input [((CHANNEL_WIDTH>0) ? (CHANNEL_WIDTH-1):0): 0] in_channel,
output in_ready,
output [DATA_WIDTH-1 : 0] out_data,
output reg out_valid,
output out_startofpacket,
output out_endofpacket,
output [((EMPTY_WIDTH>0) ? (EMPTY_WIDTH-1):0) : 0] out_empty,
output [((ERROR_WIDTH>0) ? (ERROR_WIDTH-1):0) : 0] out_error,
output [((CHANNEL_WIDTH>0) ? (CHANNEL_WIDTH-1):0): 0] out_channel,
input out_ready,
input [(USE_STORE_FORWARD ? 2 : 1) : 0] csr_address,
input csr_write,
input csr_read,
input [31 : 0] csr_writedata,
output reg [31 : 0] csr_readdata,
output wire almost_full_data,
output wire almost_empty_data
);
// --------------------------------------------------
// Local Parameters
// --------------------------------------------------
localparam ADDR_WIDTH = log2ceil(FIFO_DEPTH);
localparam DEPTH = FIFO_DEPTH;
localparam PKT_SIGNALS_WIDTH = 2 + EMPTY_WIDTH;
localparam PAYLOAD_WIDTH = (USE_PACKETS == 1) ?
2 + EMPTY_WIDTH + DATA_WIDTH + ERROR_WIDTH + CHANNEL_WIDTH:
DATA_WIDTH + ERROR_WIDTH + CHANNEL_WIDTH;
// --------------------------------------------------
// Internal Signals
// --------------------------------------------------
genvar i;
reg [PAYLOAD_WIDTH-1 : 0] mem [DEPTH-1 : 0];
reg [ADDR_WIDTH-1 : 0] wr_ptr;
reg [ADDR_WIDTH-1 : 0] rd_ptr;
reg [DEPTH-1 : 0] mem_used;
wire [ADDR_WIDTH-1 : 0] next_wr_ptr;
wire [ADDR_WIDTH-1 : 0] next_rd_ptr;
wire [ADDR_WIDTH-1 : 0] incremented_wr_ptr;
wire [ADDR_WIDTH-1 : 0] incremented_rd_ptr;
wire [ADDR_WIDTH-1 : 0] mem_rd_ptr;
wire read;
wire write;
reg empty;
reg next_empty;
reg full;
reg next_full;
wire [PKT_SIGNALS_WIDTH-1 : 0] in_packet_signals;
wire [PKT_SIGNALS_WIDTH-1 : 0] out_packet_signals;
wire [PAYLOAD_WIDTH-1 : 0] in_payload;
reg [PAYLOAD_WIDTH-1 : 0] internal_out_payload;
reg [PAYLOAD_WIDTH-1 : 0] out_payload;
reg internal_out_valid;
wire internal_out_ready;
reg [ADDR_WIDTH : 0] fifo_fill_level;
reg [ADDR_WIDTH : 0] fill_level;
reg [ADDR_WIDTH-1 : 0] sop_ptr = 0;
reg [23:0] almost_full_threshold;
reg [23:0] almost_empty_threshold;
reg [23:0] cut_through_threshold;
reg [15:0] pkt_cnt;
reg [15:0] pkt_cnt_r;
reg [15:0] pkt_cnt_plusone;
reg [15:0] pkt_cnt_minusone;
reg drop_on_error_en;
reg error_in_pkt;
reg pkt_has_started;
reg sop_has_left_fifo;
reg fifo_too_small_r;
reg pkt_cnt_eq_zero;
reg pkt_cnt_eq_one;
reg pkt_cnt_changed;
wire wait_for_threshold;
reg pkt_mode;
wire wait_for_pkt;
wire ok_to_forward;
wire in_pkt_eop_arrive;
wire out_pkt_leave;
wire in_pkt_start;
wire in_pkt_error;
wire drop_on_error;
wire fifo_too_small;
wire out_pkt_sop_leave;
wire [31:0] max_fifo_size;
reg fifo_fill_level_lt_cut_through_threshold;
// --------------------------------------------------
// Define Payload
//
// Icky part where we decide which signals form the
// payload to the FIFO with generate blocks.
// --------------------------------------------------
generate
if (EMPTY_WIDTH > 0) begin
assign in_packet_signals = {in_startofpacket, in_endofpacket, in_empty};
assign {out_startofpacket, out_endofpacket, out_empty} = out_packet_signals;
end
else begin
assign out_empty = in_error;
assign in_packet_signals = {in_startofpacket, in_endofpacket};
assign {out_startofpacket, out_endofpacket} = out_packet_signals;
end
endgenerate
generate
if (USE_PACKETS) begin
if (ERROR_WIDTH > 0) begin
if (CHANNEL_WIDTH > 0) begin
assign in_payload = {in_packet_signals, in_data, in_error, in_channel};
assign {out_packet_signals, out_data, out_error, out_channel} = out_payload;
end
else begin
assign out_channel = in_channel;
assign in_payload = {in_packet_signals, in_data, in_error};
assign {out_packet_signals, out_data, out_error} = out_payload;
end
end
else begin
assign out_error = in_error;
if (CHANNEL_WIDTH > 0) begin
assign in_payload = {in_packet_signals, in_data, in_channel};
assign {out_packet_signals, out_data, out_channel} = out_payload;
end
else begin
assign out_channel = in_channel;
assign in_payload = {in_packet_signals, in_data};
assign {out_packet_signals, out_data} = out_payload;
end
end
end
else begin
assign out_packet_signals = 0;
if (ERROR_WIDTH > 0) begin
if (CHANNEL_WIDTH > 0) begin
assign in_payload = {in_data, in_error, in_channel};
assign {out_data, out_error, out_channel} = out_payload;
end
else begin
assign out_channel = in_channel;
assign in_payload = {in_data, in_error};
assign {out_data, out_error} = out_payload;
end
end
else begin
assign out_error = in_error;
if (CHANNEL_WIDTH > 0) begin
assign in_payload = {in_data, in_channel};
assign {out_data, out_channel} = out_payload;
end
else begin
assign out_channel = in_channel;
assign in_payload = in_data;
assign out_data = out_payload;
end
end
end
endgenerate
// --------------------------------------------------
// Memory-based FIFO storage
//
// To allow a ready latency of 0, the read index is
// obtained from the next read pointer and memory
// outputs are unregistered.
//
// If the empty latency is 1, we infer bypass logic
// around the memory so writes propagate to the
// outputs on the next cycle.
//
// Do not change the way this is coded: Quartus needs
// a perfect match to the template, and any attempt to
// refactor the two always blocks into one will break
// memory inference.
// --------------------------------------------------
generate if (USE_MEMORY_BLOCKS == 1) begin
if (EMPTY_LATENCY == 1) begin
always @(posedge clk) begin
if (in_valid && in_ready)
mem[wr_ptr] = in_payload;
internal_out_payload = mem[mem_rd_ptr];
end
end else begin
always @(posedge clk) begin
if (in_valid && in_ready)
mem[wr_ptr] <= in_payload;
internal_out_payload <= mem[mem_rd_ptr];
end
end
assign mem_rd_ptr = next_rd_ptr;
end else begin
// --------------------------------------------------
// Register-based FIFO storage
//
// Uses a shift register as the storage element. Each
// shift register slot has a bit which indicates if
// the slot is occupied (credit to Sam H for the idea).
// The occupancy bits are contiguous and start from the
// lsb, so 0000, 0001, 0011, 0111, 1111 for a 4-deep
// FIFO.
//
// Each slot is enabled during a read or when it
// is unoccupied. New data is always written to every
// going-to-be-empty slot (we keep track of which ones
// are actually useful with the occupancy bits). On a
// read we shift occupied slots.
//
// The exception is the last slot, which always gets
// new data when it is unoccupied.
// --------------------------------------------------
for (i = 0; i < DEPTH-1; i = i + 1) begin : shift_reg
always @(posedge clk or posedge reset) begin
if (reset) begin
mem[i] <= 0;
end
else if (read || !mem_used[i]) begin
if (!mem_used[i+1])
mem[i] <= in_payload;
else
mem[i] <= mem[i+1];
end
end
end
always @(posedge clk, posedge reset) begin
if (reset) begin
mem[DEPTH-1] <= 0;
end
else begin
if (!mem_used[DEPTH-1])
mem[DEPTH-1] <= in_payload;
if (DEPTH == 1) begin
if (write)
mem[DEPTH-1] <= in_payload;
end
end
end
end
endgenerate
assign read = internal_out_ready && internal_out_valid && ok_to_forward;
assign write = in_ready && in_valid;
// --------------------------------------------------
// Pointer Management
// --------------------------------------------------
generate if (USE_MEMORY_BLOCKS == 1) begin
assign incremented_wr_ptr = wr_ptr + 1'b1;
assign incremented_rd_ptr = rd_ptr + 1'b1;
assign next_wr_ptr = drop_on_error ? sop_ptr : write ? incremented_wr_ptr : wr_ptr;
assign next_rd_ptr = (read) ? incremented_rd_ptr : rd_ptr;
always @(posedge clk or posedge reset) begin
if (reset) begin
wr_ptr <= 0;
rd_ptr <= 0;
end
else begin
wr_ptr <= next_wr_ptr;
rd_ptr <= next_rd_ptr;
end
end
end else begin
// --------------------------------------------------
// Shift Register Occupancy Bits
//
// Consider a 4-deep FIFO with 2 entries: 0011
// On a read and write, do not modify the bits.
// On a write, left-shift the bits to get 0111.
// On a read, right-shift the bits to get 0001.
//
// Also, on a write we set bit0 (the head), while
// clearing the tail on a read.
// --------------------------------------------------
always @(posedge clk or posedge reset) begin
if (reset) begin
mem_used[0] <= 0;
end
else begin
if (write ^ read) begin
if (read) begin
if (DEPTH > 1)
mem_used[0] <= mem_used[1];
else
mem_used[0] <= 0;
end
if (write)
mem_used[0] <= 1;
end
end
end
if (DEPTH > 1) begin
always @(posedge clk or posedge reset) begin
if (reset) begin
mem_used[DEPTH-1] <= 0;
end
else begin
if (write ^ read) begin
mem_used[DEPTH-1] <= 0;
if (write)
mem_used[DEPTH-1] <= mem_used[DEPTH-2];
end
end
end
end
for (i = 1; i < DEPTH-1; i = i + 1) begin : storage_logic
always @(posedge clk, posedge reset) begin
if (reset) begin
mem_used[i] <= 0;
end
else begin
if (write ^ read) begin
if (read)
mem_used[i] <= mem_used[i+1];
if (write)
mem_used[i] <= mem_used[i-1];
end
end
end
end
end
endgenerate
// --------------------------------------------------
// Memory FIFO Status Management
//
// Generates the full and empty signals from the
// pointers. The FIFO is full when the next write
// pointer will be equal to the read pointer after
// a write. Reading from a FIFO clears full.
//
// The FIFO is empty when the next read pointer will
// be equal to the write pointer after a read. Writing
// to a FIFO clears empty.
//
// A simultaneous read and write must not change any of
// the empty or full flags unless there is a drop on error event.
// --------------------------------------------------
generate if (USE_MEMORY_BLOCKS == 1) begin
always @* begin
next_full = full;
next_empty = empty;
if (read && !write) begin
next_full = 1'b0;
if (incremented_rd_ptr == wr_ptr)
next_empty = 1'b1;
end
if (write && !read) begin
if (!drop_on_error)
next_empty = 1'b0;
else if (sop_ptr == rd_ptr) // drop on error and only 1 pkt in fifo
next_empty = 1'b1;
if (incremented_wr_ptr == rd_ptr && !drop_on_error)
next_full = 1'b1;
end
if (write && read && drop_on_error) begin
if (sop_ptr == next_rd_ptr)
next_empty = 1'b1;
end
end
always @(posedge clk or posedge reset) begin
if (reset) begin
empty <= 1;
full <= 0;
end
else begin
empty <= next_empty;
full <= next_full;
end
end
end else begin
// --------------------------------------------------
// Register FIFO Status Management
//
// Full when the tail occupancy bit is 1. Empty when
// the head occupancy bit is 0.
// --------------------------------------------------
always @* begin
full = mem_used[DEPTH-1];
empty = !mem_used[0];
// ------------------------------------------
// For a single slot FIFO, reading clears the
// full status immediately.
// ------------------------------------------
if (DEPTH == 1)
full = mem_used[0] && !read;
internal_out_payload = mem[0];
// ------------------------------------------
// Writes clear empty immediately for lookahead modes.
// Note that we use in_valid instead of write to avoid
// combinational loops (in lookahead mode, qualifying
// with in_ready is meaningless).
//
// In a 1-deep FIFO, a possible combinational loop runs
// from write -> out_valid -> out_ready -> write
// ------------------------------------------
if (EMPTY_LATENCY == 0) begin
empty = !mem_used[0] && !in_valid;
if (!mem_used[0] && in_valid)
internal_out_payload = in_payload;
end
end
end
endgenerate
// --------------------------------------------------
// Avalon-ST Signals
//
// The in_ready signal is straightforward.
//
// To match memory latency when empty latency > 1,
// out_valid assertions must be delayed by one clock
// cycle.
//
// Note: out_valid deassertions must not be delayed or
// the FIFO will underflow.
// --------------------------------------------------
assign in_ready = !full;
assign internal_out_ready = out_ready || !out_valid;
generate if (EMPTY_LATENCY > 1) begin
always @(posedge clk or posedge reset) begin
if (reset)
internal_out_valid <= 0;
else begin
internal_out_valid <= !empty & ok_to_forward & ~drop_on_error;
if (read) begin
if (incremented_rd_ptr == wr_ptr)
internal_out_valid <= 1'b0;
end
end
end
end else begin
always @* begin
internal_out_valid = !empty & ok_to_forward;
end
end
endgenerate
// --------------------------------------------------
// Single Output Pipeline Stage
//
// This output pipeline stage is enabled if the FIFO's
// empty latency is set to 3 (default). It is disabled
// for all other allowed latencies.
//
// Reason: The memory outputs are unregistered, so we have to
// register the output or fmax will drop if combinatorial
// logic is present on the output datapath.
//
// Q: The Avalon-ST spec says that I have to register my outputs
// But isn't the memory counted as a register?
// A: The path from the address lookup to the memory output is
// slow. Registering the memory outputs is a good idea.
//
// The registers get packed into the memory by the fitter
// which means minimal resources are consumed (the result
// is a altsyncram with registered outputs, available on
// all modern Altera devices).
//
// This output stage acts as an extra slot in the FIFO,
// and complicates the fill level.
// --------------------------------------------------
generate if (EMPTY_LATENCY == 3) begin
always @(posedge clk or posedge reset) begin
if (reset) begin
out_valid <= 0;
out_payload <= 0;
end
else begin
if (internal_out_ready) begin
out_valid <= internal_out_valid & ok_to_forward;
out_payload <= internal_out_payload;
end
end
end
end
else begin
always @* begin
out_valid = internal_out_valid;
out_payload = internal_out_payload;
end
end
endgenerate
// --------------------------------------------------
// Fill Level
//
// The fill level is calculated from the next write
// and read pointers to avoid unnecessary latency.
//
// If the output pipeline is enabled, the fill level
// must account for it, or we'll always be off by one.
// This may, or may not be important depending on the
// application.
//
// For now, we'll always calculate the exact fill level
// at the cost of an extra adder when the output stage
// is enabled.
// --------------------------------------------------
generate if (USE_FILL_LEVEL) begin
wire [31:0] depth32;
assign depth32 = DEPTH;
always @(posedge clk or posedge reset) begin
if (reset)
fifo_fill_level <= 0;
else if (next_full & !drop_on_error)
fifo_fill_level <= depth32[ADDR_WIDTH:0];
else begin
fifo_fill_level[ADDR_WIDTH] <= 1'b0;
fifo_fill_level[ADDR_WIDTH-1 : 0] <= next_wr_ptr - next_rd_ptr;
end
end
always @* begin
fill_level = fifo_fill_level;
if (EMPTY_LATENCY == 3)
fill_level = fifo_fill_level + {{ADDR_WIDTH{1'b0}}, out_valid};
end
end
else begin
always @* begin
fill_level = 0;
end
end
endgenerate
generate if (USE_ALMOST_FULL_IF) begin
assign almost_full_data = (fill_level >= almost_full_threshold);
end
else
assign almost_full_data = 0;
endgenerate
generate if (USE_ALMOST_EMPTY_IF) begin
assign almost_empty_data = (fill_level <= almost_empty_threshold);
end
else
assign almost_empty_data = 0;
endgenerate
// --------------------------------------------------
// Avalon-MM Status & Control Connection Point
//
// Register map:
//
// | Addr | RW | 31 - 0 |
// | 0 | R | Fill level |
//
// The registering of this connection point means
// that there is a cycle of latency between
// reads/writes and the updating of the fill level.
// --------------------------------------------------
generate if (USE_STORE_FORWARD) begin
assign max_fifo_size = FIFO_DEPTH - 1;
always @(posedge clk or posedge reset) begin
if (reset) begin
almost_full_threshold <= max_fifo_size[23 : 0];
almost_empty_threshold <= 0;
cut_through_threshold <= 0;
drop_on_error_en <= 0;
csr_readdata <= 0;
pkt_mode <= 1'b1;
end
else begin
if (csr_write) begin
if(csr_address == 3'b010)
almost_full_threshold <= csr_writedata[23:0];
if(csr_address == 3'b011)
almost_empty_threshold <= csr_writedata[23:0];
if(csr_address == 3'b100) begin
cut_through_threshold <= csr_writedata[23:0];
pkt_mode <= (csr_writedata[23:0] == 0);
end
if(csr_address == 3'b101)
drop_on_error_en <= csr_writedata[0];
end
if (csr_read) begin
csr_readdata <= 32'b0;
if (csr_address == 0)
csr_readdata <= {{(31 - ADDR_WIDTH){1'b0}}, fill_level};
if (csr_address == 2)
csr_readdata <= {8'b0, almost_full_threshold};
if (csr_address == 3)
csr_readdata <= {8'b0, almost_empty_threshold};
if (csr_address == 4)
csr_readdata <= {8'b0, cut_through_threshold};
if (csr_address == 5)
csr_readdata <= {31'b0, drop_on_error_en};
end
end
end
end
else if (USE_ALMOST_FULL_IF || USE_ALMOST_EMPTY_IF) begin
assign max_fifo_size = FIFO_DEPTH - 1;
always @(posedge clk or posedge reset) begin
if (reset) begin
almost_full_threshold <= max_fifo_size[23 : 0];
almost_empty_threshold <= 0;
csr_readdata <= 0;
end
else begin
if (csr_write) begin
if(csr_address == 3'b010)
almost_full_threshold <= csr_writedata[23:0];
if(csr_address == 3'b011)
almost_empty_threshold <= csr_writedata[23:0];
end
if (csr_read) begin
csr_readdata <= 32'b0;
if (csr_address == 0)
csr_readdata <= {{(31 - ADDR_WIDTH){1'b0}}, fill_level};
if (csr_address == 2)
csr_readdata <= {8'b0, almost_full_threshold};
if (csr_address == 3)
csr_readdata <= {8'b0, almost_empty_threshold};
end
end
end
end
else begin
always @(posedge clk or posedge reset) begin
if (reset) begin
csr_readdata <= 0;
end
else if (csr_read) begin
csr_readdata <= 0;
if (csr_address == 0)
csr_readdata <= fill_level;
end
end
end
endgenerate
// --------------------------------------------------
// Store and forward logic
// --------------------------------------------------
// if the fifo gets full before the entire packet or the
// cut-threshold condition is met then start sending out
// data in order to avoid dead-lock situation
generate if (USE_STORE_FORWARD) begin
assign wait_for_threshold = (fifo_fill_level_lt_cut_through_threshold) & wait_for_pkt ;
assign wait_for_pkt = pkt_cnt_eq_zero | (pkt_cnt_eq_one & out_pkt_leave);
assign ok_to_forward = (pkt_mode ? (~wait_for_pkt | ~pkt_has_started) :
~wait_for_threshold) | fifo_too_small_r;
assign in_pkt_eop_arrive = in_valid & in_ready & in_endofpacket;
assign in_pkt_start = in_valid & in_ready & in_startofpacket;
assign in_pkt_error = in_valid & in_ready & |in_error;
assign out_pkt_sop_leave = out_valid & out_ready & out_startofpacket;
assign out_pkt_leave = out_valid & out_ready & out_endofpacket;
assign fifo_too_small = (pkt_mode ? wait_for_pkt : wait_for_threshold) & full & out_ready;
// count packets coming and going into the fifo
always @(posedge clk or posedge reset) begin
if (reset) begin
pkt_cnt <= 0;
pkt_cnt_r <= 0;
pkt_cnt_plusone <= 1;
pkt_cnt_minusone <= 0;
pkt_cnt_changed <= 0;
pkt_has_started <= 0;
sop_has_left_fifo <= 0;
fifo_too_small_r <= 0;
pkt_cnt_eq_zero <= 1'b1;
pkt_cnt_eq_one <= 1'b0;
fifo_fill_level_lt_cut_through_threshold <= 1'b1;
end
else begin
fifo_fill_level_lt_cut_through_threshold <= fifo_fill_level < cut_through_threshold;
fifo_too_small_r <= fifo_too_small;
pkt_cnt_plusone <= pkt_cnt + 1'b1;
pkt_cnt_minusone <= pkt_cnt - 1'b1;
pkt_cnt_r <= pkt_cnt;
pkt_cnt_changed <= 1'b0;
if( in_pkt_eop_arrive )
sop_has_left_fifo <= 1'b0;
else if (out_pkt_sop_leave & pkt_cnt_eq_zero )
sop_has_left_fifo <= 1'b1;
if (in_pkt_eop_arrive & ~out_pkt_leave & ~drop_on_error ) begin
pkt_cnt_changed <= 1'b1;
pkt_cnt <= pkt_cnt_changed ? pkt_cnt_r : pkt_cnt_plusone;
pkt_cnt_eq_zero <= 0;
if (pkt_cnt == 0)
pkt_cnt_eq_one <= 1'b1;
else
pkt_cnt_eq_one <= 1'b0;
end
else if((~in_pkt_eop_arrive | drop_on_error) & out_pkt_leave) begin
pkt_cnt_changed <= 1'b1;
pkt_cnt <= pkt_cnt_changed ? pkt_cnt_r : pkt_cnt_minusone;
if (pkt_cnt == 1)
pkt_cnt_eq_zero <= 1'b1;
else
pkt_cnt_eq_zero <= 1'b0;
if (pkt_cnt == 2)
pkt_cnt_eq_one <= 1'b1;
else
pkt_cnt_eq_one <= 1'b0;
end
if (in_pkt_start)
pkt_has_started <= 1'b1;
else if (in_pkt_eop_arrive)
pkt_has_started <= 1'b0;
end
end
// drop on error logic
always @(posedge clk or posedge reset) begin
if (reset) begin
sop_ptr <= 0;
error_in_pkt <= 0;
end
else begin
// save the location of the SOP
if ( in_pkt_start )
sop_ptr <= wr_ptr;
// remember if error in pkt
// log error only if packet has already started
if (in_pkt_eop_arrive)
error_in_pkt <= 1'b0;
else if ( in_pkt_error & (pkt_has_started | in_pkt_start))
error_in_pkt <= 1'b1;
end
end
assign drop_on_error = drop_on_error_en & (error_in_pkt | in_pkt_error) & in_pkt_eop_arrive &
~sop_has_left_fifo & ~(out_pkt_sop_leave & pkt_cnt_eq_zero);
end
else begin
assign ok_to_forward = 1'b1;
assign drop_on_error = 1'b0;
end
endgenerate
// --------------------------------------------------
// Calculates the log2ceil of the input value
// --------------------------------------------------
function integer log2ceil;
input integer val;
integer i;
begin
i = 1;
log2ceil = 0;
while (i < val) begin
log2ceil = log2ceil + 1;
i = i << 1;
end
end
endfunction
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
bit a_finished;
bit b_finished;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
wire [31:0] o;
wire si = 1'b0;
ExampInst i
(// Outputs
.o (o[31:0]),
// Inputs
.i (1'b0)
/*AUTOINST*/);
Prog p (/*AUTOINST*/
// Inputs
.si (si));
always @ (posedge clk) begin
if (!a_finished) $stop;
if (!b_finished) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module InstModule (
output logic [31:0] so,
input si
);
assign so = {32{si}};
endmodule
program Prog (input si);
initial a_finished = 1'b1;
endprogram
module ExampInst (o,i);
output logic [31:0] o;
input i;
InstModule instName
(// Outputs
.so (o[31:0]),
// Inputs
.si (i)
/*AUTOINST*/);
//bind InstModule Prog instProg
// (.si(si));
// Note is based on context of caller
bind InstModule Prog instProg
(/*AUTOBIND*/
.si (si));
endmodule
// Check bind at top level
bind InstModule Prog2 instProg2
(/*AUTOBIND*/
.si (si));
// Check program declared after bind
program Prog2 (input si);
initial b_finished = 1'b1;
endprogram
|
//-----------------------------------------------------------------------------
// 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 min_max_tracker
`include "min_max_tracker.v"
`define FIN "tb_tmp/data.filtered.gold"
`define FOUT_MIN "tb_tmp/data.min"
`define FOUT_MAX "tb_tmp/data.max"
module min_max_tracker_tb;
integer fin;
integer fout_min, fout_max;
integer r;
reg clk;
reg [7:0] adc_d;
wire [7:0] min;
wire [7:0] max;
initial
begin
clk = 0;
fin = $fopen(`FIN, "r");
if (!fin) begin
$display("ERROR: can't open the data file");
$finish;
end
fout_min = $fopen(`FOUT_MIN, "w+");
fout_max = $fopen(`FOUT_MAX, "w+");
if (!$feof(fin))
adc_d = $fgetc(fin); // read the first value
end
always
# 1 clk = !clk;
// input
initial
begin
while (!$feof(fin)) begin
@(negedge clk) adc_d <= $fgetc(fin);
end
if ($feof(fin))
begin
# 3 $fclose(fin);
$fclose(fout_min);
$fclose(fout_max);
$finish;
end
end
initial
begin
// $monitor("%d\t min: %x, max: %x", $time, min, max);
end
// output
always @(negedge clk)
if ($time > 2) begin
r = $fputc(min, fout_min);
r = $fputc(max, fout_max);
end
// module to test
min_max_tracker tracker(clk, adc_d, 8'd127, min, max);
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 *)
(***********************************************************************)
(**************************************************************)
(* FSetDecide.v *)
(* *)
(* Author: Aaron Bohannon *)
(**************************************************************)
(** This file implements a decision procedure for a certain
class of propositions involving finite sets. *)
Require Import Decidable Setoid DecidableTypeEx FSetFacts.
(** First, a version for Weak Sets in functorial presentation *)
Module WDecide_fun (E : DecidableType)(Import M : WSfun E).
Module F := FSetFacts.WFacts_fun 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 FSet-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 FSetLogicalFacts.
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 FSetLogicalFacts.
Import FSetLogicalFacts.
(** * 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 FSetDecideAuxiliary.
(** ** 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-FSet-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 FSet_elt_Prop : Prop -> Prop :=
| eq_Prop : forall (S : Type) (x y : S),
FSet_elt_Prop (x = y)
| eq_elt_prop : forall x y,
FSet_elt_Prop (E.eq x y)
| In_elt_prop : forall x s,
FSet_elt_Prop (In x s)
| True_elt_prop :
FSet_elt_Prop True
| False_elt_prop :
FSet_elt_Prop False
| conj_elt_prop : forall P Q,
FSet_elt_Prop P ->
FSet_elt_Prop Q ->
FSet_elt_Prop (P /\ Q)
| disj_elt_prop : forall P Q,
FSet_elt_Prop P ->
FSet_elt_Prop Q ->
FSet_elt_Prop (P \/ Q)
| impl_elt_prop : forall P Q,
FSet_elt_Prop P ->
FSet_elt_Prop Q ->
FSet_elt_Prop (P -> Q)
| not_elt_prop : forall P,
FSet_elt_Prop P ->
FSet_elt_Prop (~ P).
Inductive FSet_Prop : Prop -> Prop :=
| elt_FSet_Prop : forall P,
FSet_elt_Prop P ->
FSet_Prop P
| Empty_FSet_Prop : forall s,
FSet_Prop (Empty s)
| Subset_FSet_Prop : forall s1 s2,
FSet_Prop (Subset s1 s2)
| Equal_FSet_Prop : forall s1 s2,
FSet_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 FSet_elt_Prop FSet_Prop : FSet_Prop.
Ltac discard_nonFSet :=
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 (FSet_Prop P) holds by
(auto 100 with FSet_Prop)
then fail
else clear H
end).
(** ** Turning Set Operators into Propositional Connectives
The lemmas from [FSetFacts] 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 FSet 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 [FSet_decidability] will be given to
the [push_neg] tactic from the module [Negation]. *)
Hint Resolve dec_In dec_eq : FSet_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 substFSet :=
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_FSet_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 substFSet; 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_FSet_hypotheses;
autorewrite with set_simpl set_eq_simpl in *;
push not in * using FSet_decidability;
substFSet;
assert_decidability;
auto;
(intuition fsetdec_rec) ||
fail 1
"because the goal is beyond the scope of this tactic".
End FSetDecideAuxiliary.
Import FSetDecideAuxiliary.
(** * 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_nonFSet] and [assert_decidability] tactics to
do a much better job. *)
decompose records;
discard_nonFSet;
(** 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 [FSet_elt_Prop], noting
that any [FSet_elt_Prop] is decidable. *)
pull not using FSet_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 (FSet_elt_Prop P) holds by
(auto 100 with FSet_Prop)
then (contradict H; fsetdec_body)
else fsetdec_body
| |- _ =>
fsetdec_body
end.
(** * Examples *)
Module FSetDecideTestCases.
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 FSetDecideTestCases.
End WDecide_fun.
Require Import FSetInterface.
(** 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:WS) := !WDecide_fun M.E M.
Module Decide := WDecide.
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Lane Brooks
`define WIDTH 2
module top (
input OE1,
input OE2,
input [`WIDTH-1:0] A1,
input [`WIDTH-1:0] A2,
output [`WIDTH-1:0] Y1,
output [`WIDTH-1:0] Y2,
output [`WIDTH-1:0] Y3,
output [`WIDTH**2-1:0] W);
assign W[A1] = (OE2) ? A2[0] : 1'bz;
assign W[A2] = (OE1) ? A2[1] : 1'bz;
// have 2 different 'chips' drive the PAD to act like a bi-directional bus
wire [`WIDTH-1:0] PAD;
io_ring io_ring1 (.OE(OE1), .A(A1), .O(Y1), .PAD(PAD));
io_ring io_ring2 (.OE(OE2), .A(A2), .O(Y2), .PAD(PAD));
assign Y3 = PAD;
pullup p1(PAD);
// pulldown p1(PAD);
wire [5:0] fill = { 4'b0, A1 };
endmodule
module io_ring (input OE, input [`WIDTH-1:0] A, output [`WIDTH-1:0] O, inout [`WIDTH-1:0] PAD);
io io[`WIDTH-1:0] (.OE(OE), .I(A), .O(O), .PAD(PAD));
endmodule
module io (input OE, input I, output O, inout PAD);
assign O = PAD;
assign PAD = OE ? I : 1'bz;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
counter_io c1_data();
counter_io c2_data();
//counter_io c3_data; // IEEE illegal, and VCS doesn't allow non-() as it does with cells
counter_io c3_data();
counter_ansi c1 (.clkm(clk),
.c_data(c1_data),
.i_value(4'h1));
counter_ansi c2 (.clkm(clk),
.c_data(c2_data),
.i_value(4'h2));
`ifdef VERILATOR counter_ansi `else counter_nansi `endif
/**/ c3 (.clkm(clk),
.c_data(c3_data),
.i_value(4'h3));
initial begin
c1_data.value = 4'h4;
c2_data.value = 4'h5;
c3_data.value = 4'h6;
end
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc<2) begin
c1_data.reset <= 1;
c2_data.reset <= 1;
c3_data.reset <= 1;
end
if (cyc==2) begin
c1_data.reset <= 0;
c2_data.reset <= 0;
c3_data.reset <= 0;
end
if (cyc==3) begin
if (c1_data.get_lcl() != 12345) $stop;
end
if (cyc==20) begin
$write("[%0t] c1 cyc%0d: c1 %0x %0x c2 %0x %0x c3 %0x %0x\n", $time, cyc,
c1_data.value, c1_data.reset,
c2_data.value, c2_data.reset,
c3_data.value, c3_data.reset);
if (c1_data.value != 2) $stop;
if (c2_data.value != 3) $stop;
if (c3_data.value != 4) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
interface counter_io;
logic [3:0] value;
logic reset;
integer lcl;
task set_lcl (input integer a); lcl=a; endtask
function integer get_lcl (); return lcl; endfunction
endinterface
interface ifunused;
logic unused;
endinterface
module counter_ansi
(
input clkm,
counter_io c_data,
input logic [3:0] i_value
);
initial begin
c_data.set_lcl(12345);
end
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_ansi
`ifndef VERILATOR
// non-ansi modports not seen in the wild yet. Verilog-Perl needs parser improvement too.
module counter_nansi(clkm, c_data, i_value);
input clkm;
counter_io c_data;
input logic [3:0] i_value;
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_nansi
`endif
module modunused (ifunused ifinunused);
ifunused ifunused();
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
interface ifc;
integer value;
endinterface
module t (/*AUTOARG*/
// Inputs
clk
);
`ifdef INLINE_A //verilator inline_module
`else //verilator no_inline_module
`endif
input clk;
integer cyc=1;
ifc itop1a();
ifc itop1b();
ifc itop2a();
ifc itop2b();
wrapper c1 (.isuba(itop1a),
.isubb(itop1b),
.i_valuea(14),
.i_valueb(15));
wrapper c2 (.isuba(itop2a),
.isubb(itop2b),
.i_valuea(24),
.i_valueb(25));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==20) begin
if (itop1a.value != 14) $stop;
if (itop1b.value != 15) $stop;
if (itop2a.value != 24) $stop;
if (itop2b.value != 25) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module wrapper
(
ifc isuba,
ifc isubb,
input integer i_valuea,
input integer i_valueb
);
`ifdef INLINE_B //verilator inline_module
`else //verilator no_inline_module
`endif
lower subsuba (.isub(isuba), .i_value(i_valuea));
lower subsubb (.isub(isubb), .i_value(i_valueb));
endmodule
module lower
(
ifc isub,
input integer i_value
);
`ifdef INLINE_C //verilator inline_module
`else //verilator no_inline_module
`endif
always @* begin
isub.value = i_value;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
interface ifc;
integer value;
endinterface
module t (/*AUTOARG*/
// Inputs
clk
);
`ifdef INLINE_A //verilator inline_module
`else //verilator no_inline_module
`endif
input clk;
integer cyc=1;
ifc itop1a();
ifc itop1b();
ifc itop2a();
ifc itop2b();
wrapper c1 (.isuba(itop1a),
.isubb(itop1b),
.i_valuea(14),
.i_valueb(15));
wrapper c2 (.isuba(itop2a),
.isubb(itop2b),
.i_valuea(24),
.i_valueb(25));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==20) begin
if (itop1a.value != 14) $stop;
if (itop1b.value != 15) $stop;
if (itop2a.value != 24) $stop;
if (itop2b.value != 25) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module wrapper
(
ifc isuba,
ifc isubb,
input integer i_valuea,
input integer i_valueb
);
`ifdef INLINE_B //verilator inline_module
`else //verilator no_inline_module
`endif
lower subsuba (.isub(isuba), .i_value(i_valuea));
lower subsubb (.isub(isubb), .i_value(i_valueb));
endmodule
module lower
(
ifc isub,
input integer i_value
);
`ifdef INLINE_C //verilator inline_module
`else //verilator no_inline_module
`endif
always @* begin
isub.value = i_value;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
interface ifc;
integer value;
endinterface
module t (/*AUTOARG*/
// Inputs
clk
);
`ifdef INLINE_A //verilator inline_module
`else //verilator no_inline_module
`endif
input clk;
integer cyc=1;
ifc itop1a();
ifc itop1b();
ifc itop2a();
ifc itop2b();
wrapper c1 (.isuba(itop1a),
.isubb(itop1b),
.i_valuea(14),
.i_valueb(15));
wrapper c2 (.isuba(itop2a),
.isubb(itop2b),
.i_valuea(24),
.i_valueb(25));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==20) begin
if (itop1a.value != 14) $stop;
if (itop1b.value != 15) $stop;
if (itop2a.value != 24) $stop;
if (itop2b.value != 25) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module wrapper
(
ifc isuba,
ifc isubb,
input integer i_valuea,
input integer i_valueb
);
`ifdef INLINE_B //verilator inline_module
`else //verilator no_inline_module
`endif
lower subsuba (.isub(isuba), .i_value(i_valuea));
lower subsubb (.isub(isubb), .i_value(i_valueb));
endmodule
module lower
(
ifc isub,
input integer i_value
);
`ifdef INLINE_C //verilator inline_module
`else //verilator no_inline_module
`endif
always @* begin
isub.value = i_value;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 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 [3:0] datai = crc[3:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [3:0] datao; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.datao (datao[3:0]),
// Inputs
.clk (clk),
.datai (datai[3:0]));
// Aggregate outputs into a single result vector
wire [63:0] result = {60'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'h3db7bc8bfe61f983
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test
(
input logic clk,
input logic [3:0] datai,
output logic [3:0] datao
);
genvar i;
parameter SIZE = 4;
logic [SIZE:1][3:0] delay;
always_ff @(posedge clk) begin
delay[1][3:0] <= datai;
end
generate
for (i = 2; i < (SIZE+1); i++) begin
always_ff @(posedge clk) begin
delay[i][3:0] <= delay[i-1][3:0];
end
end
endgenerate
always_comb datao = delay[SIZE][3:0];
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 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 [3:0] datai = crc[3:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [3:0] datao; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.datao (datao[3:0]),
// Inputs
.clk (clk),
.datai (datai[3:0]));
// Aggregate outputs into a single result vector
wire [63:0] result = {60'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'h3db7bc8bfe61f983
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test
(
input logic clk,
input logic [3:0] datai,
output logic [3:0] datao
);
genvar i;
parameter SIZE = 4;
logic [SIZE:1][3:0] delay;
always_ff @(posedge clk) begin
delay[1][3:0] <= datai;
end
generate
for (i = 2; i < (SIZE+1); i++) begin
always_ff @(posedge clk) begin
delay[i][3:0] <= delay[i-1][3:0];
end
end
endgenerate
always_comb datao = delay[SIZE][3:0];
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;
parameter [31:0] TWENTY4 = 24;
parameter [31:0] PA = TWENTY4/8;
parameter [1:0] VALUE = 2'b10;
parameter [5:0] REPL = {PA{VALUE}};
parameter [7:0] CONC = {REPL,VALUE};
parameter DBITS = 32;
parameter INIT_BYTE = 8'h1F;
parameter DWORDS_LOG2 = 7;
parameter DWORDS = (1<<DWORDS_LOG2);
parameter DBYTES=DBITS/8;
// verilator lint_off LITENDIAN
reg [DBITS-1:0] mem [0:DWORDS-1];
// verilator lint_on LITENDIAN
integer i;
integer cyc=1;
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==1) begin
if (REPL != {2'b10,2'b10,2'b10}) $stop;
if (CONC != {2'b10,2'b10,2'b10,2'b10}) $stop;
end
if (cyc==2) begin
for (i = 0; i < DWORDS; i = i + 1)
mem[i] = {DBYTES{INIT_BYTE}};
end
if (cyc==3) begin
for (i = 0; i < DWORDS; i = i + 1)
if (mem[i] != {DBYTES{INIT_BYTE}}) $stop;
end
if (cyc==9) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
|
/////////////////////////////////////////////////////////////////////////
//
// pLIB
// D-FLIP-FLOPS
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// p_I_FD FD error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FD (Q,D,C,E);
parameter INIT=1'b0;
output Q;
input D;
input C;
input E;
wire Dtemp;
// Xilinx FD instance
defparam FD_z.INIT=INIT;
FD FD_z (.Q(Q),.D(Dtemp),.C(C));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FD FD error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FD (Q,D,C,E);
parameter INIT = 1'b0;
output Q;
input D;
input C;
input E;
wire Qtemp;
// Xilinx FD instance
FD #(.INIT(INIT)) FD_z (.Q(Qtemp),.D(D),.C(C));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FD_1 FD_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FD_1 (Q,D,C,E);
output Q;
input D;
input C;
input E;
wire Dtemp;
// Xilinx FD instance
FD_1 FD_z (.Q(Q),.D(Dtemp),.C(C));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FD_1 FD_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FD_1 (Q,D,C,E);
output Q;
input D;
input C;
input E;
wire Qtemp;
// Xilinx FD instance
FD_1 FD_z (.Q(Qtemp),.D(D),.C(C));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDC FDC error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDC (Q,D,C,CLR,E);
output Q;
input D;
input C;
input E;
input CLR;
wire Dtemp;
// Xilinx FD instance
FDC FD_z (.Q(Q),.D(Dtemp),.C(C),.CLR(CLR));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDC FDC error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDC (Q,D,C,CLR,E);
output Q;
input D;
input C;
input E;
input CLR;
wire Qtemp;
// Xilinx FD instance
FDC FD_z (.Q(Qtemp),.D(D),.C(C),.CLR(CLR));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDC_1 FDC_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDC_1 (Q,D,C,CLR,E);
output Q;
input D;
input C;
input E;
input CLR;
wire Dtemp;
// Xilinx FD instance
FDC_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.CLR(CLR));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDC_1 FDC_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDC_1 (Q,D,C,CLR,E);
output Q;
input D;
input C;
input E;
input CLR;
wire Qtemp;
// Xilinx FD instance
FDC_1 FD_z (.Q(Qtemp),.D(D),.C(C),.CLR(CLR));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDCE FDCE error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDCE (Q,D,C,CLR,CE,E);
output Q;
input D;
input C;
input E;
input CLR;
input CE;
wire Dtemp;
// Xilinx FD instance
FDCE FD_z (.Q(Q),.D(Dtemp),.C(C),.CLR(CLR),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDCE FDCE error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDCE (Q,D,C,CLR,CE,E);
output Q;
input D;
input C;
input E;
input CLR;
input CE;
wire Qtemp;
// Xilinx FD instance
FDCE FD_z (.Q(Qtemp),.D(D),.C(C),.CLR(CLR),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDCE_1 FDCE error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDCE_1 (Q,D,C,CLR,CE,E);
output Q;
input D;
input C;
input E;
input CLR;
input CE;
wire Dtemp;
// Xilinx FD instance
FDCE_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.CLR(CLR),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDCE_1 FDCE_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDCE_1 (Q,D,C,CLR,CE,E);
output Q;
input D;
input C;
input E;
input CLR;
input CE;
wire Qtemp;
// Xilinx FD instance
FDCE_1 FD_z (.Q(Qtemp),.D(D),.C(C),.CLR(CLR),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDCP FDCP error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDCP (Q,D,C,CLR,PRE,E);
output Q;
input D;
input C;
input E;
input CLR;
input PRE;
wire Dtemp;
// Xilinx FD instance
FDCP FD_z (.Q(Q),.D(Dtemp),.C(C),.CLR(CLR),.PRE(PRE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDCP FDCP error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDCP (Q,D,C,CLR,PRE,E);
output Q;
input D;
input C;
input E;
input CLR;
input PRE;
wire Qtemp;
// Xilinx FD instance
FDCP FD_z (.Q(Qtemp),.D(D),.C(C),.CLR(CLR),.PRE(PRE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDCP_1 FDCP_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDCP_1 (Q,D,C,CLR,PRE,E);
output Q;
input D;
input C;
input E;
input CLR;
input PRE;
wire Dtemp;
// Xilinx FD instance
FDCP_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.CLR(CLR),.PRE(PRE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDCP_1 FDCP_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDCP_1 (Q,D,C,CLR,PRE,E);
output Q;
input D;
input C;
input E;
input CLR;
input PRE;
wire Qtemp;
// Xilinx FD instance
FDCP_1 FD_z (.Q(Qtemp),.D(D),.C(C),.CLR(CLR),.PRE(PRE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDCPE FDCPE error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDCPE (Q,D,C,CLR,PRE,CE,E);
output Q;
input D;
input C;
input E;
input CLR;
input PRE;
input CE;
wire Dtemp;
// Xilinx FD instance
FDCPE FD_z (.Q(Q),.D(Dtemp),.C(C),.CLR(CLR),.PRE(PRE),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDCPE FDCPE error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDCPE (Q,D,C,CLR,PRE,CE,E);
output Q;
input D;
input C;
input E;
input CLR;
input PRE;
input CE;
wire Qtemp;
// Xilinx FD instance
FDCPE FD_z (.Q(Qtemp),.D(D),.C(C),.CLR(CLR),.PRE(PRE),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDCPE_1 FDCPE_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDCPE_1 (Q,D,C,CLR,PRE,CE,E);
output Q;
input D;
input C;
input E;
input CLR;
input PRE;
input CE;
wire Dtemp;
// Xilinx FD instance
FDCPE_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.CLR(CLR),.PRE(PRE),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDCPE_1 FDCPE_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDCPE_1 (Q,D,C,CLR,PRE,CE,E);
output Q;
input D;
input C;
input E;
input CLR;
input PRE;
input CE;
wire Qtemp;
// Xilinx FD instance
FDCPE_1 FD_z (.Q(Qtemp),.D(D),.C(C),.CLR(CLR),.PRE(PRE),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDE FDE error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDE (Q,D,C,CE,E);
output Q;
input D;
input C;
input E;
input CE;
wire Dtemp;
// Xilinx FD instance
FDE FD_z (.Q(Q),.D(Dtemp),.C(C),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDE FDE error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDE (Q,D,C,CE,E);
output Q;
input D;
input C;
input E;
input CE;
wire Qtemp;
// Xilinx FD instance
FDE FD_z (.Q(Qtemp),.D(D),.C(C),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDE_1 FDE_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDE_1 (Q,D,C,CE,E);
output Q;
input D;
input C;
input E;
input CE;
wire Dtemp;
// Xilinx FD instance
FDE_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDE_1 FDE_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDE_1 (Q,D,C,CE,E);
output Q;
input D;
input C;
input E;
input CE;
wire Qtemp;
// Xilinx FD instance
FDE_1 FD_z (.Q(Qtemp),.D(D),.C(C),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDP FDP error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDP (Q,D,C,PRE,E);
output Q;
input D;
input C;
input E;
input PRE;
wire Dtemp;
// Xilinx FD instance
FDP FD_z (.Q(Q),.D(Dtemp),.C(C),.PRE(PRE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDP FDP error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDP (Q,D,C,PRE,E);
output Q;
input D;
input C;
input E;
input PRE;
wire Qtemp;
// Xilinx FD instance
FDP FD_z (.Q(Qtemp),.D(D),.C(C),.PRE(PRE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDP_1 FDP_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDP_1 (Q,D,C,PRE,E);
output Q;
input D;
input C;
input E;
input PRE;
wire Dtemp;
// Xilinx FD instance
FDP_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.PRE(PRE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDP_1 FDP_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDP_1 (Q,D,C,PRE,E);
output Q;
input D;
input C;
input E;
input PRE;
wire Qtemp;
// Xilinx FD instance
FDP_1 FD_z (.Q(Qtemp),.D(D),.C(C),.PRE(PRE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDPE FDPE error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDPE (Q,D,C,PRE,CE,E);
output Q;
input D;
input C;
input E;
input PRE;
input CE;
wire Dtemp;
// Xilinx FD instance
FDPE FD_z (.Q(Q),.D(Dtemp),.C(C),.PRE(PRE),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDPE FDPE error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDPE (Q,D,C,PRE,CE,E);
output Q;
input D;
input C;
input E;
input PRE;
input CE;
wire Qtemp;
// Xilinx FD instance
FDPE FD_z (.Q(Qtemp),.D(D),.C(C),.PRE(PRE),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDPE_1 FDPE_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDPE_1 (Q,D,C,PRE,CE,E);
output Q;
input D;
input C;
input E;
input PRE;
input CE;
wire Dtemp;
// Xilinx FD instance
FDPE_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.PRE(PRE),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDPE_1 FDPE_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDPE_1 (Q,D,C,PRE,CE,E);
output Q;
input D;
input C;
input E;
input PRE;
input CE;
wire Qtemp;
// Xilinx FD instance
FDPE_1 FD_z (.Q(Qtemp),.D(D),.C(C),.PRE(PRE),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDR FDR error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDR (Q,D,C,R,E);
output Q;
input D;
input C;
input E;
input R;
wire Dtemp;
// Xilinx FD instance
FDR FD_z (.Q(Q),.D(Dtemp),.C(C),.R(R));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDR FDR error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDR (Q,D,C,R,E);
parameter INIT=1'b0;
output Q;
input D;
input C;
input E;
input R;
wire Qtemp;
defparam FD_z.INIT=INIT;
// Xilinx FD instance
FDR FD_z (.Q(Qtemp),.D(D),.C(C),.R(R));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDR_1 FDR_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDR_1 (Q,D,C,R,E);
output Q;
input D;
input C;
input E;
input R;
wire Dtemp;
// Xilinx FD instance
FDR_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.R(R));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDR_1 FDR_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDR_1 (Q,D,C,R,E);
output Q;
input D;
input C;
input E;
input R;
wire Qtemp;
// Xilinx FD instance
FDR_1 FD_z (.Q(Qtemp),.D(D),.C(C),.R(R));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDRE FDRE error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDRE (Q,D,C,R,CE,E);
output Q;
input D;
input C;
input E;
input R;
input CE;
wire Dtemp;
// Xilinx FD instance
FDRE FD_z (.Q(Q),.D(Dtemp),.C(C),.R(R),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDRE FDRE error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDRE (Q,D,C,R,CE,E);
parameter INIT=1'b0;
output Q;
input D;
input C;
input E;
input R;
input CE;
wire Qtemp;
// Xilinx FD instance
FDRE #(.INIT(INIT)) FD_z (.Q(Qtemp),.D(D),.C(C),.R(R),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDRE_1 FDRE_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDRE_1 (Q,D,C,R,CE,E);
output Q;
input D;
input C;
input E;
input R;
input CE;
wire Dtemp;
// Xilinx FD instance
FDRE_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.R(R),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDRE_1 FDRE_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDRE_1 (Q,D,C,R,CE,E);
output Q;
input D;
input C;
input E;
input R;
input CE;
wire Qtemp;
// Xilinx FD instance
FDRE_1 FD_z (.Q(Qtemp),.D(D),.C(C),.R(R),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDRS FDRS error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDRS (Q,D,C,R,S,E);
output Q;
input D;
input C;
input E;
input R;
input S;
wire Dtemp;
// Xilinx FD instance
FDRS FD_z (.Q(Q),.D(Dtemp),.C(C),.R(R),.S(S));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDRS FDRS error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDRS (Q,D,C,R,S,E);
output Q;
input D;
input C;
input E;
input R;
input S;
wire Qtemp;
// Xilinx FD instance
FDRS FD_z (.Q(Qtemp),.D(D),.C(C),.R(R),.S(S));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDRS_1 FDRS_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDRS_1 (Q,D,C,R,S,E);
output Q;
input D;
input C;
input E;
input R;
input S;
wire Dtemp;
// Xilinx FD instance
FDRS_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.R(R),.S(S));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDRS_1 FDRS_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDRS_1 (Q,D,C,R,S,E);
output Q;
input D;
input C;
input E;
input R;
input S;
wire Qtemp;
// Xilinx FD instance
FDRS_1 FD_z (.Q(Qtemp),.D(D),.C(C),.R(R),.S(S));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDRSE FDRS error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDRSE (Q,D,C,R,S,CE,E);
output Q;
input D;
input C;
input E;
input R;
input S;
input CE;
wire Dtemp;
// Xilinx FD instance
FDRSE FD_z (.Q(Q),.D(Dtemp),.C(C),.R(R),.S(S),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDRSE FDRSE error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDRSE (Q,D,C,R,S,CE,E);
output Q;
input D;
input C;
input E;
input R;
input S;
input CE;
wire Qtemp;
// Xilinx FD instance
FDRSE FD_z (.Q(Qtemp),.D(D),.C(C),.R(R),.S(S),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDRSE_1 FDRSE_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDRSE_1 (Q,D,C,R,S,CE,E);
output Q;
input D;
input C;
input E;
input R;
input S;
input CE;
wire Dtemp;
// Xilinx FD instance
FDRSE_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.R(R),.S(S),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDRSE_1 FDRSE_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDRSE_1 (Q,D,C,R,S,CE,E);
output Q;
input D;
input C;
input E;
input R;
input S;
input CE;
wire Qtemp;
// Xilinx FD instance
FDRSE_1 FD_z (.Q(Qtemp),.D(D),.C(C),.R(R),.S(S),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDS FDS error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDS (Q,D,C,S,E);
output Q;
input D;
input C;
input E;
input S;
wire Dtemp;
// Xilinx FD instance
FDS FD_z (.Q(Q),.D(Dtemp),.C(C),.S(S));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDS FDS error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDS (Q,D,C,S,E);
output Q;
input D;
input C;
input E;
input S;
wire Qtemp;
// Xilinx FD instance
FDS FD_z (.Q(Qtemp),.D(D),.C(C),.S(S));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDS_1 FDS_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDS_1 (Q,D,C,S,E);
output Q;
input D;
input C;
input E;
input S;
wire Dtemp;
// Xilinx FD instance
FDS_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.S(S));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDS_1 FDS_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDS_1 (Q,D,C,S,E);
output Q;
input D;
input C;
input E;
input S;
wire Qtemp;
// Xilinx FD instance
FDS_1 FD_z (.Q(Qtemp),.D(D),.C(C),.S(S));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDSE FDSE error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDSE (Q,D,C,S,CE,E);
output Q;
input D;
input C;
input E;
input S;
input CE;
wire Dtemp;
// Xilinx FD instance
FDSE FD_z (.Q(Q),.D(Dtemp),.C(C),.S(S),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDSE FDSE error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDSE (Q,D,C,S,CE,E);
output Q;
input D;
input C;
input E;
input S;
input CE;
wire Qtemp;
// Xilinx FD instance
FDSE FD_z (.Q(Qtemp),.D(D),.C(C),.S(S),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_I_FDSE_1 FDSE_1 error at input
/////////////////////////////////////////////////////////////////////////
module p_I_FDSE_1 (Q,D,C,S,CE,E);
output Q;
input D;
input C;
input E;
input S;
input CE;
wire Dtemp;
// Xilinx FD instance
FDSE_1 FD_z (.Q(Q),.D(Dtemp),.C(C),.S(S),.CE(CE));
// Error injection
xor (Dtemp,D,E);
endmodule
/////////////////////////////////////////////////////////////////////////
// p_O_FDSE_1 FDSE_1 error at output
/////////////////////////////////////////////////////////////////////////
module p_O_FDSE_1 (Q,D,C,S,CE,E);
output Q;
input D;
input C;
input E;
input S;
input CE;
wire Qtemp;
// Xilinx FD instance
FDSE_1 FD_z (.Q(Qtemp),.D(D),.C(C),.S(S),.CE(CE));
// Error injection
xor (Q,Qtemp,E);
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// This test demonstrates how not only parameters but the type of a parent
// interface could propagate down to child modules, changing their data type
// determinations. Note presently unsupported in all commercial simulators.
interface ifc;
parameter MODE = 0;
generate
// Note block must be named per SystemVerilog 2005
if (MODE==1) begin : g
integer value;
end
else if (MODE==2) begin : g
real value;
end
endgenerate
endinterface
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(1) itop1a();
ifc #(1) itop1b();
ifc #(2) itop2a();
ifc #(2) itop2b();
wrapper c1 (.isuba(itop1a),
.isubb(itop1b),
.i_valuea(14.1),
.i_valueb(15.2));
wrapper c2 (.isuba(itop2a),
.isubb(itop2b),
.i_valuea(24.3),
.i_valueb(25.4));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==20) begin
if (itop1a.g.value != 14) $stop;
if (itop1b.g.value != 15) $stop;
if (itop2a.g.value != 24) $stop;
if (itop2b.g.value != 25) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module wrapper
(
ifc isuba,
ifc isubb,
input real i_valuea,
input real i_valueb
);
lower subsuba (.isub(isuba), .i_value(i_valuea));
lower subsubb (.isub(isubb), .i_value(i_valueb));
endmodule
module lower
(
ifc isub,
input real i_value
);
always @* begin
`error Commercial sims choke on cross ref here
isub.g.value = i_value;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// This test demonstrates how not only parameters but the type of a parent
// interface could propagate down to child modules, changing their data type
// determinations. Note presently unsupported in all commercial simulators.
interface ifc;
parameter MODE = 0;
generate
// Note block must be named per SystemVerilog 2005
if (MODE==1) begin : g
integer value;
end
else if (MODE==2) begin : g
real value;
end
endgenerate
endinterface
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(1) itop1a();
ifc #(1) itop1b();
ifc #(2) itop2a();
ifc #(2) itop2b();
wrapper c1 (.isuba(itop1a),
.isubb(itop1b),
.i_valuea(14.1),
.i_valueb(15.2));
wrapper c2 (.isuba(itop2a),
.isubb(itop2b),
.i_valuea(24.3),
.i_valueb(25.4));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==20) begin
if (itop1a.g.value != 14) $stop;
if (itop1b.g.value != 15) $stop;
if (itop2a.g.value != 24) $stop;
if (itop2b.g.value != 25) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module wrapper
(
ifc isuba,
ifc isubb,
input real i_valuea,
input real i_valueb
);
lower subsuba (.isub(isuba), .i_value(i_valuea));
lower subsubb (.isub(isubb), .i_value(i_valueb));
endmodule
module lower
(
ifc isub,
input real i_value
);
always @* begin
`error Commercial sims choke on cross ref here
isub.g.value = i_value;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// This test demonstrates how not only parameters but the type of a parent
// interface could propagate down to child modules, changing their data type
// determinations. Note presently unsupported in all commercial simulators.
interface ifc;
parameter MODE = 0;
generate
// Note block must be named per SystemVerilog 2005
if (MODE==1) begin : g
integer value;
end
else if (MODE==2) begin : g
real value;
end
endgenerate
endinterface
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(1) itop1a();
ifc #(1) itop1b();
ifc #(2) itop2a();
ifc #(2) itop2b();
wrapper c1 (.isuba(itop1a),
.isubb(itop1b),
.i_valuea(14.1),
.i_valueb(15.2));
wrapper c2 (.isuba(itop2a),
.isubb(itop2b),
.i_valuea(24.3),
.i_valueb(25.4));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==20) begin
if (itop1a.g.value != 14) $stop;
if (itop1b.g.value != 15) $stop;
if (itop2a.g.value != 24) $stop;
if (itop2b.g.value != 25) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module wrapper
(
ifc isuba,
ifc isubb,
input real i_valuea,
input real i_valueb
);
lower subsuba (.isub(isuba), .i_value(i_valuea));
lower subsubb (.isub(isubb), .i_value(i_valueb));
endmodule
module lower
(
ifc isub,
input real i_value
);
always @* begin
`error Commercial sims choke on cross ref here
isub.g.value = i_value;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// This test demonstrates how not only parameters but the type of a parent
// interface could propagate down to child modules, changing their data type
// determinations. Note presently unsupported in all commercial simulators.
interface ifc;
parameter MODE = 0;
generate
// Note block must be named per SystemVerilog 2005
if (MODE==1) begin : g
integer value;
end
else if (MODE==2) begin : g
real value;
end
endgenerate
endinterface
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(1) itop1a();
ifc #(1) itop1b();
ifc #(2) itop2a();
ifc #(2) itop2b();
wrapper c1 (.isuba(itop1a),
.isubb(itop1b),
.i_valuea(14.1),
.i_valueb(15.2));
wrapper c2 (.isuba(itop2a),
.isubb(itop2b),
.i_valuea(24.3),
.i_valueb(25.4));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==20) begin
if (itop1a.g.value != 14) $stop;
if (itop1b.g.value != 15) $stop;
if (itop2a.g.value != 24) $stop;
if (itop2b.g.value != 25) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module wrapper
(
ifc isuba,
ifc isubb,
input real i_valuea,
input real i_valueb
);
lower subsuba (.isub(isuba), .i_value(i_valuea));
lower subsubb (.isub(isubb), .i_value(i_valueb));
endmodule
module lower
(
ifc isub,
input real i_value
);
always @* begin
`error Commercial sims choke on cross ref here
isub.g.value = i_value;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2013 by Wilson Snyder.
// This test demonstrates how not only parameters but the type of a parent
// interface could propagate down to child modules, changing their data type
// determinations. Note presently unsupported in all commercial simulators.
interface ifc;
parameter MODE = 0;
generate
// Note block must be named per SystemVerilog 2005
if (MODE==1) begin : g
integer value;
end
else if (MODE==2) begin : g
real value;
end
endgenerate
endinterface
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
ifc #(1) itop1a();
ifc #(1) itop1b();
ifc #(2) itop2a();
ifc #(2) itop2b();
wrapper c1 (.isuba(itop1a),
.isubb(itop1b),
.i_valuea(14.1),
.i_valueb(15.2));
wrapper c2 (.isuba(itop2a),
.isubb(itop2b),
.i_valuea(24.3),
.i_valueb(25.4));
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==20) begin
if (itop1a.g.value != 14) $stop;
if (itop1b.g.value != 15) $stop;
if (itop2a.g.value != 24) $stop;
if (itop2b.g.value != 25) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module wrapper
(
ifc isuba,
ifc isubb,
input real i_valuea,
input real i_valueb
);
lower subsuba (.isub(isuba), .i_value(i_valuea));
lower subsubb (.isub(isubb), .i_value(i_valueb));
endmodule
module lower
(
ifc isub,
input real i_value
);
always @* begin
`error Commercial sims choke on cross ref here
isub.g.value = i_value;
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Iztok Jeras.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// counters
int cnt;
int cnt_bit ;
int cnt_byte;
int cnt_int ;
int cnt_ar1d;
int cnt_ar2d;
// sizes
int siz_bit ;
int siz_byte;
int siz_int ;
int siz_ar1d;
int siz_ar2d;
// add all counters
assign cnt = cnt_bit + cnt_byte + cnt_int + cnt_ar1d + cnt_ar2d;
// finish report
always @ (posedge clk)
if (cnt == 5) begin
if (siz_bit != 1) $stop();
if (siz_byte != 8) $stop();
if (siz_int != 32) $stop();
if (siz_ar1d != 24) $stop();
if (siz_ar2d != 16) $stop();
end else if (cnt > 5) begin
$write("*-* All Finished *-*\n");
$finish;
end
// instances with various types
mod_typ #(.TYP (bit )) mod_bit (clk, cnt_bit [ 1-1:0], siz_bit );
mod_typ #(.TYP (byte )) mod_byte (clk, cnt_byte[ 8-1:0], siz_byte);
mod_typ #(.TYP (int )) mod_int (clk, cnt_int [32-1:0], siz_int );
mod_typ #(.TYP (bit [23:0] )) mod_ar1d (clk, cnt_ar1d[24-1:0], siz_ar1d);
mod_typ #(.TYP (bit [3:0][3:0])) mod_ar2d (clk, cnt_ar2d[16-1:0], siz_ar2d);
endmodule : t
module mod_typ #(
parameter type TYP = byte
)(
input logic clk,
output TYP cnt = 0,
output int siz
);
always @ (posedge clk)
cnt <= cnt + 1;
assign siz = $bits (cnt);
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
interface counter_if;
logic [3:0] value;
logic reset;
modport counter_mp (input reset, output value);
modport core_mp (output reset, input value);
endinterface
// Check can have inst module before top module
module counter_ansi
(
input clkm,
counter_if c_data,
input logic [3:0] i_value
);
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_ansi
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
counter_if c1_data();
counter_if c2_data();
counter_if c3_data();
counter_if c4_data();
counter_ansi c1 (.clkm(clk),
.c_data(c1_data.counter_mp),
.i_value(4'h1));
`ifdef VERILATOR counter_ansi `else counter_nansi `endif
/**/ c2 (.clkm(clk),
.c_data(c2_data.counter_mp),
.i_value(4'h2));
counter_ansi_m c3 (.clkm(clk),
.c_data(c3_data),
.i_value(4'h3));
`ifdef VERILATOR counter_ansi_m `else counter_nansi_m `endif
/**/ c4 (.clkm(clk),
.c_data(c4_data),
.i_value(4'h4));
initial begin
c1_data.value = 4'h4;
c2_data.value = 4'h5;
c3_data.value = 4'h6;
c4_data.value = 4'h7;
end
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc<2) begin
c1_data.reset <= 1;
c2_data.reset <= 1;
c3_data.reset <= 1;
c4_data.reset <= 1;
end
if (cyc==2) begin
c1_data.reset <= 0;
c2_data.reset <= 0;
c3_data.reset <= 0;
c4_data.reset <= 0;
end
if (cyc==20) begin
$write("[%0t] cyc%0d: c1 %0x %0x c2 %0x %0x c3 %0x %0x c4 %0x %0x\n", $time, cyc,
c1_data.value, c1_data.reset,
c2_data.value, c2_data.reset,
c3_data.value, c3_data.reset,
c4_data.value, c4_data.reset);
if (c1_data.value != 2) $stop;
if (c2_data.value != 3) $stop;
if (c3_data.value != 4) $stop;
if (c4_data.value != 5) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`ifndef VERILATOR
// non-ansi modports not seen in the wild yet. Verilog-Perl needs parser improvement too.
module counter_nansi
(clkm, c_data, i_value);
input clkm;
counter_if c_data;
input logic [3:0] i_value;
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_nansi
`endif
module counter_ansi_m
(
input clkm,
counter_if.counter_mp c_data,
input logic [3:0] i_value
);
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_ansi_m
`ifndef VERILATOR
// non-ansi modports not seen in the wild yet. Verilog-Perl needs parser improvement too.
module counter_nansi_m
(clkm, c_data, i_value);
input clkm;
counter_if.counter_mp c_data;
input logic [3:0] i_value;
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_nansi_m
`endif
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
interface counter_if;
logic [3:0] value;
logic reset;
modport counter_mp (input reset, output value);
modport core_mp (output reset, input value);
endinterface
// Check can have inst module before top module
module counter_ansi
(
input clkm,
counter_if c_data,
input logic [3:0] i_value
);
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_ansi
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
counter_if c1_data();
counter_if c2_data();
counter_if c3_data();
counter_if c4_data();
counter_ansi c1 (.clkm(clk),
.c_data(c1_data.counter_mp),
.i_value(4'h1));
`ifdef VERILATOR counter_ansi `else counter_nansi `endif
/**/ c2 (.clkm(clk),
.c_data(c2_data.counter_mp),
.i_value(4'h2));
counter_ansi_m c3 (.clkm(clk),
.c_data(c3_data),
.i_value(4'h3));
`ifdef VERILATOR counter_ansi_m `else counter_nansi_m `endif
/**/ c4 (.clkm(clk),
.c_data(c4_data),
.i_value(4'h4));
initial begin
c1_data.value = 4'h4;
c2_data.value = 4'h5;
c3_data.value = 4'h6;
c4_data.value = 4'h7;
end
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc<2) begin
c1_data.reset <= 1;
c2_data.reset <= 1;
c3_data.reset <= 1;
c4_data.reset <= 1;
end
if (cyc==2) begin
c1_data.reset <= 0;
c2_data.reset <= 0;
c3_data.reset <= 0;
c4_data.reset <= 0;
end
if (cyc==20) begin
$write("[%0t] cyc%0d: c1 %0x %0x c2 %0x %0x c3 %0x %0x c4 %0x %0x\n", $time, cyc,
c1_data.value, c1_data.reset,
c2_data.value, c2_data.reset,
c3_data.value, c3_data.reset,
c4_data.value, c4_data.reset);
if (c1_data.value != 2) $stop;
if (c2_data.value != 3) $stop;
if (c3_data.value != 4) $stop;
if (c4_data.value != 5) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`ifndef VERILATOR
// non-ansi modports not seen in the wild yet. Verilog-Perl needs parser improvement too.
module counter_nansi
(clkm, c_data, i_value);
input clkm;
counter_if c_data;
input logic [3:0] i_value;
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_nansi
`endif
module counter_ansi_m
(
input clkm,
counter_if.counter_mp c_data,
input logic [3:0] i_value
);
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_ansi_m
`ifndef VERILATOR
// non-ansi modports not seen in the wild yet. Verilog-Perl needs parser improvement too.
module counter_nansi_m
(clkm, c_data, i_value);
input clkm;
counter_if.counter_mp c_data;
input logic [3:0] i_value;
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_nansi_m
`endif
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
interface counter_if;
logic [3:0] value;
logic reset;
modport counter_mp (input reset, output value);
modport core_mp (output reset, input value);
endinterface
// Check can have inst module before top module
module counter_ansi
(
input clkm,
counter_if c_data,
input logic [3:0] i_value
);
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_ansi
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=1;
counter_if c1_data();
counter_if c2_data();
counter_if c3_data();
counter_if c4_data();
counter_ansi c1 (.clkm(clk),
.c_data(c1_data.counter_mp),
.i_value(4'h1));
`ifdef VERILATOR counter_ansi `else counter_nansi `endif
/**/ c2 (.clkm(clk),
.c_data(c2_data.counter_mp),
.i_value(4'h2));
counter_ansi_m c3 (.clkm(clk),
.c_data(c3_data),
.i_value(4'h3));
`ifdef VERILATOR counter_ansi_m `else counter_nansi_m `endif
/**/ c4 (.clkm(clk),
.c_data(c4_data),
.i_value(4'h4));
initial begin
c1_data.value = 4'h4;
c2_data.value = 4'h5;
c3_data.value = 4'h6;
c4_data.value = 4'h7;
end
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc<2) begin
c1_data.reset <= 1;
c2_data.reset <= 1;
c3_data.reset <= 1;
c4_data.reset <= 1;
end
if (cyc==2) begin
c1_data.reset <= 0;
c2_data.reset <= 0;
c3_data.reset <= 0;
c4_data.reset <= 0;
end
if (cyc==20) begin
$write("[%0t] cyc%0d: c1 %0x %0x c2 %0x %0x c3 %0x %0x c4 %0x %0x\n", $time, cyc,
c1_data.value, c1_data.reset,
c2_data.value, c2_data.reset,
c3_data.value, c3_data.reset,
c4_data.value, c4_data.reset);
if (c1_data.value != 2) $stop;
if (c2_data.value != 3) $stop;
if (c3_data.value != 4) $stop;
if (c4_data.value != 5) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
`ifndef VERILATOR
// non-ansi modports not seen in the wild yet. Verilog-Perl needs parser improvement too.
module counter_nansi
(clkm, c_data, i_value);
input clkm;
counter_if c_data;
input logic [3:0] i_value;
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_nansi
`endif
module counter_ansi_m
(
input clkm,
counter_if.counter_mp c_data,
input logic [3:0] i_value
);
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_ansi_m
`ifndef VERILATOR
// non-ansi modports not seen in the wild yet. Verilog-Perl needs parser improvement too.
module counter_nansi_m
(clkm, c_data, i_value);
input clkm;
counter_if.counter_mp c_data;
input logic [3:0] i_value;
always @ (posedge clkm) begin
c_data.value <= c_data.reset ? i_value : c_data.value + 1;
end
endmodule : counter_nansi_m
`endif
|
/*+--------------------------------------------------------------------------
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: completer_pkt_gen
// Project Name: Sora
// Target Devices: Virtex5 LX50T
// Tool versions: ISE10.1.03
// Description:
// Purpose: Completer Packet Generator module. This block creates the header
// info for completer packets- it also passes along the data source and
// address info for the TRN state machine block to request the data from
// the egress data presenter.
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module completer_pkt_gen(
input clk,
input rst,
//interface from RX Engine
input [6:0] bar_hit, //denotes which base address was hit
input comp_req, //gets asserted when the rx engine recevies a MemRd request
input [31:0] MEM_addr, //needed to fetch data from egress_data_presenter
input [15:0] MEM_req_id,//needed for completion header
input [15:0] comp_id, //needed for completion header
input [7:0] MEM_tag, //neede for completion header
//interface to completion header fifo
output reg comp_fifo_wren,
output reg [63:0] comp_fifo_data
);
//State machine states
localparam IDLE = 4'h0;
localparam HEAD1 = 4'h1;
localparam HEAD2 = 4'h2;
//parameters used to define fixed header fields
localparam rsvd = 1'b0;
localparam fmt = 2'b10; //always with data
localparam CplD = 5'b01010; //completer
localparam TC = 3'b000;
localparam TD = 1'b0;
localparam EP = 1'b0;
localparam ATTR = 2'b00;
localparam Length = 10'b0000000001; //length is always one DWORD
localparam ByteCount = 12'b000000000100; //BC is always one DWORD
localparam BCM = 1'b0;
reg [3:0] state;
reg [6:0] bar_hit_reg;
reg [26:0] MEM_addr_reg;
reg [15:0] MEM_req_id_reg;
reg [15:0] comp_id_reg;
reg [7:0] MEM_tag_reg;
reg rst_reg;
always@(posedge clk) rst_reg <= rst;
//if there is a memory read request then latch the header information
//needed to create the completion TLP header
always@(posedge clk)begin
if(comp_req)begin
bar_hit_reg <= bar_hit;
MEM_addr_reg[26:0] <= MEM_addr[26:0];
MEM_req_id_reg <= MEM_req_id;
comp_id_reg <= comp_id;
MEM_tag_reg <= MEM_tag;
end
end
// State machine
// Builds headers for completion TLP headers
// Writes them into a FIFO
always @ (posedge clk) begin
if (rst_reg) begin
comp_fifo_data <= 0;
comp_fifo_wren <= 1'b0;
state <= IDLE;
end else begin
case (state)
IDLE : begin
comp_fifo_data <= 0;
comp_fifo_wren <= 1'b0;
if(comp_req)
state<= HEAD1;
else
state<= IDLE;
end
HEAD1 : begin //create first 64-bit completion TLP header
//NOTE: bar_hit_reg[6:0],MEM_addr_reg[26:2] are not part of completion TLP
//header but are used by tx_trn_sm module to fetch data from the
//egress_data_presenter
comp_fifo_data <= {bar_hit_reg[6:0],MEM_addr_reg[26:2],
rsvd,fmt,CplD,rsvd,TC,rsvd,rsvd,rsvd,rsvd,
TD,EP,ATTR,rsvd,rsvd,Length};
comp_fifo_wren <= 1'b1; //write to comp header fifo
state <= HEAD2;
end
HEAD2 : begin //create second 64-bit completion TLP header
comp_fifo_data <= {comp_id_reg[15:0],3'b000, BCM,ByteCount,
MEM_req_id_reg[15:0],MEM_tag_reg[7:0],rsvd,
MEM_addr_reg[6:0]};
comp_fifo_wren <= 1'b1; //write to comp header fifo
state <= IDLE;
end
default : begin
comp_fifo_data <= 0;
comp_fifo_wren <= 1'b0;
state <= IDLE;
end
endcase
end
end
endmodule
|
(** * Types: Type Systems *)
Require Export Smallstep.
Hint Constructors multi.
(** Our next major topic is _type systems_ -- static program
analyses that classify expressions according to the "shapes" of
their results. We'll begin with a typed version of a very simple
language with just booleans and numbers, to introduce the basic
ideas of types, typing rules, and the fundamental theorems about
type systems: _type preservation_ and _progress_. Then we'll move
on to the _simply typed lambda-calculus_, which lives at the core
of every modern functional programming language (including
Coq). *)
(* ###################################################################### *)
(** * Typed Arithmetic Expressions *)
(** To motivate the discussion of type systems, let's begin as
usual with an extremely simple toy language. We want it to have
the potential for programs "going wrong" because of runtime type
errors, so we need something a tiny bit more complex than the
language of constants and addition that we used in chapter
[Smallstep]: a single kind of data (just numbers) is too simple,
but just two kinds (numbers and booleans) already gives us enough
material to tell an interesting story.
The language definition is completely routine. *)
(* ###################################################################### *)
(** ** Syntax *)
(** Informally:
t ::= true
| false
| if t then t else t
| 0
| succ t
| pred t
| iszero t
Formally:
*)
Inductive tm : Type :=
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tzero : tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tiszero : tm -> tm.
(** _Values_ are [true], [false], and numeric values... *)
Inductive bvalue : tm -> Prop :=
| bv_true : bvalue ttrue
| bv_false : bvalue tfalse.
Inductive nvalue : tm -> Prop :=
| nv_zero : nvalue tzero
| nv_succ : forall t, nvalue t -> nvalue (tsucc t).
Definition value (t:tm) := bvalue t \/ nvalue t.
Hint Constructors bvalue nvalue.
Hint Unfold value.
Hint Unfold extend.
(* ###################################################################### *)
(** ** Operational Semantics *)
(** Informally: *)
(**
------------------------------ (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
t1 ==> t1'
-------------------- (ST_Succ)
succ t1 ==> succ t1'
------------ (ST_PredZero)
pred 0 ==> 0
numeric value v1
--------------------- (ST_PredSucc)
pred (succ v1) ==> v1
t1 ==> t1'
-------------------- (ST_Pred)
pred t1 ==> pred t1'
----------------- (ST_IszeroZero)
iszero 0 ==> true
numeric value v1
-------------------------- (ST_IszeroSucc)
iszero (succ v1) ==> false
t1 ==> t1'
------------------------ (ST_Iszero)
iszero t1 ==> iszero t1'
*)
(** Formally: *)
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| 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)
| ST_Succ : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
| ST_PredZero :
(tpred tzero) ==> tzero
| ST_PredSucc : forall t1,
nvalue t1 ->
(tpred (tsucc t1)) ==> t1
| ST_Pred : forall t1 t1',
t1 ==> t1' ->
(tpred t1) ==> (tpred t1')
| ST_IszeroZero :
(tiszero tzero) ==> ttrue
| ST_IszeroSucc : forall t1,
nvalue t1 ->
(tiszero (tsucc t1)) ==> tfalse
| ST_Iszero : forall t1 t1',
t1 ==> t1' ->
(tiszero t1) ==> (tiszero t1')
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredZero"
| Case_aux c "ST_PredSucc" | Case_aux c "ST_Pred"
| Case_aux c "ST_IszeroZero" | Case_aux c "ST_IszeroSucc"
| Case_aux c "ST_Iszero" ].
Hint Constructors step.
(** Notice that the [step] relation doesn't care about whether
expressions make global sense -- it just checks that the operation
in the _next_ reduction step is being applied to the right kinds
of operands.
For example, the term [succ true] (i.e., [tsucc ttrue] in the
formal syntax) cannot take a step, but the almost as obviously
nonsensical term
succ (if true then true else true)
can take a step (once, before becoming stuck). *)
(* ###################################################################### *)
(** ** Normal Forms and Values *)
(** The first interesting thing about the [step] relation in this
language is that the strong progress theorem from the Smallstep
chapter fails! That is, there are terms that are normal
forms (they can't take a step) but not values (because we have not
included them in our definition of possible "results of
evaluation"). Such terms are _stuck_. *)
Notation step_normal_form := (normal_form step).
Definition stuck (t:tm) : Prop :=
step_normal_form t /\ ~ value t.
Hint Unfold stuck.
(** **** Exercise: 2 stars (some_term_is_stuck) *)
Example some_term_is_stuck :
exists t, stuck t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** However, although values and normal forms are not the same in this
language, the former set is included in the latter. This is
important because it shows we did not accidentally define things
so that some value could still take a step. *)
(** **** Exercise: 3 stars, advanced (value_is_nf) *)
(** Hint: You will reach a point in this proof where you need to
use an induction to reason about a term that is known to be a
numeric value. This induction can be performed either over the
term itself or over the evidence that it is a numeric value. The
proof goes through in either case, but you will find that one way
is quite a bit shorter than the other. For the sake of the
exercise, try to complete the proof both ways. *)
Lemma value_is_nf : forall t,
value t -> step_normal_form t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, optional (step_deterministic) *)
(** Using [value_is_nf], we can show that the [step] relation is
also deterministic... *)
Theorem step_deterministic:
deterministic step.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Typing *)
(** The next critical observation about this language is that,
although there are stuck terms, they are all "nonsensical", mixing
booleans and numbers in a way that we don't even _want_ to have a
meaning. We can easily exclude such ill-typed terms by defining a
_typing relation_ that relates terms to the types (either numeric
or boolean) of their final results. *)
Inductive ty : Type :=
| TBool : ty
| TNat : ty.
(** In informal notation, the typing relation is often written
[|- t \in T], pronounced "[t] has type [T]." The [|-] symbol is
called a "turnstile". (Below, we're going to see richer typing
relations where an additional "context" argument is written to the
left of the turnstile. Here, the context is always empty.) *)
(**
---------------- (T_True)
|- true \in Bool
----------------- (T_False)
|- false \in Bool
|- t1 \in Bool |- t2 \in T |- t3 \in T
-------------------------------------------- (T_If)
|- if t1 then t2 else t3 \in T
------------ (T_Zero)
|- 0 \in Nat
|- t1 \in Nat
------------------ (T_Succ)
|- succ t1 \in Nat
|- t1 \in Nat
------------------ (T_Pred)
|- pred t1 \in Nat
|- t1 \in Nat
--------------------- (T_IsZero)
|- iszero t1 \in Bool
*)
Reserved Notation "'|-' t '\in' T" (at level 40).
Inductive has_type : tm -> ty -> Prop :=
| T_True :
|- ttrue \in TBool
| T_False :
|- tfalse \in TBool
| T_If : forall t1 t2 t3 T,
|- t1 \in TBool ->
|- t2 \in T ->
|- t3 \in T ->
|- tif t1 t2 t3 \in T
| T_Zero :
|- tzero \in TNat
| T_Succ : forall t1,
|- t1 \in TNat ->
|- tsucc t1 \in TNat
| T_Pred : forall t1,
|- t1 \in TNat ->
|- tpred t1 \in TNat
| T_Iszero : forall t1,
|- t1 \in TNat ->
|- tiszero t1 \in TBool
where "'|-' t '\in' T" := (has_type t T).
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_True" | Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Zero" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Iszero" ].
Hint Constructors has_type.
(* ###################################################################### *)
(** *** Examples *)
(** It's important to realize that the typing relation is a
_conservative_ (or _static_) approximation: it does not calculate
the type of the normal form of a term. *)
Example has_type_1 :
|- tif tfalse tzero (tsucc tzero) \in TNat.
Proof.
apply T_If.
apply T_False.
apply T_Zero.
apply T_Succ.
apply T_Zero.
Qed.
(** (Since we've included all the constructors of the typing relation
in the hint database, the [auto] tactic can actually find this
proof automatically.) *)
Example has_type_not :
~ (|- tif tfalse tzero ttrue \in TBool).
Proof.
intros Contra. solve by inversion 2. Qed.
(** **** Exercise: 1 star, optional (succ_hastype_nat__hastype_nat) *)
Example succ_hastype_nat__hastype_nat : forall t,
|- tsucc t \in TNat ->
|- t \in TNat.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Canonical forms *)
(** The following two lemmas capture the basic property that defines
the shape of well-typed values. They say that the definition of value
and the typing relation agree. *)
Lemma bool_canonical : forall t,
|- t \in TBool -> value t -> bvalue t.
Proof.
intros t HT HV.
inversion HV; auto.
induction H; inversion HT; auto.
Qed.
Lemma nat_canonical : forall t,
|- t \in TNat -> value t -> nvalue t.
Proof.
intros t HT HV.
inversion HV.
inversion H; subst; inversion HT.
auto.
Qed.
(* ###################################################################### *)
(** ** Progress *)
(** The typing relation enjoys two critical properties. The first is
that well-typed normal forms are values (i.e., not stuck). *)
Theorem progress : forall t T,
|- t \in T ->
value t \/ exists t', t ==> t'.
(** **** Exercise: 3 stars (finish_progress) *)
(** Complete the formal proof of the [progress] property. (Make sure
you understand the informal proof fragment in the following
exercise before starting -- this will save you a lot of time.) *)
Proof with auto.
intros t T HT.
has_type_cases (induction HT) Case...
(* The cases that were obviously values, like T_True and
T_False, were eliminated immediately by auto *)
Case "T_If".
right. inversion IHHT1; clear IHHT1.
SCase "t1 is a value".
apply (bool_canonical t1 HT1) in H.
inversion H; subst; clear H.
exists t2...
exists t3...
SCase "t1 can take a step".
inversion H as [t1' H1].
exists (tif t1' t2 t3)...
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, advanced (finish_progress_informal) *)
(** Complete the corresponding informal proof: *)
(** _Theorem_: If [|- t \in T], then either [t] is a value or else
[t ==> t'] for some [t']. *)
(** _Proof_: By induction on a derivation of [|- t \in T].
- If the last rule in the derivation is [T_If], then [t = if t1
then t2 else t3], with [|- t1 \in Bool], [|- t2 \in T] and [|- t3
\in T]. By the IH, either [t1] is a value or else [t1] can step
to some [t1'].
- If [t1] is a value, then by the canonical forms lemmas
and the fact that [|- t1 \in Bool] we have that [t1]
is a [bvalue] -- i.e., it is either [true] or [false].
If [t1 = true], then [t] steps to [t2] by [ST_IfTrue],
while if [t1 = false], then [t] steps to [t3] by
[ST_IfFalse]. Either way, [t] can step, which is what
we wanted to show.
- If [t1] itself can take a step, then, by [ST_If], so can
[t].
(* FILL IN HERE *)
[] *)
(** This is more interesting than the strong progress theorem that we
saw in the Smallstep chapter, where _all_ normal forms were
values. Here, a term can be stuck, but only if it is ill
typed. *)
(** **** Exercise: 1 star (step_review) *)
(** Quick review. Answer _true_ or _false_. In this language...
- Every well-typed normal form is a value.
- Every value is a normal form.
- The single-step evaluation relation is
a partial function (i.e., it is deterministic).
- The single-step evaluation relation is a _total_ function.
*)
(** [] *)
(* ###################################################################### *)
(** ** Type Preservation *)
(** The second critical property of typing is that, when a well-typed
term takes a step, the result is also a well-typed term.
This theorem is often called the _subject reduction_ property,
because it tells us what happens when the "subject" of the typing
relation is reduced. This terminology comes from thinking of
typing statements as sentences, where the term is the subject and
the type is the predicate. *)
Theorem preservation : forall t t' T,
|- t \in T ->
t ==> t' ->
|- t' \in T.
(** **** Exercise: 2 stars (finish_preservation) *)
(** Complete the formal proof of the [preservation] property. (Again,
make sure you understand the informal proof fragment in the
following exercise first.) *)
Proof with auto.
intros t t' T HT HE.
generalize dependent t'.
has_type_cases (induction HT) Case;
(* every case needs to introduce a couple of things *)
intros t' HE;
(* and we can deal with several impossible
cases all at once *)
try (solve by inversion).
Case "T_If". inversion HE; subst; clear HE.
SCase "ST_IFTrue". assumption.
SCase "ST_IfFalse". assumption.
SCase "ST_If". apply T_If; try assumption.
apply IHHT1; assumption.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, advanced (finish_preservation_informal) *)
(** Complete the following proof: *)
(** _Theorem_: If [|- t \in T] and [t ==> t'], then [|- t' \in T]. *)
(** _Proof_: By induction on a derivation of [|- t \in T].
- If the last rule in the derivation is [T_If], then [t = if t1
then t2 else t3], with [|- t1 \in Bool], [|- t2 \in T] and [|- t3
\in T].
Inspecting the rules for the small-step reduction relation and
remembering that [t] has the form [if ...], we see that the
only ones that could have been used to prove [t ==> t'] are
[ST_IfTrue], [ST_IfFalse], or [ST_If].
- If the last rule was [ST_IfTrue], then [t' = t2]. But we
know that [|- t2 \in T], so we are done.
- If the last rule was [ST_IfFalse], then [t' = t3]. But we
know that [|- t3 \in T], so we are done.
- If the last rule was [ST_If], then [t' = if t1' then t2
else t3], where [t1 ==> t1']. We know [|- t1 \in Bool] so,
by the IH, [|- t1' \in Bool]. The [T_If] rule then gives us
[|- if t1' then t2 else t3 \in T], as required.
(* FILL IN HERE *)
[] *)
(** **** Exercise: 3 stars (preservation_alternate_proof) *)
(** Now prove the same property again by induction on the
_evaluation_ derivation instead of on the typing derivation.
Begin by carefully reading and thinking about the first few
lines of the above proof to make sure you understand what
each one is doing. The set-up for this proof is similar, but
not exactly the same. *)
Theorem preservation' : forall t t' T,
|- t \in T ->
t ==> t' ->
|- t' \in T.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Type Soundness *)
(** Putting progress and preservation together, we can see that a
well-typed term can _never_ reach a stuck state. *)
Definition multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Corollary soundness : forall t t' T,
|- t \in T ->
t ==>* t' ->
~(stuck t').
Proof.
intros t t' T HT P. induction P; intros [R S].
destruct (progress x T HT); auto.
apply IHP. apply (preservation x y T HT H).
unfold stuck. split; auto. Qed.
(* ###################################################################### *)
(** * Aside: the [normalize] Tactic *)
(** When experimenting with definitions of programming languages in
Coq, we often want to see what a particular concrete term steps
to -- i.e., we want to find proofs for goals of the form [t ==>*
t'], where [t] is a completely concrete term and [t'] is unknown.
These proofs are simple but repetitive to do by hand. Consider for
example reducing an arithmetic expression using the small-step
relation [astep]. *)
Definition amultistep st := multi (astep st).
Notation " t '/' st '==>a*' t' " := (amultistep st t t')
(at level 40, st at level 39).
Example astep_example1 :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
apply multi_step with (APlus (ANum 3) (ANum 12)).
apply AS_Plus2.
apply av_num.
apply AS_Mult.
apply multi_step with (ANum 15).
apply AS_Plus.
apply multi_refl.
Qed.
(** We repeatedly apply [multi_step] until we get to a normal
form. The proofs that the intermediate steps are possible are
simple enough that [auto], with appropriate hints, can solve
them. *)
Hint Constructors astep aval.
Example astep_example1' :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
eapply multi_step. auto. simpl.
eapply multi_step. auto. simpl.
apply multi_refl.
Qed.
(** The following custom [Tactic Notation] definition captures this
pattern. In addition, before each [multi_step] we print out the
current goal, so that the user can follow how the term is being
evaluated. *)
Tactic Notation "print_goal" := match goal with |- ?x => idtac x end.
Tactic Notation "normalize" :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; simpl)]);
apply multi_refl.
Example astep_example1'' :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
normalize.
(* At this point in the proof script, the Coq response shows
a trace of how the expression evaluated.
(APlus (ANum 3) (AMult (ANum 3) (ANum 4)) / empty_state ==>a* ANum 15)
(multi (astep empty_state) (APlus (ANum 3) (ANum 12)) (ANum 15))
(multi (astep empty_state) (ANum 15) (ANum 15))
*)
Qed.
(** The [normalize] tactic also provides a simple way to calculate
what the normal form of a term is, by proving a goal with an
existential variable in it. *)
Example astep_example1''' : exists e',
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* e'.
Proof.
eapply ex_intro. normalize.
(* This time, the trace will be:
(APlus (ANum 3) (AMult (ANum 3) (ANum 4)) / empty_state ==>a* ??)
(multi (astep empty_state) (APlus (ANum 3) (ANum 12)) ??)
(multi (astep empty_state) (ANum 15) ??)
where ?? is the variable ``guessed'' by eapply.
*)
Qed.
(** **** Exercise: 1 star (normalize_ex) *)
Theorem normalize_ex : exists e',
(AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state
==>a* e'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (normalize_ex') *)
(** For comparison, prove it using [apply] instead of [eapply]. *)
Theorem normalize_ex' : exists e',
(AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state
==>a* e'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Additional Exercises *)
(** **** Exercise: 2 stars (subject_expansion) *)
(** Having seen the subject reduction property, it is reasonable to
wonder whether the opposity property -- subject _expansion_ --
also holds. That is, is it always the case that, if [t ==> t']
and [|- t' \in T], then [|- t \in T]? If so, prove it. If
not, give a counter-example. (You do not need to prove your
counter-example in Coq, but feel free to do so if you like.)
(* FILL IN HERE *)
[] *)
(** **** Exercise: 2 stars (variation1) *)
(** Suppose, that we add this new rule to the typing relation:
| T_SuccBool : forall t,
|- t \in TBool ->
|- tsucc t \in TBool
Which of the following properties remain true in the presence of
this rule? For each one, write either "remains true" or
else "becomes false." If a property becomes false, give a
counterexample.
- Determinism of [step]
- Progress
- Preservation
[] *)
(** **** Exercise: 2 stars (variation2) *)
(** Suppose, instead, that we add this new rule to the [step] relation:
| ST_Funny1 : forall t2 t3,
(tif ttrue t2 t3) ==> t3
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation3) *)
(** Suppose instead that we add this rule:
| ST_Funny2 : forall t1 t2 t2' t3,
t2 ==> t2' ->
(tif t1 t2 t3) ==> (tif t1 t2' t3)
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation4) *)
(** Suppose instead that we add this rule:
| ST_Funny3 :
(tpred tfalse) ==> (tpred (tpred tfalse))
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation5) *)
(** Suppose instead that we add this rule:
| T_Funny4 :
|- tzero \in TBool
]]
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation6) *)
(** Suppose instead that we add this rule:
| T_Funny5 :
|- tpred tzero \in TBool
]]
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 3 stars, optional (more_variations) *)
(** Make up some exercises of your own along the same lines as
the ones above. Try to find ways of selectively breaking
properties -- i.e., ways of changing the definitions that
break just one of the properties and leave the others alone.
[] *)
(** **** Exercise: 1 star (remove_predzero) *)
(** The evaluation rule [E_PredZero] is a bit counter-intuitive: we
might feel that it makes more sense for the predecessor of zero to
be undefined, rather than being defined to be zero. Can we
achieve this simply by removing the rule from the definition of
[step]? Would doing so create any problems elsewhere?
(* FILL IN HERE *)
[] *)
(** **** Exercise: 4 stars, advanced (prog_pres_bigstep) *)
(** Suppose our evaluation relation is defined in the big-step style.
What are the appropriate analogs of the progress and preservation
properties?
(* FILL IN HERE *)
[] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Types: Type Systems *)
Require Export Smallstep.
Hint Constructors multi.
(** Our next major topic is _type systems_ -- static program
analyses that classify expressions according to the "shapes" of
their results. We'll begin with a typed version of a very simple
language with just booleans and numbers, to introduce the basic
ideas of types, typing rules, and the fundamental theorems about
type systems: _type preservation_ and _progress_. Then we'll move
on to the _simply typed lambda-calculus_, which lives at the core
of every modern functional programming language (including
Coq). *)
(* ###################################################################### *)
(** * Typed Arithmetic Expressions *)
(** To motivate the discussion of type systems, let's begin as
usual with an extremely simple toy language. We want it to have
the potential for programs "going wrong" because of runtime type
errors, so we need something a tiny bit more complex than the
language of constants and addition that we used in chapter
[Smallstep]: a single kind of data (just numbers) is too simple,
but just two kinds (numbers and booleans) already gives us enough
material to tell an interesting story.
The language definition is completely routine. *)
(* ###################################################################### *)
(** ** Syntax *)
(** Informally:
t ::= true
| false
| if t then t else t
| 0
| succ t
| pred t
| iszero t
Formally:
*)
Inductive tm : Type :=
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tzero : tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tiszero : tm -> tm.
(** _Values_ are [true], [false], and numeric values... *)
Inductive bvalue : tm -> Prop :=
| bv_true : bvalue ttrue
| bv_false : bvalue tfalse.
Inductive nvalue : tm -> Prop :=
| nv_zero : nvalue tzero
| nv_succ : forall t, nvalue t -> nvalue (tsucc t).
Definition value (t:tm) := bvalue t \/ nvalue t.
Hint Constructors bvalue nvalue.
Hint Unfold value.
Hint Unfold extend.
(* ###################################################################### *)
(** ** Operational Semantics *)
(** Informally: *)
(**
------------------------------ (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
t1 ==> t1'
-------------------- (ST_Succ)
succ t1 ==> succ t1'
------------ (ST_PredZero)
pred 0 ==> 0
numeric value v1
--------------------- (ST_PredSucc)
pred (succ v1) ==> v1
t1 ==> t1'
-------------------- (ST_Pred)
pred t1 ==> pred t1'
----------------- (ST_IszeroZero)
iszero 0 ==> true
numeric value v1
-------------------------- (ST_IszeroSucc)
iszero (succ v1) ==> false
t1 ==> t1'
------------------------ (ST_Iszero)
iszero t1 ==> iszero t1'
*)
(** Formally: *)
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| 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)
| ST_Succ : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
| ST_PredZero :
(tpred tzero) ==> tzero
| ST_PredSucc : forall t1,
nvalue t1 ->
(tpred (tsucc t1)) ==> t1
| ST_Pred : forall t1 t1',
t1 ==> t1' ->
(tpred t1) ==> (tpred t1')
| ST_IszeroZero :
(tiszero tzero) ==> ttrue
| ST_IszeroSucc : forall t1,
nvalue t1 ->
(tiszero (tsucc t1)) ==> tfalse
| ST_Iszero : forall t1 t1',
t1 ==> t1' ->
(tiszero t1) ==> (tiszero t1')
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredZero"
| Case_aux c "ST_PredSucc" | Case_aux c "ST_Pred"
| Case_aux c "ST_IszeroZero" | Case_aux c "ST_IszeroSucc"
| Case_aux c "ST_Iszero" ].
Hint Constructors step.
(** Notice that the [step] relation doesn't care about whether
expressions make global sense -- it just checks that the operation
in the _next_ reduction step is being applied to the right kinds
of operands.
For example, the term [succ true] (i.e., [tsucc ttrue] in the
formal syntax) cannot take a step, but the almost as obviously
nonsensical term
succ (if true then true else true)
can take a step (once, before becoming stuck). *)
(* ###################################################################### *)
(** ** Normal Forms and Values *)
(** The first interesting thing about the [step] relation in this
language is that the strong progress theorem from the Smallstep
chapter fails! That is, there are terms that are normal
forms (they can't take a step) but not values (because we have not
included them in our definition of possible "results of
evaluation"). Such terms are _stuck_. *)
Notation step_normal_form := (normal_form step).
Definition stuck (t:tm) : Prop :=
step_normal_form t /\ ~ value t.
Hint Unfold stuck.
(** **** Exercise: 2 stars (some_term_is_stuck) *)
Example some_term_is_stuck :
exists t, stuck t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** However, although values and normal forms are not the same in this
language, the former set is included in the latter. This is
important because it shows we did not accidentally define things
so that some value could still take a step. *)
(** **** Exercise: 3 stars, advanced (value_is_nf) *)
(** Hint: You will reach a point in this proof where you need to
use an induction to reason about a term that is known to be a
numeric value. This induction can be performed either over the
term itself or over the evidence that it is a numeric value. The
proof goes through in either case, but you will find that one way
is quite a bit shorter than the other. For the sake of the
exercise, try to complete the proof both ways. *)
Lemma value_is_nf : forall t,
value t -> step_normal_form t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, optional (step_deterministic) *)
(** Using [value_is_nf], we can show that the [step] relation is
also deterministic... *)
Theorem step_deterministic:
deterministic step.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Typing *)
(** The next critical observation about this language is that,
although there are stuck terms, they are all "nonsensical", mixing
booleans and numbers in a way that we don't even _want_ to have a
meaning. We can easily exclude such ill-typed terms by defining a
_typing relation_ that relates terms to the types (either numeric
or boolean) of their final results. *)
Inductive ty : Type :=
| TBool : ty
| TNat : ty.
(** In informal notation, the typing relation is often written
[|- t \in T], pronounced "[t] has type [T]." The [|-] symbol is
called a "turnstile". (Below, we're going to see richer typing
relations where an additional "context" argument is written to the
left of the turnstile. Here, the context is always empty.) *)
(**
---------------- (T_True)
|- true \in Bool
----------------- (T_False)
|- false \in Bool
|- t1 \in Bool |- t2 \in T |- t3 \in T
-------------------------------------------- (T_If)
|- if t1 then t2 else t3 \in T
------------ (T_Zero)
|- 0 \in Nat
|- t1 \in Nat
------------------ (T_Succ)
|- succ t1 \in Nat
|- t1 \in Nat
------------------ (T_Pred)
|- pred t1 \in Nat
|- t1 \in Nat
--------------------- (T_IsZero)
|- iszero t1 \in Bool
*)
Reserved Notation "'|-' t '\in' T" (at level 40).
Inductive has_type : tm -> ty -> Prop :=
| T_True :
|- ttrue \in TBool
| T_False :
|- tfalse \in TBool
| T_If : forall t1 t2 t3 T,
|- t1 \in TBool ->
|- t2 \in T ->
|- t3 \in T ->
|- tif t1 t2 t3 \in T
| T_Zero :
|- tzero \in TNat
| T_Succ : forall t1,
|- t1 \in TNat ->
|- tsucc t1 \in TNat
| T_Pred : forall t1,
|- t1 \in TNat ->
|- tpred t1 \in TNat
| T_Iszero : forall t1,
|- t1 \in TNat ->
|- tiszero t1 \in TBool
where "'|-' t '\in' T" := (has_type t T).
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_True" | Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Zero" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Iszero" ].
Hint Constructors has_type.
(* ###################################################################### *)
(** *** Examples *)
(** It's important to realize that the typing relation is a
_conservative_ (or _static_) approximation: it does not calculate
the type of the normal form of a term. *)
Example has_type_1 :
|- tif tfalse tzero (tsucc tzero) \in TNat.
Proof.
apply T_If.
apply T_False.
apply T_Zero.
apply T_Succ.
apply T_Zero.
Qed.
(** (Since we've included all the constructors of the typing relation
in the hint database, the [auto] tactic can actually find this
proof automatically.) *)
Example has_type_not :
~ (|- tif tfalse tzero ttrue \in TBool).
Proof.
intros Contra. solve by inversion 2. Qed.
(** **** Exercise: 1 star, optional (succ_hastype_nat__hastype_nat) *)
Example succ_hastype_nat__hastype_nat : forall t,
|- tsucc t \in TNat ->
|- t \in TNat.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Canonical forms *)
(** The following two lemmas capture the basic property that defines
the shape of well-typed values. They say that the definition of value
and the typing relation agree. *)
Lemma bool_canonical : forall t,
|- t \in TBool -> value t -> bvalue t.
Proof.
intros t HT HV.
inversion HV; auto.
induction H; inversion HT; auto.
Qed.
Lemma nat_canonical : forall t,
|- t \in TNat -> value t -> nvalue t.
Proof.
intros t HT HV.
inversion HV.
inversion H; subst; inversion HT.
auto.
Qed.
(* ###################################################################### *)
(** ** Progress *)
(** The typing relation enjoys two critical properties. The first is
that well-typed normal forms are values (i.e., not stuck). *)
Theorem progress : forall t T,
|- t \in T ->
value t \/ exists t', t ==> t'.
(** **** Exercise: 3 stars (finish_progress) *)
(** Complete the formal proof of the [progress] property. (Make sure
you understand the informal proof fragment in the following
exercise before starting -- this will save you a lot of time.) *)
Proof with auto.
intros t T HT.
has_type_cases (induction HT) Case...
(* The cases that were obviously values, like T_True and
T_False, were eliminated immediately by auto *)
Case "T_If".
right. inversion IHHT1; clear IHHT1.
SCase "t1 is a value".
apply (bool_canonical t1 HT1) in H.
inversion H; subst; clear H.
exists t2...
exists t3...
SCase "t1 can take a step".
inversion H as [t1' H1].
exists (tif t1' t2 t3)...
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, advanced (finish_progress_informal) *)
(** Complete the corresponding informal proof: *)
(** _Theorem_: If [|- t \in T], then either [t] is a value or else
[t ==> t'] for some [t']. *)
(** _Proof_: By induction on a derivation of [|- t \in T].
- If the last rule in the derivation is [T_If], then [t = if t1
then t2 else t3], with [|- t1 \in Bool], [|- t2 \in T] and [|- t3
\in T]. By the IH, either [t1] is a value or else [t1] can step
to some [t1'].
- If [t1] is a value, then by the canonical forms lemmas
and the fact that [|- t1 \in Bool] we have that [t1]
is a [bvalue] -- i.e., it is either [true] or [false].
If [t1 = true], then [t] steps to [t2] by [ST_IfTrue],
while if [t1 = false], then [t] steps to [t3] by
[ST_IfFalse]. Either way, [t] can step, which is what
we wanted to show.
- If [t1] itself can take a step, then, by [ST_If], so can
[t].
(* FILL IN HERE *)
[] *)
(** This is more interesting than the strong progress theorem that we
saw in the Smallstep chapter, where _all_ normal forms were
values. Here, a term can be stuck, but only if it is ill
typed. *)
(** **** Exercise: 1 star (step_review) *)
(** Quick review. Answer _true_ or _false_. In this language...
- Every well-typed normal form is a value.
- Every value is a normal form.
- The single-step evaluation relation is
a partial function (i.e., it is deterministic).
- The single-step evaluation relation is a _total_ function.
*)
(** [] *)
(* ###################################################################### *)
(** ** Type Preservation *)
(** The second critical property of typing is that, when a well-typed
term takes a step, the result is also a well-typed term.
This theorem is often called the _subject reduction_ property,
because it tells us what happens when the "subject" of the typing
relation is reduced. This terminology comes from thinking of
typing statements as sentences, where the term is the subject and
the type is the predicate. *)
Theorem preservation : forall t t' T,
|- t \in T ->
t ==> t' ->
|- t' \in T.
(** **** Exercise: 2 stars (finish_preservation) *)
(** Complete the formal proof of the [preservation] property. (Again,
make sure you understand the informal proof fragment in the
following exercise first.) *)
Proof with auto.
intros t t' T HT HE.
generalize dependent t'.
has_type_cases (induction HT) Case;
(* every case needs to introduce a couple of things *)
intros t' HE;
(* and we can deal with several impossible
cases all at once *)
try (solve by inversion).
Case "T_If". inversion HE; subst; clear HE.
SCase "ST_IFTrue". assumption.
SCase "ST_IfFalse". assumption.
SCase "ST_If". apply T_If; try assumption.
apply IHHT1; assumption.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, advanced (finish_preservation_informal) *)
(** Complete the following proof: *)
(** _Theorem_: If [|- t \in T] and [t ==> t'], then [|- t' \in T]. *)
(** _Proof_: By induction on a derivation of [|- t \in T].
- If the last rule in the derivation is [T_If], then [t = if t1
then t2 else t3], with [|- t1 \in Bool], [|- t2 \in T] and [|- t3
\in T].
Inspecting the rules for the small-step reduction relation and
remembering that [t] has the form [if ...], we see that the
only ones that could have been used to prove [t ==> t'] are
[ST_IfTrue], [ST_IfFalse], or [ST_If].
- If the last rule was [ST_IfTrue], then [t' = t2]. But we
know that [|- t2 \in T], so we are done.
- If the last rule was [ST_IfFalse], then [t' = t3]. But we
know that [|- t3 \in T], so we are done.
- If the last rule was [ST_If], then [t' = if t1' then t2
else t3], where [t1 ==> t1']. We know [|- t1 \in Bool] so,
by the IH, [|- t1' \in Bool]. The [T_If] rule then gives us
[|- if t1' then t2 else t3 \in T], as required.
(* FILL IN HERE *)
[] *)
(** **** Exercise: 3 stars (preservation_alternate_proof) *)
(** Now prove the same property again by induction on the
_evaluation_ derivation instead of on the typing derivation.
Begin by carefully reading and thinking about the first few
lines of the above proof to make sure you understand what
each one is doing. The set-up for this proof is similar, but
not exactly the same. *)
Theorem preservation' : forall t t' T,
|- t \in T ->
t ==> t' ->
|- t' \in T.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Type Soundness *)
(** Putting progress and preservation together, we can see that a
well-typed term can _never_ reach a stuck state. *)
Definition multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Corollary soundness : forall t t' T,
|- t \in T ->
t ==>* t' ->
~(stuck t').
Proof.
intros t t' T HT P. induction P; intros [R S].
destruct (progress x T HT); auto.
apply IHP. apply (preservation x y T HT H).
unfold stuck. split; auto. Qed.
(* ###################################################################### *)
(** * Aside: the [normalize] Tactic *)
(** When experimenting with definitions of programming languages in
Coq, we often want to see what a particular concrete term steps
to -- i.e., we want to find proofs for goals of the form [t ==>*
t'], where [t] is a completely concrete term and [t'] is unknown.
These proofs are simple but repetitive to do by hand. Consider for
example reducing an arithmetic expression using the small-step
relation [astep]. *)
Definition amultistep st := multi (astep st).
Notation " t '/' st '==>a*' t' " := (amultistep st t t')
(at level 40, st at level 39).
Example astep_example1 :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
apply multi_step with (APlus (ANum 3) (ANum 12)).
apply AS_Plus2.
apply av_num.
apply AS_Mult.
apply multi_step with (ANum 15).
apply AS_Plus.
apply multi_refl.
Qed.
(** We repeatedly apply [multi_step] until we get to a normal
form. The proofs that the intermediate steps are possible are
simple enough that [auto], with appropriate hints, can solve
them. *)
Hint Constructors astep aval.
Example astep_example1' :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
eapply multi_step. auto. simpl.
eapply multi_step. auto. simpl.
apply multi_refl.
Qed.
(** The following custom [Tactic Notation] definition captures this
pattern. In addition, before each [multi_step] we print out the
current goal, so that the user can follow how the term is being
evaluated. *)
Tactic Notation "print_goal" := match goal with |- ?x => idtac x end.
Tactic Notation "normalize" :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; simpl)]);
apply multi_refl.
Example astep_example1'' :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
normalize.
(* At this point in the proof script, the Coq response shows
a trace of how the expression evaluated.
(APlus (ANum 3) (AMult (ANum 3) (ANum 4)) / empty_state ==>a* ANum 15)
(multi (astep empty_state) (APlus (ANum 3) (ANum 12)) (ANum 15))
(multi (astep empty_state) (ANum 15) (ANum 15))
*)
Qed.
(** The [normalize] tactic also provides a simple way to calculate
what the normal form of a term is, by proving a goal with an
existential variable in it. *)
Example astep_example1''' : exists e',
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* e'.
Proof.
eapply ex_intro. normalize.
(* This time, the trace will be:
(APlus (ANum 3) (AMult (ANum 3) (ANum 4)) / empty_state ==>a* ??)
(multi (astep empty_state) (APlus (ANum 3) (ANum 12)) ??)
(multi (astep empty_state) (ANum 15) ??)
where ?? is the variable ``guessed'' by eapply.
*)
Qed.
(** **** Exercise: 1 star (normalize_ex) *)
Theorem normalize_ex : exists e',
(AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state
==>a* e'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (normalize_ex') *)
(** For comparison, prove it using [apply] instead of [eapply]. *)
Theorem normalize_ex' : exists e',
(AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state
==>a* e'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Additional Exercises *)
(** **** Exercise: 2 stars (subject_expansion) *)
(** Having seen the subject reduction property, it is reasonable to
wonder whether the opposity property -- subject _expansion_ --
also holds. That is, is it always the case that, if [t ==> t']
and [|- t' \in T], then [|- t \in T]? If so, prove it. If
not, give a counter-example. (You do not need to prove your
counter-example in Coq, but feel free to do so if you like.)
(* FILL IN HERE *)
[] *)
(** **** Exercise: 2 stars (variation1) *)
(** Suppose, that we add this new rule to the typing relation:
| T_SuccBool : forall t,
|- t \in TBool ->
|- tsucc t \in TBool
Which of the following properties remain true in the presence of
this rule? For each one, write either "remains true" or
else "becomes false." If a property becomes false, give a
counterexample.
- Determinism of [step]
- Progress
- Preservation
[] *)
(** **** Exercise: 2 stars (variation2) *)
(** Suppose, instead, that we add this new rule to the [step] relation:
| ST_Funny1 : forall t2 t3,
(tif ttrue t2 t3) ==> t3
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation3) *)
(** Suppose instead that we add this rule:
| ST_Funny2 : forall t1 t2 t2' t3,
t2 ==> t2' ->
(tif t1 t2 t3) ==> (tif t1 t2' t3)
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation4) *)
(** Suppose instead that we add this rule:
| ST_Funny3 :
(tpred tfalse) ==> (tpred (tpred tfalse))
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation5) *)
(** Suppose instead that we add this rule:
| T_Funny4 :
|- tzero \in TBool
]]
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation6) *)
(** Suppose instead that we add this rule:
| T_Funny5 :
|- tpred tzero \in TBool
]]
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 3 stars, optional (more_variations) *)
(** Make up some exercises of your own along the same lines as
the ones above. Try to find ways of selectively breaking
properties -- i.e., ways of changing the definitions that
break just one of the properties and leave the others alone.
[] *)
(** **** Exercise: 1 star (remove_predzero) *)
(** The evaluation rule [E_PredZero] is a bit counter-intuitive: we
might feel that it makes more sense for the predecessor of zero to
be undefined, rather than being defined to be zero. Can we
achieve this simply by removing the rule from the definition of
[step]? Would doing so create any problems elsewhere?
(* FILL IN HERE *)
[] *)
(** **** Exercise: 4 stars, advanced (prog_pres_bigstep) *)
(** Suppose our evaluation relation is defined in the big-step style.
What are the appropriate analogs of the progress and preservation
properties?
(* FILL IN HERE *)
[] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Types: Type Systems *)
Require Export Smallstep.
Hint Constructors multi.
(** Our next major topic is _type systems_ -- static program
analyses that classify expressions according to the "shapes" of
their results. We'll begin with a typed version of a very simple
language with just booleans and numbers, to introduce the basic
ideas of types, typing rules, and the fundamental theorems about
type systems: _type preservation_ and _progress_. Then we'll move
on to the _simply typed lambda-calculus_, which lives at the core
of every modern functional programming language (including
Coq). *)
(* ###################################################################### *)
(** * Typed Arithmetic Expressions *)
(** To motivate the discussion of type systems, let's begin as
usual with an extremely simple toy language. We want it to have
the potential for programs "going wrong" because of runtime type
errors, so we need something a tiny bit more complex than the
language of constants and addition that we used in chapter
[Smallstep]: a single kind of data (just numbers) is too simple,
but just two kinds (numbers and booleans) already gives us enough
material to tell an interesting story.
The language definition is completely routine. *)
(* ###################################################################### *)
(** ** Syntax *)
(** Informally:
t ::= true
| false
| if t then t else t
| 0
| succ t
| pred t
| iszero t
Formally:
*)
Inductive tm : Type :=
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tzero : tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tiszero : tm -> tm.
(** _Values_ are [true], [false], and numeric values... *)
Inductive bvalue : tm -> Prop :=
| bv_true : bvalue ttrue
| bv_false : bvalue tfalse.
Inductive nvalue : tm -> Prop :=
| nv_zero : nvalue tzero
| nv_succ : forall t, nvalue t -> nvalue (tsucc t).
Definition value (t:tm) := bvalue t \/ nvalue t.
Hint Constructors bvalue nvalue.
Hint Unfold value.
Hint Unfold extend.
(* ###################################################################### *)
(** ** Operational Semantics *)
(** Informally: *)
(**
------------------------------ (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
t1 ==> t1'
-------------------- (ST_Succ)
succ t1 ==> succ t1'
------------ (ST_PredZero)
pred 0 ==> 0
numeric value v1
--------------------- (ST_PredSucc)
pred (succ v1) ==> v1
t1 ==> t1'
-------------------- (ST_Pred)
pred t1 ==> pred t1'
----------------- (ST_IszeroZero)
iszero 0 ==> true
numeric value v1
-------------------------- (ST_IszeroSucc)
iszero (succ v1) ==> false
t1 ==> t1'
------------------------ (ST_Iszero)
iszero t1 ==> iszero t1'
*)
(** Formally: *)
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| 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)
| ST_Succ : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
| ST_PredZero :
(tpred tzero) ==> tzero
| ST_PredSucc : forall t1,
nvalue t1 ->
(tpred (tsucc t1)) ==> t1
| ST_Pred : forall t1 t1',
t1 ==> t1' ->
(tpred t1) ==> (tpred t1')
| ST_IszeroZero :
(tiszero tzero) ==> ttrue
| ST_IszeroSucc : forall t1,
nvalue t1 ->
(tiszero (tsucc t1)) ==> tfalse
| ST_Iszero : forall t1 t1',
t1 ==> t1' ->
(tiszero t1) ==> (tiszero t1')
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredZero"
| Case_aux c "ST_PredSucc" | Case_aux c "ST_Pred"
| Case_aux c "ST_IszeroZero" | Case_aux c "ST_IszeroSucc"
| Case_aux c "ST_Iszero" ].
Hint Constructors step.
(** Notice that the [step] relation doesn't care about whether
expressions make global sense -- it just checks that the operation
in the _next_ reduction step is being applied to the right kinds
of operands.
For example, the term [succ true] (i.e., [tsucc ttrue] in the
formal syntax) cannot take a step, but the almost as obviously
nonsensical term
succ (if true then true else true)
can take a step (once, before becoming stuck). *)
(* ###################################################################### *)
(** ** Normal Forms and Values *)
(** The first interesting thing about the [step] relation in this
language is that the strong progress theorem from the Smallstep
chapter fails! That is, there are terms that are normal
forms (they can't take a step) but not values (because we have not
included them in our definition of possible "results of
evaluation"). Such terms are _stuck_. *)
Notation step_normal_form := (normal_form step).
Definition stuck (t:tm) : Prop :=
step_normal_form t /\ ~ value t.
Hint Unfold stuck.
(** **** Exercise: 2 stars (some_term_is_stuck) *)
Example some_term_is_stuck :
exists t, stuck t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** However, although values and normal forms are not the same in this
language, the former set is included in the latter. This is
important because it shows we did not accidentally define things
so that some value could still take a step. *)
(** **** Exercise: 3 stars, advanced (value_is_nf) *)
(** Hint: You will reach a point in this proof where you need to
use an induction to reason about a term that is known to be a
numeric value. This induction can be performed either over the
term itself or over the evidence that it is a numeric value. The
proof goes through in either case, but you will find that one way
is quite a bit shorter than the other. For the sake of the
exercise, try to complete the proof both ways. *)
Lemma value_is_nf : forall t,
value t -> step_normal_form t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, optional (step_deterministic) *)
(** Using [value_is_nf], we can show that the [step] relation is
also deterministic... *)
Theorem step_deterministic:
deterministic step.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Typing *)
(** The next critical observation about this language is that,
although there are stuck terms, they are all "nonsensical", mixing
booleans and numbers in a way that we don't even _want_ to have a
meaning. We can easily exclude such ill-typed terms by defining a
_typing relation_ that relates terms to the types (either numeric
or boolean) of their final results. *)
Inductive ty : Type :=
| TBool : ty
| TNat : ty.
(** In informal notation, the typing relation is often written
[|- t \in T], pronounced "[t] has type [T]." The [|-] symbol is
called a "turnstile". (Below, we're going to see richer typing
relations where an additional "context" argument is written to the
left of the turnstile. Here, the context is always empty.) *)
(**
---------------- (T_True)
|- true \in Bool
----------------- (T_False)
|- false \in Bool
|- t1 \in Bool |- t2 \in T |- t3 \in T
-------------------------------------------- (T_If)
|- if t1 then t2 else t3 \in T
------------ (T_Zero)
|- 0 \in Nat
|- t1 \in Nat
------------------ (T_Succ)
|- succ t1 \in Nat
|- t1 \in Nat
------------------ (T_Pred)
|- pred t1 \in Nat
|- t1 \in Nat
--------------------- (T_IsZero)
|- iszero t1 \in Bool
*)
Reserved Notation "'|-' t '\in' T" (at level 40).
Inductive has_type : tm -> ty -> Prop :=
| T_True :
|- ttrue \in TBool
| T_False :
|- tfalse \in TBool
| T_If : forall t1 t2 t3 T,
|- t1 \in TBool ->
|- t2 \in T ->
|- t3 \in T ->
|- tif t1 t2 t3 \in T
| T_Zero :
|- tzero \in TNat
| T_Succ : forall t1,
|- t1 \in TNat ->
|- tsucc t1 \in TNat
| T_Pred : forall t1,
|- t1 \in TNat ->
|- tpred t1 \in TNat
| T_Iszero : forall t1,
|- t1 \in TNat ->
|- tiszero t1 \in TBool
where "'|-' t '\in' T" := (has_type t T).
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_True" | Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Zero" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Iszero" ].
Hint Constructors has_type.
(* ###################################################################### *)
(** *** Examples *)
(** It's important to realize that the typing relation is a
_conservative_ (or _static_) approximation: it does not calculate
the type of the normal form of a term. *)
Example has_type_1 :
|- tif tfalse tzero (tsucc tzero) \in TNat.
Proof.
apply T_If.
apply T_False.
apply T_Zero.
apply T_Succ.
apply T_Zero.
Qed.
(** (Since we've included all the constructors of the typing relation
in the hint database, the [auto] tactic can actually find this
proof automatically.) *)
Example has_type_not :
~ (|- tif tfalse tzero ttrue \in TBool).
Proof.
intros Contra. solve by inversion 2. Qed.
(** **** Exercise: 1 star, optional (succ_hastype_nat__hastype_nat) *)
Example succ_hastype_nat__hastype_nat : forall t,
|- tsucc t \in TNat ->
|- t \in TNat.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Canonical forms *)
(** The following two lemmas capture the basic property that defines
the shape of well-typed values. They say that the definition of value
and the typing relation agree. *)
Lemma bool_canonical : forall t,
|- t \in TBool -> value t -> bvalue t.
Proof.
intros t HT HV.
inversion HV; auto.
induction H; inversion HT; auto.
Qed.
Lemma nat_canonical : forall t,
|- t \in TNat -> value t -> nvalue t.
Proof.
intros t HT HV.
inversion HV.
inversion H; subst; inversion HT.
auto.
Qed.
(* ###################################################################### *)
(** ** Progress *)
(** The typing relation enjoys two critical properties. The first is
that well-typed normal forms are values (i.e., not stuck). *)
Theorem progress : forall t T,
|- t \in T ->
value t \/ exists t', t ==> t'.
(** **** Exercise: 3 stars (finish_progress) *)
(** Complete the formal proof of the [progress] property. (Make sure
you understand the informal proof fragment in the following
exercise before starting -- this will save you a lot of time.) *)
Proof with auto.
intros t T HT.
has_type_cases (induction HT) Case...
(* The cases that were obviously values, like T_True and
T_False, were eliminated immediately by auto *)
Case "T_If".
right. inversion IHHT1; clear IHHT1.
SCase "t1 is a value".
apply (bool_canonical t1 HT1) in H.
inversion H; subst; clear H.
exists t2...
exists t3...
SCase "t1 can take a step".
inversion H as [t1' H1].
exists (tif t1' t2 t3)...
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, advanced (finish_progress_informal) *)
(** Complete the corresponding informal proof: *)
(** _Theorem_: If [|- t \in T], then either [t] is a value or else
[t ==> t'] for some [t']. *)
(** _Proof_: By induction on a derivation of [|- t \in T].
- If the last rule in the derivation is [T_If], then [t = if t1
then t2 else t3], with [|- t1 \in Bool], [|- t2 \in T] and [|- t3
\in T]. By the IH, either [t1] is a value or else [t1] can step
to some [t1'].
- If [t1] is a value, then by the canonical forms lemmas
and the fact that [|- t1 \in Bool] we have that [t1]
is a [bvalue] -- i.e., it is either [true] or [false].
If [t1 = true], then [t] steps to [t2] by [ST_IfTrue],
while if [t1 = false], then [t] steps to [t3] by
[ST_IfFalse]. Either way, [t] can step, which is what
we wanted to show.
- If [t1] itself can take a step, then, by [ST_If], so can
[t].
(* FILL IN HERE *)
[] *)
(** This is more interesting than the strong progress theorem that we
saw in the Smallstep chapter, where _all_ normal forms were
values. Here, a term can be stuck, but only if it is ill
typed. *)
(** **** Exercise: 1 star (step_review) *)
(** Quick review. Answer _true_ or _false_. In this language...
- Every well-typed normal form is a value.
- Every value is a normal form.
- The single-step evaluation relation is
a partial function (i.e., it is deterministic).
- The single-step evaluation relation is a _total_ function.
*)
(** [] *)
(* ###################################################################### *)
(** ** Type Preservation *)
(** The second critical property of typing is that, when a well-typed
term takes a step, the result is also a well-typed term.
This theorem is often called the _subject reduction_ property,
because it tells us what happens when the "subject" of the typing
relation is reduced. This terminology comes from thinking of
typing statements as sentences, where the term is the subject and
the type is the predicate. *)
Theorem preservation : forall t t' T,
|- t \in T ->
t ==> t' ->
|- t' \in T.
(** **** Exercise: 2 stars (finish_preservation) *)
(** Complete the formal proof of the [preservation] property. (Again,
make sure you understand the informal proof fragment in the
following exercise first.) *)
Proof with auto.
intros t t' T HT HE.
generalize dependent t'.
has_type_cases (induction HT) Case;
(* every case needs to introduce a couple of things *)
intros t' HE;
(* and we can deal with several impossible
cases all at once *)
try (solve by inversion).
Case "T_If". inversion HE; subst; clear HE.
SCase "ST_IFTrue". assumption.
SCase "ST_IfFalse". assumption.
SCase "ST_If". apply T_If; try assumption.
apply IHHT1; assumption.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 3 stars, advanced (finish_preservation_informal) *)
(** Complete the following proof: *)
(** _Theorem_: If [|- t \in T] and [t ==> t'], then [|- t' \in T]. *)
(** _Proof_: By induction on a derivation of [|- t \in T].
- If the last rule in the derivation is [T_If], then [t = if t1
then t2 else t3], with [|- t1 \in Bool], [|- t2 \in T] and [|- t3
\in T].
Inspecting the rules for the small-step reduction relation and
remembering that [t] has the form [if ...], we see that the
only ones that could have been used to prove [t ==> t'] are
[ST_IfTrue], [ST_IfFalse], or [ST_If].
- If the last rule was [ST_IfTrue], then [t' = t2]. But we
know that [|- t2 \in T], so we are done.
- If the last rule was [ST_IfFalse], then [t' = t3]. But we
know that [|- t3 \in T], so we are done.
- If the last rule was [ST_If], then [t' = if t1' then t2
else t3], where [t1 ==> t1']. We know [|- t1 \in Bool] so,
by the IH, [|- t1' \in Bool]. The [T_If] rule then gives us
[|- if t1' then t2 else t3 \in T], as required.
(* FILL IN HERE *)
[] *)
(** **** Exercise: 3 stars (preservation_alternate_proof) *)
(** Now prove the same property again by induction on the
_evaluation_ derivation instead of on the typing derivation.
Begin by carefully reading and thinking about the first few
lines of the above proof to make sure you understand what
each one is doing. The set-up for this proof is similar, but
not exactly the same. *)
Theorem preservation' : forall t t' T,
|- t \in T ->
t ==> t' ->
|- t' \in T.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Type Soundness *)
(** Putting progress and preservation together, we can see that a
well-typed term can _never_ reach a stuck state. *)
Definition multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Corollary soundness : forall t t' T,
|- t \in T ->
t ==>* t' ->
~(stuck t').
Proof.
intros t t' T HT P. induction P; intros [R S].
destruct (progress x T HT); auto.
apply IHP. apply (preservation x y T HT H).
unfold stuck. split; auto. Qed.
(* ###################################################################### *)
(** * Aside: the [normalize] Tactic *)
(** When experimenting with definitions of programming languages in
Coq, we often want to see what a particular concrete term steps
to -- i.e., we want to find proofs for goals of the form [t ==>*
t'], where [t] is a completely concrete term and [t'] is unknown.
These proofs are simple but repetitive to do by hand. Consider for
example reducing an arithmetic expression using the small-step
relation [astep]. *)
Definition amultistep st := multi (astep st).
Notation " t '/' st '==>a*' t' " := (amultistep st t t')
(at level 40, st at level 39).
Example astep_example1 :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
apply multi_step with (APlus (ANum 3) (ANum 12)).
apply AS_Plus2.
apply av_num.
apply AS_Mult.
apply multi_step with (ANum 15).
apply AS_Plus.
apply multi_refl.
Qed.
(** We repeatedly apply [multi_step] until we get to a normal
form. The proofs that the intermediate steps are possible are
simple enough that [auto], with appropriate hints, can solve
them. *)
Hint Constructors astep aval.
Example astep_example1' :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
eapply multi_step. auto. simpl.
eapply multi_step. auto. simpl.
apply multi_refl.
Qed.
(** The following custom [Tactic Notation] definition captures this
pattern. In addition, before each [multi_step] we print out the
current goal, so that the user can follow how the term is being
evaluated. *)
Tactic Notation "print_goal" := match goal with |- ?x => idtac x end.
Tactic Notation "normalize" :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; simpl)]);
apply multi_refl.
Example astep_example1'' :
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* (ANum 15).
Proof.
normalize.
(* At this point in the proof script, the Coq response shows
a trace of how the expression evaluated.
(APlus (ANum 3) (AMult (ANum 3) (ANum 4)) / empty_state ==>a* ANum 15)
(multi (astep empty_state) (APlus (ANum 3) (ANum 12)) (ANum 15))
(multi (astep empty_state) (ANum 15) (ANum 15))
*)
Qed.
(** The [normalize] tactic also provides a simple way to calculate
what the normal form of a term is, by proving a goal with an
existential variable in it. *)
Example astep_example1''' : exists e',
(APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state
==>a* e'.
Proof.
eapply ex_intro. normalize.
(* This time, the trace will be:
(APlus (ANum 3) (AMult (ANum 3) (ANum 4)) / empty_state ==>a* ??)
(multi (astep empty_state) (APlus (ANum 3) (ANum 12)) ??)
(multi (astep empty_state) (ANum 15) ??)
where ?? is the variable ``guessed'' by eapply.
*)
Qed.
(** **** Exercise: 1 star (normalize_ex) *)
Theorem normalize_ex : exists e',
(AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state
==>a* e'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (normalize_ex') *)
(** For comparison, prove it using [apply] instead of [eapply]. *)
Theorem normalize_ex' : exists e',
(AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state
==>a* e'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** ** Additional Exercises *)
(** **** Exercise: 2 stars (subject_expansion) *)
(** Having seen the subject reduction property, it is reasonable to
wonder whether the opposity property -- subject _expansion_ --
also holds. That is, is it always the case that, if [t ==> t']
and [|- t' \in T], then [|- t \in T]? If so, prove it. If
not, give a counter-example. (You do not need to prove your
counter-example in Coq, but feel free to do so if you like.)
(* FILL IN HERE *)
[] *)
(** **** Exercise: 2 stars (variation1) *)
(** Suppose, that we add this new rule to the typing relation:
| T_SuccBool : forall t,
|- t \in TBool ->
|- tsucc t \in TBool
Which of the following properties remain true in the presence of
this rule? For each one, write either "remains true" or
else "becomes false." If a property becomes false, give a
counterexample.
- Determinism of [step]
- Progress
- Preservation
[] *)
(** **** Exercise: 2 stars (variation2) *)
(** Suppose, instead, that we add this new rule to the [step] relation:
| ST_Funny1 : forall t2 t3,
(tif ttrue t2 t3) ==> t3
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation3) *)
(** Suppose instead that we add this rule:
| ST_Funny2 : forall t1 t2 t2' t3,
t2 ==> t2' ->
(tif t1 t2 t3) ==> (tif t1 t2' t3)
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation4) *)
(** Suppose instead that we add this rule:
| ST_Funny3 :
(tpred tfalse) ==> (tpred (tpred tfalse))
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation5) *)
(** Suppose instead that we add this rule:
| T_Funny4 :
|- tzero \in TBool
]]
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 2 stars, optional (variation6) *)
(** Suppose instead that we add this rule:
| T_Funny5 :
|- tpred tzero \in TBool
]]
Which of the above properties become false in the presence of
this rule? For each one that does, give a counter-example.
[] *)
(** **** Exercise: 3 stars, optional (more_variations) *)
(** Make up some exercises of your own along the same lines as
the ones above. Try to find ways of selectively breaking
properties -- i.e., ways of changing the definitions that
break just one of the properties and leave the others alone.
[] *)
(** **** Exercise: 1 star (remove_predzero) *)
(** The evaluation rule [E_PredZero] is a bit counter-intuitive: we
might feel that it makes more sense for the predecessor of zero to
be undefined, rather than being defined to be zero. Can we
achieve this simply by removing the rule from the definition of
[step]? Would doing so create any problems elsewhere?
(* FILL IN HERE *)
[] *)
(** **** Exercise: 4 stars, advanced (prog_pres_bigstep) *)
(** Suppose our evaluation relation is defined in the big-step style.
What are the appropriate analogs of the progress and preservation
properties?
(* FILL IN HERE *)
[] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
// 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;
// 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 */
integer cnt = 0;
// event counter
always @ (posedge clk)
begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if (cnt==2) begin
$write("*-* All Finished *-*\n");
$finish;
end
always @ (posedge clk)
if (cnt==1) begin
// big endian
if ($bits (struct_bg ) != 15) $stop;
if ($bits (struct_bg.e0) != 1) $stop;
if ($bits (struct_bg.e1) != 2) $stop;
if ($bits (struct_bg.e2) != 4) $stop;
if ($bits (struct_bg.e3) != 8) $stop;
if ($increment (struct_bg, 1) != 1) $stop;
// little endian
if ($bits (struct_lt ) != 15) $stop;
if ($bits (struct_lt.e0) != 1) $stop;
if ($bits (struct_lt.e1) != 2) $stop;
if ($bits (struct_lt.e2) != 4) $stop;
if ($bits (struct_lt.e3) != 8) $stop;
if ($increment (struct_lt, 1) != 1) $stop; // Structure itself always big numbered
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg [2:0] in;
wire a,y,y_fixed;
wire b = in[0];
wire en = in[1];
pullup(a);
ChildA childa ( .A(a), .B(b), .en(en), .Y(y),.Yfix(y_fixed) );
initial in=0;
initial en=0;
// Test loop
always @ (posedge clk) begin
in <= in + 1;
$display ( "a %d b %d en %d y %d yfix: %d)" , a, b, en, y, y_fixed);
if (en) begin
// driving b
// a should be b
// y and yfix should also be b
if (a!=b || y != b || y_fixed != b) begin
$display ( "Expected a %d y %b yfix %b" , a, y, y_fixed);
$stop;
end
end else begin
// not driving b
// a should be 1 (pullup)
// y and yfix shold be 1
if (a!=1 || y != 1 || y_fixed != 1) begin
$display( "Expected a,y,yfix == 1");
$stop;
end
end
if (in==3) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module ChildA(inout A, input B, input en, output Y, output Yfix);
// workaround
wire a_in = A;
ChildB childB(.A(A), .Y(Y));
assign A = en ? B : 1'bz;
ChildB childBfix(.A(a_in),.Y(Yfix));
endmodule
module ChildB(input A, output Y);
assign Y = A;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg [2:0] in;
wire a,y,y_fixed;
wire b = in[0];
wire en = in[1];
pullup(a);
ChildA childa ( .A(a), .B(b), .en(en), .Y(y),.Yfix(y_fixed) );
initial in=0;
initial en=0;
// Test loop
always @ (posedge clk) begin
in <= in + 1;
$display ( "a %d b %d en %d y %d yfix: %d)" , a, b, en, y, y_fixed);
if (en) begin
// driving b
// a should be b
// y and yfix should also be b
if (a!=b || y != b || y_fixed != b) begin
$display ( "Expected a %d y %b yfix %b" , a, y, y_fixed);
$stop;
end
end else begin
// not driving b
// a should be 1 (pullup)
// y and yfix shold be 1
if (a!=1 || y != 1 || y_fixed != 1) begin
$display( "Expected a,y,yfix == 1");
$stop;
end
end
if (in==3) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module ChildA(inout A, input B, input en, output Y, output Yfix);
// workaround
wire a_in = A;
ChildB childB(.A(A), .Y(Y));
assign A = en ? B : 1'bz;
ChildB childBfix(.A(a_in),.Y(Yfix));
endmodule
module ChildB(input A, output Y);
assign Y = A;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
reg [2:0] in;
wire a,y,y_fixed;
wire b = in[0];
wire en = in[1];
pullup(a);
ChildA childa ( .A(a), .B(b), .en(en), .Y(y),.Yfix(y_fixed) );
initial in=0;
initial en=0;
// Test loop
always @ (posedge clk) begin
in <= in + 1;
$display ( "a %d b %d en %d y %d yfix: %d)" , a, b, en, y, y_fixed);
if (en) begin
// driving b
// a should be b
// y and yfix should also be b
if (a!=b || y != b || y_fixed != b) begin
$display ( "Expected a %d y %b yfix %b" , a, y, y_fixed);
$stop;
end
end else begin
// not driving b
// a should be 1 (pullup)
// y and yfix shold be 1
if (a!=1 || y != 1 || y_fixed != 1) begin
$display( "Expected a,y,yfix == 1");
$stop;
end
end
if (in==3) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module ChildA(inout A, input B, input en, output Y, output Yfix);
// workaround
wire a_in = A;
ChildB childB(.A(A), .Y(Y));
assign A = en ? B : 1'bz;
ChildB childBfix(.A(a_in),.Y(Yfix));
endmodule
module ChildB(input A, output Y);
assign Y = A;
endmodule
|
(** * StlcProp: Properties of STLC *)
Require Export Stlc.
Module STLCProp.
Import STLC.
(** In this chapter, we develop the fundamental theory of the Simply
Typed Lambda Calculus -- in particular, the type safety
theorem. *)
(* ###################################################################### *)
(** * Canonical Forms *)
Lemma canonical_forms_bool : forall t,
empty |- t \in TBool ->
value t ->
(t = ttrue) \/ (t = tfalse).
Proof.
intros t HT HVal.
inversion HVal; intros; subst; try inversion HT; auto.
Qed.
Lemma canonical_forms_fun : forall t T1 T2,
empty |- t \in (TArrow T1 T2) ->
value t ->
exists x u, t = tabs x T1 u.
Proof.
intros t T1 T2 HT HVal.
inversion HVal; intros; subst; try inversion HT; subst; auto.
exists x0. exists t0. auto.
Qed.
(* ###################################################################### *)
(** * Progress *)
(** As before, the _progress_ theorem tells us that closed, well-typed
terms are not stuck: either a well-typed term is a value, or it
can take an evaluation step. The proof is a relatively
straightforward extension of the progress proof we saw in the
[Types] chapter. *)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
(** _Proof_: by induction on the derivation of [|- t \in T].
- The last rule of the derivation cannot be [T_Var], since a
variable is never well typed in an empty context.
- The [T_True], [T_False], and [T_Abs] cases are trivial, since in
each of these cases we know immediately that [t] is a value.
- If the last rule of the derivation was [T_App], then [t = t1
t2], and we know that [t1] and [t2] are also well typed in the
empty context; in particular, there exists a type [T2] such that
[|- t1 \in T2 -> T] and [|- t2 \in T2]. By the induction
hypothesis, either [t1] is a value or it can take an evaluation
step.
- If [t1] is a value, we now consider [t2], which by the other
induction hypothesis must also either be a value or take an
evaluation step.
- Suppose [t2] is a value. Since [t1] is a value with an
arrow type, it must be a lambda abstraction; hence [t1
t2] can take a step by [ST_AppAbs].
- Otherwise, [t2] can take a step, and hence so can [t1
t2] by [ST_App2].
- If [t1] can take a step, then so can [t1 t2] by [ST_App1].
- If the last rule of the derivation was [T_If], then [t = if t1
then t2 else t3], where [t1] has type [Bool]. By the IH, [t1]
either is a value or takes a step.
- If [t1] is a value, then since it has type [Bool] it must be
either [true] or [false]. If it is [true], then [t] steps
to [t2]; otherwise it steps to [t3].
- Otherwise, [t1] takes a step, and therefore so does [t] (by
[ST_If]).
*)
Proof with eauto.
intros t T Ht.
remember (@empty ty) as Gamma.
has_type_cases (induction Ht) Case; subst Gamma...
Case "T_Var".
(* contradictory: variables cannot be typed in an
empty context *)
inversion H.
Case "T_App".
(* [t] = [t1 t2]. Proceed by cases on whether [t1] is a
value or steps... *)
right. destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 is also a value".
assert (exists x0 t0, t1 = tabs x0 T11 t0).
eapply canonical_forms_fun; eauto.
destruct H1 as [x0 [t0 Heq]]. subst.
exists ([x0:=t2]t0)...
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".
destruct (canonical_forms_bool t1); subst; eauto.
SCase "t1 also steps".
inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...
Qed.
(** **** Exercise: 3 stars, optional (progress_from_term_ind) *)
(** Show that progress can also be proved by induction on terms
instead of induction on typing derivations. *)
Theorem progress' : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof.
intros t.
t_cases (induction t) Case; intros T Ht; auto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** * Preservation *)
(** The other half of the type soundness property is the preservation
of types during reduction. For this, we need to develop some
technical machinery for reasoning about variables and
substitution. Working from top to bottom (the high-level property
we are actually interested in to the lowest-level technical lemmas
that are needed by various cases of the more interesting proofs),
the story goes like this:
- The _preservation theorem_ is proved by induction on a typing
derivation, pretty much as we did in the [Types] chapter. The
one case that is significantly different is the one for the
[ST_AppAbs] rule, which is defined using the substitution
operation. To see that this step preserves typing, we need to
know that the substitution itself does. So we prove a...
- _substitution lemma_, stating that substituting a (closed)
term [s] for a variable [x] in a term [t] preserves the type
of [t]. The proof goes by induction on the form of [t] and
requires looking at all the different cases in the definition
of substitition. This time, the tricky cases are the ones for
variables and for function abstractions. In both cases, we
discover that we need to take a term [s] that has been shown
to be well-typed in some context [Gamma] and consider the same
term [s] in a slightly different context [Gamma']. For this
we prove a...
- _context invariance_ lemma, showing that typing is preserved
under "inessential changes" to the context [Gamma] -- in
particular, changes that do not affect any of the free
variables of the term. For this, we need a careful definition
of
- the _free variables_ of a term -- i.e., the variables occuring
in the term that are not in the scope of a function
abstraction that binds them.
*)
(* ###################################################################### *)
(** ** Free Occurrences *)
(** A variable [x] _appears free in_ a term _t_ if [t] contains some
occurrence of [x] that is not under an abstraction labeled [x]. For example:
- [y] appears free, but [x] does not, in [\x:T->U. x y]
- both [x] and [y] appear free in [(\x:T->U. x y) x]
- no variables appear free in [\x:T->U. \y:T. x y] *)
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).
Tactic Notation "afi_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "afi_var"
| Case_aux c "afi_app1" | Case_aux c "afi_app2"
| Case_aux c "afi_abs"
| Case_aux c "afi_if1" | Case_aux c "afi_if2"
| Case_aux c "afi_if3" ].
Hint Constructors appears_free_in.
(** A term in which no variables appear free is said to be _closed_. *)
Definition closed (t:tm) :=
forall x, ~ appears_free_in x t.
(* ###################################################################### *)
(** ** Substitution *)
(** We first need a technical lemma connecting free variables and
typing contexts. If a variable [x] appears free in a term [t],
and if we know [t] is well typed in context [Gamma], then it must
be the case that [Gamma] assigns a type to [x]. *)
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_: We show, by induction on the proof that [x] appears free
in [t], that, for all contexts [Gamma], if [t] is well typed
under [Gamma], then [Gamma] assigns some type to [x].
- If the last rule used was [afi_var], then [t = x], and from
the assumption that [t] is well typed under [Gamma] we have
immediately that [Gamma] assigns a type to [x].
- If the last rule used was [afi_app1], then [t = t1 t2] and [x]
appears free in [t1]. Since [t] is well typed under [Gamma],
we can see from the typing rules that [t1] must also be, and
the IH then tells us that [Gamma] assigns [x] a type.
- Almost all the other cases are similar: [x] appears free in a
subterm of [t], and since [t] is well typed under [Gamma], we
know the subterm of [t] in which [x] appears is well typed
under [Gamma] as well, and the IH gives us exactly the
conclusion we want.
- The only remaining case is [afi_abs]. In this case [t =
\y:T11.t12], and [x] appears free in [t12]; we also know that
[x] is different from [y]. The difference from the previous
cases is that whereas [t] is well typed under [Gamma], its
body [t12] is well typed under [(Gamma, y:T11)], so the IH
allows us to conclude that [x] is assigned some type by the
extended context [(Gamma, y:T11)]. To conclude that [Gamma]
assigns a type to [x], we appeal to lemma [extend_neq], noting
that [x] and [y] are different variables. *)
Proof.
intros x t T Gamma H H0. generalize dependent Gamma.
generalize dependent T.
afi_cases (induction H) Case;
intros; try solve [inversion H0; eauto].
Case "afi_abs".
inversion H1; subst.
apply IHappears_free_in in H7.
rewrite extend_neq in H7; assumption.
Qed.
(** Next, we'll need the fact that any term [t] which is well typed in
the empty context is closed -- that is, it has no free variables. *)
(** **** Exercise: 2 stars, optional (typable_empty__closed) *)
Corollary typable_empty__closed : forall t T,
empty |- t \in T ->
closed t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Sometimes, when we have a proof [Gamma |- t : T], we will need to
replace [Gamma] by a different context [Gamma']. When is it safe
to do this? Intuitively, it must at least be the case that
[Gamma'] assigns the same types as [Gamma] to all the variables
that appear free in [t]. In fact, this is the only condition that
is needed. *)
Lemma context_invariance : forall Gamma Gamma' t T,
Gamma |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in T.
(** _Proof_: By induction on the derivation of [Gamma |- t \in T].
- If the last rule in the derivation was [T_Var], then [t = x]
and [Gamma x = T]. By assumption, [Gamma' x = T] as well, and
hence [Gamma' |- t \in T] by [T_Var].
- If the last rule was [T_Abs], then [t = \y:T11. t12], with [T
= T11 -> T12] and [Gamma, y:T11 |- t12 \in T12]. The induction
hypothesis is that for any context [Gamma''], if [Gamma,
y:T11] and [Gamma''] assign the same types to all the free
variables in [t12], then [t12] has type [T12] under [Gamma''].
Let [Gamma'] be a context which agrees with [Gamma] on the
free variables in [t]; we must show [Gamma' |- \y:T11. t12 \in
T11 -> T12].
By [T_Abs], it suffices to show that [Gamma', y:T11 |- t12 \in
T12]. By the IH (setting [Gamma'' = Gamma', y:T11]), it
suffices to show that [Gamma, y:T11] and [Gamma', y:T11] agree
on all the variables that appear free in [t12].
Any variable occurring free in [t12] must either be [y], or
some other variable. [Gamma, y:T11] and [Gamma', y:T11]
clearly agree on [y]. Otherwise, we note that any variable
other than [y] which occurs free in [t12] also occurs free in
[t = \y:T11. t12], and by assumption [Gamma] and [Gamma']
agree on all such variables, and hence so do [Gamma, y:T11]
and [Gamma', y:T11].
- If the last rule was [T_App], then [t = t1 t2], with [Gamma |-
t1 \in T2 -> T] and [Gamma |- t2 \in T2]. One induction
hypothesis states that for all contexts [Gamma'], if [Gamma']
agrees with [Gamma] on the free variables in [t1], then [t1]
has type [T2 -> T] under [Gamma']; there is a similar IH for
[t2]. We must show that [t1 t2] also has type [T] under
[Gamma'], given the assumption that [Gamma'] agrees with
[Gamma] on all the free variables in [t1 t2]. By [T_App], it
suffices to show that [t1] and [t2] each have the same type
under [Gamma'] as under [Gamma]. However, we note that all
free variables in [t1] are also free in [t1 t2], and similarly
for free variables in [t2]; hence the desired result follows
by the two IHs.
*)
Proof with eauto.
intros.
generalize dependent Gamma'.
has_type_cases (induction H) Case; intros; auto.
Case "T_Var".
apply T_Var. rewrite <- H0...
Case "T_Abs".
apply T_Abs.
apply IHhas_type. intros x1 Hafi.
(* the only tricky step... the [Gamma'] we use to
instantiate is [extend Gamma x T11] *)
unfold extend. destruct (eq_id_dec x0 x1)...
Case "T_App".
apply T_App with T11...
Qed.
(** Now we come to the conceptual heart of the proof that reduction
preserves types -- namely, the observation that _substitution_
preserves types.
Formally, the so-called _Substitution Lemma_ says this: suppose we
have a term [t] with a free variable [x], and suppose we've been
able to assign a type [T] to [t] under the assumption that [x] has
some type [U]. Also, suppose that we have some other term [v] and
that we've shown that [v] has type [U]. Then, since [v] satisfies
the assumption we made about [x] when typing [t], we should be
able to substitute [v] for each of the occurrences of [x] in [t]
and obtain a new term that still has type [T]. *)
(** _Lemma_: If [Gamma,x:U |- t \in T] and [|- v \in U], then [Gamma |-
[x:=v]t \in T]. *)
Lemma substitution_preserves_typing : forall Gamma x U t v T,
extend Gamma x U |- t \in T ->
empty |- v \in U ->
Gamma |- [x:=v]t \in T.
(** One technical subtlety in the statement of the lemma is that we
assign [v] the type [U] in the _empty_ context -- in other words,
we assume [v] is closed. This assumption considerably simplifies
the [T_Abs] case of the proof (compared to assuming [Gamma |- v \in
U], which would be the other reasonable assumption at this point)
because the context invariance lemma then tells us that [v] has
type [U] in any context at all -- we don't have to worry about
free variables in [v] clashing with the variable being introduced
into the context by [T_Abs].
_Proof_: We prove, by induction on [t], that, for all [T] and
[Gamma], if [Gamma,x:U |- t \in T] and [|- v \in U], then [Gamma |-
[x:=v]t \in T].
- If [t] is a variable, there are two cases to consider, depending
on whether [t] is [x] or some other variable.
- If [t = x], then from the fact that [Gamma, x:U |- x \in T] we
conclude that [U = T]. We must show that [[x:=v]x = v] has
type [T] under [Gamma], given the assumption that [v] has
type [U = T] under the empty context. This follows from
context invariance: if a closed term has type [T] in the
empty context, it has that type in any context.
- If [t] is some variable [y] that is not equal to [x], then
we need only note that [y] has the same type under [Gamma,
x:U] as under [Gamma].
- If [t] is an abstraction [\y:T11. t12], then the IH tells us,
for all [Gamma'] and [T'], that if [Gamma',x:U |- t12 \in T']
and [|- v \in U], then [Gamma' |- [x:=v]t12 \in T'].
The substitution in the conclusion behaves differently,
depending on whether [x] and [y] are the same variable name.
First, suppose [x = y]. Then, by the definition of
substitution, [[x:=v]t = t], so we just need to show [Gamma |-
t \in T]. But we know [Gamma,x:U |- t : T], and since the
variable [y] does not appear free in [\y:T11. t12], the
context invariance lemma yields [Gamma |- t \in T].
Second, suppose [x <> y]. We know [Gamma,x:U,y:T11 |- t12 \in
T12] by inversion of the typing relation, and [Gamma,y:T11,x:U
|- t12 \in T12] follows from this by the context invariance
lemma, so the IH applies, giving us [Gamma,y:T11 |- [x:=v]t12 \in
T12]. By [T_Abs], [Gamma |- \y:T11. [x:=v]t12 \in T11->T12], and
by the definition of substitution (noting that [x <> y]),
[Gamma |- \y:T11. [x:=v]t12 \in T11->T12] as required.
- If [t] is an application [t1 t2], the result follows
straightforwardly from the definition of substitution and the
induction hypotheses.
- The remaining cases are similar to the application case.
Another technical note: This proof is a rare case where an
induction on terms, rather than typing derivations, yields a
simpler argument. The reason for this is that the assumption
[extend Gamma x U |- t \in T] is not completely generic, in
the sense that one of the "slots" in the typing relation -- namely
the context -- is not just a variable, and this means that Coq's
native induction tactic does not give us the induction hypothesis
that we want. It is possible to work around this, but the needed
generalization is a little tricky. The term [t], on the other
hand, _is_ completely generic. *)
Proof with eauto.
intros Gamma x U t v T Ht Ht'.
generalize dependent Gamma. generalize dependent T.
t_cases (induction t) Case; intros T Gamma H;
(* in each case, we'll want to get at the derivation of H *)
inversion H; subst; simpl...
Case "tvar".
rename i into y. destruct (eq_id_dec x y).
SCase "x=y".
subst.
rewrite extend_eq in H2.
inversion H2; subst. clear H2.
eapply context_invariance... intros x Hcontra.
destruct (free_in_context _ _ T empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
apply T_Var. rewrite extend_neq in H2...
Case "tabs".
rename i into y. 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...
Qed.
(** The substitution lemma can be viewed as a kind of "commutation"
property. Intuitively, it says that substitution and typing can
be done in either order: we can either assign types to the terms
[t] and [v] separately (under suitable contexts) and then combine
them using substitution, or we can substitute first and then
assign a type to [ [x:=v] t ] -- the result is the same either
way. *)
(* ###################################################################### *)
(** ** Main Theorem *)
(** We now have the tools we need to prove preservation: if a closed
term [t] has type [T], and takes an evaluation step to [t'], then [t']
is also a closed term with type [T]. In other words, the small-step
evaluation relation preserves types.
*)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
(** _Proof_: by induction on the derivation of [|- t \in T].
- We can immediately rule out [T_Var], [T_Abs], [T_True], and
[T_False] as the final rules in the derivation, since in each of
these cases [t] cannot take a step.
- If the last rule in the derivation was [T_App], then [t = t1
t2]. There are three cases to consider, one for each rule that
could have been used to show that [t1 t2] takes a step to [t'].
- If [t1 t2] takes a step by [ST_App1], with [t1] stepping to
[t1'], then by the IH [t1'] has the same type as [t1], and
hence [t1' t2] has the same type as [t1 t2].
- The [ST_App2] case is similar.
- If [t1 t2] takes a step by [ST_AppAbs], then [t1 =
\x:T11.t12] and [t1 t2] steps to [[x:=t2]t12]; the
desired result now follows from the fact that substitution
preserves types.
- If the last rule in the derivation was [T_If], then [t = if t1
then t2 else t3], and there are again three cases depending on
how [t] steps.
- If [t] steps to [t2] or [t3], the result is immediate, since
[t2] and [t3] have the same type as [t].
- Otherwise, [t] steps by [ST_If], and the desired conclusion
follows directly from the induction hypothesis.
*)
Proof with eauto.
remember (@empty ty) as Gamma.
intros t t' T HT. generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HE; subst Gamma; subst;
try solve [inversion HE; subst; auto].
Case "T_App".
inversion HE; subst...
(* Most of the cases are immediate by induction,
and [eauto] takes care of them *)
SCase "ST_AppAbs".
apply substitution_preserves_typing with T11...
inversion HT1...
Qed.
(** **** Exercise: 2 stars (subject_expansion_stlc) *)
(** An exercise in the [Types] chapter asked about the subject
expansion property for the simple language of arithmetic and
boolean expressions. Does this property hold for STLC? That is,
is it always the case that, if [t ==> t'] and [has_type t' T],
then [empty |- t \in T]? If so, prove it. If not, give a
counter-example not involving conditionals.
(* FILL IN HERE *)
[]
*)
(* ###################################################################### *)
(** * Type Soundness *)
(** **** Exercise: 2 stars, optional (type_soundness) *)
(** Put progress and preservation together and show that a well-typed
term can _never_ reach a stuck state. *)
Definition stuck (t:tm) : Prop :=
(normal_form step) t /\ ~ value t.
Corollary soundness : forall t t' T,
empty |- t \in T ->
t ==>* t' ->
~(stuck t').
Proof.
intros t t' T Hhas_type Hmulti. unfold stuck.
intros [Hnf Hnot_val]. unfold normal_form in Hnf.
induction Hmulti.
(* FILL IN HERE *) Admitted.
(* ###################################################################### *)
(** * Uniqueness of Types *)
(** **** Exercise: 3 stars (types_unique) *)
(** Another pleasant property of the STLC is that types are
unique: a given term (in a given context) has at most one
type. *)
(** Formalize this statement and prove it. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Additional Exercises *)
(** **** Exercise: 1 star (progress_preservation_statement) *)
(** Without peeking, write down the progress and preservation
theorems for the simply typed lambda-calculus. *)
(** [] *)
(** **** Exercise: 2 stars (stlc_variation1) *)
(** Suppose we add a new term [zap] with the following reduction rule:
--------- (ST_Zap)
t ==> zap
and the following typing rule:
---------------- (T_Zap)
Gamma |- zap : T
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars (stlc_variation2) *)
(** Suppose instead that we add a new term [foo] with the following reduction rules:
----------------- (ST_Foo1)
(\x:A. x) ==> foo
------------ (ST_Foo2)
foo ==> true
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars (stlc_variation3) *)
(** Suppose instead that we remove the rule [ST_App1] from the [step]
relation. Which of the following properties of the STLC remain
true in the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars, optional (stlc_variation4) *)
(** Suppose instead that we add the following new rule to the reduction relation:
---------------------------------- (ST_FunnyIfTrue)
(if true then t1 else t2) ==> true
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation5) *)
(** Suppose instead that we add the following new rule to the typing relation:
Gamma |- t1 \in Bool->Bool->Bool
Gamma |- t2 \in Bool
------------------------------ (T_FunnyApp)
Gamma |- t1 t2 \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation6) *)
(** Suppose instead that we add the following new rule to the typing relation:
Gamma |- t1 \in Bool
Gamma |- t2 \in Bool
--------------------- (T_FunnyApp')
Gamma |- t1 t2 \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation7) *)
(** Suppose we add the following new rule to the typing
relation of the STLC:
------------------- (T_FunnyAbs)
|- \x:Bool.t \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
End STLCProp.
(* ###################################################################### *)
(* ###################################################################### *)
(** ** Exercise: STLC with Arithmetic *)
(** To see how the STLC might function as the core of a real
programming language, let's extend it with a concrete base
type of numbers and some constants and primitive
operators. *)
Module STLCArith.
(** To types, we add a base type of natural numbers (and remove
booleans, for brevity) *)
Inductive ty : Type :=
| TArrow : ty -> ty -> ty
| TNat : ty.
(** To terms, we add natural number constants, along with
successor, predecessor, multiplication, and zero-testing... *)
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : 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 "tnat"
| Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0" ].
(** **** Exercise: 4 stars (stlc_arith) *)
(** Finish formalizing the definition and properties of the STLC extended
with arithmetic. Specifically:
- Copy the whole development of STLC that we went through above (from
the definition of values through the Progress theorem), and
paste it into the file at this point.
- Extend the definitions of the [subst] operation and the [step]
relation to include appropriate clauses for the arithmetic operators.
- Extend the proofs of all the properties (up to [soundness]) of
the original STLC to deal with the new syntactic forms. Make
sure Coq accepts the whole file. *)
(* FILL IN HERE *)
(** [] *)
End STLCArith.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * StlcProp: Properties of STLC *)
Require Export Stlc.
Module STLCProp.
Import STLC.
(** In this chapter, we develop the fundamental theory of the Simply
Typed Lambda Calculus -- in particular, the type safety
theorem. *)
(* ###################################################################### *)
(** * Canonical Forms *)
Lemma canonical_forms_bool : forall t,
empty |- t \in TBool ->
value t ->
(t = ttrue) \/ (t = tfalse).
Proof.
intros t HT HVal.
inversion HVal; intros; subst; try inversion HT; auto.
Qed.
Lemma canonical_forms_fun : forall t T1 T2,
empty |- t \in (TArrow T1 T2) ->
value t ->
exists x u, t = tabs x T1 u.
Proof.
intros t T1 T2 HT HVal.
inversion HVal; intros; subst; try inversion HT; subst; auto.
exists x0. exists t0. auto.
Qed.
(* ###################################################################### *)
(** * Progress *)
(** As before, the _progress_ theorem tells us that closed, well-typed
terms are not stuck: either a well-typed term is a value, or it
can take an evaluation step. The proof is a relatively
straightforward extension of the progress proof we saw in the
[Types] chapter. *)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
(** _Proof_: by induction on the derivation of [|- t \in T].
- The last rule of the derivation cannot be [T_Var], since a
variable is never well typed in an empty context.
- The [T_True], [T_False], and [T_Abs] cases are trivial, since in
each of these cases we know immediately that [t] is a value.
- If the last rule of the derivation was [T_App], then [t = t1
t2], and we know that [t1] and [t2] are also well typed in the
empty context; in particular, there exists a type [T2] such that
[|- t1 \in T2 -> T] and [|- t2 \in T2]. By the induction
hypothesis, either [t1] is a value or it can take an evaluation
step.
- If [t1] is a value, we now consider [t2], which by the other
induction hypothesis must also either be a value or take an
evaluation step.
- Suppose [t2] is a value. Since [t1] is a value with an
arrow type, it must be a lambda abstraction; hence [t1
t2] can take a step by [ST_AppAbs].
- Otherwise, [t2] can take a step, and hence so can [t1
t2] by [ST_App2].
- If [t1] can take a step, then so can [t1 t2] by [ST_App1].
- If the last rule of the derivation was [T_If], then [t = if t1
then t2 else t3], where [t1] has type [Bool]. By the IH, [t1]
either is a value or takes a step.
- If [t1] is a value, then since it has type [Bool] it must be
either [true] or [false]. If it is [true], then [t] steps
to [t2]; otherwise it steps to [t3].
- Otherwise, [t1] takes a step, and therefore so does [t] (by
[ST_If]).
*)
Proof with eauto.
intros t T Ht.
remember (@empty ty) as Gamma.
has_type_cases (induction Ht) Case; subst Gamma...
Case "T_Var".
(* contradictory: variables cannot be typed in an
empty context *)
inversion H.
Case "T_App".
(* [t] = [t1 t2]. Proceed by cases on whether [t1] is a
value or steps... *)
right. destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 is also a value".
assert (exists x0 t0, t1 = tabs x0 T11 t0).
eapply canonical_forms_fun; eauto.
destruct H1 as [x0 [t0 Heq]]. subst.
exists ([x0:=t2]t0)...
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".
destruct (canonical_forms_bool t1); subst; eauto.
SCase "t1 also steps".
inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...
Qed.
(** **** Exercise: 3 stars, optional (progress_from_term_ind) *)
(** Show that progress can also be proved by induction on terms
instead of induction on typing derivations. *)
Theorem progress' : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof.
intros t.
t_cases (induction t) Case; intros T Ht; auto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** * Preservation *)
(** The other half of the type soundness property is the preservation
of types during reduction. For this, we need to develop some
technical machinery for reasoning about variables and
substitution. Working from top to bottom (the high-level property
we are actually interested in to the lowest-level technical lemmas
that are needed by various cases of the more interesting proofs),
the story goes like this:
- The _preservation theorem_ is proved by induction on a typing
derivation, pretty much as we did in the [Types] chapter. The
one case that is significantly different is the one for the
[ST_AppAbs] rule, which is defined using the substitution
operation. To see that this step preserves typing, we need to
know that the substitution itself does. So we prove a...
- _substitution lemma_, stating that substituting a (closed)
term [s] for a variable [x] in a term [t] preserves the type
of [t]. The proof goes by induction on the form of [t] and
requires looking at all the different cases in the definition
of substitition. This time, the tricky cases are the ones for
variables and for function abstractions. In both cases, we
discover that we need to take a term [s] that has been shown
to be well-typed in some context [Gamma] and consider the same
term [s] in a slightly different context [Gamma']. For this
we prove a...
- _context invariance_ lemma, showing that typing is preserved
under "inessential changes" to the context [Gamma] -- in
particular, changes that do not affect any of the free
variables of the term. For this, we need a careful definition
of
- the _free variables_ of a term -- i.e., the variables occuring
in the term that are not in the scope of a function
abstraction that binds them.
*)
(* ###################################################################### *)
(** ** Free Occurrences *)
(** A variable [x] _appears free in_ a term _t_ if [t] contains some
occurrence of [x] that is not under an abstraction labeled [x]. For example:
- [y] appears free, but [x] does not, in [\x:T->U. x y]
- both [x] and [y] appear free in [(\x:T->U. x y) x]
- no variables appear free in [\x:T->U. \y:T. x y] *)
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).
Tactic Notation "afi_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "afi_var"
| Case_aux c "afi_app1" | Case_aux c "afi_app2"
| Case_aux c "afi_abs"
| Case_aux c "afi_if1" | Case_aux c "afi_if2"
| Case_aux c "afi_if3" ].
Hint Constructors appears_free_in.
(** A term in which no variables appear free is said to be _closed_. *)
Definition closed (t:tm) :=
forall x, ~ appears_free_in x t.
(* ###################################################################### *)
(** ** Substitution *)
(** We first need a technical lemma connecting free variables and
typing contexts. If a variable [x] appears free in a term [t],
and if we know [t] is well typed in context [Gamma], then it must
be the case that [Gamma] assigns a type to [x]. *)
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_: We show, by induction on the proof that [x] appears free
in [t], that, for all contexts [Gamma], if [t] is well typed
under [Gamma], then [Gamma] assigns some type to [x].
- If the last rule used was [afi_var], then [t = x], and from
the assumption that [t] is well typed under [Gamma] we have
immediately that [Gamma] assigns a type to [x].
- If the last rule used was [afi_app1], then [t = t1 t2] and [x]
appears free in [t1]. Since [t] is well typed under [Gamma],
we can see from the typing rules that [t1] must also be, and
the IH then tells us that [Gamma] assigns [x] a type.
- Almost all the other cases are similar: [x] appears free in a
subterm of [t], and since [t] is well typed under [Gamma], we
know the subterm of [t] in which [x] appears is well typed
under [Gamma] as well, and the IH gives us exactly the
conclusion we want.
- The only remaining case is [afi_abs]. In this case [t =
\y:T11.t12], and [x] appears free in [t12]; we also know that
[x] is different from [y]. The difference from the previous
cases is that whereas [t] is well typed under [Gamma], its
body [t12] is well typed under [(Gamma, y:T11)], so the IH
allows us to conclude that [x] is assigned some type by the
extended context [(Gamma, y:T11)]. To conclude that [Gamma]
assigns a type to [x], we appeal to lemma [extend_neq], noting
that [x] and [y] are different variables. *)
Proof.
intros x t T Gamma H H0. generalize dependent Gamma.
generalize dependent T.
afi_cases (induction H) Case;
intros; try solve [inversion H0; eauto].
Case "afi_abs".
inversion H1; subst.
apply IHappears_free_in in H7.
rewrite extend_neq in H7; assumption.
Qed.
(** Next, we'll need the fact that any term [t] which is well typed in
the empty context is closed -- that is, it has no free variables. *)
(** **** Exercise: 2 stars, optional (typable_empty__closed) *)
Corollary typable_empty__closed : forall t T,
empty |- t \in T ->
closed t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Sometimes, when we have a proof [Gamma |- t : T], we will need to
replace [Gamma] by a different context [Gamma']. When is it safe
to do this? Intuitively, it must at least be the case that
[Gamma'] assigns the same types as [Gamma] to all the variables
that appear free in [t]. In fact, this is the only condition that
is needed. *)
Lemma context_invariance : forall Gamma Gamma' t T,
Gamma |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in T.
(** _Proof_: By induction on the derivation of [Gamma |- t \in T].
- If the last rule in the derivation was [T_Var], then [t = x]
and [Gamma x = T]. By assumption, [Gamma' x = T] as well, and
hence [Gamma' |- t \in T] by [T_Var].
- If the last rule was [T_Abs], then [t = \y:T11. t12], with [T
= T11 -> T12] and [Gamma, y:T11 |- t12 \in T12]. The induction
hypothesis is that for any context [Gamma''], if [Gamma,
y:T11] and [Gamma''] assign the same types to all the free
variables in [t12], then [t12] has type [T12] under [Gamma''].
Let [Gamma'] be a context which agrees with [Gamma] on the
free variables in [t]; we must show [Gamma' |- \y:T11. t12 \in
T11 -> T12].
By [T_Abs], it suffices to show that [Gamma', y:T11 |- t12 \in
T12]. By the IH (setting [Gamma'' = Gamma', y:T11]), it
suffices to show that [Gamma, y:T11] and [Gamma', y:T11] agree
on all the variables that appear free in [t12].
Any variable occurring free in [t12] must either be [y], or
some other variable. [Gamma, y:T11] and [Gamma', y:T11]
clearly agree on [y]. Otherwise, we note that any variable
other than [y] which occurs free in [t12] also occurs free in
[t = \y:T11. t12], and by assumption [Gamma] and [Gamma']
agree on all such variables, and hence so do [Gamma, y:T11]
and [Gamma', y:T11].
- If the last rule was [T_App], then [t = t1 t2], with [Gamma |-
t1 \in T2 -> T] and [Gamma |- t2 \in T2]. One induction
hypothesis states that for all contexts [Gamma'], if [Gamma']
agrees with [Gamma] on the free variables in [t1], then [t1]
has type [T2 -> T] under [Gamma']; there is a similar IH for
[t2]. We must show that [t1 t2] also has type [T] under
[Gamma'], given the assumption that [Gamma'] agrees with
[Gamma] on all the free variables in [t1 t2]. By [T_App], it
suffices to show that [t1] and [t2] each have the same type
under [Gamma'] as under [Gamma]. However, we note that all
free variables in [t1] are also free in [t1 t2], and similarly
for free variables in [t2]; hence the desired result follows
by the two IHs.
*)
Proof with eauto.
intros.
generalize dependent Gamma'.
has_type_cases (induction H) Case; intros; auto.
Case "T_Var".
apply T_Var. rewrite <- H0...
Case "T_Abs".
apply T_Abs.
apply IHhas_type. intros x1 Hafi.
(* the only tricky step... the [Gamma'] we use to
instantiate is [extend Gamma x T11] *)
unfold extend. destruct (eq_id_dec x0 x1)...
Case "T_App".
apply T_App with T11...
Qed.
(** Now we come to the conceptual heart of the proof that reduction
preserves types -- namely, the observation that _substitution_
preserves types.
Formally, the so-called _Substitution Lemma_ says this: suppose we
have a term [t] with a free variable [x], and suppose we've been
able to assign a type [T] to [t] under the assumption that [x] has
some type [U]. Also, suppose that we have some other term [v] and
that we've shown that [v] has type [U]. Then, since [v] satisfies
the assumption we made about [x] when typing [t], we should be
able to substitute [v] for each of the occurrences of [x] in [t]
and obtain a new term that still has type [T]. *)
(** _Lemma_: If [Gamma,x:U |- t \in T] and [|- v \in U], then [Gamma |-
[x:=v]t \in T]. *)
Lemma substitution_preserves_typing : forall Gamma x U t v T,
extend Gamma x U |- t \in T ->
empty |- v \in U ->
Gamma |- [x:=v]t \in T.
(** One technical subtlety in the statement of the lemma is that we
assign [v] the type [U] in the _empty_ context -- in other words,
we assume [v] is closed. This assumption considerably simplifies
the [T_Abs] case of the proof (compared to assuming [Gamma |- v \in
U], which would be the other reasonable assumption at this point)
because the context invariance lemma then tells us that [v] has
type [U] in any context at all -- we don't have to worry about
free variables in [v] clashing with the variable being introduced
into the context by [T_Abs].
_Proof_: We prove, by induction on [t], that, for all [T] and
[Gamma], if [Gamma,x:U |- t \in T] and [|- v \in U], then [Gamma |-
[x:=v]t \in T].
- If [t] is a variable, there are two cases to consider, depending
on whether [t] is [x] or some other variable.
- If [t = x], then from the fact that [Gamma, x:U |- x \in T] we
conclude that [U = T]. We must show that [[x:=v]x = v] has
type [T] under [Gamma], given the assumption that [v] has
type [U = T] under the empty context. This follows from
context invariance: if a closed term has type [T] in the
empty context, it has that type in any context.
- If [t] is some variable [y] that is not equal to [x], then
we need only note that [y] has the same type under [Gamma,
x:U] as under [Gamma].
- If [t] is an abstraction [\y:T11. t12], then the IH tells us,
for all [Gamma'] and [T'], that if [Gamma',x:U |- t12 \in T']
and [|- v \in U], then [Gamma' |- [x:=v]t12 \in T'].
The substitution in the conclusion behaves differently,
depending on whether [x] and [y] are the same variable name.
First, suppose [x = y]. Then, by the definition of
substitution, [[x:=v]t = t], so we just need to show [Gamma |-
t \in T]. But we know [Gamma,x:U |- t : T], and since the
variable [y] does not appear free in [\y:T11. t12], the
context invariance lemma yields [Gamma |- t \in T].
Second, suppose [x <> y]. We know [Gamma,x:U,y:T11 |- t12 \in
T12] by inversion of the typing relation, and [Gamma,y:T11,x:U
|- t12 \in T12] follows from this by the context invariance
lemma, so the IH applies, giving us [Gamma,y:T11 |- [x:=v]t12 \in
T12]. By [T_Abs], [Gamma |- \y:T11. [x:=v]t12 \in T11->T12], and
by the definition of substitution (noting that [x <> y]),
[Gamma |- \y:T11. [x:=v]t12 \in T11->T12] as required.
- If [t] is an application [t1 t2], the result follows
straightforwardly from the definition of substitution and the
induction hypotheses.
- The remaining cases are similar to the application case.
Another technical note: This proof is a rare case where an
induction on terms, rather than typing derivations, yields a
simpler argument. The reason for this is that the assumption
[extend Gamma x U |- t \in T] is not completely generic, in
the sense that one of the "slots" in the typing relation -- namely
the context -- is not just a variable, and this means that Coq's
native induction tactic does not give us the induction hypothesis
that we want. It is possible to work around this, but the needed
generalization is a little tricky. The term [t], on the other
hand, _is_ completely generic. *)
Proof with eauto.
intros Gamma x U t v T Ht Ht'.
generalize dependent Gamma. generalize dependent T.
t_cases (induction t) Case; intros T Gamma H;
(* in each case, we'll want to get at the derivation of H *)
inversion H; subst; simpl...
Case "tvar".
rename i into y. destruct (eq_id_dec x y).
SCase "x=y".
subst.
rewrite extend_eq in H2.
inversion H2; subst. clear H2.
eapply context_invariance... intros x Hcontra.
destruct (free_in_context _ _ T empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
apply T_Var. rewrite extend_neq in H2...
Case "tabs".
rename i into y. 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...
Qed.
(** The substitution lemma can be viewed as a kind of "commutation"
property. Intuitively, it says that substitution and typing can
be done in either order: we can either assign types to the terms
[t] and [v] separately (under suitable contexts) and then combine
them using substitution, or we can substitute first and then
assign a type to [ [x:=v] t ] -- the result is the same either
way. *)
(* ###################################################################### *)
(** ** Main Theorem *)
(** We now have the tools we need to prove preservation: if a closed
term [t] has type [T], and takes an evaluation step to [t'], then [t']
is also a closed term with type [T]. In other words, the small-step
evaluation relation preserves types.
*)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
(** _Proof_: by induction on the derivation of [|- t \in T].
- We can immediately rule out [T_Var], [T_Abs], [T_True], and
[T_False] as the final rules in the derivation, since in each of
these cases [t] cannot take a step.
- If the last rule in the derivation was [T_App], then [t = t1
t2]. There are three cases to consider, one for each rule that
could have been used to show that [t1 t2] takes a step to [t'].
- If [t1 t2] takes a step by [ST_App1], with [t1] stepping to
[t1'], then by the IH [t1'] has the same type as [t1], and
hence [t1' t2] has the same type as [t1 t2].
- The [ST_App2] case is similar.
- If [t1 t2] takes a step by [ST_AppAbs], then [t1 =
\x:T11.t12] and [t1 t2] steps to [[x:=t2]t12]; the
desired result now follows from the fact that substitution
preserves types.
- If the last rule in the derivation was [T_If], then [t = if t1
then t2 else t3], and there are again three cases depending on
how [t] steps.
- If [t] steps to [t2] or [t3], the result is immediate, since
[t2] and [t3] have the same type as [t].
- Otherwise, [t] steps by [ST_If], and the desired conclusion
follows directly from the induction hypothesis.
*)
Proof with eauto.
remember (@empty ty) as Gamma.
intros t t' T HT. generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HE; subst Gamma; subst;
try solve [inversion HE; subst; auto].
Case "T_App".
inversion HE; subst...
(* Most of the cases are immediate by induction,
and [eauto] takes care of them *)
SCase "ST_AppAbs".
apply substitution_preserves_typing with T11...
inversion HT1...
Qed.
(** **** Exercise: 2 stars (subject_expansion_stlc) *)
(** An exercise in the [Types] chapter asked about the subject
expansion property for the simple language of arithmetic and
boolean expressions. Does this property hold for STLC? That is,
is it always the case that, if [t ==> t'] and [has_type t' T],
then [empty |- t \in T]? If so, prove it. If not, give a
counter-example not involving conditionals.
(* FILL IN HERE *)
[]
*)
(* ###################################################################### *)
(** * Type Soundness *)
(** **** Exercise: 2 stars, optional (type_soundness) *)
(** Put progress and preservation together and show that a well-typed
term can _never_ reach a stuck state. *)
Definition stuck (t:tm) : Prop :=
(normal_form step) t /\ ~ value t.
Corollary soundness : forall t t' T,
empty |- t \in T ->
t ==>* t' ->
~(stuck t').
Proof.
intros t t' T Hhas_type Hmulti. unfold stuck.
intros [Hnf Hnot_val]. unfold normal_form in Hnf.
induction Hmulti.
(* FILL IN HERE *) Admitted.
(* ###################################################################### *)
(** * Uniqueness of Types *)
(** **** Exercise: 3 stars (types_unique) *)
(** Another pleasant property of the STLC is that types are
unique: a given term (in a given context) has at most one
type. *)
(** Formalize this statement and prove it. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Additional Exercises *)
(** **** Exercise: 1 star (progress_preservation_statement) *)
(** Without peeking, write down the progress and preservation
theorems for the simply typed lambda-calculus. *)
(** [] *)
(** **** Exercise: 2 stars (stlc_variation1) *)
(** Suppose we add a new term [zap] with the following reduction rule:
--------- (ST_Zap)
t ==> zap
and the following typing rule:
---------------- (T_Zap)
Gamma |- zap : T
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars (stlc_variation2) *)
(** Suppose instead that we add a new term [foo] with the following reduction rules:
----------------- (ST_Foo1)
(\x:A. x) ==> foo
------------ (ST_Foo2)
foo ==> true
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars (stlc_variation3) *)
(** Suppose instead that we remove the rule [ST_App1] from the [step]
relation. Which of the following properties of the STLC remain
true in the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars, optional (stlc_variation4) *)
(** Suppose instead that we add the following new rule to the reduction relation:
---------------------------------- (ST_FunnyIfTrue)
(if true then t1 else t2) ==> true
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation5) *)
(** Suppose instead that we add the following new rule to the typing relation:
Gamma |- t1 \in Bool->Bool->Bool
Gamma |- t2 \in Bool
------------------------------ (T_FunnyApp)
Gamma |- t1 t2 \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation6) *)
(** Suppose instead that we add the following new rule to the typing relation:
Gamma |- t1 \in Bool
Gamma |- t2 \in Bool
--------------------- (T_FunnyApp')
Gamma |- t1 t2 \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation7) *)
(** Suppose we add the following new rule to the typing
relation of the STLC:
------------------- (T_FunnyAbs)
|- \x:Bool.t \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
End STLCProp.
(* ###################################################################### *)
(* ###################################################################### *)
(** ** Exercise: STLC with Arithmetic *)
(** To see how the STLC might function as the core of a real
programming language, let's extend it with a concrete base
type of numbers and some constants and primitive
operators. *)
Module STLCArith.
(** To types, we add a base type of natural numbers (and remove
booleans, for brevity) *)
Inductive ty : Type :=
| TArrow : ty -> ty -> ty
| TNat : ty.
(** To terms, we add natural number constants, along with
successor, predecessor, multiplication, and zero-testing... *)
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : 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 "tnat"
| Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0" ].
(** **** Exercise: 4 stars (stlc_arith) *)
(** Finish formalizing the definition and properties of the STLC extended
with arithmetic. Specifically:
- Copy the whole development of STLC that we went through above (from
the definition of values through the Progress theorem), and
paste it into the file at this point.
- Extend the definitions of the [subst] operation and the [step]
relation to include appropriate clauses for the arithmetic operators.
- Extend the proofs of all the properties (up to [soundness]) of
the original STLC to deal with the new syntactic forms. Make
sure Coq accepts the whole file. *)
(* FILL IN HERE *)
(** [] *)
End STLCArith.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
module ghrd_10m50da_top (
//Clock and Reset
input wire clk_50,
//input wire clk_ddr3_100_p,
input wire fpga_reset_n,
//QSPI
output wire qspi_clk,
inout wire[3:0] qspi_io,
output wire qspi_csn,
//ddr3
//output wire [13:0] mem_a,
//output wire [2:0] mem_ba,
//inout wire [0:0] mem_ck,
//inout wire [0:0] mem_ck_n,
//output wire [0:0] mem_cke,
//output wire [0:0] mem_cs_n,
//output wire [0:0] mem_dm,
//output wire [0:0] mem_ras_n,
//output wire [0:0] mem_cas_n,
//output wire [0:0] mem_we_n,
//output wire mem_reset_n,
///inout wire [7:0] mem_dq,
//inout wire [0:0] mem_dqs,
//inout wire [0:0] mem_dqs_n,
//output wire [0:0] mem_odt,
//i2c
inout wire i2c_sda,
inout wire i2c_scl,
//spi
input wire spi_miso,
output wire spi_mosi,
output wire spi_sclk,
output wire spi_ssn,
//16550 UART
input wire uart_rx,
output wire uart_tx,
output wire [4:0] user_led
);
//Heart-beat counter
reg [25:0] heart_beat_cnt;
//DDR3 interface assignments
//wire local_init_done;
//wire local_cal_success;
//wire local_cal_fail;
//i2c interface
wire i2c_serial_sda_in ;
wire i2c_serial_scl_in ;
wire i2c_serial_sda_oe ;
wire i2c_serial_scl_oe ;
assign i2c_serial_scl_in = i2c_scl;
assign i2c_scl = i2c_serial_scl_oe ? 1'b0 : 1'bz;
assign i2c_serial_sda_in = i2c_sda;
assign i2c_sda = i2c_serial_sda_oe ? 1'b0 : 1'bz;
//assign system_resetn = fpga_reset_n & local_init_done;
// SoC sub-system module
ghrd_10m50da ghrd_10m50da_inst (
.clk_clk (clk_50),
//.ref_clock_bridge_in_clk_clk (clk_ddr3_100_p),
.reset_reset_n (fpga_reset_n),
//.mem_resetn_in_reset_reset_n (fpga_reset_n ), // mem_resetn_in_reset.reset_n
.ext_flash_qspi_pins_data (qspi_io),
.ext_flash_qspi_pins_dclk (qspi_clk),
.ext_flash_qspi_pins_ncs (qspi_csn),
//.memory_mem_a (mem_a[12:0] ), // memory.mem_a
//.memory_mem_ba (mem_ba ), // .mem_ba
//.memory_mem_ck (mem_ck ), // .mem_ck
//.memory_mem_ck_n (mem_ck_n ), // .mem_ck_n
//.memory_mem_cke (mem_cke ), // .mem_cke
//.memory_mem_cs_n (mem_cs_n ), // .mem_cs_n
//.memory_mem_dm (mem_dm ), // .mem_dm
//.memory_mem_ras_n (mem_ras_n ), // .mem_ras_n
//.memory_mem_cas_n (mem_cas_n ), // .mem_cas_n
//.memory_mem_we_n (mem_we_n ), // .mem_we_n
//.memory_mem_reset_n (mem_reset_n ), // .mem_reset_n
//.memory_mem_dq (mem_dq ), // .mem_dq
//.memory_mem_dqs (mem_dqs ), // .mem_dqs
//.memory_mem_dqs_n (mem_dqs_n ), // .mem_dqs_n
//.memory_mem_odt (mem_odt ), // .mem_odt
//.mem_if_ddr3_emif_0_status_local_init_done (local_init_done ), // mem_if_ddr3_emif_0_status.local_init_done
//.mem_if_ddr3_emif_0_status_local_cal_success (local_cal_success ), // .local_cal_success
//.mem_if_ddr3_emif_0_status_local_cal_fail (local_cal_fail ), // .local_cal_fail
//i2c
.i2c_0_i2c_serial_sda_in (i2c_serial_sda_in),
.i2c_0_i2c_serial_scl_in (i2c_serial_scl_in),
.i2c_0_i2c_serial_sda_oe (i2c_serial_sda_oe),
.i2c_0_i2c_serial_scl_oe (i2c_serial_scl_oe),
//spi
.spi_0_external_MISO (spi_miso), // spi_0_external.MISO
.spi_0_external_MOSI (spi_mosi), // .MOSI
.spi_0_external_SCLK (spi_sclk), // .SCLK
.spi_0_external_SS_n (spi_ssn), // .SS_n
//pio
.led_external_connection_export (user_led[3:0]),
//16550 UART
.a_16550_uart_0_rs_232_serial_sin (uart_rx), // a_16550_uart_0_rs_232_serial.sin
.a_16550_uart_0_rs_232_serial_sout (uart_tx), // .sout
.a_16550_uart_0_rs_232_serial_sout_oe () // .sout_oe
);
//DDR3 Address Bit #13 is not available for DDR3 SDRAM A (64Mx16)
//assign mem_a[13] = 1'b0;
//Heart beat by 50MHz clock
always @(posedge clk_50 or negedge fpga_reset_n)
if (!fpga_reset_n)
heart_beat_cnt <= 26'h0; //0x3FFFFFF
else
heart_beat_cnt <= heart_beat_cnt + 1'b1;
assign user_led[4] = heart_beat_cnt[25];
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
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 03:04:50 02/19/2009
// Design Name:
// Module Name: RCB_FRL_LED_Clock
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module RCB_FRL_LED_Clock(Test_Clock_in, LED_Clock_out, RST);
input Test_Clock_in;
output LED_Clock_out;
input RST;
reg[9:0] count1;
reg[9:0] count2;
reg[9:0] count3;
reg LED_Clock_out_reg;
assign LED_Clock_out = LED_Clock_out_reg;
always @(posedge Test_Clock_in or posedge RST) begin
if (RST) begin
count1 <= 1'b0;
count2 <= 1'b0;
count3 <= 1'b0;
LED_Clock_out_reg <= 1'b0;
end
else begin
if (count3 < 448) begin
if (count2 < 1000) begin
if (count1 < 1000)
count1 <= count1 + 1'b1;
else
begin
count1 <= 1'b0;
count2 <= count2 + 1'b1;
end
end
else
begin
count2 <= 1'b0;
count3 <= count3 + 1'b1;
end
end
else
begin
count3 <= 1'b0;
LED_Clock_out_reg <= ~LED_Clock_out_reg;
end
end
end
endmodule
module RCB_FRL_LED_Clock_DIV(Test_Clock_in, LED_Clock_out, RST);
input Test_Clock_in;
output LED_Clock_out;
input RST;
reg[9:0] count1;
reg[9:0] count2;
reg[9:0] count3;
reg LED_Clock_out_reg;
assign LED_Clock_out = LED_Clock_out_reg;
always @(posedge Test_Clock_in or posedge RST) begin
if (RST) begin
count1 <= 1'b0;
count2 <= 1'b0;
count3 <= 1'b0;
LED_Clock_out_reg <= 1'b0;
end
else begin
if (count3 < 56) begin
if (count2 < 1000) begin
if (count1 < 1000)
count1 <= count1 + 1'b1;
else
begin
count1 <= 1'b0;
count2 <= count2 + 1'b1;
end
end
else
begin
count2 <= 1'b0;
count3 <= count3 + 1'b1;
end
end
else
begin
count3 <= 1'b0;
LED_Clock_out_reg <= ~LED_Clock_out_reg;
end
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.
---------------------------------------------------------------------------*/
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 03:04:50 02/19/2009
// Design Name:
// Module Name: RCB_FRL_LED_Clock
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module RCB_FRL_LED_Clock(Test_Clock_in, LED_Clock_out, RST);
input Test_Clock_in;
output LED_Clock_out;
input RST;
reg[9:0] count1;
reg[9:0] count2;
reg[9:0] count3;
reg LED_Clock_out_reg;
assign LED_Clock_out = LED_Clock_out_reg;
always @(posedge Test_Clock_in or posedge RST) begin
if (RST) begin
count1 <= 1'b0;
count2 <= 1'b0;
count3 <= 1'b0;
LED_Clock_out_reg <= 1'b0;
end
else begin
if (count3 < 448) begin
if (count2 < 1000) begin
if (count1 < 1000)
count1 <= count1 + 1'b1;
else
begin
count1 <= 1'b0;
count2 <= count2 + 1'b1;
end
end
else
begin
count2 <= 1'b0;
count3 <= count3 + 1'b1;
end
end
else
begin
count3 <= 1'b0;
LED_Clock_out_reg <= ~LED_Clock_out_reg;
end
end
end
endmodule
module RCB_FRL_LED_Clock_DIV(Test_Clock_in, LED_Clock_out, RST);
input Test_Clock_in;
output LED_Clock_out;
input RST;
reg[9:0] count1;
reg[9:0] count2;
reg[9:0] count3;
reg LED_Clock_out_reg;
assign LED_Clock_out = LED_Clock_out_reg;
always @(posedge Test_Clock_in or posedge RST) begin
if (RST) begin
count1 <= 1'b0;
count2 <= 1'b0;
count3 <= 1'b0;
LED_Clock_out_reg <= 1'b0;
end
else begin
if (count3 < 56) begin
if (count2 < 1000) begin
if (count1 < 1000)
count1 <= count1 + 1'b1;
else
begin
count1 <= 1'b0;
count2 <= count2 + 1'b1;
end
end
else
begin
count2 <= 1'b0;
count3 <= count3 + 1'b1;
end
end
else
begin
count3 <= 1'b0;
LED_Clock_out_reg <= ~LED_Clock_out_reg;
end
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: A small shadow-RAM to qualify the data entries in the dual-port
// compram
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// Modification by zjs, 2009-6-18, pending
// (1) move posted packet generator and non-posted packet generator out --- done
// (2) add dma write data fifo --------------- done
// (3) modify tx sm
// scheduling -------------------------- done
// disable write dma done -------------- done
// register/memory read ---------------- done
//
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module pending_comp_ram_32x1(
input clk,
input d_in,
input [4:0] addr,
input we,
output reg [31:0] d_out = 32'h00000000
);
wire [31:0] addr_decode;
//binary-to-onehot address decoder for ram
assign addr_decode[31:0] = 32'h00000001 << addr[4:0];
//generate a 32-entry ram with
//addressable inputs entries
//and outputs which are always present;
//essentially this is a 32x1 register file
genvar i;
generate
for(i=0;i<32;i=i+1)begin: bitram
always@(posedge clk)begin
if(addr_decode[i] && we)begin
d_out[i] <= d_in;
end
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2004 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
by_width #(1) w1 (.clk(clk));
by_width #(31) w31 (.clk(clk));
by_width #(32) w32 (.clk(clk));
by_width #(33) w33 (.clk(clk));
by_width #(63) w63 (.clk(clk));
by_width #(64) w64 (.clk(clk));
by_width #(65) w65 (.clk(clk));
by_width #(95) w95 (.clk(clk));
by_width #(96) w96 (.clk(clk));
by_width #(97) w97 (.clk(clk));
reg signed [15:0] a;
reg signed [4:0] b;
reg signed [15:0] sr,srs,sl,sls;
reg [15:0] b_s;
reg [15:0] b_us;
task check_s(input signed [7:0] i, input [7:0] expval);
//$display("check_s %x\n", i);
if (i !== expval) $stop;
endtask
task check_us(input signed [7:0] i, input [7:0] expval);
//$display("check_us %x\n", i);
if (i !== expval) $stop;
endtask
always @* begin
sr = a>>b;
srs = copy_signed(a)>>>b;
sl = a<<b;
sls = a<<<b;
// verilator lint_off WIDTH
b_s = b>>>4; // Signed
b_us = b[4:0]>>>4; // Unsigned, due to extract
check_s ( 3'b111, 8'h07);
check_s (3'sb111, 8'hff);
check_us( 3'b111, 8'h07);
check_us(3'sb111, 8'hff); // Note we sign extend ignoring function's input requirements
// verilator lint_on WIDTH
end
reg signed [32:0] bug349;
initial
begin
end
integer i;
initial begin
if ((-1 >>> 3) != -1) $stop; // Decimals are signed
// verilator lint_off WIDTH
if ((3'b111 >>> 3) != 0) $stop; // Based numbers are unsigned
if ((3'sb111 >>> 3) != -1) $stop; // Signed based numbers
// verilator lint_on WIDTH
if ( (3'sb000 > 3'sb000)) $stop;
if (!(3'sb000 > 3'sb111)) $stop;
if ( (3'sb111 > 3'sb000)) $stop;
if ( (3'sb000 < 3'sb000)) $stop;
if ( (3'sb000 < 3'sb111)) $stop;
if (!(3'sb111 < 3'sb000)) $stop;
if (!(3'sb000 >= 3'sb000)) $stop;
if (!(3'sb000 >= 3'sb111)) $stop;
if ( (3'sb111 >= 3'sb000)) $stop;
if (!(3'sb000 <= 3'sb000)) $stop;
if ( (3'sb000 <= 3'sb111)) $stop;
if (!(3'sb111 <= 3'sb000)) $stop;
// When we multiply overflow, the sign bit stays correct.
if ( (4'sd2*4'sd8) != 4'd0) $stop;
// From the spec:
// verilator lint_off WIDTH
i = -12 /3; if (i !== 32'hfffffffc) $stop;
i = -'d12 /3; if (i !== 32'h55555551) $stop;
i = -'sd12 /3; if (i !== 32'hfffffffc) $stop;
i = -4'sd12 /3; if (i !== 32'h00000001) $stop;
// verilator lint_on WIDTH
// verilator lint_off WIDTH
bug349 = 4'sb1111 - 1'b1;
if (bug349 != 32'he) $stop;
end
function signed [15:0] copy_signed;
input [15:0] ai;
copy_signed = ai;
endfunction
integer cyc; initial cyc=0;
wire [31:0] ucyc = cyc;
always @ (posedge clk) begin
cyc <= cyc + 1;
`ifdef TEST_VERBOSE
$write("%x %x %x %x %x %x %x\n", cyc, sr,srs,sl,sls, b_s,b_us);
`endif
case (cyc)
0: begin
a <= 16'sh8b1b; b <= 5'sh1f; // -1
end
1: begin
// Check spaces in constants
a <= 16 'sh 8b1b; b <= 5'sh01; // -1
end
2: begin
a <= 16'sh8b1b; b <= 5'sh1e; // shift AMOUNT is really unsigned
if (ucyc / 1 != 32'd2) $stop;
if (ucyc / 2 != 32'd1) $stop;
if (ucyc * 1 != 32'd2) $stop;
if (ucyc * 2 != 32'd4) $stop;
if (ucyc * 3 != 32'd6) $stop;
if (cyc * 32'sd1 != 32'sd2) $stop;
if (cyc * 32'sd2 != 32'sd4) $stop;
if (cyc * 32'sd3 != 32'sd6) $stop;
end
3: begin
a <= 16'sh0048; b <= 5'sh1f;
if (ucyc * 1 != 32'd3) $stop;
if (ucyc * 2 != 32'd6) $stop;
if (ucyc * 3 != 32'd9) $stop;
if (ucyc * 4 != 32'd12) $stop;
if (cyc * 32'sd1 != 32'sd3) $stop;
if (cyc * 32'sd2 != 32'sd6) $stop;
if (cyc * 32'sd3 != 32'sd9) $stop;
end
4: begin
a <= 16'sh4154; b <= 5'sh02;
end
5: begin
a <= 16'shc3e8; b <= 5'sh12;
end
6: begin
a <= 16'sh488b; b <= 5'sh02;
end
9: begin
$write("*-* All Finished *-*\n");
$finish;
end
default: ;
endcase
case (cyc)
0: ;
1: if ({sr,srs,sl,sls,b_s,b_us}!==96'sh0000_ffff_0000_0000_ffff_0001) $stop;
2: if ({sr,srs,sl,sls,b_s,b_us}!==96'sh458d_c58d_1636_1636_0000_0000) $stop;
3: if ({sr,srs,sl,sls,b_s,b_us}!==96'sh0000_ffff_0000_0000_ffff_0001) $stop;
4: if ({sr,srs,sl,sls,b_s,b_us}!==96'sh0000_0000_0000_0000_ffff_0001) $stop;
5: if ({sr,srs,sl,sls,b_s,b_us}!==96'sh1055_1055_0550_0550_0000_0000) $stop;
6: if ({sr,srs,sl,sls,b_s,b_us}!==96'sh0000_ffff_0000_0000_ffff_0001) $stop;
7: if ({sr,srs,sl,sls,b_s,b_us}!==96'sh1222_1222_222c_222c_0000_0000) $stop;
8: ;
9: ;
endcase
end
endmodule
module by_width (
input clk
);
parameter WIDTH=1;
reg signed i1;
reg signed [62:0] i63;
reg signed [64:0] i65;
// verilator lint_off WIDTH
wire signed [WIDTH-1:0] i1extp /*verilator public*/ = i1;
wire signed [WIDTH-1:0] i1ext = i1;
wire signed [WIDTH-1:0] i63ext = i63;
wire signed [WIDTH-1:0] i65ext = i65;
// verilator lint_on WIDTH
integer cyc; initial cyc=0;
always @ (posedge clk) begin
cyc <= cyc + 1;
i1 <= cyc[0];
i63 <= {63{cyc[0]}};
i65 <= {65{cyc[0]}};
case (cyc)
1: begin
if (i1extp != {WIDTH{1'b0}}) $stop;
if (i1ext != {WIDTH{1'b0}}) $stop;
if (i63ext != {WIDTH{1'b0}}) $stop;
if (i65ext != {WIDTH{1'b0}}) $stop;
end
2: begin
if (i1extp != {WIDTH{1'b1}}) $stop;
if (i1ext != {WIDTH{1'b1}}) $stop;
if (i63ext != {WIDTH{1'b1}}) $stop;
if (i65ext != {WIDTH{1'b1}}) $stop;
end
default: ;
endcase
end
endmodule
|
//------------------------------------------------------------------------
//--
//-- Filename : xlconcat.v
//--
//-- Date : 06/05/12
//-
//- Description : Verilog description of a concat block. This
//- block does not use a core.
//-
//-----------------------------------------------------------------------
`timescale 1ps/1ps
module xlconcat (In0, In1, In2, In3, In4, In5, In6, In7, In8, In9, In10, In11, In12, In13, In14, In15, In16, In17, In18, In19, In20, In21, In22, In23, In24, In25, In26, In27, In28, In29, In30, In31, dout);
parameter IN0_WIDTH = 1;
input [IN0_WIDTH -1:0] In0;
parameter IN1_WIDTH = 1;
input [IN1_WIDTH -1:0] In1;
parameter IN2_WIDTH = 1;
input [IN2_WIDTH -1:0] In2;
parameter IN3_WIDTH = 1;
input [IN3_WIDTH -1:0] In3;
parameter IN4_WIDTH = 1;
input [IN4_WIDTH -1:0] In4;
parameter IN5_WIDTH = 1;
input [IN5_WIDTH -1:0] In5;
parameter IN6_WIDTH = 1;
input [IN6_WIDTH -1:0] In6;
parameter IN7_WIDTH = 1;
input [IN7_WIDTH -1:0] In7;
parameter IN8_WIDTH = 1;
input [IN8_WIDTH -1:0] In8;
parameter IN9_WIDTH = 1;
input [IN9_WIDTH -1:0] In9;
parameter IN10_WIDTH = 1;
input [IN10_WIDTH -1:0] In10;
parameter IN11_WIDTH = 1;
input [IN11_WIDTH -1:0] In11;
parameter IN12_WIDTH = 1;
input [IN12_WIDTH -1:0] In12;
parameter IN13_WIDTH = 1;
input [IN13_WIDTH -1:0] In13;
parameter IN14_WIDTH = 1;
input [IN14_WIDTH -1:0] In14;
parameter IN15_WIDTH = 1;
input [IN15_WIDTH -1:0] In15;
parameter IN16_WIDTH = 1;
input [IN16_WIDTH -1:0] In16;
parameter IN17_WIDTH = 1;
input [IN17_WIDTH -1:0] In17;
parameter IN18_WIDTH = 1;
input [IN18_WIDTH -1:0] In18;
parameter IN19_WIDTH = 1;
input [IN19_WIDTH -1:0] In19;
parameter IN20_WIDTH = 1;
input [IN20_WIDTH -1:0] In20;
parameter IN21_WIDTH = 1;
input [IN21_WIDTH -1:0] In21;
parameter IN22_WIDTH = 1;
input [IN22_WIDTH -1:0] In22;
parameter IN23_WIDTH = 1;
input [IN23_WIDTH -1:0] In23;
parameter IN24_WIDTH = 1;
input [IN24_WIDTH -1:0] In24;
parameter IN25_WIDTH = 1;
input [IN25_WIDTH -1:0] In25;
parameter IN26_WIDTH = 1;
input [IN26_WIDTH -1:0] In26;
parameter IN27_WIDTH = 1;
input [IN27_WIDTH -1:0] In27;
parameter IN28_WIDTH = 1;
input [IN28_WIDTH -1:0] In28;
parameter IN29_WIDTH = 1;
input [IN29_WIDTH -1:0] In29;
parameter IN30_WIDTH = 1;
input [IN30_WIDTH -1:0] In30;
parameter IN31_WIDTH = 1;
input [IN31_WIDTH -1:0] In31;
parameter dout_width = 2;
output [dout_width-1:0] dout;
parameter NUM_PORTS =2;
generate if (NUM_PORTS == 1)
begin : C_NUM_1
assign dout = In0;
end
endgenerate
generate if (NUM_PORTS == 2)
begin : C_NUM_2
assign dout = {In1,In0};
end
endgenerate
generate if (NUM_PORTS == 3)
begin:C_NUM_3
assign dout = {In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 4)
begin:C_NUM_4
assign dout = {In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 5)
begin:C_NUM_5
assign dout = {In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 6)
begin:C_NUM_6
assign dout = {In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 7)
begin:C_NUM_7
assign dout = {In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 8)
begin:C_NUM_8
assign dout = {In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 9)
begin:C_NUM_9
assign dout = {In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 10)
begin:C_NUM_10
assign dout = {In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 11)
begin:C_NUM_11
assign dout = {In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 12)
begin:C_NUM_12
assign dout = {In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 13)
begin:C_NUM_13
assign dout = {In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 14)
begin:C_NUM_14
assign dout = {In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 15)
begin:C_NUM_15
assign dout = {In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 16)
begin:C_NUM_16
assign dout = {In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 17)
begin:C_NUM_17
assign dout = {In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 18)
begin:C_NUM_18
assign dout = {In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 19)
begin:C_NUM_19
assign dout = {In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 20)
begin:C_NUM_20
assign dout = {In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 21)
begin:C_NUM_21
assign dout = {In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 22)
begin:C_NUM_22
assign dout = {In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 23)
begin:C_NUM_23
assign dout = {In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 24)
begin:C_NUM_24
assign dout = {In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 25)
begin:C_NUM_25
assign dout = {In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 26)
begin:C_NUM_26
assign dout = {In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 27)
begin:C_NUM_27
assign dout = {In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 28)
begin:C_NUM_28
assign dout = {In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 29)
begin:C_NUM_29
assign dout = {In28, In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 30)
begin:C_NUM_30
assign dout = {In29, In28, In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 31)
begin:C_NUM_31
assign dout = {In30, In29, In28, In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 32)
begin:C_NUM_32
assign dout = {In31, In30, In29, In28, In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
endmodule
|
//------------------------------------------------------------------------
//--
//-- Filename : xlconcat.v
//--
//-- Date : 06/05/12
//-
//- Description : Verilog description of a concat block. This
//- block does not use a core.
//-
//-----------------------------------------------------------------------
`timescale 1ps/1ps
module xlconcat (In0, In1, In2, In3, In4, In5, In6, In7, In8, In9, In10, In11, In12, In13, In14, In15, In16, In17, In18, In19, In20, In21, In22, In23, In24, In25, In26, In27, In28, In29, In30, In31, dout);
parameter IN0_WIDTH = 1;
input [IN0_WIDTH -1:0] In0;
parameter IN1_WIDTH = 1;
input [IN1_WIDTH -1:0] In1;
parameter IN2_WIDTH = 1;
input [IN2_WIDTH -1:0] In2;
parameter IN3_WIDTH = 1;
input [IN3_WIDTH -1:0] In3;
parameter IN4_WIDTH = 1;
input [IN4_WIDTH -1:0] In4;
parameter IN5_WIDTH = 1;
input [IN5_WIDTH -1:0] In5;
parameter IN6_WIDTH = 1;
input [IN6_WIDTH -1:0] In6;
parameter IN7_WIDTH = 1;
input [IN7_WIDTH -1:0] In7;
parameter IN8_WIDTH = 1;
input [IN8_WIDTH -1:0] In8;
parameter IN9_WIDTH = 1;
input [IN9_WIDTH -1:0] In9;
parameter IN10_WIDTH = 1;
input [IN10_WIDTH -1:0] In10;
parameter IN11_WIDTH = 1;
input [IN11_WIDTH -1:0] In11;
parameter IN12_WIDTH = 1;
input [IN12_WIDTH -1:0] In12;
parameter IN13_WIDTH = 1;
input [IN13_WIDTH -1:0] In13;
parameter IN14_WIDTH = 1;
input [IN14_WIDTH -1:0] In14;
parameter IN15_WIDTH = 1;
input [IN15_WIDTH -1:0] In15;
parameter IN16_WIDTH = 1;
input [IN16_WIDTH -1:0] In16;
parameter IN17_WIDTH = 1;
input [IN17_WIDTH -1:0] In17;
parameter IN18_WIDTH = 1;
input [IN18_WIDTH -1:0] In18;
parameter IN19_WIDTH = 1;
input [IN19_WIDTH -1:0] In19;
parameter IN20_WIDTH = 1;
input [IN20_WIDTH -1:0] In20;
parameter IN21_WIDTH = 1;
input [IN21_WIDTH -1:0] In21;
parameter IN22_WIDTH = 1;
input [IN22_WIDTH -1:0] In22;
parameter IN23_WIDTH = 1;
input [IN23_WIDTH -1:0] In23;
parameter IN24_WIDTH = 1;
input [IN24_WIDTH -1:0] In24;
parameter IN25_WIDTH = 1;
input [IN25_WIDTH -1:0] In25;
parameter IN26_WIDTH = 1;
input [IN26_WIDTH -1:0] In26;
parameter IN27_WIDTH = 1;
input [IN27_WIDTH -1:0] In27;
parameter IN28_WIDTH = 1;
input [IN28_WIDTH -1:0] In28;
parameter IN29_WIDTH = 1;
input [IN29_WIDTH -1:0] In29;
parameter IN30_WIDTH = 1;
input [IN30_WIDTH -1:0] In30;
parameter IN31_WIDTH = 1;
input [IN31_WIDTH -1:0] In31;
parameter dout_width = 2;
output [dout_width-1:0] dout;
parameter NUM_PORTS =2;
generate if (NUM_PORTS == 1)
begin : C_NUM_1
assign dout = In0;
end
endgenerate
generate if (NUM_PORTS == 2)
begin : C_NUM_2
assign dout = {In1,In0};
end
endgenerate
generate if (NUM_PORTS == 3)
begin:C_NUM_3
assign dout = {In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 4)
begin:C_NUM_4
assign dout = {In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 5)
begin:C_NUM_5
assign dout = {In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 6)
begin:C_NUM_6
assign dout = {In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 7)
begin:C_NUM_7
assign dout = {In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 8)
begin:C_NUM_8
assign dout = {In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 9)
begin:C_NUM_9
assign dout = {In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 10)
begin:C_NUM_10
assign dout = {In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 11)
begin:C_NUM_11
assign dout = {In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 12)
begin:C_NUM_12
assign dout = {In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 13)
begin:C_NUM_13
assign dout = {In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 14)
begin:C_NUM_14
assign dout = {In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 15)
begin:C_NUM_15
assign dout = {In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 16)
begin:C_NUM_16
assign dout = {In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 17)
begin:C_NUM_17
assign dout = {In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 18)
begin:C_NUM_18
assign dout = {In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 19)
begin:C_NUM_19
assign dout = {In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 20)
begin:C_NUM_20
assign dout = {In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 21)
begin:C_NUM_21
assign dout = {In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 22)
begin:C_NUM_22
assign dout = {In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 23)
begin:C_NUM_23
assign dout = {In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 24)
begin:C_NUM_24
assign dout = {In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 25)
begin:C_NUM_25
assign dout = {In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 26)
begin:C_NUM_26
assign dout = {In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 27)
begin:C_NUM_27
assign dout = {In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 28)
begin:C_NUM_28
assign dout = {In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 29)
begin:C_NUM_29
assign dout = {In28, In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 30)
begin:C_NUM_30
assign dout = {In29, In28, In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 31)
begin:C_NUM_31
assign dout = {In30, In29, In28, In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
generate if (NUM_PORTS == 32)
begin:C_NUM_32
assign dout = {In31, In30, In29, In28, In27, In26, In25, In24, In23, In22, In21, In20, In19, In18, In17, In16, In15, In14, In13, In12, In11, In10, In9, In8, In7, In6, In5, In4, In3, In2, In1, In0};
end
endgenerate
endmodule
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.