text
stringlengths 938
1.05M
|
---|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
// that should not work.
//
// The given generate loops should attempt to access invalid bits of mask and
// trigger errors.
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 3
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, so we can immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that all have errors in applying short-circuting to
// generate "if" conditionals.
// Attempt to access invalid bits of MASK in different ways
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE + 1)) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g + 1]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise AND
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE)) & MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise OR
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) | ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
// that should not work.
//
// The given generate loops should attempt to access invalid bits of mask and
// trigger errors.
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 3
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, so we can immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that all have errors in applying short-circuting to
// generate "if" conditionals.
// Attempt to access invalid bits of MASK in different ways
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE + 1)) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g + 1]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise AND
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE)) & MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise OR
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) | ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
// that should not work.
//
// The given generate loops should attempt to access invalid bits of mask and
// trigger errors.
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 3
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, so we can immediately finish
always @(posedge clk) begin
$write("*-* All Finished *-*\n");
$finish;
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that all have errors in applying short-circuting to
// generate "if" conditionals.
// Attempt to access invalid bits of MASK in different ways
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE + 1)) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g + 1]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise AND
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < (SIZE)) & MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
// Attempt to short-circuit bitwise OR
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) | ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Bitwise OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
end
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_arb2
#(
// Configuration
parameter string PIPELINE = "data_stall", // none|data|stall|data_stall|stall_data
parameter integer KEEP_LAST_GRANT = 1, // 0|1 - if one request can last multiple cycles (e.g. write burst), KEEP_LAST_GRANT must be 1
parameter integer NO_STALL_NETWORK = 0, // 0|1 - if one, remove the ability for arb to stall backward - must guarantee no collisions!
// Masters
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
// INPUTS
input logic clock,
input logic resetn,
// INTERFACES
acl_arb_intf m0_intf,
acl_arb_intf m1_intf,
acl_arb_intf mout_intf
);
/////////////////////////////////////////////
// ARCHITECTURE
/////////////////////////////////////////////
// mux_intf acts as an interface immediately after request arbitration
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
mux_intf();
// Selector and request arbitration.
logic mux_sel;
assign mux_intf.req = mux_sel ? m1_intf.req : m0_intf.req;
generate
if( KEEP_LAST_GRANT == 1 )
begin
logic last_mux_sel_r;
always_ff @( posedge clock )
last_mux_sel_r <= mux_sel;
always_comb
// Maintain last grant.
if( last_mux_sel_r == 1'b0 && m0_intf.req.request )
mux_sel = 1'b0;
else if( last_mux_sel_r == 1'b1 && m1_intf.req.request )
mux_sel = 1'b1;
// Arbitrarily favor m0.
else
mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
else
begin
// Arbitrarily favor m0.
assign mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
endgenerate
// Stall signal for each upstream master.
generate
if( NO_STALL_NETWORK == 1 )
begin
assign m0_intf.stall = '0;
assign m1_intf.stall = '0;
end
else
begin
assign m0_intf.stall = ( mux_sel & m1_intf.req.request) | mux_intf.stall;
assign m1_intf.stall = (~mux_sel & m0_intf.req.request) | mux_intf.stall;
end
endgenerate
// What happens at the output of the arbitration block? Depends on the pipelining option...
// Each option is responsible for the following:
// 1. Connecting mout_intf.req: request output of the arbitration block
// 2. Connecting mux_intf.stall: upstream (to input masters) stall signal
generate
if( PIPELINE == "none" )
begin
// Purely combinational. Not a single register to be seen.
// Request for downstream blocks.
assign mout_intf.req = mux_intf.req;
// Stall signal from downstream blocks
assign mux_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data" )
begin
// Standard pipeline register at output. Latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall" )
begin
// Staging register at output. Min. latency of zero cycles, max. latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data_stall" )
begin
// Pipeline register followed by staging register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf(), staging_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( pipe_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall_data" )
begin
// Staging register followed by pipeline register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf(), pipe_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( staging_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
endgenerate
endmodule
module acl_arb_pipeline_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_r();
// Pipeline register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
pipe_r.req <= 'x; // only signals reset explicitly below need to be reset at all
pipe_r.req.request <= 1'b0;
pipe_r.req.read <= 1'b0;
pipe_r.req.write <= 1'b0;
end
else if( !(out_intf.stall & pipe_r.req.request) )
pipe_r.req <= in_intf.req;
// Request for downstream blocks.
assign out_intf.req = pipe_r.req;
// Upstream stall signal.
assign in_intf.stall = out_intf.stall & pipe_r.req.request;
endmodule
module acl_arb_staging_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
logic stall_r;
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_r();
// Staging register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
staging_r.req <= 'x; // only signals reset explicitly below need to be reset at all
staging_r.req.request <= 1'b0;
staging_r.req.read <= 1'b0;
staging_r.req.write <= 1'b0;
end
else if( !stall_r )
staging_r.req <= in_intf.req;
// Stall register.
always @( posedge clock or negedge resetn )
if( !resetn )
stall_r <= 1'b0;
else
stall_r <= out_intf.stall & (stall_r | in_intf.req.request);
// Request for downstream blocks.
assign out_intf.req = stall_r ? staging_r.req : in_intf.req;
// Upstream stall signal.
assign in_intf.stall = stall_r;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_arb2
#(
// Configuration
parameter string PIPELINE = "data_stall", // none|data|stall|data_stall|stall_data
parameter integer KEEP_LAST_GRANT = 1, // 0|1 - if one request can last multiple cycles (e.g. write burst), KEEP_LAST_GRANT must be 1
parameter integer NO_STALL_NETWORK = 0, // 0|1 - if one, remove the ability for arb to stall backward - must guarantee no collisions!
// Masters
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
// INPUTS
input logic clock,
input logic resetn,
// INTERFACES
acl_arb_intf m0_intf,
acl_arb_intf m1_intf,
acl_arb_intf mout_intf
);
/////////////////////////////////////////////
// ARCHITECTURE
/////////////////////////////////////////////
// mux_intf acts as an interface immediately after request arbitration
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
mux_intf();
// Selector and request arbitration.
logic mux_sel;
assign mux_intf.req = mux_sel ? m1_intf.req : m0_intf.req;
generate
if( KEEP_LAST_GRANT == 1 )
begin
logic last_mux_sel_r;
always_ff @( posedge clock )
last_mux_sel_r <= mux_sel;
always_comb
// Maintain last grant.
if( last_mux_sel_r == 1'b0 && m0_intf.req.request )
mux_sel = 1'b0;
else if( last_mux_sel_r == 1'b1 && m1_intf.req.request )
mux_sel = 1'b1;
// Arbitrarily favor m0.
else
mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
else
begin
// Arbitrarily favor m0.
assign mux_sel = m0_intf.req.request ? 1'b0 : 1'b1;
end
endgenerate
// Stall signal for each upstream master.
generate
if( NO_STALL_NETWORK == 1 )
begin
assign m0_intf.stall = '0;
assign m1_intf.stall = '0;
end
else
begin
assign m0_intf.stall = ( mux_sel & m1_intf.req.request) | mux_intf.stall;
assign m1_intf.stall = (~mux_sel & m0_intf.req.request) | mux_intf.stall;
end
endgenerate
// What happens at the output of the arbitration block? Depends on the pipelining option...
// Each option is responsible for the following:
// 1. Connecting mout_intf.req: request output of the arbitration block
// 2. Connecting mux_intf.stall: upstream (to input masters) stall signal
generate
if( PIPELINE == "none" )
begin
// Purely combinational. Not a single register to be seen.
// Request for downstream blocks.
assign mout_intf.req = mux_intf.req;
// Stall signal from downstream blocks
assign mux_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data" )
begin
// Standard pipeline register at output. Latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall" )
begin
// Staging register at output. Min. latency of zero cycles, max. latency of one cycle.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "data_stall" )
begin
// Pipeline register followed by staging register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_intf(), staging_intf();
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( pipe_intf )
);
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( pipe_intf ),
.out_intf( staging_intf )
);
// Request for downstream blocks.
assign mout_intf.req = staging_intf.req;
// Stall signal from downstream blocks.
assign staging_intf.stall = mout_intf.stall;
end
else if( PIPELINE == "stall_data" )
begin
// Staging register followed by pipeline register at output. Min. latency
// of one cycle, max. latency of two cycles.
acl_arb_intf #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_intf(), pipe_intf();
acl_arb_staging_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging(
.clock( clock ),
.resetn( resetn ),
.in_intf( mux_intf ),
.out_intf( staging_intf )
);
acl_arb_pipeline_reg #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe(
.clock( clock ),
.resetn( resetn ),
.in_intf( staging_intf ),
.out_intf( pipe_intf )
);
// Request for downstream blocks.
assign mout_intf.req = pipe_intf.req;
// Stall signal from downstream blocks.
assign pipe_intf.stall = mout_intf.stall;
end
endgenerate
endmodule
module acl_arb_pipeline_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
pipe_r();
// Pipeline register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
pipe_r.req <= 'x; // only signals reset explicitly below need to be reset at all
pipe_r.req.request <= 1'b0;
pipe_r.req.read <= 1'b0;
pipe_r.req.write <= 1'b0;
end
else if( !(out_intf.stall & pipe_r.req.request) )
pipe_r.req <= in_intf.req;
// Request for downstream blocks.
assign out_intf.req = pipe_r.req;
// Upstream stall signal.
assign in_intf.stall = out_intf.stall & pipe_r.req.request;
endmodule
module acl_arb_staging_reg #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1 // > 0
)
(
input clock,
input resetn,
acl_arb_intf in_intf,
acl_arb_intf out_intf
);
logic stall_r;
acl_arb_data #(
.DATA_W( DATA_W ),
.BURSTCOUNT_W( BURSTCOUNT_W ),
.ADDRESS_W( ADDRESS_W ),
.BYTEENA_W( BYTEENA_W ),
.ID_W( ID_W )
)
staging_r();
// Staging register.
always @( posedge clock or negedge resetn )
if( !resetn )
begin
staging_r.req <= 'x; // only signals reset explicitly below need to be reset at all
staging_r.req.request <= 1'b0;
staging_r.req.read <= 1'b0;
staging_r.req.write <= 1'b0;
end
else if( !stall_r )
staging_r.req <= in_intf.req;
// Stall register.
always @( posedge clock or negedge resetn )
if( !resetn )
stall_r <= 1'b0;
else
stall_r <= out_intf.stall & (stall_r | in_intf.req.request);
// Request for downstream blocks.
assign out_intf.req = stall_r ? staging_r.req : in_intf.req;
// Upstream stall signal.
assign in_intf.stall = stall_r;
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Wilson Snyder.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [31:0] in = crc[31:0];
/*AUTOWIRE*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
wire [31:0] out; // From test of Test.v
// End of automatics
Test test (/*AUTOINST*/
// Outputs
.out (out[31:0]),
// Inputs
.clk (clk),
.in (in[31:0]));
// Aggregate outputs into a single result vector
wire [63:0] result = {32'h0, out};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'h458c2de282e30f8b
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module Test (/*AUTOARG*/
// Outputs
out,
// Inputs
clk, in
);
input clk;
input [31:0] in;
output wire [31:0] out;
reg [31:0] stage [3:0];
genvar g;
generate
for (g=0; g<4; g++) begin
always_comb begin
if (g==0) stage[g] = in;
else stage[g] = {stage[g-1][30:0],1'b1};
end
end
endgenerate
assign out = stage[3];
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_slave_rrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
parameter integer FIFO_DEPTH = 32, // > 0 (don't care if SLAVE_FIXED_LATENCY > 0)
parameter integer USE_LL_FIFO = 1, // 0|1
parameter integer SLAVE_FIXED_LATENCY = 0, // 0=not fixed latency, >0=# fixed latency cycles
// if >0 effectively FIFO_DEPTH=SLAVE_FIXED_LATENCY+1
parameter integer PIPELINE = 1 // 0|1
)
(
input logic clock,
input logic resetn,
acl_arb_intf m_intf,
input logic s_readdatavalid,
input logic [DATA_W-1:0] s_readdata,
acl_ic_rrp_intf rrp_intf,
output logic stall
);
typedef struct packed {
logic valid;
logic [DATA_W-1:0] data;
} slave_raw_read;
slave_raw_read slave_read_in;
slave_raw_read slave_read; // this is the slave interface to the rest of the module
assign slave_read_in = {s_readdatavalid, s_readdata};
generate
if( PIPELINE )
begin
// Pipeline the return path from the slave.
slave_raw_read slave_read_pipe;
always @(posedge clock or negedge resetn)
if( !resetn )
begin
slave_read_pipe <= 'x;
slave_read_pipe.valid <= 1'b0;
end
else
slave_read_pipe <= slave_read_in;
assign slave_read = slave_read_pipe;
end
else
begin
assign slave_read = slave_read_in;
end
endgenerate
generate
if( NUM_MASTERS > 1 )
begin
localparam READ_FIFO_DEPTH = SLAVE_FIXED_LATENCY > 0 ? SLAVE_FIXED_LATENCY : FIFO_DEPTH;
typedef struct packed {
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} raw_read_item;
typedef struct packed {
logic valid;
logic [ID_W-1:0] id;
logic [BURSTCOUNT_W-1:0] burstcount;
} read_item;
logic rf_full, rf_empty, rf_read, rf_write, next_read_item;
raw_read_item m_raw_read_item, rf_raw_read_item;
read_item rf_read_item, cur_read_item;
// FIFO of pending reads.
// Two parts to this FIFO:
// 1. An actual FIFO (either llfifo or scfifo).
// 2. cur_read_item is the current pending read
//
// Together, there must be at least READ_FIFO_DEPTH
// entries. Since cur_read_item counts as one,
// the actual FIFOs are sized to READ_FIFO_DEPTH-1.
if( USE_LL_FIFO == 1 )
begin
acl_ll_fifo #(
.WIDTH( $bits(raw_read_item) ),
.DEPTH( READ_FIFO_DEPTH - 1 )
)
read_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_raw_read_item ),
.write( rf_write ),
.data_out( rf_raw_read_item ),
.read( rf_read ),
.empty( rf_empty ),
.full( rf_full )
);
end
else
begin
scfifo #(
.lpm_width( $bits(raw_read_item) ),
.lpm_widthu( $clog2(READ_FIFO_DEPTH-1) ),
.lpm_numwords( READ_FIFO_DEPTH-1 ),
.add_ram_output_register( "ON" ),
.intended_device_family( "stratixiv" )
)
read_fifo (
.aclr( ~resetn ),
.clock( clock ),
.empty( rf_empty ),
.full( rf_full ),
.data( m_raw_read_item ),
.q( rf_raw_read_item ),
.wrreq( rf_write ),
.rdreq( rf_read ),
.sclr(),
.usedw(),
.almost_full(),
.almost_empty()
);
end
assign m_raw_read_item.id = m_intf.req.id;
assign m_raw_read_item.burstcount = m_intf.req.burstcount;
assign rf_read_item.id = rf_raw_read_item.id;
assign rf_read_item.burstcount = rf_raw_read_item.burstcount;
// Place incoming read requests from the master into read FIFO.
assign rf_write = ~m_intf.stall & m_intf.req.read;
// Read next item from the FIFO.
assign rf_read = ~rf_empty & (~rf_read_item.valid | next_read_item);
// Determine when cur_read_item can be updated, which is controlled by next_read_item.
assign next_read_item = ~cur_read_item.valid | (slave_read.valid & (cur_read_item.burstcount == 1));
// Stall upstream when read FIFO is full. If the slave is fixed latency, the read FIFO
// is sized such that it can never stall.
assign stall = SLAVE_FIXED_LATENCY > 0 ? 1'b0 : rf_full;
// cur_read_item
always @( posedge clock or negedge resetn )
begin
if( !resetn )
begin
cur_read_item <= 'x; // only fields explicitly reset below need to be reset at all
cur_read_item.valid <= 1'b0;
end
else
begin
// Handle incoming data from the slave.
if( slave_read.valid )
cur_read_item.burstcount <= cur_read_item.burstcount - 1;
// Update current read from the read FIFO. This logic takes priority over
// the logic above (both update cur_read_item.burstcount).
if( next_read_item )
cur_read_item <= rf_read_item;
end
end
// rrp_intf
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign rrp_intf.id = cur_read_item.id;
// Handle the rf_read_item.valid signal. Different behavior between
// sc_fifo and acl_ll_fifo.
if( USE_LL_FIFO == 1 )
begin
// The data is already at the output of the acl_ll_fifo, so the
// data is valid as long as the FIFO is not empty.
assign rf_read_item.valid = ~rf_empty;
end
else
begin
// The data is valid on the next cycle (due to output register on
// scfifo RAM block).
always @( posedge clock or negedge resetn )
begin
if( !resetn )
rf_read_item.valid <= 1'b0;
else if( rf_read )
rf_read_item.valid <= 1'b1;
else if( next_read_item & ~rf_read )
rf_read_item.valid <= 1'b0;
end
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
assign rrp_intf.datavalid = slave_read.valid;
assign rrp_intf.data = slave_read.data;
assign stall = 1'b0;
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Test for using DPI as general accessors
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012.
//
// Contributed by Jeremy Bennett and Jie Xul
//
// This test exercises the use of DPI to access signals and registers in a
// module hierarchy in a uniform fashion. See the discussion at
//
// http://www.veripool.org/boards/3/topics/show/752-Verilator-Command-line-specification-of-public-access-to-variables
//
// We need to test read and write access to:
// - scalars
// - vectors
// - array elements
// - slices of vectors or array elements
//
// We need to test that writing to non-writable elements generates an error.
//
// This Verilog would run forever. It will be stopped externally by the C++
// instantiating program.
// Define the width of registers and size of memory we use
`define REG_WIDTH 8
`define MEM_SIZE 256
// Top module defines the accessors and instantiates a sub-module with
// substantive content.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
`include "t_dpi_accessors_macros_inc.vh"
`include "t_dpi_accessors_inc.vh"
// Put the serious stuff in a sub-module, so we can check hierarchical
// access works OK.
test_sub i_test_sub (.clk (clk));
endmodule // t
// A sub-module with all sorts of goodies we would like to access
module test_sub (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer i; // General counter
// Elements we would like to access from outside
reg a;
reg [`REG_WIDTH - 1:0] b;
reg [`REG_WIDTH - 1:0] mem [`MEM_SIZE - 1:0];
wire c;
wire [`REG_WIDTH - 1:0] d;
reg [`REG_WIDTH - 1:0] e;
reg [`REG_WIDTH - 1:0] f;
// Drive our wires from our registers
assign c = ~a;
assign d = ~b;
// Initial values for registers and array
initial begin
a = 0;
b = `REG_WIDTH'h0;
for (i = 0; i < `MEM_SIZE; i++) begin
mem[i] = i [`REG_WIDTH - 1:0];
end
e = 0;
f = 0;
end
// Wipe out one memory cell in turn on the positive clock edge, restoring
// the previous element. We toggle the wipeout value.
always @(posedge clk) begin
mem[b] <= {`REG_WIDTH {a}};
mem[b - 1] <= b - 1;
a <= ~a;
b <= b + 1;
end
endmodule // test_sub
|
// DESCRIPTION: Verilator: Test for using DPI as general accessors
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012.
//
// Contributed by Jeremy Bennett and Jie Xul
//
// This test exercises the use of DPI to access signals and registers in a
// module hierarchy in a uniform fashion. See the discussion at
//
// http://www.veripool.org/boards/3/topics/show/752-Verilator-Command-line-specification-of-public-access-to-variables
//
// We need to test read and write access to:
// - scalars
// - vectors
// - array elements
// - slices of vectors or array elements
//
// We need to test that writing to non-writable elements generates an error.
//
// This Verilog would run forever. It will be stopped externally by the C++
// instantiating program.
// Define the width of registers and size of memory we use
`define REG_WIDTH 8
`define MEM_SIZE 256
// Top module defines the accessors and instantiates a sub-module with
// substantive content.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
`include "t_dpi_accessors_macros_inc.vh"
`include "t_dpi_accessors_inc.vh"
// Put the serious stuff in a sub-module, so we can check hierarchical
// access works OK.
test_sub i_test_sub (.clk (clk));
endmodule // t
// A sub-module with all sorts of goodies we would like to access
module test_sub (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer i; // General counter
// Elements we would like to access from outside
reg a;
reg [`REG_WIDTH - 1:0] b;
reg [`REG_WIDTH - 1:0] mem [`MEM_SIZE - 1:0];
wire c;
wire [`REG_WIDTH - 1:0] d;
reg [`REG_WIDTH - 1:0] e;
reg [`REG_WIDTH - 1:0] f;
// Drive our wires from our registers
assign c = ~a;
assign d = ~b;
// Initial values for registers and array
initial begin
a = 0;
b = `REG_WIDTH'h0;
for (i = 0; i < `MEM_SIZE; i++) begin
mem[i] = i [`REG_WIDTH - 1:0];
end
e = 0;
f = 0;
end
// Wipe out one memory cell in turn on the positive clock edge, restoring
// the previous element. We toggle the wipeout value.
always @(posedge clk) begin
mem[b] <= {`REG_WIDTH {a}};
mem[b - 1] <= b - 1;
a <= ~a;
b <= b + 1;
end
endmodule // test_sub
|
// DESCRIPTION: Verilator: Test for using DPI as general accessors
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012.
//
// Contributed by Jeremy Bennett and Jie Xul
//
// This test exercises the use of DPI to access signals and registers in a
// module hierarchy in a uniform fashion. See the discussion at
//
// http://www.veripool.org/boards/3/topics/show/752-Verilator-Command-line-specification-of-public-access-to-variables
//
// We need to test read and write access to:
// - scalars
// - vectors
// - array elements
// - slices of vectors or array elements
//
// We need to test that writing to non-writable elements generates an error.
//
// This Verilog would run forever. It will be stopped externally by the C++
// instantiating program.
// Define the width of registers and size of memory we use
`define REG_WIDTH 8
`define MEM_SIZE 256
// Top module defines the accessors and instantiates a sub-module with
// substantive content.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
`include "t_dpi_accessors_macros_inc.vh"
`include "t_dpi_accessors_inc.vh"
// Put the serious stuff in a sub-module, so we can check hierarchical
// access works OK.
test_sub i_test_sub (.clk (clk));
endmodule // t
// A sub-module with all sorts of goodies we would like to access
module test_sub (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer i; // General counter
// Elements we would like to access from outside
reg a;
reg [`REG_WIDTH - 1:0] b;
reg [`REG_WIDTH - 1:0] mem [`MEM_SIZE - 1:0];
wire c;
wire [`REG_WIDTH - 1:0] d;
reg [`REG_WIDTH - 1:0] e;
reg [`REG_WIDTH - 1:0] f;
// Drive our wires from our registers
assign c = ~a;
assign d = ~b;
// Initial values for registers and array
initial begin
a = 0;
b = `REG_WIDTH'h0;
for (i = 0; i < `MEM_SIZE; i++) begin
mem[i] = i [`REG_WIDTH - 1:0];
end
e = 0;
f = 0;
end
// Wipe out one memory cell in turn on the positive clock edge, restoring
// the previous element. We toggle the wipeout value.
always @(posedge clk) begin
mem[b] <= {`REG_WIDTH {a}};
mem[b - 1] <= b - 1;
a <= ~a;
b <= b + 1;
end
endmodule // test_sub
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. Device implementation can be selected via parameters.
//
// DATA_WIDTH = 0:
// Data width can be zero, in which case the the FIFO stores no data.
//
// Supported implementations (DATA_WIDTH > 0):
// ram: RAM-based FIFO (min. latency 3)
// ll_reg: low-latency register-based FIFO (min. latency 1)
// ll_ram: low-latency RAM (min. latency 1; combination of ll_reg + ram)
// zl_reg: zero-latency ll_reg (adds bypass path)
// zl_ram: zero-latency ll_ram (adds bypass path)
//
// Supported implementations (DATA_WIDTH == 0);
// For DATA_WIDTH == 0, the latency is either 1 ("low") or 0.
// All implementations mentioned above are supported, with their implications
// for either using the "ll_counter" or the "zl_counter"
// (i.e. ram/ll_reg/ll_ram -> ll_counter, zl_reg/zl_ram -> zl_counter).
//
// STRICT_DEPTH:
// A value of 0 means the FIFO that is instantiated will have a depth
// of at least DEPTH. A value of 1 means the FIFO will have a depth exactly
// equal to DEPTH.
//
//===----------------------------------------------------------------------===//
module acl_data_fifo
#(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 0, // 0|1 (1 == FIFO depth will be EXACTLY equal to DEPTH, otherwise >= DEPTH)
parameter integer ALLOW_FULL_WRITE = 0, // 0|1 (only supported by pure reg fifos: ll_reg, zl_reg, ll_counter, zl_counter)
parameter string IMPL = "ram", // see above (ram|ll_reg|ll_ram|zl_reg|zl_ram|ll_counter|zl_counter)
parameter integer ALMOST_FULL_VALUE = 0 // >= 0
)
(
input logic clock,
input logic resetn,
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
input logic valid_in,
output logic valid_out,
input logic stall_in,
output logic stall_out,
// internal signals (not required to use)
output logic empty,
output logic full,
output logic almost_full
);
generate
if( DATA_WIDTH > 0 )
begin
if( IMPL == "ram" )
begin
// Normal RAM FIFO.
// Note that ALLOW_FULL_WRITE == 1 is not supported.
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
end
else if( (IMPL == "ll_reg" || IMPL == "shift_reg") && DEPTH >= 2 && !ALLOW_FULL_WRITE )
begin
// For ll_reg's create an ll_fifo of DEPTH-1 with ALLOW_FULL_WRITE=1 followed by a staging register
wire r_valid;
wire [DATA_WIDTH-1:0] r_data;
wire staging_reg_stall;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH-1),
.ALLOW_FULL_WRITE(1),
.IMPL(IMPL),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(r_data),
.valid_in(valid_in),
.valid_out(r_valid),
.empty(empty),
.stall_in(staging_reg_stall),
.stall_out(stall_out),
.almost_full(almost_full)
);
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(r_data),
.i_valid(r_valid),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
else if( IMPL == "shift_reg" && DEPTH <= 1)
begin
// Shift register implementation of a FIFO
// Case:149478 Removed individual no-shift-reg
// assignments.
reg [DEPTH-1:0] r_valid_NO_SHIFT_REG;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data_NO_SHIFT_REG;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled_NO_SHIFT_REG;
integer i;
assign r_o_stall = r_valid_NO_SHIFT_REG & r_i_stall;
assign empty = !r_valid_NO_SHIFT_REG[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data_NO_SHIFT_REG[i+1];
r_valid_in[i] = r_valid_NO_SHIFT_REG[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid_NO_SHIFT_REG <= {(DEPTH){1'b0}};
r_data_NO_SHIFT_REG <= 'x;
filled_NO_SHIFT_REG <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled_NO_SHIFT_REG <= {filled_NO_SHIFT_REG[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled_NO_SHIFT_REG <= {1'b0,filled_NO_SHIFT_REG[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid_NO_SHIFT_REG[i] <= r_valid_in[i];
r_data_NO_SHIFT_REG[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled_NO_SHIFT_REG[DEPTH] & stall_in;
assign valid_out = r_valid_NO_SHIFT_REG[0];
assign data_out = r_data_NO_SHIFT_REG[0];
end
else if( IMPL == "shift_reg" )
begin
// Shift register implementation of a FIFO
reg [DEPTH-1:0] r_valid;
logic [DEPTH-1:0] r_valid_in;
reg [DEPTH-1:0][DATA_WIDTH-1:0] r_data;
logic [DEPTH-1:0][DATA_WIDTH-1:0] r_data_in;
wire [DEPTH-1:0] r_o_stall;
logic [DEPTH-1:0] r_i_stall;
reg [DEPTH:0] filled;
integer i;
assign r_o_stall = r_valid & r_i_stall;
assign empty = !r_valid[0];
always @(*)
begin
r_i_stall[0] = stall_in;
r_data_in[DEPTH-1] = data_in;
r_valid_in[DEPTH-1] = valid_in;
for (i=1; i<=DEPTH-1; i++)
r_i_stall[i] = r_o_stall[i-1];
for (i=0; i<DEPTH-1; i++)
begin
r_data_in[i] = r_data[i+1];
r_valid_in[i] = r_valid[i+1];
end
end
always @(posedge clock or negedge resetn)
begin
if (!resetn)
begin
r_valid <= {(DEPTH){1'b0}};
r_data <= 'x;
filled <= {{(DEPTH){1'b0}},1'b1};
end
else
begin
if (valid_in & ~stall_out & ~(valid_out & ~stall_in))
begin
filled <= {filled[DEPTH-1:0],1'b0}; // Added an element
end
else if (~(valid_in & ~stall_out) & valid_out & ~stall_in)
begin
filled <= {1'b0,filled[DEPTH:1]}; // Subtracted an element
end
for (i=0; i<=DEPTH-1; i++)
begin
if (!r_o_stall[i])
begin
r_valid[i] <= r_valid_in[i];
r_data[i] <= r_data_in[i];
end
end
end
end
assign stall_out = filled[DEPTH] & stall_in;
assign valid_out = r_valid[0];
assign data_out = r_data[0];
end
else if( IMPL == "ll_reg" )
begin
// LL REG FIFO. Supports ALLOW_FULL_WRITE == 1.
logic write, read;
assign write = valid_in & ~stall_out;
assign read = ~stall_in & ~empty;
acl_ll_fifo #(
.WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clk(clock),
.reset(~resetn),
.data_in(data_in),
.write(write),
.data_out(data_out),
.read(read),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
end
else if( IMPL == "ll_ram" )
begin
// LL RAM FIFO.
acl_ll_ram_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(data_out),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "passthrough" )
begin
// Useful for turning off a FIFO and making it into a wire
assign valid_out = valid_in;
assign stall_out = stall_in;
assign data_out = data_in;
end
else if( IMPL == "ram_plus_reg" )
begin
wire [DATA_WIDTH-1:0] rdata2;
wire v2;
wire s2;
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata2),
.valid_in(valid_in),
.valid_out(v2),
.stall_in(s2),
.empty(empty),
.stall_out(stall_out)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "sandwich" )
begin
wire [DATA_WIDTH-1:0] rdata1;
wire [DATA_WIDTH-1:0] rdata2;
wire v1, v2;
wire s1, s2;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer1 (
.clock(clock),
.resetn(resetn),
.data_in(data_in),
.data_out(rdata1),
.valid_in(valid_in),
.valid_out(v1),
.stall_in(s1),
.stall_out(stall_out)
);
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo_inner (
.clock(clock),
.resetn(resetn),
.data_in(rdata1),
.data_out(rdata2),
.valid_in(v1),
.valid_out(v2),
.stall_in(s2),
.stall_out(s1),
.empty(empty),
.almost_full(almost_full)
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
)
fifo_outer2 (
.clock(clock),
.resetn(resetn),
.data_in(rdata2),
.data_out(data_out),
.valid_in(v2),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(s2)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" )
begin
// ZL RAM/REG FIFO.
logic [DATA_WIDTH-1:0] fifo_data_in, fifo_data_out;
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL(IMPL == "zl_reg" ? "ll_reg" : "ll_ram"),
.ALMOST_FULL_VALUE(ALMOST_FULL_VALUE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(fifo_data_in),
.data_out(fifo_data_out),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full),
.almost_full(almost_full)
);
wire staging_reg_stall;
assign fifo_data_in = data_in;
assign fifo_valid_in = valid_in & (staging_reg_stall | fifo_valid_out);
assign fifo_stall_in = staging_reg_stall;
assign stall_out = fifo_stall_out;
// Staging register to break the stall path
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(fifo_valid_out ? fifo_data_out : data_in),
.i_valid(fifo_valid_out | valid_in),
.o_stall(staging_reg_stall),
.o_data(data_out),
.o_valid(valid_out),
.i_stall(stall_in)
);
end
end
else // DATA_WIDTH == 0
begin
if( IMPL == "ram" || IMPL == "ram_plus_reg" || IMPL == "ll_reg" || IMPL == "ll_ram" || IMPL == "ll_counter" )
begin
// LL counter fifo.
acl_valid_fifo_counter #(
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
counter (
.clock(clock),
.resetn(resetn),
.valid_in(valid_in),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_out),
.empty(empty),
.full(full)
);
end
else if( IMPL == "zl_reg" || IMPL == "zl_ram" || IMPL == "zl_counter" )
begin
// ZL counter fifo.
logic fifo_valid_in, fifo_valid_out;
logic fifo_stall_in, fifo_stall_out;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(DEPTH),
.STRICT_DEPTH(STRICT_DEPTH),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE),
.IMPL("ll_counter")
)
fifo (
.clock(clock),
.resetn(resetn),
.valid_in(fifo_valid_in),
.valid_out(fifo_valid_out),
.stall_in(fifo_stall_in),
.stall_out(fifo_stall_out),
.empty(empty),
.full(full)
);
assign fifo_valid_in = valid_in & (stall_in | fifo_valid_out);
assign fifo_stall_in = stall_in;
assign stall_out = fifo_stall_out;
assign valid_out = fifo_valid_out | valid_in;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// acl_staging_reg.v
//
// Module to implement a staging register. Used to pipeline stall signals.
//
module acl_staging_reg
(
clk, reset, i_data, i_valid, o_stall, o_data, o_valid, i_stall
);
/*************
* Parameters *
*************/
parameter WIDTH=32;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
input [WIDTH-1:0] i_data;
input i_valid;
output o_stall;
// Downstream interface
output [WIDTH-1:0] o_data;
output o_valid;
input i_stall;
/***************
* Architecture *
***************/
reg [WIDTH-1:0] r_data;
reg r_valid;
// Upstream
assign o_stall = r_valid;
// Downstream
assign o_data = (r_valid) ? r_data : i_data;
assign o_valid = (r_valid) ? r_valid : i_valid;
// Storage reg
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
r_valid <= 1'b0;
r_data <= 'x; // don't need to reset
end
else
begin
if (~r_valid) r_data <= i_data;
r_valid <= i_stall && (r_valid || i_valid);
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.
// acl_staging_reg.v
//
// Module to implement a staging register. Used to pipeline stall signals.
//
module acl_staging_reg
(
clk, reset, i_data, i_valid, o_stall, o_data, o_valid, i_stall
);
/*************
* Parameters *
*************/
parameter WIDTH=32;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
input [WIDTH-1:0] i_data;
input i_valid;
output o_stall;
// Downstream interface
output [WIDTH-1:0] o_data;
output o_valid;
input i_stall;
/***************
* Architecture *
***************/
reg [WIDTH-1:0] r_data;
reg r_valid;
// Upstream
assign o_stall = r_valid;
// Downstream
assign o_data = (r_valid) ? r_data : i_data;
assign o_valid = (r_valid) ? r_valid : i_valid;
// Storage reg
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
r_valid <= 1'b0;
r_data <= 'x; // don't need to reset
end
else
begin
if (~r_valid) r_data <= i_data;
r_valid <= i_stall && (r_valid || i_valid);
end
end
endmodule
|
(***********************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA-Rocquencourt & LRI-CNRS-Orsay *)
(* \VV/ *************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(***********************************************************************)
(**************************************************************)
(* MSetDecide.v *)
(* *)
(* Author: Aaron Bohannon *)
(**************************************************************)
(** This file implements a decision procedure for a certain
class of propositions involving finite sets. *)
Require Import Decidable DecidableTypeEx MSetFacts.
(** First, a version for Weak Sets in functorial presentation *)
Module WDecideOn (E : DecidableType)(Import M : WSetsOn E).
Module F := MSetFacts.WFactsOn E M.
(** * Overview
This functor defines the tactic [fsetdec], which will
solve any valid goal of the form
<<
forall s1 ... sn,
forall x1 ... xm,
P1 -> ... -> Pk -> P
>>
where [P]'s are defined by the grammar:
<<
P ::=
| Q
| Empty F
| Subset F F'
| Equal F F'
Q ::=
| E.eq X X'
| In X F
| Q /\ Q'
| Q \/ Q'
| Q -> Q'
| Q <-> Q'
| ~ Q
| True
| False
F ::=
| S
| empty
| singleton X
| add X F
| remove X F
| union F F'
| inter F F'
| diff F F'
X ::= x1 | ... | xm
S ::= s1 | ... | sn
>>
The tactic will also work on some goals that vary slightly from
the above form:
- The variables and hypotheses may be mixed in any order and may
have already been introduced into the context. Moreover,
there may be additional, unrelated hypotheses mixed in (these
will be ignored).
- A conjunction of hypotheses will be handled as easily as
separate hypotheses, i.e., [P1 /\ P2 -> P] can be solved iff
[P1 -> P2 -> P] can be solved.
- [fsetdec] should solve any goal if the MSet-related hypotheses
are contradictory.
- [fsetdec] will first perform any necessary zeta and beta
reductions and will invoke [subst] to eliminate any Coq
equalities between finite sets or their elements.
- If [E.eq] is convertible with Coq's equality, it will not
matter which one is used in the hypotheses or conclusion.
- The tactic can solve goals where the finite sets or set
elements are expressed by Coq terms that are more complicated
than variables. However, non-local definitions are not
expanded, and Coq equalities between non-variable terms are
not used. For example, this goal will be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2)
>>
This one will not be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2)
>>
*)
(** * Facts and Tactics for Propositional Logic
These lemmas and tactics are in a module so that they do
not affect the namespace if you import the enclosing
module [Decide]. *)
Module MSetLogicalFacts.
Require Export Decidable.
Require Export Setoid.
(** ** Lemmas and Tactics About Decidable Propositions *)
(** ** Propositional Equivalences Involving Negation
These are all written with the unfolded form of
negation, since I am not sure if setoid rewriting will
always perform conversion. *)
(** ** Tactics for Negations *)
Tactic Notation "fold" "any" "not" :=
repeat (
match goal with
| H: context [?P -> False] |- _ =>
fold (~ P) in H
| |- context [?P -> False] =>
fold (~ P)
end).
(** [push not using db] will pushes all negations to the
leaves of propositions in the goal, using the lemmas in
[db] to assist in checking the decidability of the
propositions involved. If [using db] is omitted, then
[core] will be used. Additional versions are provided
to manipulate the hypotheses or the hypotheses and goal
together.
XXX: This tactic and the similar subsequent ones should
have been defined using [autorewrite]. However, dealing
with multiples rewrite sites and side-conditions is
done more cleverly with the following explicit
analysis of goals. *)
Ltac or_not_l_iff P Q tac :=
(rewrite (or_not_l_iff_1 P Q) by tac) ||
(rewrite (or_not_l_iff_2 P Q) by tac).
Ltac or_not_r_iff P Q tac :=
(rewrite (or_not_r_iff_1 P Q) by tac) ||
(rewrite (or_not_r_iff_2 P Q) by tac).
Ltac or_not_l_iff_in P Q H tac :=
(rewrite (or_not_l_iff_1 P Q) in H by tac) ||
(rewrite (or_not_l_iff_2 P Q) in H by tac).
Ltac or_not_r_iff_in P Q H tac :=
(rewrite (or_not_r_iff_1 P Q) in H by tac) ||
(rewrite (or_not_r_iff_2 P Q) in H by tac).
Tactic Notation "push" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [?P \/ ?Q -> False] => rewrite (not_or_iff P Q)
| |- context [?P /\ ?Q -> False] => rewrite (not_and_iff P Q)
| |- context [(?P -> ?Q) -> False] => rewrite (not_imp_iff P Q) by dec
end);
fold any not.
Tactic Notation "push" "not" :=
push not using core.
Tactic Notation
"push" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [?P \/ ?Q -> False] |- _ => rewrite (not_or_iff P Q) in H
| H: context [?P /\ ?Q -> False] |- _ => rewrite (not_and_iff P Q) in H
| H: context [(?P -> ?Q) -> False] |- _ =>
rewrite (not_imp_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "push" "not" "in" "*" "|-" :=
push not in * |- using core.
Tactic Notation "push" "not" "in" "*" "using" ident(db) :=
push not using db; push not in * |- using db.
Tactic Notation "push" "not" "in" "*" :=
push not in * using core.
(** A simple test case to see how this works. *)
Lemma test_push : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ ((R -> P) \/ (Q -> R))) ->
(~ (P /\ R)) ->
(~ (P -> R)) ->
True.
Proof.
intros. push not in *.
(* note that ~(R->P) remains (since R isnt decidable) *)
tauto.
Qed.
(** [pull not using db] will pull as many negations as
possible toward the top of the propositions in the goal,
using the lemmas in [db] to assist in checking the
decidability of the propositions involved. If [using
db] is omitted, then [core] will be used. Additional
versions are provided to manipulate the hypotheses or
the hypotheses and goal together. *)
Tactic Notation "pull" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [(?P -> False) /\ (?Q -> False)] =>
rewrite <- (not_or_iff P Q)
| |- context [?P -> ?Q -> False] => rewrite <- (not_and_iff P Q)
| |- context [?P /\ (?Q -> False)] => rewrite <- (not_imp_iff P Q) by dec
| |- context [(?Q -> False) /\ ?P] =>
rewrite <- (not_imp_rev_iff P Q) by dec
end);
fold any not.
Tactic Notation "pull" "not" :=
pull not using core.
Tactic Notation
"pull" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
rewrite <- (not_or_iff P Q) in H
| H: context [?P -> ?Q -> False] |- _ =>
rewrite <- (not_and_iff P Q) in H
| H: context [?P /\ (?Q -> False)] |- _ =>
rewrite <- (not_imp_iff P Q) in H by dec
| H: context [(?Q -> False) /\ ?P] |- _ =>
rewrite <- (not_imp_rev_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "pull" "not" "in" "*" "|-" :=
pull not in * |- using core.
Tactic Notation "pull" "not" "in" "*" "using" ident(db) :=
pull not using db; pull not in * |- using db.
Tactic Notation "pull" "not" "in" "*" :=
pull not in * using core.
(** A simple test case to see how this works. *)
Lemma test_pull : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ (R -> P) /\ ~ (Q -> R)) ->
(~ P \/ ~ R) ->
(P /\ ~ R) ->
(~ R /\ P) ->
True.
Proof.
intros. pull not in *. tauto.
Qed.
End MSetLogicalFacts.
Import MSetLogicalFacts.
(** * Auxiliary Tactics
Again, these lemmas and tactics are in a module so that
they do not affect the namespace if you import the
enclosing module [Decide]. *)
Module MSetDecideAuxiliary.
(** ** Generic Tactics
We begin by defining a few generic, useful tactics. *)
(** remove logical hypothesis inter-dependencies (fix #2136). *)
Ltac no_logical_interdep :=
match goal with
| H : ?P |- _ =>
match type of P with
| Prop =>
match goal with H' : context [ H ] |- _ => clear dependent H' end
| _ => fail
end; no_logical_interdep
| _ => idtac
end.
(** [if t then t1 else t2] executes [t] and, if it does not
fail, then [t1] will be applied to all subgoals
produced. If [t] fails, then [t2] is executed. *)
Tactic Notation
"if" tactic(t)
"then" tactic(t1)
"else" tactic(t2) :=
first [ t; first [ t1 | fail 2 ] | t2 ].
Ltac abstract_term t :=
if (is_var t) then fail "no need to abstract a variable"
else (let x := fresh "x" in set (x := t) in *; try clearbody x).
Ltac abstract_elements :=
repeat
(match goal with
| |- context [ singleton ?t ] => abstract_term t
| _ : context [ singleton ?t ] |- _ => abstract_term t
| |- context [ add ?t _ ] => abstract_term t
| _ : context [ add ?t _ ] |- _ => abstract_term t
| |- context [ remove ?t _ ] => abstract_term t
| _ : context [ remove ?t _ ] |- _ => abstract_term t
| |- context [ In ?t _ ] => abstract_term t
| _ : context [ In ?t _ ] |- _ => abstract_term t
end).
(** [prop P holds by t] succeeds (but does not modify the
goal or context) if the proposition [P] can be proved by
[t] in the current context. Otherwise, the tactic
fails. *)
Tactic Notation "prop" constr(P) "holds" "by" tactic(t) :=
let H := fresh in
assert P as H by t;
clear H.
(** This tactic acts just like [assert ... by ...] but will
fail if the context already contains the proposition. *)
Tactic Notation "assert" "new" constr(e) "by" tactic(t) :=
match goal with
| H: e |- _ => fail 1
| _ => assert e by t
end.
(** [subst++] is similar to [subst] except that
- it never fails (as [subst] does on recursive
equations),
- it substitutes locally defined variable for their
definitions,
- it performs beta reductions everywhere, which may
arise after substituting a locally defined function
for its definition.
*)
Tactic Notation "subst" "++" :=
repeat (
match goal with
| x : _ |- _ => subst x
end);
cbv zeta beta in *.
(** [decompose records] calls [decompose record H] on every
relevant hypothesis [H]. *)
Tactic Notation "decompose" "records" :=
repeat (
match goal with
| H: _ |- _ => progress (decompose record H); clear H
end).
(** ** Discarding Irrelevant Hypotheses
We will want to clear the context of any
non-MSet-related hypotheses in order to increase the
speed of the tactic. To do this, we will need to be
able to decide which are relevant. We do this by making
a simple inductive definition classifying the
propositions of interest. *)
Inductive MSet_elt_Prop : Prop -> Prop :=
| eq_Prop : forall (S : Type) (x y : S),
MSet_elt_Prop (x = y)
| eq_elt_prop : forall x y,
MSet_elt_Prop (E.eq x y)
| In_elt_prop : forall x s,
MSet_elt_Prop (In x s)
| True_elt_prop :
MSet_elt_Prop True
| False_elt_prop :
MSet_elt_Prop False
| conj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P /\ Q)
| disj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P \/ Q)
| impl_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P -> Q)
| not_elt_prop : forall P,
MSet_elt_Prop P ->
MSet_elt_Prop (~ P).
Inductive MSet_Prop : Prop -> Prop :=
| elt_MSet_Prop : forall P,
MSet_elt_Prop P ->
MSet_Prop P
| Empty_MSet_Prop : forall s,
MSet_Prop (Empty s)
| Subset_MSet_Prop : forall s1 s2,
MSet_Prop (Subset s1 s2)
| Equal_MSet_Prop : forall s1 s2,
MSet_Prop (Equal s1 s2).
(** Here is the tactic that will throw away hypotheses that
are not useful (for the intended scope of the [fsetdec]
tactic). *)
Hint Constructors MSet_elt_Prop MSet_Prop : MSet_Prop.
Ltac discard_nonMSet :=
repeat (
match goal with
| H : context [ @Logic.eq ?T ?x ?y ] |- _ =>
if (change T with E.t in H) then fail
else if (change T with t in H) then fail
else clear H
| H : ?P |- _ =>
if prop (MSet_Prop P) holds by
(auto 100 with MSet_Prop)
then fail
else clear H
end).
(** ** Turning Set Operators into Propositional Connectives
The lemmas from [MSetFacts] will be used to break down
set operations into propositional formulas built over
the predicates [In] and [E.eq] applied only to
variables. We are going to use them with [autorewrite].
*)
Hint Rewrite
F.empty_iff F.singleton_iff F.add_iff F.remove_iff
F.union_iff F.inter_iff F.diff_iff
: set_simpl.
Lemma eq_refl_iff (x : E.t) : E.eq x x <-> True.
Proof.
now split.
Qed.
Hint Rewrite eq_refl_iff : set_eq_simpl.
(** ** Decidability of MSet Propositions *)
(** [In] is decidable. *)
Lemma dec_In : forall x s,
decidable (In x s).
Proof.
red; intros; generalize (F.mem_iff s x); case (mem x s); intuition.
Qed.
(** [E.eq] is decidable. *)
Lemma dec_eq : forall (x y : E.t),
decidable (E.eq x y).
Proof.
red; intros x y; destruct (E.eq_dec x y); auto.
Qed.
(** The hint database [MSet_decidability] will be given to
the [push_neg] tactic from the module [Negation]. *)
Hint Resolve dec_In dec_eq : MSet_decidability.
(** ** Normalizing Propositions About Equality
We have to deal with the fact that [E.eq] may be
convertible with Coq's equality. Thus, we will find the
following tactics useful to replace one form with the
other everywhere. *)
(** The next tactic, [Logic_eq_to_E_eq], mentions the term
[E.t]; thus, we must ensure that [E.t] is used in favor
of any other convertible but syntactically distinct
term. *)
Ltac change_to_E_t :=
repeat (
match goal with
| H : ?T |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
| H : forall x : ?T, _ |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
end).
(** These two tactics take us from Coq's built-in equality
to [E.eq] (and vice versa) when possible. *)
Ltac Logic_eq_to_E_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change (@Logic.eq E.t) with E.eq in H)
| |- _ =>
progress (change (@Logic.eq E.t) with E.eq)
end).
Ltac E_eq_to_Logic_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change E.eq with (@Logic.eq E.t) in H)
| |- _ =>
progress (change E.eq with (@Logic.eq E.t))
end).
(** This tactic works like the built-in tactic [subst], but
at the level of set element equality (which may not be
the convertible with Coq's equality). *)
Ltac substMSet :=
repeat (
match goal with
| H: E.eq ?x ?x |- _ => clear H
| H: E.eq ?x ?y |- _ => rewrite H in *; clear H
end);
autorewrite with set_eq_simpl in *.
(** ** Considering Decidability of Base Propositions
This tactic adds assertions about the decidability of
[E.eq] and [In] to the context. This is necessary for
the completeness of the [fsetdec] tactic. However, in
order to minimize the cost of proof search, we should be
careful to not add more than we need. Once negations
have been pushed to the leaves of the propositions, we
only need to worry about decidability for those base
propositions that appear in a negated form. *)
Ltac assert_decidability :=
(** We actually don't want these rules to fire if the
syntactic context in the patterns below is trivially
empty, but we'll just do some clean-up at the
afterward. *)
repeat (
match goal with
| H: context [~ E.eq ?x ?y] |- _ =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| H: context [~ In ?x ?s] |- _ =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
| |- context [~ E.eq ?x ?y] =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| |- context [~ In ?x ?s] =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
end);
(** Now we eliminate the useless facts we added (because
they would likely be very harmful to performance). *)
repeat (
match goal with
| _: ~ ?P, H : ?P \/ ~ ?P |- _ => clear H
end).
(** ** Handling [Empty], [Subset], and [Equal]
This tactic instantiates universally quantified
hypotheses (which arise from the unfolding of [Empty],
[Subset], and [Equal]) for each of the set element
expressions that is involved in some membership or
equality fact. Then it throws away those hypotheses,
which should no longer be needed. *)
Ltac inst_MSet_hypotheses :=
repeat (
match goal with
| H : forall a : E.t, _,
_ : context [ In ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ In ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq _ ?x ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq _ ?x ] =>
let P := type of (H x) in
assert new P by (exact (H x))
end);
repeat (
match goal with
| H : forall a : E.t, _ |- _ =>
clear H
end).
(** ** The Core [fsetdec] Auxiliary Tactics *)
(** Here is the crux of the proof search. Recursion through
[intuition]! (This will terminate if I correctly
understand the behavior of [intuition].) *)
Ltac fsetdec_rec := progress substMSet; intuition fsetdec_rec.
(** If we add [unfold Empty, Subset, Equal in *; intros;] to
the beginning of this tactic, it will satisfy the same
specification as the [fsetdec] tactic; however, it will
be much slower than necessary without the pre-processing
done by the wrapper tactic [fsetdec]. *)
Ltac fsetdec_body :=
autorewrite with set_eq_simpl in *;
inst_MSet_hypotheses;
autorewrite with set_simpl set_eq_simpl in *;
push not in * using MSet_decidability;
substMSet;
assert_decidability;
auto;
(intuition fsetdec_rec) ||
fail 1
"because the goal is beyond the scope of this tactic".
End MSetDecideAuxiliary.
Import MSetDecideAuxiliary.
(** * The [fsetdec] Tactic
Here is the top-level tactic (the only one intended for
clients of this library). It's specification is given at
the top of the file. *)
Ltac fsetdec :=
(** We first unfold any occurrences of [iff]. *)
unfold iff in *;
(** We fold occurrences of [not] because it is better for
[intros] to leave us with a goal of [~ P] than a goal of
[False]. *)
fold any not; intros;
(** We don't care about the value of elements : complex ones are
abstracted as new variables (avoiding potential dependencies,
see bug #2464) *)
abstract_elements;
(** We remove dependencies to logical hypothesis. This way,
later "clear" will work nicely (see bug #2136) *)
no_logical_interdep;
(** Now we decompose conjunctions, which will allow the
[discard_nonMSet] and [assert_decidability] tactics to
do a much better job. *)
decompose records;
discard_nonMSet;
(** We unfold these defined propositions on finite sets. If
our goal was one of them, then have one more item to
introduce now. *)
unfold Empty, Subset, Equal in *; intros;
(** We now want to get rid of all uses of [=] in favor of
[E.eq]. However, the best way to eliminate a [=] is in
the context is with [subst], so we will try that first.
In fact, we may as well convert uses of [E.eq] into [=]
when possible before we do [subst] so that we can even
more mileage out of it. Then we will convert all
remaining uses of [=] back to [E.eq] when possible. We
use [change_to_E_t] to ensure that we have a canonical
name for set elements, so that [Logic_eq_to_E_eq] will
work properly. *)
change_to_E_t; E_eq_to_Logic_eq; subst++; Logic_eq_to_E_eq;
(** The next optimization is to swap a negated goal with a
negated hypothesis when possible. Any swap will improve
performance by eliminating the total number of
negations, but we will get the maximum benefit if we
swap the goal with a hypotheses mentioning the same set
element, so we try that first. If we reach the fourth
branch below, we attempt any swap. However, to maintain
completeness of this tactic, we can only perform such a
swap with a decidable proposition; hence, we first test
whether the hypothesis is an [MSet_elt_Prop], noting
that any [MSet_elt_Prop] is decidable. *)
pull not using MSet_decidability;
unfold not in *;
match goal with
| H: (In ?x ?r) -> False |- (In ?x ?s) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
contradict H; fsetdec_body
| H: ?P -> False |- ?Q -> False =>
if prop (MSet_elt_Prop P) holds by
(auto 100 with MSet_Prop)
then (contradict H; fsetdec_body)
else fsetdec_body
| |- _ =>
fsetdec_body
end.
(** * Examples *)
Module MSetDecideTestCases.
Lemma test_eq_trans_1 : forall x y z s,
E.eq x y ->
~ ~ E.eq z y ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_trans_2 : forall x y z r s,
In x (singleton y) ->
~ In z r ->
~ ~ In z (add y r) ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_1 : forall w x y z s,
E.eq x w ->
~ ~ E.eq x y ->
~ E.eq y z ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_2 : forall w x y z r1 r2 s,
In x (singleton w) ->
~ In x r1 ->
In x (add y r1) ->
In y r2 ->
In y (remove z r2) ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_In_singleton : forall x,
In x (singleton x).
Proof. fsetdec. Qed.
Lemma test_add_In : forall x y s,
In x (add y s) ->
~ E.eq x y ->
In x s.
Proof. fsetdec. Qed.
Lemma test_Subset_add_remove : forall x s,
s [<=] (add x (remove x s)).
Proof. fsetdec. Qed.
Lemma test_eq_disjunction : forall w x y z,
In w (add x (add y (singleton z))) ->
E.eq w x \/ E.eq w y \/ E.eq w z.
Proof. fsetdec. Qed.
Lemma test_not_In_disj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ (In x s1 \/ In x s4 \/ E.eq y x).
Proof. fsetdec. Qed.
Lemma test_not_In_conj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ In x s1 /\ ~ In x s4 /\ ~ E.eq y x.
Proof. fsetdec. Qed.
Lemma test_iff_conj : forall a x s s',
(In a s' <-> E.eq x a \/ In a s) ->
(In a s' <-> In a (add x s)).
Proof. fsetdec. Qed.
Lemma test_set_ops_1 : forall x q r s,
(singleton x) [<=] s ->
Empty (union q r) ->
Empty (inter (diff s q) (diff s r)) ->
~ In x s.
Proof. fsetdec. Qed.
Lemma eq_chain_test : forall x1 x2 x3 x4 s1 s2 s3 s4,
Empty s1 ->
In x2 (add x1 s1) ->
In x3 s2 ->
~ In x3 (remove x2 s2) ->
~ In x4 s3 ->
In x4 (add x3 s3) ->
In x1 s4 ->
Subset (add x4 s4) s4.
Proof. fsetdec. Qed.
Lemma test_too_complex : forall x y z r s,
E.eq x y ->
(In x (singleton y) -> r [<=] s) ->
In z r ->
In z s.
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until s; intros Heq H Hr; lapply H; fsetdec.
Qed.
Lemma function_test_1 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2).
Proof. fsetdec. Qed.
Lemma function_test_2 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2).
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until 3. intros g_eq. rewrite <- g_eq. fsetdec.
Qed.
Lemma test_baydemir :
forall (f : t -> t),
forall (s : t),
forall (x y : elt),
In x (add y (f s)) ->
~ E.eq x y ->
In x (f s).
Proof.
fsetdec.
Qed.
End MSetDecideTestCases.
End WDecideOn.
Require Import MSetInterface.
(** Now comes variants for self-contained weak sets and for full sets.
For these variants, only one argument is necessary. Thanks to
the subtyping [WS<=S], the [Decide] functor which is meant to be
used on modules [(M:S)] can simply be an alias of [WDecide]. *)
Module WDecide (M:WSets) := !WDecideOn M.E M.
Module Decide := WDecide.
|
(***********************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA-Rocquencourt & LRI-CNRS-Orsay *)
(* \VV/ *************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(***********************************************************************)
(**************************************************************)
(* MSetDecide.v *)
(* *)
(* Author: Aaron Bohannon *)
(**************************************************************)
(** This file implements a decision procedure for a certain
class of propositions involving finite sets. *)
Require Import Decidable DecidableTypeEx MSetFacts.
(** First, a version for Weak Sets in functorial presentation *)
Module WDecideOn (E : DecidableType)(Import M : WSetsOn E).
Module F := MSetFacts.WFactsOn E M.
(** * Overview
This functor defines the tactic [fsetdec], which will
solve any valid goal of the form
<<
forall s1 ... sn,
forall x1 ... xm,
P1 -> ... -> Pk -> P
>>
where [P]'s are defined by the grammar:
<<
P ::=
| Q
| Empty F
| Subset F F'
| Equal F F'
Q ::=
| E.eq X X'
| In X F
| Q /\ Q'
| Q \/ Q'
| Q -> Q'
| Q <-> Q'
| ~ Q
| True
| False
F ::=
| S
| empty
| singleton X
| add X F
| remove X F
| union F F'
| inter F F'
| diff F F'
X ::= x1 | ... | xm
S ::= s1 | ... | sn
>>
The tactic will also work on some goals that vary slightly from
the above form:
- The variables and hypotheses may be mixed in any order and may
have already been introduced into the context. Moreover,
there may be additional, unrelated hypotheses mixed in (these
will be ignored).
- A conjunction of hypotheses will be handled as easily as
separate hypotheses, i.e., [P1 /\ P2 -> P] can be solved iff
[P1 -> P2 -> P] can be solved.
- [fsetdec] should solve any goal if the MSet-related hypotheses
are contradictory.
- [fsetdec] will first perform any necessary zeta and beta
reductions and will invoke [subst] to eliminate any Coq
equalities between finite sets or their elements.
- If [E.eq] is convertible with Coq's equality, it will not
matter which one is used in the hypotheses or conclusion.
- The tactic can solve goals where the finite sets or set
elements are expressed by Coq terms that are more complicated
than variables. However, non-local definitions are not
expanded, and Coq equalities between non-variable terms are
not used. For example, this goal will be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2)
>>
This one will not be solved:
<<
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2)
>>
*)
(** * Facts and Tactics for Propositional Logic
These lemmas and tactics are in a module so that they do
not affect the namespace if you import the enclosing
module [Decide]. *)
Module MSetLogicalFacts.
Require Export Decidable.
Require Export Setoid.
(** ** Lemmas and Tactics About Decidable Propositions *)
(** ** Propositional Equivalences Involving Negation
These are all written with the unfolded form of
negation, since I am not sure if setoid rewriting will
always perform conversion. *)
(** ** Tactics for Negations *)
Tactic Notation "fold" "any" "not" :=
repeat (
match goal with
| H: context [?P -> False] |- _ =>
fold (~ P) in H
| |- context [?P -> False] =>
fold (~ P)
end).
(** [push not using db] will pushes all negations to the
leaves of propositions in the goal, using the lemmas in
[db] to assist in checking the decidability of the
propositions involved. If [using db] is omitted, then
[core] will be used. Additional versions are provided
to manipulate the hypotheses or the hypotheses and goal
together.
XXX: This tactic and the similar subsequent ones should
have been defined using [autorewrite]. However, dealing
with multiples rewrite sites and side-conditions is
done more cleverly with the following explicit
analysis of goals. *)
Ltac or_not_l_iff P Q tac :=
(rewrite (or_not_l_iff_1 P Q) by tac) ||
(rewrite (or_not_l_iff_2 P Q) by tac).
Ltac or_not_r_iff P Q tac :=
(rewrite (or_not_r_iff_1 P Q) by tac) ||
(rewrite (or_not_r_iff_2 P Q) by tac).
Ltac or_not_l_iff_in P Q H tac :=
(rewrite (or_not_l_iff_1 P Q) in H by tac) ||
(rewrite (or_not_l_iff_2 P Q) in H by tac).
Ltac or_not_r_iff_in P Q H tac :=
(rewrite (or_not_r_iff_1 P Q) in H by tac) ||
(rewrite (or_not_r_iff_2 P Q) in H by tac).
Tactic Notation "push" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [?P \/ ?Q -> False] => rewrite (not_or_iff P Q)
| |- context [?P /\ ?Q -> False] => rewrite (not_and_iff P Q)
| |- context [(?P -> ?Q) -> False] => rewrite (not_imp_iff P Q) by dec
end);
fold any not.
Tactic Notation "push" "not" :=
push not using core.
Tactic Notation
"push" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [?P \/ ?Q -> False] |- _ => rewrite (not_or_iff P Q) in H
| H: context [?P /\ ?Q -> False] |- _ => rewrite (not_and_iff P Q) in H
| H: context [(?P -> ?Q) -> False] |- _ =>
rewrite (not_imp_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "push" "not" "in" "*" "|-" :=
push not in * |- using core.
Tactic Notation "push" "not" "in" "*" "using" ident(db) :=
push not using db; push not in * |- using db.
Tactic Notation "push" "not" "in" "*" :=
push not in * using core.
(** A simple test case to see how this works. *)
Lemma test_push : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ ((R -> P) \/ (Q -> R))) ->
(~ (P /\ R)) ->
(~ (P -> R)) ->
True.
Proof.
intros. push not in *.
(* note that ~(R->P) remains (since R isnt decidable) *)
tauto.
Qed.
(** [pull not using db] will pull as many negations as
possible toward the top of the propositions in the goal,
using the lemmas in [db] to assist in checking the
decidability of the propositions involved. If [using
db] is omitted, then [core] will be used. Additional
versions are provided to manipulate the hypotheses or
the hypotheses and goal together. *)
Tactic Notation "pull" "not" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff;
repeat (
match goal with
| |- context [True -> False] => rewrite not_true_iff
| |- context [False -> False] => rewrite not_false_iff
| |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
| |- context [(?P -> False) -> (?Q -> False)] =>
rewrite (contrapositive P Q) by dec
| |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
| |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
| |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
| |- context [(?P -> False) /\ (?Q -> False)] =>
rewrite <- (not_or_iff P Q)
| |- context [?P -> ?Q -> False] => rewrite <- (not_and_iff P Q)
| |- context [?P /\ (?Q -> False)] => rewrite <- (not_imp_iff P Q) by dec
| |- context [(?Q -> False) /\ ?P] =>
rewrite <- (not_imp_rev_iff P Q) by dec
end);
fold any not.
Tactic Notation "pull" "not" :=
pull not using core.
Tactic Notation
"pull" "not" "in" "*" "|-" "using" ident(db) :=
let dec := solve_decidable using db in
unfold not, iff in * |-;
repeat (
match goal with
| H: context [True -> False] |- _ => rewrite not_true_iff in H
| H: context [False -> False] |- _ => rewrite not_false_iff in H
| H: context [(?P -> False) -> False] |- _ =>
rewrite (not_not_iff P) in H by dec
| H: context [(?P -> False) -> (?Q -> False)] |- _ =>
rewrite (contrapositive P Q) in H by dec
| H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
| H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
| H: context [(?P -> False) -> ?Q] |- _ =>
rewrite (imp_not_l P Q) in H by dec
| H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
rewrite <- (not_or_iff P Q) in H
| H: context [?P -> ?Q -> False] |- _ =>
rewrite <- (not_and_iff P Q) in H
| H: context [?P /\ (?Q -> False)] |- _ =>
rewrite <- (not_imp_iff P Q) in H by dec
| H: context [(?Q -> False) /\ ?P] |- _ =>
rewrite <- (not_imp_rev_iff P Q) in H by dec
end);
fold any not.
Tactic Notation "pull" "not" "in" "*" "|-" :=
pull not in * |- using core.
Tactic Notation "pull" "not" "in" "*" "using" ident(db) :=
pull not using db; pull not in * |- using db.
Tactic Notation "pull" "not" "in" "*" :=
pull not in * using core.
(** A simple test case to see how this works. *)
Lemma test_pull : forall P Q R : Prop,
decidable P ->
decidable Q ->
(~ True) ->
(~ False) ->
(~ ~ P) ->
(~ (P /\ Q) -> ~ R) ->
((P /\ Q) \/ ~ R) ->
(~ (P /\ Q) \/ R) ->
(R \/ ~ (P /\ Q)) ->
(~ R \/ (P /\ Q)) ->
(~ P -> R) ->
(~ (R -> P) /\ ~ (Q -> R)) ->
(~ P \/ ~ R) ->
(P /\ ~ R) ->
(~ R /\ P) ->
True.
Proof.
intros. pull not in *. tauto.
Qed.
End MSetLogicalFacts.
Import MSetLogicalFacts.
(** * Auxiliary Tactics
Again, these lemmas and tactics are in a module so that
they do not affect the namespace if you import the
enclosing module [Decide]. *)
Module MSetDecideAuxiliary.
(** ** Generic Tactics
We begin by defining a few generic, useful tactics. *)
(** remove logical hypothesis inter-dependencies (fix #2136). *)
Ltac no_logical_interdep :=
match goal with
| H : ?P |- _ =>
match type of P with
| Prop =>
match goal with H' : context [ H ] |- _ => clear dependent H' end
| _ => fail
end; no_logical_interdep
| _ => idtac
end.
(** [if t then t1 else t2] executes [t] and, if it does not
fail, then [t1] will be applied to all subgoals
produced. If [t] fails, then [t2] is executed. *)
Tactic Notation
"if" tactic(t)
"then" tactic(t1)
"else" tactic(t2) :=
first [ t; first [ t1 | fail 2 ] | t2 ].
Ltac abstract_term t :=
if (is_var t) then fail "no need to abstract a variable"
else (let x := fresh "x" in set (x := t) in *; try clearbody x).
Ltac abstract_elements :=
repeat
(match goal with
| |- context [ singleton ?t ] => abstract_term t
| _ : context [ singleton ?t ] |- _ => abstract_term t
| |- context [ add ?t _ ] => abstract_term t
| _ : context [ add ?t _ ] |- _ => abstract_term t
| |- context [ remove ?t _ ] => abstract_term t
| _ : context [ remove ?t _ ] |- _ => abstract_term t
| |- context [ In ?t _ ] => abstract_term t
| _ : context [ In ?t _ ] |- _ => abstract_term t
end).
(** [prop P holds by t] succeeds (but does not modify the
goal or context) if the proposition [P] can be proved by
[t] in the current context. Otherwise, the tactic
fails. *)
Tactic Notation "prop" constr(P) "holds" "by" tactic(t) :=
let H := fresh in
assert P as H by t;
clear H.
(** This tactic acts just like [assert ... by ...] but will
fail if the context already contains the proposition. *)
Tactic Notation "assert" "new" constr(e) "by" tactic(t) :=
match goal with
| H: e |- _ => fail 1
| _ => assert e by t
end.
(** [subst++] is similar to [subst] except that
- it never fails (as [subst] does on recursive
equations),
- it substitutes locally defined variable for their
definitions,
- it performs beta reductions everywhere, which may
arise after substituting a locally defined function
for its definition.
*)
Tactic Notation "subst" "++" :=
repeat (
match goal with
| x : _ |- _ => subst x
end);
cbv zeta beta in *.
(** [decompose records] calls [decompose record H] on every
relevant hypothesis [H]. *)
Tactic Notation "decompose" "records" :=
repeat (
match goal with
| H: _ |- _ => progress (decompose record H); clear H
end).
(** ** Discarding Irrelevant Hypotheses
We will want to clear the context of any
non-MSet-related hypotheses in order to increase the
speed of the tactic. To do this, we will need to be
able to decide which are relevant. We do this by making
a simple inductive definition classifying the
propositions of interest. *)
Inductive MSet_elt_Prop : Prop -> Prop :=
| eq_Prop : forall (S : Type) (x y : S),
MSet_elt_Prop (x = y)
| eq_elt_prop : forall x y,
MSet_elt_Prop (E.eq x y)
| In_elt_prop : forall x s,
MSet_elt_Prop (In x s)
| True_elt_prop :
MSet_elt_Prop True
| False_elt_prop :
MSet_elt_Prop False
| conj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P /\ Q)
| disj_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P \/ Q)
| impl_elt_prop : forall P Q,
MSet_elt_Prop P ->
MSet_elt_Prop Q ->
MSet_elt_Prop (P -> Q)
| not_elt_prop : forall P,
MSet_elt_Prop P ->
MSet_elt_Prop (~ P).
Inductive MSet_Prop : Prop -> Prop :=
| elt_MSet_Prop : forall P,
MSet_elt_Prop P ->
MSet_Prop P
| Empty_MSet_Prop : forall s,
MSet_Prop (Empty s)
| Subset_MSet_Prop : forall s1 s2,
MSet_Prop (Subset s1 s2)
| Equal_MSet_Prop : forall s1 s2,
MSet_Prop (Equal s1 s2).
(** Here is the tactic that will throw away hypotheses that
are not useful (for the intended scope of the [fsetdec]
tactic). *)
Hint Constructors MSet_elt_Prop MSet_Prop : MSet_Prop.
Ltac discard_nonMSet :=
repeat (
match goal with
| H : context [ @Logic.eq ?T ?x ?y ] |- _ =>
if (change T with E.t in H) then fail
else if (change T with t in H) then fail
else clear H
| H : ?P |- _ =>
if prop (MSet_Prop P) holds by
(auto 100 with MSet_Prop)
then fail
else clear H
end).
(** ** Turning Set Operators into Propositional Connectives
The lemmas from [MSetFacts] will be used to break down
set operations into propositional formulas built over
the predicates [In] and [E.eq] applied only to
variables. We are going to use them with [autorewrite].
*)
Hint Rewrite
F.empty_iff F.singleton_iff F.add_iff F.remove_iff
F.union_iff F.inter_iff F.diff_iff
: set_simpl.
Lemma eq_refl_iff (x : E.t) : E.eq x x <-> True.
Proof.
now split.
Qed.
Hint Rewrite eq_refl_iff : set_eq_simpl.
(** ** Decidability of MSet Propositions *)
(** [In] is decidable. *)
Lemma dec_In : forall x s,
decidable (In x s).
Proof.
red; intros; generalize (F.mem_iff s x); case (mem x s); intuition.
Qed.
(** [E.eq] is decidable. *)
Lemma dec_eq : forall (x y : E.t),
decidable (E.eq x y).
Proof.
red; intros x y; destruct (E.eq_dec x y); auto.
Qed.
(** The hint database [MSet_decidability] will be given to
the [push_neg] tactic from the module [Negation]. *)
Hint Resolve dec_In dec_eq : MSet_decidability.
(** ** Normalizing Propositions About Equality
We have to deal with the fact that [E.eq] may be
convertible with Coq's equality. Thus, we will find the
following tactics useful to replace one form with the
other everywhere. *)
(** The next tactic, [Logic_eq_to_E_eq], mentions the term
[E.t]; thus, we must ensure that [E.t] is used in favor
of any other convertible but syntactically distinct
term. *)
Ltac change_to_E_t :=
repeat (
match goal with
| H : ?T |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
| H : forall x : ?T, _ |- _ =>
progress (change T with E.t in H);
repeat (
match goal with
| J : _ |- _ => progress (change T with E.t in J)
| |- _ => progress (change T with E.t)
end )
end).
(** These two tactics take us from Coq's built-in equality
to [E.eq] (and vice versa) when possible. *)
Ltac Logic_eq_to_E_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change (@Logic.eq E.t) with E.eq in H)
| |- _ =>
progress (change (@Logic.eq E.t) with E.eq)
end).
Ltac E_eq_to_Logic_eq :=
repeat (
match goal with
| H: _ |- _ =>
progress (change E.eq with (@Logic.eq E.t) in H)
| |- _ =>
progress (change E.eq with (@Logic.eq E.t))
end).
(** This tactic works like the built-in tactic [subst], but
at the level of set element equality (which may not be
the convertible with Coq's equality). *)
Ltac substMSet :=
repeat (
match goal with
| H: E.eq ?x ?x |- _ => clear H
| H: E.eq ?x ?y |- _ => rewrite H in *; clear H
end);
autorewrite with set_eq_simpl in *.
(** ** Considering Decidability of Base Propositions
This tactic adds assertions about the decidability of
[E.eq] and [In] to the context. This is necessary for
the completeness of the [fsetdec] tactic. However, in
order to minimize the cost of proof search, we should be
careful to not add more than we need. Once negations
have been pushed to the leaves of the propositions, we
only need to worry about decidability for those base
propositions that appear in a negated form. *)
Ltac assert_decidability :=
(** We actually don't want these rules to fire if the
syntactic context in the patterns below is trivially
empty, but we'll just do some clean-up at the
afterward. *)
repeat (
match goal with
| H: context [~ E.eq ?x ?y] |- _ =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| H: context [~ In ?x ?s] |- _ =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
| |- context [~ E.eq ?x ?y] =>
assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
| |- context [~ In ?x ?s] =>
assert new (In x s \/ ~ In x s) by (apply dec_In)
end);
(** Now we eliminate the useless facts we added (because
they would likely be very harmful to performance). *)
repeat (
match goal with
| _: ~ ?P, H : ?P \/ ~ ?P |- _ => clear H
end).
(** ** Handling [Empty], [Subset], and [Equal]
This tactic instantiates universally quantified
hypotheses (which arise from the unfolding of [Empty],
[Subset], and [Equal]) for each of the set element
expressions that is involved in some membership or
equality fact. Then it throws away those hypotheses,
which should no longer be needed. *)
Ltac inst_MSet_hypotheses :=
repeat (
match goal with
| H : forall a : E.t, _,
_ : context [ In ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ In ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq ?x _ ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq ?x _ ] =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _,
_ : context [ E.eq _ ?x ] |- _ =>
let P := type of (H x) in
assert new P by (exact (H x))
| H : forall a : E.t, _
|- context [ E.eq _ ?x ] =>
let P := type of (H x) in
assert new P by (exact (H x))
end);
repeat (
match goal with
| H : forall a : E.t, _ |- _ =>
clear H
end).
(** ** The Core [fsetdec] Auxiliary Tactics *)
(** Here is the crux of the proof search. Recursion through
[intuition]! (This will terminate if I correctly
understand the behavior of [intuition].) *)
Ltac fsetdec_rec := progress substMSet; intuition fsetdec_rec.
(** If we add [unfold Empty, Subset, Equal in *; intros;] to
the beginning of this tactic, it will satisfy the same
specification as the [fsetdec] tactic; however, it will
be much slower than necessary without the pre-processing
done by the wrapper tactic [fsetdec]. *)
Ltac fsetdec_body :=
autorewrite with set_eq_simpl in *;
inst_MSet_hypotheses;
autorewrite with set_simpl set_eq_simpl in *;
push not in * using MSet_decidability;
substMSet;
assert_decidability;
auto;
(intuition fsetdec_rec) ||
fail 1
"because the goal is beyond the scope of this tactic".
End MSetDecideAuxiliary.
Import MSetDecideAuxiliary.
(** * The [fsetdec] Tactic
Here is the top-level tactic (the only one intended for
clients of this library). It's specification is given at
the top of the file. *)
Ltac fsetdec :=
(** We first unfold any occurrences of [iff]. *)
unfold iff in *;
(** We fold occurrences of [not] because it is better for
[intros] to leave us with a goal of [~ P] than a goal of
[False]. *)
fold any not; intros;
(** We don't care about the value of elements : complex ones are
abstracted as new variables (avoiding potential dependencies,
see bug #2464) *)
abstract_elements;
(** We remove dependencies to logical hypothesis. This way,
later "clear" will work nicely (see bug #2136) *)
no_logical_interdep;
(** Now we decompose conjunctions, which will allow the
[discard_nonMSet] and [assert_decidability] tactics to
do a much better job. *)
decompose records;
discard_nonMSet;
(** We unfold these defined propositions on finite sets. If
our goal was one of them, then have one more item to
introduce now. *)
unfold Empty, Subset, Equal in *; intros;
(** We now want to get rid of all uses of [=] in favor of
[E.eq]. However, the best way to eliminate a [=] is in
the context is with [subst], so we will try that first.
In fact, we may as well convert uses of [E.eq] into [=]
when possible before we do [subst] so that we can even
more mileage out of it. Then we will convert all
remaining uses of [=] back to [E.eq] when possible. We
use [change_to_E_t] to ensure that we have a canonical
name for set elements, so that [Logic_eq_to_E_eq] will
work properly. *)
change_to_E_t; E_eq_to_Logic_eq; subst++; Logic_eq_to_E_eq;
(** The next optimization is to swap a negated goal with a
negated hypothesis when possible. Any swap will improve
performance by eliminating the total number of
negations, but we will get the maximum benefit if we
swap the goal with a hypotheses mentioning the same set
element, so we try that first. If we reach the fourth
branch below, we attempt any swap. However, to maintain
completeness of this tactic, we can only perform such a
swap with a decidable proposition; hence, we first test
whether the hypothesis is an [MSet_elt_Prop], noting
that any [MSet_elt_Prop] is decidable. *)
pull not using MSet_decidability;
unfold not in *;
match goal with
| H: (In ?x ?r) -> False |- (In ?x ?s) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
contradict H; fsetdec_body
| H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
contradict H; fsetdec_body
| H: ?P -> False |- ?Q -> False =>
if prop (MSet_elt_Prop P) holds by
(auto 100 with MSet_Prop)
then (contradict H; fsetdec_body)
else fsetdec_body
| |- _ =>
fsetdec_body
end.
(** * Examples *)
Module MSetDecideTestCases.
Lemma test_eq_trans_1 : forall x y z s,
E.eq x y ->
~ ~ E.eq z y ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_trans_2 : forall x y z r s,
In x (singleton y) ->
~ In z r ->
~ ~ In z (add y r) ->
In x s ->
In z s.
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_1 : forall w x y z s,
E.eq x w ->
~ ~ E.eq x y ->
~ E.eq y z ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_eq_neq_trans_2 : forall w x y z r1 r2 s,
In x (singleton w) ->
~ In x r1 ->
In x (add y r1) ->
In y r2 ->
In y (remove z r2) ->
In w s ->
In w (remove z s).
Proof. fsetdec. Qed.
Lemma test_In_singleton : forall x,
In x (singleton x).
Proof. fsetdec. Qed.
Lemma test_add_In : forall x y s,
In x (add y s) ->
~ E.eq x y ->
In x s.
Proof. fsetdec. Qed.
Lemma test_Subset_add_remove : forall x s,
s [<=] (add x (remove x s)).
Proof. fsetdec. Qed.
Lemma test_eq_disjunction : forall w x y z,
In w (add x (add y (singleton z))) ->
E.eq w x \/ E.eq w y \/ E.eq w z.
Proof. fsetdec. Qed.
Lemma test_not_In_disj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ (In x s1 \/ In x s4 \/ E.eq y x).
Proof. fsetdec. Qed.
Lemma test_not_In_conj : forall x y s1 s2 s3 s4,
~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
~ In x s1 /\ ~ In x s4 /\ ~ E.eq y x.
Proof. fsetdec. Qed.
Lemma test_iff_conj : forall a x s s',
(In a s' <-> E.eq x a \/ In a s) ->
(In a s' <-> In a (add x s)).
Proof. fsetdec. Qed.
Lemma test_set_ops_1 : forall x q r s,
(singleton x) [<=] s ->
Empty (union q r) ->
Empty (inter (diff s q) (diff s r)) ->
~ In x s.
Proof. fsetdec. Qed.
Lemma eq_chain_test : forall x1 x2 x3 x4 s1 s2 s3 s4,
Empty s1 ->
In x2 (add x1 s1) ->
In x3 s2 ->
~ In x3 (remove x2 s2) ->
~ In x4 s3 ->
In x4 (add x3 s3) ->
In x1 s4 ->
Subset (add x4 s4) s4.
Proof. fsetdec. Qed.
Lemma test_too_complex : forall x y z r s,
E.eq x y ->
(In x (singleton y) -> r [<=] s) ->
In z r ->
In z s.
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until s; intros Heq H Hr; lapply H; fsetdec.
Qed.
Lemma function_test_1 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g (g x2)) ->
In x1 s1 ->
In (g (g x2)) (f s2).
Proof. fsetdec. Qed.
Lemma function_test_2 :
forall (f : t -> t),
forall (g : elt -> elt),
forall (s1 s2 : t),
forall (x1 x2 : elt),
Equal s1 (f s2) ->
E.eq x1 (g x2) ->
In x1 s1 ->
g x2 = g (g x2) ->
In (g (g x2)) (f s2).
Proof.
(** [fsetdec] is not intended to solve this directly. *)
intros until 3. intros g_eq. rewrite <- g_eq. fsetdec.
Qed.
Lemma test_baydemir :
forall (f : t -> t),
forall (s : t),
forall (x y : elt),
In x (add y (f s)) ->
~ E.eq x y ->
In x (f s).
Proof.
fsetdec.
Qed.
End MSetDecideTestCases.
End WDecideOn.
Require Import MSetInterface.
(** Now comes variants for self-contained weak sets and for full sets.
For these variants, only one argument is necessary. Thanks to
the subtyping [WS<=S], the [Decide] functor which is meant to be
used on modules [(M:S)] can simply be an alias of [WDecide]. *)
Module WDecide (M:WSets) := !WDecideOn M.E M.
Module Decide := WDecide.
|
module timer #
(
parameter WIDTH = 64,
parameter USE_2XCLK = 0,
parameter S_WIDTH_A = 2
)
(
input clk,
input clk2x,
input resetn,
// Slave port
input [S_WIDTH_A-1:0] slave_address, // Word address
input [WIDTH-1:0] slave_writedata,
input slave_read,
input slave_write,
input [WIDTH/8-1:0] slave_byteenable,
output slave_waitrequest,
output [WIDTH-1:0] slave_readdata,
output slave_readdatavalid
);
reg [WIDTH-1:0] counter;
reg [WIDTH-1:0] counter2x;
reg clock_sel;
always@(posedge clk or negedge resetn)
if (!resetn)
clock_sel <= 1'b0;
else if (slave_write)
if (|slave_writedata)
clock_sel <= 1'b1;
else
clock_sel <= 1'b0;
always@(posedge clk or negedge resetn)
if (!resetn)
counter <= {WIDTH{1'b0}};
else if (slave_write)
counter <= {WIDTH{1'b0}};
else
counter <= counter + 2'b01;
always@(posedge clk2x or negedge resetn)
if (!resetn)
counter2x <= {WIDTH{1'b0}};
else if (slave_write)
counter2x <= {WIDTH{1'b0}};
else
counter2x <= counter2x + 2'b01;
assign slave_waitrequest = 1'b0;
assign slave_readdata = (USE_2XCLK && clock_sel) ? counter2x : counter;
assign slave_readdatavalid = slave_read;
endmodule
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
`timescale 1ps/1ps
module altera_pll_reconfig_core
#(
parameter reconf_width = 64,
parameter device_family = "Stratix V",
// MIF Streaming parameters
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter ROM_ADDR_WIDTH = 9,
parameter ROM_DATA_WIDTH = 32,
parameter ROM_NUM_WORDS = 512
) (
//input
input wire mgmt_clk,
input wire mgmt_reset,
//conduits
output wire [reconf_width-1:0] reconfig_to_pll,
input wire [reconf_width-1:0] reconfig_from_pll,
// user data (avalon-MM slave interface)
output wire [31:0] mgmt_readdata,
output wire mgmt_waitrequest,
input wire [5:0] mgmt_address,
input wire mgmt_read,
input wire mgmt_write,
input wire [31:0] mgmt_writedata,
//other
output wire mif_start_out,
output reg [ROM_ADDR_WIDTH-1:0] mif_base_addr
);
localparam mode_WR = 1'b0;
localparam mode_POLL = 1'b1;
localparam MODE_REG = 6'b000000;
localparam STATUS_REG = 6'b000001;
localparam START_REG = 6'b000010;
localparam N_REG = 6'b000011;
localparam M_REG = 6'b000100;
localparam C_COUNTERS_REG = 6'b000101;
localparam DPS_REG = 6'b000110;
localparam DSM_REG = 6'b000111;
localparam BWCTRL_REG = 6'b001000;
localparam CP_CURRENT_REG = 6'b001001;
localparam ANY_DPRIO = 6'b100000;
localparam CNT_BASE = 5'b001010;
localparam MIF_REG = 6'b011111;
//C Counters
localparam number_of_counters = 5'd18;
localparam CNT_0 = 1'd0, CNT_1 = 5'd1, CNT_2 = 5'd2,
CNT_3 = 5'd3, CNT_4 = 5'd4, CNT_5 = 5'd5,
CNT_6 = 5'd6, CNT_7 = 5'd7, CNT_8 = 5'd8,
CNT_9 = 5'd9, CNT_10 = 5'd10, CNT_11 = 5'd11,
CNT_12 = 5'd12, CNT_13 = 5'd13, CNT_14 = 5'd14,
CNT_15 = 5'd15, CNT_16 = 5'd16, CNT_17 = 5'd17;
//C counter addresses
localparam C_CNT_0_DIV_ADDR = 5'h00;
localparam C_CNT_0_DIV_ADDR_DPRIO_1 = 5'h11;
localparam C_CNT_0_3_BYPASS_EN_ADDR = 5'h15;
localparam C_CNT_0_3_ODD_DIV_EN_ADDR = 5'h17;
localparam C_CNT_4_17_BYPASS_EN_ADDR = 5'h14;
localparam C_CNT_4_17_ODD_DIV_EN_ADDR = 5'h16;
//N counter addresses
localparam N_CNT_DIV_ADDR = 5'h13;
localparam N_CNT_BYPASS_EN_ADDR = 5'h15;
localparam N_CNT_ODD_DIV_EN_ADDR = 5'h17;
//M counter addresses
localparam M_CNT_DIV_ADDR = 5'h12;
localparam M_CNT_BYPASS_EN_ADDR = 5'h15;
localparam M_CNT_ODD_DIV_EN_ADDR = 5'h17;
//DSM address
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_0 = 5'h18;
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_1 = 5'h19;
localparam DSM_K_READY_ADDR = 5'h17;
localparam DSM_K_DITHER_ADDR = 5'h17;
localparam DSM_OUT_SEL_ADDR = 6'h30;
//Other DSM params
localparam DSM_K_READY_BIT_INDEX = 4'd11;
//BWCTRL address
//Bit 0-3 of addr
localparam BWCTRL_ADDR = 6'h30;
//CP_CURRENT address
//Bit 0-2 of addr
localparam CP_CURRENT_ADDR = 6'h31;
localparam DPRIO_IDLE = 3'd0, ONE = 3'd1, TWO = 3'd2, THREE = 3'd3, FOUR = 3'd4,
FIVE = 3'd5, SIX = 3'd6, SEVEN = 3'd7, EIGHT = 4'd8, NINE = 4'd9, TEN = 4'd10,
ELEVEN = 4'd11, TWELVE = 4'd12, THIRTEEN = 4'd13, FOURTEEN = 4'd14, DPRIO_DONE = 4'd15;
localparam IDLE = 2'b00, WAIT_ON_LOCK = 2'b01, LOCKED = 2'b10;
wire clk;
wire reset;
wire gnd;
wire [5: 0] slave_address;
wire slave_read;
wire slave_write;
wire [31: 0] slave_writedata;
reg [31: 0] slave_readdata_d;
reg [31: 0] slave_readdata_q;
wire slave_waitrequest;
assign clk = mgmt_clk;
assign slave_address = mgmt_address;
assign slave_read = mgmt_read;
assign slave_write = mgmt_write;
assign slave_writedata = mgmt_writedata;
// Outputs
assign mgmt_readdata = slave_readdata_q;
assign mgmt_waitrequest = slave_waitrequest;
//internal signals
wire locked;
wire pll_start;
wire pll_start_valid;
reg status_read;
wire read_slave_mode_asserted;
wire pll_start_asserted;
reg [1:0] current_state;
reg [1:0] next_state;
reg slave_mode;
reg status;//0=busy, 1=ready
//user_mode_init user_mode_init_inst (clk, reset, dprio_mdio_dis, ser_shift_load);
//declaring the init wires. These will have 0 on them for 64 clk cycles
wire [ 5:0] init_dprio_address;
wire init_dprio_read;
wire [ 1:0] init_dprio_byteen;
wire init_dprio_write;
wire [15:0] init_dprio_writedata;
wire init_atpgmode;
wire init_mdio_dis;
wire init_scanen;
wire init_ser_shift_load;
wire dprio_init_done;
//DPRIO output signals after initialization is done
wire dprio_clk;
reg avmm_dprio_write;
reg avmm_dprio_read;
reg [5:0] avmm_dprio_address;
reg [15:0] avmm_dprio_writedata;
reg [1:0] avmm_dprio_byteen;
wire avmm_atpgmode;
wire avmm_mdio_dis;
wire avmm_scanen;
//Final output wires that are muxed between the init and avmm wires.
wire dprio_init_reset;
wire [5:0] dprio_address /*synthesis keep*/;
wire dprio_read/*synthesis keep*/;
wire [1:0] dprio_byteen/*synthesis keep*/;
wire dprio_write/*synthesis keep*/;
wire [15:0] dprio_writedata/*synthesis keep*/;
wire dprio_mdio_dis/*synthesis keep*/;
wire dprio_ser_shift_load/*synthesis keep*/;
wire dprio_atpgmode/*synthesis keep*/;
wire dprio_scanen/*synthesis keep*/;
//other PLL signals for dyn ph shift
wire phase_done/*synthesis keep*/;
wire phase_en/*synthesis keep*/;
wire up_dn/*synthesis keep*/;
wire [4:0] cnt_sel;
//DPRIO input signals
wire [15:0] dprio_readdata;
//internal logic signals
//storage registers for user sent data
reg dprio_temp_read_1;
reg dprio_temp_read_2;
reg dprio_start;
reg mif_start_assert;
reg dps_start_assert;
wire usr_valid_changes;
reg [3:0] dprio_cur_state;
reg [3:0] dprio_next_state;
reg [15:0] dprio_temp_m_n_c_readdata_1_d;
reg [15:0] dprio_temp_m_n_c_readdata_2_d;
reg [15:0] dprio_temp_m_n_c_readdata_1_q;
reg [15:0] dprio_temp_m_n_c_readdata_2_q;
reg dprio_write_done;
//C counters signals
reg [7:0] usr_c_cnt_lo;
reg [7:0] usr_c_cnt_hi;
reg usr_c_cnt_bypass_en;
reg usr_c_cnt_odd_duty_div_en;
reg [7:0] temp_c_cnt_lo [0:17];
reg [7:0] temp_c_cnt_hi [0:17];
reg temp_c_cnt_bypass_en [0:17];
reg temp_c_cnt_odd_duty_div_en [0:17];
reg any_c_cnt_changed;
reg all_c_cnt_done_q;
reg all_c_cnt_done_d;
reg [17:0] c_cnt_changed;
reg [17:0] c_cnt_done_d;
reg [17:0] c_cnt_done_q;
//N counter signals
reg [7:0] usr_n_cnt_lo;
reg [7:0] usr_n_cnt_hi;
reg usr_n_cnt_bypass_en;
reg usr_n_cnt_odd_duty_div_en;
reg n_cnt_changed;
reg n_cnt_done_d;
reg n_cnt_done_q;
//M counter signals
reg [7:0] usr_m_cnt_lo;
reg [7:0] usr_m_cnt_hi;
reg usr_m_cnt_bypass_en;
reg usr_m_cnt_odd_duty_div_en;
reg m_cnt_changed;
reg m_cnt_done_d;
reg m_cnt_done_q;
//dyn phase regs
reg [15:0] usr_num_shifts;
reg [4:0] usr_cnt_sel /*synthesis preserve*/;
reg usr_up_dn;
reg dps_changed;
wire dps_changed_valid;
wire dps_done;
//DSM Signals
reg [31:0] usr_k_value;
reg dsm_k_changed;
reg dsm_k_done_d;
reg dsm_k_done_q;
reg dsm_k_ready_false_done_d;
//BW signals
reg [3:0] usr_bwctrl_value;
reg bwctrl_changed;
reg bwctrl_done_d;
reg bwctrl_done_q;
//CP signals
reg [2:0] usr_cp_current_value;
reg cp_current_changed;
reg cp_current_done_d;
reg cp_current_done_q;
//Manual DPRIO signals
reg manual_dprio_done_q;
reg manual_dprio_done_d;
reg manual_dprio_changed;
reg [5:0] usr_dprio_address;
reg [15:0] usr_dprio_writedata_0;
reg usr_r_w;
//keeping track of which operation happened last
reg [5:0] operation_address;
// Address wires for all C_counter DPRIO registers
// These are outputs of LUTS, changing depending
// on whether PLL_0 or PLL_1 being used
//Fitter will tell if FPLL1 is being used
wire fpll_1;
// other
reg mif_reg_asserted;
// MAIN FSM
always @(posedge clk)
begin
if (reset)
begin
dprio_cur_state <= DPRIO_IDLE;
current_state <= IDLE;
end
else
begin
current_state <= next_state;
dprio_cur_state <= dprio_next_state;
end
end
always @(*)
begin
case(current_state)
IDLE:
begin
if (pll_start & !slave_waitrequest & usr_valid_changes)
next_state = WAIT_ON_LOCK;
else
next_state = IDLE;
end
WAIT_ON_LOCK:
begin
if (locked & dps_done & dprio_write_done) // received locked high from PLL
begin
if (slave_mode==mode_WR) //if the mode is waitrequest, then
// goto IDLE state directly
next_state = IDLE;
else
next_state = LOCKED; //otherwise go the locked state
end
else
next_state = WAIT_ON_LOCK;
end
LOCKED:
begin
if (status_read) // stay in LOCKED until user reads status
next_state = IDLE;
else
next_state = LOCKED;
end
default: next_state = 2'bxx;
endcase
end
// ask the pll to start reconfig
assign pll_start = (pll_start_asserted & (current_state==IDLE)) ;
assign pll_start_valid = (pll_start & (next_state==WAIT_ON_LOCK)) ;
// WRITE OPERATIONS
assign pll_start_asserted = slave_write & (slave_address == START_REG);
assign mif_start_out = pll_start & mif_reg_asserted;
//reading the mode register to determine what mode the slave will operate
//in.
always @(posedge clk)
begin
if (reset)
slave_mode <= mode_WR;
else if (slave_write & (slave_address == MODE_REG) & !slave_waitrequest)
slave_mode <= slave_writedata[0];
end
//record which values user wants to change.
//reading in the actual values that need to be reconfigged and sending
//them to the PLL
always @(posedge clk)
begin
if (reset)
begin
//reset all regs here
//BW signals reset
usr_bwctrl_value <= 0;
bwctrl_changed <= 0;
bwctrl_done_q <= 0;
//CP signals reset
usr_cp_current_value <= 0;
cp_current_changed <= 0;
cp_current_done_q <= 0;
//DSM signals reset
usr_k_value <= 0;
dsm_k_changed <= 0;
dsm_k_done_q <= 0;
//N counter signals reset
usr_n_cnt_lo <= 0;
usr_n_cnt_hi <= 0;
usr_n_cnt_bypass_en <= 0;
usr_n_cnt_odd_duty_div_en <= 0;
n_cnt_changed <= 0;
n_cnt_done_q <= 0;
//M counter signals reset
usr_m_cnt_lo <= 0;
usr_m_cnt_hi <= 0;
usr_m_cnt_bypass_en <= 0;
usr_m_cnt_odd_duty_div_en <= 0;
m_cnt_changed <= 0;
m_cnt_done_q <= 0;
//C counter signals reset
usr_c_cnt_lo <= 0;
usr_c_cnt_hi <= 0;
usr_c_cnt_bypass_en <= 0;
usr_c_cnt_odd_duty_div_en <= 0;
any_c_cnt_changed <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
//generic signals
dprio_start <= 0;
mif_start_assert <= 0;
dps_start_assert <= 0;
dprio_temp_m_n_c_readdata_1_q <= 0;
dprio_temp_m_n_c_readdata_2_q <= 0;
c_cnt_done_q <= 0;
//DPS signals
usr_up_dn <= 0;
usr_cnt_sel <= 0;
usr_num_shifts <= 0;
dps_changed <= 0;
//manual DPRIO signals
manual_dprio_changed <= 0;
usr_dprio_address <= 0;
usr_dprio_writedata_0 <= 0;
usr_r_w <= 0;
operation_address <= 0;
mif_reg_asserted <= 0;
mif_base_addr <= 0;
end
else
begin
if (dprio_temp_read_1)
begin
dprio_temp_m_n_c_readdata_1_q <= dprio_temp_m_n_c_readdata_1_d;
end
if (dprio_temp_read_2)
begin
dprio_temp_m_n_c_readdata_2_q <= dprio_temp_m_n_c_readdata_2_d;
end
if ((dps_done)) dps_changed <= 0;
if (dsm_k_done_d) dsm_k_done_q <= dsm_k_done_d;
if (n_cnt_done_d) n_cnt_done_q <= n_cnt_done_d;
if (m_cnt_done_d) m_cnt_done_q <= m_cnt_done_d;
if (all_c_cnt_done_d) all_c_cnt_done_q <= all_c_cnt_done_d;
if (c_cnt_done_d != 0) c_cnt_done_q <= c_cnt_done_q | c_cnt_done_d;
if (bwctrl_done_d) bwctrl_done_q <= bwctrl_done_d;
if (cp_current_done_d) cp_current_done_q <= cp_current_done_d;
if (manual_dprio_done_d) manual_dprio_done_q <= manual_dprio_done_d;
if (mif_start_out == 1'b1)
mif_start_assert <= 0; // Signaled MIF block to start, so deassert on next cycle
if (dps_done != 1'b1)
dps_start_assert <= 0; // DPS has started, so dessert its start signal on next cycle
if (dprio_next_state == ONE)
dprio_start <= 0;
if (dprio_write_done)
begin
bwctrl_done_q <= 0;
cp_current_done_q <= 0;
dsm_k_done_q <= 0;
dsm_k_done_q <= 0;
n_cnt_done_q <= 0;
m_cnt_done_q <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
dsm_k_changed <= 0;
n_cnt_changed <= 0;
m_cnt_changed <= 0;
any_c_cnt_changed <= 0;
bwctrl_changed <= 0;
cp_current_changed <= 0;
manual_dprio_changed <= 0;
manual_dprio_done_q <= 0;
if (dps_changed | dps_changed_valid | !dps_done )
begin
usr_cnt_sel <= usr_cnt_sel;
end
else
begin
usr_cnt_sel <= 0;
end
mif_reg_asserted <= 0;
end
else
begin
dsm_k_changed <= dsm_k_changed;
n_cnt_changed <= n_cnt_changed;
m_cnt_changed <= m_cnt_changed;
any_c_cnt_changed <= any_c_cnt_changed;
manual_dprio_changed <= manual_dprio_changed;
mif_reg_asserted <= mif_reg_asserted;
usr_cnt_sel <= usr_cnt_sel;
end
if(slave_write & !slave_waitrequest)
begin
case(slave_address)
//read in the values here from the user and act on them
DSM_REG:
begin
operation_address <= DSM_REG;
usr_k_value <= slave_writedata[31:0];
dsm_k_changed <= 1'b1;
dsm_k_done_q <= 0;
dprio_start <= 1'b1;
end
N_REG:
begin
operation_address <= N_REG;
usr_n_cnt_lo <= slave_writedata[7:0];
usr_n_cnt_hi <= slave_writedata[15:8];
usr_n_cnt_bypass_en <= slave_writedata[16];
usr_n_cnt_odd_duty_div_en <= slave_writedata[17];
n_cnt_changed <= 1'b1;
n_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
M_REG:
begin
operation_address <= M_REG;
usr_m_cnt_lo <= slave_writedata[7:0];
usr_m_cnt_hi <= slave_writedata[15:8];
usr_m_cnt_bypass_en <= slave_writedata[16];
usr_m_cnt_odd_duty_div_en <= slave_writedata[17];
m_cnt_changed <= 1'b1;
m_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
DPS_REG:
begin
operation_address <= DPS_REG;
usr_num_shifts <= slave_writedata[15:0];
usr_cnt_sel <= slave_writedata[20:16];
usr_up_dn <= slave_writedata[21];
dps_changed <= 1;
dps_start_assert <= 1;
end
C_COUNTERS_REG:
begin
operation_address <= C_COUNTERS_REG;
usr_c_cnt_lo <= slave_writedata[7:0];
usr_c_cnt_hi <= slave_writedata[15:8];
usr_c_cnt_bypass_en <= slave_writedata[16];
usr_c_cnt_odd_duty_div_en <= slave_writedata[17];
usr_cnt_sel <= slave_writedata[22:18];
any_c_cnt_changed <= 1'b1;
all_c_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
BWCTRL_REG:
begin
usr_bwctrl_value <= slave_writedata[3:0];
bwctrl_changed <= 1'b1;
bwctrl_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= BWCTRL_REG;
end
CP_CURRENT_REG:
begin
usr_cp_current_value <= slave_writedata[2:0];
cp_current_changed <= 1'b1;
cp_current_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= CP_CURRENT_REG;
end
ANY_DPRIO:
begin
operation_address <= ANY_DPRIO;
manual_dprio_changed <= 1'b1;
usr_dprio_address <= slave_writedata[5:0];
usr_dprio_writedata_0 <= slave_writedata[21:6];
usr_r_w <= slave_writedata[22];
manual_dprio_done_q <= 0;
dprio_start <= 1'b1;
end
MIF_REG:
begin
mif_reg_asserted <= 1'b1;
mif_base_addr <= slave_writedata[ROM_ADDR_WIDTH-1:0];
mif_start_assert <= 1'b1;
end
endcase
end
end
end
//C Counter assigning values to the 2-d array of values for each C counter
reg [4:0] j;
always @(posedge clk)
begin
if (reset)
begin
c_cnt_changed[17:0] <= 0;
for (j = 0; j < number_of_counters; j = j + 1'b1)
begin : c_cnt_reset
temp_c_cnt_bypass_en[j] <= 0;
temp_c_cnt_odd_duty_div_en[j] <= 0;
temp_c_cnt_lo[j][7:0] <= 0;
temp_c_cnt_hi[j][7:0] <= 0;
end
end
else
begin
if (dprio_write_done)
begin
c_cnt_changed <= 0;
end
if (any_c_cnt_changed && (operation_address == C_COUNTERS_REG))
begin
case (cnt_sel)
CNT_0:
begin
temp_c_cnt_lo [0] <= usr_c_cnt_lo;
temp_c_cnt_hi [0] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [0] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [0] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [0] <= 1'b1;
end
CNT_1:
begin
temp_c_cnt_lo [1] <= usr_c_cnt_lo;
temp_c_cnt_hi [1] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [1] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [1] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [1] <= 1'b1;
end
CNT_2:
begin
temp_c_cnt_lo [2] <= usr_c_cnt_lo;
temp_c_cnt_hi [2] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [2] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [2] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [2] <= 1'b1;
end
CNT_3:
begin
temp_c_cnt_lo [3] <= usr_c_cnt_lo;
temp_c_cnt_hi [3] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [3] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [3] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [3] <= 1'b1;
end
CNT_4:
begin
temp_c_cnt_lo [4] <= usr_c_cnt_lo;
temp_c_cnt_hi [4] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [4] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [4] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [4] <= 1'b1;
end
CNT_5:
begin
temp_c_cnt_lo [5] <= usr_c_cnt_lo;
temp_c_cnt_hi [5] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [5] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [5] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [5] <= 1'b1;
end
CNT_6:
begin
temp_c_cnt_lo [6] <= usr_c_cnt_lo;
temp_c_cnt_hi [6] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [6] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [6] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [6] <= 1'b1;
end
CNT_7:
begin
temp_c_cnt_lo [7] <= usr_c_cnt_lo;
temp_c_cnt_hi [7] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [7] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [7] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [7] <= 1'b1;
end
CNT_8:
begin
temp_c_cnt_lo [8] <= usr_c_cnt_lo;
temp_c_cnt_hi [8] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [8] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [8] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [8] <= 1'b1;
end
CNT_9:
begin
temp_c_cnt_lo [9] <= usr_c_cnt_lo;
temp_c_cnt_hi [9] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [9] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [9] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [9] <= 1'b1;
end
CNT_10:
begin
temp_c_cnt_lo [10] <= usr_c_cnt_lo;
temp_c_cnt_hi [10] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [10] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [10] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [10] <= 1'b1;
end
CNT_11:
begin
temp_c_cnt_lo [11] <= usr_c_cnt_lo;
temp_c_cnt_hi [11] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [11] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [11] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [11] <= 1'b1;
end
CNT_12:
begin
temp_c_cnt_lo [12] <= usr_c_cnt_lo;
temp_c_cnt_hi [12] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [12] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [12] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [12] <= 1'b1;
end
CNT_13:
begin
temp_c_cnt_lo [13] <= usr_c_cnt_lo;
temp_c_cnt_hi [13] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [13] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [13] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [13] <= 1'b1;
end
CNT_14:
begin
temp_c_cnt_lo [14] <= usr_c_cnt_lo;
temp_c_cnt_hi [14] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [14] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [14] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [14] <= 1'b1;
end
CNT_15:
begin
temp_c_cnt_lo [15] <= usr_c_cnt_lo;
temp_c_cnt_hi [15] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [15] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [15] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [15] <= 1'b1;
end
CNT_16:
begin
temp_c_cnt_lo [16] <= usr_c_cnt_lo;
temp_c_cnt_hi [16] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [16] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [16] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [16] <= 1'b1;
end
CNT_17:
begin
temp_c_cnt_lo [17] <= usr_c_cnt_lo;
temp_c_cnt_hi [17] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [17] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [17] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [17] <= 1'b1;
end
endcase
end
end
end
//logic to handle which writes the user indicated and wants to start.
assign usr_valid_changes =dsm_k_changed| any_c_cnt_changed |n_cnt_changed | m_cnt_changed | dps_changed_valid |manual_dprio_changed |cp_current_changed|bwctrl_changed;
//start the reconfig operations by writing to the DPRIO
reg break_loop;
reg [4:0] i;
always @(*)
begin
dprio_temp_read_1 = 0;
dprio_temp_read_2 = 0;
dprio_temp_m_n_c_readdata_1_d = 0;
dprio_temp_m_n_c_readdata_2_d = 0;
break_loop = 0;
dprio_next_state = DPRIO_IDLE;
avmm_dprio_write = 0;
avmm_dprio_read = 0;
avmm_dprio_address = 0;
avmm_dprio_writedata = 0;
avmm_dprio_byteen = 0;
dprio_write_done = 1;
manual_dprio_done_d = 0;
n_cnt_done_d = 0;
dsm_k_done_d = 0;
dsm_k_ready_false_done_d = 0;
m_cnt_done_d = 0;
c_cnt_done_d[17:0] = 0;
all_c_cnt_done_d = 0;
bwctrl_done_d = 0;
cp_current_done_d = 0;
i = 0;
// Deassert dprio_write_done so it doesn't reset mif_reg_asserted (toggled writes)
if (dprio_start | mif_start_assert)
dprio_write_done = 0;
if (current_state == WAIT_ON_LOCK)
begin
case (dprio_cur_state)
ONE:
begin
if (n_cnt_changed & !n_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = N_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_n_cnt_lo;
avmm_dprio_writedata[15:8] = usr_n_cnt_hi;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = M_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_m_cnt_lo;
avmm_dprio_writedata[15:8] = usr_m_cnt_hi;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_hilo
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
if (fpll_1) avmm_dprio_address = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - i;
else avmm_dprio_address = C_CNT_0_DIV_ADDR + i;
avmm_dprio_writedata[7:0] = temp_c_cnt_lo[i];
avmm_dprio_writedata[15:8] = temp_c_cnt_hi[i];
//To break from the loop, since only one counter
//is addressed at a time
break_loop = 1'b1;
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (cp_current_changed & !cp_current_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_write = usr_r_w;
avmm_dprio_address = usr_dprio_address;
avmm_dprio_writedata[15:0] = usr_dprio_writedata_0;
end
else dprio_next_state = DPRIO_IDLE;
end
TWO:
begin
//handle reading the two setting bits on n_cnt, then
//writing them back while preserving other bits.
//Issue two consecutive reads then wait; readLatency=3
dprio_write_done = 0;
dprio_next_state = THREE;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
//reading the K ready 16 bit word. Need to write 0 to it
//afterwards to indicate that K has not been done writing
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
dprio_next_state = FOUR;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
dprio_next_state = FOUR;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
dprio_next_state = FOUR;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
avmm_dprio_read = ~usr_r_w;
avmm_dprio_address = usr_dprio_address;
dprio_next_state = DPRIO_DONE;
end
else dprio_next_state = DPRIO_IDLE;
end
THREE:
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
dprio_next_state = FOUR;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
else dprio_next_state = DPRIO_IDLE;
end
FOUR:
begin
dprio_temp_read_1 = 1'b1;
dprio_write_done = 0;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
dprio_temp_m_n_c_readdata_1_d = dprio_readdata;
dprio_next_state = FIVE;
end
else dprio_next_state = DPRIO_IDLE;
end
FIVE:
begin
dprio_write_done = 0;
dprio_temp_read_2 = 1'b1;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
//this is where DSM ready value comes.
//Need to store in a register to be used later
dprio_temp_m_n_c_readdata_2_d = dprio_readdata;
dprio_next_state = SIX;
end
else dprio_next_state = DPRIO_IDLE;
end
SIX:
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = SEVEN;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_1_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_bypass_en;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_bypass_en;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_write = 0;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_write = 0;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_write = 0;
end
else dprio_next_state = DPRIO_IDLE;
end
SEVEN:
begin
dprio_write_done = 0;
dprio_next_state = EIGHT;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_odd_duty_div_en;
n_cnt_done_d = 1'b1;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_odd_duty_div_en;
m_cnt_done_d = 1'b1;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b0;
dsm_k_ready_false_done_d = 1'b1;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
avmm_dprio_writedata[3:0] = usr_bwctrl_value;
bwctrl_done_d = 1'b1;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
avmm_dprio_writedata[2:0] = usr_cp_current_value;
cp_current_done_d = 1'b1;
end
//if all C_cnt that were changed are done, then assert all_c_cnt_done
if (c_cnt_done_d == c_cnt_changed)
all_c_cnt_done_d = 1'b1;
if (n_cnt_changed & n_cnt_done_d)
dprio_next_state = DPRIO_DONE;
if (any_c_cnt_changed & !all_c_cnt_done_d & !all_c_cnt_done_q)
dprio_next_state = ONE;
else if (m_cnt_changed & !m_cnt_done_d & !m_cnt_done_q)
dprio_next_state = ONE;
else if (dsm_k_changed & !dsm_k_ready_false_done_d)
dprio_next_state = TWO;
else if (dsm_k_changed & !dsm_k_done_q)
dprio_next_state = EIGHT;
else if (bwctrl_changed & !bwctrl_done_d)
dprio_next_state = TWO;
else if (cp_current_changed & !cp_current_done_d)
dprio_next_state = TWO;
else
begin
dprio_next_state = DPRIO_DONE;
dprio_write_done = 1'b1;
end
end
//finish the rest of the DSM reads/writes
//writing k value, writing k_ready to 1.
EIGHT:
begin
dprio_write_done = 0;
dprio_next_state = NINE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_0;
avmm_dprio_writedata[15:0] = usr_k_value[15:0];
end
end
NINE:
begin
dprio_write_done = 0;
dprio_next_state = TEN;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_1;
avmm_dprio_writedata[15:0] = usr_k_value[31:16];
end
end
TEN:
begin
dprio_write_done = 0;
dprio_next_state = ONE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
//already have the readdata for DSM_K_READY_ADDR since we read it
//earlier. Just reuse here
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b1;
dsm_k_done_d = 1'b1;
end
end
DPRIO_DONE:
begin
dprio_write_done = 1'b1;
if (dprio_start) dprio_next_state = DPRIO_IDLE;
else dprio_next_state = DPRIO_DONE;
end
DPRIO_IDLE:
begin
if (dprio_start) dprio_next_state = ONE;
else dprio_next_state = DPRIO_IDLE;
end
default: dprio_next_state = 4'bxxxx;
endcase
end
end
//assert the waitreq signal according to the state of the slave
assign slave_waitrequest = (slave_mode==mode_WR) ? ((locked === 1'b1) ? (((current_state==WAIT_ON_LOCK) & !dprio_write_done) | !dps_done |reset|!dprio_init_done) : 1'b1) : 1'b0;
// Read operations
always @(*)
begin
status = 0;
if (slave_mode == mode_POLL)
//asserting status to 1 if the slave is done.
status = (current_state == LOCKED);
end
//************************************************************//
//************************************************************//
//******************** READ STATE MACHINE ********************//
//************************************************************//
//************************************************************//
reg [1:0] current_read_state;
reg [1:0] next_read_state;
reg [5:0] slave_address_int_d;
reg [5:0] slave_address_int_q;
reg dprio_read_1;
reg [5:0] dprio_address_1;
reg [1:0] dprio_byteen_1;
reg [4:0] usr_cnt_sel_1;
localparam READ = 2'b00, READ_WAIT = 2'b01, READ_IDLE = 2'b10;
always @(posedge clk)
begin
if (reset)
begin
current_read_state <= READ_IDLE;
slave_address_int_q <= 0;
slave_readdata_q <= 0;
end
else
begin
current_read_state <= next_read_state;
slave_address_int_q <= slave_address_int_d;
slave_readdata_q <= slave_readdata_d;
end
end
always @(*)
begin
dprio_read_1 = 0;
dprio_address_1 = 0;
dprio_byteen_1 = 0;
slave_address_int_d = 0;
slave_readdata_d = 0;
status_read = 0;
usr_cnt_sel_1 = 0;
case(current_read_state)
READ_IDLE:
begin
slave_address_int_d = 0;
next_read_state = READ_IDLE;
if ((current_state != WAIT_ON_LOCK) && slave_read)
begin
slave_address_int_d = slave_address;
if ((slave_address >= CNT_BASE) && (slave_address < CNT_BASE+18))
begin
next_read_state = READ_WAIT;
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
usr_cnt_sel_1 = (slave_address[4:0] - CNT_BASE);
if (fpll_1) dprio_address_1 = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - cnt_sel;
else dprio_address_1 = C_CNT_0_DIV_ADDR + cnt_sel;
end
else
begin
case (slave_address)
MODE_REG:
begin
next_read_state = READ_WAIT;
slave_readdata_d = slave_mode;
end
STATUS_REG:
begin
next_read_state = READ_WAIT;
status_read = 1'b1;
slave_readdata_d = status;
end
N_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = N_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
M_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = M_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
BWCTRL_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = BWCTRL_ADDR;
next_read_state = READ_WAIT;
end
CP_CURRENT_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = CP_CURRENT_ADDR;
next_read_state = READ_WAIT;
end
default : next_read_state = READ_IDLE;
endcase
end
end
else
next_read_state = READ_IDLE;
end
READ_WAIT:
begin
next_read_state = READ;
slave_address_int_d = slave_address_int_q;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
endcase
end
READ:
begin
next_read_state = READ_IDLE;
slave_address_int_d = slave_address_int_q;
slave_readdata_d = dprio_readdata;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
BWCTRL_REG:
begin
slave_readdata_d = dprio_readdata[3:0];
end
CP_CURRENT_REG:
begin
slave_readdata_d = dprio_readdata[2:0];
end
endcase
end
default: next_read_state = 2'bxx;
endcase
end
dyn_phase_shift dyn_phase_shift_inst (
.clk(clk),
.reset(reset),
.phase_done(phase_done),
.pll_start_valid(pll_start_valid),
.dps_changed(dps_changed),
.dps_changed_valid(dps_changed_valid),
.dprio_write_done(dprio_write_done),
.usr_num_shifts(usr_num_shifts),
.usr_cnt_sel(usr_cnt_sel|usr_cnt_sel_1),
.usr_up_dn(usr_up_dn),
.locked(locked),
.dps_done(dps_done),
.phase_en(phase_en),
.up_dn(up_dn),
.cnt_sel(cnt_sel));
defparam dyn_phase_shift_inst.device_family = device_family;
assign dprio_clk = clk;
self_reset self_reset_inst (mgmt_reset, clk, reset, dprio_init_reset);
dprio_mux dprio_mux_inst (
.init_dprio_address(init_dprio_address),
.init_dprio_read(init_dprio_read),
.init_dprio_byteen(init_dprio_byteen),
.init_dprio_write(init_dprio_write),
.init_dprio_writedata(init_dprio_writedata),
.init_atpgmode(init_atpgmode),
.init_mdio_dis(init_mdio_dis),
.init_scanen(init_scanen),
.init_ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done),
// Inputs from avmm master
.avmm_dprio_address(avmm_dprio_address | dprio_address_1),
.avmm_dprio_read(avmm_dprio_read | dprio_read_1),
.avmm_dprio_byteen(avmm_dprio_byteen | dprio_byteen_1),
.avmm_dprio_write(avmm_dprio_write),
.avmm_dprio_writedata(avmm_dprio_writedata),
.avmm_atpgmode(avmm_atpgmode),
.avmm_mdio_dis(avmm_mdio_dis),
.avmm_scanen(avmm_scanen),
// Outputs to fpll
.dprio_address(dprio_address),
.dprio_read(dprio_read),
.dprio_byteen(dprio_byteen),
.dprio_write(dprio_write),
.dprio_writedata(dprio_writedata),
.atpgmode(dprio_atpgmode),
.mdio_dis(dprio_mdio_dis),
.scanen(dprio_scanen),
.ser_shift_load(dprio_ser_shift_load)
);
fpll_dprio_init fpll_dprio_init_inst (
.clk(clk),
.reset_n(~reset),
.locked(locked),
//outputs
.dprio_address(init_dprio_address),
.dprio_read(init_dprio_read),
.dprio_byteen(init_dprio_byteen),
.dprio_write(init_dprio_write),
.dprio_writedata(init_dprio_writedata),
.atpgmode(init_atpgmode),
.mdio_dis(init_mdio_dis),
.scanen(init_scanen),
.ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done));
//address luts, to be reconfigged by the Fitter
//FPLL_1 or 0 address lut
generic_lcell_comb lcell_fpll_0_1 (
.dataa(1'b0),
.combout (fpll_1));
defparam lcell_fpll_0_1.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_fpll_0_1.dont_touch = "on";
defparam lcell_fpll_0_1.family = device_family;
wire dprio_read_combout;
generic_lcell_comb lcell_dprio_read (
.dataa(fpll_1),
.datab(dprio_read),
.datac(1'b0),
.datad(1'b0),
.datae(1'b0),
.dataf(1'b0),
.combout (dprio_read_combout));
defparam lcell_dprio_read.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_dprio_read.dont_touch = "on";
defparam lcell_dprio_read.family = device_family;
//assign reconfig_to_pll signals
assign reconfig_to_pll[0] = dprio_clk;
assign reconfig_to_pll[1] = ~dprio_init_reset;
assign reconfig_to_pll[2] = dprio_write;
assign reconfig_to_pll[3] = dprio_read_combout;
assign reconfig_to_pll[9:4] = dprio_address;
assign reconfig_to_pll[25:10] = dprio_writedata;
assign reconfig_to_pll[27:26] = dprio_byteen;
assign reconfig_to_pll[28] = dprio_ser_shift_load;
assign reconfig_to_pll[29] = dprio_mdio_dis;
assign reconfig_to_pll[30] = phase_en;
assign reconfig_to_pll[31] = up_dn;
assign reconfig_to_pll[36:32] = cnt_sel;
assign reconfig_to_pll[37] = dprio_scanen;
assign reconfig_to_pll[38] = dprio_atpgmode;
//assign reconfig_to_pll[40:37] = clken;
assign reconfig_to_pll[63:39] = 0;
//assign reconfig_from_pll signals
assign dprio_readdata = reconfig_from_pll [15:0];
assign locked = reconfig_from_pll [16];
assign phase_done = reconfig_from_pll [17];
endmodule
module self_reset (input wire mgmt_reset, input wire clk, output wire reset, output wire init_reset);
localparam RESET_COUNTER_VALUE = 3'd2;
localparam INITIAL_WAIT_VALUE = 9'd340;
reg [9:0]counter;
reg local_reset;
reg usr_mode_init_wait;
initial
begin
local_reset = 1'b1;
counter = 0;
usr_mode_init_wait = 0;
end
always @(posedge clk)
begin
if (mgmt_reset)
begin
counter <= 0;
end
else
begin
if (!usr_mode_init_wait)
begin
if (counter == INITIAL_WAIT_VALUE)
begin
local_reset <= 0;
usr_mode_init_wait <= 1'b1;
counter <= 0;
end
else
begin
counter <= counter + 1'b1;
end
end
else
begin
if (counter == RESET_COUNTER_VALUE)
local_reset <= 0;
else
counter <= counter + 1'b1;
end
end
end
assign reset = mgmt_reset | local_reset;
assign init_reset = local_reset;
endmodule
module dprio_mux (
// Inputs from init block
input [ 5:0] init_dprio_address,
input init_dprio_read,
input [ 1:0] init_dprio_byteen,
input init_dprio_write,
input [15:0] init_dprio_writedata,
input init_atpgmode,
input init_mdio_dis,
input init_scanen,
input init_ser_shift_load,
input dprio_init_done,
// Inputs from avmm master
input [ 5:0] avmm_dprio_address,
input avmm_dprio_read,
input [ 1:0] avmm_dprio_byteen,
input avmm_dprio_write,
input [15:0] avmm_dprio_writedata,
input avmm_atpgmode,
input avmm_mdio_dis,
input avmm_scanen,
input avmm_ser_shift_load,
// Outputs to fpll
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output atpgmode,
output mdio_dis,
output scanen,
output ser_shift_load
);
assign dprio_address = dprio_init_done ? avmm_dprio_address : init_dprio_address;
assign dprio_read = dprio_init_done ? avmm_dprio_read : init_dprio_read;
assign dprio_byteen = dprio_init_done ? avmm_dprio_byteen : init_dprio_byteen;
assign dprio_write = dprio_init_done ? avmm_dprio_write : init_dprio_write;
assign dprio_writedata = dprio_init_done ? avmm_dprio_writedata : init_dprio_writedata;
assign atpgmode = init_atpgmode;
assign scanen = init_scanen;
assign mdio_dis = init_mdio_dis;
assign ser_shift_load = init_ser_shift_load ;
endmodule
module fpll_dprio_init (
input clk,
input reset_n,
input locked,
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output reg atpgmode,
output reg mdio_dis,
output reg scanen,
output reg ser_shift_load,
output reg dprio_init_done
);
reg [1:0] rst_n = 2'b00;
reg [6:0] count = 7'd0;
reg init_done_forever;
// Internal versions of control signals
wire int_mdio_dis;
wire int_ser_shift_load;
wire int_dprio_init_done;
wire int_atpgmode/*synthesis keep*/;
wire int_scanen/*synthesis keep*/;
assign dprio_address = count[6] ? 5'b0 : count[5:0] ;
assign dprio_byteen = 2'b11; // always enabled
assign dprio_write = ~count[6] & reset_n ; // write for first 64 cycles
assign dprio_read = 1'b0;
assign dprio_writedata = 16'd0;
assign int_ser_shift_load = count[6] ? |count[2:1] : 1'b1;
assign int_mdio_dis = count[6] ? ~count[2] : 1'b1;
assign int_dprio_init_done = ~init_done_forever ? (count[6] ? &count[2:0] : 1'b0)
: 1'b1;
assign int_atpgmode = 0;
assign int_scanen = 0;
initial begin
count = 7'd0;
init_done_forever = 0;
mdio_dis = 1'b1;
ser_shift_load = 1'b1;
dprio_init_done = 1'b0;
scanen = 1'b0;
atpgmode = 1'b0;
end
// reset synch.
always @(posedge clk or negedge reset_n)
if(!reset_n) rst_n <= 2'b00;
else rst_n <= {rst_n[0],1'b1};
// counter
always @(posedge clk)
begin
if (!rst_n[1])
init_done_forever <= 1'b0;
else
begin
if (count[6] && &count[1:0])
init_done_forever <= 1'b1;
end
end
always @(posedge clk or negedge rst_n[1])
begin
if(!rst_n[1])
begin
count <= 7'd0;
end
else if(~int_dprio_init_done)
begin
count <= count + 7'd1;
end
else
begin
count <= count;
end
end
// outputs
always @(posedge clk) begin
mdio_dis <= int_mdio_dis;
ser_shift_load <= int_ser_shift_load;
dprio_init_done <= int_dprio_init_done;
atpgmode <= int_atpgmode;
scanen <= int_scanen;
end
endmodule
module dyn_phase_shift
#(
parameter device_family = "Stratix V"
) (
input wire clk,
input wire reset,
input wire phase_done,
input wire pll_start_valid,
input wire dps_changed,
input wire dprio_write_done,
input wire [15:0] usr_num_shifts,
input wire [4:0] usr_cnt_sel,
input wire usr_up_dn,
input wire locked,
//output
output wire dps_done,
output reg phase_en,
output wire up_dn,
output wire dps_changed_valid,
output wire [4:0] cnt_sel);
reg first_phase_shift_d;
reg first_phase_shift_q;
reg [15:0] phase_en_counter;
reg [3:0] dps_current_state;
reg [3:0] dps_next_state;
localparam DPS_START = 4'd0, DPS_WAIT_PHASE_DONE = 4'd1, DPS_DONE = 4'd2, DPS_WAIT_PHASE_EN = 4'd3, DPS_WAIT_DPRIO_WRITING = 4'd4, DPS_CHANGED = 4'd5;
localparam PHASE_EN_WAIT_COUNTER = 5'd1;
reg [15:0] shifts_done_counter;
reg phase_done_final;
wire gnd /*synthesis keep*/;
//fsm
//always block controlling the state regs
always @(posedge clk)
begin
if (reset)
begin
dps_current_state <= DPS_DONE;
end
else
begin
dps_current_state <= dps_next_state;
end
end
//the combinational part. assigning the next state
//this turns on the phase_done_final signal when phase_done does this:
//_____ ______
// |______|
always @(*)
begin
phase_done_final = 0;
first_phase_shift_d = 0;
phase_en = 0;
dps_next_state = DPS_DONE;
case (dps_current_state)
DPS_START:
begin
phase_en = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
DPS_WAIT_PHASE_EN:
begin
phase_en = 1'b1;
if (first_phase_shift_q)
begin
first_phase_shift_d = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
else
begin
if (phase_en_counter == PHASE_EN_WAIT_COUNTER)
dps_next_state = DPS_WAIT_PHASE_DONE;
else dps_next_state = DPS_WAIT_PHASE_EN;
end
end
DPS_WAIT_PHASE_DONE:
begin
if (!phase_done | !locked)
begin
dps_next_state = DPS_WAIT_PHASE_DONE;
end
else
begin
if ((usr_num_shifts != shifts_done_counter) & (usr_num_shifts != 0))
begin
dps_next_state = DPS_START;
phase_done_final = 1'b1;
end
else
begin
dps_next_state = DPS_DONE;
end
end
end
DPS_DONE:
begin
phase_done_final = 0;
if (dps_changed)
dps_next_state = DPS_CHANGED;
else dps_next_state = DPS_DONE;
end
DPS_CHANGED:
begin
if (pll_start_valid)
dps_next_state = DPS_WAIT_DPRIO_WRITING;
else
dps_next_state = DPS_CHANGED;
end
DPS_WAIT_DPRIO_WRITING:
begin
if (dprio_write_done)
dps_next_state = DPS_START;
else
dps_next_state = DPS_WAIT_DPRIO_WRITING;
end
default: dps_next_state = 4'bxxxx;
endcase
end
always @(posedge clk)
begin
if (dps_current_state == DPS_WAIT_PHASE_DONE)
phase_en_counter <= 0;
else if (dps_current_state == DPS_WAIT_PHASE_EN)
phase_en_counter <= phase_en_counter + 1'b1;
if (reset)
begin
phase_en_counter <= 0;
shifts_done_counter <= 1'b1;
first_phase_shift_q <= 1;
end
else
begin
if (first_phase_shift_d)
first_phase_shift_q <= 0;
if (dps_done)
begin
shifts_done_counter <= 1'b1;
end
else
begin
if (phase_done_final & (dps_next_state!= DPS_DONE))
shifts_done_counter <= shifts_done_counter + 1'b1;
else
shifts_done_counter <= shifts_done_counter;
end
end
end
assign dps_changed_valid = (dps_current_state == DPS_CHANGED);
assign dps_done =(dps_current_state == DPS_DONE) | (dps_current_state == DPS_CHANGED);
assign up_dn = usr_up_dn;
assign gnd = 1'b0;
//cnt select luts (5)
generic_lcell_comb lcell_cnt_sel_0 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[0]));
defparam lcell_cnt_sel_0.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_cnt_sel_0.dont_touch = "on";
defparam lcell_cnt_sel_0.family = device_family;
generic_lcell_comb lcell_cnt_sel_1 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[1]));
defparam lcell_cnt_sel_1.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_cnt_sel_1.dont_touch = "on";
defparam lcell_cnt_sel_1.family = device_family;
generic_lcell_comb lcell_cnt_sel_2 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[2]));
defparam lcell_cnt_sel_2.lut_mask = 64'hF0F0F0F0F0F0F0F0;
defparam lcell_cnt_sel_2.dont_touch = "on";
defparam lcell_cnt_sel_2.family = device_family;
generic_lcell_comb lcell_cnt_sel_3 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[3]));
defparam lcell_cnt_sel_3.lut_mask = 64'hFF00FF00FF00FF00;
defparam lcell_cnt_sel_3.dont_touch = "on";
defparam lcell_cnt_sel_3.family = device_family;
generic_lcell_comb lcell_cnt_sel_4 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[4]));
defparam lcell_cnt_sel_4.lut_mask = 64'hFFFF0000FFFF0000;
defparam lcell_cnt_sel_4.dont_touch = "on";
defparam lcell_cnt_sel_4.family = device_family;
endmodule
module generic_lcell_comb
#(
//parameter
parameter family = "Stratix V",
parameter lut_mask = 64'hAAAAAAAAAAAAAAAA,
parameter dont_touch = "on"
) (
input dataa,
input datab,
input datac,
input datad,
input datae,
input dataf,
output combout
);
generate
if (family == "Stratix V")
begin
stratixv_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V")
begin
arriav_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V GZ")
begin
arriavgz_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Cyclone V")
begin
cyclonev_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
endgenerate
endmodule
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
`timescale 1ps/1ps
module altera_pll_reconfig_core
#(
parameter reconf_width = 64,
parameter device_family = "Stratix V",
// MIF Streaming parameters
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter ROM_ADDR_WIDTH = 9,
parameter ROM_DATA_WIDTH = 32,
parameter ROM_NUM_WORDS = 512
) (
//input
input wire mgmt_clk,
input wire mgmt_reset,
//conduits
output wire [reconf_width-1:0] reconfig_to_pll,
input wire [reconf_width-1:0] reconfig_from_pll,
// user data (avalon-MM slave interface)
output wire [31:0] mgmt_readdata,
output wire mgmt_waitrequest,
input wire [5:0] mgmt_address,
input wire mgmt_read,
input wire mgmt_write,
input wire [31:0] mgmt_writedata,
//other
output wire mif_start_out,
output reg [ROM_ADDR_WIDTH-1:0] mif_base_addr
);
localparam mode_WR = 1'b0;
localparam mode_POLL = 1'b1;
localparam MODE_REG = 6'b000000;
localparam STATUS_REG = 6'b000001;
localparam START_REG = 6'b000010;
localparam N_REG = 6'b000011;
localparam M_REG = 6'b000100;
localparam C_COUNTERS_REG = 6'b000101;
localparam DPS_REG = 6'b000110;
localparam DSM_REG = 6'b000111;
localparam BWCTRL_REG = 6'b001000;
localparam CP_CURRENT_REG = 6'b001001;
localparam ANY_DPRIO = 6'b100000;
localparam CNT_BASE = 5'b001010;
localparam MIF_REG = 6'b011111;
//C Counters
localparam number_of_counters = 5'd18;
localparam CNT_0 = 1'd0, CNT_1 = 5'd1, CNT_2 = 5'd2,
CNT_3 = 5'd3, CNT_4 = 5'd4, CNT_5 = 5'd5,
CNT_6 = 5'd6, CNT_7 = 5'd7, CNT_8 = 5'd8,
CNT_9 = 5'd9, CNT_10 = 5'd10, CNT_11 = 5'd11,
CNT_12 = 5'd12, CNT_13 = 5'd13, CNT_14 = 5'd14,
CNT_15 = 5'd15, CNT_16 = 5'd16, CNT_17 = 5'd17;
//C counter addresses
localparam C_CNT_0_DIV_ADDR = 5'h00;
localparam C_CNT_0_DIV_ADDR_DPRIO_1 = 5'h11;
localparam C_CNT_0_3_BYPASS_EN_ADDR = 5'h15;
localparam C_CNT_0_3_ODD_DIV_EN_ADDR = 5'h17;
localparam C_CNT_4_17_BYPASS_EN_ADDR = 5'h14;
localparam C_CNT_4_17_ODD_DIV_EN_ADDR = 5'h16;
//N counter addresses
localparam N_CNT_DIV_ADDR = 5'h13;
localparam N_CNT_BYPASS_EN_ADDR = 5'h15;
localparam N_CNT_ODD_DIV_EN_ADDR = 5'h17;
//M counter addresses
localparam M_CNT_DIV_ADDR = 5'h12;
localparam M_CNT_BYPASS_EN_ADDR = 5'h15;
localparam M_CNT_ODD_DIV_EN_ADDR = 5'h17;
//DSM address
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_0 = 5'h18;
localparam DSM_K_FRACTIONAL_DIVISION_ADDR_1 = 5'h19;
localparam DSM_K_READY_ADDR = 5'h17;
localparam DSM_K_DITHER_ADDR = 5'h17;
localparam DSM_OUT_SEL_ADDR = 6'h30;
//Other DSM params
localparam DSM_K_READY_BIT_INDEX = 4'd11;
//BWCTRL address
//Bit 0-3 of addr
localparam BWCTRL_ADDR = 6'h30;
//CP_CURRENT address
//Bit 0-2 of addr
localparam CP_CURRENT_ADDR = 6'h31;
localparam DPRIO_IDLE = 3'd0, ONE = 3'd1, TWO = 3'd2, THREE = 3'd3, FOUR = 3'd4,
FIVE = 3'd5, SIX = 3'd6, SEVEN = 3'd7, EIGHT = 4'd8, NINE = 4'd9, TEN = 4'd10,
ELEVEN = 4'd11, TWELVE = 4'd12, THIRTEEN = 4'd13, FOURTEEN = 4'd14, DPRIO_DONE = 4'd15;
localparam IDLE = 2'b00, WAIT_ON_LOCK = 2'b01, LOCKED = 2'b10;
wire clk;
wire reset;
wire gnd;
wire [5: 0] slave_address;
wire slave_read;
wire slave_write;
wire [31: 0] slave_writedata;
reg [31: 0] slave_readdata_d;
reg [31: 0] slave_readdata_q;
wire slave_waitrequest;
assign clk = mgmt_clk;
assign slave_address = mgmt_address;
assign slave_read = mgmt_read;
assign slave_write = mgmt_write;
assign slave_writedata = mgmt_writedata;
// Outputs
assign mgmt_readdata = slave_readdata_q;
assign mgmt_waitrequest = slave_waitrequest;
//internal signals
wire locked;
wire pll_start;
wire pll_start_valid;
reg status_read;
wire read_slave_mode_asserted;
wire pll_start_asserted;
reg [1:0] current_state;
reg [1:0] next_state;
reg slave_mode;
reg status;//0=busy, 1=ready
//user_mode_init user_mode_init_inst (clk, reset, dprio_mdio_dis, ser_shift_load);
//declaring the init wires. These will have 0 on them for 64 clk cycles
wire [ 5:0] init_dprio_address;
wire init_dprio_read;
wire [ 1:0] init_dprio_byteen;
wire init_dprio_write;
wire [15:0] init_dprio_writedata;
wire init_atpgmode;
wire init_mdio_dis;
wire init_scanen;
wire init_ser_shift_load;
wire dprio_init_done;
//DPRIO output signals after initialization is done
wire dprio_clk;
reg avmm_dprio_write;
reg avmm_dprio_read;
reg [5:0] avmm_dprio_address;
reg [15:0] avmm_dprio_writedata;
reg [1:0] avmm_dprio_byteen;
wire avmm_atpgmode;
wire avmm_mdio_dis;
wire avmm_scanen;
//Final output wires that are muxed between the init and avmm wires.
wire dprio_init_reset;
wire [5:0] dprio_address /*synthesis keep*/;
wire dprio_read/*synthesis keep*/;
wire [1:0] dprio_byteen/*synthesis keep*/;
wire dprio_write/*synthesis keep*/;
wire [15:0] dprio_writedata/*synthesis keep*/;
wire dprio_mdio_dis/*synthesis keep*/;
wire dprio_ser_shift_load/*synthesis keep*/;
wire dprio_atpgmode/*synthesis keep*/;
wire dprio_scanen/*synthesis keep*/;
//other PLL signals for dyn ph shift
wire phase_done/*synthesis keep*/;
wire phase_en/*synthesis keep*/;
wire up_dn/*synthesis keep*/;
wire [4:0] cnt_sel;
//DPRIO input signals
wire [15:0] dprio_readdata;
//internal logic signals
//storage registers for user sent data
reg dprio_temp_read_1;
reg dprio_temp_read_2;
reg dprio_start;
reg mif_start_assert;
reg dps_start_assert;
wire usr_valid_changes;
reg [3:0] dprio_cur_state;
reg [3:0] dprio_next_state;
reg [15:0] dprio_temp_m_n_c_readdata_1_d;
reg [15:0] dprio_temp_m_n_c_readdata_2_d;
reg [15:0] dprio_temp_m_n_c_readdata_1_q;
reg [15:0] dprio_temp_m_n_c_readdata_2_q;
reg dprio_write_done;
//C counters signals
reg [7:0] usr_c_cnt_lo;
reg [7:0] usr_c_cnt_hi;
reg usr_c_cnt_bypass_en;
reg usr_c_cnt_odd_duty_div_en;
reg [7:0] temp_c_cnt_lo [0:17];
reg [7:0] temp_c_cnt_hi [0:17];
reg temp_c_cnt_bypass_en [0:17];
reg temp_c_cnt_odd_duty_div_en [0:17];
reg any_c_cnt_changed;
reg all_c_cnt_done_q;
reg all_c_cnt_done_d;
reg [17:0] c_cnt_changed;
reg [17:0] c_cnt_done_d;
reg [17:0] c_cnt_done_q;
//N counter signals
reg [7:0] usr_n_cnt_lo;
reg [7:0] usr_n_cnt_hi;
reg usr_n_cnt_bypass_en;
reg usr_n_cnt_odd_duty_div_en;
reg n_cnt_changed;
reg n_cnt_done_d;
reg n_cnt_done_q;
//M counter signals
reg [7:0] usr_m_cnt_lo;
reg [7:0] usr_m_cnt_hi;
reg usr_m_cnt_bypass_en;
reg usr_m_cnt_odd_duty_div_en;
reg m_cnt_changed;
reg m_cnt_done_d;
reg m_cnt_done_q;
//dyn phase regs
reg [15:0] usr_num_shifts;
reg [4:0] usr_cnt_sel /*synthesis preserve*/;
reg usr_up_dn;
reg dps_changed;
wire dps_changed_valid;
wire dps_done;
//DSM Signals
reg [31:0] usr_k_value;
reg dsm_k_changed;
reg dsm_k_done_d;
reg dsm_k_done_q;
reg dsm_k_ready_false_done_d;
//BW signals
reg [3:0] usr_bwctrl_value;
reg bwctrl_changed;
reg bwctrl_done_d;
reg bwctrl_done_q;
//CP signals
reg [2:0] usr_cp_current_value;
reg cp_current_changed;
reg cp_current_done_d;
reg cp_current_done_q;
//Manual DPRIO signals
reg manual_dprio_done_q;
reg manual_dprio_done_d;
reg manual_dprio_changed;
reg [5:0] usr_dprio_address;
reg [15:0] usr_dprio_writedata_0;
reg usr_r_w;
//keeping track of which operation happened last
reg [5:0] operation_address;
// Address wires for all C_counter DPRIO registers
// These are outputs of LUTS, changing depending
// on whether PLL_0 or PLL_1 being used
//Fitter will tell if FPLL1 is being used
wire fpll_1;
// other
reg mif_reg_asserted;
// MAIN FSM
always @(posedge clk)
begin
if (reset)
begin
dprio_cur_state <= DPRIO_IDLE;
current_state <= IDLE;
end
else
begin
current_state <= next_state;
dprio_cur_state <= dprio_next_state;
end
end
always @(*)
begin
case(current_state)
IDLE:
begin
if (pll_start & !slave_waitrequest & usr_valid_changes)
next_state = WAIT_ON_LOCK;
else
next_state = IDLE;
end
WAIT_ON_LOCK:
begin
if (locked & dps_done & dprio_write_done) // received locked high from PLL
begin
if (slave_mode==mode_WR) //if the mode is waitrequest, then
// goto IDLE state directly
next_state = IDLE;
else
next_state = LOCKED; //otherwise go the locked state
end
else
next_state = WAIT_ON_LOCK;
end
LOCKED:
begin
if (status_read) // stay in LOCKED until user reads status
next_state = IDLE;
else
next_state = LOCKED;
end
default: next_state = 2'bxx;
endcase
end
// ask the pll to start reconfig
assign pll_start = (pll_start_asserted & (current_state==IDLE)) ;
assign pll_start_valid = (pll_start & (next_state==WAIT_ON_LOCK)) ;
// WRITE OPERATIONS
assign pll_start_asserted = slave_write & (slave_address == START_REG);
assign mif_start_out = pll_start & mif_reg_asserted;
//reading the mode register to determine what mode the slave will operate
//in.
always @(posedge clk)
begin
if (reset)
slave_mode <= mode_WR;
else if (slave_write & (slave_address == MODE_REG) & !slave_waitrequest)
slave_mode <= slave_writedata[0];
end
//record which values user wants to change.
//reading in the actual values that need to be reconfigged and sending
//them to the PLL
always @(posedge clk)
begin
if (reset)
begin
//reset all regs here
//BW signals reset
usr_bwctrl_value <= 0;
bwctrl_changed <= 0;
bwctrl_done_q <= 0;
//CP signals reset
usr_cp_current_value <= 0;
cp_current_changed <= 0;
cp_current_done_q <= 0;
//DSM signals reset
usr_k_value <= 0;
dsm_k_changed <= 0;
dsm_k_done_q <= 0;
//N counter signals reset
usr_n_cnt_lo <= 0;
usr_n_cnt_hi <= 0;
usr_n_cnt_bypass_en <= 0;
usr_n_cnt_odd_duty_div_en <= 0;
n_cnt_changed <= 0;
n_cnt_done_q <= 0;
//M counter signals reset
usr_m_cnt_lo <= 0;
usr_m_cnt_hi <= 0;
usr_m_cnt_bypass_en <= 0;
usr_m_cnt_odd_duty_div_en <= 0;
m_cnt_changed <= 0;
m_cnt_done_q <= 0;
//C counter signals reset
usr_c_cnt_lo <= 0;
usr_c_cnt_hi <= 0;
usr_c_cnt_bypass_en <= 0;
usr_c_cnt_odd_duty_div_en <= 0;
any_c_cnt_changed <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
//generic signals
dprio_start <= 0;
mif_start_assert <= 0;
dps_start_assert <= 0;
dprio_temp_m_n_c_readdata_1_q <= 0;
dprio_temp_m_n_c_readdata_2_q <= 0;
c_cnt_done_q <= 0;
//DPS signals
usr_up_dn <= 0;
usr_cnt_sel <= 0;
usr_num_shifts <= 0;
dps_changed <= 0;
//manual DPRIO signals
manual_dprio_changed <= 0;
usr_dprio_address <= 0;
usr_dprio_writedata_0 <= 0;
usr_r_w <= 0;
operation_address <= 0;
mif_reg_asserted <= 0;
mif_base_addr <= 0;
end
else
begin
if (dprio_temp_read_1)
begin
dprio_temp_m_n_c_readdata_1_q <= dprio_temp_m_n_c_readdata_1_d;
end
if (dprio_temp_read_2)
begin
dprio_temp_m_n_c_readdata_2_q <= dprio_temp_m_n_c_readdata_2_d;
end
if ((dps_done)) dps_changed <= 0;
if (dsm_k_done_d) dsm_k_done_q <= dsm_k_done_d;
if (n_cnt_done_d) n_cnt_done_q <= n_cnt_done_d;
if (m_cnt_done_d) m_cnt_done_q <= m_cnt_done_d;
if (all_c_cnt_done_d) all_c_cnt_done_q <= all_c_cnt_done_d;
if (c_cnt_done_d != 0) c_cnt_done_q <= c_cnt_done_q | c_cnt_done_d;
if (bwctrl_done_d) bwctrl_done_q <= bwctrl_done_d;
if (cp_current_done_d) cp_current_done_q <= cp_current_done_d;
if (manual_dprio_done_d) manual_dprio_done_q <= manual_dprio_done_d;
if (mif_start_out == 1'b1)
mif_start_assert <= 0; // Signaled MIF block to start, so deassert on next cycle
if (dps_done != 1'b1)
dps_start_assert <= 0; // DPS has started, so dessert its start signal on next cycle
if (dprio_next_state == ONE)
dprio_start <= 0;
if (dprio_write_done)
begin
bwctrl_done_q <= 0;
cp_current_done_q <= 0;
dsm_k_done_q <= 0;
dsm_k_done_q <= 0;
n_cnt_done_q <= 0;
m_cnt_done_q <= 0;
all_c_cnt_done_q <= 0;
c_cnt_done_q <= 0;
dsm_k_changed <= 0;
n_cnt_changed <= 0;
m_cnt_changed <= 0;
any_c_cnt_changed <= 0;
bwctrl_changed <= 0;
cp_current_changed <= 0;
manual_dprio_changed <= 0;
manual_dprio_done_q <= 0;
if (dps_changed | dps_changed_valid | !dps_done )
begin
usr_cnt_sel <= usr_cnt_sel;
end
else
begin
usr_cnt_sel <= 0;
end
mif_reg_asserted <= 0;
end
else
begin
dsm_k_changed <= dsm_k_changed;
n_cnt_changed <= n_cnt_changed;
m_cnt_changed <= m_cnt_changed;
any_c_cnt_changed <= any_c_cnt_changed;
manual_dprio_changed <= manual_dprio_changed;
mif_reg_asserted <= mif_reg_asserted;
usr_cnt_sel <= usr_cnt_sel;
end
if(slave_write & !slave_waitrequest)
begin
case(slave_address)
//read in the values here from the user and act on them
DSM_REG:
begin
operation_address <= DSM_REG;
usr_k_value <= slave_writedata[31:0];
dsm_k_changed <= 1'b1;
dsm_k_done_q <= 0;
dprio_start <= 1'b1;
end
N_REG:
begin
operation_address <= N_REG;
usr_n_cnt_lo <= slave_writedata[7:0];
usr_n_cnt_hi <= slave_writedata[15:8];
usr_n_cnt_bypass_en <= slave_writedata[16];
usr_n_cnt_odd_duty_div_en <= slave_writedata[17];
n_cnt_changed <= 1'b1;
n_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
M_REG:
begin
operation_address <= M_REG;
usr_m_cnt_lo <= slave_writedata[7:0];
usr_m_cnt_hi <= slave_writedata[15:8];
usr_m_cnt_bypass_en <= slave_writedata[16];
usr_m_cnt_odd_duty_div_en <= slave_writedata[17];
m_cnt_changed <= 1'b1;
m_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
DPS_REG:
begin
operation_address <= DPS_REG;
usr_num_shifts <= slave_writedata[15:0];
usr_cnt_sel <= slave_writedata[20:16];
usr_up_dn <= slave_writedata[21];
dps_changed <= 1;
dps_start_assert <= 1;
end
C_COUNTERS_REG:
begin
operation_address <= C_COUNTERS_REG;
usr_c_cnt_lo <= slave_writedata[7:0];
usr_c_cnt_hi <= slave_writedata[15:8];
usr_c_cnt_bypass_en <= slave_writedata[16];
usr_c_cnt_odd_duty_div_en <= slave_writedata[17];
usr_cnt_sel <= slave_writedata[22:18];
any_c_cnt_changed <= 1'b1;
all_c_cnt_done_q <= 0;
dprio_start <= 1'b1;
end
BWCTRL_REG:
begin
usr_bwctrl_value <= slave_writedata[3:0];
bwctrl_changed <= 1'b1;
bwctrl_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= BWCTRL_REG;
end
CP_CURRENT_REG:
begin
usr_cp_current_value <= slave_writedata[2:0];
cp_current_changed <= 1'b1;
cp_current_done_q <= 0;
dprio_start <= 1'b1;
operation_address <= CP_CURRENT_REG;
end
ANY_DPRIO:
begin
operation_address <= ANY_DPRIO;
manual_dprio_changed <= 1'b1;
usr_dprio_address <= slave_writedata[5:0];
usr_dprio_writedata_0 <= slave_writedata[21:6];
usr_r_w <= slave_writedata[22];
manual_dprio_done_q <= 0;
dprio_start <= 1'b1;
end
MIF_REG:
begin
mif_reg_asserted <= 1'b1;
mif_base_addr <= slave_writedata[ROM_ADDR_WIDTH-1:0];
mif_start_assert <= 1'b1;
end
endcase
end
end
end
//C Counter assigning values to the 2-d array of values for each C counter
reg [4:0] j;
always @(posedge clk)
begin
if (reset)
begin
c_cnt_changed[17:0] <= 0;
for (j = 0; j < number_of_counters; j = j + 1'b1)
begin : c_cnt_reset
temp_c_cnt_bypass_en[j] <= 0;
temp_c_cnt_odd_duty_div_en[j] <= 0;
temp_c_cnt_lo[j][7:0] <= 0;
temp_c_cnt_hi[j][7:0] <= 0;
end
end
else
begin
if (dprio_write_done)
begin
c_cnt_changed <= 0;
end
if (any_c_cnt_changed && (operation_address == C_COUNTERS_REG))
begin
case (cnt_sel)
CNT_0:
begin
temp_c_cnt_lo [0] <= usr_c_cnt_lo;
temp_c_cnt_hi [0] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [0] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [0] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [0] <= 1'b1;
end
CNT_1:
begin
temp_c_cnt_lo [1] <= usr_c_cnt_lo;
temp_c_cnt_hi [1] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [1] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [1] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [1] <= 1'b1;
end
CNT_2:
begin
temp_c_cnt_lo [2] <= usr_c_cnt_lo;
temp_c_cnt_hi [2] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [2] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [2] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [2] <= 1'b1;
end
CNT_3:
begin
temp_c_cnt_lo [3] <= usr_c_cnt_lo;
temp_c_cnt_hi [3] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [3] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [3] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [3] <= 1'b1;
end
CNT_4:
begin
temp_c_cnt_lo [4] <= usr_c_cnt_lo;
temp_c_cnt_hi [4] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [4] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [4] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [4] <= 1'b1;
end
CNT_5:
begin
temp_c_cnt_lo [5] <= usr_c_cnt_lo;
temp_c_cnt_hi [5] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [5] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [5] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [5] <= 1'b1;
end
CNT_6:
begin
temp_c_cnt_lo [6] <= usr_c_cnt_lo;
temp_c_cnt_hi [6] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [6] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [6] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [6] <= 1'b1;
end
CNT_7:
begin
temp_c_cnt_lo [7] <= usr_c_cnt_lo;
temp_c_cnt_hi [7] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [7] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [7] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [7] <= 1'b1;
end
CNT_8:
begin
temp_c_cnt_lo [8] <= usr_c_cnt_lo;
temp_c_cnt_hi [8] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [8] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [8] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [8] <= 1'b1;
end
CNT_9:
begin
temp_c_cnt_lo [9] <= usr_c_cnt_lo;
temp_c_cnt_hi [9] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [9] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [9] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [9] <= 1'b1;
end
CNT_10:
begin
temp_c_cnt_lo [10] <= usr_c_cnt_lo;
temp_c_cnt_hi [10] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [10] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [10] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [10] <= 1'b1;
end
CNT_11:
begin
temp_c_cnt_lo [11] <= usr_c_cnt_lo;
temp_c_cnt_hi [11] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [11] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [11] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [11] <= 1'b1;
end
CNT_12:
begin
temp_c_cnt_lo [12] <= usr_c_cnt_lo;
temp_c_cnt_hi [12] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [12] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [12] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [12] <= 1'b1;
end
CNT_13:
begin
temp_c_cnt_lo [13] <= usr_c_cnt_lo;
temp_c_cnt_hi [13] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [13] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [13] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [13] <= 1'b1;
end
CNT_14:
begin
temp_c_cnt_lo [14] <= usr_c_cnt_lo;
temp_c_cnt_hi [14] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [14] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [14] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [14] <= 1'b1;
end
CNT_15:
begin
temp_c_cnt_lo [15] <= usr_c_cnt_lo;
temp_c_cnt_hi [15] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [15] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [15] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [15] <= 1'b1;
end
CNT_16:
begin
temp_c_cnt_lo [16] <= usr_c_cnt_lo;
temp_c_cnt_hi [16] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [16] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [16] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [16] <= 1'b1;
end
CNT_17:
begin
temp_c_cnt_lo [17] <= usr_c_cnt_lo;
temp_c_cnt_hi [17] <= usr_c_cnt_hi;
temp_c_cnt_bypass_en [17] <= usr_c_cnt_bypass_en;
temp_c_cnt_odd_duty_div_en [17] <= usr_c_cnt_odd_duty_div_en;
c_cnt_changed [17] <= 1'b1;
end
endcase
end
end
end
//logic to handle which writes the user indicated and wants to start.
assign usr_valid_changes =dsm_k_changed| any_c_cnt_changed |n_cnt_changed | m_cnt_changed | dps_changed_valid |manual_dprio_changed |cp_current_changed|bwctrl_changed;
//start the reconfig operations by writing to the DPRIO
reg break_loop;
reg [4:0] i;
always @(*)
begin
dprio_temp_read_1 = 0;
dprio_temp_read_2 = 0;
dprio_temp_m_n_c_readdata_1_d = 0;
dprio_temp_m_n_c_readdata_2_d = 0;
break_loop = 0;
dprio_next_state = DPRIO_IDLE;
avmm_dprio_write = 0;
avmm_dprio_read = 0;
avmm_dprio_address = 0;
avmm_dprio_writedata = 0;
avmm_dprio_byteen = 0;
dprio_write_done = 1;
manual_dprio_done_d = 0;
n_cnt_done_d = 0;
dsm_k_done_d = 0;
dsm_k_ready_false_done_d = 0;
m_cnt_done_d = 0;
c_cnt_done_d[17:0] = 0;
all_c_cnt_done_d = 0;
bwctrl_done_d = 0;
cp_current_done_d = 0;
i = 0;
// Deassert dprio_write_done so it doesn't reset mif_reg_asserted (toggled writes)
if (dprio_start | mif_start_assert)
dprio_write_done = 0;
if (current_state == WAIT_ON_LOCK)
begin
case (dprio_cur_state)
ONE:
begin
if (n_cnt_changed & !n_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = N_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_n_cnt_lo;
avmm_dprio_writedata[15:8] = usr_n_cnt_hi;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_address = M_CNT_DIV_ADDR;
avmm_dprio_writedata[7:0] = usr_m_cnt_lo;
avmm_dprio_writedata[15:8] = usr_m_cnt_hi;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_hilo
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
if (fpll_1) avmm_dprio_address = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - i;
else avmm_dprio_address = C_CNT_0_DIV_ADDR + i;
avmm_dprio_writedata[7:0] = temp_c_cnt_lo[i];
avmm_dprio_writedata[15:8] = temp_c_cnt_hi[i];
//To break from the loop, since only one counter
//is addressed at a time
break_loop = 1'b1;
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (cp_current_changed & !cp_current_done_q)
begin
dprio_write_done = 0;
avmm_dprio_write = 0;
dprio_next_state = TWO;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
dprio_next_state = TWO;
avmm_dprio_write = usr_r_w;
avmm_dprio_address = usr_dprio_address;
avmm_dprio_writedata[15:0] = usr_dprio_writedata_0;
end
else dprio_next_state = DPRIO_IDLE;
end
TWO:
begin
//handle reading the two setting bits on n_cnt, then
//writing them back while preserving other bits.
//Issue two consecutive reads then wait; readLatency=3
dprio_write_done = 0;
dprio_next_state = THREE;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
//reading the K ready 16 bit word. Need to write 0 to it
//afterwards to indicate that K has not been done writing
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
dprio_next_state = FOUR;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
dprio_next_state = FOUR;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
dprio_next_state = FOUR;
end
else if (manual_dprio_changed & !manual_dprio_done_q)
begin
avmm_dprio_read = ~usr_r_w;
avmm_dprio_address = usr_dprio_address;
dprio_next_state = DPRIO_DONE;
end
else dprio_next_state = DPRIO_IDLE;
end
THREE:
begin
dprio_write_done = 0;
avmm_dprio_byteen = 2'b11;
avmm_dprio_read = 1'b1;
dprio_next_state = FOUR;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_read_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
break_loop = 1'b1;
end
end
end
end
end
else dprio_next_state = DPRIO_IDLE;
end
FOUR:
begin
dprio_temp_read_1 = 1'b1;
dprio_write_done = 0;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
dprio_temp_m_n_c_readdata_1_d = dprio_readdata;
dprio_next_state = FIVE;
end
else dprio_next_state = DPRIO_IDLE;
end
FIVE:
begin
dprio_write_done = 0;
dprio_temp_read_2 = 1'b1;
if (cp_current_changed|bwctrl_changed|dsm_k_changed|n_cnt_changed|m_cnt_changed|any_c_cnt_changed)
begin
//this is where DSM ready value comes.
//Need to store in a register to be used later
dprio_temp_m_n_c_readdata_2_d = dprio_readdata;
dprio_next_state = SIX;
end
else dprio_next_state = DPRIO_IDLE;
end
SIX:
begin
dprio_write_done = 0;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
dprio_next_state = SEVEN;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_1_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_bypass_en;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_BYPASS_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_bypass_en;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_bypass
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_BYPASS_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_BYPASS_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_bypass_en[i];
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_write = 0;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_write = 0;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_write = 0;
end
else dprio_next_state = DPRIO_IDLE;
end
SEVEN:
begin
dprio_write_done = 0;
dprio_next_state = EIGHT;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
if (n_cnt_changed & !n_cnt_done_q)
begin
avmm_dprio_address = N_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[5] = usr_n_cnt_odd_duty_div_en;
n_cnt_done_d = 1'b1;
end
else if (m_cnt_changed & !m_cnt_done_q)
begin
avmm_dprio_address = M_CNT_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[4] = usr_m_cnt_odd_duty_div_en;
m_cnt_done_d = 1'b1;
end
else if (any_c_cnt_changed & !all_c_cnt_done_q)
begin
for (i = 0; (i < number_of_counters) & !break_loop; i = i + 1'b1)
begin : c_cnt_write_odd_div
if (fpll_1)
begin
if (i > 13)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i-14] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
else
begin
if (i < 4)
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_0_3_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[3-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
//have to OR the signals to prevent
//overwriting of previous dones
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
else
begin
if (c_cnt_changed[i] & !c_cnt_done_q[i])
begin
avmm_dprio_address = C_CNT_4_17_ODD_DIV_EN_ADDR;
avmm_dprio_writedata[17-i] = temp_c_cnt_odd_duty_div_en[i];
c_cnt_done_d[i] = 1'b1;
c_cnt_done_d = c_cnt_done_d | c_cnt_done_q;
break_loop = 1'b1;
end
end
end
end
end
else if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b0;
dsm_k_ready_false_done_d = 1'b1;
end
else if (bwctrl_changed & !bwctrl_done_q)
begin
avmm_dprio_address = BWCTRL_ADDR;
avmm_dprio_writedata[3:0] = usr_bwctrl_value;
bwctrl_done_d = 1'b1;
end
else if (cp_current_changed & !cp_current_done_q)
begin
avmm_dprio_address = CP_CURRENT_ADDR;
avmm_dprio_writedata[2:0] = usr_cp_current_value;
cp_current_done_d = 1'b1;
end
//if all C_cnt that were changed are done, then assert all_c_cnt_done
if (c_cnt_done_d == c_cnt_changed)
all_c_cnt_done_d = 1'b1;
if (n_cnt_changed & n_cnt_done_d)
dprio_next_state = DPRIO_DONE;
if (any_c_cnt_changed & !all_c_cnt_done_d & !all_c_cnt_done_q)
dprio_next_state = ONE;
else if (m_cnt_changed & !m_cnt_done_d & !m_cnt_done_q)
dprio_next_state = ONE;
else if (dsm_k_changed & !dsm_k_ready_false_done_d)
dprio_next_state = TWO;
else if (dsm_k_changed & !dsm_k_done_q)
dprio_next_state = EIGHT;
else if (bwctrl_changed & !bwctrl_done_d)
dprio_next_state = TWO;
else if (cp_current_changed & !cp_current_done_d)
dprio_next_state = TWO;
else
begin
dprio_next_state = DPRIO_DONE;
dprio_write_done = 1'b1;
end
end
//finish the rest of the DSM reads/writes
//writing k value, writing k_ready to 1.
EIGHT:
begin
dprio_write_done = 0;
dprio_next_state = NINE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_0;
avmm_dprio_writedata[15:0] = usr_k_value[15:0];
end
end
NINE:
begin
dprio_write_done = 0;
dprio_next_state = TEN;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_FRACTIONAL_DIVISION_ADDR_1;
avmm_dprio_writedata[15:0] = usr_k_value[31:16];
end
end
TEN:
begin
dprio_write_done = 0;
dprio_next_state = ONE;
avmm_dprio_write = 1'b1;
avmm_dprio_byteen = 2'b11;
if (dsm_k_changed & !dsm_k_done_q)
begin
avmm_dprio_address = DSM_K_READY_ADDR;
//already have the readdata for DSM_K_READY_ADDR since we read it
//earlier. Just reuse here
avmm_dprio_writedata = dprio_temp_m_n_c_readdata_2_q;
avmm_dprio_writedata[DSM_K_READY_BIT_INDEX] = 1'b1;
dsm_k_done_d = 1'b1;
end
end
DPRIO_DONE:
begin
dprio_write_done = 1'b1;
if (dprio_start) dprio_next_state = DPRIO_IDLE;
else dprio_next_state = DPRIO_DONE;
end
DPRIO_IDLE:
begin
if (dprio_start) dprio_next_state = ONE;
else dprio_next_state = DPRIO_IDLE;
end
default: dprio_next_state = 4'bxxxx;
endcase
end
end
//assert the waitreq signal according to the state of the slave
assign slave_waitrequest = (slave_mode==mode_WR) ? ((locked === 1'b1) ? (((current_state==WAIT_ON_LOCK) & !dprio_write_done) | !dps_done |reset|!dprio_init_done) : 1'b1) : 1'b0;
// Read operations
always @(*)
begin
status = 0;
if (slave_mode == mode_POLL)
//asserting status to 1 if the slave is done.
status = (current_state == LOCKED);
end
//************************************************************//
//************************************************************//
//******************** READ STATE MACHINE ********************//
//************************************************************//
//************************************************************//
reg [1:0] current_read_state;
reg [1:0] next_read_state;
reg [5:0] slave_address_int_d;
reg [5:0] slave_address_int_q;
reg dprio_read_1;
reg [5:0] dprio_address_1;
reg [1:0] dprio_byteen_1;
reg [4:0] usr_cnt_sel_1;
localparam READ = 2'b00, READ_WAIT = 2'b01, READ_IDLE = 2'b10;
always @(posedge clk)
begin
if (reset)
begin
current_read_state <= READ_IDLE;
slave_address_int_q <= 0;
slave_readdata_q <= 0;
end
else
begin
current_read_state <= next_read_state;
slave_address_int_q <= slave_address_int_d;
slave_readdata_q <= slave_readdata_d;
end
end
always @(*)
begin
dprio_read_1 = 0;
dprio_address_1 = 0;
dprio_byteen_1 = 0;
slave_address_int_d = 0;
slave_readdata_d = 0;
status_read = 0;
usr_cnt_sel_1 = 0;
case(current_read_state)
READ_IDLE:
begin
slave_address_int_d = 0;
next_read_state = READ_IDLE;
if ((current_state != WAIT_ON_LOCK) && slave_read)
begin
slave_address_int_d = slave_address;
if ((slave_address >= CNT_BASE) && (slave_address < CNT_BASE+18))
begin
next_read_state = READ_WAIT;
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
usr_cnt_sel_1 = (slave_address[4:0] - CNT_BASE);
if (fpll_1) dprio_address_1 = C_CNT_0_DIV_ADDR + C_CNT_0_DIV_ADDR_DPRIO_1 - cnt_sel;
else dprio_address_1 = C_CNT_0_DIV_ADDR + cnt_sel;
end
else
begin
case (slave_address)
MODE_REG:
begin
next_read_state = READ_WAIT;
slave_readdata_d = slave_mode;
end
STATUS_REG:
begin
next_read_state = READ_WAIT;
status_read = 1'b1;
slave_readdata_d = status;
end
N_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = N_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
M_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = M_CNT_DIV_ADDR;
next_read_state = READ_WAIT;
end
BWCTRL_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = BWCTRL_ADDR;
next_read_state = READ_WAIT;
end
CP_CURRENT_REG:
begin
dprio_byteen_1 = 2'b11;
dprio_read_1 = 1'b1;
dprio_address_1 = CP_CURRENT_ADDR;
next_read_state = READ_WAIT;
end
default : next_read_state = READ_IDLE;
endcase
end
end
else
next_read_state = READ_IDLE;
end
READ_WAIT:
begin
next_read_state = READ;
slave_address_int_d = slave_address_int_q;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
endcase
end
READ:
begin
next_read_state = READ_IDLE;
slave_address_int_d = slave_address_int_q;
slave_readdata_d = dprio_readdata;
case (slave_address_int_q)
MODE_REG:
begin
slave_readdata_d = slave_readdata_q;
end
STATUS_REG:
begin
slave_readdata_d = slave_readdata_q;
end
BWCTRL_REG:
begin
slave_readdata_d = dprio_readdata[3:0];
end
CP_CURRENT_REG:
begin
slave_readdata_d = dprio_readdata[2:0];
end
endcase
end
default: next_read_state = 2'bxx;
endcase
end
dyn_phase_shift dyn_phase_shift_inst (
.clk(clk),
.reset(reset),
.phase_done(phase_done),
.pll_start_valid(pll_start_valid),
.dps_changed(dps_changed),
.dps_changed_valid(dps_changed_valid),
.dprio_write_done(dprio_write_done),
.usr_num_shifts(usr_num_shifts),
.usr_cnt_sel(usr_cnt_sel|usr_cnt_sel_1),
.usr_up_dn(usr_up_dn),
.locked(locked),
.dps_done(dps_done),
.phase_en(phase_en),
.up_dn(up_dn),
.cnt_sel(cnt_sel));
defparam dyn_phase_shift_inst.device_family = device_family;
assign dprio_clk = clk;
self_reset self_reset_inst (mgmt_reset, clk, reset, dprio_init_reset);
dprio_mux dprio_mux_inst (
.init_dprio_address(init_dprio_address),
.init_dprio_read(init_dprio_read),
.init_dprio_byteen(init_dprio_byteen),
.init_dprio_write(init_dprio_write),
.init_dprio_writedata(init_dprio_writedata),
.init_atpgmode(init_atpgmode),
.init_mdio_dis(init_mdio_dis),
.init_scanen(init_scanen),
.init_ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done),
// Inputs from avmm master
.avmm_dprio_address(avmm_dprio_address | dprio_address_1),
.avmm_dprio_read(avmm_dprio_read | dprio_read_1),
.avmm_dprio_byteen(avmm_dprio_byteen | dprio_byteen_1),
.avmm_dprio_write(avmm_dprio_write),
.avmm_dprio_writedata(avmm_dprio_writedata),
.avmm_atpgmode(avmm_atpgmode),
.avmm_mdio_dis(avmm_mdio_dis),
.avmm_scanen(avmm_scanen),
// Outputs to fpll
.dprio_address(dprio_address),
.dprio_read(dprio_read),
.dprio_byteen(dprio_byteen),
.dprio_write(dprio_write),
.dprio_writedata(dprio_writedata),
.atpgmode(dprio_atpgmode),
.mdio_dis(dprio_mdio_dis),
.scanen(dprio_scanen),
.ser_shift_load(dprio_ser_shift_load)
);
fpll_dprio_init fpll_dprio_init_inst (
.clk(clk),
.reset_n(~reset),
.locked(locked),
//outputs
.dprio_address(init_dprio_address),
.dprio_read(init_dprio_read),
.dprio_byteen(init_dprio_byteen),
.dprio_write(init_dprio_write),
.dprio_writedata(init_dprio_writedata),
.atpgmode(init_atpgmode),
.mdio_dis(init_mdio_dis),
.scanen(init_scanen),
.ser_shift_load(init_ser_shift_load),
.dprio_init_done(dprio_init_done));
//address luts, to be reconfigged by the Fitter
//FPLL_1 or 0 address lut
generic_lcell_comb lcell_fpll_0_1 (
.dataa(1'b0),
.combout (fpll_1));
defparam lcell_fpll_0_1.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_fpll_0_1.dont_touch = "on";
defparam lcell_fpll_0_1.family = device_family;
wire dprio_read_combout;
generic_lcell_comb lcell_dprio_read (
.dataa(fpll_1),
.datab(dprio_read),
.datac(1'b0),
.datad(1'b0),
.datae(1'b0),
.dataf(1'b0),
.combout (dprio_read_combout));
defparam lcell_dprio_read.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_dprio_read.dont_touch = "on";
defparam lcell_dprio_read.family = device_family;
//assign reconfig_to_pll signals
assign reconfig_to_pll[0] = dprio_clk;
assign reconfig_to_pll[1] = ~dprio_init_reset;
assign reconfig_to_pll[2] = dprio_write;
assign reconfig_to_pll[3] = dprio_read_combout;
assign reconfig_to_pll[9:4] = dprio_address;
assign reconfig_to_pll[25:10] = dprio_writedata;
assign reconfig_to_pll[27:26] = dprio_byteen;
assign reconfig_to_pll[28] = dprio_ser_shift_load;
assign reconfig_to_pll[29] = dprio_mdio_dis;
assign reconfig_to_pll[30] = phase_en;
assign reconfig_to_pll[31] = up_dn;
assign reconfig_to_pll[36:32] = cnt_sel;
assign reconfig_to_pll[37] = dprio_scanen;
assign reconfig_to_pll[38] = dprio_atpgmode;
//assign reconfig_to_pll[40:37] = clken;
assign reconfig_to_pll[63:39] = 0;
//assign reconfig_from_pll signals
assign dprio_readdata = reconfig_from_pll [15:0];
assign locked = reconfig_from_pll [16];
assign phase_done = reconfig_from_pll [17];
endmodule
module self_reset (input wire mgmt_reset, input wire clk, output wire reset, output wire init_reset);
localparam RESET_COUNTER_VALUE = 3'd2;
localparam INITIAL_WAIT_VALUE = 9'd340;
reg [9:0]counter;
reg local_reset;
reg usr_mode_init_wait;
initial
begin
local_reset = 1'b1;
counter = 0;
usr_mode_init_wait = 0;
end
always @(posedge clk)
begin
if (mgmt_reset)
begin
counter <= 0;
end
else
begin
if (!usr_mode_init_wait)
begin
if (counter == INITIAL_WAIT_VALUE)
begin
local_reset <= 0;
usr_mode_init_wait <= 1'b1;
counter <= 0;
end
else
begin
counter <= counter + 1'b1;
end
end
else
begin
if (counter == RESET_COUNTER_VALUE)
local_reset <= 0;
else
counter <= counter + 1'b1;
end
end
end
assign reset = mgmt_reset | local_reset;
assign init_reset = local_reset;
endmodule
module dprio_mux (
// Inputs from init block
input [ 5:0] init_dprio_address,
input init_dprio_read,
input [ 1:0] init_dprio_byteen,
input init_dprio_write,
input [15:0] init_dprio_writedata,
input init_atpgmode,
input init_mdio_dis,
input init_scanen,
input init_ser_shift_load,
input dprio_init_done,
// Inputs from avmm master
input [ 5:0] avmm_dprio_address,
input avmm_dprio_read,
input [ 1:0] avmm_dprio_byteen,
input avmm_dprio_write,
input [15:0] avmm_dprio_writedata,
input avmm_atpgmode,
input avmm_mdio_dis,
input avmm_scanen,
input avmm_ser_shift_load,
// Outputs to fpll
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output atpgmode,
output mdio_dis,
output scanen,
output ser_shift_load
);
assign dprio_address = dprio_init_done ? avmm_dprio_address : init_dprio_address;
assign dprio_read = dprio_init_done ? avmm_dprio_read : init_dprio_read;
assign dprio_byteen = dprio_init_done ? avmm_dprio_byteen : init_dprio_byteen;
assign dprio_write = dprio_init_done ? avmm_dprio_write : init_dprio_write;
assign dprio_writedata = dprio_init_done ? avmm_dprio_writedata : init_dprio_writedata;
assign atpgmode = init_atpgmode;
assign scanen = init_scanen;
assign mdio_dis = init_mdio_dis;
assign ser_shift_load = init_ser_shift_load ;
endmodule
module fpll_dprio_init (
input clk,
input reset_n,
input locked,
output [ 5:0] dprio_address,
output dprio_read,
output [ 1:0] dprio_byteen,
output dprio_write,
output [15:0] dprio_writedata,
output reg atpgmode,
output reg mdio_dis,
output reg scanen,
output reg ser_shift_load,
output reg dprio_init_done
);
reg [1:0] rst_n = 2'b00;
reg [6:0] count = 7'd0;
reg init_done_forever;
// Internal versions of control signals
wire int_mdio_dis;
wire int_ser_shift_load;
wire int_dprio_init_done;
wire int_atpgmode/*synthesis keep*/;
wire int_scanen/*synthesis keep*/;
assign dprio_address = count[6] ? 5'b0 : count[5:0] ;
assign dprio_byteen = 2'b11; // always enabled
assign dprio_write = ~count[6] & reset_n ; // write for first 64 cycles
assign dprio_read = 1'b0;
assign dprio_writedata = 16'd0;
assign int_ser_shift_load = count[6] ? |count[2:1] : 1'b1;
assign int_mdio_dis = count[6] ? ~count[2] : 1'b1;
assign int_dprio_init_done = ~init_done_forever ? (count[6] ? &count[2:0] : 1'b0)
: 1'b1;
assign int_atpgmode = 0;
assign int_scanen = 0;
initial begin
count = 7'd0;
init_done_forever = 0;
mdio_dis = 1'b1;
ser_shift_load = 1'b1;
dprio_init_done = 1'b0;
scanen = 1'b0;
atpgmode = 1'b0;
end
// reset synch.
always @(posedge clk or negedge reset_n)
if(!reset_n) rst_n <= 2'b00;
else rst_n <= {rst_n[0],1'b1};
// counter
always @(posedge clk)
begin
if (!rst_n[1])
init_done_forever <= 1'b0;
else
begin
if (count[6] && &count[1:0])
init_done_forever <= 1'b1;
end
end
always @(posedge clk or negedge rst_n[1])
begin
if(!rst_n[1])
begin
count <= 7'd0;
end
else if(~int_dprio_init_done)
begin
count <= count + 7'd1;
end
else
begin
count <= count;
end
end
// outputs
always @(posedge clk) begin
mdio_dis <= int_mdio_dis;
ser_shift_load <= int_ser_shift_load;
dprio_init_done <= int_dprio_init_done;
atpgmode <= int_atpgmode;
scanen <= int_scanen;
end
endmodule
module dyn_phase_shift
#(
parameter device_family = "Stratix V"
) (
input wire clk,
input wire reset,
input wire phase_done,
input wire pll_start_valid,
input wire dps_changed,
input wire dprio_write_done,
input wire [15:0] usr_num_shifts,
input wire [4:0] usr_cnt_sel,
input wire usr_up_dn,
input wire locked,
//output
output wire dps_done,
output reg phase_en,
output wire up_dn,
output wire dps_changed_valid,
output wire [4:0] cnt_sel);
reg first_phase_shift_d;
reg first_phase_shift_q;
reg [15:0] phase_en_counter;
reg [3:0] dps_current_state;
reg [3:0] dps_next_state;
localparam DPS_START = 4'd0, DPS_WAIT_PHASE_DONE = 4'd1, DPS_DONE = 4'd2, DPS_WAIT_PHASE_EN = 4'd3, DPS_WAIT_DPRIO_WRITING = 4'd4, DPS_CHANGED = 4'd5;
localparam PHASE_EN_WAIT_COUNTER = 5'd1;
reg [15:0] shifts_done_counter;
reg phase_done_final;
wire gnd /*synthesis keep*/;
//fsm
//always block controlling the state regs
always @(posedge clk)
begin
if (reset)
begin
dps_current_state <= DPS_DONE;
end
else
begin
dps_current_state <= dps_next_state;
end
end
//the combinational part. assigning the next state
//this turns on the phase_done_final signal when phase_done does this:
//_____ ______
// |______|
always @(*)
begin
phase_done_final = 0;
first_phase_shift_d = 0;
phase_en = 0;
dps_next_state = DPS_DONE;
case (dps_current_state)
DPS_START:
begin
phase_en = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
DPS_WAIT_PHASE_EN:
begin
phase_en = 1'b1;
if (first_phase_shift_q)
begin
first_phase_shift_d = 1'b1;
dps_next_state = DPS_WAIT_PHASE_EN;
end
else
begin
if (phase_en_counter == PHASE_EN_WAIT_COUNTER)
dps_next_state = DPS_WAIT_PHASE_DONE;
else dps_next_state = DPS_WAIT_PHASE_EN;
end
end
DPS_WAIT_PHASE_DONE:
begin
if (!phase_done | !locked)
begin
dps_next_state = DPS_WAIT_PHASE_DONE;
end
else
begin
if ((usr_num_shifts != shifts_done_counter) & (usr_num_shifts != 0))
begin
dps_next_state = DPS_START;
phase_done_final = 1'b1;
end
else
begin
dps_next_state = DPS_DONE;
end
end
end
DPS_DONE:
begin
phase_done_final = 0;
if (dps_changed)
dps_next_state = DPS_CHANGED;
else dps_next_state = DPS_DONE;
end
DPS_CHANGED:
begin
if (pll_start_valid)
dps_next_state = DPS_WAIT_DPRIO_WRITING;
else
dps_next_state = DPS_CHANGED;
end
DPS_WAIT_DPRIO_WRITING:
begin
if (dprio_write_done)
dps_next_state = DPS_START;
else
dps_next_state = DPS_WAIT_DPRIO_WRITING;
end
default: dps_next_state = 4'bxxxx;
endcase
end
always @(posedge clk)
begin
if (dps_current_state == DPS_WAIT_PHASE_DONE)
phase_en_counter <= 0;
else if (dps_current_state == DPS_WAIT_PHASE_EN)
phase_en_counter <= phase_en_counter + 1'b1;
if (reset)
begin
phase_en_counter <= 0;
shifts_done_counter <= 1'b1;
first_phase_shift_q <= 1;
end
else
begin
if (first_phase_shift_d)
first_phase_shift_q <= 0;
if (dps_done)
begin
shifts_done_counter <= 1'b1;
end
else
begin
if (phase_done_final & (dps_next_state!= DPS_DONE))
shifts_done_counter <= shifts_done_counter + 1'b1;
else
shifts_done_counter <= shifts_done_counter;
end
end
end
assign dps_changed_valid = (dps_current_state == DPS_CHANGED);
assign dps_done =(dps_current_state == DPS_DONE) | (dps_current_state == DPS_CHANGED);
assign up_dn = usr_up_dn;
assign gnd = 1'b0;
//cnt select luts (5)
generic_lcell_comb lcell_cnt_sel_0 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[0]));
defparam lcell_cnt_sel_0.lut_mask = 64'hAAAAAAAAAAAAAAAA;
defparam lcell_cnt_sel_0.dont_touch = "on";
defparam lcell_cnt_sel_0.family = device_family;
generic_lcell_comb lcell_cnt_sel_1 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[1]));
defparam lcell_cnt_sel_1.lut_mask = 64'hCCCCCCCCCCCCCCCC;
defparam lcell_cnt_sel_1.dont_touch = "on";
defparam lcell_cnt_sel_1.family = device_family;
generic_lcell_comb lcell_cnt_sel_2 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[2]));
defparam lcell_cnt_sel_2.lut_mask = 64'hF0F0F0F0F0F0F0F0;
defparam lcell_cnt_sel_2.dont_touch = "on";
defparam lcell_cnt_sel_2.family = device_family;
generic_lcell_comb lcell_cnt_sel_3 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[3]));
defparam lcell_cnt_sel_3.lut_mask = 64'hFF00FF00FF00FF00;
defparam lcell_cnt_sel_3.dont_touch = "on";
defparam lcell_cnt_sel_3.family = device_family;
generic_lcell_comb lcell_cnt_sel_4 (
.dataa(usr_cnt_sel[0]),
.datab(usr_cnt_sel[1]),
.datac(usr_cnt_sel[2]),
.datad(usr_cnt_sel[3]),
.datae(usr_cnt_sel[4]),
.dataf(gnd),
.combout (cnt_sel[4]));
defparam lcell_cnt_sel_4.lut_mask = 64'hFFFF0000FFFF0000;
defparam lcell_cnt_sel_4.dont_touch = "on";
defparam lcell_cnt_sel_4.family = device_family;
endmodule
module generic_lcell_comb
#(
//parameter
parameter family = "Stratix V",
parameter lut_mask = 64'hAAAAAAAAAAAAAAAA,
parameter dont_touch = "on"
) (
input dataa,
input datab,
input datac,
input datad,
input datae,
input dataf,
output combout
);
generate
if (family == "Stratix V")
begin
stratixv_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V")
begin
arriav_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Arria V GZ")
begin
arriavgz_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
else if (family == "Cyclone V")
begin
cyclonev_lcell_comb lcell_inst (
.dataa(dataa),
.datab(datab),
.datac(datac),
.datad(datad),
.datae(datae),
.dataf(dataf),
.combout (combout));
defparam lcell_inst.lut_mask = lut_mask;
defparam lcell_inst.dont_touch = dont_touch;
end
endgenerate
endmodule
|
/*
Copyright (c) 2014-2017 Alex Forencich
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.
*/
// Language: Verilog-2001
`timescale 1 ns / 1 ps
/*
* Synchronizes an asyncronous signal to a given clock by using a pipeline of
* two registers.
*/
module sync_signal #(
parameter WIDTH=1, // width of the input and output signals
parameter N=2 // depth of synchronizer
)(
input wire clk,
input wire [WIDTH-1:0] in,
output wire [WIDTH-1:0] out
);
reg [WIDTH-1:0] sync_reg[N-1:0];
/*
* The synchronized output is the last register in the pipeline.
*/
assign out = sync_reg[N-1];
integer k;
always @(posedge clk) begin
sync_reg[0] <= in;
for (k = 1; k < N; k = k + 1) begin
sync_reg[k] <= sync_reg[k-1];
end
end
endmodule
|
/*
Copyright (c) 2014-2017 Alex Forencich
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.
*/
// Language: Verilog-2001
`timescale 1 ns / 1 ps
/*
* Synchronizes an asyncronous signal to a given clock by using a pipeline of
* two registers.
*/
module sync_signal #(
parameter WIDTH=1, // width of the input and output signals
parameter N=2 // depth of synchronizer
)(
input wire clk,
input wire [WIDTH-1:0] in,
output wire [WIDTH-1:0] out
);
reg [WIDTH-1:0] sync_reg[N-1:0];
/*
* The synchronized output is the last register in the pipeline.
*/
assign out = sync_reg[N-1];
integer k;
always @(posedge clk) begin
sync_reg[0] <= in;
for (k = 1; k < N; k = k + 1) begin
sync_reg[k] <= sync_reg[k-1];
end
end
endmodule
|
(** * Extraction: Extracting ML from Coq *)
(** * Basic Extraction *)
(** In its simplest form, program extraction from Coq is completely straightforward. *)
(** First we say what language we want to extract into. Options are OCaml (the
most mature), Haskell (which mostly works), and Scheme (a bit out
of date). *)
Extraction Language Ocaml.
(** Now we load up the Coq environment with some definitions, either
directly or by importing them from other modules. *)
Require Import SfLib.
Require Import ImpCEvalFun.
(** Finally, we tell Coq the name of a definition to extract and the
name of a file to put the extracted code into. *)
Extraction "imp1.ml" ceval_step.
(** When Coq processes this command, it generates a file [imp1.ml]
containing an extracted version of [ceval_step], together with
everything that it recursively depends on. Have a look at this
file now. *)
(* ############################################################## *)
(** * Controlling Extraction of Specific Types *)
(** We can tell Coq to extract certain [Inductive] definitions to
specific OCaml types. For each one, we must say
- how the Coq type itself should be represented in OCaml, and
- how each constructor should be translated. *)
Extract Inductive bool => "bool" [ "true" "false" ].
(** Also, for non-enumeration types (where the constructors take
arguments), we give an OCaml expression that can be used as a
"recursor" over elements of the type. (Think Church numerals.) *)
Extract Inductive nat => "int"
[ "0" "(fun x -> x + 1)" ]
"(fun zero succ n ->
if n=0 then zero () else succ (n-1))".
(** We can also extract defined constants to specific OCaml terms or
operators. *)
Extract Constant plus => "( + )".
Extract Constant mult => "( * )".
Extract Constant beq_nat => "( = )".
(** Important: It is entirely _your responsibility_ to make sure that
the translations you're proving make sense. For example, it might
be tempting to include this one
Extract Constant minus => "( - )".
but doing so could lead to serious confusion! (Why?)
*)
Extraction "imp2.ml" ceval_step.
(** Have a look at the file [imp2.ml]. Notice how the fundamental
definitions have changed from [imp1.ml]. *)
(* ############################################################## *)
(** * A Complete Example *)
(** To use our extracted evaluator to run Imp programs, all we need to
add is a tiny driver program that calls the evaluator and somehow
prints out the result.
For simplicity, we'll print results by dumping out the first four
memory locations in the final state.
Also, to make it easier to type in examples, let's extract a
parser from the [ImpParser] Coq module. To do this, we need a few
more declarations to set up the right correspondence between Coq
strings and lists of OCaml characters. *)
Require Import Ascii String.
Extract Inductive ascii => char
[
"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))"
]
"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))".
Extract Constant zero => "'\000'".
Extract Constant one => "'\001'".
Extract Constant shift =>
"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)".
Extract Inlined Constant ascii_dec => "(=)".
(** We also need one more variant of booleans. *)
Extract Inductive sumbool => "bool" ["true" "false"].
(** The extraction is the same as always. *)
Require Import Imp.
Require Import ImpParser.
Extraction "imp.ml" empty_state ceval_step parse.
(** Now let's run our generated Imp evaluator. First, have a look at
[impdriver.ml]. (This was written by hand, not extracted.)
Next, compile the driver together with the extracted code and
execute it, as follows.
<<
ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml
./impdriver
>>
(The [-w] flags to [ocamlc] are just there to suppress a few
spurious warnings.) *)
(* ############################################################## *)
(** * Discussion *)
(** Since we've proved that the [ceval_step] function behaves the same
as the [ceval] relation in an appropriate sense, the extracted
program can be viewed as a _certified_ Imp interpreter. (Of
course, the parser is not certified in any interesting sense,
since we didn't prove anything about it.) *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * Extraction: Extracting ML from Coq *)
(** * Basic Extraction *)
(** In its simplest form, program extraction from Coq is completely straightforward. *)
(** First we say what language we want to extract into. Options are OCaml (the
most mature), Haskell (which mostly works), and Scheme (a bit out
of date). *)
Extraction Language Ocaml.
(** Now we load up the Coq environment with some definitions, either
directly or by importing them from other modules. *)
Require Import SfLib.
Require Import ImpCEvalFun.
(** Finally, we tell Coq the name of a definition to extract and the
name of a file to put the extracted code into. *)
Extraction "imp1.ml" ceval_step.
(** When Coq processes this command, it generates a file [imp1.ml]
containing an extracted version of [ceval_step], together with
everything that it recursively depends on. Have a look at this
file now. *)
(* ############################################################## *)
(** * Controlling Extraction of Specific Types *)
(** We can tell Coq to extract certain [Inductive] definitions to
specific OCaml types. For each one, we must say
- how the Coq type itself should be represented in OCaml, and
- how each constructor should be translated. *)
Extract Inductive bool => "bool" [ "true" "false" ].
(** Also, for non-enumeration types (where the constructors take
arguments), we give an OCaml expression that can be used as a
"recursor" over elements of the type. (Think Church numerals.) *)
Extract Inductive nat => "int"
[ "0" "(fun x -> x + 1)" ]
"(fun zero succ n ->
if n=0 then zero () else succ (n-1))".
(** We can also extract defined constants to specific OCaml terms or
operators. *)
Extract Constant plus => "( + )".
Extract Constant mult => "( * )".
Extract Constant beq_nat => "( = )".
(** Important: It is entirely _your responsibility_ to make sure that
the translations you're proving make sense. For example, it might
be tempting to include this one
Extract Constant minus => "( - )".
but doing so could lead to serious confusion! (Why?)
*)
Extraction "imp2.ml" ceval_step.
(** Have a look at the file [imp2.ml]. Notice how the fundamental
definitions have changed from [imp1.ml]. *)
(* ############################################################## *)
(** * A Complete Example *)
(** To use our extracted evaluator to run Imp programs, all we need to
add is a tiny driver program that calls the evaluator and somehow
prints out the result.
For simplicity, we'll print results by dumping out the first four
memory locations in the final state.
Also, to make it easier to type in examples, let's extract a
parser from the [ImpParser] Coq module. To do this, we need a few
more declarations to set up the right correspondence between Coq
strings and lists of OCaml characters. *)
Require Import Ascii String.
Extract Inductive ascii => char
[
"(* If this appears, you're using Ascii internals. Please don't *) (fun (b0,b1,b2,b3,b4,b5,b6,b7) -> let f b i = if b then 1 lsl i else 0 in Char.chr (f b0 0 + f b1 1 + f b2 2 + f b3 3 + f b4 4 + f b5 5 + f b6 6 + f b7 7))"
]
"(* If this appears, you're using Ascii internals. Please don't *) (fun f c -> let n = Char.code c in let h i = (n land (1 lsl i)) <> 0 in f (h 0) (h 1) (h 2) (h 3) (h 4) (h 5) (h 6) (h 7))".
Extract Constant zero => "'\000'".
Extract Constant one => "'\001'".
Extract Constant shift =>
"fun b c -> Char.chr (((Char.code c) lsl 1) land 255 + if b then 1 else 0)".
Extract Inlined Constant ascii_dec => "(=)".
(** We also need one more variant of booleans. *)
Extract Inductive sumbool => "bool" ["true" "false"].
(** The extraction is the same as always. *)
Require Import Imp.
Require Import ImpParser.
Extraction "imp.ml" empty_state ceval_step parse.
(** Now let's run our generated Imp evaluator. First, have a look at
[impdriver.ml]. (This was written by hand, not extracted.)
Next, compile the driver together with the extracted code and
execute it, as follows.
<<
ocamlc -w -20 -w -26 -o impdriver imp.mli imp.ml impdriver.ml
./impdriver
>>
(The [-w] flags to [ocamlc] are just there to suppress a few
spurious warnings.) *)
(* ############################################################## *)
(** * Discussion *)
(** Since we've proved that the [ceval_step] function behaves the same
as the [ceval] relation in an appropriate sense, the extracted
program can be viewed as a _certified_ Imp interpreter. (Of
course, the parser is not certified in any interesting sense,
since we didn't prove anything about it.) *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * MoreStlc: More on the Simply Typed Lambda-Calculus *)
Require Export Stlc.
(* ###################################################################### *)
(** * Simple Extensions to STLC *)
(** The simply typed lambda-calculus has enough structure to make its
theoretical properties interesting, but it is not much of a
programming language. In this chapter, we begin to close the gap
with real-world languages by introducing a number of familiar
features that have straightforward treatments at the level of
typing. *)
(** ** Numbers *)
(** Adding types, constants, and primitive operations for numbers is
easy -- just a matter of combining the [Types] and [Stlc]
chapters. *)
(** ** [let]-bindings *)
(** When writing a complex expression, it is often useful to give
names to some of its subexpressions: this avoids repetition and
often increases readability. Most languages provide one or more
ways of doing this. In OCaml (and Coq), for example, we can write
[let x=t1 in t2] to mean ``evaluate the expression [t1] and bind
the name [x] to the resulting value while evaluating [t2].''
Our [let]-binder follows OCaml's in choosing a call-by-value
evaluation order, where the [let]-bound term must be fully
evaluated before evaluation of the [let]-body can begin. The
typing rule [T_Let] tells us that the type of a [let] can be
calculated by calculating the type of the [let]-bound term,
extending the context with a binding with this type, and in this
enriched context calculating the type of the body, which is then
the type of the whole [let] expression.
At this point in the course, it's probably easier simply to look
at the rules defining this new feature as to wade through a lot of
english text conveying the same information. Here they are: *)
(** Syntax:
<<
t ::= Terms
| ... (other terms same as before)
| let x=t in t let-binding
>>
*)
(**
Reduction:
t1 ==> t1'
---------------------------------- (ST_Let1)
let x=t1 in t2 ==> let x=t1' in t2
---------------------------- (ST_LetValue)
let x=v1 in t2 ==> [x:=v1]t2
Typing:
Gamma |- t1 : T1 Gamma , x:T1 |- t2 : T2
-------------------------------------------- (T_Let)
Gamma |- let x=t1 in t2 : T2
*)
(** ** Pairs *)
(** Our functional programming examples in Coq have made
frequent use of _pairs_ of values. The type of such pairs is
called a _product type_.
The formalization of pairs is almost too simple to be worth
discussing. However, let's look briefly at the various parts of
the definition to emphasize the common pattern. *)
(** In Coq, the primitive way of extracting the components of a pair
is _pattern matching_. An alternative style is to take [fst] and
[snd] -- the first- and second-projection operators -- as
primitives. Just for fun, let's do our products this way. For
example, here's how we'd write a function that takes a pair of
numbers and returns the pair of their sum and difference:
<<
\x:Nat*Nat.
let sum = x.fst + x.snd in
let diff = x.fst - x.snd in
(sum,diff)
>>
*)
(** Adding pairs to the simply typed lambda-calculus, then, involves
adding two new forms of term -- pairing, written [(t1,t2)], and
projection, written [t.fst] for the first projection from [t] and
[t.snd] for the second projection -- plus one new type constructor,
[T1*T2], called the _product_ of [T1] and [T2]. *)
(** Syntax:
<<
t ::= Terms
| ...
| (t,t) pair
| t.fst first projection
| t.snd second projection
v ::= Values
| ...
| (v,v) pair value
T ::= Types
| ...
| T * T product type
>>
*)
(** For evaluation, we need several new rules specifying how pairs and
projection behave.
t1 ==> t1'
-------------------- (ST_Pair1)
(t1,t2) ==> (t1',t2)
t2 ==> t2'
-------------------- (ST_Pair2)
(v1,t2) ==> (v1,t2')
t1 ==> t1'
------------------ (ST_Fst1)
t1.fst ==> t1'.fst
------------------ (ST_FstPair)
(v1,v2).fst ==> v1
t1 ==> t1'
------------------ (ST_Snd1)
t1.snd ==> t1'.snd
------------------ (ST_SndPair)
(v1,v2).snd ==> v2
*)
(**
Rules [ST_FstPair] and [ST_SndPair] specify that, when a fully
evaluated pair meets a first or second projection, the result is
the appropriate component. The congruence rules [ST_Fst1] and
[ST_Snd1] allow reduction to proceed under projections, when the
term being projected from has not yet been fully evaluated.
[ST_Pair1] and [ST_Pair2] evaluate the parts of pairs: first the
left part, and then -- when a value appears on the left -- the right
part. The ordering arising from the use of the metavariables [v]
and [t] in these rules enforces a left-to-right evaluation
strategy for pairs. (Note the implicit convention that
metavariables like [v] and [v1] can only denote values.) We've
also added a clause to the definition of values, above, specifying
that [(v1,v2)] is a value. The fact that the components of a pair
value must themselves be values ensures that a pair passed as an
argument to a function will be fully evaluated before the function
body starts executing. *)
(** The typing rules for pairs and projections are straightforward.
Gamma |- t1 : T1 Gamma |- t2 : T2
--------------------------------------- (T_Pair)
Gamma |- (t1,t2) : T1*T2
Gamma |- t1 : T11*T12
--------------------- (T_Fst)
Gamma |- t1.fst : T11
Gamma |- t1 : T11*T12
--------------------- (T_Snd)
Gamma |- t1.snd : T12
*)
(** The rule [T_Pair] says that [(t1,t2)] has type [T1*T2] if [t1] has
type [T1] and [t2] has type [T2]. Conversely, the rules [T_Fst]
and [T_Snd] tell us that, if [t1] has a product type
[T11*T12] (i.e., if it will evaluate to a pair), then the types of
the projections from this pair are [T11] and [T12]. *)
(** ** Unit *)
(** Another handy base type, found especially in languages in
the ML family, is the singleton type [Unit]. *)
(** It has a single element -- the term constant [unit] (with a small
[u]) -- and a typing rule making [unit] an element of [Unit]. We
also add [unit] to the set of possible result values of
computations -- indeed, [unit] is the _only_ possible result of
evaluating an expression of type [Unit]. *)
(** Syntax:
<<
t ::= Terms
| ...
| unit unit value
v ::= Values
| ...
| unit unit
T ::= Types
| ...
| Unit Unit type
>>
Typing:
-------------------- (T_Unit)
Gamma |- unit : Unit
*)
(** It may seem a little strange to bother defining a type that
has just one element -- after all, wouldn't every computation
living in such a type be trivial?
This is a fair question, and indeed in the STLC the [Unit] type is
not especially critical (though we'll see two uses for it below).
Where [Unit] really comes in handy is in richer languages with
various sorts of _side effects_ -- e.g., assignment statements
that mutate variables or pointers, exceptions and other sorts of
nonlocal control structures, etc. In such languages, it is
convenient to have a type for the (trivial) result of an
expression that is evaluated only for its effect. *)
(** ** Sums *)
(** Many programs need to deal with values that can take two distinct
forms. For example, we might identify employees in an accounting
application using using _either_ their name _or_ their id number.
A search function might return _either_ a matching value _or_ an
error code.
These are specific examples of a binary _sum type_,
which describes a set of values drawn from exactly two given types, e.g.
<<
Nat + Bool
>>
*)
(** We create elements of these types by _tagging_ elements of
the component types. For example, if [n] is a [Nat] then [inl v]
is an element of [Nat+Bool]; similarly, if [b] is a [Bool] then
[inr b] is a [Nat+Bool]. The names of the tags [inl] and [inr]
arise from thinking of them as functions
<<
inl : Nat -> Nat + Bool
inr : Bool -> Nat + Bool
>>
that "inject" elements of [Nat] or [Bool] into the left and right
components of the sum type [Nat+Bool]. (But note that we don't
actually treat them as functions in the way we formalize them:
[inl] and [inr] are keywords, and [inl t] and [inr t] are primitive
syntactic forms, not function applications. This allows us to give
them their own special typing rules.) *)
(** In general, the elements of a type [T1 + T2] consist of the
elements of [T1] tagged with the token [inl], plus the elements of
[T2] tagged with [inr]. *)
(** One important usage of sums is signaling errors:
<<
div : Nat -> Nat -> (Nat + Unit) =
div =
\x:Nat. \y:Nat.
if iszero y then
inr unit
else
inl ...
>>
The type [Nat + Unit] above is in fact isomorphic to [option nat]
in Coq, and we've already seen how to signal errors with options. *)
(** To _use_ elements of sum types, we introduce a [case]
construct (a very simplified form of Coq's [match]) to destruct
them. For example, the following procedure converts a [Nat+Bool]
into a [Nat]: *)
(**
<<
getNat =
\x:Nat+Bool.
case x of
inl n => n
| inr b => if b then 1 else 0
>>
*)
(** More formally... *)
(** Syntax:
<<
t ::= Terms
| ...
| inl T t tagging (left)
| inr T t tagging (right)
| case t of case
inl x => t
| inr x => t
v ::= Values
| ...
| inl T v tagged value (left)
| inr T v tagged value (right)
T ::= Types
| ...
| T + T sum type
>>
*)
(** Evaluation:
t1 ==> t1'
---------------------- (ST_Inl)
inl T t1 ==> inl T t1'
t1 ==> t1'
---------------------- (ST_Inr)
inr T t1 ==> inr T t1'
t0 ==> t0'
------------------------------------------- (ST_Case)
case t0 of inl x1 => t1 | inr x2 => t2 ==>
case t0' of inl x1 => t1 | inr x2 => t2
---------------------------------------------- (ST_CaseInl)
case (inl T v0) of inl x1 => t1 | inr x2 => t2
==> [x1:=v0]t1
---------------------------------------------- (ST_CaseInr)
case (inr T v0) of inl x1 => t1 | inr x2 => t2
==> [x2:=v0]t2
*)
(** Typing:
Gamma |- t1 : T1
---------------------------- (T_Inl)
Gamma |- inl T2 t1 : T1 + T2
Gamma |- t1 : T2
---------------------------- (T_Inr)
Gamma |- inr T1 t1 : T1 + T2
Gamma |- t0 : T1+T2
Gamma , x1:T1 |- t1 : T
Gamma , x2:T2 |- t2 : T
--------------------------------------------------- (T_Case)
Gamma |- case t0 of inl x1 => t1 | inr x2 => t2 : T
We use the type annotation in [inl] and [inr] to make the typing
simpler, similarly to what we did for functions. *)
(** Without this extra
information, the typing rule [T_Inl], for example, would have to
say that, once we have shown that [t1] is an element of type [T1],
we can derive that [inl t1] is an element of [T1 + T2] for _any_
type T2. For example, we could derive both [inl 5 : Nat + Nat]
and [inl 5 : Nat + Bool] (and infinitely many other types).
This failure of uniqueness of types would mean that we cannot
build a typechecking algorithm simply by "reading the rules from
bottom to top" as we could for all the other features seen so far.
There are various ways to deal with this difficulty. One simple
one -- which we've adopted here -- forces the programmer to
explicitly annotate the "other side" of a sum type when performing
an injection. This is rather heavyweight for programmers (and so
real languages adopt other solutions), but it is easy to
understand and formalize. *)
(** ** Lists *)
(** The typing features we have seen can be classified into _base
types_ like [Bool], and _type constructors_ like [->] and [*] that
build new types from old ones. Another useful type constructor is
[List]. For every type [T], the type [List T] describes
finite-length lists whose elements are drawn from [T].
In principle, we could encode lists using pairs, sums and
_recursive_ types. But giving semantics to recursive types is
non-trivial. Instead, we'll just discuss the special case of lists
directly.
Below we give the syntax, semantics, and typing rules for lists.
Except for the fact that explicit type annotations are mandatory
on [nil] and cannot appear on [cons], these lists are essentially
identical to those we built in Coq. We use [lcase] to destruct
lists, to avoid dealing with questions like "what is the [head] of
the empty list?" *)
(** For example, here is a function that calculates the sum of
the first two elements of a list of numbers:
<<
\x:List Nat.
lcase x of nil -> 0
| a::x' -> lcase x' of nil -> a
| b::x'' -> a+b
>>
*)
(**
Syntax:
<<
t ::= Terms
| ...
| nil T
| cons t t
| lcase t of nil -> t | x::x -> t
v ::= Values
| ...
| nil T nil value
| cons v v cons value
T ::= Types
| ...
| List T list of Ts
>>
*)
(** Reduction:
t1 ==> t1'
-------------------------- (ST_Cons1)
cons t1 t2 ==> cons t1' t2
t2 ==> t2'
-------------------------- (ST_Cons2)
cons v1 t2 ==> cons v1 t2'
t1 ==> t1'
---------------------------------------- (ST_Lcase1)
(lcase t1 of nil -> t2 | xh::xt -> t3) ==>
(lcase t1' of nil -> t2 | xh::xt -> t3)
----------------------------------------- (ST_LcaseNil)
(lcase nil T of nil -> t2 | xh::xt -> t3)
==> t2
----------------------------------------------- (ST_LcaseCons)
(lcase (cons vh vt) of nil -> t2 | xh::xt -> t3)
==> [xh:=vh,xt:=vt]t3
*)
(** Typing:
----------------------- (T_Nil)
Gamma |- nil T : List T
Gamma |- t1 : T Gamma |- t2 : List T
----------------------------------------- (T_Cons)
Gamma |- cons t1 t2: List T
Gamma |- t1 : List T1
Gamma |- t2 : T
Gamma , h:T1, t:List T1 |- t3 : T
------------------------------------------------- (T_Lcase)
Gamma |- (lcase t1 of nil -> t2 | h::t -> t3) : T
*)
(** ** General Recursion *)
(** Another facility found in most programming languages (including
Coq) is the ability to define recursive functions. For example,
we might like to be able to define the factorial function like
this:
<<
fact = \x:Nat.
if x=0 then 1 else x * (fact (pred x)))
>>
But this would require quite a bit of work to formalize: we'd have
to introduce a notion of "function definitions" and carry around an
"environment" of such definitions in the definition of the [step]
relation. *)
(** Here is another way that is straightforward to formalize: instead
of writing recursive definitions where the right-hand side can
contain the identifier being defined, we can define a _fixed-point
operator_ that performs the "unfolding" of the recursive definition
in the right-hand side lazily during reduction.
<<
fact =
fix
(\f:Nat->Nat.
\x:Nat.
if x=0 then 1 else x * (f (pred x)))
>>
*)
(** The intuition is that the higher-order function [f] passed
to [fix] is a _generator_ for the [fact] function: if [fact] is
applied to a function that approximates the desired behavior of
[fact] up to some number [n] (that is, a function that returns
correct results on inputs less than or equal to [n]), then it
returns a better approximation to [fact] -- a function that returns
correct results for inputs up to [n+1]. Applying [fix] to this
generator returns its _fixed point_ -- a function that gives the
desired behavior for all inputs [n].
(The term "fixed point" has exactly the same sense as in ordinary
mathematics, where a fixed point of a function [f] is an input [x]
such that [f(x) = x]. Here, a fixed point of a function [F] of
type (say) [(Nat->Nat)->(Nat->Nat)] is a function [f] such that [F
f] is behaviorally equivalent to [f].) *)
(** Syntax:
<<
t ::= Terms
| ...
| fix t fixed-point operator
>>
Reduction:
t1 ==> t1'
------------------ (ST_Fix1)
fix t1 ==> fix t1'
F = \xf:T1.t2
----------------------- (ST_FixAbs)
fix F ==> [xf:=fix F]t2
Typing:
Gamma |- t1 : T1->T1
-------------------- (T_Fix)
Gamma |- fix t1 : T1
*)
(** Let's see how [ST_FixAbs] works by reducing [fact 3 = fix F 3],
where [F = (\f. \x. if x=0 then 1 else x * (f (pred x)))] (we are
omitting type annotations for brevity here).
<<
fix F 3
>>
[==>] [ST_FixAbs]
<<
(\x. if x=0 then 1 else x * (fix F (pred x))) 3
>>
[==>] [ST_AppAbs]
<<
if 3=0 then 1 else 3 * (fix F (pred 3))
>>
[==>] [ST_If0_Nonzero]
<<
3 * (fix F (pred 3))
>>
[==>] [ST_FixAbs + ST_Mult2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 3))
>>
[==>] [ST_PredNat + ST_Mult2 + ST_App2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 2)
>>
[==>] [ST_AppAbs + ST_Mult2]
<<
3 * (if 2=0 then 1 else 2 * (fix F (pred 2)))
>>
[==>] [ST_If0_Nonzero + ST_Mult2]
<<
3 * (2 * (fix F (pred 2)))
>>
[==>] [ST_FixAbs + 2 x ST_Mult2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 2)))
>>
[==>] [ST_PredNat + 2 x ST_Mult2 + ST_App2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 1))
>>
[==>] [ST_AppAbs + 2 x ST_Mult2]
<<
3 * (2 * (if 1=0 then 1 else 1 * (fix F (pred 1))))
>>
[==>] [ST_If0_Nonzero + 2 x ST_Mult2]
<<
3 * (2 * (1 * (fix F (pred 1))))
>>
[==>] [ST_FixAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 1))))
>>
[==>] [ST_PredNat + 3 x ST_Mult2 + ST_App2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 0)))
>>
[==>] [ST_AppAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * (if 0=0 then 1 else 0 * (fix F (pred 0)))))
>>
[==>] [ST_If0Zero + 3 x ST_Mult2]
<<
3 * (2 * (1 * 1))
>>
[==>] [ST_MultNats + 2 x ST_Mult2]
<<
3 * (2 * 1)
>>
[==>] [ST_MultNats + ST_Mult2]
<<
3 * 2
>>
[==>] [ST_MultNats]
<<
6
>>
*)
(** **** Exercise: 1 star, optional (halve_fix) *)
(** Translate this informal recursive definition into one using [fix]:
<<
halve =
\x:Nat.
if x=0 then 0
else if (pred x)=0 then 0
else 1 + (halve (pred (pred x))))
>>
(* FILL IN HERE *)
[]
*)
(** **** Exercise: 1 star, optional (fact_steps) *)
(** Write down the sequence of steps that the term [fact 1] goes
through to reduce to a normal form (assuming the usual reduction
rules for arithmetic operations).
(* FILL IN HERE *)
[]
*)
(** The ability to form the fixed point of a function of type [T->T]
for any [T] has some surprising consequences. In particular, it
implies that _every_ type is inhabited by some term. To see this,
observe that, for every type [T], we can define the term
fix (\x:T.x)
By [T_Fix] and [T_Abs], this term has type [T]. By [ST_FixAbs]
it reduces to itself, over and over again. Thus it is an
_undefined element_ of [T].
More usefully, here's an example using [fix] to define a
two-argument recursive function:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
And finally, here is an example where [fix] is used to define a
_pair_ of recursive functions (illustrating the fact that the type
[T1] in the rule [T_Fix] need not be a function type):
<<
evenodd =
fix
(\eo: (Nat->Bool * Nat->Bool).
let e = \n:Nat. if n=0 then true else eo.snd (pred n) in
let o = \n:Nat. if n=0 then false else eo.fst (pred n) in
(e,o))
even = evenodd.fst
odd = evenodd.snd
>>
*)
(* ###################################################################### *)
(** ** Records *)
(** As a final example of a basic extension of the STLC, let's
look briefly at how to define _records_ and their types.
Intuitively, records can be obtained from pairs by two kinds of
generalization: they are n-ary products (rather than just binary)
and their fields are accessed by _label_ (rather than position).
Conceptually, this extension is a straightforward generalization
of pairs and product types, but notationally it becomes a little
heavier; for this reason, we postpone its formal treatment to a
separate chapter ([Records]). *)
(** Records are not included in the extended exercise below, but
they will be useful to motivate the [Sub] chapter. *)
(** Syntax:
<<
t ::= Terms
| ...
| {i1=t1, ..., in=tn} record
| t.i projection
v ::= Values
| ...
| {i1=v1, ..., in=vn} record value
T ::= Types
| ...
| {i1:T1, ..., in:Tn} record type
>>
Intuitively, the generalization is pretty obvious. But it's worth
noticing that what we've actually written is rather informal: in
particular, we've written "[...]" in several places to mean "any
number of these," and we've omitted explicit mention of the usual
side-condition that the labels of a record should not contain
repetitions. *)
(** It is possible to devise informal notations that are
more precise, but these tend to be quite heavy and to obscure the
main points of the definitions. So we'll leave these a bit loose
here (they are informal anyway, after all) and do the work of
tightening things up elsewhere (in chapter [Records]). *)
(**
Reduction:
ti ==> ti'
------------------------------------ (ST_Rcd)
{i1=v1, ..., im=vm, in=ti, ...}
==> {i1=v1, ..., im=vm, in=ti', ...}
t1 ==> t1'
-------------- (ST_Proj1)
t1.i ==> t1'.i
------------------------- (ST_ProjRcd)
{..., i=vi, ...}.i ==> vi
Again, these rules are a bit informal. For example, the first rule
is intended to be read "if [ti] is the leftmost field that is not a
value and if [ti] steps to [ti'], then the whole record steps..."
In the last rule, the intention is that there should only be one
field called i, and that all the other fields must contain values. *)
(**
Typing:
Gamma |- t1 : T1 ... Gamma |- tn : Tn
-------------------------------------------------- (T_Rcd)
Gamma |- {i1=t1, ..., in=tn} : {i1:T1, ..., in:Tn}
Gamma |- t : {..., i:Ti, ...}
----------------------------- (T_Proj)
Gamma |- t.i : Ti
*)
(* ###################################################################### *)
(** *** Encoding Records (Optional) *)
(** There are several ways to make the above definitions precise.
- We can directly formalize the syntactic forms and inference
rules, staying as close as possible to the form we've given
them above. This is conceptually straightforward, and it's
probably what we'd want to do if we were building a real
compiler -- in particular, it will allow is to print error
messages in the form that programmers will find easy to
understand. But the formal versions of the rules will not be
pretty at all!
- We could look for a smoother way of presenting records -- for
example, a binary presentation with one constructor for the
empty record and another constructor for adding a single field
to an existing record, instead of a single monolithic
constructor that builds a whole record at once. This is the
right way to go if we are primarily interested in studying the
metatheory of the calculi with records, since it leads to
clean and elegant definitions and proofs. Chapter [Records]
shows how this can be done.
- Alternatively, if we like, we can avoid formalizing records
altogether, by stipulating that record notations are just
informal shorthands for more complex expressions involving
pairs and product types. We sketch this approach here.
First, observe that we can encode arbitrary-size tuples using
nested pairs and the [unit] value. To avoid overloading the pair
notation [(t1,t2)], we'll use curly braces without labels to write
down tuples, so [{}] is the empty tuple, [{5}] is a singleton
tuple, [{5,6}] is a 2-tuple (morally the same as a pair),
[{5,6,7}] is a triple, etc.
<<
{} ----> unit
{t1, t2, ..., tn} ----> (t1, trest)
where {t2, ..., tn} ----> trest
>>
Similarly, we can encode tuple types using nested product types:
<<
{} ----> Unit
{T1, T2, ..., Tn} ----> T1 * TRest
where {T2, ..., Tn} ----> TRest
>>
The operation of projecting a field from a tuple can be encoded
using a sequence of second projections followed by a first projection:
<<
t.0 ----> t.fst
t.(n+1) ----> (t.snd).n
>>
Next, suppose that there is some total ordering on record labels,
so that we can associate each label with a unique natural number.
This number is called the _position_ of the label. For example,
we might assign positions like this:
<<
LABEL POSITION
a 0
b 1
c 2
... ...
foo 1004
... ...
bar 10562
... ...
>>
We use these positions to encode record values as tuples (i.e., as
nested pairs) by sorting the fields according to their positions.
For example:
<<
{a=5, b=6} ----> {5,6}
{a=5, c=7} ----> {5,unit,7}
{c=7, a=5} ----> {5,unit,7}
{c=5, b=3} ----> {unit,3,5}
{f=8,c=5,a=7} ----> {7,unit,5,unit,unit,8}
{f=8,c=5} ----> {unit,unit,5,unit,unit,8}
>>
Note that each field appears in the position associated with its
label, that the size of the tuple is determined by the label with
the highest position, and that we fill in unused positions with
[unit].
We do exactly the same thing with record types:
<<
{a:Nat, b:Nat} ----> {Nat,Nat}
{c:Nat, a:Nat} ----> {Nat,Unit,Nat}
{f:Nat,c:Nat} ----> {Unit,Unit,Nat,Unit,Unit,Nat}
>>
Finally, record projection is encoded as a tuple projection from
the appropriate position:
<<
t.l ----> t.(position of l)
>>
It is not hard to check that all the typing rules for the original
"direct" presentation of records are validated by this
encoding. (The reduction rules are "almost validated" -- not
quite, because the encoding reorders fields.) *)
(** Of course, this encoding will not be very efficient if we
happen to use a record with label [bar]! But things are not
actually as bad as they might seem: for example, if we assume that
our compiler can see the whole program at the same time, we can
_choose_ the numbering of labels so that we assign small positions
to the most frequently used labels. Indeed, there are industrial
compilers that essentially do this! *)
(** *** Variants (Optional Reading) *)
(** Just as products can be generalized to records, sums can be
generalized to n-ary labeled types called _variants_. Instead of
[T1+T2], we can write something like [<l1:T1,l2:T2,...ln:Tn>]
where [l1],[l2],... are field labels which are used both to build
instances and as case arm labels.
These n-ary variants give us almost enough mechanism to build
arbitrary inductive data types like lists and trees from
scratch -- the only thing missing is a way to allow _recursion_ in
type definitions. We won't cover this here, but detailed
treatments can be found in many textbooks -- e.g., Types and
Programming Languages. *)
(* ###################################################################### *)
(** * Exercise: Formalizing the Extensions *)
(** **** Exercise: 4 stars, optional (STLC_extensions) *)
(** In this problem you will formalize a couple of the extensions
described above. We've provided the necessary additions to the
syntax of terms and types, and we've included a few examples that
you can test your definitions with to make sure they are working
as expected. You'll fill in the rest of the definitions and
extend all the proofs accordingly.
To get you started, we've provided implementations for:
- numbers
- pairs and units
- sums
- lists
You need to complete the implementations for:
- let (which involves binding)
- [fix]
A good strategy is to work on the extensions one at a time, in
multiple passes, rather than trying to work through the file from
start to finish in a single pass. For each definition or proof,
begin by reading carefully through the parts that are provided for
you, referring to the text in the [Stlc] chapter for high-level
intuitions and the embedded comments for detailed mechanics.
*)
Module STLCExtended.
(* ###################################################################### *)
(** *** Syntax and Operational Semantics *)
Inductive ty : Type :=
| TArrow : ty -> ty -> ty
| TNat : ty
| TUnit : ty
| TProd : ty -> ty -> ty
| TSum : ty -> ty -> ty
| TList : ty -> ty.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TArrow" | Case_aux c "TNat"
| Case_aux c "TProd" | Case_aux c "TUnit"
| Case_aux c "TSum" | Case_aux c "TList" ].
Inductive tm : Type :=
(* pure STLC *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
(* numbers *)
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm
(* pairs *)
| tpair : tm -> tm -> tm
| tfst : tm -> tm
| tsnd : tm -> tm
(* units *)
| tunit : tm
(* let *)
| tlet : id -> tm -> tm -> tm
(* i.e., [let x = t1 in t2] *)
(* sums *)
| tinl : ty -> tm -> tm
| tinr : ty -> tm -> tm
| tcase : tm -> id -> tm -> id -> tm -> tm
(* i.e., [case t0 of inl x1 => t1 | inr x2 => t2] *)
(* lists *)
| tnil : ty -> tm
| tcons : tm -> tm -> tm
| tlcase : tm -> tm -> id -> id -> tm -> tm
(* i.e., [lcase t1 of | nil -> t2 | x::y -> t3] *)
(* fix *)
| tfix : tm -> tm.
(** Note that, for brevity, we've omitted booleans and instead
provided a single [if0] form combining a zero test and a
conditional. That is, instead of writing
<<
if x = 0 then ... else ...
>>
we'll write this:
<<
if0 x then ... else ...
>>
*)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"
| Case_aux c "tnat" | Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd"
| Case_aux c "tunit" | Case_aux c "tlet"
| Case_aux c "tinl" | Case_aux c "tinr" | Case_aux c "tcase"
| Case_aux c "tnil" | Case_aux c "tcons" | Case_aux c "tlcase"
| Case_aux c "tfix" ].
(* ###################################################################### *)
(** *** Substitution *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tnat n =>
tnat n
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tpair t1 t2 =>
tpair (subst x s t1) (subst x s t2)
| tfst t1 =>
tfst (subst x s t1)
| tsnd t1 =>
tsnd (subst x s t1)
| tunit => tunit
(* FILL IN HERE *)
| tinl T t1 =>
tinl T (subst x s t1)
| tinr T t1 =>
tinr T (subst x s t1)
| tcase t0 y1 t1 y2 t2 =>
tcase (subst x s t0)
y1 (if eq_id_dec x y1 then t1 else (subst x s t1))
y2 (if eq_id_dec x y2 then t2 else (subst x s t2))
| tnil T =>
tnil T
| tcons t1 t2 =>
tcons (subst x s t1) (subst x s t2)
| tlcase t1 t2 y1 y2 t3 =>
tlcase (subst x s t1) (subst x s t2) y1 y2
(if eq_id_dec x y1 then
t3
else if eq_id_dec x y2 then t3
else (subst x s t3))
(* FILL IN HERE *)
| _ => t (* ... and delete this line *)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** *** Reduction *)
(** Next we define the values of our language. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T11 t12,
value (tabs x T11 t12)
(* Numbers are values: *)
| v_nat : forall n1,
value (tnat n1)
(* A pair is a value if both components are: *)
| v_pair : forall v1 v2,
value v1 ->
value v2 ->
value (tpair v1 v2)
(* A unit is always a value *)
| v_unit : value tunit
(* A tagged value is a value: *)
| v_inl : forall v T,
value v ->
value (tinl T v)
| v_inr : forall v T,
value v ->
value (tinr T v)
(* A list is a value iff its head and tail are values: *)
| v_lnil : forall T, value (tnil T)
| v_lcons : forall v1 vl,
value v1 ->
value vl ->
value (tcons v1 vl)
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T11 t12 v2,
value v2 ->
(tapp (tabs x T11 t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
(* nats *)
| ST_Succ1 : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
| ST_SuccNat : forall n1,
(tsucc (tnat n1)) ==> (tnat (S n1))
| ST_Pred : forall t1 t1',
t1 ==> t1' ->
(tpred t1) ==> (tpred t1')
| ST_PredNat : forall n1,
(tpred (tnat n1)) ==> (tnat (pred n1))
| ST_Mult1 : forall t1 t1' t2,
t1 ==> t1' ->
(tmult t1 t2) ==> (tmult t1' t2)
| ST_Mult2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tmult v1 t2) ==> (tmult v1 t2')
| ST_MultNats : forall n1 n2,
(tmult (tnat n1) (tnat n2)) ==> (tnat (mult n1 n2))
| ST_If01 : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif0 t1 t2 t3) ==> (tif0 t1' t2 t3)
| ST_If0Zero : forall t2 t3,
(tif0 (tnat 0) t2 t3) ==> t2
| ST_If0Nonzero : forall n t2 t3,
(tif0 (tnat (S n)) t2 t3) ==> t3
(* pairs *)
| ST_Pair1 : forall t1 t1' t2,
t1 ==> t1' ->
(tpair t1 t2) ==> (tpair t1' t2)
| ST_Pair2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tpair v1 t2) ==> (tpair v1 t2')
| ST_Fst1 : forall t1 t1',
t1 ==> t1' ->
(tfst t1) ==> (tfst t1')
| ST_FstPair : forall v1 v2,
value v1 ->
value v2 ->
(tfst (tpair v1 v2)) ==> v1
| ST_Snd1 : forall t1 t1',
t1 ==> t1' ->
(tsnd t1) ==> (tsnd t1')
| ST_SndPair : forall v1 v2,
value v1 ->
value v2 ->
(tsnd (tpair v1 v2)) ==> v2
(* let *)
(* FILL IN HERE *)
(* sums *)
| ST_Inl : forall t1 t1' T,
t1 ==> t1' ->
(tinl T t1) ==> (tinl T t1')
| ST_Inr : forall t1 t1' T,
t1 ==> t1' ->
(tinr T t1) ==> (tinr T t1')
| ST_Case : forall t0 t0' x1 t1 x2 t2,
t0 ==> t0' ->
(tcase t0 x1 t1 x2 t2) ==> (tcase t0' x1 t1 x2 t2)
| ST_CaseInl : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinl T v0) x1 t1 x2 t2) ==> [x1:=v0]t1
| ST_CaseInr : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinr T v0) x1 t1 x2 t2) ==> [x2:=v0]t2
(* lists *)
| ST_Cons1 : forall t1 t1' t2,
t1 ==> t1' ->
(tcons t1 t2) ==> (tcons t1' t2)
| ST_Cons2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tcons v1 t2) ==> (tcons v1 t2')
| ST_Lcase1 : forall t1 t1' t2 x1 x2 t3,
t1 ==> t1' ->
(tlcase t1 t2 x1 x2 t3) ==> (tlcase t1' t2 x1 x2 t3)
| ST_LcaseNil : forall T t2 x1 x2 t3,
(tlcase (tnil T) t2 x1 x2 t3) ==> t2
| ST_LcaseCons : forall v1 vl t2 x1 x2 t3,
value v1 ->
value vl ->
(tlcase (tcons v1 vl) t2 x1 x2 t3) ==> (subst x2 vl (subst x1 v1 t3))
(* fix *)
(* FILL IN HERE *)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"
| Case_aux c "ST_Succ1" | Case_aux c "ST_SuccNat"
| Case_aux c "ST_Pred1" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_MultNats" | Case_aux c "ST_If01"
| Case_aux c "ST_If0Zero" | Case_aux c "ST_If0Nonzero"
| Case_aux c "ST_Pair1" | Case_aux c "ST_Pair2"
| Case_aux c "ST_Fst1" | Case_aux c "ST_FstPair"
| Case_aux c "ST_Snd1" | Case_aux c "ST_SndPair"
(* FILL IN HERE *)
| Case_aux c "ST_Inl" | Case_aux c "ST_Inr" | Case_aux c "ST_Case"
| Case_aux c "ST_CaseInl" | Case_aux c "ST_CaseInr"
| Case_aux c "ST_Cons1" | Case_aux c "ST_Cons2" | Case_aux c "ST_Lcase1"
| Case_aux c "ST_LcaseNil" | Case_aux c "ST_LcaseCons"
(* FILL IN HERE *)
].
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Hint Constructors step.
(* ###################################################################### *)
(** *** Typing *)
Definition context := partial_map ty.
(** Next we define the typing rules. These are nearly direct
transcriptions of the inference rules shown above. *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Typing rules for proper terms *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
(* nats *)
| T_Nat : forall Gamma n1,
Gamma |- (tnat n1) \in TNat
| T_Succ : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tsucc t1) \in TNat
| T_Pred : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tpred t1) \in TNat
| T_Mult : forall Gamma t1 t2,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in TNat ->
Gamma |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma t1 t2 t3 T1,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in T1 ->
Gamma |- t3 \in T1 ->
Gamma |- (tif0 t1 t2 t3) \in T1
(* pairs *)
| T_Pair : forall Gamma t1 t2 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in T2 ->
Gamma |- (tpair t1 t2) \in (TProd T1 T2)
| T_Fst : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tfst t) \in T1
| T_Snd : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tsnd t) \in T2
(* unit *)
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* let *)
(* FILL IN HERE *)
(* sums *)
| T_Inl : forall Gamma t1 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- (tinl T2 t1) \in (TSum T1 T2)
| T_Inr : forall Gamma t2 T1 T2,
Gamma |- t2 \in T2 ->
Gamma |- (tinr T1 t2) \in (TSum T1 T2)
| T_Case : forall Gamma t0 x1 T1 t1 x2 T2 t2 T,
Gamma |- t0 \in (TSum T1 T2) ->
(extend Gamma x1 T1) |- t1 \in T ->
(extend Gamma x2 T2) |- t2 \in T ->
Gamma |- (tcase t0 x1 t1 x2 t2) \in T
(* lists *)
| T_Nil : forall Gamma T,
Gamma |- (tnil T) \in (TList T)
| T_Cons : forall Gamma t1 t2 T1,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in (TList T1) ->
Gamma |- (tcons t1 t2) \in (TList T1)
| T_Lcase : forall Gamma t1 T1 t2 x1 x2 t3 T2,
Gamma |- t1 \in (TList T1) ->
Gamma |- t2 \in T2 ->
(extend (extend Gamma x2 (TList T1)) x1 T1) |- t3 \in T2 ->
Gamma |- (tlcase t1 t2 x1 x2 t3) \in T2
(* fix *)
(* FILL IN HERE *)
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd"
| Case_aux c "T_Unit"
(* let *)
(* FILL IN HERE *)
| Case_aux c "T_Inl" | Case_aux c "T_Inr" | Case_aux c "T_Case"
| Case_aux c "T_Nil" | Case_aux c "T_Cons" | Case_aux c "T_Lcase"
(* fix *)
(* FILL IN HERE *)
].
(* ###################################################################### *)
(** ** Examples *)
(** This section presents formalized versions of the examples from
above (plus several more). The ones at the beginning focus on
specific features; you can use these to make sure your definition
of a given feature is reasonable before moving on to extending the
proofs later in the file with the cases relating to this feature.
The later examples require all the features together, so you'll
need to come back to these when you've got all the definitions
filled in. *)
Module Examples.
(** *** Preliminaries *)
(** First, let's define a few variable names: *)
Notation a := (Id 0).
Notation f := (Id 1).
Notation g := (Id 2).
Notation l := (Id 3).
Notation k := (Id 6).
Notation i1 := (Id 7).
Notation i2 := (Id 8).
Notation x := (Id 9).
Notation y := (Id 10).
Notation processSum := (Id 11).
Notation n := (Id 12).
Notation eq := (Id 13).
Notation m := (Id 14).
Notation evenodd := (Id 15).
Notation even := (Id 16).
Notation odd := (Id 17).
Notation eo := (Id 18).
(** Next, a bit of Coq hackery to automate searching for typing
derivations. You don't need to understand this bit in detail --
just have a look over it so that you'll know what to look for if
you ever find yourself needing to make custom extensions to
[auto].
The following [Hint] declarations say that, whenever [auto]
arrives at a goal of the form [(Gamma |- (tapp e1 e1) \in T)], it
should consider [eapply T_App], leaving an existential variable
for the middle type T1, and similar for [lcase]. That variable
will then be filled in during the search for type derivations for
[e1] and [e2]. We also include a hint to "try harder" when
solving equality goals; this is useful to automate uses of
[T_Var] (which includes an equality as a precondition). *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
(* You'll want to uncomment the following line once
you've defined the [T_Lcase] constructor for the typing
relation: *)
(*
Hint Extern 2 (has_type _ (tlcase _ _ _ _ _) _) =>
eapply T_Lcase; auto.
*)
Hint Extern 2 (_ = _) => compute; reflexivity.
(** *** Numbers *)
Module Numtest.
(* if0 (pred (succ (pred (2 * 0))) then 5 else 6 *)
Definition test :=
tif0
(tpred
(tsucc
(tpred
(tmult
(tnat 2)
(tnat 0)))))
(tnat 5)
(tnat 6).
(** Remove the comment braces once you've implemented enough of the
definitions that you think this should work. *)
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof.
unfold test.
(* This typing derivation is quite deep, so we need to increase the
max search depth of [auto] from the default 5 to 10. *)
auto 10.
Qed.
Example numtest_reduces :
test ==>* tnat 5.
Proof.
unfold test. normalize.
Qed.
*)
End Numtest.
(** *** Products *)
Module Prodtest.
(* ((5,6),7).fst.snd *)
Definition test :=
tsnd
(tfst
(tpair
(tpair
(tnat 5)
(tnat 6))
(tnat 7))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End Prodtest.
(** *** [let] *)
Module LetTest.
(* let x = pred 6 in succ x *)
Definition test :=
tlet
x
(tpred (tnat 6))
(tsucc (tvar x)).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End LetTest.
(** *** Sums *)
Module Sumtest1.
(* case (inl Nat 5) of
inl x => x
| inr y => y *)
Definition test :=
tcase (tinl TNat (tnat 5))
x (tvar x)
y (tvar y).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tnat 5).
Proof. unfold test. normalize. Qed.
*)
End Sumtest1.
Module Sumtest2.
(* let processSum =
\x:Nat+Nat.
case x of
inl n => n
inr n => if0 n then 1 else 0 in
(processSum (inl Nat 5), processSum (inr Nat 5)) *)
Definition test :=
tlet
processSum
(tabs x (TSum TNat TNat)
(tcase (tvar x)
n (tvar n)
n (tif0 (tvar n) (tnat 1) (tnat 0))))
(tpair
(tapp (tvar processSum) (tinl TNat (tnat 5)))
(tapp (tvar processSum) (tinr TNat (tnat 5)))).
(*
Example typechecks :
(@empty ty) |- test \in (TProd TNat TNat).
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tpair (tnat 5) (tnat 0)).
Proof. unfold test. normalize. Qed.
*)
End Sumtest2.
(** *** Lists *)
Module ListTest.
(* let l = cons 5 (cons 6 (nil Nat)) in
lcase l of
nil => 0
| x::y => x*x *)
Definition test :=
tlet l
(tcons (tnat 5) (tcons (tnat 6) (tnil TNat)))
(tlcase (tvar l)
(tnat 0)
x y (tmult (tvar x) (tvar x))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 20. Qed.
Example reduces :
test ==>* (tnat 25).
Proof. unfold test. normalize. Qed.
*)
End ListTest.
(** *** [fix] *)
Module FixTest1.
(* fact := fix
(\f:nat->nat.
\a:nat.
if a=0 then 1 else a * (f (pred a))) *)
Definition fact :=
tfix
(tabs f (TArrow TNat TNat)
(tabs a TNat
(tif0
(tvar a)
(tnat 1)
(tmult
(tvar a)
(tapp (tvar f) (tpred (tvar a))))))).
(** (Warning: you may be able to typecheck [fact] but still have some
rules wrong!) *)
(*
Example fact_typechecks :
(@empty ty) |- fact \in (TArrow TNat TNat).
Proof. unfold fact. auto 10.
Qed.
*)
(*
Example fact_example:
(tapp fact (tnat 4)) ==>* (tnat 24).
Proof. unfold fact. normalize. Qed.
*)
End FixTest1.
Module FixTest2.
(* map :=
\g:nat->nat.
fix
(\f:[nat]->[nat].
\l:[nat].
case l of
| [] -> []
| x::l -> (g x)::(f l)) *)
Definition map :=
tabs g (TArrow TNat TNat)
(tfix
(tabs f (TArrow (TList TNat) (TList TNat))
(tabs l (TList TNat)
(tlcase (tvar l)
(tnil TNat)
a l (tcons (tapp (tvar g) (tvar a))
(tapp (tvar f) (tvar l))))))).
(*
(* Make sure you've uncommented the last [Hint Extern] above... *)
Example map_typechecks :
empty |- map \in
(TArrow (TArrow TNat TNat)
(TArrow (TList TNat)
(TList TNat))).
Proof. unfold map. auto 10. Qed.
Example map_example :
tapp (tapp map (tabs a TNat (tsucc (tvar a))))
(tcons (tnat 1) (tcons (tnat 2) (tnil TNat)))
==>* (tcons (tnat 2) (tcons (tnat 3) (tnil TNat))).
Proof. unfold map. normalize. Qed.
*)
End FixTest2.
Module FixTest3.
(* equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if0 m then (if0 n then 1 else 0)
else if0 n then 0
else eq (pred m) (pred n)) *)
Definition equal :=
tfix
(tabs eq (TArrow TNat (TArrow TNat TNat))
(tabs m TNat
(tabs n TNat
(tif0 (tvar m)
(tif0 (tvar n) (tnat 1) (tnat 0))
(tif0 (tvar n)
(tnat 0)
(tapp (tapp (tvar eq)
(tpred (tvar m)))
(tpred (tvar n)))))))).
(*
Example equal_typechecks :
(@empty ty) |- equal \in (TArrow TNat (TArrow TNat TNat)).
Proof. unfold equal. auto 10.
Qed.
*)
(*
Example equal_example1:
(tapp (tapp equal (tnat 4)) (tnat 4)) ==>* (tnat 1).
Proof. unfold equal. normalize. Qed.
*)
(*
Example equal_example2:
(tapp (tapp equal (tnat 4)) (tnat 5)) ==>* (tnat 0).
Proof. unfold equal. normalize. Qed.
*)
End FixTest3.
Module FixTest4.
(* let evenodd =
fix
(\eo: (Nat->Nat * Nat->Nat).
let e = \n:Nat. if0 n then 1 else eo.snd (pred n) in
let o = \n:Nat. if0 n then 0 else eo.fst (pred n) in
(e,o)) in
let even = evenodd.fst in
let odd = evenodd.snd in
(even 3, even 4)
*)
Definition eotest :=
tlet evenodd
(tfix
(tabs eo (TProd (TArrow TNat TNat) (TArrow TNat TNat))
(tpair
(tabs n TNat
(tif0 (tvar n)
(tnat 1)
(tapp (tsnd (tvar eo)) (tpred (tvar n)))))
(tabs n TNat
(tif0 (tvar n)
(tnat 0)
(tapp (tfst (tvar eo)) (tpred (tvar n))))))))
(tlet even (tfst (tvar evenodd))
(tlet odd (tsnd (tvar evenodd))
(tpair
(tapp (tvar even) (tnat 3))
(tapp (tvar even) (tnat 4))))).
(*
Example eotest_typechecks :
(@empty ty) |- eotest \in (TProd TNat TNat).
Proof. unfold eotest. eauto 30.
Qed.
*)
(*
Example eotest_example1:
eotest ==>* (tpair (tnat 0) (tnat 1)).
Proof. unfold eotest. normalize. Qed.
*)
End FixTest4.
End Examples.
(* ###################################################################### *)
(** ** Properties of Typing *)
(** The proofs of progress and preservation for this system are
essentially the same (though of course somewhat longer) as for the
pure simply typed lambda-calculus. *)
(* ###################################################################### *)
(** *** Progress *)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
(* Theorem: Suppose empty |- t : T. Then either
1. t is a value, or
2. t ==> t' for some t'.
Proof: By induction on the given typing derivation. *)
intros t T Ht.
remember (@empty ty) as Gamma.
generalize dependent HeqGamma.
has_type_cases (induction Ht) Case; intros HeqGamma; subst.
Case "T_Var".
(* The final rule in the given typing derivation cannot be [T_Var],
since it can never be the case that [empty |- x : T] (since the
context is empty). *)
inversion H.
Case "T_Abs".
(* If the [T_Abs] rule was the last used, then [t = tabs x T11 t12],
which is a value. *)
left...
Case "T_App".
(* If the last rule applied was T_App, then [t = t1 t2], and we know
from the form of the rule that
[empty |- t1 : T1 -> T2]
[empty |- t2 : T1]
By the induction hypothesis, each of t1 and t2 either is a value
or can take a step. *)
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
(* If both [t1] and [t2] are values, then we know that
[t1 = tabs x T11 t12], since abstractions are the only values
that can have an arrow type. But
[(tabs x T11 t12) t2 ==> [x:=t2]t12] by [ST_AppAbs]. *)
inversion H; subst; try (solve by inversion).
exists (subst x t2 t12)...
SSCase "t2 steps".
(* If [t1] is a value and [t2 ==> t2'], then [t1 t2 ==> t1 t2']
by [ST_App2]. *)
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
(* Finally, If [t1 ==> t1'], then [t1 t2 ==> t1' t2] by [ST_App1]. *)
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_Nat".
left...
Case "T_Succ".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (S n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsucc t1')...
Case "T_Pred".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (pred n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tpred t1')...
Case "T_Mult".
right.
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 is a value".
inversion H; subst; try solve by inversion.
inversion H0; subst; try solve by inversion.
exists (tnat (mult n1 n0))...
SSCase "t2 steps".
inversion H0 as [t2' Hstp].
exists (tmult t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tmult t1' t2)...
Case "T_If0".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
destruct n1 as [|n1'].
SSCase "n1=0".
exists t2...
SSCase "n1<>0".
exists t3...
SCase "t1 steps".
inversion H as [t1' H0].
exists (tif0 t1' t2 t3)...
Case "T_Pair".
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 steps".
right. inversion H0 as [t2' Hstp].
exists (tpair t1 t2')...
SCase "t1 steps".
right. inversion H as [t1' Hstp].
exists (tpair t1' t2)...
Case "T_Fst".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v1...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tfst t1')...
Case "T_Snd".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v2...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsnd t1')...
Case "T_Unit".
left...
(* let *)
(* FILL IN HERE *)
Case "T_Inl".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinl _ t1')... *)
Case "T_Inr".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinr _ t1')... *)
Case "T_Case".
right.
destruct IHHt1...
SCase "t0 is a value".
inversion H; subst; try solve by inversion.
SSCase "t0 is inl".
exists ([x1:=v]t1)...
SSCase "t0 is inr".
exists ([x2:=v]t2)...
SCase "t0 steps".
inversion H as [t0' Hstp].
exists (tcase t0' x1 t1 x2 t2)...
Case "T_Nil".
left...
Case "T_Cons".
destruct IHHt1...
SCase "head is a value".
destruct IHHt2...
SSCase "tail steps".
right. inversion H0 as [t2' Hstp].
exists (tcons t1 t2')...
SCase "head steps".
right. inversion H as [t1' Hstp].
exists (tcons t1' t2)...
Case "T_Lcase".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
SSCase "t1=tnil".
exists t2...
SSCase "t1=tcons v1 vl".
exists ([x2:=vl]([x1:=v1]t3))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tlcase t1' t2 x1 x2 t3)...
(* fix *)
(* FILL IN HERE *)
Qed.
(* ###################################################################### *)
(** *** Context Invariance *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
(* nats *)
| afi_succ : forall x t,
appears_free_in x t ->
appears_free_in x (tsucc t)
| afi_pred : forall x t,
appears_free_in x t ->
appears_free_in x (tpred t)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if01 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if02 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if03 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
(* pairs *)
| afi_pair1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tpair t1 t2)
| afi_pair2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tpair t1 t2)
| afi_fst : forall x t,
appears_free_in x t ->
appears_free_in x (tfst t)
| afi_snd : forall x t,
appears_free_in x t ->
appears_free_in x (tsnd t)
(* let *)
(* FILL IN HERE *)
(* sums *)
| afi_inl : forall x t T,
appears_free_in x t ->
appears_free_in x (tinl T t)
| afi_inr : forall x t T,
appears_free_in x t ->
appears_free_in x (tinr T t)
| afi_case0 : forall x t0 x1 t1 x2 t2,
appears_free_in x t0 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case1 : forall x t0 x1 t1 x2 t2,
x1 <> x ->
appears_free_in x t1 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case2 : forall x t0 x1 t1 x2 t2,
x2 <> x ->
appears_free_in x t2 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
(* lists *)
| afi_cons1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tcons t1 t2)
| afi_cons2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tcons t1 t2)
| afi_lcase1 : forall x t1 t2 y1 y2 t3,
appears_free_in x t1 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase2 : forall x t1 t2 y1 y2 t3,
appears_free_in x t2 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase3 : forall x t1 t2 y1 y2 t3,
y1 <> x ->
y2 <> x ->
appears_free_in x t3 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
(* fix *)
(* FILL IN HERE *)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros y Hafi.
unfold extend.
destruct (eq_id_dec x y)...
Case "T_Mult".
apply T_Mult...
Case "T_If0".
apply T_If0...
Case "T_Pair".
apply T_Pair...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
eapply T_Case...
apply IHhas_type2. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x2 y)...
Case "T_Cons".
apply T_Cons...
Case "T_Lcase".
eapply T_Lcase... apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
destruct (eq_id_dec x2 y)...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case; inversion Hafi; subst...
Case "T_Abs".
destruct IHHtyp as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "left".
destruct IHHtyp2 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
SCase "right".
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
Case "T_Lcase".
clear Htyp1 IHHtyp1 Htyp2 IHHtyp2.
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx... rewrite neq_id in Hctx...
Qed.
(* ###################################################################### *)
(** *** Substitution *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
(* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then
Gamma |- [x:=v]t : S. *)
intros Gamma x U v t S Htypt Htypv.
generalize dependent Gamma. generalize dependent S.
(* Proof: By induction on the term t. Most cases follow directly
from the IH, with the exception of tvar and tabs.
The former aren't automatic because we must reason about how the
variables interact. *)
t_cases (induction t) Case;
intros S Gamma Htypt; simpl; inversion Htypt; subst...
Case "tvar".
simpl. rename i into y.
(* If t = y, we know that
[empty |- v : U] and
[Gamma,x:U |- y : S]
and, by inversion, [extend Gamma x U y = Some S]. We want to
show that [Gamma |- [x:=v]y : S].
There are two cases to consider: either [x=y] or [x<>y]. *)
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then we know that [U = S], and that [[x:=v]y = v].
So what we really must show is that if [empty |- v : U] then
[Gamma |- v : U]. We have already proven a more general version
of this theorem, called context invariance. *)
subst.
unfold extend in H1. rewrite eq_id in H1.
inversion H1; subst. clear H1.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
(* If [x <> y], then [Gamma y = Some S] and the substitution has no
effect. We can show that [Gamma |- y : S] by [T_Var]. *)
apply T_Var... unfold extend in H1. rewrite neq_id in H1...
Case "tabs".
rename i into y. rename t into T11.
(* If [t = tabs y T11 t0], then we know that
[Gamma,x:U |- tabs y T11 t0 : T11->T12]
[Gamma,x:U,y:T11 |- t0 : T12]
[empty |- v : U]
As our IH, we know that forall S Gamma,
[Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 : S].
We can calculate that
[x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0)
And we must show that [Gamma |- [x:=v]t : T11->T12]. We know
we will do so using [T_Abs], so it remains to be shown that:
[Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12]
We consider two cases: [x = y] and [x <> y].
*)
apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then the substitution has no effect. Context
invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are
equivalent. Since the former context shows that [t0 : T12], so
does the latter. *)
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
(* If [x <> y], then the IH and context invariance allow us to show that
[Gamma,x:U,y:T11 |- t0 : T12] =>
[Gamma,y:T11,x:U |- t0 : T12] =>
[Gamma,y:T11 |- [x:=v]t0 : T12] *)
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
(* let *)
(* FILL IN HERE *)
Case "tcase".
rename i into x1. rename i0 into x2.
eapply T_Case...
SCase "left arm".
destruct (eq_id_dec x x1).
SSCase "x = x1".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
SSCase "x <> x1".
apply IHt2. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
subst. rewrite neq_id...
SCase "right arm".
destruct (eq_id_dec x x2).
SSCase "x = x2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
SSCase "x <> x2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
subst. rewrite neq_id...
Case "tlcase".
rename i into y1. rename i0 into y2.
eapply T_Lcase...
destruct (eq_id_dec x y1).
SCase "x=y1".
simpl.
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
SCase "x<>y1".
destruct (eq_id_dec x y2).
SSCase "x=y2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y2 z)...
SSCase "x<>y2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
subst. rewrite neq_id...
destruct (eq_id_dec y2 z)...
subst. rewrite neq_id...
Qed.
(* ###################################################################### *)
(** *** Preservation *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
(* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *)
remember (@empty ty) as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
(* Proof: By induction on the given typing derivation. Many cases are
contradictory ([T_Var], [T_Abs]). We show just the interesting ones. *)
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
(* If the last rule used was [T_App], then [t = t1 t2], and three rules
could have been used to show [t ==> t']: [ST_App1], [ST_App2], and
[ST_AppAbs]. In the first two cases, the result follows directly from
the IH. *)
inversion HE; subst...
SCase "ST_AppAbs".
(* For the third case, suppose
[t1 = tabs x T11 t12]
and
[t2 = v2].
We must show that [empty |- [x:=v2]t12 : T2].
We know by assumption that
[empty |- tabs x T11 t12 : T1->T2]
and by inversion
[x:T1 |- t12 : T2]
We have already proven that substitution_preserves_typing and
[empty |- v2 : T1]
by assumption, so we are done. *)
apply substitution_preserves_typing with T1...
inversion HT1...
Case "T_Fst".
inversion HT...
Case "T_Snd".
inversion HT...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "ST_CaseInl".
inversion HT1; subst.
eapply substitution_preserves_typing...
SCase "ST_CaseInr".
inversion HT1; subst.
eapply substitution_preserves_typing...
Case "T_Lcase".
SCase "ST_LcaseCons".
inversion HT1; subst.
apply substitution_preserves_typing with (TList T1)...
apply substitution_preserves_typing with T1...
(* fix *)
(* FILL IN HERE *)
Qed.
(** [] *)
End STLCExtended.
(* $Date: 2014-12-01 15:15:02 -0500 (Mon, 01 Dec 2014) $ *)
|
(** * MoreStlc: More on the Simply Typed Lambda-Calculus *)
Require Export Stlc.
(* ###################################################################### *)
(** * Simple Extensions to STLC *)
(** The simply typed lambda-calculus has enough structure to make its
theoretical properties interesting, but it is not much of a
programming language. In this chapter, we begin to close the gap
with real-world languages by introducing a number of familiar
features that have straightforward treatments at the level of
typing. *)
(** ** Numbers *)
(** Adding types, constants, and primitive operations for numbers is
easy -- just a matter of combining the [Types] and [Stlc]
chapters. *)
(** ** [let]-bindings *)
(** When writing a complex expression, it is often useful to give
names to some of its subexpressions: this avoids repetition and
often increases readability. Most languages provide one or more
ways of doing this. In OCaml (and Coq), for example, we can write
[let x=t1 in t2] to mean ``evaluate the expression [t1] and bind
the name [x] to the resulting value while evaluating [t2].''
Our [let]-binder follows OCaml's in choosing a call-by-value
evaluation order, where the [let]-bound term must be fully
evaluated before evaluation of the [let]-body can begin. The
typing rule [T_Let] tells us that the type of a [let] can be
calculated by calculating the type of the [let]-bound term,
extending the context with a binding with this type, and in this
enriched context calculating the type of the body, which is then
the type of the whole [let] expression.
At this point in the course, it's probably easier simply to look
at the rules defining this new feature as to wade through a lot of
english text conveying the same information. Here they are: *)
(** Syntax:
<<
t ::= Terms
| ... (other terms same as before)
| let x=t in t let-binding
>>
*)
(**
Reduction:
t1 ==> t1'
---------------------------------- (ST_Let1)
let x=t1 in t2 ==> let x=t1' in t2
---------------------------- (ST_LetValue)
let x=v1 in t2 ==> [x:=v1]t2
Typing:
Gamma |- t1 : T1 Gamma , x:T1 |- t2 : T2
-------------------------------------------- (T_Let)
Gamma |- let x=t1 in t2 : T2
*)
(** ** Pairs *)
(** Our functional programming examples in Coq have made
frequent use of _pairs_ of values. The type of such pairs is
called a _product type_.
The formalization of pairs is almost too simple to be worth
discussing. However, let's look briefly at the various parts of
the definition to emphasize the common pattern. *)
(** In Coq, the primitive way of extracting the components of a pair
is _pattern matching_. An alternative style is to take [fst] and
[snd] -- the first- and second-projection operators -- as
primitives. Just for fun, let's do our products this way. For
example, here's how we'd write a function that takes a pair of
numbers and returns the pair of their sum and difference:
<<
\x:Nat*Nat.
let sum = x.fst + x.snd in
let diff = x.fst - x.snd in
(sum,diff)
>>
*)
(** Adding pairs to the simply typed lambda-calculus, then, involves
adding two new forms of term -- pairing, written [(t1,t2)], and
projection, written [t.fst] for the first projection from [t] and
[t.snd] for the second projection -- plus one new type constructor,
[T1*T2], called the _product_ of [T1] and [T2]. *)
(** Syntax:
<<
t ::= Terms
| ...
| (t,t) pair
| t.fst first projection
| t.snd second projection
v ::= Values
| ...
| (v,v) pair value
T ::= Types
| ...
| T * T product type
>>
*)
(** For evaluation, we need several new rules specifying how pairs and
projection behave.
t1 ==> t1'
-------------------- (ST_Pair1)
(t1,t2) ==> (t1',t2)
t2 ==> t2'
-------------------- (ST_Pair2)
(v1,t2) ==> (v1,t2')
t1 ==> t1'
------------------ (ST_Fst1)
t1.fst ==> t1'.fst
------------------ (ST_FstPair)
(v1,v2).fst ==> v1
t1 ==> t1'
------------------ (ST_Snd1)
t1.snd ==> t1'.snd
------------------ (ST_SndPair)
(v1,v2).snd ==> v2
*)
(**
Rules [ST_FstPair] and [ST_SndPair] specify that, when a fully
evaluated pair meets a first or second projection, the result is
the appropriate component. The congruence rules [ST_Fst1] and
[ST_Snd1] allow reduction to proceed under projections, when the
term being projected from has not yet been fully evaluated.
[ST_Pair1] and [ST_Pair2] evaluate the parts of pairs: first the
left part, and then -- when a value appears on the left -- the right
part. The ordering arising from the use of the metavariables [v]
and [t] in these rules enforces a left-to-right evaluation
strategy for pairs. (Note the implicit convention that
metavariables like [v] and [v1] can only denote values.) We've
also added a clause to the definition of values, above, specifying
that [(v1,v2)] is a value. The fact that the components of a pair
value must themselves be values ensures that a pair passed as an
argument to a function will be fully evaluated before the function
body starts executing. *)
(** The typing rules for pairs and projections are straightforward.
Gamma |- t1 : T1 Gamma |- t2 : T2
--------------------------------------- (T_Pair)
Gamma |- (t1,t2) : T1*T2
Gamma |- t1 : T11*T12
--------------------- (T_Fst)
Gamma |- t1.fst : T11
Gamma |- t1 : T11*T12
--------------------- (T_Snd)
Gamma |- t1.snd : T12
*)
(** The rule [T_Pair] says that [(t1,t2)] has type [T1*T2] if [t1] has
type [T1] and [t2] has type [T2]. Conversely, the rules [T_Fst]
and [T_Snd] tell us that, if [t1] has a product type
[T11*T12] (i.e., if it will evaluate to a pair), then the types of
the projections from this pair are [T11] and [T12]. *)
(** ** Unit *)
(** Another handy base type, found especially in languages in
the ML family, is the singleton type [Unit]. *)
(** It has a single element -- the term constant [unit] (with a small
[u]) -- and a typing rule making [unit] an element of [Unit]. We
also add [unit] to the set of possible result values of
computations -- indeed, [unit] is the _only_ possible result of
evaluating an expression of type [Unit]. *)
(** Syntax:
<<
t ::= Terms
| ...
| unit unit value
v ::= Values
| ...
| unit unit
T ::= Types
| ...
| Unit Unit type
>>
Typing:
-------------------- (T_Unit)
Gamma |- unit : Unit
*)
(** It may seem a little strange to bother defining a type that
has just one element -- after all, wouldn't every computation
living in such a type be trivial?
This is a fair question, and indeed in the STLC the [Unit] type is
not especially critical (though we'll see two uses for it below).
Where [Unit] really comes in handy is in richer languages with
various sorts of _side effects_ -- e.g., assignment statements
that mutate variables or pointers, exceptions and other sorts of
nonlocal control structures, etc. In such languages, it is
convenient to have a type for the (trivial) result of an
expression that is evaluated only for its effect. *)
(** ** Sums *)
(** Many programs need to deal with values that can take two distinct
forms. For example, we might identify employees in an accounting
application using using _either_ their name _or_ their id number.
A search function might return _either_ a matching value _or_ an
error code.
These are specific examples of a binary _sum type_,
which describes a set of values drawn from exactly two given types, e.g.
<<
Nat + Bool
>>
*)
(** We create elements of these types by _tagging_ elements of
the component types. For example, if [n] is a [Nat] then [inl v]
is an element of [Nat+Bool]; similarly, if [b] is a [Bool] then
[inr b] is a [Nat+Bool]. The names of the tags [inl] and [inr]
arise from thinking of them as functions
<<
inl : Nat -> Nat + Bool
inr : Bool -> Nat + Bool
>>
that "inject" elements of [Nat] or [Bool] into the left and right
components of the sum type [Nat+Bool]. (But note that we don't
actually treat them as functions in the way we formalize them:
[inl] and [inr] are keywords, and [inl t] and [inr t] are primitive
syntactic forms, not function applications. This allows us to give
them their own special typing rules.) *)
(** In general, the elements of a type [T1 + T2] consist of the
elements of [T1] tagged with the token [inl], plus the elements of
[T2] tagged with [inr]. *)
(** One important usage of sums is signaling errors:
<<
div : Nat -> Nat -> (Nat + Unit) =
div =
\x:Nat. \y:Nat.
if iszero y then
inr unit
else
inl ...
>>
The type [Nat + Unit] above is in fact isomorphic to [option nat]
in Coq, and we've already seen how to signal errors with options. *)
(** To _use_ elements of sum types, we introduce a [case]
construct (a very simplified form of Coq's [match]) to destruct
them. For example, the following procedure converts a [Nat+Bool]
into a [Nat]: *)
(**
<<
getNat =
\x:Nat+Bool.
case x of
inl n => n
| inr b => if b then 1 else 0
>>
*)
(** More formally... *)
(** Syntax:
<<
t ::= Terms
| ...
| inl T t tagging (left)
| inr T t tagging (right)
| case t of case
inl x => t
| inr x => t
v ::= Values
| ...
| inl T v tagged value (left)
| inr T v tagged value (right)
T ::= Types
| ...
| T + T sum type
>>
*)
(** Evaluation:
t1 ==> t1'
---------------------- (ST_Inl)
inl T t1 ==> inl T t1'
t1 ==> t1'
---------------------- (ST_Inr)
inr T t1 ==> inr T t1'
t0 ==> t0'
------------------------------------------- (ST_Case)
case t0 of inl x1 => t1 | inr x2 => t2 ==>
case t0' of inl x1 => t1 | inr x2 => t2
---------------------------------------------- (ST_CaseInl)
case (inl T v0) of inl x1 => t1 | inr x2 => t2
==> [x1:=v0]t1
---------------------------------------------- (ST_CaseInr)
case (inr T v0) of inl x1 => t1 | inr x2 => t2
==> [x2:=v0]t2
*)
(** Typing:
Gamma |- t1 : T1
---------------------------- (T_Inl)
Gamma |- inl T2 t1 : T1 + T2
Gamma |- t1 : T2
---------------------------- (T_Inr)
Gamma |- inr T1 t1 : T1 + T2
Gamma |- t0 : T1+T2
Gamma , x1:T1 |- t1 : T
Gamma , x2:T2 |- t2 : T
--------------------------------------------------- (T_Case)
Gamma |- case t0 of inl x1 => t1 | inr x2 => t2 : T
We use the type annotation in [inl] and [inr] to make the typing
simpler, similarly to what we did for functions. *)
(** Without this extra
information, the typing rule [T_Inl], for example, would have to
say that, once we have shown that [t1] is an element of type [T1],
we can derive that [inl t1] is an element of [T1 + T2] for _any_
type T2. For example, we could derive both [inl 5 : Nat + Nat]
and [inl 5 : Nat + Bool] (and infinitely many other types).
This failure of uniqueness of types would mean that we cannot
build a typechecking algorithm simply by "reading the rules from
bottom to top" as we could for all the other features seen so far.
There are various ways to deal with this difficulty. One simple
one -- which we've adopted here -- forces the programmer to
explicitly annotate the "other side" of a sum type when performing
an injection. This is rather heavyweight for programmers (and so
real languages adopt other solutions), but it is easy to
understand and formalize. *)
(** ** Lists *)
(** The typing features we have seen can be classified into _base
types_ like [Bool], and _type constructors_ like [->] and [*] that
build new types from old ones. Another useful type constructor is
[List]. For every type [T], the type [List T] describes
finite-length lists whose elements are drawn from [T].
In principle, we could encode lists using pairs, sums and
_recursive_ types. But giving semantics to recursive types is
non-trivial. Instead, we'll just discuss the special case of lists
directly.
Below we give the syntax, semantics, and typing rules for lists.
Except for the fact that explicit type annotations are mandatory
on [nil] and cannot appear on [cons], these lists are essentially
identical to those we built in Coq. We use [lcase] to destruct
lists, to avoid dealing with questions like "what is the [head] of
the empty list?" *)
(** For example, here is a function that calculates the sum of
the first two elements of a list of numbers:
<<
\x:List Nat.
lcase x of nil -> 0
| a::x' -> lcase x' of nil -> a
| b::x'' -> a+b
>>
*)
(**
Syntax:
<<
t ::= Terms
| ...
| nil T
| cons t t
| lcase t of nil -> t | x::x -> t
v ::= Values
| ...
| nil T nil value
| cons v v cons value
T ::= Types
| ...
| List T list of Ts
>>
*)
(** Reduction:
t1 ==> t1'
-------------------------- (ST_Cons1)
cons t1 t2 ==> cons t1' t2
t2 ==> t2'
-------------------------- (ST_Cons2)
cons v1 t2 ==> cons v1 t2'
t1 ==> t1'
---------------------------------------- (ST_Lcase1)
(lcase t1 of nil -> t2 | xh::xt -> t3) ==>
(lcase t1' of nil -> t2 | xh::xt -> t3)
----------------------------------------- (ST_LcaseNil)
(lcase nil T of nil -> t2 | xh::xt -> t3)
==> t2
----------------------------------------------- (ST_LcaseCons)
(lcase (cons vh vt) of nil -> t2 | xh::xt -> t3)
==> [xh:=vh,xt:=vt]t3
*)
(** Typing:
----------------------- (T_Nil)
Gamma |- nil T : List T
Gamma |- t1 : T Gamma |- t2 : List T
----------------------------------------- (T_Cons)
Gamma |- cons t1 t2: List T
Gamma |- t1 : List T1
Gamma |- t2 : T
Gamma , h:T1, t:List T1 |- t3 : T
------------------------------------------------- (T_Lcase)
Gamma |- (lcase t1 of nil -> t2 | h::t -> t3) : T
*)
(** ** General Recursion *)
(** Another facility found in most programming languages (including
Coq) is the ability to define recursive functions. For example,
we might like to be able to define the factorial function like
this:
<<
fact = \x:Nat.
if x=0 then 1 else x * (fact (pred x)))
>>
But this would require quite a bit of work to formalize: we'd have
to introduce a notion of "function definitions" and carry around an
"environment" of such definitions in the definition of the [step]
relation. *)
(** Here is another way that is straightforward to formalize: instead
of writing recursive definitions where the right-hand side can
contain the identifier being defined, we can define a _fixed-point
operator_ that performs the "unfolding" of the recursive definition
in the right-hand side lazily during reduction.
<<
fact =
fix
(\f:Nat->Nat.
\x:Nat.
if x=0 then 1 else x * (f (pred x)))
>>
*)
(** The intuition is that the higher-order function [f] passed
to [fix] is a _generator_ for the [fact] function: if [fact] is
applied to a function that approximates the desired behavior of
[fact] up to some number [n] (that is, a function that returns
correct results on inputs less than or equal to [n]), then it
returns a better approximation to [fact] -- a function that returns
correct results for inputs up to [n+1]. Applying [fix] to this
generator returns its _fixed point_ -- a function that gives the
desired behavior for all inputs [n].
(The term "fixed point" has exactly the same sense as in ordinary
mathematics, where a fixed point of a function [f] is an input [x]
such that [f(x) = x]. Here, a fixed point of a function [F] of
type (say) [(Nat->Nat)->(Nat->Nat)] is a function [f] such that [F
f] is behaviorally equivalent to [f].) *)
(** Syntax:
<<
t ::= Terms
| ...
| fix t fixed-point operator
>>
Reduction:
t1 ==> t1'
------------------ (ST_Fix1)
fix t1 ==> fix t1'
F = \xf:T1.t2
----------------------- (ST_FixAbs)
fix F ==> [xf:=fix F]t2
Typing:
Gamma |- t1 : T1->T1
-------------------- (T_Fix)
Gamma |- fix t1 : T1
*)
(** Let's see how [ST_FixAbs] works by reducing [fact 3 = fix F 3],
where [F = (\f. \x. if x=0 then 1 else x * (f (pred x)))] (we are
omitting type annotations for brevity here).
<<
fix F 3
>>
[==>] [ST_FixAbs]
<<
(\x. if x=0 then 1 else x * (fix F (pred x))) 3
>>
[==>] [ST_AppAbs]
<<
if 3=0 then 1 else 3 * (fix F (pred 3))
>>
[==>] [ST_If0_Nonzero]
<<
3 * (fix F (pred 3))
>>
[==>] [ST_FixAbs + ST_Mult2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 3))
>>
[==>] [ST_PredNat + ST_Mult2 + ST_App2]
<<
3 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 2)
>>
[==>] [ST_AppAbs + ST_Mult2]
<<
3 * (if 2=0 then 1 else 2 * (fix F (pred 2)))
>>
[==>] [ST_If0_Nonzero + ST_Mult2]
<<
3 * (2 * (fix F (pred 2)))
>>
[==>] [ST_FixAbs + 2 x ST_Mult2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 2)))
>>
[==>] [ST_PredNat + 2 x ST_Mult2 + ST_App2]
<<
3 * (2 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 1))
>>
[==>] [ST_AppAbs + 2 x ST_Mult2]
<<
3 * (2 * (if 1=0 then 1 else 1 * (fix F (pred 1))))
>>
[==>] [ST_If0_Nonzero + 2 x ST_Mult2]
<<
3 * (2 * (1 * (fix F (pred 1))))
>>
[==>] [ST_FixAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) (pred 1))))
>>
[==>] [ST_PredNat + 3 x ST_Mult2 + ST_App2]
<<
3 * (2 * (1 * ((\x. if x=0 then 1 else x * (fix F (pred x))) 0)))
>>
[==>] [ST_AppAbs + 3 x ST_Mult2]
<<
3 * (2 * (1 * (if 0=0 then 1 else 0 * (fix F (pred 0)))))
>>
[==>] [ST_If0Zero + 3 x ST_Mult2]
<<
3 * (2 * (1 * 1))
>>
[==>] [ST_MultNats + 2 x ST_Mult2]
<<
3 * (2 * 1)
>>
[==>] [ST_MultNats + ST_Mult2]
<<
3 * 2
>>
[==>] [ST_MultNats]
<<
6
>>
*)
(** **** Exercise: 1 star, optional (halve_fix) *)
(** Translate this informal recursive definition into one using [fix]:
<<
halve =
\x:Nat.
if x=0 then 0
else if (pred x)=0 then 0
else 1 + (halve (pred (pred x))))
>>
(* FILL IN HERE *)
[]
*)
(** **** Exercise: 1 star, optional (fact_steps) *)
(** Write down the sequence of steps that the term [fact 1] goes
through to reduce to a normal form (assuming the usual reduction
rules for arithmetic operations).
(* FILL IN HERE *)
[]
*)
(** The ability to form the fixed point of a function of type [T->T]
for any [T] has some surprising consequences. In particular, it
implies that _every_ type is inhabited by some term. To see this,
observe that, for every type [T], we can define the term
fix (\x:T.x)
By [T_Fix] and [T_Abs], this term has type [T]. By [ST_FixAbs]
it reduces to itself, over and over again. Thus it is an
_undefined element_ of [T].
More usefully, here's an example using [fix] to define a
two-argument recursive function:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
And finally, here is an example where [fix] is used to define a
_pair_ of recursive functions (illustrating the fact that the type
[T1] in the rule [T_Fix] need not be a function type):
<<
evenodd =
fix
(\eo: (Nat->Bool * Nat->Bool).
let e = \n:Nat. if n=0 then true else eo.snd (pred n) in
let o = \n:Nat. if n=0 then false else eo.fst (pred n) in
(e,o))
even = evenodd.fst
odd = evenodd.snd
>>
*)
(* ###################################################################### *)
(** ** Records *)
(** As a final example of a basic extension of the STLC, let's
look briefly at how to define _records_ and their types.
Intuitively, records can be obtained from pairs by two kinds of
generalization: they are n-ary products (rather than just binary)
and their fields are accessed by _label_ (rather than position).
Conceptually, this extension is a straightforward generalization
of pairs and product types, but notationally it becomes a little
heavier; for this reason, we postpone its formal treatment to a
separate chapter ([Records]). *)
(** Records are not included in the extended exercise below, but
they will be useful to motivate the [Sub] chapter. *)
(** Syntax:
<<
t ::= Terms
| ...
| {i1=t1, ..., in=tn} record
| t.i projection
v ::= Values
| ...
| {i1=v1, ..., in=vn} record value
T ::= Types
| ...
| {i1:T1, ..., in:Tn} record type
>>
Intuitively, the generalization is pretty obvious. But it's worth
noticing that what we've actually written is rather informal: in
particular, we've written "[...]" in several places to mean "any
number of these," and we've omitted explicit mention of the usual
side-condition that the labels of a record should not contain
repetitions. *)
(** It is possible to devise informal notations that are
more precise, but these tend to be quite heavy and to obscure the
main points of the definitions. So we'll leave these a bit loose
here (they are informal anyway, after all) and do the work of
tightening things up elsewhere (in chapter [Records]). *)
(**
Reduction:
ti ==> ti'
------------------------------------ (ST_Rcd)
{i1=v1, ..., im=vm, in=ti, ...}
==> {i1=v1, ..., im=vm, in=ti', ...}
t1 ==> t1'
-------------- (ST_Proj1)
t1.i ==> t1'.i
------------------------- (ST_ProjRcd)
{..., i=vi, ...}.i ==> vi
Again, these rules are a bit informal. For example, the first rule
is intended to be read "if [ti] is the leftmost field that is not a
value and if [ti] steps to [ti'], then the whole record steps..."
In the last rule, the intention is that there should only be one
field called i, and that all the other fields must contain values. *)
(**
Typing:
Gamma |- t1 : T1 ... Gamma |- tn : Tn
-------------------------------------------------- (T_Rcd)
Gamma |- {i1=t1, ..., in=tn} : {i1:T1, ..., in:Tn}
Gamma |- t : {..., i:Ti, ...}
----------------------------- (T_Proj)
Gamma |- t.i : Ti
*)
(* ###################################################################### *)
(** *** Encoding Records (Optional) *)
(** There are several ways to make the above definitions precise.
- We can directly formalize the syntactic forms and inference
rules, staying as close as possible to the form we've given
them above. This is conceptually straightforward, and it's
probably what we'd want to do if we were building a real
compiler -- in particular, it will allow is to print error
messages in the form that programmers will find easy to
understand. But the formal versions of the rules will not be
pretty at all!
- We could look for a smoother way of presenting records -- for
example, a binary presentation with one constructor for the
empty record and another constructor for adding a single field
to an existing record, instead of a single monolithic
constructor that builds a whole record at once. This is the
right way to go if we are primarily interested in studying the
metatheory of the calculi with records, since it leads to
clean and elegant definitions and proofs. Chapter [Records]
shows how this can be done.
- Alternatively, if we like, we can avoid formalizing records
altogether, by stipulating that record notations are just
informal shorthands for more complex expressions involving
pairs and product types. We sketch this approach here.
First, observe that we can encode arbitrary-size tuples using
nested pairs and the [unit] value. To avoid overloading the pair
notation [(t1,t2)], we'll use curly braces without labels to write
down tuples, so [{}] is the empty tuple, [{5}] is a singleton
tuple, [{5,6}] is a 2-tuple (morally the same as a pair),
[{5,6,7}] is a triple, etc.
<<
{} ----> unit
{t1, t2, ..., tn} ----> (t1, trest)
where {t2, ..., tn} ----> trest
>>
Similarly, we can encode tuple types using nested product types:
<<
{} ----> Unit
{T1, T2, ..., Tn} ----> T1 * TRest
where {T2, ..., Tn} ----> TRest
>>
The operation of projecting a field from a tuple can be encoded
using a sequence of second projections followed by a first projection:
<<
t.0 ----> t.fst
t.(n+1) ----> (t.snd).n
>>
Next, suppose that there is some total ordering on record labels,
so that we can associate each label with a unique natural number.
This number is called the _position_ of the label. For example,
we might assign positions like this:
<<
LABEL POSITION
a 0
b 1
c 2
... ...
foo 1004
... ...
bar 10562
... ...
>>
We use these positions to encode record values as tuples (i.e., as
nested pairs) by sorting the fields according to their positions.
For example:
<<
{a=5, b=6} ----> {5,6}
{a=5, c=7} ----> {5,unit,7}
{c=7, a=5} ----> {5,unit,7}
{c=5, b=3} ----> {unit,3,5}
{f=8,c=5,a=7} ----> {7,unit,5,unit,unit,8}
{f=8,c=5} ----> {unit,unit,5,unit,unit,8}
>>
Note that each field appears in the position associated with its
label, that the size of the tuple is determined by the label with
the highest position, and that we fill in unused positions with
[unit].
We do exactly the same thing with record types:
<<
{a:Nat, b:Nat} ----> {Nat,Nat}
{c:Nat, a:Nat} ----> {Nat,Unit,Nat}
{f:Nat,c:Nat} ----> {Unit,Unit,Nat,Unit,Unit,Nat}
>>
Finally, record projection is encoded as a tuple projection from
the appropriate position:
<<
t.l ----> t.(position of l)
>>
It is not hard to check that all the typing rules for the original
"direct" presentation of records are validated by this
encoding. (The reduction rules are "almost validated" -- not
quite, because the encoding reorders fields.) *)
(** Of course, this encoding will not be very efficient if we
happen to use a record with label [bar]! But things are not
actually as bad as they might seem: for example, if we assume that
our compiler can see the whole program at the same time, we can
_choose_ the numbering of labels so that we assign small positions
to the most frequently used labels. Indeed, there are industrial
compilers that essentially do this! *)
(** *** Variants (Optional Reading) *)
(** Just as products can be generalized to records, sums can be
generalized to n-ary labeled types called _variants_. Instead of
[T1+T2], we can write something like [<l1:T1,l2:T2,...ln:Tn>]
where [l1],[l2],... are field labels which are used both to build
instances and as case arm labels.
These n-ary variants give us almost enough mechanism to build
arbitrary inductive data types like lists and trees from
scratch -- the only thing missing is a way to allow _recursion_ in
type definitions. We won't cover this here, but detailed
treatments can be found in many textbooks -- e.g., Types and
Programming Languages. *)
(* ###################################################################### *)
(** * Exercise: Formalizing the Extensions *)
(** **** Exercise: 4 stars, optional (STLC_extensions) *)
(** In this problem you will formalize a couple of the extensions
described above. We've provided the necessary additions to the
syntax of terms and types, and we've included a few examples that
you can test your definitions with to make sure they are working
as expected. You'll fill in the rest of the definitions and
extend all the proofs accordingly.
To get you started, we've provided implementations for:
- numbers
- pairs and units
- sums
- lists
You need to complete the implementations for:
- let (which involves binding)
- [fix]
A good strategy is to work on the extensions one at a time, in
multiple passes, rather than trying to work through the file from
start to finish in a single pass. For each definition or proof,
begin by reading carefully through the parts that are provided for
you, referring to the text in the [Stlc] chapter for high-level
intuitions and the embedded comments for detailed mechanics.
*)
Module STLCExtended.
(* ###################################################################### *)
(** *** Syntax and Operational Semantics *)
Inductive ty : Type :=
| TArrow : ty -> ty -> ty
| TNat : ty
| TUnit : ty
| TProd : ty -> ty -> ty
| TSum : ty -> ty -> ty
| TList : ty -> ty.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TArrow" | Case_aux c "TNat"
| Case_aux c "TProd" | Case_aux c "TUnit"
| Case_aux c "TSum" | Case_aux c "TList" ].
Inductive tm : Type :=
(* pure STLC *)
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
(* numbers *)
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm
(* pairs *)
| tpair : tm -> tm -> tm
| tfst : tm -> tm
| tsnd : tm -> tm
(* units *)
| tunit : tm
(* let *)
| tlet : id -> tm -> tm -> tm
(* i.e., [let x = t1 in t2] *)
(* sums *)
| tinl : ty -> tm -> tm
| tinr : ty -> tm -> tm
| tcase : tm -> id -> tm -> id -> tm -> tm
(* i.e., [case t0 of inl x1 => t1 | inr x2 => t2] *)
(* lists *)
| tnil : ty -> tm
| tcons : tm -> tm -> tm
| tlcase : tm -> tm -> id -> id -> tm -> tm
(* i.e., [lcase t1 of | nil -> t2 | x::y -> t3] *)
(* fix *)
| tfix : tm -> tm.
(** Note that, for brevity, we've omitted booleans and instead
provided a single [if0] form combining a zero test and a
conditional. That is, instead of writing
<<
if x = 0 then ... else ...
>>
we'll write this:
<<
if0 x then ... else ...
>>
*)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"
| Case_aux c "tnat" | Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd"
| Case_aux c "tunit" | Case_aux c "tlet"
| Case_aux c "tinl" | Case_aux c "tinr" | Case_aux c "tcase"
| Case_aux c "tnil" | Case_aux c "tcons" | Case_aux c "tlcase"
| Case_aux c "tfix" ].
(* ###################################################################### *)
(** *** Substitution *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tnat n =>
tnat n
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tpair t1 t2 =>
tpair (subst x s t1) (subst x s t2)
| tfst t1 =>
tfst (subst x s t1)
| tsnd t1 =>
tsnd (subst x s t1)
| tunit => tunit
(* FILL IN HERE *)
| tinl T t1 =>
tinl T (subst x s t1)
| tinr T t1 =>
tinr T (subst x s t1)
| tcase t0 y1 t1 y2 t2 =>
tcase (subst x s t0)
y1 (if eq_id_dec x y1 then t1 else (subst x s t1))
y2 (if eq_id_dec x y2 then t2 else (subst x s t2))
| tnil T =>
tnil T
| tcons t1 t2 =>
tcons (subst x s t1) (subst x s t2)
| tlcase t1 t2 y1 y2 t3 =>
tlcase (subst x s t1) (subst x s t2) y1 y2
(if eq_id_dec x y1 then
t3
else if eq_id_dec x y2 then t3
else (subst x s t3))
(* FILL IN HERE *)
| _ => t (* ... and delete this line *)
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** *** Reduction *)
(** Next we define the values of our language. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T11 t12,
value (tabs x T11 t12)
(* Numbers are values: *)
| v_nat : forall n1,
value (tnat n1)
(* A pair is a value if both components are: *)
| v_pair : forall v1 v2,
value v1 ->
value v2 ->
value (tpair v1 v2)
(* A unit is always a value *)
| v_unit : value tunit
(* A tagged value is a value: *)
| v_inl : forall v T,
value v ->
value (tinl T v)
| v_inr : forall v T,
value v ->
value (tinr T v)
(* A list is a value iff its head and tail are values: *)
| v_lnil : forall T, value (tnil T)
| v_lcons : forall v1 vl,
value v1 ->
value vl ->
value (tcons v1 vl)
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T11 t12 v2,
value v2 ->
(tapp (tabs x T11 t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
(* nats *)
| ST_Succ1 : forall t1 t1',
t1 ==> t1' ->
(tsucc t1) ==> (tsucc t1')
| ST_SuccNat : forall n1,
(tsucc (tnat n1)) ==> (tnat (S n1))
| ST_Pred : forall t1 t1',
t1 ==> t1' ->
(tpred t1) ==> (tpred t1')
| ST_PredNat : forall n1,
(tpred (tnat n1)) ==> (tnat (pred n1))
| ST_Mult1 : forall t1 t1' t2,
t1 ==> t1' ->
(tmult t1 t2) ==> (tmult t1' t2)
| ST_Mult2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tmult v1 t2) ==> (tmult v1 t2')
| ST_MultNats : forall n1 n2,
(tmult (tnat n1) (tnat n2)) ==> (tnat (mult n1 n2))
| ST_If01 : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif0 t1 t2 t3) ==> (tif0 t1' t2 t3)
| ST_If0Zero : forall t2 t3,
(tif0 (tnat 0) t2 t3) ==> t2
| ST_If0Nonzero : forall n t2 t3,
(tif0 (tnat (S n)) t2 t3) ==> t3
(* pairs *)
| ST_Pair1 : forall t1 t1' t2,
t1 ==> t1' ->
(tpair t1 t2) ==> (tpair t1' t2)
| ST_Pair2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tpair v1 t2) ==> (tpair v1 t2')
| ST_Fst1 : forall t1 t1',
t1 ==> t1' ->
(tfst t1) ==> (tfst t1')
| ST_FstPair : forall v1 v2,
value v1 ->
value v2 ->
(tfst (tpair v1 v2)) ==> v1
| ST_Snd1 : forall t1 t1',
t1 ==> t1' ->
(tsnd t1) ==> (tsnd t1')
| ST_SndPair : forall v1 v2,
value v1 ->
value v2 ->
(tsnd (tpair v1 v2)) ==> v2
(* let *)
(* FILL IN HERE *)
(* sums *)
| ST_Inl : forall t1 t1' T,
t1 ==> t1' ->
(tinl T t1) ==> (tinl T t1')
| ST_Inr : forall t1 t1' T,
t1 ==> t1' ->
(tinr T t1) ==> (tinr T t1')
| ST_Case : forall t0 t0' x1 t1 x2 t2,
t0 ==> t0' ->
(tcase t0 x1 t1 x2 t2) ==> (tcase t0' x1 t1 x2 t2)
| ST_CaseInl : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinl T v0) x1 t1 x2 t2) ==> [x1:=v0]t1
| ST_CaseInr : forall v0 x1 t1 x2 t2 T,
value v0 ->
(tcase (tinr T v0) x1 t1 x2 t2) ==> [x2:=v0]t2
(* lists *)
| ST_Cons1 : forall t1 t1' t2,
t1 ==> t1' ->
(tcons t1 t2) ==> (tcons t1' t2)
| ST_Cons2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tcons v1 t2) ==> (tcons v1 t2')
| ST_Lcase1 : forall t1 t1' t2 x1 x2 t3,
t1 ==> t1' ->
(tlcase t1 t2 x1 x2 t3) ==> (tlcase t1' t2 x1 x2 t3)
| ST_LcaseNil : forall T t2 x1 x2 t3,
(tlcase (tnil T) t2 x1 x2 t3) ==> t2
| ST_LcaseCons : forall v1 vl t2 x1 x2 t3,
value v1 ->
value vl ->
(tlcase (tcons v1 vl) t2 x1 x2 t3) ==> (subst x2 vl (subst x1 v1 t3))
(* fix *)
(* FILL IN HERE *)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"
| Case_aux c "ST_Succ1" | Case_aux c "ST_SuccNat"
| Case_aux c "ST_Pred1" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_MultNats" | Case_aux c "ST_If01"
| Case_aux c "ST_If0Zero" | Case_aux c "ST_If0Nonzero"
| Case_aux c "ST_Pair1" | Case_aux c "ST_Pair2"
| Case_aux c "ST_Fst1" | Case_aux c "ST_FstPair"
| Case_aux c "ST_Snd1" | Case_aux c "ST_SndPair"
(* FILL IN HERE *)
| Case_aux c "ST_Inl" | Case_aux c "ST_Inr" | Case_aux c "ST_Case"
| Case_aux c "ST_CaseInl" | Case_aux c "ST_CaseInr"
| Case_aux c "ST_Cons1" | Case_aux c "ST_Cons2" | Case_aux c "ST_Lcase1"
| Case_aux c "ST_LcaseNil" | Case_aux c "ST_LcaseCons"
(* FILL IN HERE *)
].
Notation multistep := (multi step).
Notation "t1 '==>*' t2" := (multistep t1 t2) (at level 40).
Hint Constructors step.
(* ###################################################################### *)
(** *** Typing *)
Definition context := partial_map ty.
(** Next we define the typing rules. These are nearly direct
transcriptions of the inference rules shown above. *)
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Typing rules for proper terms *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
(* nats *)
| T_Nat : forall Gamma n1,
Gamma |- (tnat n1) \in TNat
| T_Succ : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tsucc t1) \in TNat
| T_Pred : forall Gamma t1,
Gamma |- t1 \in TNat ->
Gamma |- (tpred t1) \in TNat
| T_Mult : forall Gamma t1 t2,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in TNat ->
Gamma |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma t1 t2 t3 T1,
Gamma |- t1 \in TNat ->
Gamma |- t2 \in T1 ->
Gamma |- t3 \in T1 ->
Gamma |- (tif0 t1 t2 t3) \in T1
(* pairs *)
| T_Pair : forall Gamma t1 t2 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in T2 ->
Gamma |- (tpair t1 t2) \in (TProd T1 T2)
| T_Fst : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tfst t) \in T1
| T_Snd : forall Gamma t T1 T2,
Gamma |- t \in (TProd T1 T2) ->
Gamma |- (tsnd t) \in T2
(* unit *)
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* let *)
(* FILL IN HERE *)
(* sums *)
| T_Inl : forall Gamma t1 T1 T2,
Gamma |- t1 \in T1 ->
Gamma |- (tinl T2 t1) \in (TSum T1 T2)
| T_Inr : forall Gamma t2 T1 T2,
Gamma |- t2 \in T2 ->
Gamma |- (tinr T1 t2) \in (TSum T1 T2)
| T_Case : forall Gamma t0 x1 T1 t1 x2 T2 t2 T,
Gamma |- t0 \in (TSum T1 T2) ->
(extend Gamma x1 T1) |- t1 \in T ->
(extend Gamma x2 T2) |- t2 \in T ->
Gamma |- (tcase t0 x1 t1 x2 t2) \in T
(* lists *)
| T_Nil : forall Gamma T,
Gamma |- (tnil T) \in (TList T)
| T_Cons : forall Gamma t1 t2 T1,
Gamma |- t1 \in T1 ->
Gamma |- t2 \in (TList T1) ->
Gamma |- (tcons t1 t2) \in (TList T1)
| T_Lcase : forall Gamma t1 T1 t2 x1 x2 t3 T2,
Gamma |- t1 \in (TList T1) ->
Gamma |- t2 \in T2 ->
(extend (extend Gamma x2 (TList T1)) x1 T1) |- t3 \in T2 ->
Gamma |- (tlcase t1 t2 x1 x2 t3) \in T2
(* fix *)
(* FILL IN HERE *)
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd"
| Case_aux c "T_Unit"
(* let *)
(* FILL IN HERE *)
| Case_aux c "T_Inl" | Case_aux c "T_Inr" | Case_aux c "T_Case"
| Case_aux c "T_Nil" | Case_aux c "T_Cons" | Case_aux c "T_Lcase"
(* fix *)
(* FILL IN HERE *)
].
(* ###################################################################### *)
(** ** Examples *)
(** This section presents formalized versions of the examples from
above (plus several more). The ones at the beginning focus on
specific features; you can use these to make sure your definition
of a given feature is reasonable before moving on to extending the
proofs later in the file with the cases relating to this feature.
The later examples require all the features together, so you'll
need to come back to these when you've got all the definitions
filled in. *)
Module Examples.
(** *** Preliminaries *)
(** First, let's define a few variable names: *)
Notation a := (Id 0).
Notation f := (Id 1).
Notation g := (Id 2).
Notation l := (Id 3).
Notation k := (Id 6).
Notation i1 := (Id 7).
Notation i2 := (Id 8).
Notation x := (Id 9).
Notation y := (Id 10).
Notation processSum := (Id 11).
Notation n := (Id 12).
Notation eq := (Id 13).
Notation m := (Id 14).
Notation evenodd := (Id 15).
Notation even := (Id 16).
Notation odd := (Id 17).
Notation eo := (Id 18).
(** Next, a bit of Coq hackery to automate searching for typing
derivations. You don't need to understand this bit in detail --
just have a look over it so that you'll know what to look for if
you ever find yourself needing to make custom extensions to
[auto].
The following [Hint] declarations say that, whenever [auto]
arrives at a goal of the form [(Gamma |- (tapp e1 e1) \in T)], it
should consider [eapply T_App], leaving an existential variable
for the middle type T1, and similar for [lcase]. That variable
will then be filled in during the search for type derivations for
[e1] and [e2]. We also include a hint to "try harder" when
solving equality goals; this is useful to automate uses of
[T_Var] (which includes an equality as a precondition). *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
(* You'll want to uncomment the following line once
you've defined the [T_Lcase] constructor for the typing
relation: *)
(*
Hint Extern 2 (has_type _ (tlcase _ _ _ _ _) _) =>
eapply T_Lcase; auto.
*)
Hint Extern 2 (_ = _) => compute; reflexivity.
(** *** Numbers *)
Module Numtest.
(* if0 (pred (succ (pred (2 * 0))) then 5 else 6 *)
Definition test :=
tif0
(tpred
(tsucc
(tpred
(tmult
(tnat 2)
(tnat 0)))))
(tnat 5)
(tnat 6).
(** Remove the comment braces once you've implemented enough of the
definitions that you think this should work. *)
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof.
unfold test.
(* This typing derivation is quite deep, so we need to increase the
max search depth of [auto] from the default 5 to 10. *)
auto 10.
Qed.
Example numtest_reduces :
test ==>* tnat 5.
Proof.
unfold test. normalize.
Qed.
*)
End Numtest.
(** *** Products *)
Module Prodtest.
(* ((5,6),7).fst.snd *)
Definition test :=
tsnd
(tfst
(tpair
(tpair
(tnat 5)
(tnat 6))
(tnat 7))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End Prodtest.
(** *** [let] *)
Module LetTest.
(* let x = pred 6 in succ x *)
Definition test :=
tlet
x
(tpred (tnat 6))
(tsucc (tvar x)).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* tnat 6.
Proof. unfold test. normalize. Qed.
*)
End LetTest.
(** *** Sums *)
Module Sumtest1.
(* case (inl Nat 5) of
inl x => x
| inr y => y *)
Definition test :=
tcase (tinl TNat (tnat 5))
x (tvar x)
y (tvar y).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tnat 5).
Proof. unfold test. normalize. Qed.
*)
End Sumtest1.
Module Sumtest2.
(* let processSum =
\x:Nat+Nat.
case x of
inl n => n
inr n => if0 n then 1 else 0 in
(processSum (inl Nat 5), processSum (inr Nat 5)) *)
Definition test :=
tlet
processSum
(tabs x (TSum TNat TNat)
(tcase (tvar x)
n (tvar n)
n (tif0 (tvar n) (tnat 1) (tnat 0))))
(tpair
(tapp (tvar processSum) (tinl TNat (tnat 5)))
(tapp (tvar processSum) (tinr TNat (tnat 5)))).
(*
Example typechecks :
(@empty ty) |- test \in (TProd TNat TNat).
Proof. unfold test. eauto 15. Qed.
Example reduces :
test ==>* (tpair (tnat 5) (tnat 0)).
Proof. unfold test. normalize. Qed.
*)
End Sumtest2.
(** *** Lists *)
Module ListTest.
(* let l = cons 5 (cons 6 (nil Nat)) in
lcase l of
nil => 0
| x::y => x*x *)
Definition test :=
tlet l
(tcons (tnat 5) (tcons (tnat 6) (tnil TNat)))
(tlcase (tvar l)
(tnat 0)
x y (tmult (tvar x) (tvar x))).
(*
Example typechecks :
(@empty ty) |- test \in TNat.
Proof. unfold test. eauto 20. Qed.
Example reduces :
test ==>* (tnat 25).
Proof. unfold test. normalize. Qed.
*)
End ListTest.
(** *** [fix] *)
Module FixTest1.
(* fact := fix
(\f:nat->nat.
\a:nat.
if a=0 then 1 else a * (f (pred a))) *)
Definition fact :=
tfix
(tabs f (TArrow TNat TNat)
(tabs a TNat
(tif0
(tvar a)
(tnat 1)
(tmult
(tvar a)
(tapp (tvar f) (tpred (tvar a))))))).
(** (Warning: you may be able to typecheck [fact] but still have some
rules wrong!) *)
(*
Example fact_typechecks :
(@empty ty) |- fact \in (TArrow TNat TNat).
Proof. unfold fact. auto 10.
Qed.
*)
(*
Example fact_example:
(tapp fact (tnat 4)) ==>* (tnat 24).
Proof. unfold fact. normalize. Qed.
*)
End FixTest1.
Module FixTest2.
(* map :=
\g:nat->nat.
fix
(\f:[nat]->[nat].
\l:[nat].
case l of
| [] -> []
| x::l -> (g x)::(f l)) *)
Definition map :=
tabs g (TArrow TNat TNat)
(tfix
(tabs f (TArrow (TList TNat) (TList TNat))
(tabs l (TList TNat)
(tlcase (tvar l)
(tnil TNat)
a l (tcons (tapp (tvar g) (tvar a))
(tapp (tvar f) (tvar l))))))).
(*
(* Make sure you've uncommented the last [Hint Extern] above... *)
Example map_typechecks :
empty |- map \in
(TArrow (TArrow TNat TNat)
(TArrow (TList TNat)
(TList TNat))).
Proof. unfold map. auto 10. Qed.
Example map_example :
tapp (tapp map (tabs a TNat (tsucc (tvar a))))
(tcons (tnat 1) (tcons (tnat 2) (tnil TNat)))
==>* (tcons (tnat 2) (tcons (tnat 3) (tnil TNat))).
Proof. unfold map. normalize. Qed.
*)
End FixTest2.
Module FixTest3.
(* equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if0 m then (if0 n then 1 else 0)
else if0 n then 0
else eq (pred m) (pred n)) *)
Definition equal :=
tfix
(tabs eq (TArrow TNat (TArrow TNat TNat))
(tabs m TNat
(tabs n TNat
(tif0 (tvar m)
(tif0 (tvar n) (tnat 1) (tnat 0))
(tif0 (tvar n)
(tnat 0)
(tapp (tapp (tvar eq)
(tpred (tvar m)))
(tpred (tvar n)))))))).
(*
Example equal_typechecks :
(@empty ty) |- equal \in (TArrow TNat (TArrow TNat TNat)).
Proof. unfold equal. auto 10.
Qed.
*)
(*
Example equal_example1:
(tapp (tapp equal (tnat 4)) (tnat 4)) ==>* (tnat 1).
Proof. unfold equal. normalize. Qed.
*)
(*
Example equal_example2:
(tapp (tapp equal (tnat 4)) (tnat 5)) ==>* (tnat 0).
Proof. unfold equal. normalize. Qed.
*)
End FixTest3.
Module FixTest4.
(* let evenodd =
fix
(\eo: (Nat->Nat * Nat->Nat).
let e = \n:Nat. if0 n then 1 else eo.snd (pred n) in
let o = \n:Nat. if0 n then 0 else eo.fst (pred n) in
(e,o)) in
let even = evenodd.fst in
let odd = evenodd.snd in
(even 3, even 4)
*)
Definition eotest :=
tlet evenodd
(tfix
(tabs eo (TProd (TArrow TNat TNat) (TArrow TNat TNat))
(tpair
(tabs n TNat
(tif0 (tvar n)
(tnat 1)
(tapp (tsnd (tvar eo)) (tpred (tvar n)))))
(tabs n TNat
(tif0 (tvar n)
(tnat 0)
(tapp (tfst (tvar eo)) (tpred (tvar n))))))))
(tlet even (tfst (tvar evenodd))
(tlet odd (tsnd (tvar evenodd))
(tpair
(tapp (tvar even) (tnat 3))
(tapp (tvar even) (tnat 4))))).
(*
Example eotest_typechecks :
(@empty ty) |- eotest \in (TProd TNat TNat).
Proof. unfold eotest. eauto 30.
Qed.
*)
(*
Example eotest_example1:
eotest ==>* (tpair (tnat 0) (tnat 1)).
Proof. unfold eotest. normalize. Qed.
*)
End FixTest4.
End Examples.
(* ###################################################################### *)
(** ** Properties of Typing *)
(** The proofs of progress and preservation for this system are
essentially the same (though of course somewhat longer) as for the
pure simply typed lambda-calculus. *)
(* ###################################################################### *)
(** *** Progress *)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
(* Theorem: Suppose empty |- t : T. Then either
1. t is a value, or
2. t ==> t' for some t'.
Proof: By induction on the given typing derivation. *)
intros t T Ht.
remember (@empty ty) as Gamma.
generalize dependent HeqGamma.
has_type_cases (induction Ht) Case; intros HeqGamma; subst.
Case "T_Var".
(* The final rule in the given typing derivation cannot be [T_Var],
since it can never be the case that [empty |- x : T] (since the
context is empty). *)
inversion H.
Case "T_Abs".
(* If the [T_Abs] rule was the last used, then [t = tabs x T11 t12],
which is a value. *)
left...
Case "T_App".
(* If the last rule applied was T_App, then [t = t1 t2], and we know
from the form of the rule that
[empty |- t1 : T1 -> T2]
[empty |- t2 : T1]
By the induction hypothesis, each of t1 and t2 either is a value
or can take a step. *)
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
(* If both [t1] and [t2] are values, then we know that
[t1 = tabs x T11 t12], since abstractions are the only values
that can have an arrow type. But
[(tabs x T11 t12) t2 ==> [x:=t2]t12] by [ST_AppAbs]. *)
inversion H; subst; try (solve by inversion).
exists (subst x t2 t12)...
SSCase "t2 steps".
(* If [t1] is a value and [t2 ==> t2'], then [t1 t2 ==> t1 t2']
by [ST_App2]. *)
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
(* Finally, If [t1 ==> t1'], then [t1 t2 ==> t1' t2] by [ST_App1]. *)
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_Nat".
left...
Case "T_Succ".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (S n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsucc t1')...
Case "T_Pred".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists (tnat (pred n1))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tpred t1')...
Case "T_Mult".
right.
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 is a value".
inversion H; subst; try solve by inversion.
inversion H0; subst; try solve by inversion.
exists (tnat (mult n1 n0))...
SSCase "t2 steps".
inversion H0 as [t2' Hstp].
exists (tmult t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tmult t1' t2)...
Case "T_If0".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
destruct n1 as [|n1'].
SSCase "n1=0".
exists t2...
SSCase "n1<>0".
exists t3...
SCase "t1 steps".
inversion H as [t1' H0].
exists (tif0 t1' t2 t3)...
Case "T_Pair".
destruct IHHt1...
SCase "t1 is a value".
destruct IHHt2...
SSCase "t2 steps".
right. inversion H0 as [t2' Hstp].
exists (tpair t1 t2')...
SCase "t1 steps".
right. inversion H as [t1' Hstp].
exists (tpair t1' t2)...
Case "T_Fst".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v1...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tfst t1')...
Case "T_Snd".
right.
destruct IHHt...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
exists v2...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tsnd t1')...
Case "T_Unit".
left...
(* let *)
(* FILL IN HERE *)
Case "T_Inl".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinl _ t1')... *)
Case "T_Inr".
destruct IHHt...
SCase "t1 steps".
right. inversion H as [t1' Hstp]...
(* exists (tinr _ t1')... *)
Case "T_Case".
right.
destruct IHHt1...
SCase "t0 is a value".
inversion H; subst; try solve by inversion.
SSCase "t0 is inl".
exists ([x1:=v]t1)...
SSCase "t0 is inr".
exists ([x2:=v]t2)...
SCase "t0 steps".
inversion H as [t0' Hstp].
exists (tcase t0' x1 t1 x2 t2)...
Case "T_Nil".
left...
Case "T_Cons".
destruct IHHt1...
SCase "head is a value".
destruct IHHt2...
SSCase "tail steps".
right. inversion H0 as [t2' Hstp].
exists (tcons t1 t2')...
SCase "head steps".
right. inversion H as [t1' Hstp].
exists (tcons t1' t2)...
Case "T_Lcase".
right.
destruct IHHt1...
SCase "t1 is a value".
inversion H; subst; try solve by inversion.
SSCase "t1=tnil".
exists t2...
SSCase "t1=tcons v1 vl".
exists ([x2:=vl]([x1:=v1]t3))...
SCase "t1 steps".
inversion H as [t1' Hstp].
exists (tlcase t1' t2 x1 x2 t3)...
(* fix *)
(* FILL IN HERE *)
Qed.
(* ###################################################################### *)
(** *** Context Invariance *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
(* nats *)
| afi_succ : forall x t,
appears_free_in x t ->
appears_free_in x (tsucc t)
| afi_pred : forall x t,
appears_free_in x t ->
appears_free_in x (tpred t)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if01 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if02 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if03 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
(* pairs *)
| afi_pair1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tpair t1 t2)
| afi_pair2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tpair t1 t2)
| afi_fst : forall x t,
appears_free_in x t ->
appears_free_in x (tfst t)
| afi_snd : forall x t,
appears_free_in x t ->
appears_free_in x (tsnd t)
(* let *)
(* FILL IN HERE *)
(* sums *)
| afi_inl : forall x t T,
appears_free_in x t ->
appears_free_in x (tinl T t)
| afi_inr : forall x t T,
appears_free_in x t ->
appears_free_in x (tinr T t)
| afi_case0 : forall x t0 x1 t1 x2 t2,
appears_free_in x t0 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case1 : forall x t0 x1 t1 x2 t2,
x1 <> x ->
appears_free_in x t1 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
| afi_case2 : forall x t0 x1 t1 x2 t2,
x2 <> x ->
appears_free_in x t2 ->
appears_free_in x (tcase t0 x1 t1 x2 t2)
(* lists *)
| afi_cons1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tcons t1 t2)
| afi_cons2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tcons t1 t2)
| afi_lcase1 : forall x t1 t2 y1 y2 t3,
appears_free_in x t1 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase2 : forall x t1 t2 y1 y2 t3,
appears_free_in x t2 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
| afi_lcase3 : forall x t1 t2 y1 y2 t3,
y1 <> x ->
y2 <> x ->
appears_free_in x t3 ->
appears_free_in x (tlcase t1 t2 y1 y2 t3)
(* fix *)
(* FILL IN HERE *)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros y Hafi.
unfold extend.
destruct (eq_id_dec x y)...
Case "T_Mult".
apply T_Mult...
Case "T_If0".
apply T_If0...
Case "T_Pair".
apply T_Pair...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
eapply T_Case...
apply IHhas_type2. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x2 y)...
Case "T_Cons".
apply T_Cons...
Case "T_Lcase".
eapply T_Lcase... apply IHhas_type3. intros y Hafi.
unfold extend.
destruct (eq_id_dec x1 y)...
destruct (eq_id_dec x2 y)...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case; inversion Hafi; subst...
Case "T_Abs".
destruct IHHtyp as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "left".
destruct IHHtyp2 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
SCase "right".
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx...
Case "T_Lcase".
clear Htyp1 IHHtyp1 Htyp2 IHHtyp2.
destruct IHHtyp3 as [T' Hctx]... exists T'.
unfold extend in Hctx.
rewrite neq_id in Hctx... rewrite neq_id in Hctx...
Qed.
(* ###################################################################### *)
(** *** Substitution *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
(* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then
Gamma |- [x:=v]t : S. *)
intros Gamma x U v t S Htypt Htypv.
generalize dependent Gamma. generalize dependent S.
(* Proof: By induction on the term t. Most cases follow directly
from the IH, with the exception of tvar and tabs.
The former aren't automatic because we must reason about how the
variables interact. *)
t_cases (induction t) Case;
intros S Gamma Htypt; simpl; inversion Htypt; subst...
Case "tvar".
simpl. rename i into y.
(* If t = y, we know that
[empty |- v : U] and
[Gamma,x:U |- y : S]
and, by inversion, [extend Gamma x U y = Some S]. We want to
show that [Gamma |- [x:=v]y : S].
There are two cases to consider: either [x=y] or [x<>y]. *)
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then we know that [U = S], and that [[x:=v]y = v].
So what we really must show is that if [empty |- v : U] then
[Gamma |- v : U]. We have already proven a more general version
of this theorem, called context invariance. *)
subst.
unfold extend in H1. rewrite eq_id in H1.
inversion H1; subst. clear H1.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...
inversion HT'.
SCase "x<>y".
(* If [x <> y], then [Gamma y = Some S] and the substitution has no
effect. We can show that [Gamma |- y : S] by [T_Var]. *)
apply T_Var... unfold extend in H1. rewrite neq_id in H1...
Case "tabs".
rename i into y. rename t into T11.
(* If [t = tabs y T11 t0], then we know that
[Gamma,x:U |- tabs y T11 t0 : T11->T12]
[Gamma,x:U,y:T11 |- t0 : T12]
[empty |- v : U]
As our IH, we know that forall S Gamma,
[Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 : S].
We can calculate that
[x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0)
And we must show that [Gamma |- [x:=v]t : T11->T12]. We know
we will do so using [T_Abs], so it remains to be shown that:
[Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12]
We consider two cases: [x = y] and [x <> y].
*)
apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
(* If [x = y], then the substitution has no effect. Context
invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are
equivalent. Since the former context shows that [t0 : T12], so
does the latter. *)
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
(* If [x <> y], then the IH and context invariance allow us to show that
[Gamma,x:U,y:T11 |- t0 : T12] =>
[Gamma,y:T11,x:U |- t0 : T12] =>
[Gamma,y:T11 |- [x:=v]t0 : T12] *)
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
(* let *)
(* FILL IN HERE *)
Case "tcase".
rename i into x1. rename i0 into x2.
eapply T_Case...
SCase "left arm".
destruct (eq_id_dec x x1).
SSCase "x = x1".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
SSCase "x <> x1".
apply IHt2. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x1 z)...
subst. rewrite neq_id...
SCase "right arm".
destruct (eq_id_dec x x2).
SSCase "x = x2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
SSCase "x <> x2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec x2 z)...
subst. rewrite neq_id...
Case "tlcase".
rename i into y1. rename i0 into y2.
eapply T_Lcase...
destruct (eq_id_dec x y1).
SCase "x=y1".
simpl.
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
SCase "x<>y1".
destruct (eq_id_dec x y2).
SSCase "x=y2".
eapply context_invariance...
subst.
intros z Hafi. unfold extend.
destruct (eq_id_dec y2 z)...
SSCase "x<>y2".
apply IHt3. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y1 z)...
subst. rewrite neq_id...
destruct (eq_id_dec y2 z)...
subst. rewrite neq_id...
Qed.
(* ###################################################################### *)
(** *** Preservation *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
(* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *)
remember (@empty ty) as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
(* Proof: By induction on the given typing derivation. Many cases are
contradictory ([T_Var], [T_Abs]). We show just the interesting ones. *)
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
(* If the last rule used was [T_App], then [t = t1 t2], and three rules
could have been used to show [t ==> t']: [ST_App1], [ST_App2], and
[ST_AppAbs]. In the first two cases, the result follows directly from
the IH. *)
inversion HE; subst...
SCase "ST_AppAbs".
(* For the third case, suppose
[t1 = tabs x T11 t12]
and
[t2 = v2].
We must show that [empty |- [x:=v2]t12 : T2].
We know by assumption that
[empty |- tabs x T11 t12 : T1->T2]
and by inversion
[x:T1 |- t12 : T2]
We have already proven that substitution_preserves_typing and
[empty |- v2 : T1]
by assumption, so we are done. *)
apply substitution_preserves_typing with T1...
inversion HT1...
Case "T_Fst".
inversion HT...
Case "T_Snd".
inversion HT...
(* let *)
(* FILL IN HERE *)
Case "T_Case".
SCase "ST_CaseInl".
inversion HT1; subst.
eapply substitution_preserves_typing...
SCase "ST_CaseInr".
inversion HT1; subst.
eapply substitution_preserves_typing...
Case "T_Lcase".
SCase "ST_LcaseCons".
inversion HT1; subst.
apply substitution_preserves_typing with (TList T1)...
apply substitution_preserves_typing with T1...
(* fix *)
(* FILL IN HERE *)
Qed.
(** [] *)
End STLCExtended.
(* $Date: 2014-12-01 15:15:02 -0500 (Mon, 01 Dec 2014) $ *)
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2011 by Wilson Snyder.
// bug420
typedef logic [7-1:0] wb_ind_t;
typedef logic [7-1:0] id_t;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [31:0] in = crc[31:0];
/*AUTOWIRE*/
wire [6:0] out = line_wb_ind( in[6:0] );
// Aggregate outputs into a single result vector
wire [63:0] result = {57'h0, out};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'hc918fa0aa882a206
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
function wb_ind_t line_wb_ind( id_t id );
if( id[$bits(id_t)-1] == 0 )
return {2'b00, id[$bits(wb_ind_t)-3:0]};
else
return {2'b01, id[$bits(wb_ind_t)-3:0]};
endfunction // line_wb_ind
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2011 by Wilson Snyder.
// bug420
typedef logic [7-1:0] wb_ind_t;
typedef logic [7-1:0] id_t;
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
integer cyc=0;
reg [63:0] crc;
reg [63:0] sum;
// Take CRC data and apply to testblock inputs
wire [31:0] in = crc[31:0];
/*AUTOWIRE*/
wire [6:0] out = line_wb_ind( in[6:0] );
// Aggregate outputs into a single result vector
wire [63:0] result = {57'h0, out};
// Test loop
always @ (posedge clk) begin
`ifdef TEST_VERBOSE
$write("[%0t] cyc==%0d crc=%x result=%x\n",$time, cyc, crc, result);
`endif
cyc <= cyc + 1;
crc <= {crc[62:0], crc[63]^crc[2]^crc[0]};
sum <= result ^ {sum[62:0],sum[63]^sum[2]^sum[0]};
if (cyc==0) begin
// Setup
crc <= 64'h5aef0c8d_d70a4497;
sum <= 64'h0;
end
else if (cyc<10) begin
sum <= 64'h0;
end
else if (cyc<90) begin
end
else if (cyc==99) begin
$write("[%0t] cyc==%0d crc=%x sum=%x\n",$time, cyc, crc, sum);
if (crc !== 64'hc77bb9b3784ea091) $stop;
// What checksum will we end up with (above print should match)
`define EXPECTED_SUM 64'hc918fa0aa882a206
if (sum !== `EXPECTED_SUM) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
end
function wb_ind_t line_wb_ind( id_t id );
if( id[$bits(id_t)-1] == 0 )
return {2'b00, id[$bits(wb_ind_t)-3:0]};
else
return {2'b01, id[$bits(wb_ind_t)-3:0]};
endfunction // line_wb_ind
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/26/2016 09:14:57 AM
// Design Name:
// Module Name: FSM_test
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module FSM_test
(
input wire clk,
input wire rst,
input wire ready_op,
input wire max_tick_address,
input wire max_tick_ch,
input wire TX_DONE,
output reg beg_op,
output reg ack_op,
output reg load_address,
output reg enab_address,
output reg enab_ch,
output reg load_ch,
output reg TX_START
);
//symbolic state declaration
localparam [3:0] est0 = 4'b0000,
est1 = 4'b0001,
est2 = 4'b0010,
est3 = 4'b0011,
est4 = 4'b0100,
est5 = 4'b0101,
est6 = 4'b0110,
est7 = 4'b0111,
est8 = 4'b1000,
est9 = 4'b1001,
est10 = 4'b1010,
est11 = 4'b1011;
//signal declaration
reg [3:0] state_reg, state_next; // Guardan el estado actual y el estado futuro, respectivamente.
//state register
always @( posedge clk, posedge rst)
begin
if(rst) // Si hay reset, el estado actual es el estado inicial.
state_reg <= est0;
else //Si no hay reset el estado actual es igual al estado siguiente.
state_reg <= state_next;
end
//next-state logic and output logic
always @*
begin
state_next = state_reg; // default state : the same
//declaration of default outputs.
beg_op = 1'b0;
ack_op = 1'b0;
load_address = 1'b0;
enab_address = 1'b0;
enab_ch = 1'b0;
load_ch = 1'b0;
TX_START = 1'b0;
case(state_reg)
est0:
begin
state_next = est1;
end
est1:
begin
load_address = 1'b1;
enab_address = 1'b1;
state_next = est2;
end
est2:
begin
beg_op = 1'b1;
state_next=est3;
end
est3:
begin
beg_op = 1'b1;
enab_ch = 1'b1;
load_ch = 1'b1;
state_next=est4;
end
est4:
begin
if(ready_op)
state_next=est5;
else
state_next=est4;
end
est5:
begin
state_next=est6;
end
est6:
begin
TX_START = 1'b1;
state_next=est7;
end
est7:
begin
if(TX_DONE)
if(max_tick_ch)
state_next=est9;
else
begin
state_next=est8;
end
else
state_next=est7;
end
est8:
begin
enab_ch = 1'b1;
state_next=est5;
end
est9:
begin
if(max_tick_address)
state_next=est11;
else
begin
state_next=est10;
end
end
est10:
begin
enab_address = 1'b1;
ack_op = 1'b1;
state_next=est2;
end
est11:
begin
state_next=est11;
end
default:
state_next=est0;
endcase
end
endmodule
|
(** * Sub: Subtyping *)
Require Export Types.
(* ###################################################### *)
(** * Concepts *)
(** We now turn to the study of _subtyping_, perhaps the most
characteristic feature of the static type systems of recently
designed programming languages and a key feature needed to support
the object-oriented programming style. *)
(* ###################################################### *)
(** ** A Motivating Example *)
(** Suppose we are writing a program involving two record types
defined as follows:
<<
Person = {name:String, age:Nat}
Student = {name:String, age:Nat, gpa:Nat}
>>
*)
(** In the simply typed lamdba-calculus with records, the term
<<
(\r:Person. (r.age)+1) {name="Pat",age=21,gpa=1}
>>
is not typable: it involves an application of a function that wants
a one-field record to an argument that actually provides two
fields, while the [T_App] rule demands that the domain type of the
function being applied must match the type of the argument
precisely.
But this is silly: we're passing the function a _better_ argument
than it needs! The only thing the body of the function can
possibly do with its record argument [r] is project the field [age]
from it: nothing else is allowed by the type, and the presence or
absence of an extra [gpa] field makes no difference at all. So,
intuitively, it seems that this function should be applicable to
any record value that has at least an [age] field.
Looking at the same thing from another point of view, a record with
more fields is "at least as good in any context" as one with just a
subset of these fields, in the sense that any value belonging to
the longer record type can be used _safely_ in any context
expecting the shorter record type. If the context expects
something with the shorter type but we actually give it something
with the longer type, nothing bad will happen (formally, the
program will not get stuck).
The general principle at work here is called _subtyping_. We say
that "[S] is a subtype of [T]", informally written [S <: T], if a
value of type [S] can safely be used in any context where a value
of type [T] is expected. The idea of subtyping applies not only to
records, but to all of the type constructors in the language --
functions, pairs, etc. *)
(** ** Subtyping and Object-Oriented Languages *)
(** Subtyping plays a fundamental role in many programming
languages -- in particular, it is closely related to the notion of
_subclassing_ in object-oriented languages.
An _object_ in Java, C[#], etc. can be thought of as a record,
some of whose fields are functions ("methods") and some of whose
fields are data values ("fields" or "instance variables").
Invoking a method [m] of an object [o] on some arguments [a1..an]
consists of projecting out the [m] field of [o] and applying it to
[a1..an].
The type of an object can be given as either a _class_ or an
_interface_. Both of these provide a description of which methods
and which data fields the object offers.
Classes and interfaces are related by the _subclass_ and
_subinterface_ relations. An object belonging to a subclass (or
subinterface) is required to provide all the methods and fields of
one belonging to a superclass (or superinterface), plus possibly
some more.
The fact that an object from a subclass (or sub-interface) can be
used in place of one from a superclass (or super-interface)
provides a degree of flexibility that is is extremely handy for
organizing complex libraries. For example, a GUI toolkit like
Java's Swing framework might define an abstract interface
[Component] that collects together the common fields and methods
of all objects having a graphical representation that can be
displayed on the screen and that can interact with the user.
Examples of such object would include the buttons, checkboxes, and
scrollbars of a typical GUI. A method that relies only on this
common interface can now be applied to any of these objects.
Of course, real object-oriented languages include many other
features besides these. For example, fields can be updated.
Fields and methods can be declared [private]. Classes also give
_code_ that is used when constructing objects and implementing
their methods, and the code in subclasses cooperate with code in
superclasses via _inheritance_. Classes can have static methods
and fields, initializers, etc., etc.
To keep things simple here, we won't deal with any of these
issues -- in fact, we won't even talk any more about objects or
classes. (There is a lot of discussion in _Types and Programming
Languages_, if you are interested.) Instead, we'll study the core
concepts behind the subclass / subinterface relation in the
simplified setting of the STLC. *)
(** *** *)
(** Of course, real OO languages have lots of other features...
- mutable fields
- [private] and other visibility modifiers
- method inheritance
- static components
- etc., etc.
We'll ignore all these and focus on core mechanisms. *)
(** ** The Subsumption Rule *)
(** Our goal for this chapter is to add subtyping to the simply typed
lambda-calculus (with some of the basic extensions from [MoreStlc]).
This involves two steps:
- Defining a binary _subtype relation_ between types.
- Enriching the typing relation to take subtyping into account.
The second step is actually very simple. We add just a single rule
to the typing relation: the so-called _rule of subsumption_:
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
This rule says, intuitively, that it is OK to "forget" some of
what we know about a term. *)
(** For example, we may know that [t] is a record with two
fields (e.g., [S = {x:A->A, y:B->B}]), but choose to forget about
one of the fields ([T = {y:B->B}]) so that we can pass [t] to a
function that requires just a single-field record. *)
(** ** The Subtype Relation *)
(** The first step -- the definition of the relation [S <: T] -- is
where all the action is. Let's look at each of the clauses of its
definition. *)
(** *** Structural Rules *)
(** To start off, we impose two "structural rules" that are
independent of any particular type constructor: a rule of
_transitivity_, which says intuitively that, if [S] is better than
[U] and [U] is better than [T], then [S] is better than [T]...
S <: U U <: T
---------------- (S_Trans)
S <: T
... and a rule of _reflexivity_, since certainly any type [T] is
as good as itself:
------ (S_Refl)
T <: T
*)
(** *** Products *)
(** Now we consider the individual type constructors, one by one,
beginning with product types. We consider one pair to be "better
than" another if each of its components is.
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
*)
(** *** Arrows *)
(** Suppose we have two functions [f] and [g] with these types:
f : C -> Student
g : (C->Person) -> D
That is, [f] is a function that yields a record of type [Student],
and [g] is a (higher-order) function that expects its (function)
argument to yield a record of type [Person]. Also suppose, even
though we haven't yet discussed subtyping for records, that
[Student] is a subtype of [Person]. Then the application [g f] is
safe even though their types do not match up precisely, because
the only thing [g] can do with [f] is to apply it to some
argument (of type [C]); the result will actually be a [Student],
while [g] will be expecting a [Person], but this is safe because
the only thing [g] can then do is to project out the two fields
that it knows about ([name] and [age]), and these will certainly
be among the fields that are present.
This example suggests that the subtyping rule for arrow types
should say that two arrow types are in the subtype relation if
their results are:
S2 <: T2
---------------- (S_Arrow_Co)
S1 -> S2 <: S1 -> T2
We can generalize this to allow the arguments of the two arrow
types to be in the subtype relation as well:
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
Notice that the argument types are subtypes "the other way round":
in order to conclude that [S1->S2] to be a subtype of [T1->T2], it
must be the case that [T1] is a subtype of [S1]. The arrow
constructor is said to be _contravariant_ in its first argument
and _covariant_ in its second.
Here is an example that illustrates this:
f : Person -> C
g : (Student -> C) -> D
The application [g f] is safe, because the only thing the body of
[g] can do with [f] is to apply it to some argument of type
[Student]. Since [f] requires records having (at least) the
fields of a [Person], this will always work. So [Person -> C] is a
subtype of [Student -> C] since [Student] is a subtype of
[Person].
The intuition is that, if we have a function [f] of type [S1->S2],
then we know that [f] accepts elements of type [S1]; clearly, [f]
will also accept elements of any subtype [T1] of [S1]. The type of
[f] also tells us that it returns elements of type [S2]; we can
also view these results belonging to any supertype [T2] of
[S2]. That is, any function [f] of type [S1->S2] can also be
viewed as having type [T1->T2].
*)
(** *** Records *)
(** What about subtyping for record types? *)
(** The basic intuition about subtyping for record types is that it is
always safe to use a "bigger" record in place of a "smaller" one.
That is, given a record type, adding extra fields will always
result in a subtype. If some code is expecting a record with
fields [x] and [y], it is perfectly safe for it to receive a record
with fields [x], [y], and [z]; the [z] field will simply be ignored.
For example,
{name:String, age:Nat, gpa:Nat} <: {name:String, age:Nat}
{name:String, age:Nat} <: {name:String}
{name:String} <: {}
This is known as "width subtyping" for records. *)
(** We can also create a subtype of a record type by replacing the type
of one of its fields with a subtype. If some code is expecting a
record with a field [x] of type [T], it will be happy with a record
having a field [x] of type [S] as long as [S] is a subtype of
[T]. For example,
{x:Student} <: {x:Person}
This is known as "depth subtyping". *)
(** Finally, although the fields of a record type are written in a
particular order, the order does not really matter. For example,
{name:String,age:Nat} <: {age:Nat,name:String}
This is known as "permutation subtyping". *)
(** We could formalize these requirements in a single subtyping rule
for records as follows:
for each jk in j1..jn,
exists ip in i1..im, such that
jk=ip and Sp <: Tk
---------------------------------- (S_Rcd)
{i1:S1...im:Sm} <: {j1:T1...jn:Tn}
That is, the record on the left should have all the field labels of
the one on the right (and possibly more), while the types of the
common fields should be in the subtype relation. However, this rule
is rather heavy and hard to read. If we like, we can decompose it
into three simpler rules, which can be combined using [S_Trans] to
achieve all the same effects. *)
(** First, adding fields to the end of a record type gives a subtype:
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
We can use [S_RcdWidth] to drop later fields of a multi-field
record while keeping earlier fields, showing for example that
[{age:Nat,name:String} <: {name:String}]. *)
(** Second, we can apply subtyping inside the components of a compound
record type:
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
For example, we can use [S_RcdDepth] and [S_RcdWidth] together to
show that [{y:Student, x:Nat} <: {y:Person}]. *)
(** Third, we need to be able to reorder fields. For example, we
might expect that [{name:String, gpa:Nat, age:Nat} <: Person]. We
haven't quite achieved this yet: using just [S_RcdDepth] and
[S_RcdWidth] we can only drop fields from the _end_ of a record
type. So we need:
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(** It is worth noting that full-blown language designs may choose not
to adopt all of these subtyping rules. For example, in Java:
- A subclass may not change the argument or result types of a
method of its superclass (i.e., no depth subtyping or no arrow
subtyping, depending how you look at it).
- Each class has just one superclass ("single inheritance" of
classes).
- Each class member (field or method) can be assigned a single
index, adding new indices "on the right" as more members are
added in subclasses (i.e., no permutation for classes).
- A class may implement multiple interfaces -- so-called "multiple
inheritance" of interfaces (i.e., permutation is allowed for
interfaces). *)
(** **** Exercise: 2 stars (arrow_sub_wrong) *)
(** Suppose we had incorrectly defined subtyping as covariant on both
the right and the left of arrow types:
S1 <: T1 S2 <: T2
-------------------- (S_Arrow_wrong)
S1 -> S2 <: T1 -> T2
Give a concrete example of functions [f] and [g] with the following types...
f : Student -> Nat
g : (Person -> Nat) -> Nat
... such that the application [g f] will get stuck during
execution.
[] *)
(** *** Top *)
(** Finally, it is natural to give the subtype relation a maximal
element -- a type that lies above every other type and is
inhabited by all (well-typed) values. We do this by adding to the
language one new type constant, called [Top], together with a
subtyping rule that places it above every other type in the
subtype relation:
-------- (S_Top)
S <: Top
The [Top] type is an analog of the [Object] type in Java and C[#]. *)
(* ############################################### *)
(** *** Summary *)
(** In summary, we form the STLC with subtyping by starting with the
pure STLC (over some set of base types) and...
- adding a base type [Top],
- adding the rule of subsumption
Gamma |- t : S S <: T
------------------------- (T_Sub)
Gamma |- t : T
to the typing relation, and
- defining a subtype relation as follows:
S <: U U <: T
---------------- (S_Trans)
S <: T
------ (S_Refl)
T <: T
-------- (S_Top)
S <: Top
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1 * S2 <: T1 * T2
T1 <: S1 S2 <: T2
-------------------- (S_Arrow)
S1 -> S2 <: T1 -> T2
n > m
--------------------------------- (S_RcdWidth)
{i1:T1...in:Tn} <: {i1:T1...im:Tm}
S1 <: T1 ... Sn <: Tn
---------------------------------- (S_RcdDepth)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
{i1:S1...in:Sn} is a permutation of {i1:T1...in:Tn}
--------------------------------------------------- (S_RcdPerm)
{i1:S1...in:Sn} <: {i1:T1...in:Tn}
*)
(* ############################################### *)
(** ** Exercises *)
(** **** Exercise: 1 star, optional (subtype_instances_tf_1) *)
(** Suppose we have types [S], [T], [U], and [V] with [S <: T]
and [U <: V]. Which of the following subtyping assertions
are then true? Write _true_ or _false_ after each one.
([A], [B], and [C] here are base types.)
- [T->S <: T->S]
- [Top->U <: S->Top]
- [(C->C) -> (A*B) <: (C->C) -> (Top*B)]
- [T->T->U <: S->S->V]
- [(T->T)->U <: (S->S)->V]
- [((T->S)->T)->U <: ((S->T)->S)->V]
- [S*V <: T*U]
[] *)
(** **** Exercise: 2 stars (subtype_order) *)
(** The following types happen to form a linear order with respect to subtyping:
- [Top]
- [Top -> Student]
- [Student -> Person]
- [Student -> Top]
- [Person -> Student]
Write these types in order from the most specific to the most general.
Where does the type [Top->Top->Student] fit into this order?
*)
(** **** Exercise: 1 star (subtype_instances_tf_2) *)
(** Which of the following statements are true? Write _true_ or
_false_ after each one.
forall S T,
S <: T ->
S->S <: T->T
forall S,
S <: A->A ->
exists T,
S = T->T /\ T <: A
forall S T1 T2,
(S <: T1 -> T2) ->
exists S1 S2,
S = S1 -> S2 /\ T1 <: S1 /\ S2 <: T2
exists S,
S <: S->S
exists S,
S->S <: S
forall S T1 T2,
S <: T1*T2 ->
exists S1 S2,
S = S1*S2 /\ S1 <: T1 /\ S2 <: T2
[] *)
(** **** Exercise: 1 star (subtype_concepts_tf) *)
(** Which of the following statements are true, and which are false?
- There exists a type that is a supertype of every other type.
- There exists a type that is a subtype of every other type.
- There exists a pair type that is a supertype of every other
pair type.
- There exists a pair type that is a subtype of every other
pair type.
- There exists an arrow type that is a supertype of every other
arrow type.
- There exists an arrow type that is a subtype of every other
arrow type.
- There is an infinite descending chain of distinct types in the
subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a subtype of [Si].
- There is an infinite _ascending_ chain of distinct types in
the subtype relation---that is, an infinite sequence of types
[S0], [S1], etc., such that all the [Si]'s are different and
each [S(i+1)] is a supertype of [Si].
[] *)
(** **** Exercise: 2 stars (proper_subtypes) *)
(** Is the following statement true or false? Briefly explain your
answer.
forall T,
~(exists n, T = TBase n) ->
exists S,
S <: T /\ S <> T
]]
[] *)
(** **** Exercise: 2 stars (small_large_1) *)
(**
- What is the _smallest_ type [T] ("smallest" in the subtype
relation) that makes the following assertion true? (Assume we
have [Unit] among the base types and [unit] as a constant of this
type.)
empty |- (\p:T*Top. p.fst) ((\z:A.z), unit) : A->A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_2) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\p:(A->A * B->B). p) ((\z:A.z), (\z:B.z)) : T
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars, optional (small_large_3) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
a:A |- (\p:(A*T). (p.snd) (p.fst)) (a , \z:A.z) : A
- What is the _largest_ type [T] that makes the same assertion true?
[] *)
(** **** Exercise: 2 stars (small_large_4) *)
(**
- What is the _smallest_ type [T] that makes the following
assertion true?
exists S,
empty |- (\p:(A*T). (p.snd) (p.fst)) : S
- What is the _largest_ type [T] that makes the same
assertion true?
[] *)
(** **** Exercise: 2 stars (smallest_1) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
exists S, exists t,
empty |- (\x:T. x x) t : S
]]
[] *)
(** **** Exercise: 2 stars (smallest_2) *)
(** What is the _smallest_ type [T] that makes the following
assertion true?
empty |- (\x:Top. x) ((\z:A.z) , (\z:B.z)) : T
]]
[] *)
(** **** Exercise: 3 stars, optional (count_supertypes) *)
(** How many supertypes does the record type [{x:A, y:C->C}] have? That is,
how many different types [T] are there such that [{x:A, y:C->C} <:
T]? (We consider two types to be different if they are written
differently, even if each is a subtype of the other. For example,
[{x:A,y:B}] and [{y:B,x:A}] are different.)
[] *)
(** **** Exercise: 2 stars (pair_permutation) *)
(** The subtyping rule for product types
S1 <: T1 S2 <: T2
-------------------- (S_Prod)
S1*S2 <: T1*T2
intuitively corresponds to the "depth" subtyping rule for records. Extending the analogy, we might consider adding a "permutation" rule
--------------
T1*T2 <: T2*T1
for products.
Is this a good idea? Briefly explain why or why not.
[] *)
(* ###################################################### *)
(** * Formal Definitions *)
(** Most of the definitions -- in particular, the syntax and
operational semantics of the language -- are identical to what we
saw in the last chapter. We just need to extend the typing
relation with the subsumption rule and add a new [Inductive]
definition for the subtyping relation. Let's first do the
identical bits. *)
(* ###################################################### *)
(** ** Core Definitions *)
(* ################################### *)
(** *** Syntax *)
(** For the sake of more interesting examples below, we'll allow an
arbitrary set of additional base types like [String], [Float],
etc. We won't bother adding any constants belonging to these
types or any operators on them, but we could easily do so. *)
(** In the rest of the chapter, we formalize just base types,
booleans, arrow types, [Unit], and [Top], omitting record types
and leaving product types as an exercise. *)
Inductive ty : Type :=
| TTop : ty
| TBool : ty
| TBase : id -> ty
| TArrow : ty -> ty -> ty
| TUnit : ty
.
Tactic Notation "T_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "TTop" | Case_aux c "TBool"
| Case_aux c "TBase" | Case_aux c "TArrow"
| Case_aux c "TUnit" |
].
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| ttrue : tm
| tfalse : tm
| tif : tm -> tm -> tm -> tm
| tunit : tm
.
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "ttrue"
| Case_aux c "tfalse" | Case_aux c "tif"
| Case_aux c "tunit"
].
(* ################################### *)
(** *** Substitution *)
(** The definition of substitution remains exactly the same as for the
pure STLC. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar y =>
if eq_id_dec x y then s else t
| tabs y T t1 =>
tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| ttrue =>
ttrue
| tfalse =>
tfalse
| tif t1 t2 t3 =>
tif (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
tunit
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ################################### *)
(** *** Reduction *)
(** Likewise the definitions of the [value] property and the [step]
relation. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_true :
value ttrue
| v_false :
value tfalse
| v_unit :
value tunit
.
Hint Constructors value.
Reserved Notation "t1 '==>' t2" (at level 40).
Inductive step : tm -> tm -> Prop :=
| ST_AppAbs : forall x T t12 v2,
value v2 ->
(tapp (tabs x T t12) v2) ==> [x:=v2]t12
| ST_App1 : forall t1 t1' t2,
t1 ==> t1' ->
(tapp t1 t2) ==> (tapp t1' t2)
| ST_App2 : forall v1 t2 t2',
value v1 ->
t2 ==> t2' ->
(tapp v1 t2) ==> (tapp v1 t2')
| ST_IfTrue : forall t1 t2,
(tif ttrue t1 t2) ==> t1
| ST_IfFalse : forall t1 t2,
(tif tfalse t1 t2) ==> t2
| ST_If : forall t1 t1' t2 t3,
t1 ==> t1' ->
(tif t1 t2 t3) ==> (tif t1' t2 t3)
where "t1 '==>' t2" := (step t1 t2).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_IfTrue"
| Case_aux c "ST_IfFalse" | Case_aux c "ST_If"
].
Hint Constructors step.
(* ###################################################################### *)
(** ** Subtyping *)
(** Now we come to the most interesting part. We begin by
defining the subtyping relation and developing some of its
important technical properties. *)
(** The definition of subtyping is just what we sketched in the
motivating discussion. *)
Reserved Notation "T '<:' U" (at level 40).
Inductive subtype : ty -> ty -> Prop :=
| S_Refl : forall T,
T <: T
| S_Trans : forall S U T,
S <: U ->
U <: T ->
S <: T
| S_Top : forall S,
S <: TTop
| S_Arrow : forall S1 S2 T1 T2,
T1 <: S1 ->
S2 <: T2 ->
(TArrow S1 S2) <: (TArrow T1 T2)
where "T '<:' U" := (subtype T U).
(** Note that we don't need any special rules for base types: they are
automatically subtypes of themselves (by [S_Refl]) and [Top] (by
[S_Top]), and that's all we want. *)
Hint Constructors subtype.
Tactic Notation "subtype_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "S_Refl" | Case_aux c "S_Trans"
| Case_aux c "S_Top" | Case_aux c "S_Arrow"
].
Module Examples.
Notation x := (Id 0).
Notation y := (Id 1).
Notation z := (Id 2).
Notation A := (TBase (Id 6)).
Notation B := (TBase (Id 7)).
Notation C := (TBase (Id 8)).
Notation String := (TBase (Id 9)).
Notation Float := (TBase (Id 10)).
Notation Integer := (TBase (Id 11)).
(** **** Exercise: 2 stars, optional (subtyping_judgements) *)
(** (Do this exercise after you have added product types to the
language, at least up to this point in the file).
Using the encoding of records into pairs, define pair types
representing the record types
Person := { name : String }
Student := { name : String ;
gpa : Float }
Employee := { name : String ;
ssn : Integer }
Recall that in chapter MoreStlc, the optional subsection "Encoding
Records" describes how records can be encoded as pairs.
*)
Definition Person : ty :=
(* FILL IN HERE *) admit.
Definition Student : ty :=
(* FILL IN HERE *) admit.
Definition Employee : ty :=
(* FILL IN HERE *) admit.
Example sub_student_person :
Student <: Person.
Proof.
(* FILL IN HERE *) Admitted.
Example sub_employee_person :
Employee <: Person.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
Example subtyping_example_0 :
(TArrow C Person) <: (TArrow C TTop).
(* C->Person <: C->Top *)
Proof.
apply S_Arrow.
apply S_Refl. auto.
Qed.
(** The following facts are mostly easy to prove in Coq. To get
full benefit from the exercises, make sure you also
understand how to prove them on paper! *)
(** **** Exercise: 1 star, optional (subtyping_example_1) *)
Example subtyping_example_1 :
(TArrow TTop Student) <: (TArrow (TArrow C C) Person).
(* Top->Student <: (C->C)->Person *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star, optional (subtyping_example_2) *)
Example subtyping_example_2 :
(TArrow TTop Person) <: (TArrow Person TTop).
(* Top->Person <: Person->Top *)
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
End Examples.
(* ###################################################################### *)
(** ** Typing *)
(** The only change to the typing relation is the addition of the rule
of subsumption, [T_Sub]. *)
Definition context := id -> (option ty).
Definition empty : context := (fun _ => None).
Definition extend (Gamma : context) (x:id) (T : ty) :=
fun x' => if eq_id_dec x x' then Some T else Gamma x'.
Reserved Notation "Gamma '|-' t '\in' T" (at level 40).
Inductive has_type : context -> tm -> ty -> Prop :=
(* Same as before *)
| T_Var : forall Gamma x T,
Gamma x = Some T ->
Gamma |- (tvar x) \in T
| T_Abs : forall Gamma x T11 T12 t12,
(extend Gamma x T11) |- t12 \in T12 ->
Gamma |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma t1 t2,
Gamma |- t1 \in (TArrow T1 T2) ->
Gamma |- t2 \in T1 ->
Gamma |- (tapp t1 t2) \in T2
| T_True : forall Gamma,
Gamma |- ttrue \in TBool
| T_False : forall Gamma,
Gamma |- tfalse \in TBool
| T_If : forall t1 t2 t3 T Gamma,
Gamma |- t1 \in TBool ->
Gamma |- t2 \in T ->
Gamma |- t3 \in T ->
Gamma |- (tif t1 t2 t3) \in T
| T_Unit : forall Gamma,
Gamma |- tunit \in TUnit
(* New rule of subsumption *)
| T_Sub : forall Gamma t S T,
Gamma |- t \in S ->
S <: T ->
Gamma |- t \in T
where "Gamma '|-' t '\in' T" := (has_type Gamma t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs"
| Case_aux c "T_App" | Case_aux c "T_True"
| Case_aux c "T_False" | Case_aux c "T_If"
| Case_aux c "T_Unit"
| Case_aux c "T_Sub" ].
(* To make your job simpler, the following hints help construct typing
derivations. *)
Hint Extern 2 (has_type _ (tapp _ _) _) =>
eapply T_App; auto.
Hint Extern 2 (_ = _) => compute; reflexivity.
(* ############################################### *)
(** ** Typing examples *)
Module Examples2.
Import Examples.
(** Do the following exercises after you have added product types to
the language. For each informal typing judgement, write it as a
formal statement in Coq and prove it. *)
(** **** Exercise: 1 star, optional (typing_example_0) *)
(* empty |- ((\z:A.z), (\z:B.z))
: (A->A * B->B) *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_1) *)
(* empty |- (\x:(Top * B->B). x.snd) ((\z:A.z), (\z:B.z))
: B->B *)
(* FILL IN HERE *)
(** [] *)
(** **** Exercise: 2 stars, optional (typing_example_2) *)
(* empty |- (\z:(C->C)->(Top * B->B). (z (\x:C.x)).snd)
(\z:C->C. ((\z:A.z), (\z:B.z)))
: B->B *)
(* FILL IN HERE *)
(** [] *)
End Examples2.
(* ###################################################################### *)
(** * Properties *)
(** The fundamental properties of the system that we want to check are
the same as always: progress and preservation. Unlike the
extension of the STLC with references, we don't need to change the
_statements_ of these properties to take subtyping into account.
However, their proofs do become a little bit more involved. *)
(* ###################################################################### *)
(** ** Inversion Lemmas for Subtyping *)
(** Before we look at the properties of the typing relation, we need
to record a couple of critical structural properties of the subtype
relation:
- [Bool] is the only subtype of [Bool]
- every subtype of an arrow type is itself an arrow type. *)
(** These are called _inversion lemmas_ because they play the same
role in later proofs as the built-in [inversion] tactic: given a
hypothesis that there exists a derivation of some subtyping
statement [S <: T] and some constraints on the shape of [S] and/or
[T], each one reasons about what this derivation must look like to
tell us something further about the shapes of [S] and [T] and the
existence of subtype relations between their parts. *)
(** **** Exercise: 2 stars, optional (sub_inversion_Bool) *)
Lemma sub_inversion_Bool : forall U,
U <: TBool ->
U = TBool.
Proof with auto.
intros U Hs.
remember TBool as V.
(* FILL IN HERE *) Admitted.
(** **** Exercise: 3 stars, optional (sub_inversion_arrow) *)
Lemma sub_inversion_arrow : forall U V1 V2,
U <: (TArrow V1 V2) ->
exists U1, exists U2,
U = (TArrow U1 U2) /\ (V1 <: U1) /\ (U2 <: V2).
Proof with eauto.
intros U V1 V2 Hs.
remember (TArrow V1 V2) as V.
generalize dependent V2. generalize dependent V1.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ########################################## *)
(** ** Canonical Forms *)
(** We'll see first that the proof of the progress theorem doesn't
change too much -- we just need one small refinement. When we're
considering the case where the term in question is an application
[t1 t2] where both [t1] and [t2] are values, we need to know that
[t1] has the _form_ of a lambda-abstraction, so that we can apply
the [ST_AppAbs] reduction rule. In the ordinary STLC, this is
obvious: we know that [t1] has a function type [T11->T12], and
there is only one rule that can be used to give a function type to
a value -- rule [T_Abs] -- and the form of the conclusion of this
rule forces [t1] to be an abstraction.
In the STLC with subtyping, this reasoning doesn't quite work
because there's another rule that can be used to show that a value
has a function type: subsumption. Fortunately, this possibility
doesn't change things much: if the last rule used to show [Gamma
|- t1 : T11->T12] is subsumption, then there is some
_sub_-derivation whose subject is also [t1], and we can reason by
induction until we finally bottom out at a use of [T_Abs].
This bit of reasoning is packaged up in the following lemma, which
tells us the possible "canonical forms" (i.e. values) of function
type. *)
(** **** Exercise: 3 stars, optional (canonical_forms_of_arrow_types) *)
Lemma canonical_forms_of_arrow_types : forall Gamma s T1 T2,
Gamma |- s \in (TArrow T1 T2) ->
value s ->
exists x, exists S1, exists s2,
s = tabs x S1 s2.
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Similarly, the canonical forms of type [Bool] are the constants
[true] and [false]. *)
Lemma canonical_forms_of_Bool : forall Gamma s,
Gamma |- s \in TBool ->
value s ->
(s = ttrue \/ s = tfalse).
Proof with eauto.
intros Gamma s Hty Hv.
remember TBool as T.
has_type_cases (induction Hty) Case; try solve by inversion...
Case "T_Sub".
subst. apply sub_inversion_Bool in H. subst...
Qed.
(* ########################################## *)
(** ** Progress *)
(** The proof of progress proceeds like the one for the pure
STLC, except that in several places we invoke canonical forms
lemmas... *)
(** _Theorem_ (Progress): For any term [t] and type [T], if [empty |-
t : T] then [t] is a value or [t ==> t'] for some term [t'].
_Proof_: Let [t] and [T] be given, with [empty |- t : T]. Proceed
by induction on the typing derivation.
The cases for [T_Abs], [T_Unit], [T_True] and [T_False] are
immediate because abstractions, [unit], [true], and [false] are
already values. The [T_Var] case is vacuous because variables
cannot be typed in the empty context. The remaining cases are
more interesting:
- If the last step in the typing derivation uses rule [T_App],
then there are terms [t1] [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and [empty |-
t2 : T1]. Moreover, by the induction hypothesis, either [t1] is
a value or it steps, and either [t2] is a value or it steps.
There are three possibilities to consider:
- Suppose [t1 ==> t1'] for some term [t1']. Then [t1 t2 ==> t1' t2]
by [ST_App1].
- Suppose [t1] is a value and [t2 ==> t2'] for some term [t2'].
Then [t1 t2 ==> t1 t2'] by rule [ST_App2] because [t1] is a
value.
- Finally, suppose [t1] and [t2] are both values. By Lemma
[canonical_forms_for_arrow_types], we know that [t1] has the
form [\x:S1.s2] for some [x], [S1], and [s2]. But then
[(\x:S1.s2) t2 ==> [x:=t2]s2] by [ST_AppAbs], since [t2] is a
value.
- If the final step of the derivation uses rule [T_If], then there
are terms [t1], [t2], and [t3] such that [t = if t1 then t2 else
t3], with [empty |- t1 : Bool] and with [empty |- t2 : T] and
[empty |- t3 : T]. Moreover, by the induction hypothesis,
either [t1] is a value or it steps.
- If [t1] is a value, then by the canonical forms lemma for
booleans, either [t1 = true] or [t1 = false]. In either
case, [t] can step, using rule [ST_IfTrue] or [ST_IfFalse].
- If [t1] can step, then so can [t], by rule [ST_If].
- If the final step of the derivation is by [T_Sub], then there is
a type [S] such that [S <: T] and [empty |- t : S]. The desired
result is exactly the induction hypothesis for the typing
subderivation.
*)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof with eauto.
intros t T Ht.
remember empty as Gamma.
revert HeqGamma.
has_type_cases (induction Ht) Case;
intros HeqGamma; subst...
Case "T_Var".
inversion H.
Case "T_App".
right.
destruct IHHt1; subst...
SCase "t1 is a value".
destruct IHHt2; subst...
SSCase "t2 is a value".
destruct (canonical_forms_of_arrow_types empty t1 T1 T2)
as [x [S1 [t12 Heqt1]]]...
subst. exists ([x:=t2]t12)...
SSCase "t2 steps".
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
SCase "t1 steps".
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
Case "T_If".
right.
destruct IHHt1.
SCase "t1 is a value"...
assert (t1 = ttrue \/ t1 = tfalse)
by (eapply canonical_forms_of_Bool; eauto).
inversion H0; subst...
inversion H. rename x into t1'. eauto.
Qed.
(* ########################################## *)
(** ** Inversion Lemmas for Typing *)
(** The proof of the preservation theorem also becomes a little more
complex with the addition of subtyping. The reason is that, as
with the "inversion lemmas for subtyping" above, there are a
number of facts about the typing relation that are "obvious from
the definition" in the pure STLC (and hence can be obtained
directly from the [inversion] tactic) but that require real proofs
in the presence of subtyping because there are multiple ways to
derive the same [has_type] statement.
The following "inversion lemma" tells us that, if we have a
derivation of some typing statement [Gamma |- \x:S1.t2 : T] whose
subject is an abstraction, then there must be some subderivation
giving a type to the body [t2]. *)
(** _Lemma_: If [Gamma |- \x:S1.t2 : T], then there is a type [S2]
such that [Gamma, x:S1 |- t2 : S2] and [S1 -> S2 <: T].
(Notice that the lemma does _not_ say, "then [T] itself is an arrow
type" -- this is tempting, but false!)
_Proof_: Let [Gamma], [x], [S1], [t2] and [T] be given as
described. Proceed by induction on the derivation of [Gamma |-
\x:S1.t2 : T]. Cases [T_Var], [T_App], are vacuous as those
rules cannot be used to give a type to a syntactic abstraction.
- If the last step of the derivation is a use of [T_Abs] then
there is a type [T12] such that [T = S1 -> T12] and [Gamma,
x:S1 |- t2 : T12]. Picking [T12] for [S2] gives us what we
need: [S1 -> T12 <: S1 -> T12] follows from [S_Refl].
- If the last step of the derivation is a use of [T_Sub] then
there is a type [S] such that [S <: T] and [Gamma |- \x:S1.t2 :
S]. The IH for the typing subderivation tell us that there is
some type [S2] with [S1 -> S2 <: S] and [Gamma, x:S1 |- t2 :
S2]. Picking type [S2] gives us what we need, since [S1 -> S2
<: T] then follows by [S_Trans]. *)
Lemma typing_inversion_abs : forall Gamma x S1 t2 T,
Gamma |- (tabs x S1 t2) \in T ->
(exists S2, (TArrow S1 S2) <: T
/\ (extend Gamma x S1) |- t2 \in S2).
Proof with eauto.
intros Gamma x S1 t2 T H.
remember (tabs x S1 t2) as t.
has_type_cases (induction H) Case;
inversion Heqt; subst; intros; try solve by inversion.
Case "T_Abs".
exists T12...
Case "T_Sub".
destruct IHhas_type as [S2 [Hsub Hty]]...
Qed.
(** Similarly... *)
Lemma typing_inversion_var : forall Gamma x T,
Gamma |- (tvar x) \in T ->
exists S,
Gamma x = Some S /\ S <: T.
Proof with eauto.
intros Gamma x T Hty.
remember (tvar x) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_Var".
exists T...
Case "T_Sub".
destruct IHHty as [U [Hctx HsubU]]... Qed.
Lemma typing_inversion_app : forall Gamma t1 t2 T2,
Gamma |- (tapp t1 t2) \in T2 ->
exists T1,
Gamma |- t1 \in (TArrow T1 T2) /\
Gamma |- t2 \in T1.
Proof with eauto.
intros Gamma t1 t2 T2 Hty.
remember (tapp t1 t2) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_App".
exists T1...
Case "T_Sub".
destruct IHHty as [U1 [Hty1 Hty2]]...
Qed.
Lemma typing_inversion_true : forall Gamma T,
Gamma |- ttrue \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember ttrue as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_false : forall Gamma T,
Gamma |- tfalse \in T ->
TBool <: T.
Proof with eauto.
intros Gamma T Htyp. remember tfalse as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
Lemma typing_inversion_if : forall Gamma t1 t2 t3 T,
Gamma |- (tif t1 t2 t3) \in T ->
Gamma |- t1 \in TBool
/\ Gamma |- t2 \in T
/\ Gamma |- t3 \in T.
Proof with eauto.
intros Gamma t1 t2 t3 T Hty.
remember (tif t1 t2 t3) as t.
has_type_cases (induction Hty) Case; intros;
inversion Heqt; subst; try solve by inversion.
Case "T_If".
auto.
Case "T_Sub".
destruct (IHHty H0) as [H1 [H2 H3]]...
Qed.
Lemma typing_inversion_unit : forall Gamma T,
Gamma |- tunit \in T ->
TUnit <: T.
Proof with eauto.
intros Gamma T Htyp. remember tunit as tu.
has_type_cases (induction Htyp) Case;
inversion Heqtu; subst; intros...
Qed.
(** The inversion lemmas for typing and for subtyping between arrow
types can be packaged up as a useful "combination lemma" telling
us exactly what we'll actually require below. *)
Lemma abs_arrow : forall x S1 s2 T1 T2,
empty |- (tabs x S1 s2) \in (TArrow T1 T2) ->
T1 <: S1
/\ (extend empty x S1) |- s2 \in T2.
Proof with eauto.
intros x S1 s2 T1 T2 Hty.
apply typing_inversion_abs in Hty.
inversion Hty as [S2 [Hsub Hty1]].
apply sub_inversion_arrow in Hsub.
inversion Hsub as [U1 [U2 [Heq [Hsub1 Hsub2]]]].
inversion Heq; subst... Qed.
(* ########################################## *)
(** ** Context Invariance *)
(** The context invariance lemma follows the same pattern as in the
pure STLC. *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_if1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif t1 t2 t3)
| afi_if2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif t1 t2 t3)
| afi_if3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif t1 t2 t3)
.
Hint Constructors appears_free_in.
Lemma context_invariance : forall Gamma Gamma' t S,
Gamma |- t \in S ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in S.
Proof with eauto.
intros. generalize dependent Gamma'.
has_type_cases (induction H) Case;
intros Gamma' Heqv...
Case "T_Var".
apply T_Var... rewrite <- Heqv...
Case "T_Abs".
apply T_Abs... apply IHhas_type. intros x0 Hafi.
unfold extend. destruct (eq_id_dec x x0)...
Case "T_If".
apply T_If...
Qed.
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros x t T Gamma Hafi Htyp.
has_type_cases (induction Htyp) Case;
subst; inversion Hafi; subst...
Case "T_Abs".
destruct (IHHtyp H4) as [T Hctx]. exists T.
unfold extend in Hctx. rewrite neq_id in Hctx... Qed.
(* ########################################## *)
(** ** Substitution *)
(** The _substitution lemma_ is proved along the same lines as
for the pure STLC. The only significant change is that there are
several places where, instead of the built-in [inversion] tactic,
we need to use the inversion lemmas that we proved above to
extract structural information from assumptions about the
well-typedness of subterms. *)
Lemma substitution_preserves_typing : forall Gamma x U v t S,
(extend Gamma x U) |- t \in S ->
empty |- v \in U ->
Gamma |- ([x:=v]t) \in S.
Proof with eauto.
intros Gamma x U v t S Htypt Htypv.
generalize dependent S. generalize dependent Gamma.
t_cases (induction t) Case; intros; simpl.
Case "tvar".
rename i into y.
destruct (typing_inversion_var _ _ _ Htypt)
as [T [Hctx Hsub]].
unfold extend in Hctx.
destruct (eq_id_dec x y)...
SCase "x=y".
subst.
inversion Hctx; subst. clear Hctx.
apply context_invariance with empty...
intros x Hcontra.
destruct (free_in_context _ _ S empty Hcontra)
as [T' HT']...
inversion HT'.
Case "tapp".
destruct (typing_inversion_app _ _ _ _ Htypt)
as [T1 [Htypt1 Htypt2]].
eapply T_App...
Case "tabs".
rename i into y. rename t into T1.
destruct (typing_inversion_abs _ _ _ _ _ Htypt)
as [T2 [Hsub Htypt2]].
apply T_Sub with (TArrow T1 T2)... apply T_Abs...
destruct (eq_id_dec x y).
SCase "x=y".
eapply context_invariance...
subst.
intros x Hafi. unfold extend.
destruct (eq_id_dec y x)...
SCase "x<>y".
apply IHt. eapply context_invariance...
intros z Hafi. unfold extend.
destruct (eq_id_dec y z)...
subst. rewrite neq_id...
Case "ttrue".
assert (TBool <: S)
by apply (typing_inversion_true _ _ Htypt)...
Case "tfalse".
assert (TBool <: S)
by apply (typing_inversion_false _ _ Htypt)...
Case "tif".
assert ((extend Gamma x U) |- t1 \in TBool
/\ (extend Gamma x U) |- t2 \in S
/\ (extend Gamma x U) |- t3 \in S)
by apply (typing_inversion_if _ _ _ _ _ Htypt).
inversion H as [H1 [H2 H3]].
apply IHt1 in H1. apply IHt2 in H2. apply IHt3 in H3.
auto.
Case "tunit".
assert (TUnit <: S)
by apply (typing_inversion_unit _ _ Htypt)...
Qed.
(* ########################################## *)
(** ** Preservation *)
(** The proof of preservation now proceeds pretty much as in earlier
chapters, using the substitution lemma at the appropriate point
and again using inversion lemmas from above to extract structural
information from typing assumptions. *)
(** _Theorem_ (Preservation): If [t], [t'] are terms and [T] is a type
such that [empty |- t : T] and [t ==> t'], then [empty |- t' :
T].
_Proof_: Let [t] and [T] be given such that [empty |- t : T]. We
proceed by induction on the structure of this typing derivation,
leaving [t'] general. The cases [T_Abs], [T_Unit], [T_True], and
[T_False] cases are vacuous because abstractions and constants
don't step. Case [T_Var] is vacuous as well, since the context is
empty.
- If the final step of the derivation is by [T_App], then there
are terms [t1] and [t2] and types [T1] and [T2] such that
[t = t1 t2], [T = T2], [empty |- t1 : T1 -> T2], and
[empty |- t2 : T1].
By the definition of the step relation, there are three ways
[t1 t2] can step. Cases [ST_App1] and [ST_App2] follow
immediately by the induction hypotheses for the typing
subderivations and a use of [T_App].
Suppose instead [t1 t2] steps by [ST_AppAbs]. Then [t1 =
\x:S.t12] for some type [S] and term [t12], and [t' =
[x:=t2]t12].
By lemma [abs_arrow], we have [T1 <: S] and [x:S1 |- s2 : T2].
It then follows by the substitution lemma
([substitution_preserves_typing]) that [empty |- [x:=t2]
t12 : T2] as desired.
- If the final step of the derivation uses rule [T_If], then
there are terms [t1], [t2], and [t3] such that [t = if t1 then
t2 else t3], with [empty |- t1 : Bool] and with [empty |- t2 :
T] and [empty |- t3 : T]. Moreover, by the induction
hypothesis, if [t1] steps to [t1'] then [empty |- t1' : Bool].
There are three cases to consider, depending on which rule was
used to show [t ==> t'].
- If [t ==> t'] by rule [ST_If], then [t' = if t1' then t2
else t3] with [t1 ==> t1']. By the induction hypothesis,
[empty |- t1' : Bool], and so [empty |- t' : T] by [T_If].
- If [t ==> t'] by rule [ST_IfTrue] or [ST_IfFalse], then
either [t' = t2] or [t' = t3], and [empty |- t' : T]
follows by assumption.
- If the final step of the derivation is by [T_Sub], then there
is a type [S] such that [S <: T] and [empty |- t : S]. The
result is immediate by the induction hypothesis for the typing
subderivation and an application of [T_Sub]. [] *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
Proof with eauto.
intros t t' T HT.
remember empty as Gamma. generalize dependent HeqGamma.
generalize dependent t'.
has_type_cases (induction HT) Case;
intros t' HeqGamma HE; subst; inversion HE; subst...
Case "T_App".
inversion HE; subst...
SCase "ST_AppAbs".
destruct (abs_arrow _ _ _ _ _ HT1) as [HA1 HA2].
apply substitution_preserves_typing with T...
Qed.
(** ** Records, via Products and Top *)
(** This formalization of the STLC with subtyping has omitted record
types, for brevity. If we want to deal with them more seriously,
we have two choices.
First, we can treat them as part of the core language, writing
down proper syntax, typing, and subtyping rules for them. Chapter
[RecordSub] shows how this extension works.
On the other hand, if we are treating them as a derived form that
is desugared in the parser, then we shouldn't need any new rules:
we should just check that the existing rules for subtyping product
and [Unit] types give rise to reasonable rules for record
subtyping via this encoding. To do this, we just need to make one
small change to the encoding described earlier: instead of using
[Unit] as the base case in the encoding of tuples and the "don't
care" placeholder in the encoding of records, we use [Top]. So:
<<
{a:Nat, b:Nat} ----> {Nat,Nat} i.e. (Nat,(Nat,Top))
{c:Nat, a:Nat} ----> {Nat,Top,Nat} i.e. (Nat,(Top,(Nat,Top)))
>>
The encoding of record values doesn't change at all. It is
easy (and instructive) to check that the subtyping rules above are
validated by the encoding. For the rest of this chapter, we'll
follow this encoding-based approach. *)
(* ###################################################### *)
(** ** Exercises *)
(** **** Exercise: 2 stars (variations) *)
(** Each part of this problem suggests a different way of
changing the definition of the STLC with Unit and
subtyping. (These changes are not cumulative: each part
starts from the original language.) In each part, list which
properties (Progress, Preservation, both, or neither) become
false. If a property becomes false, give a counterexample.
- Suppose we add the following typing rule:
Gamma |- t : S1->S2
S1 <: T1 T1 <: S1 S2 <: T2
----------------------------------- (T_Funny1)
Gamma |- t : T1->T2
- Suppose we add the following reduction rule:
------------------ (ST_Funny21)
unit ==> (\x:Top. x)
- Suppose we add the following subtyping rule:
-------------- (S_Funny3)
Unit <: Top->Top
- Suppose we add the following subtyping rule:
-------------- (S_Funny4)
Top->Top <: Unit
- Suppose we add the following evaluation rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
- Suppose we add the same evaluation rule _and_ a new typing rule:
----------------- (ST_Funny5)
(unit t) ==> (t unit)
---------------------- (T_Funny6)
empty |- Unit : Top->Top
- Suppose we _change_ the arrow subtyping rule to:
S1 <: T1 S2 <: T2
----------------------- (S_Arrow')
S1->S2 <: T1->T2
[] *)
(* ###################################################################### *)
(** * Exercise: Adding Products *)
(** **** Exercise: 4 stars (products) *)
(** Adding pairs, projections, and product types to the system we have
defined is a relatively straightforward matter. Carry out this
extension:
- Add constructors for pairs, first and second projections, and
product types to the definitions of [ty] and [tm]. (Don't
forget to add corresponding cases to [T_cases] and [t_cases].)
- Extend the substitution function and value relation as in
MoreSTLC.
- Extend the operational semantics with the same reduction rules
as in MoreSTLC.
- Extend the subtyping relation with this rule:
S1 <: T1 S2 <: T2
--------------------- (Sub_Prod)
S1 * S2 <: T1 * T2
- Extend the typing relation with the same rules for pairs and
projections as in MoreSTLC.
- Extend the proofs of progress, preservation, and all their
supporting lemmas to deal with the new constructs. (You'll also
need to add some completely new lemmas.)
[] *)
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
`timescale 1ps/1ps
module altera_pll_reconfig_mif_reader
#(
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter MIF_ADDR_WIDTH = 6,
parameter ROM_ADDR_WIDTH = 9, // 512 words x
parameter ROM_DATA_WIDTH = 32, // 32 bits per word = 20kB
parameter ROM_NUM_WORDS = 512, // Default 512 32-bit words = 1 M20K
parameter DEVICE_FAMILY = "Stratix V",
parameter ENABLE_MIF = 0,
parameter MIF_FILE_NAME = ""
) (
// Inputs
input wire mif_clk,
input wire mif_rst,
// Reconfig Module interface for internal register mapping
input wire reconfig_busy, // waitrequest
input wire [RECONFIG_DATA_WIDTH-1:0] reconfig_read_data,
output reg [RECONFIG_DATA_WIDTH-1:0] reconfig_write_data,
output reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_addr,
output reg reconfig_write,
output reg reconfig_read,
// MIF Controller Interface
input wire [ROM_ADDR_WIDTH-1:0] mif_base_addr,
input wire mif_start,
output wire mif_busy
);
// NOTE: Assumes settings opcodes/registers are continguous and OP_MODE is 0
// ROM Interface ctlr states
localparam NUM_STATES = 5;
localparam STATE_REG_WIDTH = 32;
localparam MIF_IDLE = 32'd0;
localparam SET_INSTR_ADDR = 32'd1;
localparam FETCH_INSTR = 32'd2;
localparam WAIT_FOR_ROM_INSTR = 32'd3;
localparam STORE_INSTR = 32'd4;
localparam DECODE_ROM_INSTR = 32'd5;
localparam SET_DATA_ADDR = 32'd6;
localparam SET_DATA_ADDR_DLY = 32'd34;
localparam FETCH_DATA = 32'd7;
localparam WAIT_FOR_ROM_DATA = 32'd8;
localparam STORE_DATA = 32'd9;
localparam SET_INDEX = 32'd35;
localparam CHANGE_SETTINGS_REG = 32'd10;
localparam SET_MODE_REG_INFO = 32'd11;
localparam WAIT_MODE_REG = 32'd12;
localparam SAVE_MODE_REG = 32'd13;
localparam SET_WR_MODE = 32'd14;
localparam WAIT_WRITE_MODE = 32'd15;
localparam INIT_RECONFIG_PARAMS = 32'd16;
localparam CHECK_RECONFIG_SETTING = 32'd17;
localparam WRITE_RECONFIG_SETTING = 32'd18;
localparam DECREMENT_SETTING_NUM = 32'd19;
localparam CHECK_C_SETTINGS = 32'd20;
localparam WRITE_C_SETTINGS = 32'd21;
localparam DECREMENT_C_NUM = 32'd22;
localparam CHECK_DPS_SETTINGS = 32'd23;
localparam WRITE_DPS_SETTINGS = 32'd24;
localparam DECREMENT_DPS_NUM = 32'd25;
localparam START_RECONFIG_CHANGE = 32'd26;
localparam START_RECONFIG_DELAY = 32'd27;
localparam START_RECONFIG_DELAY2 = 32'd28;
localparam WAIT_DONE_SIGNAL = 32'd29;
localparam SET_MODE_REG = 32'd30;
localparam WRITE_FINAL_MODE = 32'd31;
localparam WAIT_FINAL_MODE = 32'd32;
localparam MIF_STREAMING_DONE = 32'd33;
// MIF Opcodes
// Addresses for settings from PLL Reconfig module
localparam OP_MODE = 6'b000000;
localparam OP_STATUS = 6'b000001; // Read only
localparam OP_START = 6'b000010;
localparam OP_N = 6'b000011;
localparam OP_M = 6'b000100;
localparam OP_C_COUNTERS = 6'b000101;
localparam OP_DPS = 6'b000110;
localparam OP_DSM = 6'b000111;
localparam OP_BWCTRL = 6'b001000;
localparam OP_CP_CURRENT = 6'b001001;
localparam OP_SOM = 6'b111110;
localparam OP_EOM = 6'b111111;
localparam INVAL_SETTING = 6'b111100;
localparam MODE_WR = 1'b0;
localparam MODE_POLL = 1'b1;
// Total MIF changeable settings = 8
// + Total non-MIF changeable settings = 2 (status, start)
// + StartOfMif, EndOfMif, Invalid = 3
// = 13 total settings
localparam NUM_SETTINGS = 6'd13;
localparam NUM_MIF_SETTINGS = 6'd10; // Mode = 0.. CP_Current=9
localparam LOG2NUM_SETTINGS = 6; // Consistent with Reconfig addr width
localparam NUM_C_COUNTERS = 5'd18;
localparam LOG2NUM_C_COUNTERS = 3'd5;
localparam NUM_DPS_COUNTERS = 6'd32;
localparam LOG2NUM_DPS_COUNTERS = 3'd6;
// Reconfig Module parameters
localparam WAITREQUEST_MODE = 1'b1;
// Control flow registers
reg [STATE_REG_WIDTH-1:0] mif_curstate;
reg [STATE_REG_WIDTH-1:0] mif_nextstate;
wire is_done;
// Internal data registers
reg [ROM_ADDR_WIDTH-1:0] reg_mif_base_addr;
reg [LOG2NUM_SETTINGS-1:0] reg_instr;
reg [RECONFIG_DATA_WIDTH-1:0] reg_data;
reg [RECONFIG_DATA_WIDTH-1:0] settings_reg [NUM_MIF_SETTINGS-1:0];
reg [RECONFIG_DATA_WIDTH-1:0] c_settings_reg [NUM_C_COUNTERS-1:0];
reg [RECONFIG_DATA_WIDTH-1:0] dps_settings_reg [NUM_DPS_COUNTERS-1:0];
reg [4:0] c_cntr_index; // C cntr is data[22:18];
reg [4:0] dps_index; // DPS is data[20:16];
reg [NUM_SETTINGS-1:0] is_setting_changed; // 1 bit per setting
reg [NUM_C_COUNTERS-1:0] is_c_cntr_changed;
reg [NUM_DPS_COUNTERS-1:0] is_dps_changed;
reg user_mode_setting; // 0 for waitrequest mode, 1 for polling
reg mif_started;
reg saved_mode;
reg mode_reg;
reg [RECONFIG_ADDR_WIDTH-1:0] setting_number;
reg [LOG2NUM_C_COUNTERS-1:0] c_cntr_number;
reg [LOG2NUM_DPS_COUNTERS-1:0] dps_number;
reg c_done;
reg dps_done;
reg is_mode_changed;
// ROM Interface
wire [ROM_DATA_WIDTH-1:0] rom_q;
reg [ROM_ADDR_WIDTH-1:0] rom_addr;
assign mif_busy = (is_done) ? 1'b0 : 1'b1;
// mif_started register
always @(posedge mif_clk)
begin
if (mif_curstate == MIF_IDLE)
mif_started <= 0;
else if (reg_instr == OP_SOM && mif_curstate == DECODE_ROM_INSTR)
mif_started <= 1;
else
mif_started <= mif_started;
end
// is_done logic
assign is_done = (mif_curstate == MIF_IDLE && mif_nextstate == MIF_IDLE) ? 1'b1 : 1'b0;
// State register
always @(posedge mif_clk)
begin
if (mif_rst)
mif_curstate <= MIF_IDLE;
else
mif_curstate <= mif_nextstate;
end
// Next state logic
always @(*)
begin
case (mif_curstate)
MIF_IDLE:
begin
if (mif_start)
mif_nextstate = SET_INSTR_ADDR;
else
mif_nextstate = MIF_IDLE;
end
// Set address for instruction to be fetched from ROM
SET_INSTR_ADDR: // SET_ROM_INFO
begin
mif_nextstate = FETCH_INSTR;
end
FETCH_INSTR:
begin
mif_nextstate = WAIT_FOR_ROM_INSTR;
end
WAIT_FOR_ROM_INSTR:
begin
mif_nextstate = STORE_INSTR;
end
STORE_INSTR:
begin
mif_nextstate = DECODE_ROM_INSTR;
end
DECODE_ROM_INSTR:
begin
if (reg_instr == OP_SOM)
mif_nextstate = SET_INSTR_ADDR;
else if (reg_instr == OP_EOM)
mif_nextstate = SET_MODE_REG_INFO; // Done reading MIF, send it to reconfig module
else
mif_nextstate = SET_DATA_ADDR;
end
SET_DATA_ADDR:
begin
mif_nextstate = SET_DATA_ADDR_DLY;
end
SET_DATA_ADDR_DLY:
begin
mif_nextstate = FETCH_DATA;
end
FETCH_DATA:
begin
mif_nextstate = WAIT_FOR_ROM_DATA;
end
WAIT_FOR_ROM_DATA:
begin
mif_nextstate = STORE_DATA;
end
STORE_DATA:
begin
mif_nextstate = SET_INDEX;
end
SET_INDEX:
begin
mif_nextstate = CHANGE_SETTINGS_REG;
end
CHANGE_SETTINGS_REG:
begin
mif_nextstate = SET_INSTR_ADDR; // Loop back to read rest of MIF file
end
// --- CHANGE RECONFIG REGISTERS --- //
// GENERAL STEPS FOR MANAGING WITH RECONFIG MODULE:
// 1) Save user's configured mode register,
// 2) Change mode to waitrequest mode,
// 3) Send all settings that have changed to
// 4) Start reconfig
// 5) Wait till PLL has locked again.
// 6) Restore user's mode register
SET_MODE_REG_INFO:
begin
mif_nextstate = WAIT_MODE_REG;
end
WAIT_MODE_REG:
begin
mif_nextstate = SAVE_MODE_REG;
end
SAVE_MODE_REG:
begin
mif_nextstate = SET_WR_MODE;
end
SET_WR_MODE:
begin
mif_nextstate = WAIT_WRITE_MODE;
end
WAIT_WRITE_MODE:
begin
mif_nextstate = INIT_RECONFIG_PARAMS;
end
INIT_RECONFIG_PARAMS:
begin
mif_nextstate = CHECK_RECONFIG_SETTING;
end
// PARENT LOOP (writing to reconfig)
CHECK_RECONFIG_SETTING: // Loop over changed settings until setting_num = 0 = MODE
begin
// Don't write the user's mode reg just yet
// Stay in WR mode till we're done with reconfig IP
// then restore the user's old mode/the new mode
// they wrote in the MIF
if (setting_number == 6'b0)
mif_nextstate = START_RECONFIG_CHANGE;
else
begin
if(is_setting_changed[setting_number])
// C and DPS settings are different,
// since multiple can be reconfigured in
// one MIF. If they are changed, check them all.
// In their respective loops
if (setting_number == OP_C_COUNTERS)
begin
mif_nextstate = DECREMENT_C_NUM;
end
else if (setting_number == OP_DPS)
begin
mif_nextstate = DECREMENT_DPS_NUM;
end
else
begin
mif_nextstate = WRITE_RECONFIG_SETTING;
end
else
mif_nextstate = DECREMENT_SETTING_NUM;
end
end
// C LOOP
// We need to check the 0th setting always (unlike the parent loop) so decrement first.
DECREMENT_C_NUM:
begin
if (c_done)
begin
// Done checking and writing C counters
// check next setting in parent loop
mif_nextstate = DECREMENT_SETTING_NUM;
end
else
mif_nextstate = CHECK_C_SETTINGS;
end
CHECK_C_SETTINGS:
begin
if (is_c_cntr_changed[c_cntr_number])
mif_nextstate = WRITE_C_SETTINGS;
else
mif_nextstate = DECREMENT_C_NUM;
end
WRITE_C_SETTINGS:
begin
mif_nextstate = DECREMENT_C_NUM;
end
//End C Loop
// DPS LOOP
// Same as C loop, decrement first.
DECREMENT_DPS_NUM:
begin
if (dps_done)
begin
// Done checking and writing DPS counters
// check next setting in parent loop
mif_nextstate = DECREMENT_SETTING_NUM;
end
else
mif_nextstate = CHECK_DPS_SETTINGS; // Check next DPS setting
end
CHECK_DPS_SETTINGS:
begin
if(is_dps_changed[dps_number])
mif_nextstate = WRITE_DPS_SETTINGS;
else
mif_nextstate = DECREMENT_DPS_NUM;
end
WRITE_DPS_SETTINGS:
begin
mif_nextstate = DECREMENT_DPS_NUM;
end
//End DPS Loop
WRITE_RECONFIG_SETTING:
begin
mif_nextstate = DECREMENT_SETTING_NUM;
end
DECREMENT_SETTING_NUM:
begin
mif_nextstate = CHECK_RECONFIG_SETTING; // Loop back
end
// --- DONE CHANGING SETTINGS, START RECONFIG --- //
START_RECONFIG_CHANGE:
begin
mif_nextstate = START_RECONFIG_DELAY;
end
START_RECONFIG_DELAY:
begin
mif_nextstate = START_RECONFIG_DELAY2;
end
START_RECONFIG_DELAY2: // register at top level before we mux into reconfig
begin
mif_nextstate = WAIT_DONE_SIGNAL;
end
WAIT_DONE_SIGNAL:
begin
if (reconfig_busy)
mif_nextstate = WAIT_DONE_SIGNAL;
else
mif_nextstate = SET_MODE_REG;
end
SET_MODE_REG:
begin
mif_nextstate = WRITE_FINAL_MODE;
end
WRITE_FINAL_MODE:
begin
mif_nextstate = WAIT_FINAL_MODE;
end
WAIT_FINAL_MODE:
begin
mif_nextstate = MIF_STREAMING_DONE;
end
MIF_STREAMING_DONE:
begin
mif_nextstate = MIF_IDLE;
end
default:
begin
mif_nextstate = MIF_IDLE;
end
endcase
end
// Data flow
reg [LOG2NUM_SETTINGS-1:0] i;
reg [LOG2NUM_C_COUNTERS-1:0] j;
reg [LOG2NUM_DPS_COUNTERS-1:0] k;
always @(posedge mif_clk)
begin
if (mif_rst)
begin
reg_mif_base_addr <= 0;
is_setting_changed <= 0;
is_c_cntr_changed <= 0;
is_dps_changed <= 0;
rom_addr <= 0;
reg_instr <= 0;
reg_data <= 0;
for (i = 0; i < NUM_MIF_SETTINGS; i = i + 1'b1)
begin
settings_reg [i] <= 0;
end
for (j = 0; j < NUM_C_COUNTERS; j = j + 1'b1)
begin
c_settings_reg [j] <= 0;
end
for (k = 0; k < NUM_DPS_COUNTERS; k = k + 1'b1)
begin
dps_settings_reg [k] <= 0;
end
setting_number <= 0;
c_cntr_number <= 0;
dps_number <= 0;
c_done <= 0;
dps_done <= 0;
c_cntr_index <= 0;
dps_index <= 0;
reconfig_write_data <= 0;
reconfig_addr <= 0;
reconfig_write <= 0;
reconfig_read <= 0;
end
else
begin
case (mif_curstate)
MIF_IDLE:
begin
reg_mif_base_addr <= mif_base_addr;
is_setting_changed <= 0;
is_c_cntr_changed <= 0;
is_dps_changed <= 0;
rom_addr <= 0;
reg_instr <= 0;
reg_data <= 0;
for (i = 0; i < NUM_MIF_SETTINGS; i = i + 1'b1)
begin
settings_reg [i] <= 0;
end
for (j = 0; j < NUM_C_COUNTERS; j = j + 1'b1)
begin
c_settings_reg [j] <= 0;
end
for (k = 0; k < NUM_DPS_COUNTERS; k = k + 1'b1)
begin
dps_settings_reg [k] <= 0;
end
setting_number <= 0;
c_cntr_number <= 0;
dps_number <= 0;
c_done <= 0;
dps_done <= 0;
c_cntr_index <= 0;
dps_index <= 0;
reconfig_write_data <= 0;
reconfig_addr <= 0;
reconfig_write <= 0;
reconfig_read <= 0;
end
// ----- ROM FLOW ----- //
SET_INSTR_ADDR: rom_addr <= (mif_started) ? rom_addr + 9'd1 : reg_mif_base_addr; // ROM_ADDR_WIDTH = 9
FETCH_INSTR: ;
WAIT_FOR_ROM_INSTR: ;
STORE_INSTR: reg_instr <= rom_q [LOG2NUM_SETTINGS-1:0]; // Only the last 6 bits are instr bits, rest is reserved
DECODE_ROM_INSTR: ;
SET_DATA_ADDR: rom_addr <= rom_addr + 9'd1; // ROM_ADDR_WIDTH = 9
SET_DATA_ADDR_DLY: ;
FETCH_DATA: ;
WAIT_FOR_ROM_DATA: ;
STORE_DATA: reg_data <= rom_q; // Data is 32 bits
SET_INDEX:
begin
c_cntr_index <= reg_data[22:18];
dps_index <= reg_data[20:16];
end
CHANGE_SETTINGS_REG:
begin
if (reg_instr == OP_C_COUNTERS)
begin
c_settings_reg [c_cntr_index] <= reg_data; //22:18 is c cnt number
is_c_cntr_changed [c_cntr_index] <= 1'b1;
end
else if (reg_instr == OP_DPS)
begin
dps_settings_reg [dps_index] <= reg_data; //20:16 is DPS number
is_dps_changed [dps_index] <= 1'b1;
end
else
begin
c_settings_reg [c_cntr_index] <= c_settings_reg [c_cntr_index];
is_c_cntr_changed [c_cntr_index] <= is_c_cntr_changed[c_cntr_index];
dps_settings_reg [dps_index] <= dps_settings_reg [dps_index];
is_dps_changed [dps_index] <= is_dps_changed [dps_index];
end
settings_reg [reg_instr] <= reg_data;
is_setting_changed [reg_instr] <= 1'b1;
end
// ---------- RECONFIG FLOW ---------- //
// Reading/writing mode takes only one cycle
// (we don't know what mode its in initally)
SET_MODE_REG_INFO:
begin
reconfig_addr <= OP_MODE;
reconfig_read <= 1'b1;
reconfig_write <= 1'b0;
reconfig_write_data <= 0;
end
WAIT_MODE_REG: reconfig_read <= 1'b0;
SAVE_MODE_REG: saved_mode <= reconfig_read_data[0];
SET_WR_MODE:
begin
reconfig_addr <= OP_MODE;
reconfig_write <= 1'b1;
reconfig_write_data[0] <= MODE_WR; // Want WaitRequest Mode while MIF reader changes Reconfig regs
end
WAIT_WRITE_MODE: reconfig_write <= 1'b0;
// Done saving the mode reg, start writing the reconfig regs
// Start with the highest setting and work our way down
INIT_RECONFIG_PARAMS:
begin
setting_number <= NUM_MIF_SETTINGS - 6'd1;
c_cntr_number <= NUM_C_COUNTERS;
dps_number <= NUM_DPS_COUNTERS;
end
CHECK_RECONFIG_SETTING: ;
// C LOOP
DECREMENT_C_NUM:
begin
c_cntr_number <= c_cntr_number - 5'd1;
reconfig_write <= 1'b0;
end
CHECK_C_SETTINGS:
begin
if (c_cntr_number == 5'b0)
c_done <= 1'b1;
else
c_done <= c_done;
end
WRITE_C_SETTINGS:
begin
reconfig_addr <= OP_C_COUNTERS;
reconfig_write_data <= c_settings_reg[c_cntr_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
//End C Loop
// DPS LOOP
DECREMENT_DPS_NUM:
begin
dps_number <= dps_number - 5'd1;
reconfig_write <= 1'b0;
end
CHECK_DPS_SETTINGS:
begin
if (dps_number == 5'b0)
dps_done <= 1'b1;
else
dps_done <= dps_done;
end
WRITE_DPS_SETTINGS:
begin
reconfig_addr <= OP_DPS;
reconfig_write_data <= dps_settings_reg[dps_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
//End DPS Loop
WRITE_RECONFIG_SETTING:
begin
reconfig_addr <= setting_number; // setting_number = OP_CODE
reconfig_write_data <= settings_reg[setting_number];
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
DECREMENT_SETTING_NUM:
begin
reconfig_write <= 1'b0;
setting_number <= setting_number - 6'd1; // Decrement for looping back
end
// --- Wrote all the changed settings to the Reconfig IP except MODE
// --- Start the Reconfig process (write to start reg) and wait for
// --- waitrequest signal to deassert
START_RECONFIG_CHANGE:
begin
reconfig_addr <= OP_START;
reconfig_write_data <= 1;
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
START_RECONFIG_DELAY:
begin
reconfig_write <= 1'b0;
end
WAIT_DONE_SIGNAL: ;
// --- Restore saved MODE reg ONLY if mode hasn't been changed by MIF
SET_MODE_REG:
mode_reg <= (is_setting_changed[OP_MODE]) ? settings_reg [OP_MODE][0] : saved_mode;
WRITE_FINAL_MODE:
begin
reconfig_addr <= OP_MODE;
reconfig_write_data[0] <= mode_reg;
reconfig_read <= 1'b0;
reconfig_write <= 1'b1;
end
WAIT_FINAL_MODE:
begin
reconfig_write <= 1'b0;
end
MIF_STREAMING_DONE: ;
default : ;
endcase
end
end
// RAM block
altsyncram altsyncram_component (
.address_a (rom_addr),
.clock0 (mif_clk),
.q_a (rom_q),
.aclr0 (1'b0),
.aclr1 (1'b0),
.address_b (1'b1),
.addressstall_a (1'b0),
.addressstall_b (1'b0),
.byteena_a (1'b1),
.byteena_b (1'b1),
.clock1 (1'b1),
.clocken0 (1'b1),
.clocken1 (1'b1),
.clocken2 (1'b1),
.clocken3 (1'b1),
.data_a ({32{1'b1}}),
.data_b (1'b1),
.eccstatus (),
.q_b (),
.rden_a (1'b1),
.rden_b (1'b1),
.wren_a (1'b0),
.wren_b (1'b0));
defparam
altsyncram_component.address_aclr_a = "NONE",
altsyncram_component.clock_enable_input_a = "BYPASS",
altsyncram_component.clock_enable_output_a = "BYPASS",
altsyncram_component.init_file = MIF_FILE_NAME,
altsyncram_component.intended_device_family = "Stratix V",
altsyncram_component.lpm_hint = "ENABLE_RUNTIME_MOD=NO",
altsyncram_component.lpm_type = "altsyncram",
altsyncram_component.numwords_a = ROM_NUM_WORDS,
altsyncram_component.operation_mode = "ROM",
altsyncram_component.outdata_aclr_a = "NONE",
altsyncram_component.outdata_reg_a = "CLOCK0",
altsyncram_component.widthad_a = ROM_ADDR_WIDTH,
altsyncram_component.width_a = ROM_DATA_WIDTH,
altsyncram_component.width_byteena_a = 1;
endmodule // mif_reader
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_to_avm #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer ID_W = 1
)
(
// AVM interface
output logic avm_read,
output logic avm_write,
output logic [DATA_W-1:0] avm_writedata,
output logic [BURSTCOUNT_W-1:0] avm_burstcount,
output logic [ADDRESS_W-1:0] avm_address,
output logic [BYTEENA_W-1:0] avm_byteenable,
input logic avm_waitrequest,
input logic avm_readdatavalid,
input logic [DATA_W-1:0] avm_readdata,
input logic avm_writeack, // not a true Avalon signal, so ignore this
// IC interface
input logic ic_arb_request,
input logic ic_arb_read,
input logic ic_arb_write,
input logic [DATA_W-1:0] ic_arb_writedata,
input logic [BURSTCOUNT_W-1:0] ic_arb_burstcount,
input logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address,
input logic [BYTEENA_W-1:0] ic_arb_byteenable,
input logic [ID_W-1:0] ic_arb_id,
output logic ic_arb_stall,
output logic ic_wrp_ack,
output logic ic_rrp_datavalid,
output logic [DATA_W-1:0] ic_rrp_data
);
assign avm_read = ic_arb_read;
assign avm_write = ic_arb_write;
assign avm_writedata = ic_arb_writedata;
assign avm_burstcount = ic_arb_burstcount;
assign avm_address = {ic_arb_address, {$clog2(DATA_W / 8){1'b0}}};
assign avm_byteenable = ic_arb_byteenable;
assign ic_arb_stall = avm_waitrequest;
assign ic_rrp_datavalid = avm_readdatavalid;
assign ic_rrp_data = avm_readdata;
//assign ic_wrp_ack = avm_writeack;
assign ic_wrp_ack = avm_write & ~avm_waitrequest;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_to_avm #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer ID_W = 1
)
(
// AVM interface
output logic avm_read,
output logic avm_write,
output logic [DATA_W-1:0] avm_writedata,
output logic [BURSTCOUNT_W-1:0] avm_burstcount,
output logic [ADDRESS_W-1:0] avm_address,
output logic [BYTEENA_W-1:0] avm_byteenable,
input logic avm_waitrequest,
input logic avm_readdatavalid,
input logic [DATA_W-1:0] avm_readdata,
input logic avm_writeack, // not a true Avalon signal, so ignore this
// IC interface
input logic ic_arb_request,
input logic ic_arb_read,
input logic ic_arb_write,
input logic [DATA_W-1:0] ic_arb_writedata,
input logic [BURSTCOUNT_W-1:0] ic_arb_burstcount,
input logic [ADDRESS_W-$clog2(DATA_W / 8)-1:0] ic_arb_address,
input logic [BYTEENA_W-1:0] ic_arb_byteenable,
input logic [ID_W-1:0] ic_arb_id,
output logic ic_arb_stall,
output logic ic_wrp_ack,
output logic ic_rrp_datavalid,
output logic [DATA_W-1:0] ic_rrp_data
);
assign avm_read = ic_arb_read;
assign avm_write = ic_arb_write;
assign avm_writedata = ic_arb_writedata;
assign avm_burstcount = ic_arb_burstcount;
assign avm_address = {ic_arb_address, {$clog2(DATA_W / 8){1'b0}}};
assign avm_byteenable = ic_arb_byteenable;
assign ic_arb_stall = avm_waitrequest;
assign ic_rrp_datavalid = avm_readdatavalid;
assign ic_rrp_data = avm_readdata;
//assign ic_wrp_ack = avm_writeack;
assign ic_wrp_ack = avm_write & ~avm_waitrequest;
endmodule
|
////////////////////////////////////////////////////////////////////////////////
// //
// This file is placed into the Public Domain, for any use, without warranty. //
// 2012 by Iztok Jeras //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// //
// This testbench contains a bus source and a bus drain. The source creates //
// address and data bus values, while the drain is the final destination of //
// such pairs. All source and drain transfers are logged into memories, which //
// are used at the end of simulation to check for data transfer correctness. //
// Inside the RLT wrapper there is a multiplexer and a demultiplexer, they //
// bus transfers into a 8bit data stream and back. Both stream input and //
// output are exposed, they are connected together into a loopback. //
// //
// ----------- --------------------- //
// | bso_mem | | wrap | //
// ----------- | | //
// ----------- | | ----------- | //
// | bsi src | ------------> | -> | mux | -> | -> - sto //
// ----------- | ----------- | \ //
// | | | loopback //
// ----------- | ----------- | / //
// | bso drn | <------------ | <- | demux | <- | <- - sti //
// ----------- | | ----------- | //
// ----------- | | //
// | bso_mem | | | //
// ----------- --------------------- //
// //
// PROTOCOL: //
// //
// The 'vld' signal is driven by the source to indicate valid data is //
// available, 'rdy' is used by the drain to indicate is is ready to accept //
// valid data. A data transfer only happens if both 'vld' & 'rdy' are active. //
// //
////////////////////////////////////////////////////////////////////////////////
`timescale 1ns/1ps
// include RTL files
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_def.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_demux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_mux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_wrap.sv"
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
parameter SIZ = 10;
// system signals
//logic clk = 1'b1; // clock
logic rst = 1'b1; // reset
integer rst_cnt = 0;
// input bus
logic bsi_vld; // valid (chip select)
logic [31:0] bsi_adr; // address
logic [31:0] bsi_dat; // data
logic bsi_rdy; // ready (acknowledge)
logic bsi_trn; // data transfer
logic [31:0] bsi_mem [SIZ];
// output stream
logic sto_vld; // valid (chip select)
logic [7:0] sto_bus; // data bus
logic sto_rdy; // ready (acknowledge)
// input stream
logic sti_vld; // valid (chip select)
logic [7:0] sti_bus; // data bus
logic sti_rdy; // ready (acknowledge)
// output bus
logic bso_vld; // valid (chip select)
logic [31:0] bso_adr; // address
logic [31:0] bso_dat; // data
logic bso_rdy; // ready (acknowledge)
logic bso_trn; // data transfer
logic [31:0] bso_mem [SIZ];
integer bso_cnt = 0;
////////////////////////////////////////////////////////////////////////////////
// clock and reset
////////////////////////////////////////////////////////////////////////////////
// clock toggling
//always #5 clk = ~clk;
// reset is removed after a delay
always @ (posedge clk)
begin
rst_cnt <= rst_cnt + 1;
rst <= rst_cnt <= 3;
end
// reset is removed after a delay
always @ (posedge clk)
if (bso_cnt == SIZ) begin
if (bsi_mem === bso_mem) begin $write("*-* All Finished *-*\n"); $finish(); end
else begin $display ("FAILED"); $stop(); end
end
////////////////////////////////////////////////////////////////////////////////
// input data generator
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bsi_trn = bsi_vld & bsi_rdy;
// valid (for SIZ transfers)
always @ (posedge clk, posedge rst)
if (rst) bsi_vld = 1'b0;
else bsi_vld = (bsi_adr < SIZ);
// address (increments every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_adr <= 32'h00000000;
else if (bsi_trn) bsi_adr <= bsi_adr + 'd1;
// data (new random value generated after every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_dat <= 32'h00000000;
else if (bsi_trn) bsi_dat <= $random();
// storing transferred data into memory for final check
always @ (posedge clk)
if (bsi_trn) bsi_mem [bsi_adr] <= bsi_dat;
////////////////////////////////////////////////////////////////////////////////
// RTL instance
////////////////////////////////////////////////////////////////////////////////
sv_bus_mux_demux_wrap wrap (
// system signals
.clk (clk),
.rst (rst),
// input bus
.bsi_vld (bsi_vld),
.bsi_adr (bsi_adr),
.bsi_dat (bsi_dat),
.bsi_rdy (bsi_rdy),
// output stream
.sto_vld (sto_vld),
.sto_bus (sto_bus),
.sto_rdy (sto_rdy),
// input stream
.sti_vld (sti_vld),
.sti_bus (sti_bus),
.sti_rdy (sti_rdy),
// output bus
.bso_vld (bso_vld),
.bso_adr (bso_adr),
.bso_dat (bso_dat),
.bso_rdy (bso_rdy)
);
// stream output from mux is looped back into stream input for demux
assign sti_vld = sto_vld;
assign sti_bus = sto_bus;
assign sto_rdy = sti_rdy;
////////////////////////////////////////////////////////////////////////////////
// output data monitor
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bso_trn = bso_vld & bso_rdy;
// output transfer counter used to end the test
always @ (posedge clk, posedge rst)
if (rst) bso_cnt <= 0;
else if (bso_trn) bso_cnt <= bso_cnt + 1;
// storing transferred data into memory for final check
always @ (posedge clk)
if (bso_trn) bso_mem [bso_adr] <= bso_dat;
// every output transfer against expected value stored in memory
always @ (posedge clk)
if (bso_trn && (bsi_mem [bso_adr] !== bso_dat))
$display ("@%08h i:%08h o:%08h", bso_adr, bsi_mem [bso_adr], bso_dat);
// ready is active for SIZ transfers
always @ (posedge clk, posedge rst)
if (rst) bso_rdy = 1'b0;
else bso_rdy = 1'b1;
endmodule : sv_bus_mux_demux_tb
|
////////////////////////////////////////////////////////////////////////////////
// //
// This file is placed into the Public Domain, for any use, without warranty. //
// 2012 by Iztok Jeras //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// //
// This testbench contains a bus source and a bus drain. The source creates //
// address and data bus values, while the drain is the final destination of //
// such pairs. All source and drain transfers are logged into memories, which //
// are used at the end of simulation to check for data transfer correctness. //
// Inside the RLT wrapper there is a multiplexer and a demultiplexer, they //
// bus transfers into a 8bit data stream and back. Both stream input and //
// output are exposed, they are connected together into a loopback. //
// //
// ----------- --------------------- //
// | bso_mem | | wrap | //
// ----------- | | //
// ----------- | | ----------- | //
// | bsi src | ------------> | -> | mux | -> | -> - sto //
// ----------- | ----------- | \ //
// | | | loopback //
// ----------- | ----------- | / //
// | bso drn | <------------ | <- | demux | <- | <- - sti //
// ----------- | | ----------- | //
// ----------- | | //
// | bso_mem | | | //
// ----------- --------------------- //
// //
// PROTOCOL: //
// //
// The 'vld' signal is driven by the source to indicate valid data is //
// available, 'rdy' is used by the drain to indicate is is ready to accept //
// valid data. A data transfer only happens if both 'vld' & 'rdy' are active. //
// //
////////////////////////////////////////////////////////////////////////////////
`timescale 1ns/1ps
// include RTL files
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_def.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_demux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_mux.sv"
`include "t_sv_bus_mux_demux/sv_bus_mux_demux_wrap.sv"
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
parameter SIZ = 10;
// system signals
//logic clk = 1'b1; // clock
logic rst = 1'b1; // reset
integer rst_cnt = 0;
// input bus
logic bsi_vld; // valid (chip select)
logic [31:0] bsi_adr; // address
logic [31:0] bsi_dat; // data
logic bsi_rdy; // ready (acknowledge)
logic bsi_trn; // data transfer
logic [31:0] bsi_mem [SIZ];
// output stream
logic sto_vld; // valid (chip select)
logic [7:0] sto_bus; // data bus
logic sto_rdy; // ready (acknowledge)
// input stream
logic sti_vld; // valid (chip select)
logic [7:0] sti_bus; // data bus
logic sti_rdy; // ready (acknowledge)
// output bus
logic bso_vld; // valid (chip select)
logic [31:0] bso_adr; // address
logic [31:0] bso_dat; // data
logic bso_rdy; // ready (acknowledge)
logic bso_trn; // data transfer
logic [31:0] bso_mem [SIZ];
integer bso_cnt = 0;
////////////////////////////////////////////////////////////////////////////////
// clock and reset
////////////////////////////////////////////////////////////////////////////////
// clock toggling
//always #5 clk = ~clk;
// reset is removed after a delay
always @ (posedge clk)
begin
rst_cnt <= rst_cnt + 1;
rst <= rst_cnt <= 3;
end
// reset is removed after a delay
always @ (posedge clk)
if (bso_cnt == SIZ) begin
if (bsi_mem === bso_mem) begin $write("*-* All Finished *-*\n"); $finish(); end
else begin $display ("FAILED"); $stop(); end
end
////////////////////////////////////////////////////////////////////////////////
// input data generator
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bsi_trn = bsi_vld & bsi_rdy;
// valid (for SIZ transfers)
always @ (posedge clk, posedge rst)
if (rst) bsi_vld = 1'b0;
else bsi_vld = (bsi_adr < SIZ);
// address (increments every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_adr <= 32'h00000000;
else if (bsi_trn) bsi_adr <= bsi_adr + 'd1;
// data (new random value generated after every transfer)
always @ (posedge clk, posedge rst)
if (rst) bsi_dat <= 32'h00000000;
else if (bsi_trn) bsi_dat <= $random();
// storing transferred data into memory for final check
always @ (posedge clk)
if (bsi_trn) bsi_mem [bsi_adr] <= bsi_dat;
////////////////////////////////////////////////////////////////////////////////
// RTL instance
////////////////////////////////////////////////////////////////////////////////
sv_bus_mux_demux_wrap wrap (
// system signals
.clk (clk),
.rst (rst),
// input bus
.bsi_vld (bsi_vld),
.bsi_adr (bsi_adr),
.bsi_dat (bsi_dat),
.bsi_rdy (bsi_rdy),
// output stream
.sto_vld (sto_vld),
.sto_bus (sto_bus),
.sto_rdy (sto_rdy),
// input stream
.sti_vld (sti_vld),
.sti_bus (sti_bus),
.sti_rdy (sti_rdy),
// output bus
.bso_vld (bso_vld),
.bso_adr (bso_adr),
.bso_dat (bso_dat),
.bso_rdy (bso_rdy)
);
// stream output from mux is looped back into stream input for demux
assign sti_vld = sto_vld;
assign sti_bus = sto_bus;
assign sto_rdy = sti_rdy;
////////////////////////////////////////////////////////////////////////////////
// output data monitor
////////////////////////////////////////////////////////////////////////////////
// input data transfer
assign bso_trn = bso_vld & bso_rdy;
// output transfer counter used to end the test
always @ (posedge clk, posedge rst)
if (rst) bso_cnt <= 0;
else if (bso_trn) bso_cnt <= bso_cnt + 1;
// storing transferred data into memory for final check
always @ (posedge clk)
if (bso_trn) bso_mem [bso_adr] <= bso_dat;
// every output transfer against expected value stored in memory
always @ (posedge clk)
if (bso_trn && (bsi_mem [bso_adr] !== bso_dat))
$display ("@%08h i:%08h o:%08h", bso_adr, bsi_mem [bso_adr], bso_dat);
// ready is active for SIZ transfers
always @ (posedge clk, posedge rst)
if (rst) bso_rdy = 1'b0;
else bso_rdy = 1'b1;
endmodule : sv_bus_mux_demux_tb
|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
//
// The given generate loops should only access valid bits of mask, since that
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 4
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, but for good measure we do one clock
// cycle.
integer count;
initial begin
count = 0;
end
always @(posedge clk) begin
if (count == 1) begin
$write("*-* All Finished *-*\n");
$finish;
end
else begin
count = count + 1;
end
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that rely on short-circuiting of the logic to avoid errors.
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) || ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g < SIZE) -> ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical infer generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ( g < SIZE ? MASK[g] : 1'b0) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Conditional generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
// The other way round
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ( g >= SIZE ? 1'b0 : MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Conditional generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test for short-circuiting in generate "if"
//
// The given generate loops should only access valid bits of mask, since that
// is defined by SIZE. However since the loop range is larger, this only works
// if short-circuited evaluation of the generate loop is in place.
// This file ONLY is placed into the Public Domain, for any use, without
// warranty, 2012 by Jeremy Bennett.
`define MAX_SIZE 4
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
// Set the parameters, so that we use a size less than MAX_SIZE
test_gen
#(.SIZE (2),
.MASK (2'b11))
i_test_gen (.clk (clk));
// This is only a compilation test, but for good measure we do one clock
// cycle.
integer count;
initial begin
count = 0;
end
always @(posedge clk) begin
if (count == 1) begin
$write("*-* All Finished *-*\n");
$finish;
end
else begin
count = count + 1;
end
end
endmodule // t
module test_gen
#( parameter
SIZE = `MAX_SIZE,
MASK = `MAX_SIZE'b0)
(/*AUTOARG*/
// Inputs
clk
);
input clk;
// Generate blocks that rely on short-circuiting of the logic to avoid errors.
generate
genvar g;
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ((g < SIZE) && MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical AND generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g >= SIZE) || ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical OR generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if (!((g < SIZE) -> ~MASK[g])) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Logical infer generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ( g < SIZE ? MASK[g] : 1'b0) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Conditional generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
// The other way round
generate
for (g = 0; g < `MAX_SIZE; g = g + 1) begin
if ( g >= SIZE ? 1'b0 : MASK[g]) begin
always @(posedge clk) begin
`ifdef TEST_VERBOSE
$write ("Conditional generate if MASK [%1d] = %d\n", g, MASK[g]);
`endif
if (g >= SIZE) begin
$stop;
end
end
end
end
endgenerate
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;
localparam P4 = f_add(P3,1);
localparam P8 = f_add2(P3,P3,f_add(1,1));
localparam P5 = f_while(7);
localparam P16 = f_for(P4);
localparam P18 = f_case(P4);
localparam P6 = f_return(P4);
localparam P3 = 3;
initial begin
`ifdef TEST_VERBOSE
$display("P5=%0d P8=%0d P16=%0d P18=%0d",P5,P8,P16,P18);
`endif
if (P3 !== 3) $stop;
if (P4 !== 4) $stop;
if (P5 !== 5) $stop;
if (P6 !== 6) $stop;
if (P8 !== 8) $stop;
if (P16 !== 16) $stop;
if (P18 !== 18) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
function integer f_add(input [31:0] a, input [31:0] b);
f_add = a+b;
endfunction
// Speced ok: function called from function
function integer f_add2(input [31:0] a, input [31:0] b, input [31:0] c);
f_add2 = f_add(a,b)+c;
endfunction
// Speced ok: local variables
function integer f_for(input [31:0] a);
integer i;
integer times;
begin
times = 1;
for (i=0; i<a; i=i+1) times = times*2;
f_for = times;
end
endfunction
function integer f_while(input [31:0] a);
integer i;
begin
i=0;
begin : named
f_while = 1;
end : named
while (i<=a) begin
if (i[0]) f_while = f_while + 1;
i = i + 1;
end
end
endfunction
// Speced ok: local variables
function integer f_case(input [31:0] a);
case(a)
32'd1: f_case = 1;
32'd0, 32'd4: f_case = 18;
32'd1234: begin $display("never get here"); $stop; end
default: f_case = 99;
endcase
endfunction
function integer f_return(input [31:0] a);
integer out = 2;
while (1) begin
out = out+1;
if (a>1) break;
end
while (1) begin
out = out+1;
if (a>1) return 2+out;
end
f_return = 0;
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.
module t;
localparam P4 = f_add(P3,1);
localparam P8 = f_add2(P3,P3,f_add(1,1));
localparam P5 = f_while(7);
localparam P16 = f_for(P4);
localparam P18 = f_case(P4);
localparam P6 = f_return(P4);
localparam P3 = 3;
initial begin
`ifdef TEST_VERBOSE
$display("P5=%0d P8=%0d P16=%0d P18=%0d",P5,P8,P16,P18);
`endif
if (P3 !== 3) $stop;
if (P4 !== 4) $stop;
if (P5 !== 5) $stop;
if (P6 !== 6) $stop;
if (P8 !== 8) $stop;
if (P16 !== 16) $stop;
if (P18 !== 18) $stop;
$write("*-* All Finished *-*\n");
$finish;
end
function integer f_add(input [31:0] a, input [31:0] b);
f_add = a+b;
endfunction
// Speced ok: function called from function
function integer f_add2(input [31:0] a, input [31:0] b, input [31:0] c);
f_add2 = f_add(a,b)+c;
endfunction
// Speced ok: local variables
function integer f_for(input [31:0] a);
integer i;
integer times;
begin
times = 1;
for (i=0; i<a; i=i+1) times = times*2;
f_for = times;
end
endfunction
function integer f_while(input [31:0] a);
integer i;
begin
i=0;
begin : named
f_while = 1;
end : named
while (i<=a) begin
if (i[0]) f_while = f_while + 1;
i = i + 1;
end
end
endfunction
// Speced ok: local variables
function integer f_case(input [31:0] a);
case(a)
32'd1: f_case = 1;
32'd0, 32'd4: f_case = 18;
32'd1234: begin $display("never get here"); $stop; end
default: f_case = 99;
endcase
endfunction
function integer f_return(input [31:0] a);
integer out = 2;
while (1) begin
out = out+1;
if (a>1) break;
end
while (1) begin
out = out+1;
if (a>1) return 2+out;
end
f_return = 0;
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.
// This is almost an exact copy of the lsu_burst_master, but has special support
// for placing items into a a block ram rather than a fifo. I'd rather leave them
// as separate files rather than complicating the already existing lsu's which are
// are known to work.
//
// Helper module to handle bursting large sequential blocks of memory to or
// from global memory.
//
/*****************************************************************************/
// Burst read master:
// Keeps a local buffer populated with data from a sequential block of
// global memory. The block of global memory is specified by a base address
// and size.
/*****************************************************************************/
module lsu_prefetch_block (
clk,
reset,
o_active, //Debugging signal
// control inputs and outputs
control_fixed_location,
control_read_base,
control_read_length,
control_go,
cache_line_to_write_to,
control_done,
control_early_done,
// user logic inputs and outputs
cache_line_to_read_from,
user_buffer_address,
user_buffer_data,
user_data_available,
read_reg_enable,
// master inputs and outputs
master_address,
master_read,
master_byteenable,
master_readdata,
master_readdatavalid,
master_burstcount,
master_waitrequest
);
/*************
* Parameters *
*************/
parameter DATAWIDTH = 32;
parameter MWIDTH = DATAWIDTH;
parameter MAXBURSTCOUNT = 4;
parameter BURSTCOUNTWIDTH = 3;
parameter BYTEENABLEWIDTH = 4;
parameter ADDRESSWIDTH = 32;
parameter FIFODEPTH = 32;
parameter FIFODEPTH_LOG2 = 5;
parameter FIFOUSEMEMORY = 1; // set to 0 to use LEs instead
parameter N=8;
parameter LOG2N=3;
/********
* Ports *
********/
input clk;
input reset;
output o_active;
// control inputs and outputs
input control_fixed_location;
input [ADDRESSWIDTH-1:0] control_read_base;
input [ADDRESSWIDTH-1:0] control_read_length;
input control_go;
input [LOG2N-1:0] cache_line_to_write_to;
output wire control_done;
output wire control_early_done; // don't use this unless you know what you are doing, it's going to fire when the last read is posted, not when the last data returns!
// user logic inputs and outputs
input [LOG2N-1:0] cache_line_to_read_from;
input [FIFODEPTH_LOG2-1:0] user_buffer_address;
output wire [DATAWIDTH-1:0] user_buffer_data;
output wire user_data_available;
input read_reg_enable;
// master inputs and outputs
input master_waitrequest;
input master_readdatavalid;
input [DATAWIDTH-1:0] master_readdata;
output wire [ADDRESSWIDTH-1:0] master_address;
output wire master_read;
output wire [BYTEENABLEWIDTH-1:0] master_byteenable;
output wire [BURSTCOUNTWIDTH-1:0] master_burstcount;
/***************
* Architecture *
***************/
// internal control signals
reg control_fixed_location_d1;
reg [ADDRESSWIDTH-1:0] address;
reg [ADDRESSWIDTH-1:0] length;
wire increment_address;
wire [BURSTCOUNTWIDTH-1:0] burst_count;
wire [BURSTCOUNTWIDTH-1:0] first_short_burst_count;
wire first_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] final_short_burst_count;
wire final_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] burst_boundary_word_address;
wire too_many_reads_pending;
reg [FIFODEPTH_LOG2:0] w_user_buffer_address;
// Pipelining
reg r_avm_readdatavalid;
reg [MWIDTH-1:0] r_avm_readdata /* synthesis dont_merge */;
// registering the control_fixed_location bit
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
control_fixed_location_d1 <= 0;
end
else
begin
if (control_go == 1)
begin
control_fixed_location_d1 <= control_fixed_location;
end
end
end
// master address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
address <= 0;
end
else
begin
if(control_go == 1)
begin
address <= control_read_base;
end
else if((increment_address == 1) & (control_fixed_location_d1 == 0))
begin
address <= address + (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, increment by the burst count presented
end
end
end
// user buffer address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
w_user_buffer_address <= 0;
end
else
begin
if(control_go == 1)
begin
w_user_buffer_address <= 0;
end
else
begin
w_user_buffer_address <= w_user_buffer_address + r_avm_readdatavalid;
end
end
end
// master length logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
length <= 0;
end
else
begin
if(control_go == 1)
begin
length <= control_read_length;
end
else if(increment_address == 1)
begin
length <= length - (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, decrement by the burst count presented
end
end
end
// controlled signals going to the master/control ports
assign master_address = address;
assign master_byteenable = -1; // all ones, always performing word size accesses
assign master_burstcount = burst_count;
assign control_done = 1'b0;
assign control_early_done = 1'b0;
assign master_read = (too_many_reads_pending == 0) & (length != 0);
assign burst_boundary_word_address = ((address / BYTEENABLEWIDTH) & (MAXBURSTCOUNT - 1));
assign first_short_burst_enable = (burst_boundary_word_address != 0);
assign final_short_burst_enable = (length < (MAXBURSTCOUNT * BYTEENABLEWIDTH));
assign first_short_burst_count = ((burst_boundary_word_address & 1'b1) == 1'b1)? 1 : // if the burst boundary isn't a multiple of 2 then must post a burst of 1 to get to a multiple of 2 for the next burst
(((MAXBURSTCOUNT - burst_boundary_word_address) < (length / BYTEENABLEWIDTH))?
(MAXBURSTCOUNT - burst_boundary_word_address) : (length / BYTEENABLEWIDTH));
assign final_short_burst_count = (length / BYTEENABLEWIDTH);
assign burst_count = (first_short_burst_enable == 1)? first_short_burst_count : // this will get the transfer back on a burst boundary,
(final_short_burst_enable == 1)? final_short_burst_count : MAXBURSTCOUNT;
assign increment_address = (too_many_reads_pending == 0) & (master_waitrequest == 0) & (length != 0);
assign too_many_reads_pending = 0;
/* --- Pipeline Return Path --- */
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
r_avm_readdata <= 'x;
r_avm_readdatavalid <= 1'b0;
end
else
begin
r_avm_readdata <= master_readdata;
r_avm_readdatavalid <= master_readdatavalid;
end
end
assign user_data_available = w_user_buffer_address[FIFODEPTH_LOG2];
altsyncram altsyncram_component (
.clock0 (clk),
.address_a ({cache_line_to_write_to,w_user_buffer_address[FIFODEPTH_LOG2-1:0]}),
.wren_a (r_avm_readdatavalid),
.data_a (r_avm_readdata),
.address_b ({cache_line_to_read_from,user_buffer_address}),
.q_b (user_buffer_data),
.aclr0 (1'b0),
.aclr1 (1'b0),
.addressstall_a (1'b0),
.addressstall_b (~read_reg_enable),
.byteena_a (1'b1),
.byteena_b (1'b1),
.clock1 (1'b1),
.clocken0 (1'b1),
.clocken1 (1'b1),
.clocken2 (1'b1),
.clocken3 (1'b1),
.data_b ({DATAWIDTH{1'b1}}),
.eccstatus (),
.q_a (),
.rden_a (1'b1),
.rden_b (1'b1),
.wren_b (1'b0));
defparam
altsyncram_component.address_aclr_b = "NONE",
altsyncram_component.address_reg_b = "CLOCK0",
altsyncram_component.clock_enable_input_a = "BYPASS",
altsyncram_component.clock_enable_input_b = "BYPASS",
altsyncram_component.clock_enable_output_b = "BYPASS",
altsyncram_component.intended_device_family = "Stratix IV",
altsyncram_component.lpm_type = "altsyncram",
altsyncram_component.numwords_a = N*FIFODEPTH,
altsyncram_component.numwords_b = N*FIFODEPTH,
altsyncram_component.operation_mode = "DUAL_PORT",
altsyncram_component.outdata_aclr_b = "NONE",
altsyncram_component.outdata_reg_b = "UNREGISTERED",
altsyncram_component.power_up_uninitialized = "FALSE",
altsyncram_component.read_during_write_mode_mixed_ports = "DONT_CARE",
altsyncram_component.widthad_a = FIFODEPTH_LOG2+LOG2N,
altsyncram_component.widthad_b = FIFODEPTH_LOG2+LOG2N,
altsyncram_component.width_a = DATAWIDTH,
altsyncram_component.width_b = DATAWIDTH,
altsyncram_component.width_byteena_a = 1;
assign o_active = |length;
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.
/********
* This module captures the relative frequency with which each bit in 'value'
* toggles. This can be useful for detecting address patterns for example.
*
* Eg. (in hex)
* Linear: 1ff ff 80 40 20 10 08 04 02 1 0 0 0 ...
* Linear predicated: 1ff ff 80 40 00 00 00 20 10 8 4 2 1 0 0 0 ...
* Strided: 00 00 ff 80 40 20 10 08 04 02 1 0 0 0 ...
* Random: ff ff ff ff ff ff ff ff ff ...
*
* The counters that track the toggle rates automatically get divided by 2 once
* any of their values comes close to overflowing. Hence the toggle rates are
* relative, and comparable only within a single module instance.
*
* The last counter (count[WIDTH]) is a saturating counter storing the number of
* times a scaledown was performed. If you assume the relative rates don't
* change between scaledowns, this can be used to approximate absolute toggle
* rates (which can be compared against rates from another instance).
*****************/
module acl_toggle_detect
#(
parameter WIDTH=13, // Width of input signal in bits
parameter COUNTERWIDTH=10 // in bits, MUST be greater than 3
)
(
input logic clk,
input logic resetn,
input logic valid,
input logic [WIDTH-1:0] value,
output logic [COUNTERWIDTH-1:0] count[WIDTH+1]
);
/******************
* LOCAL PARAMETERS
*******************/
/******************
* SIGNALS
*******************/
logic [WIDTH-1:0] last_value;
logic [WIDTH-1:0] bits_toggled;
logic scaledown;
/******************
* ARCHITECTURE
*******************/
always@(posedge clk or negedge resetn)
if (!resetn)
last_value<={WIDTH{1'b0}};
else if (valid)
last_value<=value;
// Compute which bits toggled via XOR
always@(posedge clk or negedge resetn)
if (!resetn)
bits_toggled<={WIDTH{1'b0}};
else if (valid)
bits_toggled<=value^last_value;
else
bits_toggled<={WIDTH{1'b0}};
// Create one counter for each bit in value. Increment the respective
// counter if that bit toggled.
genvar i;
generate
for (i = 0; i < WIDTH; i = i + 1)
begin:counters
always@(posedge clk or negedge resetn)
if (!resetn)
count[i] <= {COUNTERWIDTH{1'b0}};
else if (bits_toggled[i] && scaledown)
count[i] <= (count[i] + 2'b1) >> 1;
else if (bits_toggled[i])
count[i] <= count[i] + 2'b1;
else if (scaledown)
count[i] <= count[i] >> 1;
end
endgenerate
// Count total number of times scaled down - saturating counter
// This can be used to approximate absolute toggle rates
always@(posedge clk or negedge resetn)
if (!resetn)
count[WIDTH] <= 1'b0;
else if (scaledown && count[WIDTH]!={COUNTERWIDTH{1'b1}})
count[WIDTH] <= count[WIDTH] + 2'b1;
// If any counter value's top 3 bits are 1s, scale down all counter values
integer j;
always@(posedge clk or negedge resetn)
if (!resetn)
scaledown <= 1'b0;
else if (scaledown)
scaledown <= 1'b0;
else
for (j = 0; j < WIDTH; j = j + 1)
if (&count[j][COUNTERWIDTH-1:COUNTERWIDTH-3])
scaledown <= 1'b1;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_slave_wrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
// If the fifo depth is zero, the module will perform the write ack here,
// otherwise it will take the write ack from the input s_writeack.
parameter integer FIFO_DEPTH = 0, // >= 0 (0 disables)
parameter integer PIPELINE = 1 // 0|1
)
(
input clock,
input resetn,
acl_arb_intf m_intf,
input logic s_writeack,
acl_ic_wrp_intf wrp_intf,
output logic stall
);
generate
if( NUM_MASTERS > 1 )
begin
// This slave endpoint may not directly talk to the ACTUAL slave. In
// this case we need a fifo to store which master each write ack should
// go to. If FIFO_DEPTH is 0 then we assume the writeack can be
// generated right here (the way it was done originally)
if( FIFO_DEPTH > 0 )
begin
// We don't have to worry about bursts, we'll fifo each transaction
// since writeack behaves like readdatavalid
logic rf_empty, rf_full;
acl_ll_fifo #(
.WIDTH( ID_W ),
.DEPTH( FIFO_DEPTH )
)
write_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_intf.req.id ),
.write( ~m_intf.stall & m_intf.req.write ),
.data_out( wrp_intf.id ),
.read( wrp_intf.ack & ~rf_empty),
.empty( rf_empty ),
.full( rf_full )
);
// Register slave writeack to guarantee fifo output is ready
always @( posedge clock or negedge resetn )
begin
if( !resetn )
wrp_intf.ack <= 1'b0;
else
wrp_intf.ack <= s_writeack;
end
assign stall = rf_full;
end
else if( PIPELINE == 1 )
begin
assign stall = 1'b0;
always @( posedge clock or negedge resetn )
if( !resetn )
begin
wrp_intf.ack <= 1'b0;
wrp_intf.id <= 'x; // don't need to reset
end
else
begin
// Always register the id. The ack signal acts as the enable.
wrp_intf.id <= m_intf.req.id;
wrp_intf.ack <= 1'b0;
if( ~m_intf.stall & m_intf.req.write )
// A valid write cycle. Ack it.
wrp_intf.ack <= 1'b1;
end
end
else
begin
assign wrp_intf.id = m_intf.req.id;
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
if ( FIFO_DEPTH == 0 )
begin
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
else
begin
assign wrp_intf.ack = s_writeack;
assign stall = 1'b0;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_slave_wrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
// If the fifo depth is zero, the module will perform the write ack here,
// otherwise it will take the write ack from the input s_writeack.
parameter integer FIFO_DEPTH = 0, // >= 0 (0 disables)
parameter integer PIPELINE = 1 // 0|1
)
(
input clock,
input resetn,
acl_arb_intf m_intf,
input logic s_writeack,
acl_ic_wrp_intf wrp_intf,
output logic stall
);
generate
if( NUM_MASTERS > 1 )
begin
// This slave endpoint may not directly talk to the ACTUAL slave. In
// this case we need a fifo to store which master each write ack should
// go to. If FIFO_DEPTH is 0 then we assume the writeack can be
// generated right here (the way it was done originally)
if( FIFO_DEPTH > 0 )
begin
// We don't have to worry about bursts, we'll fifo each transaction
// since writeack behaves like readdatavalid
logic rf_empty, rf_full;
acl_ll_fifo #(
.WIDTH( ID_W ),
.DEPTH( FIFO_DEPTH )
)
write_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_intf.req.id ),
.write( ~m_intf.stall & m_intf.req.write ),
.data_out( wrp_intf.id ),
.read( wrp_intf.ack & ~rf_empty),
.empty( rf_empty ),
.full( rf_full )
);
// Register slave writeack to guarantee fifo output is ready
always @( posedge clock or negedge resetn )
begin
if( !resetn )
wrp_intf.ack <= 1'b0;
else
wrp_intf.ack <= s_writeack;
end
assign stall = rf_full;
end
else if( PIPELINE == 1 )
begin
assign stall = 1'b0;
always @( posedge clock or negedge resetn )
if( !resetn )
begin
wrp_intf.ack <= 1'b0;
wrp_intf.id <= 'x; // don't need to reset
end
else
begin
// Always register the id. The ack signal acts as the enable.
wrp_intf.id <= m_intf.req.id;
wrp_intf.ack <= 1'b0;
if( ~m_intf.stall & m_intf.req.write )
// A valid write cycle. Ack it.
wrp_intf.ack <= 1'b1;
end
end
else
begin
assign wrp_intf.id = m_intf.req.id;
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
if ( FIFO_DEPTH == 0 )
begin
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
else
begin
assign wrp_intf.ack = s_writeack;
assign stall = 1'b0;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_slave_wrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
// If the fifo depth is zero, the module will perform the write ack here,
// otherwise it will take the write ack from the input s_writeack.
parameter integer FIFO_DEPTH = 0, // >= 0 (0 disables)
parameter integer PIPELINE = 1 // 0|1
)
(
input clock,
input resetn,
acl_arb_intf m_intf,
input logic s_writeack,
acl_ic_wrp_intf wrp_intf,
output logic stall
);
generate
if( NUM_MASTERS > 1 )
begin
// This slave endpoint may not directly talk to the ACTUAL slave. In
// this case we need a fifo to store which master each write ack should
// go to. If FIFO_DEPTH is 0 then we assume the writeack can be
// generated right here (the way it was done originally)
if( FIFO_DEPTH > 0 )
begin
// We don't have to worry about bursts, we'll fifo each transaction
// since writeack behaves like readdatavalid
logic rf_empty, rf_full;
acl_ll_fifo #(
.WIDTH( ID_W ),
.DEPTH( FIFO_DEPTH )
)
write_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_intf.req.id ),
.write( ~m_intf.stall & m_intf.req.write ),
.data_out( wrp_intf.id ),
.read( wrp_intf.ack & ~rf_empty),
.empty( rf_empty ),
.full( rf_full )
);
// Register slave writeack to guarantee fifo output is ready
always @( posedge clock or negedge resetn )
begin
if( !resetn )
wrp_intf.ack <= 1'b0;
else
wrp_intf.ack <= s_writeack;
end
assign stall = rf_full;
end
else if( PIPELINE == 1 )
begin
assign stall = 1'b0;
always @( posedge clock or negedge resetn )
if( !resetn )
begin
wrp_intf.ack <= 1'b0;
wrp_intf.id <= 'x; // don't need to reset
end
else
begin
// Always register the id. The ack signal acts as the enable.
wrp_intf.id <= m_intf.req.id;
wrp_intf.ack <= 1'b0;
if( ~m_intf.stall & m_intf.req.write )
// A valid write cycle. Ack it.
wrp_intf.ack <= 1'b1;
end
end
else
begin
assign wrp_intf.id = m_intf.req.id;
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
if ( FIFO_DEPTH == 0 )
begin
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
else
begin
assign wrp_intf.ack = s_writeack;
assign stall = 1'b0;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_slave_wrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
// If the fifo depth is zero, the module will perform the write ack here,
// otherwise it will take the write ack from the input s_writeack.
parameter integer FIFO_DEPTH = 0, // >= 0 (0 disables)
parameter integer PIPELINE = 1 // 0|1
)
(
input clock,
input resetn,
acl_arb_intf m_intf,
input logic s_writeack,
acl_ic_wrp_intf wrp_intf,
output logic stall
);
generate
if( NUM_MASTERS > 1 )
begin
// This slave endpoint may not directly talk to the ACTUAL slave. In
// this case we need a fifo to store which master each write ack should
// go to. If FIFO_DEPTH is 0 then we assume the writeack can be
// generated right here (the way it was done originally)
if( FIFO_DEPTH > 0 )
begin
// We don't have to worry about bursts, we'll fifo each transaction
// since writeack behaves like readdatavalid
logic rf_empty, rf_full;
acl_ll_fifo #(
.WIDTH( ID_W ),
.DEPTH( FIFO_DEPTH )
)
write_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_intf.req.id ),
.write( ~m_intf.stall & m_intf.req.write ),
.data_out( wrp_intf.id ),
.read( wrp_intf.ack & ~rf_empty),
.empty( rf_empty ),
.full( rf_full )
);
// Register slave writeack to guarantee fifo output is ready
always @( posedge clock or negedge resetn )
begin
if( !resetn )
wrp_intf.ack <= 1'b0;
else
wrp_intf.ack <= s_writeack;
end
assign stall = rf_full;
end
else if( PIPELINE == 1 )
begin
assign stall = 1'b0;
always @( posedge clock or negedge resetn )
if( !resetn )
begin
wrp_intf.ack <= 1'b0;
wrp_intf.id <= 'x; // don't need to reset
end
else
begin
// Always register the id. The ack signal acts as the enable.
wrp_intf.id <= m_intf.req.id;
wrp_intf.ack <= 1'b0;
if( ~m_intf.stall & m_intf.req.write )
// A valid write cycle. Ack it.
wrp_intf.ack <= 1'b1;
end
end
else
begin
assign wrp_intf.id = m_intf.req.id;
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
if ( FIFO_DEPTH == 0 )
begin
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
else
begin
assign wrp_intf.ack = s_writeack;
assign stall = 1'b0;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_slave_wrp #(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer NUM_MASTERS = 1, // > 0
// If the fifo depth is zero, the module will perform the write ack here,
// otherwise it will take the write ack from the input s_writeack.
parameter integer FIFO_DEPTH = 0, // >= 0 (0 disables)
parameter integer PIPELINE = 1 // 0|1
)
(
input clock,
input resetn,
acl_arb_intf m_intf,
input logic s_writeack,
acl_ic_wrp_intf wrp_intf,
output logic stall
);
generate
if( NUM_MASTERS > 1 )
begin
// This slave endpoint may not directly talk to the ACTUAL slave. In
// this case we need a fifo to store which master each write ack should
// go to. If FIFO_DEPTH is 0 then we assume the writeack can be
// generated right here (the way it was done originally)
if( FIFO_DEPTH > 0 )
begin
// We don't have to worry about bursts, we'll fifo each transaction
// since writeack behaves like readdatavalid
logic rf_empty, rf_full;
acl_ll_fifo #(
.WIDTH( ID_W ),
.DEPTH( FIFO_DEPTH )
)
write_fifo(
.clk( clock ),
.reset( ~resetn ),
.data_in( m_intf.req.id ),
.write( ~m_intf.stall & m_intf.req.write ),
.data_out( wrp_intf.id ),
.read( wrp_intf.ack & ~rf_empty),
.empty( rf_empty ),
.full( rf_full )
);
// Register slave writeack to guarantee fifo output is ready
always @( posedge clock or negedge resetn )
begin
if( !resetn )
wrp_intf.ack <= 1'b0;
else
wrp_intf.ack <= s_writeack;
end
assign stall = rf_full;
end
else if( PIPELINE == 1 )
begin
assign stall = 1'b0;
always @( posedge clock or negedge resetn )
if( !resetn )
begin
wrp_intf.ack <= 1'b0;
wrp_intf.id <= 'x; // don't need to reset
end
else
begin
// Always register the id. The ack signal acts as the enable.
wrp_intf.id <= m_intf.req.id;
wrp_intf.ack <= 1'b0;
if( ~m_intf.stall & m_intf.req.write )
// A valid write cycle. Ack it.
wrp_intf.ack <= 1'b1;
end
end
else
begin
assign wrp_intf.id = m_intf.req.id;
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
end
else // NUM_MASTERS == 1
begin
// Only one master so don't need to check the id.
if ( FIFO_DEPTH == 0 )
begin
assign wrp_intf.ack = ~m_intf.stall & m_intf.req.write;
assign stall = 1'b0;
end
else
begin
assign wrp_intf.ack = s_writeack;
assign stall = 1'b0;
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// One-to-many fanout adaptor. Ensures that fanouts
// see the right number of valid_outs under all stall conditions.
module acl_multi_fanout_adaptor #(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer NUM_FANOUTS = 2 // >0
)
(
input logic clock,
input logic resetn,
// Upstream interface
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
input logic valid_in,
output logic stall_out,
// Downstream interface
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
output logic [NUM_FANOUTS-1:0] valid_out,
input logic [NUM_FANOUTS-1:0] stall_in
);
genvar i;
logic [NUM_FANOUTS-1:0] consumed, true_stall_in;
// A downstream interface is truly stalled only if it has not already consumed
// the valid data.
assign true_stall_in = stall_in & ~consumed;
// Stall upstream if any downstream is stalling.
assign stall_out = |true_stall_in;
generate
if( DATA_WIDTH > 0 )
// Data out is just data in. Only valid if valid_out[i] is asserted.
assign data_out = data_in;
endgenerate
// Downstream output is valid if input is valid and the data has not
// already been consumed.
assign valid_out = {NUM_FANOUTS{valid_in}} & ~consumed;
// Consumed: a downstream interface has consumed its data if at least one
// downstream interface is stalling but not itself. The consumed state is
// only reset once all downstream interfaces have consumed their data.
//
// In the case where no downstream is stalling, the consumed bits are not
// used.
generate
for( i = 0; i < NUM_FANOUTS; i = i + 1 )
begin:c
always @( posedge clock or negedge resetn )
if( !resetn )
consumed[i] <= 1'b0;
else if( valid_in & (|true_stall_in) )
begin
// Valid data and there's at least one downstream interface
// stalling. Check if this interface is stalled...
if( ~stall_in[i] )
consumed[i] <= 1'b1;
end
else
consumed[i] <= 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// One-to-many fanout adaptor. Ensures that fanouts
// see the right number of valid_outs under all stall conditions.
module acl_multi_fanout_adaptor #(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer NUM_FANOUTS = 2 // >0
)
(
input logic clock,
input logic resetn,
// Upstream interface
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
input logic valid_in,
output logic stall_out,
// Downstream interface
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
output logic [NUM_FANOUTS-1:0] valid_out,
input logic [NUM_FANOUTS-1:0] stall_in
);
genvar i;
logic [NUM_FANOUTS-1:0] consumed, true_stall_in;
// A downstream interface is truly stalled only if it has not already consumed
// the valid data.
assign true_stall_in = stall_in & ~consumed;
// Stall upstream if any downstream is stalling.
assign stall_out = |true_stall_in;
generate
if( DATA_WIDTH > 0 )
// Data out is just data in. Only valid if valid_out[i] is asserted.
assign data_out = data_in;
endgenerate
// Downstream output is valid if input is valid and the data has not
// already been consumed.
assign valid_out = {NUM_FANOUTS{valid_in}} & ~consumed;
// Consumed: a downstream interface has consumed its data if at least one
// downstream interface is stalling but not itself. The consumed state is
// only reset once all downstream interfaces have consumed their data.
//
// In the case where no downstream is stalling, the consumed bits are not
// used.
generate
for( i = 0; i < NUM_FANOUTS; i = i + 1 )
begin:c
always @( posedge clock or negedge resetn )
if( !resetn )
consumed[i] <= 1'b0;
else if( valid_in & (|true_stall_in) )
begin
// Valid data and there's at least one downstream interface
// stalling. Check if this interface is stalled...
if( ~stall_in[i] )
consumed[i] <= 1'b1;
end
else
consumed[i] <= 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// One-to-many fanout adaptor. Ensures that fanouts
// see the right number of valid_outs under all stall conditions.
module acl_multi_fanout_adaptor #(
parameter integer DATA_WIDTH = 32, // >=0
parameter integer NUM_FANOUTS = 2 // >0
)
(
input logic clock,
input logic resetn,
// Upstream interface
input logic [DATA_WIDTH-1:0] data_in, // not used if DATA_WIDTH=0
input logic valid_in,
output logic stall_out,
// Downstream interface
output logic [DATA_WIDTH-1:0] data_out, // not used if DATA_WIDTH=0
output logic [NUM_FANOUTS-1:0] valid_out,
input logic [NUM_FANOUTS-1:0] stall_in
);
genvar i;
logic [NUM_FANOUTS-1:0] consumed, true_stall_in;
// A downstream interface is truly stalled only if it has not already consumed
// the valid data.
assign true_stall_in = stall_in & ~consumed;
// Stall upstream if any downstream is stalling.
assign stall_out = |true_stall_in;
generate
if( DATA_WIDTH > 0 )
// Data out is just data in. Only valid if valid_out[i] is asserted.
assign data_out = data_in;
endgenerate
// Downstream output is valid if input is valid and the data has not
// already been consumed.
assign valid_out = {NUM_FANOUTS{valid_in}} & ~consumed;
// Consumed: a downstream interface has consumed its data if at least one
// downstream interface is stalling but not itself. The consumed state is
// only reset once all downstream interfaces have consumed their data.
//
// In the case where no downstream is stalling, the consumed bits are not
// used.
generate
for( i = 0; i < NUM_FANOUTS; i = i + 1 )
begin:c
always @( posedge clock or negedge resetn )
if( !resetn )
consumed[i] <= 1'b0;
else if( valid_in & (|true_stall_in) )
begin
// Valid data and there's at least one downstream interface
// stalling. Check if this interface is stalled...
if( ~stall_in[i] )
consumed[i] <= 1'b1;
end
else
consumed[i] <= 1'b0;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// This module defines an iterator over work item space.
// Semantics:
//
// - Items for the same workgroup are issued contiguously.
// That is, items from different workgroups are never interleaved.
//
// - Subject to the previous constraint, we make the lower
// order ids (e.g. local_id[0]) iterate faster than
// higher order (e.g. local_id[2])
//
// - Id values start at zero and only increase.
//
// - Behaviour is unspecified if "issue" is asserted more than
// global_id[0] * global_id[1] * global_id[2] times between times
// that "start" is asserted.
module acl_work_item_iterator #(parameter WIDTH=32) (
input clock,
input resetn,
input start, // Assert to restart the iterators
input issue, // Assert to issue another item, i.e. advance the counters
// We assume these values are steady while "start" is not asserted.
input [WIDTH-1:0] local_size[2:0],
input [WIDTH-1:0] global_size[2:0],
// inputs from id_iterator
input [WIDTH-1:0] global_id_base[2:0],
// The counter values we export.
output reg [WIDTH-1:0] local_id[2:0],
output reg [WIDTH-1:0] global_id[2:0],
// output to id_iterator
output last_in_group
);
// This is the invariant relationship between the various ids.
// Keep these around for debugging.
wire [WIDTH-1:0] global_total = global_id[0] + global_size[0] * ( global_id[1] + global_size[1] * global_id[2] );
wire [WIDTH-1:0] local_total = local_id[0] + local_size[0] * ( local_id[1] + local_size[1] * local_id[2] );
function [WIDTH-1:0] incr_lid ( input [WIDTH-1:0] old_lid, input to_incr, input last );
if ( to_incr )
if ( last )
incr_lid = {WIDTH{1'b0}};
else
incr_lid = old_lid + 2'b01;
else
incr_lid = old_lid;
endfunction
//////////////////////////////////
// Handle local ids.
reg [WIDTH-1:0] max_local_id[2:0];
wire last_local_id[2:0];
assign last_local_id[0] = (local_id[0] == max_local_id[0] );
assign last_local_id[1] = (local_id[1] == max_local_id[1] );
assign last_local_id[2] = (local_id[2] == max_local_id[2] );
assign last_in_group = last_local_id[0] & last_local_id[1] & last_local_id[2];
wire bump_local_id[2:0];
assign bump_local_id[0] = (max_local_id[0] != 0);
assign bump_local_id[1] = (max_local_id[1] != 0) && last_local_id[0];
assign bump_local_id[2] = (max_local_id[2] != 0) && last_local_id[0] && last_local_id[1];
// Local id register updates.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= {WIDTH{1'b0}};
max_local_id[1] <= {WIDTH{1'b0}};
max_local_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
local_id[0] <= {WIDTH{1'b0}};
local_id[1] <= {WIDTH{1'b0}};
local_id[2] <= {WIDTH{1'b0}};
max_local_id[0] <= local_size[0] - 2'b01;
max_local_id[1] <= local_size[1] - 2'b01;
max_local_id[2] <= local_size[2] - 2'b01;
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
local_id[0] <= incr_lid (local_id[0], bump_local_id[0], last_local_id[0]);
local_id[1] <= incr_lid (local_id[1], bump_local_id[1], last_local_id[1]);
local_id[2] <= incr_lid (local_id[2], bump_local_id[2], last_local_id[2]);
end
end
end
// goes high one cycle after last_in_group. stays high until
// next cycle where 'issue' is high.
reg just_seen_last_in_group;
always @(posedge clock or negedge resetn) begin
if ( ~resetn )
just_seen_last_in_group <= 1'b1;
else if ( start )
just_seen_last_in_group <= 1'b1;
else if (last_in_group & issue)
just_seen_last_in_group <= 1'b1;
else if (issue)
just_seen_last_in_group <= 1'b0;
else
just_seen_last_in_group <= just_seen_last_in_group;
end
//////////////////////////////////
// Handle global ids.
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else if ( start ) begin
global_id[0] <= {WIDTH{1'b0}};
global_id[1] <= {WIDTH{1'b0}};
global_id[2] <= {WIDTH{1'b0}};
end else // We presume that start and issue are mutually exclusive.
begin
if ( issue ) begin
if ( !last_in_group ) begin
if ( just_seen_last_in_group ) begin
// get new global_id starting point from dispatcher.
// global_id_base will be one cycle late, so get it on the next cycle
// after encountering last element in previous group.
// id iterator will know to ignore the global id value on that cycle.
global_id[0] <= global_id_base[0] + bump_local_id[0];
global_id[1] <= global_id_base[1] + bump_local_id[1];
global_id[2] <= global_id_base[2] + bump_local_id[2];
end else begin
if ( bump_local_id[0] ) global_id[0] <= (last_local_id[0] ? (global_id[0] - max_local_id[0]) : (global_id[0] + 2'b01));
if ( bump_local_id[1] ) global_id[1] <= (last_local_id[1] ? (global_id[1] - max_local_id[1]) : (global_id[1] + 2'b01));
if ( bump_local_id[2] ) global_id[2] <= (last_local_id[2] ? (global_id[2] - max_local_id[2]) : (global_id[2] + 2'b01));
end
end
end
end
end
endmodule
// vim:set filetype=verilog:
|
// (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.
// one-way bidirectional connection:
// altera message_off 10665
module acl_ic_master_endpoint
#(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer TOTAL_NUM_MASTERS = 1, // > 0
parameter integer ID = 0 // [0..2^ID_W-1]
)
(
input logic clock,
input logic resetn,
acl_ic_master_intf m_intf,
acl_arb_intf arb_intf,
acl_ic_wrp_intf wrp_intf,
acl_ic_rrp_intf rrp_intf
);
// Pass-through arbitration data.
assign arb_intf.req = m_intf.arb.req;
assign m_intf.arb.stall = arb_intf.stall;
generate
if( TOTAL_NUM_MASTERS > 1 )
begin
// There shouldn't be any truncation, but be explicit about the id width.
logic [ID_W-1:0] id = ID;
// Write return path.
assign m_intf.wrp.ack = wrp_intf.ack & (wrp_intf.id == id);
// Read return path.
assign m_intf.rrp.datavalid = rrp_intf.datavalid & (rrp_intf.id == id);
assign m_intf.rrp.data = rrp_intf.data;
end
else // TOTAL_NUM_MASTERS == 1
begin
// Only one master driving the entire interconnect, so there's no need
// to check the id.
// Write return path.
assign m_intf.wrp.ack = wrp_intf.ack;
// Read return path.
assign m_intf.rrp.datavalid = rrp_intf.datavalid;
assign m_intf.rrp.data = rrp_intf.data;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// one-way bidirectional connection:
// altera message_off 10665
module acl_ic_master_endpoint
#(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer TOTAL_NUM_MASTERS = 1, // > 0
parameter integer ID = 0 // [0..2^ID_W-1]
)
(
input logic clock,
input logic resetn,
acl_ic_master_intf m_intf,
acl_arb_intf arb_intf,
acl_ic_wrp_intf wrp_intf,
acl_ic_rrp_intf rrp_intf
);
// Pass-through arbitration data.
assign arb_intf.req = m_intf.arb.req;
assign m_intf.arb.stall = arb_intf.stall;
generate
if( TOTAL_NUM_MASTERS > 1 )
begin
// There shouldn't be any truncation, but be explicit about the id width.
logic [ID_W-1:0] id = ID;
// Write return path.
assign m_intf.wrp.ack = wrp_intf.ack & (wrp_intf.id == id);
// Read return path.
assign m_intf.rrp.datavalid = rrp_intf.datavalid & (rrp_intf.id == id);
assign m_intf.rrp.data = rrp_intf.data;
end
else // TOTAL_NUM_MASTERS == 1
begin
// Only one master driving the entire interconnect, so there's no need
// to check the id.
// Write return path.
assign m_intf.wrp.ack = wrp_intf.ack;
// Read return path.
assign m_intf.rrp.datavalid = rrp_intf.datavalid;
assign m_intf.rrp.data = rrp_intf.data;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
// one-way bidirectional connection:
// altera message_off 10665
module acl_ic_master_endpoint
#(
parameter integer DATA_W = 32, // > 0
parameter integer BURSTCOUNT_W = 4, // > 0
parameter integer ADDRESS_W = 32, // > 0
parameter integer BYTEENA_W = DATA_W / 8, // > 0
parameter integer ID_W = 1, // > 0
parameter integer TOTAL_NUM_MASTERS = 1, // > 0
parameter integer ID = 0 // [0..2^ID_W-1]
)
(
input logic clock,
input logic resetn,
acl_ic_master_intf m_intf,
acl_arb_intf arb_intf,
acl_ic_wrp_intf wrp_intf,
acl_ic_rrp_intf rrp_intf
);
// Pass-through arbitration data.
assign arb_intf.req = m_intf.arb.req;
assign m_intf.arb.stall = arb_intf.stall;
generate
if( TOTAL_NUM_MASTERS > 1 )
begin
// There shouldn't be any truncation, but be explicit about the id width.
logic [ID_W-1:0] id = ID;
// Write return path.
assign m_intf.wrp.ack = wrp_intf.ack & (wrp_intf.id == id);
// Read return path.
assign m_intf.rrp.datavalid = rrp_intf.datavalid & (rrp_intf.id == id);
assign m_intf.rrp.data = rrp_intf.data;
end
else // TOTAL_NUM_MASTERS == 1
begin
// Only one master driving the entire interconnect, so there's no need
// to check the id.
// Write return path.
assign m_intf.wrp.ack = wrp_intf.ack;
// Read return path.
assign m_intf.rrp.datavalid = rrp_intf.datavalid;
assign m_intf.rrp.data = rrp_intf.data;
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for pipelined memory access.
//
// Properties - Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: Yes
// (see lsu_top.v for details)
//
// Description: Requests are submitted as soon as they are received.
// Pipelined access to memory so multiple requests can be
// in flight at a time.
// Pipelined read unit:
// Accept read requests on the upstream interface. When a request is
// received, store the requested byte address in the request fifo and
// pass the request through to the avalon interface. Response data
// is buffered in the response fifo and the appropriate word is muxed
// out of the response fifo based on the address in the request fifo.
// The response fifo has limited capacity, so a counter is used to track
// the number of pending responses to generate an upstream stall if
// we run out of room.
module lsu_pipelined_read
(
clk, reset, o_stall, i_valid, i_address, i_burstcount, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid,
o_input_fifo_depth,
avm_burstcount
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // The max number of live threads
parameter USEBURST=0;
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter USEINPUTFIFO=1;
parameter USEOUTPUTFIFO=1;
parameter INPUTFIFOSIZE=32;
parameter PIPELINE_INPUT=0;
parameter SUPERPIPELINE=0; // Enable extremely aggressive pipelining of the LSU
parameter HIGH_FMAX=1;
localparam INPUTFIFO_USEDW_MAXBITS=$clog2(INPUTFIFOSIZE);
// Derived parameters
localparam MAX_BURST=2**(BURSTCOUNT_WIDTH-1);
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
//
// We only o_stall if we have more than KERNEL_SIDE_MEM_LATENCY inflight requests
//
localparam RETURN_FIFO_SIZE=KERNEL_SIDE_MEM_LATENCY+(USEBURST ? 0 : 1);
localparam COUNTER_WIDTH=USEBURST ? $clog2(RETURN_FIFO_SIZE+1+MAX_BURST) : $clog2(RETURN_FIFO_SIZE+1);
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [BURSTCOUNT_WIDTH-1:0] i_burstcount;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
// For profiler/performance monitor
output [INPUTFIFO_USEDW_MAXBITS-1:0] o_input_fifo_depth;
/***************
* Architecture *
***************/
wire i_valid_from_fifo;
wire [AWIDTH-1:0] i_address_from_fifo;
wire o_stall_to_fifo;
wire [BURSTCOUNT_WIDTH-1:0] i_burstcount_from_fifo;
wire read_accepted;
wire read_used;
wire [BYTE_SELECT_BITS-1:0] byte_select;
wire ready;
wire out_fifo_wait;
localparam FIFO_DEPTH_BITS=USEINPUTFIFO ? $clog2(INPUTFIFOSIZE) : 0;
wire [FIFO_DEPTH_BITS-1:0] usedw_true_width;
generate
if (USEINPUTFIFO)
assign o_input_fifo_depth[FIFO_DEPTH_BITS-1:0] = usedw_true_width;
// Set unused bits to 0
genvar bit_index;
for(bit_index = FIFO_DEPTH_BITS; bit_index < INPUTFIFO_USEDW_MAXBITS; bit_index = bit_index + 1)
begin: read_fifo_depth_zero_assign
assign o_input_fifo_depth[bit_index] = 1'b0;
end
endgenerate
generate
if(USEINPUTFIFO && SUPERPIPELINE)
begin
wire int_stall;
wire int_valid;
wire [AWIDTH+BURSTCOUNT_WIDTH-1:0] int_data;
acl_fifo #(
.DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH),
.DEPTH(INPUTFIFOSIZE)
) input_fifo (
.clock(clk),
.resetn(!reset),
.data_in( {i_address,i_burstcount} ),
.data_out( int_data ),
.valid_in( i_valid ),
.valid_out( int_valid ),
.stall_in( int_stall ),
.stall_out( o_stall ),
.usedw( usedw_true_width )
);
// Add a pipeline and stall-breaking FIFO
// TODO: Consider making this parameterizeable
acl_data_fifo #(
.DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) input_fifo_buffer (
.clock(clk),
.resetn(!reset),
.data_in( int_data ),
.valid_in( int_valid ),
.data_out( {i_address_from_fifo,i_burstcount_from_fifo} ),
.valid_out( i_valid_from_fifo ),
.stall_in( o_stall_to_fifo ),
.stall_out( int_stall )
);
end
else if(USEINPUTFIFO && !SUPERPIPELINE)
begin
acl_fifo #(
.DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH),
.DEPTH(INPUTFIFOSIZE)
) input_fifo (
.clock(clk),
.resetn(!reset),
.data_in( {i_address,i_burstcount} ),
.data_out( {i_address_from_fifo,i_burstcount_from_fifo} ),
.valid_in( i_valid ),
.valid_out( i_valid_from_fifo ),
.stall_in( o_stall_to_fifo ),
.stall_out( o_stall ),
.usedw( usedw_true_width )
);
end
else if(PIPELINE_INPUT)
begin
reg r_valid;
reg [AWIDTH-1:0] r_address;
reg [BURSTCOUNT_WIDTH-1:0] r_burstcount;
assign o_stall = r_valid && o_stall_to_fifo;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
r_valid <= 1'b0;
else
begin
if (!o_stall)
begin
r_valid <= i_valid;
r_address <= i_address;
r_burstcount <= i_burstcount;
end
end
end
assign i_valid_from_fifo = r_valid;
assign i_address_from_fifo = r_address;
assign i_burstcount_from_fifo = r_burstcount;
end
else
begin
assign i_valid_from_fifo = i_valid;
assign i_address_from_fifo = i_address;
assign o_stall = o_stall_to_fifo;
assign i_burstcount_from_fifo = i_burstcount;
end
endgenerate
// Track the number of transactions waiting in the pipeline here
reg [COUNTER_WIDTH-1:0] counter;
wire incr, decr;
assign incr = read_accepted;
assign decr = read_used;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
counter <= {COUNTER_WIDTH{1'b0}};
o_active <= 1'b0;
end
else
begin
o_active <= (counter != {COUNTER_WIDTH{1'b0}});
// incr - add one or i_burstcount_from_fifo; decr - subtr one;
if (USEBURST==1)
counter <= counter + (incr ? i_burstcount_from_fifo : 0) - decr;
else
counter <= counter + incr - decr;
end
end
generate
if(USEBURST)
// Use the burstcount to figure out if there is enough space
assign ready = ((counter+i_burstcount_from_fifo) <= RETURN_FIFO_SIZE);
//
// Can also use decr in this calaculation to make ready respond faster
// but this seems to hurt Fmax ( ie. not worth it )
//assign ready = ((counter+i_burstcount_from_fifo-decr) <= RETURN_FIFO_SIZE);
else
// Can we hold one more item
assign ready = (counter <= (RETURN_FIFO_SIZE-1));
endgenerate
assign o_stall_to_fifo = !ready || out_fifo_wait;
// Optional Pipeline register before return
//
reg r_avm_readdatavalid;
reg [MWIDTH-1:0] r_avm_readdata;
generate
if(SUPERPIPELINE)
begin
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
r_avm_readdata <= 'x;
r_avm_readdatavalid <= 1'b0;
end
else
begin
r_avm_readdata <= avm_readdata;
r_avm_readdatavalid <= avm_readdatavalid;
end
end
end
else
begin
// Don't register the return
always@(*)
begin
r_avm_readdata = avm_readdata;
r_avm_readdatavalid = avm_readdatavalid;
end
end
endgenerate
wire [WIDTH-1:0] rdata;
// Byte-addresses enter a FIFO so we can demux the appropriate data back out.
generate
if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_address_out;
wire [SEGMENT_SELECT_BITS-1:0] segment_address_in;
assign segment_address_in = i_address_from_fifo[ALIGNMENT_ABITS +: BYTE_SELECT_BITS-ALIGNMENT_ABITS];
acl_ll_fifo #(
.WIDTH(SEGMENT_SELECT_BITS),
.DEPTH(KERNEL_SIDE_MEM_LATENCY+1)
) req_fifo (
.clk(clk),
.reset(reset),
.data_in( segment_address_in ),
.data_out( segment_address_out ),
.write( read_accepted ),
.read( r_avm_readdatavalid ),
.empty(),
.full()
);
assign byte_select = (segment_address_out << ALIGNMENT_ABITS);
assign rdata = r_avm_readdata[8*byte_select +: WIDTH];
end
else
begin
assign byte_select = '0;
assign rdata = r_avm_readdata;
end
endgenerate
// Status bits
assign read_accepted = i_valid_from_fifo && ready && !out_fifo_wait;
assign read_used = o_valid && !i_stall;
assign avm_byteenable = {MWIDTH_BYTES{1'b1}};
// Optional: Pipelining FIFO on the AVM interface
//
generate
if(SUPERPIPELINE)
begin
acl_data_fifo #(
.DATA_WIDTH(AWIDTH+BURSTCOUNT_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) avm_buffer (
.clock(clk),
.resetn(!reset),
.data_in({((i_address_from_fifo >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS),i_burstcount_from_fifo}),
.valid_in( i_valid_from_fifo && ready ),
.data_out( {avm_address,avm_burstcount} ),
.valid_out( avm_read ),
.stall_in( avm_waitrequest ),
.stall_out( out_fifo_wait )
);
end
else
begin
// No interface pipelining
assign out_fifo_wait = avm_waitrequest;
assign avm_address = ((i_address_from_fifo >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS);
assign avm_read = i_valid_from_fifo && ready;
assign avm_burstcount = i_burstcount_from_fifo;
end
endgenerate
// ---------------------------------------------------------------------------------
// Output fifo - must be at least as deep as the maximum number of pending requests
// so that we can guarantee a place for the response data if the downstream blocks
// are stalling.
//
generate
if(USEOUTPUTFIFO)
begin
acl_data_fifo #(
.DATA_WIDTH(WIDTH),
.DEPTH(RETURN_FIFO_SIZE),
.IMPL((SUPERPIPELINE && HIGH_FMAX) ? "ram_plus_reg" : "ram")
) data_fifo (
.clock(clk),
.resetn(!reset),
.data_in( rdata ),
.data_out( o_readdata ),
.valid_in( r_avm_readdatavalid ),
.valid_out( o_valid ),
.stall_in( i_stall ),
.stall_out()
);
end
else
begin
assign o_valid = r_avm_readdatavalid;
assign o_readdata = rdata;
end
endgenerate
endmodule
/******************************************************************************/
// Pipelined write unit:
// Accept write requests on the upstream interface. Mux the data into the
// appropriate word lines based on the segment select bits. Also toggle
// the appropriate byte-enable lines to preserve data we are not
// overwriting. A counter keeps track of how many requests have been
// send but not yet acknowledged by downstream blocks.
module lsu_pipelined_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest, o_input_fifo_depth
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access
parameter MWIDTH_BYTES=32; // Width of the global memory bus
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter COUNTER_WIDTH=6;
parameter KERNEL_SIDE_MEM_LATENCY=32;
parameter USEINPUTFIFO=1;
parameter USE_BYTE_EN=0;
parameter INPUTFIFOSIZE=32;
parameter INPUTFIFO_USEDW_MAXBITS=$clog2(INPUTFIFOSIZE);
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
input [WIDTH_BYTES-1:0] i_byteenable;
// Downstream interface
input i_stall;
output o_valid;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output reg [MWIDTH-1:0] avm_writedata;
output reg [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
// For profiler/performance monitor
output [INPUTFIFO_USEDW_MAXBITS-1:0] o_input_fifo_depth;
/***************
* Architecture *
***************/
reg transaction_complete;
wire write_accepted;
wire ready;
wire sr_stall;
wire i_valid_from_fifo;
wire [AWIDTH-1:0] i_address_from_fifo;
wire [WIDTH-1:0] i_writedata_from_fifo;
wire [WIDTH_BYTES-1:0] i_byteenable_from_fifo;
wire o_stall_to_fifo;
localparam FIFO_DEPTH_BITS=USEINPUTFIFO ? $clog2(INPUTFIFOSIZE) : 0;
wire [FIFO_DEPTH_BITS-1:0] usedw_true_width;
generate
if (USEINPUTFIFO)
assign o_input_fifo_depth[FIFO_DEPTH_BITS-1:0] = usedw_true_width;
// Set unused bits to 0
genvar bit_index;
for(bit_index = FIFO_DEPTH_BITS; bit_index < INPUTFIFO_USEDW_MAXBITS; bit_index = bit_index + 1)
begin: write_fifo_depth_zero_assign
assign o_input_fifo_depth[bit_index] = 1'b0;
end
endgenerate
localparam DATA_WIDTH = AWIDTH+WIDTH+(USE_BYTE_EN ? WIDTH_BYTES : 0);
generate
if(USEINPUTFIFO)
begin
wire valid_int;
wire stall_int;
wire [DATA_WIDTH-1:0] data_int;
if(!USE_BYTE_EN)
begin
acl_fifo #(
.DATA_WIDTH(AWIDTH+WIDTH),
.DEPTH(INPUTFIFOSIZE)
) data_fifo (
.clock(clk),
.resetn(!reset),
.data_in( {i_address,i_writedata} ),
.data_out( data_int ),
.valid_in( i_valid ),
.valid_out( valid_int ),
.stall_in( stall_int ),
.stall_out( o_stall ),
.usedw( usedw_true_width )
);
acl_data_fifo #(
.DATA_WIDTH(AWIDTH+WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) input_buf (
.clock(clk),
.resetn(!reset),
.data_in( data_int ),
.data_out( {i_address_from_fifo,i_writedata_from_fifo} ),
.valid_in( valid_int ),
.valid_out( i_valid_from_fifo ),
.stall_in( o_stall_to_fifo ),
.stall_out( stall_int )
);
assign i_byteenable_from_fifo = {WIDTH_BYTES{1'b1}};
end else begin
acl_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(INPUTFIFOSIZE)
) data_fifo (
.clock(clk),
.resetn(!reset),
.data_in( {i_byteenable, i_address,i_writedata}),
.data_out( data_int ),
.valid_in( i_valid ),
.valid_out( valid_int ),
.stall_in( stall_int ),
.stall_out( o_stall ),
.usedw( usedw_true_width )
);
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) input_buf (
.clock(clk),
.resetn(!reset),
.data_in( data_int ),
.data_out({i_byteenable_from_fifo,i_address_from_fifo,i_writedata_from_fifo}),
.valid_in( valid_int ),
.valid_out( i_valid_from_fifo ),
.stall_in( o_stall_to_fifo ),
.stall_out( stall_int )
);
end
end
else
begin
assign i_valid_from_fifo = i_valid;
assign i_address_from_fifo = i_address;
assign i_writedata_from_fifo = i_writedata;
assign o_stall = o_stall_to_fifo;
assign i_byteenable_from_fifo = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
endgenerate
// Avalon interface
assign avm_address = ((i_address_from_fifo >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS);
assign avm_write = ready && i_valid_from_fifo;
// Mux in the correct data
generate
if(SEGMENT_SELECT_BITS > 0)
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address_from_fifo[ALIGNMENT_ABITS +: BYTE_SELECT_BITS-ALIGNMENT_ABITS];
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata_from_fifo;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = i_byteenable_from_fifo;
end
end
else
begin
always@(*)
begin
avm_writedata = i_writedata_from_fifo;
avm_byteenable = i_byteenable_from_fifo;
end
end
endgenerate
// Control logic
reg [COUNTER_WIDTH-1:0] occ_counter; // occupancy counter
wire occ_incr, occ_decr;
reg [COUNTER_WIDTH-1:0] ack_counter; // acknowledge writes counter
wire ack_incr, ack_decr;
// Track the number of transactions waiting in the pipeline here
assign occ_incr = write_accepted;
assign occ_decr = o_valid && !i_stall;
assign ack_incr = avm_writeack;
assign ack_decr = o_valid && !i_stall;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
o_active <= 1'b0;
end
else
begin
// incr - add one; decr - subtr one; both - stay the same
occ_counter <= occ_counter + { {(COUNTER_WIDTH-1){!occ_incr && occ_decr}}, (occ_incr ^ occ_decr) };
ack_counter <= ack_counter + { {(COUNTER_WIDTH-1){!ack_incr && ack_decr}}, (ack_incr ^ ack_decr) };
o_active <= (occ_counter != {COUNTER_WIDTH{1'b0}});
end
end
assign ready = (occ_counter != {COUNTER_WIDTH{1'b1}});
assign write_accepted = avm_write && !avm_waitrequest;
assign o_stall_to_fifo = !ready || avm_waitrequest;
assign o_valid = (ack_counter != {COUNTER_WIDTH{1'b0}});
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_wrp_reg
(
input logic clock,
input logic resetn,
acl_ic_wrp_intf wrp_in,
(* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_wrp_intf wrp_out
);
always @(posedge clock or negedge resetn)
if( ~resetn ) begin
wrp_out.ack <= 1'b0;
wrp_out.id <= 'x;
end
else begin
wrp_out.ack <= wrp_in.ack;
wrp_out.id <= wrp_in.id;
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_wrp_reg
(
input logic clock,
input logic resetn,
acl_ic_wrp_intf wrp_in,
(* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_wrp_intf wrp_out
);
always @(posedge clock or negedge resetn)
if( ~resetn ) begin
wrp_out.ack <= 1'b0;
wrp_out.id <= 'x;
end
else begin
wrp_out.ack <= wrp_in.ack;
wrp_out.id <= wrp_in.id;
end
endmodule
|
(** * References: Typing Mutable References *)
Require Export Smallstep.
(** So far, we have considered a variety of _pure_ language features,
including functional abstraction, basic types such as numbers and
booleans, and structured types such as records and variants. These
features form the backbone of most programming languages -- including
purely functional languages such as Haskell, "mostly functional"
languages such as ML, imperative languages such as C, and
object-oriented languages such as Java.
Most practical programming languages also include various _impure_
features that cannot be described in the simple semantic framework
we have used so far. In particular, besides just yielding
results, evaluation of terms in these languages may assign to
mutable variables (reference cells, arrays, mutable record fields,
etc.), perform input and output to files, displays, or network
connections, make non-local transfers of control via exceptions,
jumps, or continuations, engage in inter-process synchronization
and communication, and so on. In the literature on programming
languages, such "side effects" of computation are more generally
referred to as _computational effects_.
In this chapter, we'll see how one sort of computational
effect -- mutable references -- can be added to the calculi we have
studied. The main extension will be dealing explicitly with a
_store_ (or _heap_). This extension is straightforward to define;
the most interesting part is the refinement we need to make to the
statement of the type preservation theorem. *)
(* ###################################################################### *)
(** * Definitions *)
(** Pretty much every programming language provides some form of
assignment operation that changes the contents of a previously
allocated piece of storage. (Coq's internal language is a rare
exception!)
In some languages -- notably ML and its relatives -- the
mechanisms for name-binding and those for assignment are kept
separate. We can have a variable [x] whose _value_ is the number
[5], or we can have a variable [y] whose value is a
_reference_ (or _pointer_) to a mutable cell whose current
contents is [5]. These are different things, and the difference
is visible to the programmer. We can add [x] to another number,
but not assign to it. We can use [y] directly to assign a new
value to the cell that it points to (by writing [y:=84]), but we
cannot use it directly as an argument to an operation like [+].
Instead, we must explicitly _dereference_ it, writing [!y] to
obtain its current contents.
In most other languages -- in particular, in all members of the C
family, including Java -- _every_ variable name refers to a mutable
cell, and the operation of dereferencing a variable to obtain its
current contents is implicit.
For purposes of formal study, it is useful to keep these
mechanisms separate. The development in this chapter will closely
follow ML's model. Applying the lessons learned here to C-like
languages is a straightforward matter of collapsing some
distinctions and rendering some operations such as dereferencing
implicit instead of explicit.
In this chapter, we study adding mutable references to the
simply-typed lambda calculus with natural numbers. *)
(* ###################################################################### *)
(** * Syntax *)
Module STLCRef.
(** The basic operations on references are _allocation_,
_dereferencing_, and _assignment_.
- To allocate a reference, we use the [ref] operator, providing
an initial value for the new cell. For example, [ref 5]
creates a new cell containing the value [5], and evaluates to
a reference to that cell.
- To read the current value of this cell, we use the
dereferencing operator [!]; for example, [!(ref 5)] evaluates
to [5].
- To change the value stored in a cell, we use the assignment
operator. If [r] is a reference, [r := 7] will store the
value [7] in the cell referenced by [r]. However, [r := 7]
evaluates to the trivial value [unit]; it exists only to have
the _side effect_ of modifying the contents of a cell. *)
(* ################################### *)
(** *** Types *)
(** We start with the simply typed lambda calculus over the
natural numbers. To the base natural number type and arrow types
we need to add two more types to deal with references. First, we
need the _unit type_, which we will use as the result type of an
assignment operation. We then add _reference types_. *)
(** If [T] is a type, then [Ref T] is the type of references which
point to a cell holding values of type [T].
T ::= Nat
| Unit
| T -> T
| Ref T
*)
Inductive ty : Type :=
| TNat : ty
| TUnit : ty
| TArrow : ty -> ty -> ty
| TRef : ty -> ty.
(* ################################### *)
(** *** Terms *)
(** Besides variables, abstractions, applications,
natural-number-related terms, and [unit], we need four more sorts
of terms in order to handle mutable references:
<<
t ::= ... Terms
| ref t allocation
| !t dereference
| t := t assignment
| l location
>>
*)
Inductive tm : Type :=
(* STLC with numbers: *)
| 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
(* New terms: *)
| tunit : tm
| tref : tm -> tm
| tderef : tm -> tm
| tassign : tm -> tm -> tm
| tloc : nat -> tm.
(** Intuitively...
- [ref t] (formally, [tref t]) allocates a new reference cell
with the value [t] and evaluates to the location of the newly
allocated cell;
- [!t] (formally, [tderef t]) evaluates to the contents of the
cell referenced by [t];
- [t1 := t2] (formally, [tassign t1 t2]) assigns [t2] to the
cell referenced by [t1]; and
- [l] (formally, [tloc l]) is a reference to the cell at
location [l]. We'll discuss locations later. *)
(** In informal examples, we'll also freely use the extensions
of the STLC developed in the [MoreStlc] chapter; however, to keep
the proofs small, we won't bother formalizing them again here. It
would be easy to do so, since there are no very interesting
interactions between those features and references. *)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "tzero"
| Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tunit" | Case_aux c "tref"
| Case_aux c "tderef" | Case_aux c "tassign"
| Case_aux c "tloc" ].
Module ExampleVariables.
Definition x := Id 0.
Definition y := Id 1.
Definition r := Id 2.
Definition s := Id 3.
End ExampleVariables.
(* ################################### *)
(** *** Typing (Preview) *)
(** Informally, the typing rules for allocation, dereferencing, and
assignment will look like this:
Gamma |- t1 : T1
------------------------ (T_Ref)
Gamma |- ref t1 : Ref T1
Gamma |- t1 : Ref T11
--------------------- (T_Deref)
Gamma |- !t1 : T11
Gamma |- t1 : Ref T11
Gamma |- t2 : T11
------------------------ (T_Assign)
Gamma |- t1 := t2 : Unit
The rule for locations will require a bit more machinery, and this
will motivate some changes to the other rules; we'll come back to
this later. *)
(* ################################### *)
(** *** Values and Substitution *)
(** Besides abstractions and numbers, we have two new types of values:
the unit value, and locations. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_nat : forall n,
value (tnat n)
| v_unit :
value tunit
| v_loc : forall l,
value (tloc l).
Hint Constructors value.
(** Extending substitution to handle the new syntax of terms is
straightforward. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tabs x' T t1 =>
if eq_id_dec x x' then t else tabs x' T (subst x s t1)
| tnat n =>
t
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
t
| tref t1 =>
tref (subst x s t1)
| tderef t1 =>
tderef (subst x s t1)
| tassign t1 t2 =>
tassign (subst x s t1) (subst x s t2)
| tloc _ =>
t
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** * Pragmatics *)
(* ################################### *)
(** ** Side Effects and Sequencing *)
(** The fact that the result of an assignment expression is the
trivial value [unit] allows us to use a nice abbreviation for
_sequencing_. For example, we can write
<<
r:=succ(!r); !r
>>
as an abbreviation for
<<
(\x:Unit. !r) (r := succ(!r)).
>>
This has the effect of evaluating two expressions in order and
returning the value of the second. Restricting the type of the first
expression to [Unit] helps the typechecker to catch some silly
errors by permitting us to throw away the first value only if it
is really guaranteed to be trivial.
Notice that, if the second expression is also an assignment, then
the type of the whole sequence will be [Unit], so we can validly
place it to the left of another [;] to build longer sequences of
assignments:
<<
r:=succ(!r); r:=succ(!r); r:=succ(!r); r:=succ(!r); !r
>>
*)
(** Formally, we introduce sequencing as a "derived form"
[tseq] that expands into an abstraction and an application. *)
Definition tseq t1 t2 :=
tapp (tabs (Id 0) TUnit t2) t1.
(* ################################### *)
(** ** References and Aliasing *)
(** It is important to bear in mind the difference between the
_reference_ that is bound to [r] and the _cell_ in the store that
is pointed to by this reference.
If we make a copy of [r], for example by binding its value to
another variable [s], what gets copied is only the _reference_,
not the contents of the cell itself.
For example, after evaluating
<<
let r = ref 5 in
let s = r in
s := 82;
(!r)+1
>>
the cell referenced by [r] will contain the value [82], while the
result of the whole expression will be [83]. The references [r]
and [s] are said to be _aliases_ for the same cell.
The possibility of aliasing can make programs with references
quite tricky to reason about. For example, the expression
<<
r := 5; r := !s
>>
assigns [5] to [r] and then immediately overwrites it with [s]'s
current value; this has exactly the same effect as the single
assignment
<<
r := !s
>>
_unless_ we happen to do it in a context where [r] and [s] are
aliases for the same cell! *)
(* ################################### *)
(** ** Shared State *)
(** Of course, aliasing is also a large part of what makes references
useful. In particular, it allows us to set up "implicit
communication channels" -- shared state -- between different parts
of a program. For example, suppose we define a reference cell and
two functions that manipulate its contents:
<<
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
...
>>
*)
(** Note that, since their argument types are [Unit], the
abstractions in the definitions of [incc] and [decc] are not
providing any useful information to the bodies of the
functions (using the wildcard [_] as the name of the bound
variable is a reminder of this). Instead, their purpose is to
"slow down" the execution of the function bodies: since function
abstractions are values, the two [let]s are executed simply by
binding these functions to the names [incc] and [decc], rather
than by actually incrementing or decrementing [c]. Later, each
call to one of these functions results in its body being executed
once and performing the appropriate mutation on [c]. Such
functions are often called _thunks_.
In the context of these declarations, calling [incc] results in
changes to [c] that can be observed by calling [decc]. For
example, if we replace the [...] with [(incc unit; incc unit; decc
unit)], the result of the whole program will be [1]. *)
(** ** Objects *)
(** We can go a step further and write a _function_ that creates [c],
[incc], and [decc], packages [incc] and [decc] together into a
record, and returns this record:
<<
newcounter =
\_:Unit.
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
{i=incc, d=decc}
>>
*)
(** Now, each time we call [newcounter], we get a new record of
functions that share access to the same storage cell [c]. The
caller of [newcounter] can't get at this storage cell directly,
but can affect it indirectly by calling the two functions. In
other words, we've created a simple form of _object_.
<<
let c1 = newcounter unit in
let c2 = newcounter unit in
// Note that we've allocated two separate storage cells now!
let r1 = c1.i unit in
let r2 = c2.i unit in
r2 // yields 1, not 2!
>>
*)
(** **** Exercise: 1 star (store_draw) *)
(** Draw (on paper) the contents of the store at the point in
execution where the first two [let]s have finished and the third
one is about to begin. *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** References to Compound Types *)
(** A reference cell need not contain just a number: the primitives
we've defined above allow us to create references to values of any
type, including functions. For example, we can use references to
functions to give a (not very efficient) implementation of arrays
of numbers, as follows. Write [NatArray] for the type
[Ref (Nat->Nat)].
Recall the [equal] function from the [MoreStlc] chapter:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
Now, to build a new array, we allocate a reference cell and fill
it with a function that, when given an index, always returns [0].
<<
newarray = \_:Unit. ref (\n:Nat.0)
>>
To look up an element of an array, we simply apply
the function to the desired index.
<<
lookup = \a:NatArray. \n:Nat. (!a) n
>>
The interesting part of the encoding is the [update] function. It
takes an array, an index, and a new value to be stored at that index, and
does its job by creating (and storing in the reference) a new function
that, when it is asked for the value at this very index, returns the new
value that was given to [update], and on all other indices passes the
lookup to the function that was previously stored in the reference.
<<
update = \a:NatArray. \m:Nat. \v:Nat.
let oldf = !a in
a := (\n:Nat. if equal m n then v else oldf n);
>>
References to values containing other references can also be very
useful, allowing us to define data structures such as mutable
lists and trees. *)
(** **** Exercise: 2 stars (compact_update) *)
(** If we defined [update] more compactly like this
<<
update = \a:NatArray. \m:Nat. \v:Nat.
a := (\n:Nat. if equal m n then v else (!a) n)
>>
would it behave the same? *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** Null References *)
(** There is one more difference between our references and C-style
mutable variables: in C-like languages, variables holding pointers
into the heap may sometimes have the value [NULL]. Dereferencing
such a "null pointer" is an error, and results in an
exception (Java) or in termination of the program (C).
Null pointers cause significant trouble in C-like languages: the
fact that any pointer might be null means that any dereference
operation in the program can potentially fail. However, even in
ML-like languages, there are occasionally situations where we may
or may not have a valid pointer in our hands. Fortunately, there
is no need to extend the basic mechanisms of references to achieve
this: the sum types introduced in the [MoreStlc] chapter already
give us what we need.
First, we can use sums to build an analog of the [option] types
introduced in the [Lists] chapter. Define [Option T] to be an
abbreviation for [Unit + T].
Then a "nullable reference to a [T]" is simply an element of the
type [Option (Ref T)]. *)
(* ################################### *)
(** ** Garbage Collection *)
(** A last issue that we should mention before we move on with
formalizing references is storage _de_-allocation. We have not
provided any primitives for freeing reference cells when they are
no longer needed. Instead, like many modern languages (including
ML and Java) we rely on the run-time system to perform _garbage
collection_, collecting and reusing cells that can no longer be
reached by the program.
This is _not_ just a question of taste in language design: it is
extremely difficult to achieve type safety in the presence of an
explicit deallocation operation. The reason for this is the
familiar _dangling reference_ problem: we allocate a cell holding
a number, save a reference to it in some data structure, use it
for a while, then deallocate it and allocate a new cell holding a
boolean, possibly reusing the same storage. Now we can have two
names for the same storage cell -- one with type [Ref Nat] and the
other with type [Ref Bool]. *)
(** **** Exercise: 1 star (type_safety_violation) *)
(** Show how this can lead to a violation of type safety. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Operational Semantics *)
(* ################################### *)
(** ** Locations *)
(** The most subtle aspect of the treatment of references
appears when we consider how to formalize their operational
behavior. One way to see why is to ask, "What should be the
_values_ of type [Ref T]?" The crucial observation that we need
to take into account is that evaluating a [ref] operator should
_do_ something -- namely, allocate some storage -- and the result
of the operation should be a reference to this storage.
What, then, is a reference?
The run-time store in most programming language implementations is
essentially just a big array of bytes. The run-time system keeps track
of which parts of this array are currently in use; when we need to
allocate a new reference cell, we allocate a large enough segment from
the free region of the store (4 bytes for integer cells, 8 bytes for
cells storing [Float]s, etc.), mark it as being used, and return the
index (typically, a 32- or 64-bit integer) of the start of the newly
allocated region. These indices are references.
For present purposes, there is no need to be quite so concrete.
We can think of the store as an array of _values_, rather than an
array of bytes, abstracting away from the different sizes of the
run-time representations of different values. A reference, then,
is simply an index into the store. (If we like, we can even
abstract away from the fact that these indices are numbers, but
for purposes of formalization in Coq it is a bit more convenient
to use numbers.) We'll use the word _location_ instead of
_reference_ or _pointer_ from now on to emphasize this abstract
quality.
Treating locations abstractly in this way will prevent us from
modeling the _pointer arithmetic_ found in low-level languages
such as C. This limitation is intentional. While pointer
arithmetic is occasionally very useful, especially for
implementing low-level services such as garbage collectors, it
cannot be tracked by most type systems: knowing that location [n]
in the store contains a [float] doesn't tell us anything useful
about the type of location [n+4]. In C, pointer arithmetic is a
notorious source of type safety violations. *)
(* ################################### *)
(** ** Stores *)
(** Recall that, in the small-step operational semantics for
IMP, the step relation needed to carry along an auxiliary state in
addition to the program being executed. In the same way, once we
have added reference cells to the STLC, our step relation must
carry along a store to keep track of the contents of reference
cells.
We could re-use the same functional representation we used for
states in IMP, but for carrying out the proofs in this chapter it
is actually more convenient to represent a store simply as a
_list_ of values. (The reason we couldn't use this representation
before is that, in IMP, a program could modify any location at any
time, so states had to be ready to map _any_ variable to a value.
However, in the STLC with references, the only way to create a
reference cell is with [tref t1], which puts the value of [t1]
in a new reference cell and evaluates to the location of the newly
created reference cell. When evaluating such an expression, we can
just add a new reference cell to the end of the list representing
the store.) *)
Definition store := list tm.
(** We use [store_lookup n st] to retrieve the value of the reference
cell at location [n] in the store [st]. Note that we must give a
default value to [nth] in case we try looking up an index which is
too large. (In fact, we will never actually do this, but proving
it will of course require some work!) *)
Definition store_lookup (n:nat) (st:store) :=
nth n st tunit.
(** To add a new reference cell to the store, we use [snoc]. *)
Fixpoint snoc {A:Type} (l:list A) (x:A) : list A :=
match l with
| nil => x :: nil
| h :: t => h :: snoc t x
end.
(** We will need some boring lemmas about [snoc]. The proofs are
routine inductions. *)
Lemma length_snoc : forall A (l:list A) x,
length (snoc l x) = S (length l).
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ]. Qed.
(* The "solve by inversion" tactic is explained in Stlc.v. *)
Lemma nth_lt_snoc : forall A (l:list A) x d n,
n < length l ->
nth n l d = nth n (snoc l x) d.
Proof.
induction l as [|a l']; intros; try solve by inversion.
Case "l = a :: l'".
destruct n; auto.
simpl. apply IHl'.
simpl in H. apply lt_S_n in H. assumption.
Qed.
Lemma nth_eq_snoc : forall A (l:list A) x d,
nth (length l) (snoc l x) d = x.
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ].
Qed.
(** To update the store, we use the [replace] function, which replaces
the contents of a cell at a particular index. *)
Fixpoint replace {A:Type} (n:nat) (x:A) (l:list A) : list A :=
match l with
| nil => nil
| h :: t =>
match n with
| O => x :: t
| S n' => h :: replace n' x t
end
end.
(** Of course, we also need some boring lemmas about [replace], which
are also fairly straightforward to prove. *)
Lemma replace_nil : forall A n (x:A),
replace n x nil = nil.
Proof.
destruct n; auto.
Qed.
Lemma length_replace : forall A n x (l:list A),
length (replace n x l) = length l.
Proof with auto.
intros A n x l. generalize dependent n.
induction l; intros n.
destruct n...
destruct n...
simpl. rewrite IHl...
Qed.
Lemma lookup_replace_eq : forall l t st,
l < length st ->
store_lookup l (replace l t st) = t.
Proof with auto.
intros l t st.
unfold store_lookup.
generalize dependent l.
induction st as [|t' st']; intros l Hlen.
Case "st = []".
inversion Hlen.
Case "st = t' :: st'".
destruct l; simpl...
apply IHst'. simpl in Hlen. omega.
Qed.
Lemma lookup_replace_neq : forall l1 l2 t st,
l1 <> l2 ->
store_lookup l1 (replace l2 t st) = store_lookup l1 st.
Proof with auto.
unfold store_lookup.
induction l1 as [|l1']; intros l2 t st Hneq.
Case "l1 = 0".
destruct st.
SCase "st = []". rewrite replace_nil...
SCase "st = _ :: _". destruct l2... contradict Hneq...
Case "l1 = S l1'".
destruct st as [|t2 st2].
SCase "st = []". destruct l2...
SCase "st = t2 :: st2".
destruct l2...
simpl; apply IHl1'...
Qed.
(* ################################### *)
(** ** Reduction *)
(** Next, we need to extend our operational semantics to take stores
into account. Since the result of evaluating an expression will
in general depend on the contents of the store in which it is
evaluated, the evaluation rules should take not just a term but
also a store as argument. Furthermore, since the evaluation of a
term may cause side effects on the store that may affect the
evaluation of other terms in the future, the evaluation rules need
to return a new store. Thus, the shape of the single-step
evaluation relation changes from [t ==> t'] to [t / st ==> t' /
st'], where [st] and [st'] are the starting and ending states of
the store.
To carry through this change, we first need to augment all of our
existing evaluation rules with stores:
value v2
-------------------------------------- (ST_AppAbs)
(\x:T.t12) v2 / st ==> [x:=v2]t12 / st
t1 / st ==> t1' / st'
--------------------------- (ST_App1)
t1 t2 / st ==> t1' t2 / st'
value v1 t2 / st ==> t2' / st'
---------------------------------- (ST_App2)
v1 t2 / st ==> v1 t2' / st'
Note that the first rule here returns the store unchanged:
function application, in itself, has no side effects. The other two
rules simply propagate side effects from premise to conclusion.
Now, the result of evaluating a [ref] expression will be a fresh
location; this is why we included locations in the syntax of terms
and in the set of values.
It is crucial to note that making this extension to the syntax of
terms does not mean that we intend _programmers_ to write terms
involving explicit, concrete locations: such terms will arise only
as intermediate results of evaluation. This may initially seem
odd, but really it follows naturally from our design decision to
represent the result of every evaluation step by a modified
term. If we had chosen a more "machine-like" model for evaluation,
e.g. with an explicit stack to contain values of bound
identifiers, then the idea of adding locations to the set of
allowed values would probably seem more obvious.
In terms of this expanded syntax, we can state evaluation rules for
the new constructs that manipulate locations and the store. First, to
evaluate a dereferencing expression [!t1], we must first reduce [t1]
until it becomes a value:
t1 / st ==> t1' / st'
----------------------- (ST_Deref)
!t1 / st ==> !t1' / st'
Once [t1] has finished reducing, we should have an expression of
the form [!l], where [l] is some location. (A term that attempts
to dereference any other sort of value, such as a function or
[unit], is erroneous, as is a term that tries to derefence a
location that is larger than the size [|st|] of the currently
allocated store; the evaluation rules simply get stuck in this
case. The type safety properties that we'll establish below
assure us that well-typed terms will never misbehave in this way.)
l < |st|
---------------------------------- (ST_DerefLoc)
!(loc l) / st ==> lookup l st / st
Next, to evaluate an assignment expression [t1:=t2], we must first
evaluate [t1] until it becomes a value (a location), and then
evaluate [t2] until it becomes a value (of any sort):
t1 / st ==> t1' / st'
----------------------------------- (ST_Assign1)
t1 := t2 / st ==> t1' := t2 / st'
t2 / st ==> t2' / st'
--------------------------------- (ST_Assign2)
v1 := t2 / st ==> v1 := t2' / st'
Once we have finished with [t1] and [t2], we have an expression of
the form [l:=v2], which we execute by updating the store to make
location [l] contain [v2]:
l < |st|
------------------------------------- (ST_Assign)
loc l := v2 / st ==> unit / [l:=v2]st
The notation [[l:=v2]st] means "the store that maps [l] to [v2]
and maps all other locations to the same thing as [st.]" Note
that the term resulting from this evaluation step is just [unit];
the interesting result is the updated store.)
Finally, to evaluate an expression of the form [ref t1], we first
evaluate [t1] until it becomes a value:
t1 / st ==> t1' / st'
----------------------------- (ST_Ref)
ref t1 / st ==> ref t1' / st'
Then, to evaluate the [ref] itself, we choose a fresh location at
the end of the current store -- i.e., location [|st|] -- and yield
a new store that extends [st] with the new value [v1].
-------------------------------- (ST_RefValue)
ref v1 / st ==> loc |st| / st,v1
The value resulting from this step is the newly allocated location
itself. (Formally, [st,v1] means [snoc st v1].)
Note that these evaluation rules do not perform any kind of
garbage collection: we simply allow the store to keep growing
without bound as evaluation proceeds. This does not affect the
correctness of the results of evaluation (after all, the
definition of "garbage" is precisely parts of the store that are
no longer reachable and so cannot play any further role in
evaluation), but it means that a naive implementation of our
evaluator might sometimes run out of memory where a more
sophisticated evaluator would be able to continue by reusing
locations whose contents have become garbage.
Formally... *)
Reserved Notation "t1 '/' st1 '==>' t2 '/' st2"
(at level 40, st1 at level 39, t2 at level 39).
Inductive step : tm * store -> tm * store -> Prop :=
| ST_AppAbs : forall x T t12 v2 st,
value v2 ->
tapp (tabs x T t12) v2 / st ==> [x:=v2]t12 / st
| ST_App1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tapp t1 t2 / st ==> tapp t1' t2 / st'
| ST_App2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tapp v1 t2 / st ==> tapp v1 t2'/ st'
| ST_SuccNat : forall n st,
tsucc (tnat n) / st ==> tnat (S n) / st
| ST_Succ : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tsucc t1 / st ==> tsucc t1' / st'
| ST_PredNat : forall n st,
tpred (tnat n) / st ==> tnat (pred n) / st
| ST_Pred : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tpred t1 / st ==> tpred t1' / st'
| ST_MultNats : forall n1 n2 st,
tmult (tnat n1) (tnat n2) / st ==> tnat (mult n1 n2) / st
| ST_Mult1 : forall t1 t2 t1' st st',
t1 / st ==> t1' / st' ->
tmult t1 t2 / st ==> tmult t1' t2 / st'
| ST_Mult2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tmult v1 t2 / st ==> tmult v1 t2' / st'
| ST_If0 : forall t1 t1' t2 t3 st st',
t1 / st ==> t1' / st' ->
tif0 t1 t2 t3 / st ==> tif0 t1' t2 t3 / st'
| ST_If0_Zero : forall t2 t3 st,
tif0 (tnat 0) t2 t3 / st ==> t2 / st
| ST_If0_Nonzero : forall n t2 t3 st,
tif0 (tnat (S n)) t2 t3 / st ==> t3 / st
| ST_RefValue : forall v1 st,
value v1 ->
tref v1 / st ==> tloc (length st) / snoc st v1
| ST_Ref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tref t1 / st ==> tref t1' / st'
| ST_DerefLoc : forall st l,
l < length st ->
tderef (tloc l) / st ==> store_lookup l st / st
| ST_Deref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tderef t1 / st ==> tderef t1' / st'
| ST_Assign : forall v2 l st,
value v2 ->
l < length st ->
tassign (tloc l) v2 / st ==> tunit / replace l v2 st
| ST_Assign1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tassign t1 t2 / st ==> tassign t1' t2 / st'
| ST_Assign2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tassign v1 t2 / st ==> tassign v1 t2' / st'
where "t1 '/' st1 '==>' t2 '/' st2" := (step (t1,st1) (t2,st2)).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_SuccNat"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Pred" | Case_aux c "ST_MultNats"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_If0" | Case_aux c "ST_If0_Zero"
| Case_aux c "ST_If0_Nonzero" | Case_aux c "ST_RefValue"
| Case_aux c "ST_Ref" | Case_aux c "ST_DerefLoc"
| Case_aux c "ST_Deref" | Case_aux c "ST_Assign"
| Case_aux c "ST_Assign1" | Case_aux c "ST_Assign2" ].
Hint Constructors step.
Definition multistep := (multi step).
Notation "t1 '/' st '==>*' t2 '/' st'" := (multistep (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(* ################################### *)
(** * Typing *)
(** Our contexts for free variables will be exactly the same as for
the STLC, partial maps from identifiers to types. *)
Definition context := partial_map ty.
(* ################################### *)
(** ** Store typings *)
(** Having extended our syntax and evaluation rules to accommodate
references, our last job is to write down typing rules for the new
constructs -- and, of course, to check that they are sound.
Naturally, the key question is, "What is the type of a location?"
First of all, notice that we do _not_ need to answer this question
for purposes of typechecking the terms that programmers actually
write. Concrete location constants arise only in terms that are
the intermediate results of evaluation; they are not in the
language that programmers write. So we only need to determine the
type of a location when we're in the middle of an evaluation
sequence, e.g. trying to apply the progress or preservation
lemmas. Thus, even though we normally think of typing as a
_static_ program property, it makes sense for the typing of
locations to depend on the _dynamic_ progress of the program too.
As a first try, note that when we evaluate a term containing
concrete locations, the type of the result depends on the contents
of the store that we start with. For example, if we evaluate the
term [!(loc 1)] in the store [[unit, unit]], the result is [unit];
if we evaluate the same term in the store [[unit, \x:Unit.x]], the
result is [\x:Unit.x]. With respect to the former store, the
location [1] has type [Unit], and with respect to the latter it
has type [Unit->Unit]. This observation leads us immediately to a
first attempt at a typing rule for locations:
Gamma |- lookup l st : T1
----------------------------
Gamma |- loc l : Ref T1
That is, to find the type of a location [l], we look up the
current contents of [l] in the store and calculate the type [T1]
of the contents. The type of the location is then [Ref T1].
Having begun in this way, we need to go a little further to reach a
consistent state. In effect, by making the type of a term depend on
the store, we have changed the typing relation from a three-place
relation (between contexts, terms, and types) to a four-place relation
(between contexts, _stores_, terms, and types). Since the store is,
intuitively, part of the context in which we calculate the type of a
term, let's write this four-place relation with the store to the left
of the turnstile: [Gamma; st |- t : T]. Our rule for typing
references now has the form
Gamma; st |- lookup l st : T1
--------------------------------
Gamma; st |- loc l : Ref T1
and all the rest of the typing rules in the system are extended
similarly with stores. The other rules do not need to do anything
interesting with their stores -- just pass them from premise to
conclusion.
However, there are two problems with this rule. First, typechecking
is rather inefficient, since calculating the type of a location [l]
involves calculating the type of the current contents [v] of [l]. If
[l] appears many times in a term [t], we will re-calculate the type of
[v] many times in the course of constructing a typing derivation for
[t]. Worse, if [v] itself contains locations, then we will have to
recalculate _their_ types each time they appear.
Second, the proposed typing rule for locations may not allow us to
derive anything at all, if the store contains a _cycle_. For example,
there is no finite typing derivation for the location [0] with respect
to this store:
<<
[\x:Nat. (!(loc 1)) x, \x:Nat. (!(loc 0)) x]
>>
*)
(** **** Exercise: 2 stars (cyclic_store) *)
(** Can you find a term whose evaluation will create this particular
cyclic store? *)
(** [] *)
(** Both of these problems arise from the fact that our proposed
typing rule for locations requires us to recalculate the type of a
location every time we mention it in a term. But this,
intuitively, should not be necessary. After all, when a location
is first created, we know the type of the initial value that we
are storing into it. Suppose we are willing to enforce the
invariant that the type of the value contained in a given location
_never changes_; that is, although we may later store other values
into this location, those other values will always have the same
type as the initial one. In other words, we always have in mind a
single, definite type for every location in the store, which is
fixed when the location is allocated. Then these intended types
can be collected together as a _store typing_ ---a finite function
mapping locations to types.
As usual, this _conservative_ typing restriction on allowed
updates means that we will rule out as ill-typed some programs
that could evaluate perfectly well without getting stuck.
*)
(** Just like we did for stores, we will represent a store type simply
as a list of types: the type at index [i] records the type of the
value stored in cell [i]. *)
Definition store_ty := list ty.
(** The [store_Tlookup] function retrieves the type at a particular
index. *)
Definition store_Tlookup (n:nat) (ST:store_ty) :=
nth n ST TUnit.
(** Suppose we are _given_ a store typing [ST] describing the store
[st] in which some term [t] will be evaluated. Then we can use
[ST] to calculate the type of the result of [t] without ever
looking directly at [st]. For example, if [ST] is [[Unit,
Unit->Unit]], then we may immediately infer that [!(loc 1)] has
type [Unit->Unit]. More generally, the typing rule for locations
can be reformulated in terms of store typings like this:
l < |ST|
-------------------------------------
Gamma; ST |- loc l : Ref (lookup l ST)
That is, as long as [l] is a valid location (it is less than the
length of [ST]), we can compute the type of [l] just by looking it
up in [ST]. Typing is again a four-place relation, but it is
parameterized on a store _typing_ rather than a concrete store.
The rest of the typing rules are analogously augmented with store
typings. *)
(* ################################### *)
(** ** The Typing Relation *)
(** We can now give the typing relation for the STLC with
references. Here, again, are the rules we're adding to the base
STLC (with numbers and [Unit]): *)
(**
l < |ST|
-------------------------------------- (T_Loc)
Gamma; ST |- loc l : Ref (lookup l ST)
Gamma; ST |- t1 : T1
---------------------------- (T_Ref)
Gamma; ST |- ref t1 : Ref T1
Gamma; ST |- t1 : Ref T11
------------------------- (T_Deref)
Gamma; ST |- !t1 : T11
Gamma; ST |- t1 : Ref T11
Gamma; ST |- t2 : T11
----------------------------- (T_Assign)
Gamma; ST |- t1 := t2 : Unit
*)
Reserved Notation "Gamma ';' ST '|-' t '\in' T" (at level 40).
Inductive has_type : context -> store_ty -> tm -> ty -> Prop :=
| T_Var : forall Gamma ST x T,
Gamma x = Some T ->
Gamma; ST |- (tvar x) \in T
| T_Abs : forall Gamma ST x T11 T12 t12,
(extend Gamma x T11); ST |- t12 \in T12 ->
Gamma; ST |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma ST t1 t2,
Gamma; ST |- t1 \in (TArrow T1 T2) ->
Gamma; ST |- t2 \in T1 ->
Gamma; ST |- (tapp t1 t2) \in T2
| T_Nat : forall Gamma ST n,
Gamma; ST |- (tnat n) \in TNat
| T_Succ : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tsucc t1) \in TNat
| T_Pred : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tpred t1) \in TNat
| T_Mult : forall Gamma ST t1 t2,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in TNat ->
Gamma; ST |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma ST t1 t2 t3 T,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in T ->
Gamma; ST |- t3 \in T ->
Gamma; ST |- (tif0 t1 t2 t3) \in T
| T_Unit : forall Gamma ST,
Gamma; ST |- tunit \in TUnit
| T_Loc : forall Gamma ST l,
l < length ST ->
Gamma; ST |- (tloc l) \in (TRef (store_Tlookup l ST))
| T_Ref : forall Gamma ST t1 T1,
Gamma; ST |- t1 \in T1 ->
Gamma; ST |- (tref t1) \in (TRef T1)
| T_Deref : forall Gamma ST t1 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- (tderef t1) \in T11
| T_Assign : forall Gamma ST t1 t2 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- t2 \in T11 ->
Gamma; ST |- (tassign t1 t2) \in TUnit
where "Gamma ';' ST '|-' t '\in' T" := (has_type Gamma ST t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Unit" | Case_aux c "T_Loc"
| Case_aux c "T_Ref" | Case_aux c "T_Deref"
| Case_aux c "T_Assign" ].
(** Of course, these typing rules will accurately predict the results
of evaluation only if the concrete store used during evaluation
actually conforms to the store typing that we assume for purposes
of typechecking. This proviso exactly parallels the situation
with free variables in the STLC: the substitution lemma promises
us that, if [Gamma |- t : T], then we can replace the free
variables in [t] with values of the types listed in [Gamma] to
obtain a closed term of type [T], which, by the type preservation
theorem will evaluate to a final result of type [T] if it yields
any result at all. (We will see later how to formalize an
analogous intuition for stores and store typings.)
However, for purposes of typechecking the terms that programmers
actually write, we do not need to do anything tricky to guess what
store typing we should use. Recall that concrete location
constants arise only in terms that are the intermediate results of
evaluation; they are not in the language that programmers write.
Thus, we can simply typecheck the programmer's terms with respect
to the _empty_ store typing. As evaluation proceeds and new
locations are created, we will always be able to see how to extend
the store typing by looking at the type of the initial values
being placed in newly allocated cells; this intuition is
formalized in the statement of the type preservation theorem
below. *)
(* ################################### *)
(** * Properties *)
(** Our final task is to check that standard type safety properties
continue to hold for the STLC with references. The progress
theorem ("well-typed terms are not stuck") can be stated and
proved almost as for the STLC; we just need to add a few
straightforward cases to the proof, dealing with the new
constructs. The preservation theorem is a bit more interesting,
so let's look at it first. *)
(* ################################### *)
(** ** Well-Typed Stores *)
(** Since we have extended both the evaluation relation (with initial
and final stores) and the typing relation (with a store typing),
we need to change the statement of preservation to include these
parameters. Clearly, though, we cannot just add stores and store
typings without saying anything about how they are related: *)
Theorem preservation_wrong1 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
empty; ST |- t' \in T.
Abort.
(** If we typecheck with respect to some set of assumptions about the
types of the values in the store and then evaluate with respect to
a store that violates these assumptions, the result will be
disaster. We say that a store [st] is _well typed_ with respect a
store typing [ST] if the term at each location [l] in [st] has the
type at location [l] in [ST]. Since only closed terms ever get
stored in locations (why?), it suffices to type them in the empty
context. The following definition of [store_well_typed] formalizes
this. *)
Definition store_well_typed (ST:store_ty) (st:store) :=
length ST = length st /\
(forall l, l < length st ->
empty; ST |- (store_lookup l st) \in (store_Tlookup l ST)).
(** Informally, we will write [ST |- st] for [store_well_typed ST st]. *)
(** Intuitively, a store [st] is consistent with a store typing
[ST] if every value in the store has the type predicted by the
store typing. (The only subtle point is the fact that, when
typing the values in the store, we supply the very same store
typing to the typing relation! This allows us to type circular
stores.) *)
(** **** Exercise: 2 stars (store_not_unique) *)
(** Can you find a store [st], and two
different store typings [ST1] and [ST2] such that both
[ST1 |- st] and [ST2 |- st]? *)
(* FILL IN HERE *)
(** [] *)
(** We can now state something closer to the desired preservation
property: *)
Theorem preservation_wrong2 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
store_well_typed ST st ->
empty; ST |- t' \in T.
Abort.
(** This statement is fine for all of the evaluation rules except the
allocation rule [ST_RefValue]. The problem is that this rule
yields a store with a larger domain than the initial store, which
falsifies the conclusion of the above statement: if [st']
includes a binding for a fresh location [l], then [l] cannot be in
the domain of [ST], and it will not be the case that [t']
(which definitely mentions [l]) is typable under [ST]. *)
(* ############################################ *)
(** ** Extending Store Typings *)
(** Evidently, since the store can increase in size during evaluation,
we need to allow the store typing to grow as well. This motivates
the following definition. We say that the store type [ST']
_extends_ [ST] if [ST'] is just [ST] with some new types added to
the end. *)
Inductive extends : store_ty -> store_ty -> Prop :=
| extends_nil : forall ST',
extends ST' nil
| extends_cons : forall x ST' ST,
extends ST' ST ->
extends (x::ST') (x::ST).
Hint Constructors extends.
(** We'll need a few technical lemmas about extended contexts.
First, looking up a type in an extended store typing yields the
same result as in the original: *)
Lemma extends_lookup : forall l ST ST',
l < length ST ->
extends ST' ST ->
store_Tlookup l ST' = store_Tlookup l ST.
Proof with auto.
intros l ST ST' Hlen H.
generalize dependent ST'. generalize dependent l.
induction ST as [|a ST2]; intros l Hlen ST' HST'.
Case "nil". inversion Hlen.
Case "cons". unfold store_Tlookup in *.
destruct ST'.
SCase "ST' = nil". inversion HST'.
SCase "ST' = a' :: ST'2".
inversion HST'; subst.
destruct l as [|l'].
SSCase "l = 0"...
SSCase "l = S l'". simpl. apply IHST2...
simpl in Hlen; omega.
Qed.
(** Next, if [ST'] extends [ST], the length of [ST'] is at least that
of [ST]. *)
Lemma length_extends : forall l ST ST',
l < length ST ->
extends ST' ST ->
l < length ST'.
Proof with eauto.
intros. generalize dependent l. induction H0; intros l Hlen.
inversion Hlen.
simpl in *.
destruct l; try omega.
apply lt_n_S. apply IHextends. omega.
Qed.
(** Finally, [snoc ST T] extends [ST], and [extends] is reflexive. *)
Lemma extends_snoc : forall ST T,
extends (snoc ST T) ST.
Proof with auto.
induction ST; intros T...
simpl...
Qed.
Lemma extends_refl : forall ST,
extends ST ST.
Proof.
induction ST; auto.
Qed.
(* ################################### *)
(** ** Preservation, Finally *)
(** We can now give the final, correct statement of the type
preservation property: *)
Definition preservation_theorem := forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
(** Note that the preservation theorem merely asserts that there is
_some_ store typing [ST'] extending [ST] (i.e., agreeing with [ST]
on the values of all the old locations) such that the new term
[t'] is well typed with respect to [ST']; it does not tell us
exactly what [ST'] is. It is intuitively clear, of course, that
[ST'] is either [ST] or else it is exactly [snoc ST T1], where
[T1] is the type of the value [v1] in the extended store [snoc st
v1], but stating this explicitly would complicate the statement of
the theorem without actually making it any more useful: the weaker
version above is already in the right form (because its conclusion
implies its hypothesis) to "turn the crank" repeatedly and
conclude that every _sequence_ of evaluation steps preserves
well-typedness. Combining this with the progress property, we
obtain the usual guarantee that "well-typed programs never go
wrong."
In order to prove this, we'll need a few lemmas, as usual. *)
(* ################################### *)
(** ** Substitution lemma *)
(** First, we need an easy extension of the standard substitution
lemma, along with the same machinery about context invariance that
we used in the proof of the substitution lemma for the STLC. *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_succ : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tsucc t1)
| afi_pred : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tpred t1)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if0_1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_ref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tref t1)
| afi_deref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tderef t1)
| afi_assign1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tassign t1 t2)
| afi_assign2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tassign t1 t2).
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_succ" | Case_aux c "afi_pred"
| Case_aux c "afi_mult1" | Case_aux c "afi_mult2"
| Case_aux c "afi_if0_1" | Case_aux c "afi_if0_2" | Case_aux c "afi_if0_3"
| Case_aux c "afi_ref" | Case_aux c "afi_deref"
| Case_aux c "afi_assign1" | Case_aux c "afi_assign2" ].
Hint Constructors appears_free_in.
Lemma free_in_context : forall x t T Gamma ST,
appears_free_in x t ->
Gamma; ST |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros. generalize dependent Gamma. generalize dependent T.
afi_cases (induction H) Case;
intros; (try solve [ inversion H0; subst; eauto ]).
Case "afi_abs".
inversion H1; subst.
apply IHappears_free_in in H8.
rewrite extend_neq in H8; assumption.
Qed.
Lemma context_invariance : forall Gamma Gamma' ST t T,
Gamma; ST |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma'; ST |- t \in T.
Proof with eauto.
intros.
generalize dependent Gamma'.
has_type_cases (induction H) Case; intros...
Case "T_Var".
apply T_Var. symmetry. rewrite <- H...
Case "T_Abs".
apply T_Abs. apply IHhas_type; intros.
unfold extend.
destruct (eq_id_dec x x0)...
Case "T_App".
eapply T_App.
apply IHhas_type1...
apply IHhas_type2...
Case "T_Mult".
eapply T_Mult.
apply IHhas_type1...
apply IHhas_type2...
Case "T_If0".
eapply T_If0.
apply IHhas_type1...
apply IHhas_type2...
apply IHhas_type3...
Case "T_Assign".
eapply T_Assign.
apply IHhas_type1...
apply IHhas_type2...
Qed.
Lemma substitution_preserves_typing : forall Gamma ST x s S t T,
empty; ST |- s \in S ->
(extend Gamma x S); ST |- t \in T ->
Gamma; ST |- ([x:=s]t) \in T.
Proof with eauto.
intros Gamma ST x s S t T Hs Ht.
generalize dependent Gamma. generalize dependent T.
t_cases (induction t) Case; intros T Gamma 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 H3.
inversion H3; subst.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ _ _ _ Hcontra Hs) as [T' HT'].
inversion HT'.
SCase "x <> y".
apply T_Var.
rewrite extend_neq in H3...
Case "tabs". subst.
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
apply T_Abs. eapply context_invariance...
intros. apply extend_shadow.
SCase "x <> x0".
apply T_Abs. apply IHt.
eapply context_invariance...
intros. unfold extend.
destruct (eq_id_dec y x0)...
subst.
rewrite neq_id...
Qed.
(* ################################### *)
(** ** Assignment Preserves Store Typing *)
(** Next, we must show that replacing the contents of a cell in the
store with a new value of appropriate type does not change the
overall type of the store. (This is needed for the [ST_Assign]
rule.) *)
Lemma assign_pres_store_typing : forall ST st l t,
l < length st ->
store_well_typed ST st ->
empty; ST |- t \in (store_Tlookup l ST) ->
store_well_typed ST (replace l t st).
Proof with auto.
intros ST st l t Hlen HST Ht.
inversion HST; subst.
split. rewrite length_replace...
intros l' Hl'.
destruct (beq_nat l' l) eqn: Heqll'.
Case "l' = l".
apply beq_nat_true in Heqll'; subst.
rewrite lookup_replace_eq...
Case "l' <> l".
apply beq_nat_false in Heqll'.
rewrite lookup_replace_neq...
rewrite length_replace in Hl'.
apply H0...
Qed.
(* ######################################## *)
(** ** Weakening for Stores *)
(** Finally, we need a lemma on store typings, stating that, if a
store typing is extended with a new location, the extended one
still allows us to assign the same types to the same terms as the
original.
(The lemma is called [store_weakening] because it resembles the
"weakening" lemmas found in proof theory, which show that adding a
new assumption to some logical theory does not decrease the set of
provable theorems.) *)
Lemma store_weakening : forall Gamma ST ST' t T,
extends ST' ST ->
Gamma; ST |- t \in T ->
Gamma; ST' |- t \in T.
Proof with eauto.
intros. has_type_cases (induction H0) Case; eauto.
Case "T_Loc".
erewrite <- extends_lookup...
apply T_Loc.
eapply length_extends...
Qed.
(** We can use the [store_weakening] lemma to prove that if a store is
well typed with respect to a store typing, then the store extended
with a new term [t] will still be well typed with respect to the
store typing extended with [t]'s type. *)
Lemma store_well_typed_snoc : forall ST st t1 T1,
store_well_typed ST st ->
empty; ST |- t1 \in T1 ->
store_well_typed (snoc ST T1) (snoc st t1).
Proof with auto.
intros.
unfold store_well_typed in *.
inversion H as [Hlen Hmatch]; clear H.
rewrite !length_snoc.
split...
Case "types match.".
intros l Hl.
unfold store_lookup, store_Tlookup.
apply le_lt_eq_dec in Hl; inversion Hl as [Hlt | Heq].
SCase "l < length st".
apply lt_S_n in Hlt.
rewrite <- !nth_lt_snoc...
apply store_weakening with ST. apply extends_snoc.
apply Hmatch...
rewrite Hlen...
SCase "l = length st".
inversion Heq.
rewrite nth_eq_snoc.
rewrite <- Hlen. rewrite nth_eq_snoc...
apply store_weakening with ST... apply extends_snoc.
Qed.
(* ################################### *)
(** ** Preservation! *)
(** Now that we've got everything set up right, the proof of
preservation is actually quite straightforward. *)
Theorem preservation : forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
Proof with eauto using store_weakening, extends_refl.
remember (@empty ty) as Gamma.
intros ST t t' T st st' Ht.
generalize dependent t'.
has_type_cases (induction Ht) Case; intros t' HST Hstep;
subst; try (solve by inversion); inversion Hstep; subst;
try (eauto using store_weakening, extends_refl).
Case "T_App".
SCase "ST_AppAbs". exists ST.
inversion Ht1; subst.
split; try split... eapply substitution_preserves_typing...
SCase "ST_App1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_App2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Succ".
SCase "ST_Succ".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Pred".
SCase "ST_Pred".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Mult".
SCase "ST_Mult1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Mult2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_If0".
SCase "ST_If0_1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'... split...
Case "T_Ref".
SCase "ST_RefValue".
exists (snoc ST T1).
inversion HST; subst.
split.
apply extends_snoc.
split.
replace (TRef T1)
with (TRef (store_Tlookup (length st) (snoc ST T1))).
apply T_Loc.
rewrite <- H. rewrite length_snoc. omega.
unfold store_Tlookup. rewrite <- H. rewrite nth_eq_snoc...
apply store_well_typed_snoc; assumption.
SCase "ST_Ref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Deref".
SCase "ST_DerefLoc".
exists ST. split; try split...
inversion HST as [_ Hsty].
replace T11 with (store_Tlookup l ST).
apply Hsty...
inversion Ht; subst...
SCase "ST_Deref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Assign".
SCase "ST_Assign".
exists ST. split; try split...
eapply assign_pres_store_typing...
inversion Ht1; subst...
SCase "ST_Assign1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Assign2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Qed.
(** **** Exercise: 3 stars (preservation_informal) *)
(** Write a careful informal proof of the preservation theorem,
concentrating on the [T_App], [T_Deref], [T_Assign], and [T_Ref]
cases.
(* FILL IN HERE *)
[] *)
(* ################################### *)
(** ** Progress *)
(** Fortunately, progress for this system is pretty easy to prove; the
proof is very similar to the proof of progress for the STLC, with
a few new cases for the new syntactic constructs. *)
Theorem progress : forall ST t T st,
empty; ST |- t \in T ->
store_well_typed ST st ->
(value t \/ exists t', exists st', t / st ==> t' / st').
Proof with eauto.
intros ST t T st Ht HST. remember (@empty ty) as Gamma.
has_type_cases (induction Ht) Case; subst; try solve by inversion...
Case "T_App".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tapp (tabs x T t) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tapp t1' t2). exists st'...
Case "T_Succ".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [ inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (S n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tsucc t1'). exists st'...
Case "T_Pred".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (pred n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tpred t1'). exists st'...
Case "T_Mult".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 is a value".
inversion Ht2p; subst; try solve [inversion Ht2].
exists (tnat (mult n n0)). exists st...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tmult (tnat n) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tmult t1' t2). exists st'...
Case "T_If0".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct n.
SSCase "n = 0". exists t2. exists st...
SSCase "n = S n'". exists t3. exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tif0 t1' t2 t3). exists st'...
Case "T_Ref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tref t1'). exists st'...
Case "T_Deref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_DerefLoc...
inversion Ht; subst. inversion HST; subst.
rewrite <- H...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tderef t1'). exists st'...
Case "T_Assign".
right. destruct IHHt1 as [Ht1p|Ht1p]...
SCase "t1 is a value".
destruct IHHt2 as [Ht2p|Ht2p]...
SSCase "t2 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_Assign...
inversion HST; subst. inversion Ht1; subst.
rewrite H in H5...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tassign t1 t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tassign t1' t2). exists st'...
Qed.
(* ################################### *)
(** * References and Nontermination *)
Section RefsAndNontermination.
Import ExampleVariables.
(** We know that the simply typed lambda calculus is _normalizing_,
that is, every well-typed term can be reduced to a value in a
finite number of steps. What about STLC + references?
Surprisingly, adding references causes us to lose the
normalization property: there exist well-typed terms in the STLC +
references which can continue to reduce forever, without ever
reaching a normal form!
How can we construct such a term? The main idea is to make a
function which calls itself. We first make a function which calls
another function stored in a reference cell; the trick is that we
then smuggle in a reference to itself!
<<
(\r:Ref (Unit -> Unit).
r := (\x:Unit.(!r) unit); (!r) unit)
(ref (\x:Unit.unit))
>>
First, [ref (\x:Unit.unit)] creates a reference to a cell of type
[Unit -> Unit]. We then pass this reference as the argument to a
function which binds it to the name [r], and assigns to it the
function (\x:Unit.(!r) unit) -- that is, the function which
ignores its argument and calls the function stored in [r] on the
argument [unit]; but of course, that function is itself! To get
the ball rolling we finally execute this function with [(!r)
unit].
*)
Definition loop_fun :=
tabs x TUnit (tapp (tderef (tvar r)) tunit).
Definition loop :=
tapp
(tabs r (TRef (TArrow TUnit TUnit))
(tseq (tassign (tvar r) loop_fun)
(tapp (tderef (tvar r)) tunit)))
(tref (tabs x TUnit tunit)).
(** This term is well typed: *)
Lemma loop_typeable : exists T, empty; nil |- loop \in T.
Proof with eauto.
eexists. unfold loop. unfold loop_fun.
eapply T_App...
eapply T_Abs...
eapply T_App...
eapply T_Abs. eapply T_App. eapply T_Deref. eapply T_Var.
unfold extend. simpl. reflexivity. auto.
eapply T_Assign.
eapply T_Var. unfold extend. simpl. reflexivity.
eapply T_Abs.
eapply T_App...
eapply T_Deref. eapply T_Var. reflexivity.
Qed.
(** To show formally that the term diverges, we first define the
[step_closure] of the single-step reduction relation, written
[==>+]. This is just like the reflexive step closure of
single-step reduction (which we're been writing [==>*]), except
that it is not reflexive: [t ==>+ t'] means that [t] can reach
[t'] by _one or more_ steps of reduction. *)
Inductive step_closure {X:Type} (R: relation X) : X -> X -> Prop :=
| sc_one : forall (x y : X),
R x y -> step_closure R x y
| sc_step : forall (x y z : X),
R x y ->
step_closure R y z ->
step_closure R x z.
Definition multistep1 := (step_closure step).
Notation "t1 '/' st '==>+' t2 '/' st'" := (multistep1 (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(** Now, we can show that the expression [loop] reduces to the
expression [!(loc 0) unit] and the size-one store [ [r:=(loc 0)]
loop_fun]. *)
(** As a convenience, we introduce a slight variant of the [normalize]
tactic, called [reduce], which tries solving the goal with
[multi_refl] at each step, instead of waiting until the goal can't
be reduced any more. Of course, the whole point is that [loop]
doesn't normalize, so the old [normalize] tactic would just go
into an infinite loop reducing it forever! *)
Ltac print_goal := match goal with |- ?x => idtac x end.
Ltac reduce :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; compute)];
try solve [apply multi_refl]).
Lemma loop_steps_to_loop_fun :
loop / nil ==>*
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop.
reduce.
Qed.
(** Finally, the latter expression reduces in two steps to itself! *)
Lemma loop_fun_step_self :
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil ==>+
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop_fun; simpl.
eapply sc_step. apply ST_App1...
eapply sc_one. compute. apply ST_AppAbs...
Qed.
(** **** Exercise: 4 stars (factorial_ref) *)
(** Use the above ideas to implement a factorial function in STLC with
references. (There is no need to prove formally that it really
behaves like the factorial. Just use the example below to make
sure it gives the correct result when applied to the argument
[4].) *)
Definition factorial : tm :=
(* FILL IN HERE *) admit.
Lemma factorial_type : empty; nil |- factorial \in (TArrow TNat TNat).
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** If your definition is correct, you should be able to just
uncomment the example below; the proof should be fully
automatic using the [reduce] tactic. *)
(*
Lemma factorial_4 : exists st,
tapp factorial (tnat 4) / nil ==>* tnat 24 / st.
Proof.
eexists. unfold factorial. reduce.
Qed.
*)
(** [] *)
(* ################################### *)
(** * Additional Exercises *)
(** **** Exercise: 5 stars, optional (garabage_collector) *)
(** Challenge problem: modify our formalization to include an account
of garbage collection, and prove that it satisfies whatever nice
properties you can think to prove about it. *)
(** [] *)
End RefsAndNontermination.
End STLCRef.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * References: Typing Mutable References *)
Require Export Smallstep.
(** So far, we have considered a variety of _pure_ language features,
including functional abstraction, basic types such as numbers and
booleans, and structured types such as records and variants. These
features form the backbone of most programming languages -- including
purely functional languages such as Haskell, "mostly functional"
languages such as ML, imperative languages such as C, and
object-oriented languages such as Java.
Most practical programming languages also include various _impure_
features that cannot be described in the simple semantic framework
we have used so far. In particular, besides just yielding
results, evaluation of terms in these languages may assign to
mutable variables (reference cells, arrays, mutable record fields,
etc.), perform input and output to files, displays, or network
connections, make non-local transfers of control via exceptions,
jumps, or continuations, engage in inter-process synchronization
and communication, and so on. In the literature on programming
languages, such "side effects" of computation are more generally
referred to as _computational effects_.
In this chapter, we'll see how one sort of computational
effect -- mutable references -- can be added to the calculi we have
studied. The main extension will be dealing explicitly with a
_store_ (or _heap_). This extension is straightforward to define;
the most interesting part is the refinement we need to make to the
statement of the type preservation theorem. *)
(* ###################################################################### *)
(** * Definitions *)
(** Pretty much every programming language provides some form of
assignment operation that changes the contents of a previously
allocated piece of storage. (Coq's internal language is a rare
exception!)
In some languages -- notably ML and its relatives -- the
mechanisms for name-binding and those for assignment are kept
separate. We can have a variable [x] whose _value_ is the number
[5], or we can have a variable [y] whose value is a
_reference_ (or _pointer_) to a mutable cell whose current
contents is [5]. These are different things, and the difference
is visible to the programmer. We can add [x] to another number,
but not assign to it. We can use [y] directly to assign a new
value to the cell that it points to (by writing [y:=84]), but we
cannot use it directly as an argument to an operation like [+].
Instead, we must explicitly _dereference_ it, writing [!y] to
obtain its current contents.
In most other languages -- in particular, in all members of the C
family, including Java -- _every_ variable name refers to a mutable
cell, and the operation of dereferencing a variable to obtain its
current contents is implicit.
For purposes of formal study, it is useful to keep these
mechanisms separate. The development in this chapter will closely
follow ML's model. Applying the lessons learned here to C-like
languages is a straightforward matter of collapsing some
distinctions and rendering some operations such as dereferencing
implicit instead of explicit.
In this chapter, we study adding mutable references to the
simply-typed lambda calculus with natural numbers. *)
(* ###################################################################### *)
(** * Syntax *)
Module STLCRef.
(** The basic operations on references are _allocation_,
_dereferencing_, and _assignment_.
- To allocate a reference, we use the [ref] operator, providing
an initial value for the new cell. For example, [ref 5]
creates a new cell containing the value [5], and evaluates to
a reference to that cell.
- To read the current value of this cell, we use the
dereferencing operator [!]; for example, [!(ref 5)] evaluates
to [5].
- To change the value stored in a cell, we use the assignment
operator. If [r] is a reference, [r := 7] will store the
value [7] in the cell referenced by [r]. However, [r := 7]
evaluates to the trivial value [unit]; it exists only to have
the _side effect_ of modifying the contents of a cell. *)
(* ################################### *)
(** *** Types *)
(** We start with the simply typed lambda calculus over the
natural numbers. To the base natural number type and arrow types
we need to add two more types to deal with references. First, we
need the _unit type_, which we will use as the result type of an
assignment operation. We then add _reference types_. *)
(** If [T] is a type, then [Ref T] is the type of references which
point to a cell holding values of type [T].
T ::= Nat
| Unit
| T -> T
| Ref T
*)
Inductive ty : Type :=
| TNat : ty
| TUnit : ty
| TArrow : ty -> ty -> ty
| TRef : ty -> ty.
(* ################################### *)
(** *** Terms *)
(** Besides variables, abstractions, applications,
natural-number-related terms, and [unit], we need four more sorts
of terms in order to handle mutable references:
<<
t ::= ... Terms
| ref t allocation
| !t dereference
| t := t assignment
| l location
>>
*)
Inductive tm : Type :=
(* STLC with numbers: *)
| 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
(* New terms: *)
| tunit : tm
| tref : tm -> tm
| tderef : tm -> tm
| tassign : tm -> tm -> tm
| tloc : nat -> tm.
(** Intuitively...
- [ref t] (formally, [tref t]) allocates a new reference cell
with the value [t] and evaluates to the location of the newly
allocated cell;
- [!t] (formally, [tderef t]) evaluates to the contents of the
cell referenced by [t];
- [t1 := t2] (formally, [tassign t1 t2]) assigns [t2] to the
cell referenced by [t1]; and
- [l] (formally, [tloc l]) is a reference to the cell at
location [l]. We'll discuss locations later. *)
(** In informal examples, we'll also freely use the extensions
of the STLC developed in the [MoreStlc] chapter; however, to keep
the proofs small, we won't bother formalizing them again here. It
would be easy to do so, since there are no very interesting
interactions between those features and references. *)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "tzero"
| Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tunit" | Case_aux c "tref"
| Case_aux c "tderef" | Case_aux c "tassign"
| Case_aux c "tloc" ].
Module ExampleVariables.
Definition x := Id 0.
Definition y := Id 1.
Definition r := Id 2.
Definition s := Id 3.
End ExampleVariables.
(* ################################### *)
(** *** Typing (Preview) *)
(** Informally, the typing rules for allocation, dereferencing, and
assignment will look like this:
Gamma |- t1 : T1
------------------------ (T_Ref)
Gamma |- ref t1 : Ref T1
Gamma |- t1 : Ref T11
--------------------- (T_Deref)
Gamma |- !t1 : T11
Gamma |- t1 : Ref T11
Gamma |- t2 : T11
------------------------ (T_Assign)
Gamma |- t1 := t2 : Unit
The rule for locations will require a bit more machinery, and this
will motivate some changes to the other rules; we'll come back to
this later. *)
(* ################################### *)
(** *** Values and Substitution *)
(** Besides abstractions and numbers, we have two new types of values:
the unit value, and locations. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_nat : forall n,
value (tnat n)
| v_unit :
value tunit
| v_loc : forall l,
value (tloc l).
Hint Constructors value.
(** Extending substitution to handle the new syntax of terms is
straightforward. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tabs x' T t1 =>
if eq_id_dec x x' then t else tabs x' T (subst x s t1)
| tnat n =>
t
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
t
| tref t1 =>
tref (subst x s t1)
| tderef t1 =>
tderef (subst x s t1)
| tassign t1 t2 =>
tassign (subst x s t1) (subst x s t2)
| tloc _ =>
t
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** * Pragmatics *)
(* ################################### *)
(** ** Side Effects and Sequencing *)
(** The fact that the result of an assignment expression is the
trivial value [unit] allows us to use a nice abbreviation for
_sequencing_. For example, we can write
<<
r:=succ(!r); !r
>>
as an abbreviation for
<<
(\x:Unit. !r) (r := succ(!r)).
>>
This has the effect of evaluating two expressions in order and
returning the value of the second. Restricting the type of the first
expression to [Unit] helps the typechecker to catch some silly
errors by permitting us to throw away the first value only if it
is really guaranteed to be trivial.
Notice that, if the second expression is also an assignment, then
the type of the whole sequence will be [Unit], so we can validly
place it to the left of another [;] to build longer sequences of
assignments:
<<
r:=succ(!r); r:=succ(!r); r:=succ(!r); r:=succ(!r); !r
>>
*)
(** Formally, we introduce sequencing as a "derived form"
[tseq] that expands into an abstraction and an application. *)
Definition tseq t1 t2 :=
tapp (tabs (Id 0) TUnit t2) t1.
(* ################################### *)
(** ** References and Aliasing *)
(** It is important to bear in mind the difference between the
_reference_ that is bound to [r] and the _cell_ in the store that
is pointed to by this reference.
If we make a copy of [r], for example by binding its value to
another variable [s], what gets copied is only the _reference_,
not the contents of the cell itself.
For example, after evaluating
<<
let r = ref 5 in
let s = r in
s := 82;
(!r)+1
>>
the cell referenced by [r] will contain the value [82], while the
result of the whole expression will be [83]. The references [r]
and [s] are said to be _aliases_ for the same cell.
The possibility of aliasing can make programs with references
quite tricky to reason about. For example, the expression
<<
r := 5; r := !s
>>
assigns [5] to [r] and then immediately overwrites it with [s]'s
current value; this has exactly the same effect as the single
assignment
<<
r := !s
>>
_unless_ we happen to do it in a context where [r] and [s] are
aliases for the same cell! *)
(* ################################### *)
(** ** Shared State *)
(** Of course, aliasing is also a large part of what makes references
useful. In particular, it allows us to set up "implicit
communication channels" -- shared state -- between different parts
of a program. For example, suppose we define a reference cell and
two functions that manipulate its contents:
<<
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
...
>>
*)
(** Note that, since their argument types are [Unit], the
abstractions in the definitions of [incc] and [decc] are not
providing any useful information to the bodies of the
functions (using the wildcard [_] as the name of the bound
variable is a reminder of this). Instead, their purpose is to
"slow down" the execution of the function bodies: since function
abstractions are values, the two [let]s are executed simply by
binding these functions to the names [incc] and [decc], rather
than by actually incrementing or decrementing [c]. Later, each
call to one of these functions results in its body being executed
once and performing the appropriate mutation on [c]. Such
functions are often called _thunks_.
In the context of these declarations, calling [incc] results in
changes to [c] that can be observed by calling [decc]. For
example, if we replace the [...] with [(incc unit; incc unit; decc
unit)], the result of the whole program will be [1]. *)
(** ** Objects *)
(** We can go a step further and write a _function_ that creates [c],
[incc], and [decc], packages [incc] and [decc] together into a
record, and returns this record:
<<
newcounter =
\_:Unit.
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
{i=incc, d=decc}
>>
*)
(** Now, each time we call [newcounter], we get a new record of
functions that share access to the same storage cell [c]. The
caller of [newcounter] can't get at this storage cell directly,
but can affect it indirectly by calling the two functions. In
other words, we've created a simple form of _object_.
<<
let c1 = newcounter unit in
let c2 = newcounter unit in
// Note that we've allocated two separate storage cells now!
let r1 = c1.i unit in
let r2 = c2.i unit in
r2 // yields 1, not 2!
>>
*)
(** **** Exercise: 1 star (store_draw) *)
(** Draw (on paper) the contents of the store at the point in
execution where the first two [let]s have finished and the third
one is about to begin. *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** References to Compound Types *)
(** A reference cell need not contain just a number: the primitives
we've defined above allow us to create references to values of any
type, including functions. For example, we can use references to
functions to give a (not very efficient) implementation of arrays
of numbers, as follows. Write [NatArray] for the type
[Ref (Nat->Nat)].
Recall the [equal] function from the [MoreStlc] chapter:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
Now, to build a new array, we allocate a reference cell and fill
it with a function that, when given an index, always returns [0].
<<
newarray = \_:Unit. ref (\n:Nat.0)
>>
To look up an element of an array, we simply apply
the function to the desired index.
<<
lookup = \a:NatArray. \n:Nat. (!a) n
>>
The interesting part of the encoding is the [update] function. It
takes an array, an index, and a new value to be stored at that index, and
does its job by creating (and storing in the reference) a new function
that, when it is asked for the value at this very index, returns the new
value that was given to [update], and on all other indices passes the
lookup to the function that was previously stored in the reference.
<<
update = \a:NatArray. \m:Nat. \v:Nat.
let oldf = !a in
a := (\n:Nat. if equal m n then v else oldf n);
>>
References to values containing other references can also be very
useful, allowing us to define data structures such as mutable
lists and trees. *)
(** **** Exercise: 2 stars (compact_update) *)
(** If we defined [update] more compactly like this
<<
update = \a:NatArray. \m:Nat. \v:Nat.
a := (\n:Nat. if equal m n then v else (!a) n)
>>
would it behave the same? *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** Null References *)
(** There is one more difference between our references and C-style
mutable variables: in C-like languages, variables holding pointers
into the heap may sometimes have the value [NULL]. Dereferencing
such a "null pointer" is an error, and results in an
exception (Java) or in termination of the program (C).
Null pointers cause significant trouble in C-like languages: the
fact that any pointer might be null means that any dereference
operation in the program can potentially fail. However, even in
ML-like languages, there are occasionally situations where we may
or may not have a valid pointer in our hands. Fortunately, there
is no need to extend the basic mechanisms of references to achieve
this: the sum types introduced in the [MoreStlc] chapter already
give us what we need.
First, we can use sums to build an analog of the [option] types
introduced in the [Lists] chapter. Define [Option T] to be an
abbreviation for [Unit + T].
Then a "nullable reference to a [T]" is simply an element of the
type [Option (Ref T)]. *)
(* ################################### *)
(** ** Garbage Collection *)
(** A last issue that we should mention before we move on with
formalizing references is storage _de_-allocation. We have not
provided any primitives for freeing reference cells when they are
no longer needed. Instead, like many modern languages (including
ML and Java) we rely on the run-time system to perform _garbage
collection_, collecting and reusing cells that can no longer be
reached by the program.
This is _not_ just a question of taste in language design: it is
extremely difficult to achieve type safety in the presence of an
explicit deallocation operation. The reason for this is the
familiar _dangling reference_ problem: we allocate a cell holding
a number, save a reference to it in some data structure, use it
for a while, then deallocate it and allocate a new cell holding a
boolean, possibly reusing the same storage. Now we can have two
names for the same storage cell -- one with type [Ref Nat] and the
other with type [Ref Bool]. *)
(** **** Exercise: 1 star (type_safety_violation) *)
(** Show how this can lead to a violation of type safety. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Operational Semantics *)
(* ################################### *)
(** ** Locations *)
(** The most subtle aspect of the treatment of references
appears when we consider how to formalize their operational
behavior. One way to see why is to ask, "What should be the
_values_ of type [Ref T]?" The crucial observation that we need
to take into account is that evaluating a [ref] operator should
_do_ something -- namely, allocate some storage -- and the result
of the operation should be a reference to this storage.
What, then, is a reference?
The run-time store in most programming language implementations is
essentially just a big array of bytes. The run-time system keeps track
of which parts of this array are currently in use; when we need to
allocate a new reference cell, we allocate a large enough segment from
the free region of the store (4 bytes for integer cells, 8 bytes for
cells storing [Float]s, etc.), mark it as being used, and return the
index (typically, a 32- or 64-bit integer) of the start of the newly
allocated region. These indices are references.
For present purposes, there is no need to be quite so concrete.
We can think of the store as an array of _values_, rather than an
array of bytes, abstracting away from the different sizes of the
run-time representations of different values. A reference, then,
is simply an index into the store. (If we like, we can even
abstract away from the fact that these indices are numbers, but
for purposes of formalization in Coq it is a bit more convenient
to use numbers.) We'll use the word _location_ instead of
_reference_ or _pointer_ from now on to emphasize this abstract
quality.
Treating locations abstractly in this way will prevent us from
modeling the _pointer arithmetic_ found in low-level languages
such as C. This limitation is intentional. While pointer
arithmetic is occasionally very useful, especially for
implementing low-level services such as garbage collectors, it
cannot be tracked by most type systems: knowing that location [n]
in the store contains a [float] doesn't tell us anything useful
about the type of location [n+4]. In C, pointer arithmetic is a
notorious source of type safety violations. *)
(* ################################### *)
(** ** Stores *)
(** Recall that, in the small-step operational semantics for
IMP, the step relation needed to carry along an auxiliary state in
addition to the program being executed. In the same way, once we
have added reference cells to the STLC, our step relation must
carry along a store to keep track of the contents of reference
cells.
We could re-use the same functional representation we used for
states in IMP, but for carrying out the proofs in this chapter it
is actually more convenient to represent a store simply as a
_list_ of values. (The reason we couldn't use this representation
before is that, in IMP, a program could modify any location at any
time, so states had to be ready to map _any_ variable to a value.
However, in the STLC with references, the only way to create a
reference cell is with [tref t1], which puts the value of [t1]
in a new reference cell and evaluates to the location of the newly
created reference cell. When evaluating such an expression, we can
just add a new reference cell to the end of the list representing
the store.) *)
Definition store := list tm.
(** We use [store_lookup n st] to retrieve the value of the reference
cell at location [n] in the store [st]. Note that we must give a
default value to [nth] in case we try looking up an index which is
too large. (In fact, we will never actually do this, but proving
it will of course require some work!) *)
Definition store_lookup (n:nat) (st:store) :=
nth n st tunit.
(** To add a new reference cell to the store, we use [snoc]. *)
Fixpoint snoc {A:Type} (l:list A) (x:A) : list A :=
match l with
| nil => x :: nil
| h :: t => h :: snoc t x
end.
(** We will need some boring lemmas about [snoc]. The proofs are
routine inductions. *)
Lemma length_snoc : forall A (l:list A) x,
length (snoc l x) = S (length l).
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ]. Qed.
(* The "solve by inversion" tactic is explained in Stlc.v. *)
Lemma nth_lt_snoc : forall A (l:list A) x d n,
n < length l ->
nth n l d = nth n (snoc l x) d.
Proof.
induction l as [|a l']; intros; try solve by inversion.
Case "l = a :: l'".
destruct n; auto.
simpl. apply IHl'.
simpl in H. apply lt_S_n in H. assumption.
Qed.
Lemma nth_eq_snoc : forall A (l:list A) x d,
nth (length l) (snoc l x) d = x.
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ].
Qed.
(** To update the store, we use the [replace] function, which replaces
the contents of a cell at a particular index. *)
Fixpoint replace {A:Type} (n:nat) (x:A) (l:list A) : list A :=
match l with
| nil => nil
| h :: t =>
match n with
| O => x :: t
| S n' => h :: replace n' x t
end
end.
(** Of course, we also need some boring lemmas about [replace], which
are also fairly straightforward to prove. *)
Lemma replace_nil : forall A n (x:A),
replace n x nil = nil.
Proof.
destruct n; auto.
Qed.
Lemma length_replace : forall A n x (l:list A),
length (replace n x l) = length l.
Proof with auto.
intros A n x l. generalize dependent n.
induction l; intros n.
destruct n...
destruct n...
simpl. rewrite IHl...
Qed.
Lemma lookup_replace_eq : forall l t st,
l < length st ->
store_lookup l (replace l t st) = t.
Proof with auto.
intros l t st.
unfold store_lookup.
generalize dependent l.
induction st as [|t' st']; intros l Hlen.
Case "st = []".
inversion Hlen.
Case "st = t' :: st'".
destruct l; simpl...
apply IHst'. simpl in Hlen. omega.
Qed.
Lemma lookup_replace_neq : forall l1 l2 t st,
l1 <> l2 ->
store_lookup l1 (replace l2 t st) = store_lookup l1 st.
Proof with auto.
unfold store_lookup.
induction l1 as [|l1']; intros l2 t st Hneq.
Case "l1 = 0".
destruct st.
SCase "st = []". rewrite replace_nil...
SCase "st = _ :: _". destruct l2... contradict Hneq...
Case "l1 = S l1'".
destruct st as [|t2 st2].
SCase "st = []". destruct l2...
SCase "st = t2 :: st2".
destruct l2...
simpl; apply IHl1'...
Qed.
(* ################################### *)
(** ** Reduction *)
(** Next, we need to extend our operational semantics to take stores
into account. Since the result of evaluating an expression will
in general depend on the contents of the store in which it is
evaluated, the evaluation rules should take not just a term but
also a store as argument. Furthermore, since the evaluation of a
term may cause side effects on the store that may affect the
evaluation of other terms in the future, the evaluation rules need
to return a new store. Thus, the shape of the single-step
evaluation relation changes from [t ==> t'] to [t / st ==> t' /
st'], where [st] and [st'] are the starting and ending states of
the store.
To carry through this change, we first need to augment all of our
existing evaluation rules with stores:
value v2
-------------------------------------- (ST_AppAbs)
(\x:T.t12) v2 / st ==> [x:=v2]t12 / st
t1 / st ==> t1' / st'
--------------------------- (ST_App1)
t1 t2 / st ==> t1' t2 / st'
value v1 t2 / st ==> t2' / st'
---------------------------------- (ST_App2)
v1 t2 / st ==> v1 t2' / st'
Note that the first rule here returns the store unchanged:
function application, in itself, has no side effects. The other two
rules simply propagate side effects from premise to conclusion.
Now, the result of evaluating a [ref] expression will be a fresh
location; this is why we included locations in the syntax of terms
and in the set of values.
It is crucial to note that making this extension to the syntax of
terms does not mean that we intend _programmers_ to write terms
involving explicit, concrete locations: such terms will arise only
as intermediate results of evaluation. This may initially seem
odd, but really it follows naturally from our design decision to
represent the result of every evaluation step by a modified
term. If we had chosen a more "machine-like" model for evaluation,
e.g. with an explicit stack to contain values of bound
identifiers, then the idea of adding locations to the set of
allowed values would probably seem more obvious.
In terms of this expanded syntax, we can state evaluation rules for
the new constructs that manipulate locations and the store. First, to
evaluate a dereferencing expression [!t1], we must first reduce [t1]
until it becomes a value:
t1 / st ==> t1' / st'
----------------------- (ST_Deref)
!t1 / st ==> !t1' / st'
Once [t1] has finished reducing, we should have an expression of
the form [!l], where [l] is some location. (A term that attempts
to dereference any other sort of value, such as a function or
[unit], is erroneous, as is a term that tries to derefence a
location that is larger than the size [|st|] of the currently
allocated store; the evaluation rules simply get stuck in this
case. The type safety properties that we'll establish below
assure us that well-typed terms will never misbehave in this way.)
l < |st|
---------------------------------- (ST_DerefLoc)
!(loc l) / st ==> lookup l st / st
Next, to evaluate an assignment expression [t1:=t2], we must first
evaluate [t1] until it becomes a value (a location), and then
evaluate [t2] until it becomes a value (of any sort):
t1 / st ==> t1' / st'
----------------------------------- (ST_Assign1)
t1 := t2 / st ==> t1' := t2 / st'
t2 / st ==> t2' / st'
--------------------------------- (ST_Assign2)
v1 := t2 / st ==> v1 := t2' / st'
Once we have finished with [t1] and [t2], we have an expression of
the form [l:=v2], which we execute by updating the store to make
location [l] contain [v2]:
l < |st|
------------------------------------- (ST_Assign)
loc l := v2 / st ==> unit / [l:=v2]st
The notation [[l:=v2]st] means "the store that maps [l] to [v2]
and maps all other locations to the same thing as [st.]" Note
that the term resulting from this evaluation step is just [unit];
the interesting result is the updated store.)
Finally, to evaluate an expression of the form [ref t1], we first
evaluate [t1] until it becomes a value:
t1 / st ==> t1' / st'
----------------------------- (ST_Ref)
ref t1 / st ==> ref t1' / st'
Then, to evaluate the [ref] itself, we choose a fresh location at
the end of the current store -- i.e., location [|st|] -- and yield
a new store that extends [st] with the new value [v1].
-------------------------------- (ST_RefValue)
ref v1 / st ==> loc |st| / st,v1
The value resulting from this step is the newly allocated location
itself. (Formally, [st,v1] means [snoc st v1].)
Note that these evaluation rules do not perform any kind of
garbage collection: we simply allow the store to keep growing
without bound as evaluation proceeds. This does not affect the
correctness of the results of evaluation (after all, the
definition of "garbage" is precisely parts of the store that are
no longer reachable and so cannot play any further role in
evaluation), but it means that a naive implementation of our
evaluator might sometimes run out of memory where a more
sophisticated evaluator would be able to continue by reusing
locations whose contents have become garbage.
Formally... *)
Reserved Notation "t1 '/' st1 '==>' t2 '/' st2"
(at level 40, st1 at level 39, t2 at level 39).
Inductive step : tm * store -> tm * store -> Prop :=
| ST_AppAbs : forall x T t12 v2 st,
value v2 ->
tapp (tabs x T t12) v2 / st ==> [x:=v2]t12 / st
| ST_App1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tapp t1 t2 / st ==> tapp t1' t2 / st'
| ST_App2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tapp v1 t2 / st ==> tapp v1 t2'/ st'
| ST_SuccNat : forall n st,
tsucc (tnat n) / st ==> tnat (S n) / st
| ST_Succ : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tsucc t1 / st ==> tsucc t1' / st'
| ST_PredNat : forall n st,
tpred (tnat n) / st ==> tnat (pred n) / st
| ST_Pred : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tpred t1 / st ==> tpred t1' / st'
| ST_MultNats : forall n1 n2 st,
tmult (tnat n1) (tnat n2) / st ==> tnat (mult n1 n2) / st
| ST_Mult1 : forall t1 t2 t1' st st',
t1 / st ==> t1' / st' ->
tmult t1 t2 / st ==> tmult t1' t2 / st'
| ST_Mult2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tmult v1 t2 / st ==> tmult v1 t2' / st'
| ST_If0 : forall t1 t1' t2 t3 st st',
t1 / st ==> t1' / st' ->
tif0 t1 t2 t3 / st ==> tif0 t1' t2 t3 / st'
| ST_If0_Zero : forall t2 t3 st,
tif0 (tnat 0) t2 t3 / st ==> t2 / st
| ST_If0_Nonzero : forall n t2 t3 st,
tif0 (tnat (S n)) t2 t3 / st ==> t3 / st
| ST_RefValue : forall v1 st,
value v1 ->
tref v1 / st ==> tloc (length st) / snoc st v1
| ST_Ref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tref t1 / st ==> tref t1' / st'
| ST_DerefLoc : forall st l,
l < length st ->
tderef (tloc l) / st ==> store_lookup l st / st
| ST_Deref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tderef t1 / st ==> tderef t1' / st'
| ST_Assign : forall v2 l st,
value v2 ->
l < length st ->
tassign (tloc l) v2 / st ==> tunit / replace l v2 st
| ST_Assign1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tassign t1 t2 / st ==> tassign t1' t2 / st'
| ST_Assign2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tassign v1 t2 / st ==> tassign v1 t2' / st'
where "t1 '/' st1 '==>' t2 '/' st2" := (step (t1,st1) (t2,st2)).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_SuccNat"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Pred" | Case_aux c "ST_MultNats"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_If0" | Case_aux c "ST_If0_Zero"
| Case_aux c "ST_If0_Nonzero" | Case_aux c "ST_RefValue"
| Case_aux c "ST_Ref" | Case_aux c "ST_DerefLoc"
| Case_aux c "ST_Deref" | Case_aux c "ST_Assign"
| Case_aux c "ST_Assign1" | Case_aux c "ST_Assign2" ].
Hint Constructors step.
Definition multistep := (multi step).
Notation "t1 '/' st '==>*' t2 '/' st'" := (multistep (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(* ################################### *)
(** * Typing *)
(** Our contexts for free variables will be exactly the same as for
the STLC, partial maps from identifiers to types. *)
Definition context := partial_map ty.
(* ################################### *)
(** ** Store typings *)
(** Having extended our syntax and evaluation rules to accommodate
references, our last job is to write down typing rules for the new
constructs -- and, of course, to check that they are sound.
Naturally, the key question is, "What is the type of a location?"
First of all, notice that we do _not_ need to answer this question
for purposes of typechecking the terms that programmers actually
write. Concrete location constants arise only in terms that are
the intermediate results of evaluation; they are not in the
language that programmers write. So we only need to determine the
type of a location when we're in the middle of an evaluation
sequence, e.g. trying to apply the progress or preservation
lemmas. Thus, even though we normally think of typing as a
_static_ program property, it makes sense for the typing of
locations to depend on the _dynamic_ progress of the program too.
As a first try, note that when we evaluate a term containing
concrete locations, the type of the result depends on the contents
of the store that we start with. For example, if we evaluate the
term [!(loc 1)] in the store [[unit, unit]], the result is [unit];
if we evaluate the same term in the store [[unit, \x:Unit.x]], the
result is [\x:Unit.x]. With respect to the former store, the
location [1] has type [Unit], and with respect to the latter it
has type [Unit->Unit]. This observation leads us immediately to a
first attempt at a typing rule for locations:
Gamma |- lookup l st : T1
----------------------------
Gamma |- loc l : Ref T1
That is, to find the type of a location [l], we look up the
current contents of [l] in the store and calculate the type [T1]
of the contents. The type of the location is then [Ref T1].
Having begun in this way, we need to go a little further to reach a
consistent state. In effect, by making the type of a term depend on
the store, we have changed the typing relation from a three-place
relation (between contexts, terms, and types) to a four-place relation
(between contexts, _stores_, terms, and types). Since the store is,
intuitively, part of the context in which we calculate the type of a
term, let's write this four-place relation with the store to the left
of the turnstile: [Gamma; st |- t : T]. Our rule for typing
references now has the form
Gamma; st |- lookup l st : T1
--------------------------------
Gamma; st |- loc l : Ref T1
and all the rest of the typing rules in the system are extended
similarly with stores. The other rules do not need to do anything
interesting with their stores -- just pass them from premise to
conclusion.
However, there are two problems with this rule. First, typechecking
is rather inefficient, since calculating the type of a location [l]
involves calculating the type of the current contents [v] of [l]. If
[l] appears many times in a term [t], we will re-calculate the type of
[v] many times in the course of constructing a typing derivation for
[t]. Worse, if [v] itself contains locations, then we will have to
recalculate _their_ types each time they appear.
Second, the proposed typing rule for locations may not allow us to
derive anything at all, if the store contains a _cycle_. For example,
there is no finite typing derivation for the location [0] with respect
to this store:
<<
[\x:Nat. (!(loc 1)) x, \x:Nat. (!(loc 0)) x]
>>
*)
(** **** Exercise: 2 stars (cyclic_store) *)
(** Can you find a term whose evaluation will create this particular
cyclic store? *)
(** [] *)
(** Both of these problems arise from the fact that our proposed
typing rule for locations requires us to recalculate the type of a
location every time we mention it in a term. But this,
intuitively, should not be necessary. After all, when a location
is first created, we know the type of the initial value that we
are storing into it. Suppose we are willing to enforce the
invariant that the type of the value contained in a given location
_never changes_; that is, although we may later store other values
into this location, those other values will always have the same
type as the initial one. In other words, we always have in mind a
single, definite type for every location in the store, which is
fixed when the location is allocated. Then these intended types
can be collected together as a _store typing_ ---a finite function
mapping locations to types.
As usual, this _conservative_ typing restriction on allowed
updates means that we will rule out as ill-typed some programs
that could evaluate perfectly well without getting stuck.
*)
(** Just like we did for stores, we will represent a store type simply
as a list of types: the type at index [i] records the type of the
value stored in cell [i]. *)
Definition store_ty := list ty.
(** The [store_Tlookup] function retrieves the type at a particular
index. *)
Definition store_Tlookup (n:nat) (ST:store_ty) :=
nth n ST TUnit.
(** Suppose we are _given_ a store typing [ST] describing the store
[st] in which some term [t] will be evaluated. Then we can use
[ST] to calculate the type of the result of [t] without ever
looking directly at [st]. For example, if [ST] is [[Unit,
Unit->Unit]], then we may immediately infer that [!(loc 1)] has
type [Unit->Unit]. More generally, the typing rule for locations
can be reformulated in terms of store typings like this:
l < |ST|
-------------------------------------
Gamma; ST |- loc l : Ref (lookup l ST)
That is, as long as [l] is a valid location (it is less than the
length of [ST]), we can compute the type of [l] just by looking it
up in [ST]. Typing is again a four-place relation, but it is
parameterized on a store _typing_ rather than a concrete store.
The rest of the typing rules are analogously augmented with store
typings. *)
(* ################################### *)
(** ** The Typing Relation *)
(** We can now give the typing relation for the STLC with
references. Here, again, are the rules we're adding to the base
STLC (with numbers and [Unit]): *)
(**
l < |ST|
-------------------------------------- (T_Loc)
Gamma; ST |- loc l : Ref (lookup l ST)
Gamma; ST |- t1 : T1
---------------------------- (T_Ref)
Gamma; ST |- ref t1 : Ref T1
Gamma; ST |- t1 : Ref T11
------------------------- (T_Deref)
Gamma; ST |- !t1 : T11
Gamma; ST |- t1 : Ref T11
Gamma; ST |- t2 : T11
----------------------------- (T_Assign)
Gamma; ST |- t1 := t2 : Unit
*)
Reserved Notation "Gamma ';' ST '|-' t '\in' T" (at level 40).
Inductive has_type : context -> store_ty -> tm -> ty -> Prop :=
| T_Var : forall Gamma ST x T,
Gamma x = Some T ->
Gamma; ST |- (tvar x) \in T
| T_Abs : forall Gamma ST x T11 T12 t12,
(extend Gamma x T11); ST |- t12 \in T12 ->
Gamma; ST |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma ST t1 t2,
Gamma; ST |- t1 \in (TArrow T1 T2) ->
Gamma; ST |- t2 \in T1 ->
Gamma; ST |- (tapp t1 t2) \in T2
| T_Nat : forall Gamma ST n,
Gamma; ST |- (tnat n) \in TNat
| T_Succ : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tsucc t1) \in TNat
| T_Pred : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tpred t1) \in TNat
| T_Mult : forall Gamma ST t1 t2,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in TNat ->
Gamma; ST |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma ST t1 t2 t3 T,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in T ->
Gamma; ST |- t3 \in T ->
Gamma; ST |- (tif0 t1 t2 t3) \in T
| T_Unit : forall Gamma ST,
Gamma; ST |- tunit \in TUnit
| T_Loc : forall Gamma ST l,
l < length ST ->
Gamma; ST |- (tloc l) \in (TRef (store_Tlookup l ST))
| T_Ref : forall Gamma ST t1 T1,
Gamma; ST |- t1 \in T1 ->
Gamma; ST |- (tref t1) \in (TRef T1)
| T_Deref : forall Gamma ST t1 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- (tderef t1) \in T11
| T_Assign : forall Gamma ST t1 t2 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- t2 \in T11 ->
Gamma; ST |- (tassign t1 t2) \in TUnit
where "Gamma ';' ST '|-' t '\in' T" := (has_type Gamma ST t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Unit" | Case_aux c "T_Loc"
| Case_aux c "T_Ref" | Case_aux c "T_Deref"
| Case_aux c "T_Assign" ].
(** Of course, these typing rules will accurately predict the results
of evaluation only if the concrete store used during evaluation
actually conforms to the store typing that we assume for purposes
of typechecking. This proviso exactly parallels the situation
with free variables in the STLC: the substitution lemma promises
us that, if [Gamma |- t : T], then we can replace the free
variables in [t] with values of the types listed in [Gamma] to
obtain a closed term of type [T], which, by the type preservation
theorem will evaluate to a final result of type [T] if it yields
any result at all. (We will see later how to formalize an
analogous intuition for stores and store typings.)
However, for purposes of typechecking the terms that programmers
actually write, we do not need to do anything tricky to guess what
store typing we should use. Recall that concrete location
constants arise only in terms that are the intermediate results of
evaluation; they are not in the language that programmers write.
Thus, we can simply typecheck the programmer's terms with respect
to the _empty_ store typing. As evaluation proceeds and new
locations are created, we will always be able to see how to extend
the store typing by looking at the type of the initial values
being placed in newly allocated cells; this intuition is
formalized in the statement of the type preservation theorem
below. *)
(* ################################### *)
(** * Properties *)
(** Our final task is to check that standard type safety properties
continue to hold for the STLC with references. The progress
theorem ("well-typed terms are not stuck") can be stated and
proved almost as for the STLC; we just need to add a few
straightforward cases to the proof, dealing with the new
constructs. The preservation theorem is a bit more interesting,
so let's look at it first. *)
(* ################################### *)
(** ** Well-Typed Stores *)
(** Since we have extended both the evaluation relation (with initial
and final stores) and the typing relation (with a store typing),
we need to change the statement of preservation to include these
parameters. Clearly, though, we cannot just add stores and store
typings without saying anything about how they are related: *)
Theorem preservation_wrong1 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
empty; ST |- t' \in T.
Abort.
(** If we typecheck with respect to some set of assumptions about the
types of the values in the store and then evaluate with respect to
a store that violates these assumptions, the result will be
disaster. We say that a store [st] is _well typed_ with respect a
store typing [ST] if the term at each location [l] in [st] has the
type at location [l] in [ST]. Since only closed terms ever get
stored in locations (why?), it suffices to type them in the empty
context. The following definition of [store_well_typed] formalizes
this. *)
Definition store_well_typed (ST:store_ty) (st:store) :=
length ST = length st /\
(forall l, l < length st ->
empty; ST |- (store_lookup l st) \in (store_Tlookup l ST)).
(** Informally, we will write [ST |- st] for [store_well_typed ST st]. *)
(** Intuitively, a store [st] is consistent with a store typing
[ST] if every value in the store has the type predicted by the
store typing. (The only subtle point is the fact that, when
typing the values in the store, we supply the very same store
typing to the typing relation! This allows us to type circular
stores.) *)
(** **** Exercise: 2 stars (store_not_unique) *)
(** Can you find a store [st], and two
different store typings [ST1] and [ST2] such that both
[ST1 |- st] and [ST2 |- st]? *)
(* FILL IN HERE *)
(** [] *)
(** We can now state something closer to the desired preservation
property: *)
Theorem preservation_wrong2 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
store_well_typed ST st ->
empty; ST |- t' \in T.
Abort.
(** This statement is fine for all of the evaluation rules except the
allocation rule [ST_RefValue]. The problem is that this rule
yields a store with a larger domain than the initial store, which
falsifies the conclusion of the above statement: if [st']
includes a binding for a fresh location [l], then [l] cannot be in
the domain of [ST], and it will not be the case that [t']
(which definitely mentions [l]) is typable under [ST]. *)
(* ############################################ *)
(** ** Extending Store Typings *)
(** Evidently, since the store can increase in size during evaluation,
we need to allow the store typing to grow as well. This motivates
the following definition. We say that the store type [ST']
_extends_ [ST] if [ST'] is just [ST] with some new types added to
the end. *)
Inductive extends : store_ty -> store_ty -> Prop :=
| extends_nil : forall ST',
extends ST' nil
| extends_cons : forall x ST' ST,
extends ST' ST ->
extends (x::ST') (x::ST).
Hint Constructors extends.
(** We'll need a few technical lemmas about extended contexts.
First, looking up a type in an extended store typing yields the
same result as in the original: *)
Lemma extends_lookup : forall l ST ST',
l < length ST ->
extends ST' ST ->
store_Tlookup l ST' = store_Tlookup l ST.
Proof with auto.
intros l ST ST' Hlen H.
generalize dependent ST'. generalize dependent l.
induction ST as [|a ST2]; intros l Hlen ST' HST'.
Case "nil". inversion Hlen.
Case "cons". unfold store_Tlookup in *.
destruct ST'.
SCase "ST' = nil". inversion HST'.
SCase "ST' = a' :: ST'2".
inversion HST'; subst.
destruct l as [|l'].
SSCase "l = 0"...
SSCase "l = S l'". simpl. apply IHST2...
simpl in Hlen; omega.
Qed.
(** Next, if [ST'] extends [ST], the length of [ST'] is at least that
of [ST]. *)
Lemma length_extends : forall l ST ST',
l < length ST ->
extends ST' ST ->
l < length ST'.
Proof with eauto.
intros. generalize dependent l. induction H0; intros l Hlen.
inversion Hlen.
simpl in *.
destruct l; try omega.
apply lt_n_S. apply IHextends. omega.
Qed.
(** Finally, [snoc ST T] extends [ST], and [extends] is reflexive. *)
Lemma extends_snoc : forall ST T,
extends (snoc ST T) ST.
Proof with auto.
induction ST; intros T...
simpl...
Qed.
Lemma extends_refl : forall ST,
extends ST ST.
Proof.
induction ST; auto.
Qed.
(* ################################### *)
(** ** Preservation, Finally *)
(** We can now give the final, correct statement of the type
preservation property: *)
Definition preservation_theorem := forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
(** Note that the preservation theorem merely asserts that there is
_some_ store typing [ST'] extending [ST] (i.e., agreeing with [ST]
on the values of all the old locations) such that the new term
[t'] is well typed with respect to [ST']; it does not tell us
exactly what [ST'] is. It is intuitively clear, of course, that
[ST'] is either [ST] or else it is exactly [snoc ST T1], where
[T1] is the type of the value [v1] in the extended store [snoc st
v1], but stating this explicitly would complicate the statement of
the theorem without actually making it any more useful: the weaker
version above is already in the right form (because its conclusion
implies its hypothesis) to "turn the crank" repeatedly and
conclude that every _sequence_ of evaluation steps preserves
well-typedness. Combining this with the progress property, we
obtain the usual guarantee that "well-typed programs never go
wrong."
In order to prove this, we'll need a few lemmas, as usual. *)
(* ################################### *)
(** ** Substitution lemma *)
(** First, we need an easy extension of the standard substitution
lemma, along with the same machinery about context invariance that
we used in the proof of the substitution lemma for the STLC. *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_succ : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tsucc t1)
| afi_pred : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tpred t1)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if0_1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_ref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tref t1)
| afi_deref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tderef t1)
| afi_assign1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tassign t1 t2)
| afi_assign2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tassign t1 t2).
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_succ" | Case_aux c "afi_pred"
| Case_aux c "afi_mult1" | Case_aux c "afi_mult2"
| Case_aux c "afi_if0_1" | Case_aux c "afi_if0_2" | Case_aux c "afi_if0_3"
| Case_aux c "afi_ref" | Case_aux c "afi_deref"
| Case_aux c "afi_assign1" | Case_aux c "afi_assign2" ].
Hint Constructors appears_free_in.
Lemma free_in_context : forall x t T Gamma ST,
appears_free_in x t ->
Gamma; ST |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros. generalize dependent Gamma. generalize dependent T.
afi_cases (induction H) Case;
intros; (try solve [ inversion H0; subst; eauto ]).
Case "afi_abs".
inversion H1; subst.
apply IHappears_free_in in H8.
rewrite extend_neq in H8; assumption.
Qed.
Lemma context_invariance : forall Gamma Gamma' ST t T,
Gamma; ST |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma'; ST |- t \in T.
Proof with eauto.
intros.
generalize dependent Gamma'.
has_type_cases (induction H) Case; intros...
Case "T_Var".
apply T_Var. symmetry. rewrite <- H...
Case "T_Abs".
apply T_Abs. apply IHhas_type; intros.
unfold extend.
destruct (eq_id_dec x x0)...
Case "T_App".
eapply T_App.
apply IHhas_type1...
apply IHhas_type2...
Case "T_Mult".
eapply T_Mult.
apply IHhas_type1...
apply IHhas_type2...
Case "T_If0".
eapply T_If0.
apply IHhas_type1...
apply IHhas_type2...
apply IHhas_type3...
Case "T_Assign".
eapply T_Assign.
apply IHhas_type1...
apply IHhas_type2...
Qed.
Lemma substitution_preserves_typing : forall Gamma ST x s S t T,
empty; ST |- s \in S ->
(extend Gamma x S); ST |- t \in T ->
Gamma; ST |- ([x:=s]t) \in T.
Proof with eauto.
intros Gamma ST x s S t T Hs Ht.
generalize dependent Gamma. generalize dependent T.
t_cases (induction t) Case; intros T Gamma 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 H3.
inversion H3; subst.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ _ _ _ Hcontra Hs) as [T' HT'].
inversion HT'.
SCase "x <> y".
apply T_Var.
rewrite extend_neq in H3...
Case "tabs". subst.
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
apply T_Abs. eapply context_invariance...
intros. apply extend_shadow.
SCase "x <> x0".
apply T_Abs. apply IHt.
eapply context_invariance...
intros. unfold extend.
destruct (eq_id_dec y x0)...
subst.
rewrite neq_id...
Qed.
(* ################################### *)
(** ** Assignment Preserves Store Typing *)
(** Next, we must show that replacing the contents of a cell in the
store with a new value of appropriate type does not change the
overall type of the store. (This is needed for the [ST_Assign]
rule.) *)
Lemma assign_pres_store_typing : forall ST st l t,
l < length st ->
store_well_typed ST st ->
empty; ST |- t \in (store_Tlookup l ST) ->
store_well_typed ST (replace l t st).
Proof with auto.
intros ST st l t Hlen HST Ht.
inversion HST; subst.
split. rewrite length_replace...
intros l' Hl'.
destruct (beq_nat l' l) eqn: Heqll'.
Case "l' = l".
apply beq_nat_true in Heqll'; subst.
rewrite lookup_replace_eq...
Case "l' <> l".
apply beq_nat_false in Heqll'.
rewrite lookup_replace_neq...
rewrite length_replace in Hl'.
apply H0...
Qed.
(* ######################################## *)
(** ** Weakening for Stores *)
(** Finally, we need a lemma on store typings, stating that, if a
store typing is extended with a new location, the extended one
still allows us to assign the same types to the same terms as the
original.
(The lemma is called [store_weakening] because it resembles the
"weakening" lemmas found in proof theory, which show that adding a
new assumption to some logical theory does not decrease the set of
provable theorems.) *)
Lemma store_weakening : forall Gamma ST ST' t T,
extends ST' ST ->
Gamma; ST |- t \in T ->
Gamma; ST' |- t \in T.
Proof with eauto.
intros. has_type_cases (induction H0) Case; eauto.
Case "T_Loc".
erewrite <- extends_lookup...
apply T_Loc.
eapply length_extends...
Qed.
(** We can use the [store_weakening] lemma to prove that if a store is
well typed with respect to a store typing, then the store extended
with a new term [t] will still be well typed with respect to the
store typing extended with [t]'s type. *)
Lemma store_well_typed_snoc : forall ST st t1 T1,
store_well_typed ST st ->
empty; ST |- t1 \in T1 ->
store_well_typed (snoc ST T1) (snoc st t1).
Proof with auto.
intros.
unfold store_well_typed in *.
inversion H as [Hlen Hmatch]; clear H.
rewrite !length_snoc.
split...
Case "types match.".
intros l Hl.
unfold store_lookup, store_Tlookup.
apply le_lt_eq_dec in Hl; inversion Hl as [Hlt | Heq].
SCase "l < length st".
apply lt_S_n in Hlt.
rewrite <- !nth_lt_snoc...
apply store_weakening with ST. apply extends_snoc.
apply Hmatch...
rewrite Hlen...
SCase "l = length st".
inversion Heq.
rewrite nth_eq_snoc.
rewrite <- Hlen. rewrite nth_eq_snoc...
apply store_weakening with ST... apply extends_snoc.
Qed.
(* ################################### *)
(** ** Preservation! *)
(** Now that we've got everything set up right, the proof of
preservation is actually quite straightforward. *)
Theorem preservation : forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
Proof with eauto using store_weakening, extends_refl.
remember (@empty ty) as Gamma.
intros ST t t' T st st' Ht.
generalize dependent t'.
has_type_cases (induction Ht) Case; intros t' HST Hstep;
subst; try (solve by inversion); inversion Hstep; subst;
try (eauto using store_weakening, extends_refl).
Case "T_App".
SCase "ST_AppAbs". exists ST.
inversion Ht1; subst.
split; try split... eapply substitution_preserves_typing...
SCase "ST_App1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_App2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Succ".
SCase "ST_Succ".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Pred".
SCase "ST_Pred".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Mult".
SCase "ST_Mult1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Mult2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_If0".
SCase "ST_If0_1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'... split...
Case "T_Ref".
SCase "ST_RefValue".
exists (snoc ST T1).
inversion HST; subst.
split.
apply extends_snoc.
split.
replace (TRef T1)
with (TRef (store_Tlookup (length st) (snoc ST T1))).
apply T_Loc.
rewrite <- H. rewrite length_snoc. omega.
unfold store_Tlookup. rewrite <- H. rewrite nth_eq_snoc...
apply store_well_typed_snoc; assumption.
SCase "ST_Ref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Deref".
SCase "ST_DerefLoc".
exists ST. split; try split...
inversion HST as [_ Hsty].
replace T11 with (store_Tlookup l ST).
apply Hsty...
inversion Ht; subst...
SCase "ST_Deref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Assign".
SCase "ST_Assign".
exists ST. split; try split...
eapply assign_pres_store_typing...
inversion Ht1; subst...
SCase "ST_Assign1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Assign2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Qed.
(** **** Exercise: 3 stars (preservation_informal) *)
(** Write a careful informal proof of the preservation theorem,
concentrating on the [T_App], [T_Deref], [T_Assign], and [T_Ref]
cases.
(* FILL IN HERE *)
[] *)
(* ################################### *)
(** ** Progress *)
(** Fortunately, progress for this system is pretty easy to prove; the
proof is very similar to the proof of progress for the STLC, with
a few new cases for the new syntactic constructs. *)
Theorem progress : forall ST t T st,
empty; ST |- t \in T ->
store_well_typed ST st ->
(value t \/ exists t', exists st', t / st ==> t' / st').
Proof with eauto.
intros ST t T st Ht HST. remember (@empty ty) as Gamma.
has_type_cases (induction Ht) Case; subst; try solve by inversion...
Case "T_App".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tapp (tabs x T t) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tapp t1' t2). exists st'...
Case "T_Succ".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [ inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (S n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tsucc t1'). exists st'...
Case "T_Pred".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (pred n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tpred t1'). exists st'...
Case "T_Mult".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 is a value".
inversion Ht2p; subst; try solve [inversion Ht2].
exists (tnat (mult n n0)). exists st...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tmult (tnat n) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tmult t1' t2). exists st'...
Case "T_If0".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct n.
SSCase "n = 0". exists t2. exists st...
SSCase "n = S n'". exists t3. exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tif0 t1' t2 t3). exists st'...
Case "T_Ref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tref t1'). exists st'...
Case "T_Deref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_DerefLoc...
inversion Ht; subst. inversion HST; subst.
rewrite <- H...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tderef t1'). exists st'...
Case "T_Assign".
right. destruct IHHt1 as [Ht1p|Ht1p]...
SCase "t1 is a value".
destruct IHHt2 as [Ht2p|Ht2p]...
SSCase "t2 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_Assign...
inversion HST; subst. inversion Ht1; subst.
rewrite H in H5...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tassign t1 t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tassign t1' t2). exists st'...
Qed.
(* ################################### *)
(** * References and Nontermination *)
Section RefsAndNontermination.
Import ExampleVariables.
(** We know that the simply typed lambda calculus is _normalizing_,
that is, every well-typed term can be reduced to a value in a
finite number of steps. What about STLC + references?
Surprisingly, adding references causes us to lose the
normalization property: there exist well-typed terms in the STLC +
references which can continue to reduce forever, without ever
reaching a normal form!
How can we construct such a term? The main idea is to make a
function which calls itself. We first make a function which calls
another function stored in a reference cell; the trick is that we
then smuggle in a reference to itself!
<<
(\r:Ref (Unit -> Unit).
r := (\x:Unit.(!r) unit); (!r) unit)
(ref (\x:Unit.unit))
>>
First, [ref (\x:Unit.unit)] creates a reference to a cell of type
[Unit -> Unit]. We then pass this reference as the argument to a
function which binds it to the name [r], and assigns to it the
function (\x:Unit.(!r) unit) -- that is, the function which
ignores its argument and calls the function stored in [r] on the
argument [unit]; but of course, that function is itself! To get
the ball rolling we finally execute this function with [(!r)
unit].
*)
Definition loop_fun :=
tabs x TUnit (tapp (tderef (tvar r)) tunit).
Definition loop :=
tapp
(tabs r (TRef (TArrow TUnit TUnit))
(tseq (tassign (tvar r) loop_fun)
(tapp (tderef (tvar r)) tunit)))
(tref (tabs x TUnit tunit)).
(** This term is well typed: *)
Lemma loop_typeable : exists T, empty; nil |- loop \in T.
Proof with eauto.
eexists. unfold loop. unfold loop_fun.
eapply T_App...
eapply T_Abs...
eapply T_App...
eapply T_Abs. eapply T_App. eapply T_Deref. eapply T_Var.
unfold extend. simpl. reflexivity. auto.
eapply T_Assign.
eapply T_Var. unfold extend. simpl. reflexivity.
eapply T_Abs.
eapply T_App...
eapply T_Deref. eapply T_Var. reflexivity.
Qed.
(** To show formally that the term diverges, we first define the
[step_closure] of the single-step reduction relation, written
[==>+]. This is just like the reflexive step closure of
single-step reduction (which we're been writing [==>*]), except
that it is not reflexive: [t ==>+ t'] means that [t] can reach
[t'] by _one or more_ steps of reduction. *)
Inductive step_closure {X:Type} (R: relation X) : X -> X -> Prop :=
| sc_one : forall (x y : X),
R x y -> step_closure R x y
| sc_step : forall (x y z : X),
R x y ->
step_closure R y z ->
step_closure R x z.
Definition multistep1 := (step_closure step).
Notation "t1 '/' st '==>+' t2 '/' st'" := (multistep1 (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(** Now, we can show that the expression [loop] reduces to the
expression [!(loc 0) unit] and the size-one store [ [r:=(loc 0)]
loop_fun]. *)
(** As a convenience, we introduce a slight variant of the [normalize]
tactic, called [reduce], which tries solving the goal with
[multi_refl] at each step, instead of waiting until the goal can't
be reduced any more. Of course, the whole point is that [loop]
doesn't normalize, so the old [normalize] tactic would just go
into an infinite loop reducing it forever! *)
Ltac print_goal := match goal with |- ?x => idtac x end.
Ltac reduce :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; compute)];
try solve [apply multi_refl]).
Lemma loop_steps_to_loop_fun :
loop / nil ==>*
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop.
reduce.
Qed.
(** Finally, the latter expression reduces in two steps to itself! *)
Lemma loop_fun_step_self :
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil ==>+
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop_fun; simpl.
eapply sc_step. apply ST_App1...
eapply sc_one. compute. apply ST_AppAbs...
Qed.
(** **** Exercise: 4 stars (factorial_ref) *)
(** Use the above ideas to implement a factorial function in STLC with
references. (There is no need to prove formally that it really
behaves like the factorial. Just use the example below to make
sure it gives the correct result when applied to the argument
[4].) *)
Definition factorial : tm :=
(* FILL IN HERE *) admit.
Lemma factorial_type : empty; nil |- factorial \in (TArrow TNat TNat).
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** If your definition is correct, you should be able to just
uncomment the example below; the proof should be fully
automatic using the [reduce] tactic. *)
(*
Lemma factorial_4 : exists st,
tapp factorial (tnat 4) / nil ==>* tnat 24 / st.
Proof.
eexists. unfold factorial. reduce.
Qed.
*)
(** [] *)
(* ################################### *)
(** * Additional Exercises *)
(** **** Exercise: 5 stars, optional (garabage_collector) *)
(** Challenge problem: modify our formalization to include an account
of garbage collection, and prove that it satisfies whatever nice
properties you can think to prove about it. *)
(** [] *)
End RefsAndNontermination.
End STLCRef.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
(** * References: Typing Mutable References *)
Require Export Smallstep.
(** So far, we have considered a variety of _pure_ language features,
including functional abstraction, basic types such as numbers and
booleans, and structured types such as records and variants. These
features form the backbone of most programming languages -- including
purely functional languages such as Haskell, "mostly functional"
languages such as ML, imperative languages such as C, and
object-oriented languages such as Java.
Most practical programming languages also include various _impure_
features that cannot be described in the simple semantic framework
we have used so far. In particular, besides just yielding
results, evaluation of terms in these languages may assign to
mutable variables (reference cells, arrays, mutable record fields,
etc.), perform input and output to files, displays, or network
connections, make non-local transfers of control via exceptions,
jumps, or continuations, engage in inter-process synchronization
and communication, and so on. In the literature on programming
languages, such "side effects" of computation are more generally
referred to as _computational effects_.
In this chapter, we'll see how one sort of computational
effect -- mutable references -- can be added to the calculi we have
studied. The main extension will be dealing explicitly with a
_store_ (or _heap_). This extension is straightforward to define;
the most interesting part is the refinement we need to make to the
statement of the type preservation theorem. *)
(* ###################################################################### *)
(** * Definitions *)
(** Pretty much every programming language provides some form of
assignment operation that changes the contents of a previously
allocated piece of storage. (Coq's internal language is a rare
exception!)
In some languages -- notably ML and its relatives -- the
mechanisms for name-binding and those for assignment are kept
separate. We can have a variable [x] whose _value_ is the number
[5], or we can have a variable [y] whose value is a
_reference_ (or _pointer_) to a mutable cell whose current
contents is [5]. These are different things, and the difference
is visible to the programmer. We can add [x] to another number,
but not assign to it. We can use [y] directly to assign a new
value to the cell that it points to (by writing [y:=84]), but we
cannot use it directly as an argument to an operation like [+].
Instead, we must explicitly _dereference_ it, writing [!y] to
obtain its current contents.
In most other languages -- in particular, in all members of the C
family, including Java -- _every_ variable name refers to a mutable
cell, and the operation of dereferencing a variable to obtain its
current contents is implicit.
For purposes of formal study, it is useful to keep these
mechanisms separate. The development in this chapter will closely
follow ML's model. Applying the lessons learned here to C-like
languages is a straightforward matter of collapsing some
distinctions and rendering some operations such as dereferencing
implicit instead of explicit.
In this chapter, we study adding mutable references to the
simply-typed lambda calculus with natural numbers. *)
(* ###################################################################### *)
(** * Syntax *)
Module STLCRef.
(** The basic operations on references are _allocation_,
_dereferencing_, and _assignment_.
- To allocate a reference, we use the [ref] operator, providing
an initial value for the new cell. For example, [ref 5]
creates a new cell containing the value [5], and evaluates to
a reference to that cell.
- To read the current value of this cell, we use the
dereferencing operator [!]; for example, [!(ref 5)] evaluates
to [5].
- To change the value stored in a cell, we use the assignment
operator. If [r] is a reference, [r := 7] will store the
value [7] in the cell referenced by [r]. However, [r := 7]
evaluates to the trivial value [unit]; it exists only to have
the _side effect_ of modifying the contents of a cell. *)
(* ################################### *)
(** *** Types *)
(** We start with the simply typed lambda calculus over the
natural numbers. To the base natural number type and arrow types
we need to add two more types to deal with references. First, we
need the _unit type_, which we will use as the result type of an
assignment operation. We then add _reference types_. *)
(** If [T] is a type, then [Ref T] is the type of references which
point to a cell holding values of type [T].
T ::= Nat
| Unit
| T -> T
| Ref T
*)
Inductive ty : Type :=
| TNat : ty
| TUnit : ty
| TArrow : ty -> ty -> ty
| TRef : ty -> ty.
(* ################################### *)
(** *** Terms *)
(** Besides variables, abstractions, applications,
natural-number-related terms, and [unit], we need four more sorts
of terms in order to handle mutable references:
<<
t ::= ... Terms
| ref t allocation
| !t dereference
| t := t assignment
| l location
>>
*)
Inductive tm : Type :=
(* STLC with numbers: *)
| 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
(* New terms: *)
| tunit : tm
| tref : tm -> tm
| tderef : tm -> tm
| tassign : tm -> tm -> tm
| tloc : nat -> tm.
(** Intuitively...
- [ref t] (formally, [tref t]) allocates a new reference cell
with the value [t] and evaluates to the location of the newly
allocated cell;
- [!t] (formally, [tderef t]) evaluates to the contents of the
cell referenced by [t];
- [t1 := t2] (formally, [tassign t1 t2]) assigns [t2] to the
cell referenced by [t1]; and
- [l] (formally, [tloc l]) is a reference to the cell at
location [l]. We'll discuss locations later. *)
(** In informal examples, we'll also freely use the extensions
of the STLC developed in the [MoreStlc] chapter; however, to keep
the proofs small, we won't bother formalizing them again here. It
would be easy to do so, since there are no very interesting
interactions between those features and references. *)
Tactic Notation "t_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "tvar" | Case_aux c "tapp"
| Case_aux c "tabs" | Case_aux c "tzero"
| Case_aux c "tsucc" | Case_aux c "tpred"
| Case_aux c "tmult" | Case_aux c "tif0"
| Case_aux c "tunit" | Case_aux c "tref"
| Case_aux c "tderef" | Case_aux c "tassign"
| Case_aux c "tloc" ].
Module ExampleVariables.
Definition x := Id 0.
Definition y := Id 1.
Definition r := Id 2.
Definition s := Id 3.
End ExampleVariables.
(* ################################### *)
(** *** Typing (Preview) *)
(** Informally, the typing rules for allocation, dereferencing, and
assignment will look like this:
Gamma |- t1 : T1
------------------------ (T_Ref)
Gamma |- ref t1 : Ref T1
Gamma |- t1 : Ref T11
--------------------- (T_Deref)
Gamma |- !t1 : T11
Gamma |- t1 : Ref T11
Gamma |- t2 : T11
------------------------ (T_Assign)
Gamma |- t1 := t2 : Unit
The rule for locations will require a bit more machinery, and this
will motivate some changes to the other rules; we'll come back to
this later. *)
(* ################################### *)
(** *** Values and Substitution *)
(** Besides abstractions and numbers, we have two new types of values:
the unit value, and locations. *)
Inductive value : tm -> Prop :=
| v_abs : forall x T t,
value (tabs x T t)
| v_nat : forall n,
value (tnat n)
| v_unit :
value tunit
| v_loc : forall l,
value (tloc l).
Hint Constructors value.
(** Extending substitution to handle the new syntax of terms is
straightforward. *)
Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
match t with
| tvar x' =>
if eq_id_dec x x' then s else t
| tapp t1 t2 =>
tapp (subst x s t1) (subst x s t2)
| tabs x' T t1 =>
if eq_id_dec x x' then t else tabs x' T (subst x s t1)
| tnat n =>
t
| tsucc t1 =>
tsucc (subst x s t1)
| tpred t1 =>
tpred (subst x s t1)
| tmult t1 t2 =>
tmult (subst x s t1) (subst x s t2)
| tif0 t1 t2 t3 =>
tif0 (subst x s t1) (subst x s t2) (subst x s t3)
| tunit =>
t
| tref t1 =>
tref (subst x s t1)
| tderef t1 =>
tderef (subst x s t1)
| tassign t1 t2 =>
tassign (subst x s t1) (subst x s t2)
| tloc _ =>
t
end.
Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).
(* ###################################################################### *)
(** * Pragmatics *)
(* ################################### *)
(** ** Side Effects and Sequencing *)
(** The fact that the result of an assignment expression is the
trivial value [unit] allows us to use a nice abbreviation for
_sequencing_. For example, we can write
<<
r:=succ(!r); !r
>>
as an abbreviation for
<<
(\x:Unit. !r) (r := succ(!r)).
>>
This has the effect of evaluating two expressions in order and
returning the value of the second. Restricting the type of the first
expression to [Unit] helps the typechecker to catch some silly
errors by permitting us to throw away the first value only if it
is really guaranteed to be trivial.
Notice that, if the second expression is also an assignment, then
the type of the whole sequence will be [Unit], so we can validly
place it to the left of another [;] to build longer sequences of
assignments:
<<
r:=succ(!r); r:=succ(!r); r:=succ(!r); r:=succ(!r); !r
>>
*)
(** Formally, we introduce sequencing as a "derived form"
[tseq] that expands into an abstraction and an application. *)
Definition tseq t1 t2 :=
tapp (tabs (Id 0) TUnit t2) t1.
(* ################################### *)
(** ** References and Aliasing *)
(** It is important to bear in mind the difference between the
_reference_ that is bound to [r] and the _cell_ in the store that
is pointed to by this reference.
If we make a copy of [r], for example by binding its value to
another variable [s], what gets copied is only the _reference_,
not the contents of the cell itself.
For example, after evaluating
<<
let r = ref 5 in
let s = r in
s := 82;
(!r)+1
>>
the cell referenced by [r] will contain the value [82], while the
result of the whole expression will be [83]. The references [r]
and [s] are said to be _aliases_ for the same cell.
The possibility of aliasing can make programs with references
quite tricky to reason about. For example, the expression
<<
r := 5; r := !s
>>
assigns [5] to [r] and then immediately overwrites it with [s]'s
current value; this has exactly the same effect as the single
assignment
<<
r := !s
>>
_unless_ we happen to do it in a context where [r] and [s] are
aliases for the same cell! *)
(* ################################### *)
(** ** Shared State *)
(** Of course, aliasing is also a large part of what makes references
useful. In particular, it allows us to set up "implicit
communication channels" -- shared state -- between different parts
of a program. For example, suppose we define a reference cell and
two functions that manipulate its contents:
<<
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
...
>>
*)
(** Note that, since their argument types are [Unit], the
abstractions in the definitions of [incc] and [decc] are not
providing any useful information to the bodies of the
functions (using the wildcard [_] as the name of the bound
variable is a reminder of this). Instead, their purpose is to
"slow down" the execution of the function bodies: since function
abstractions are values, the two [let]s are executed simply by
binding these functions to the names [incc] and [decc], rather
than by actually incrementing or decrementing [c]. Later, each
call to one of these functions results in its body being executed
once and performing the appropriate mutation on [c]. Such
functions are often called _thunks_.
In the context of these declarations, calling [incc] results in
changes to [c] that can be observed by calling [decc]. For
example, if we replace the [...] with [(incc unit; incc unit; decc
unit)], the result of the whole program will be [1]. *)
(** ** Objects *)
(** We can go a step further and write a _function_ that creates [c],
[incc], and [decc], packages [incc] and [decc] together into a
record, and returns this record:
<<
newcounter =
\_:Unit.
let c = ref 0 in
let incc = \_:Unit. (c := succ (!c); !c) in
let decc = \_:Unit. (c := pred (!c); !c) in
{i=incc, d=decc}
>>
*)
(** Now, each time we call [newcounter], we get a new record of
functions that share access to the same storage cell [c]. The
caller of [newcounter] can't get at this storage cell directly,
but can affect it indirectly by calling the two functions. In
other words, we've created a simple form of _object_.
<<
let c1 = newcounter unit in
let c2 = newcounter unit in
// Note that we've allocated two separate storage cells now!
let r1 = c1.i unit in
let r2 = c2.i unit in
r2 // yields 1, not 2!
>>
*)
(** **** Exercise: 1 star (store_draw) *)
(** Draw (on paper) the contents of the store at the point in
execution where the first two [let]s have finished and the third
one is about to begin. *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** References to Compound Types *)
(** A reference cell need not contain just a number: the primitives
we've defined above allow us to create references to values of any
type, including functions. For example, we can use references to
functions to give a (not very efficient) implementation of arrays
of numbers, as follows. Write [NatArray] for the type
[Ref (Nat->Nat)].
Recall the [equal] function from the [MoreStlc] chapter:
<<
equal =
fix
(\eq:Nat->Nat->Bool.
\m:Nat. \n:Nat.
if m=0 then iszero n
else if n=0 then false
else eq (pred m) (pred n))
>>
Now, to build a new array, we allocate a reference cell and fill
it with a function that, when given an index, always returns [0].
<<
newarray = \_:Unit. ref (\n:Nat.0)
>>
To look up an element of an array, we simply apply
the function to the desired index.
<<
lookup = \a:NatArray. \n:Nat. (!a) n
>>
The interesting part of the encoding is the [update] function. It
takes an array, an index, and a new value to be stored at that index, and
does its job by creating (and storing in the reference) a new function
that, when it is asked for the value at this very index, returns the new
value that was given to [update], and on all other indices passes the
lookup to the function that was previously stored in the reference.
<<
update = \a:NatArray. \m:Nat. \v:Nat.
let oldf = !a in
a := (\n:Nat. if equal m n then v else oldf n);
>>
References to values containing other references can also be very
useful, allowing us to define data structures such as mutable
lists and trees. *)
(** **** Exercise: 2 stars (compact_update) *)
(** If we defined [update] more compactly like this
<<
update = \a:NatArray. \m:Nat. \v:Nat.
a := (\n:Nat. if equal m n then v else (!a) n)
>>
would it behave the same? *)
(* FILL IN HERE *)
(** [] *)
(* ################################### *)
(** ** Null References *)
(** There is one more difference between our references and C-style
mutable variables: in C-like languages, variables holding pointers
into the heap may sometimes have the value [NULL]. Dereferencing
such a "null pointer" is an error, and results in an
exception (Java) or in termination of the program (C).
Null pointers cause significant trouble in C-like languages: the
fact that any pointer might be null means that any dereference
operation in the program can potentially fail. However, even in
ML-like languages, there are occasionally situations where we may
or may not have a valid pointer in our hands. Fortunately, there
is no need to extend the basic mechanisms of references to achieve
this: the sum types introduced in the [MoreStlc] chapter already
give us what we need.
First, we can use sums to build an analog of the [option] types
introduced in the [Lists] chapter. Define [Option T] to be an
abbreviation for [Unit + T].
Then a "nullable reference to a [T]" is simply an element of the
type [Option (Ref T)]. *)
(* ################################### *)
(** ** Garbage Collection *)
(** A last issue that we should mention before we move on with
formalizing references is storage _de_-allocation. We have not
provided any primitives for freeing reference cells when they are
no longer needed. Instead, like many modern languages (including
ML and Java) we rely on the run-time system to perform _garbage
collection_, collecting and reusing cells that can no longer be
reached by the program.
This is _not_ just a question of taste in language design: it is
extremely difficult to achieve type safety in the presence of an
explicit deallocation operation. The reason for this is the
familiar _dangling reference_ problem: we allocate a cell holding
a number, save a reference to it in some data structure, use it
for a while, then deallocate it and allocate a new cell holding a
boolean, possibly reusing the same storage. Now we can have two
names for the same storage cell -- one with type [Ref Nat] and the
other with type [Ref Bool]. *)
(** **** Exercise: 1 star (type_safety_violation) *)
(** Show how this can lead to a violation of type safety. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Operational Semantics *)
(* ################################### *)
(** ** Locations *)
(** The most subtle aspect of the treatment of references
appears when we consider how to formalize their operational
behavior. One way to see why is to ask, "What should be the
_values_ of type [Ref T]?" The crucial observation that we need
to take into account is that evaluating a [ref] operator should
_do_ something -- namely, allocate some storage -- and the result
of the operation should be a reference to this storage.
What, then, is a reference?
The run-time store in most programming language implementations is
essentially just a big array of bytes. The run-time system keeps track
of which parts of this array are currently in use; when we need to
allocate a new reference cell, we allocate a large enough segment from
the free region of the store (4 bytes for integer cells, 8 bytes for
cells storing [Float]s, etc.), mark it as being used, and return the
index (typically, a 32- or 64-bit integer) of the start of the newly
allocated region. These indices are references.
For present purposes, there is no need to be quite so concrete.
We can think of the store as an array of _values_, rather than an
array of bytes, abstracting away from the different sizes of the
run-time representations of different values. A reference, then,
is simply an index into the store. (If we like, we can even
abstract away from the fact that these indices are numbers, but
for purposes of formalization in Coq it is a bit more convenient
to use numbers.) We'll use the word _location_ instead of
_reference_ or _pointer_ from now on to emphasize this abstract
quality.
Treating locations abstractly in this way will prevent us from
modeling the _pointer arithmetic_ found in low-level languages
such as C. This limitation is intentional. While pointer
arithmetic is occasionally very useful, especially for
implementing low-level services such as garbage collectors, it
cannot be tracked by most type systems: knowing that location [n]
in the store contains a [float] doesn't tell us anything useful
about the type of location [n+4]. In C, pointer arithmetic is a
notorious source of type safety violations. *)
(* ################################### *)
(** ** Stores *)
(** Recall that, in the small-step operational semantics for
IMP, the step relation needed to carry along an auxiliary state in
addition to the program being executed. In the same way, once we
have added reference cells to the STLC, our step relation must
carry along a store to keep track of the contents of reference
cells.
We could re-use the same functional representation we used for
states in IMP, but for carrying out the proofs in this chapter it
is actually more convenient to represent a store simply as a
_list_ of values. (The reason we couldn't use this representation
before is that, in IMP, a program could modify any location at any
time, so states had to be ready to map _any_ variable to a value.
However, in the STLC with references, the only way to create a
reference cell is with [tref t1], which puts the value of [t1]
in a new reference cell and evaluates to the location of the newly
created reference cell. When evaluating such an expression, we can
just add a new reference cell to the end of the list representing
the store.) *)
Definition store := list tm.
(** We use [store_lookup n st] to retrieve the value of the reference
cell at location [n] in the store [st]. Note that we must give a
default value to [nth] in case we try looking up an index which is
too large. (In fact, we will never actually do this, but proving
it will of course require some work!) *)
Definition store_lookup (n:nat) (st:store) :=
nth n st tunit.
(** To add a new reference cell to the store, we use [snoc]. *)
Fixpoint snoc {A:Type} (l:list A) (x:A) : list A :=
match l with
| nil => x :: nil
| h :: t => h :: snoc t x
end.
(** We will need some boring lemmas about [snoc]. The proofs are
routine inductions. *)
Lemma length_snoc : forall A (l:list A) x,
length (snoc l x) = S (length l).
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ]. Qed.
(* The "solve by inversion" tactic is explained in Stlc.v. *)
Lemma nth_lt_snoc : forall A (l:list A) x d n,
n < length l ->
nth n l d = nth n (snoc l x) d.
Proof.
induction l as [|a l']; intros; try solve by inversion.
Case "l = a :: l'".
destruct n; auto.
simpl. apply IHl'.
simpl in H. apply lt_S_n in H. assumption.
Qed.
Lemma nth_eq_snoc : forall A (l:list A) x d,
nth (length l) (snoc l x) d = x.
Proof.
induction l; intros; [ auto | simpl; rewrite IHl; auto ].
Qed.
(** To update the store, we use the [replace] function, which replaces
the contents of a cell at a particular index. *)
Fixpoint replace {A:Type} (n:nat) (x:A) (l:list A) : list A :=
match l with
| nil => nil
| h :: t =>
match n with
| O => x :: t
| S n' => h :: replace n' x t
end
end.
(** Of course, we also need some boring lemmas about [replace], which
are also fairly straightforward to prove. *)
Lemma replace_nil : forall A n (x:A),
replace n x nil = nil.
Proof.
destruct n; auto.
Qed.
Lemma length_replace : forall A n x (l:list A),
length (replace n x l) = length l.
Proof with auto.
intros A n x l. generalize dependent n.
induction l; intros n.
destruct n...
destruct n...
simpl. rewrite IHl...
Qed.
Lemma lookup_replace_eq : forall l t st,
l < length st ->
store_lookup l (replace l t st) = t.
Proof with auto.
intros l t st.
unfold store_lookup.
generalize dependent l.
induction st as [|t' st']; intros l Hlen.
Case "st = []".
inversion Hlen.
Case "st = t' :: st'".
destruct l; simpl...
apply IHst'. simpl in Hlen. omega.
Qed.
Lemma lookup_replace_neq : forall l1 l2 t st,
l1 <> l2 ->
store_lookup l1 (replace l2 t st) = store_lookup l1 st.
Proof with auto.
unfold store_lookup.
induction l1 as [|l1']; intros l2 t st Hneq.
Case "l1 = 0".
destruct st.
SCase "st = []". rewrite replace_nil...
SCase "st = _ :: _". destruct l2... contradict Hneq...
Case "l1 = S l1'".
destruct st as [|t2 st2].
SCase "st = []". destruct l2...
SCase "st = t2 :: st2".
destruct l2...
simpl; apply IHl1'...
Qed.
(* ################################### *)
(** ** Reduction *)
(** Next, we need to extend our operational semantics to take stores
into account. Since the result of evaluating an expression will
in general depend on the contents of the store in which it is
evaluated, the evaluation rules should take not just a term but
also a store as argument. Furthermore, since the evaluation of a
term may cause side effects on the store that may affect the
evaluation of other terms in the future, the evaluation rules need
to return a new store. Thus, the shape of the single-step
evaluation relation changes from [t ==> t'] to [t / st ==> t' /
st'], where [st] and [st'] are the starting and ending states of
the store.
To carry through this change, we first need to augment all of our
existing evaluation rules with stores:
value v2
-------------------------------------- (ST_AppAbs)
(\x:T.t12) v2 / st ==> [x:=v2]t12 / st
t1 / st ==> t1' / st'
--------------------------- (ST_App1)
t1 t2 / st ==> t1' t2 / st'
value v1 t2 / st ==> t2' / st'
---------------------------------- (ST_App2)
v1 t2 / st ==> v1 t2' / st'
Note that the first rule here returns the store unchanged:
function application, in itself, has no side effects. The other two
rules simply propagate side effects from premise to conclusion.
Now, the result of evaluating a [ref] expression will be a fresh
location; this is why we included locations in the syntax of terms
and in the set of values.
It is crucial to note that making this extension to the syntax of
terms does not mean that we intend _programmers_ to write terms
involving explicit, concrete locations: such terms will arise only
as intermediate results of evaluation. This may initially seem
odd, but really it follows naturally from our design decision to
represent the result of every evaluation step by a modified
term. If we had chosen a more "machine-like" model for evaluation,
e.g. with an explicit stack to contain values of bound
identifiers, then the idea of adding locations to the set of
allowed values would probably seem more obvious.
In terms of this expanded syntax, we can state evaluation rules for
the new constructs that manipulate locations and the store. First, to
evaluate a dereferencing expression [!t1], we must first reduce [t1]
until it becomes a value:
t1 / st ==> t1' / st'
----------------------- (ST_Deref)
!t1 / st ==> !t1' / st'
Once [t1] has finished reducing, we should have an expression of
the form [!l], where [l] is some location. (A term that attempts
to dereference any other sort of value, such as a function or
[unit], is erroneous, as is a term that tries to derefence a
location that is larger than the size [|st|] of the currently
allocated store; the evaluation rules simply get stuck in this
case. The type safety properties that we'll establish below
assure us that well-typed terms will never misbehave in this way.)
l < |st|
---------------------------------- (ST_DerefLoc)
!(loc l) / st ==> lookup l st / st
Next, to evaluate an assignment expression [t1:=t2], we must first
evaluate [t1] until it becomes a value (a location), and then
evaluate [t2] until it becomes a value (of any sort):
t1 / st ==> t1' / st'
----------------------------------- (ST_Assign1)
t1 := t2 / st ==> t1' := t2 / st'
t2 / st ==> t2' / st'
--------------------------------- (ST_Assign2)
v1 := t2 / st ==> v1 := t2' / st'
Once we have finished with [t1] and [t2], we have an expression of
the form [l:=v2], which we execute by updating the store to make
location [l] contain [v2]:
l < |st|
------------------------------------- (ST_Assign)
loc l := v2 / st ==> unit / [l:=v2]st
The notation [[l:=v2]st] means "the store that maps [l] to [v2]
and maps all other locations to the same thing as [st.]" Note
that the term resulting from this evaluation step is just [unit];
the interesting result is the updated store.)
Finally, to evaluate an expression of the form [ref t1], we first
evaluate [t1] until it becomes a value:
t1 / st ==> t1' / st'
----------------------------- (ST_Ref)
ref t1 / st ==> ref t1' / st'
Then, to evaluate the [ref] itself, we choose a fresh location at
the end of the current store -- i.e., location [|st|] -- and yield
a new store that extends [st] with the new value [v1].
-------------------------------- (ST_RefValue)
ref v1 / st ==> loc |st| / st,v1
The value resulting from this step is the newly allocated location
itself. (Formally, [st,v1] means [snoc st v1].)
Note that these evaluation rules do not perform any kind of
garbage collection: we simply allow the store to keep growing
without bound as evaluation proceeds. This does not affect the
correctness of the results of evaluation (after all, the
definition of "garbage" is precisely parts of the store that are
no longer reachable and so cannot play any further role in
evaluation), but it means that a naive implementation of our
evaluator might sometimes run out of memory where a more
sophisticated evaluator would be able to continue by reusing
locations whose contents have become garbage.
Formally... *)
Reserved Notation "t1 '/' st1 '==>' t2 '/' st2"
(at level 40, st1 at level 39, t2 at level 39).
Inductive step : tm * store -> tm * store -> Prop :=
| ST_AppAbs : forall x T t12 v2 st,
value v2 ->
tapp (tabs x T t12) v2 / st ==> [x:=v2]t12 / st
| ST_App1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tapp t1 t2 / st ==> tapp t1' t2 / st'
| ST_App2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tapp v1 t2 / st ==> tapp v1 t2'/ st'
| ST_SuccNat : forall n st,
tsucc (tnat n) / st ==> tnat (S n) / st
| ST_Succ : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tsucc t1 / st ==> tsucc t1' / st'
| ST_PredNat : forall n st,
tpred (tnat n) / st ==> tnat (pred n) / st
| ST_Pred : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tpred t1 / st ==> tpred t1' / st'
| ST_MultNats : forall n1 n2 st,
tmult (tnat n1) (tnat n2) / st ==> tnat (mult n1 n2) / st
| ST_Mult1 : forall t1 t2 t1' st st',
t1 / st ==> t1' / st' ->
tmult t1 t2 / st ==> tmult t1' t2 / st'
| ST_Mult2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tmult v1 t2 / st ==> tmult v1 t2' / st'
| ST_If0 : forall t1 t1' t2 t3 st st',
t1 / st ==> t1' / st' ->
tif0 t1 t2 t3 / st ==> tif0 t1' t2 t3 / st'
| ST_If0_Zero : forall t2 t3 st,
tif0 (tnat 0) t2 t3 / st ==> t2 / st
| ST_If0_Nonzero : forall n t2 t3 st,
tif0 (tnat (S n)) t2 t3 / st ==> t3 / st
| ST_RefValue : forall v1 st,
value v1 ->
tref v1 / st ==> tloc (length st) / snoc st v1
| ST_Ref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tref t1 / st ==> tref t1' / st'
| ST_DerefLoc : forall st l,
l < length st ->
tderef (tloc l) / st ==> store_lookup l st / st
| ST_Deref : forall t1 t1' st st',
t1 / st ==> t1' / st' ->
tderef t1 / st ==> tderef t1' / st'
| ST_Assign : forall v2 l st,
value v2 ->
l < length st ->
tassign (tloc l) v2 / st ==> tunit / replace l v2 st
| ST_Assign1 : forall t1 t1' t2 st st',
t1 / st ==> t1' / st' ->
tassign t1 t2 / st ==> tassign t1' t2 / st'
| ST_Assign2 : forall v1 t2 t2' st st',
value v1 ->
t2 / st ==> t2' / st' ->
tassign v1 t2 / st ==> tassign v1 t2' / st'
where "t1 '/' st1 '==>' t2 '/' st2" := (step (t1,st1) (t2,st2)).
Tactic Notation "step_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1"
| Case_aux c "ST_App2" | Case_aux c "ST_SuccNat"
| Case_aux c "ST_Succ" | Case_aux c "ST_PredNat"
| Case_aux c "ST_Pred" | Case_aux c "ST_MultNats"
| Case_aux c "ST_Mult1" | Case_aux c "ST_Mult2"
| Case_aux c "ST_If0" | Case_aux c "ST_If0_Zero"
| Case_aux c "ST_If0_Nonzero" | Case_aux c "ST_RefValue"
| Case_aux c "ST_Ref" | Case_aux c "ST_DerefLoc"
| Case_aux c "ST_Deref" | Case_aux c "ST_Assign"
| Case_aux c "ST_Assign1" | Case_aux c "ST_Assign2" ].
Hint Constructors step.
Definition multistep := (multi step).
Notation "t1 '/' st '==>*' t2 '/' st'" := (multistep (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(* ################################### *)
(** * Typing *)
(** Our contexts for free variables will be exactly the same as for
the STLC, partial maps from identifiers to types. *)
Definition context := partial_map ty.
(* ################################### *)
(** ** Store typings *)
(** Having extended our syntax and evaluation rules to accommodate
references, our last job is to write down typing rules for the new
constructs -- and, of course, to check that they are sound.
Naturally, the key question is, "What is the type of a location?"
First of all, notice that we do _not_ need to answer this question
for purposes of typechecking the terms that programmers actually
write. Concrete location constants arise only in terms that are
the intermediate results of evaluation; they are not in the
language that programmers write. So we only need to determine the
type of a location when we're in the middle of an evaluation
sequence, e.g. trying to apply the progress or preservation
lemmas. Thus, even though we normally think of typing as a
_static_ program property, it makes sense for the typing of
locations to depend on the _dynamic_ progress of the program too.
As a first try, note that when we evaluate a term containing
concrete locations, the type of the result depends on the contents
of the store that we start with. For example, if we evaluate the
term [!(loc 1)] in the store [[unit, unit]], the result is [unit];
if we evaluate the same term in the store [[unit, \x:Unit.x]], the
result is [\x:Unit.x]. With respect to the former store, the
location [1] has type [Unit], and with respect to the latter it
has type [Unit->Unit]. This observation leads us immediately to a
first attempt at a typing rule for locations:
Gamma |- lookup l st : T1
----------------------------
Gamma |- loc l : Ref T1
That is, to find the type of a location [l], we look up the
current contents of [l] in the store and calculate the type [T1]
of the contents. The type of the location is then [Ref T1].
Having begun in this way, we need to go a little further to reach a
consistent state. In effect, by making the type of a term depend on
the store, we have changed the typing relation from a three-place
relation (between contexts, terms, and types) to a four-place relation
(between contexts, _stores_, terms, and types). Since the store is,
intuitively, part of the context in which we calculate the type of a
term, let's write this four-place relation with the store to the left
of the turnstile: [Gamma; st |- t : T]. Our rule for typing
references now has the form
Gamma; st |- lookup l st : T1
--------------------------------
Gamma; st |- loc l : Ref T1
and all the rest of the typing rules in the system are extended
similarly with stores. The other rules do not need to do anything
interesting with their stores -- just pass them from premise to
conclusion.
However, there are two problems with this rule. First, typechecking
is rather inefficient, since calculating the type of a location [l]
involves calculating the type of the current contents [v] of [l]. If
[l] appears many times in a term [t], we will re-calculate the type of
[v] many times in the course of constructing a typing derivation for
[t]. Worse, if [v] itself contains locations, then we will have to
recalculate _their_ types each time they appear.
Second, the proposed typing rule for locations may not allow us to
derive anything at all, if the store contains a _cycle_. For example,
there is no finite typing derivation for the location [0] with respect
to this store:
<<
[\x:Nat. (!(loc 1)) x, \x:Nat. (!(loc 0)) x]
>>
*)
(** **** Exercise: 2 stars (cyclic_store) *)
(** Can you find a term whose evaluation will create this particular
cyclic store? *)
(** [] *)
(** Both of these problems arise from the fact that our proposed
typing rule for locations requires us to recalculate the type of a
location every time we mention it in a term. But this,
intuitively, should not be necessary. After all, when a location
is first created, we know the type of the initial value that we
are storing into it. Suppose we are willing to enforce the
invariant that the type of the value contained in a given location
_never changes_; that is, although we may later store other values
into this location, those other values will always have the same
type as the initial one. In other words, we always have in mind a
single, definite type for every location in the store, which is
fixed when the location is allocated. Then these intended types
can be collected together as a _store typing_ ---a finite function
mapping locations to types.
As usual, this _conservative_ typing restriction on allowed
updates means that we will rule out as ill-typed some programs
that could evaluate perfectly well without getting stuck.
*)
(** Just like we did for stores, we will represent a store type simply
as a list of types: the type at index [i] records the type of the
value stored in cell [i]. *)
Definition store_ty := list ty.
(** The [store_Tlookup] function retrieves the type at a particular
index. *)
Definition store_Tlookup (n:nat) (ST:store_ty) :=
nth n ST TUnit.
(** Suppose we are _given_ a store typing [ST] describing the store
[st] in which some term [t] will be evaluated. Then we can use
[ST] to calculate the type of the result of [t] without ever
looking directly at [st]. For example, if [ST] is [[Unit,
Unit->Unit]], then we may immediately infer that [!(loc 1)] has
type [Unit->Unit]. More generally, the typing rule for locations
can be reformulated in terms of store typings like this:
l < |ST|
-------------------------------------
Gamma; ST |- loc l : Ref (lookup l ST)
That is, as long as [l] is a valid location (it is less than the
length of [ST]), we can compute the type of [l] just by looking it
up in [ST]. Typing is again a four-place relation, but it is
parameterized on a store _typing_ rather than a concrete store.
The rest of the typing rules are analogously augmented with store
typings. *)
(* ################################### *)
(** ** The Typing Relation *)
(** We can now give the typing relation for the STLC with
references. Here, again, are the rules we're adding to the base
STLC (with numbers and [Unit]): *)
(**
l < |ST|
-------------------------------------- (T_Loc)
Gamma; ST |- loc l : Ref (lookup l ST)
Gamma; ST |- t1 : T1
---------------------------- (T_Ref)
Gamma; ST |- ref t1 : Ref T1
Gamma; ST |- t1 : Ref T11
------------------------- (T_Deref)
Gamma; ST |- !t1 : T11
Gamma; ST |- t1 : Ref T11
Gamma; ST |- t2 : T11
----------------------------- (T_Assign)
Gamma; ST |- t1 := t2 : Unit
*)
Reserved Notation "Gamma ';' ST '|-' t '\in' T" (at level 40).
Inductive has_type : context -> store_ty -> tm -> ty -> Prop :=
| T_Var : forall Gamma ST x T,
Gamma x = Some T ->
Gamma; ST |- (tvar x) \in T
| T_Abs : forall Gamma ST x T11 T12 t12,
(extend Gamma x T11); ST |- t12 \in T12 ->
Gamma; ST |- (tabs x T11 t12) \in (TArrow T11 T12)
| T_App : forall T1 T2 Gamma ST t1 t2,
Gamma; ST |- t1 \in (TArrow T1 T2) ->
Gamma; ST |- t2 \in T1 ->
Gamma; ST |- (tapp t1 t2) \in T2
| T_Nat : forall Gamma ST n,
Gamma; ST |- (tnat n) \in TNat
| T_Succ : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tsucc t1) \in TNat
| T_Pred : forall Gamma ST t1,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- (tpred t1) \in TNat
| T_Mult : forall Gamma ST t1 t2,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in TNat ->
Gamma; ST |- (tmult t1 t2) \in TNat
| T_If0 : forall Gamma ST t1 t2 t3 T,
Gamma; ST |- t1 \in TNat ->
Gamma; ST |- t2 \in T ->
Gamma; ST |- t3 \in T ->
Gamma; ST |- (tif0 t1 t2 t3) \in T
| T_Unit : forall Gamma ST,
Gamma; ST |- tunit \in TUnit
| T_Loc : forall Gamma ST l,
l < length ST ->
Gamma; ST |- (tloc l) \in (TRef (store_Tlookup l ST))
| T_Ref : forall Gamma ST t1 T1,
Gamma; ST |- t1 \in T1 ->
Gamma; ST |- (tref t1) \in (TRef T1)
| T_Deref : forall Gamma ST t1 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- (tderef t1) \in T11
| T_Assign : forall Gamma ST t1 t2 T11,
Gamma; ST |- t1 \in (TRef T11) ->
Gamma; ST |- t2 \in T11 ->
Gamma; ST |- (tassign t1 t2) \in TUnit
where "Gamma ';' ST '|-' t '\in' T" := (has_type Gamma ST t T).
Hint Constructors has_type.
Tactic Notation "has_type_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
| Case_aux c "T_Nat" | Case_aux c "T_Succ" | Case_aux c "T_Pred"
| Case_aux c "T_Mult" | Case_aux c "T_If0"
| Case_aux c "T_Unit" | Case_aux c "T_Loc"
| Case_aux c "T_Ref" | Case_aux c "T_Deref"
| Case_aux c "T_Assign" ].
(** Of course, these typing rules will accurately predict the results
of evaluation only if the concrete store used during evaluation
actually conforms to the store typing that we assume for purposes
of typechecking. This proviso exactly parallels the situation
with free variables in the STLC: the substitution lemma promises
us that, if [Gamma |- t : T], then we can replace the free
variables in [t] with values of the types listed in [Gamma] to
obtain a closed term of type [T], which, by the type preservation
theorem will evaluate to a final result of type [T] if it yields
any result at all. (We will see later how to formalize an
analogous intuition for stores and store typings.)
However, for purposes of typechecking the terms that programmers
actually write, we do not need to do anything tricky to guess what
store typing we should use. Recall that concrete location
constants arise only in terms that are the intermediate results of
evaluation; they are not in the language that programmers write.
Thus, we can simply typecheck the programmer's terms with respect
to the _empty_ store typing. As evaluation proceeds and new
locations are created, we will always be able to see how to extend
the store typing by looking at the type of the initial values
being placed in newly allocated cells; this intuition is
formalized in the statement of the type preservation theorem
below. *)
(* ################################### *)
(** * Properties *)
(** Our final task is to check that standard type safety properties
continue to hold for the STLC with references. The progress
theorem ("well-typed terms are not stuck") can be stated and
proved almost as for the STLC; we just need to add a few
straightforward cases to the proof, dealing with the new
constructs. The preservation theorem is a bit more interesting,
so let's look at it first. *)
(* ################################### *)
(** ** Well-Typed Stores *)
(** Since we have extended both the evaluation relation (with initial
and final stores) and the typing relation (with a store typing),
we need to change the statement of preservation to include these
parameters. Clearly, though, we cannot just add stores and store
typings without saying anything about how they are related: *)
Theorem preservation_wrong1 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
empty; ST |- t' \in T.
Abort.
(** If we typecheck with respect to some set of assumptions about the
types of the values in the store and then evaluate with respect to
a store that violates these assumptions, the result will be
disaster. We say that a store [st] is _well typed_ with respect a
store typing [ST] if the term at each location [l] in [st] has the
type at location [l] in [ST]. Since only closed terms ever get
stored in locations (why?), it suffices to type them in the empty
context. The following definition of [store_well_typed] formalizes
this. *)
Definition store_well_typed (ST:store_ty) (st:store) :=
length ST = length st /\
(forall l, l < length st ->
empty; ST |- (store_lookup l st) \in (store_Tlookup l ST)).
(** Informally, we will write [ST |- st] for [store_well_typed ST st]. *)
(** Intuitively, a store [st] is consistent with a store typing
[ST] if every value in the store has the type predicted by the
store typing. (The only subtle point is the fact that, when
typing the values in the store, we supply the very same store
typing to the typing relation! This allows us to type circular
stores.) *)
(** **** Exercise: 2 stars (store_not_unique) *)
(** Can you find a store [st], and two
different store typings [ST1] and [ST2] such that both
[ST1 |- st] and [ST2 |- st]? *)
(* FILL IN HERE *)
(** [] *)
(** We can now state something closer to the desired preservation
property: *)
Theorem preservation_wrong2 : forall ST T t st t' st',
empty; ST |- t \in T ->
t / st ==> t' / st' ->
store_well_typed ST st ->
empty; ST |- t' \in T.
Abort.
(** This statement is fine for all of the evaluation rules except the
allocation rule [ST_RefValue]. The problem is that this rule
yields a store with a larger domain than the initial store, which
falsifies the conclusion of the above statement: if [st']
includes a binding for a fresh location [l], then [l] cannot be in
the domain of [ST], and it will not be the case that [t']
(which definitely mentions [l]) is typable under [ST]. *)
(* ############################################ *)
(** ** Extending Store Typings *)
(** Evidently, since the store can increase in size during evaluation,
we need to allow the store typing to grow as well. This motivates
the following definition. We say that the store type [ST']
_extends_ [ST] if [ST'] is just [ST] with some new types added to
the end. *)
Inductive extends : store_ty -> store_ty -> Prop :=
| extends_nil : forall ST',
extends ST' nil
| extends_cons : forall x ST' ST,
extends ST' ST ->
extends (x::ST') (x::ST).
Hint Constructors extends.
(** We'll need a few technical lemmas about extended contexts.
First, looking up a type in an extended store typing yields the
same result as in the original: *)
Lemma extends_lookup : forall l ST ST',
l < length ST ->
extends ST' ST ->
store_Tlookup l ST' = store_Tlookup l ST.
Proof with auto.
intros l ST ST' Hlen H.
generalize dependent ST'. generalize dependent l.
induction ST as [|a ST2]; intros l Hlen ST' HST'.
Case "nil". inversion Hlen.
Case "cons". unfold store_Tlookup in *.
destruct ST'.
SCase "ST' = nil". inversion HST'.
SCase "ST' = a' :: ST'2".
inversion HST'; subst.
destruct l as [|l'].
SSCase "l = 0"...
SSCase "l = S l'". simpl. apply IHST2...
simpl in Hlen; omega.
Qed.
(** Next, if [ST'] extends [ST], the length of [ST'] is at least that
of [ST]. *)
Lemma length_extends : forall l ST ST',
l < length ST ->
extends ST' ST ->
l < length ST'.
Proof with eauto.
intros. generalize dependent l. induction H0; intros l Hlen.
inversion Hlen.
simpl in *.
destruct l; try omega.
apply lt_n_S. apply IHextends. omega.
Qed.
(** Finally, [snoc ST T] extends [ST], and [extends] is reflexive. *)
Lemma extends_snoc : forall ST T,
extends (snoc ST T) ST.
Proof with auto.
induction ST; intros T...
simpl...
Qed.
Lemma extends_refl : forall ST,
extends ST ST.
Proof.
induction ST; auto.
Qed.
(* ################################### *)
(** ** Preservation, Finally *)
(** We can now give the final, correct statement of the type
preservation property: *)
Definition preservation_theorem := forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
(** Note that the preservation theorem merely asserts that there is
_some_ store typing [ST'] extending [ST] (i.e., agreeing with [ST]
on the values of all the old locations) such that the new term
[t'] is well typed with respect to [ST']; it does not tell us
exactly what [ST'] is. It is intuitively clear, of course, that
[ST'] is either [ST] or else it is exactly [snoc ST T1], where
[T1] is the type of the value [v1] in the extended store [snoc st
v1], but stating this explicitly would complicate the statement of
the theorem without actually making it any more useful: the weaker
version above is already in the right form (because its conclusion
implies its hypothesis) to "turn the crank" repeatedly and
conclude that every _sequence_ of evaluation steps preserves
well-typedness. Combining this with the progress property, we
obtain the usual guarantee that "well-typed programs never go
wrong."
In order to prove this, we'll need a few lemmas, as usual. *)
(* ################################### *)
(** ** Substitution lemma *)
(** First, we need an easy extension of the standard substitution
lemma, along with the same machinery about context invariance that
we used in the proof of the substitution lemma for the STLC. *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_succ : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tsucc t1)
| afi_pred : forall x t1,
appears_free_in x t1 ->
appears_free_in x (tpred t1)
| afi_mult1 : forall x t1 t2,
appears_free_in x t1 ->
appears_free_in x (tmult t1 t2)
| afi_mult2 : forall x t1 t2,
appears_free_in x t2 ->
appears_free_in x (tmult t1 t2)
| afi_if0_1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_if0_3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif0 t1 t2 t3)
| afi_ref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tref t1)
| afi_deref : forall x t1,
appears_free_in x t1 -> appears_free_in x (tderef t1)
| afi_assign1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tassign t1 t2)
| afi_assign2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tassign t1 t2).
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_succ" | Case_aux c "afi_pred"
| Case_aux c "afi_mult1" | Case_aux c "afi_mult2"
| Case_aux c "afi_if0_1" | Case_aux c "afi_if0_2" | Case_aux c "afi_if0_3"
| Case_aux c "afi_ref" | Case_aux c "afi_deref"
| Case_aux c "afi_assign1" | Case_aux c "afi_assign2" ].
Hint Constructors appears_free_in.
Lemma free_in_context : forall x t T Gamma ST,
appears_free_in x t ->
Gamma; ST |- t \in T ->
exists T', Gamma x = Some T'.
Proof with eauto.
intros. generalize dependent Gamma. generalize dependent T.
afi_cases (induction H) Case;
intros; (try solve [ inversion H0; subst; eauto ]).
Case "afi_abs".
inversion H1; subst.
apply IHappears_free_in in H8.
rewrite extend_neq in H8; assumption.
Qed.
Lemma context_invariance : forall Gamma Gamma' ST t T,
Gamma; ST |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma'; ST |- t \in T.
Proof with eauto.
intros.
generalize dependent Gamma'.
has_type_cases (induction H) Case; intros...
Case "T_Var".
apply T_Var. symmetry. rewrite <- H...
Case "T_Abs".
apply T_Abs. apply IHhas_type; intros.
unfold extend.
destruct (eq_id_dec x x0)...
Case "T_App".
eapply T_App.
apply IHhas_type1...
apply IHhas_type2...
Case "T_Mult".
eapply T_Mult.
apply IHhas_type1...
apply IHhas_type2...
Case "T_If0".
eapply T_If0.
apply IHhas_type1...
apply IHhas_type2...
apply IHhas_type3...
Case "T_Assign".
eapply T_Assign.
apply IHhas_type1...
apply IHhas_type2...
Qed.
Lemma substitution_preserves_typing : forall Gamma ST x s S t T,
empty; ST |- s \in S ->
(extend Gamma x S); ST |- t \in T ->
Gamma; ST |- ([x:=s]t) \in T.
Proof with eauto.
intros Gamma ST x s S t T Hs Ht.
generalize dependent Gamma. generalize dependent T.
t_cases (induction t) Case; intros T Gamma 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 H3.
inversion H3; subst.
eapply context_invariance...
intros x Hcontra.
destruct (free_in_context _ _ _ _ _ Hcontra Hs) as [T' HT'].
inversion HT'.
SCase "x <> y".
apply T_Var.
rewrite extend_neq in H3...
Case "tabs". subst.
rename i into y.
destruct (eq_id_dec x y).
SCase "x = y".
subst.
apply T_Abs. eapply context_invariance...
intros. apply extend_shadow.
SCase "x <> x0".
apply T_Abs. apply IHt.
eapply context_invariance...
intros. unfold extend.
destruct (eq_id_dec y x0)...
subst.
rewrite neq_id...
Qed.
(* ################################### *)
(** ** Assignment Preserves Store Typing *)
(** Next, we must show that replacing the contents of a cell in the
store with a new value of appropriate type does not change the
overall type of the store. (This is needed for the [ST_Assign]
rule.) *)
Lemma assign_pres_store_typing : forall ST st l t,
l < length st ->
store_well_typed ST st ->
empty; ST |- t \in (store_Tlookup l ST) ->
store_well_typed ST (replace l t st).
Proof with auto.
intros ST st l t Hlen HST Ht.
inversion HST; subst.
split. rewrite length_replace...
intros l' Hl'.
destruct (beq_nat l' l) eqn: Heqll'.
Case "l' = l".
apply beq_nat_true in Heqll'; subst.
rewrite lookup_replace_eq...
Case "l' <> l".
apply beq_nat_false in Heqll'.
rewrite lookup_replace_neq...
rewrite length_replace in Hl'.
apply H0...
Qed.
(* ######################################## *)
(** ** Weakening for Stores *)
(** Finally, we need a lemma on store typings, stating that, if a
store typing is extended with a new location, the extended one
still allows us to assign the same types to the same terms as the
original.
(The lemma is called [store_weakening] because it resembles the
"weakening" lemmas found in proof theory, which show that adding a
new assumption to some logical theory does not decrease the set of
provable theorems.) *)
Lemma store_weakening : forall Gamma ST ST' t T,
extends ST' ST ->
Gamma; ST |- t \in T ->
Gamma; ST' |- t \in T.
Proof with eauto.
intros. has_type_cases (induction H0) Case; eauto.
Case "T_Loc".
erewrite <- extends_lookup...
apply T_Loc.
eapply length_extends...
Qed.
(** We can use the [store_weakening] lemma to prove that if a store is
well typed with respect to a store typing, then the store extended
with a new term [t] will still be well typed with respect to the
store typing extended with [t]'s type. *)
Lemma store_well_typed_snoc : forall ST st t1 T1,
store_well_typed ST st ->
empty; ST |- t1 \in T1 ->
store_well_typed (snoc ST T1) (snoc st t1).
Proof with auto.
intros.
unfold store_well_typed in *.
inversion H as [Hlen Hmatch]; clear H.
rewrite !length_snoc.
split...
Case "types match.".
intros l Hl.
unfold store_lookup, store_Tlookup.
apply le_lt_eq_dec in Hl; inversion Hl as [Hlt | Heq].
SCase "l < length st".
apply lt_S_n in Hlt.
rewrite <- !nth_lt_snoc...
apply store_weakening with ST. apply extends_snoc.
apply Hmatch...
rewrite Hlen...
SCase "l = length st".
inversion Heq.
rewrite nth_eq_snoc.
rewrite <- Hlen. rewrite nth_eq_snoc...
apply store_weakening with ST... apply extends_snoc.
Qed.
(* ################################### *)
(** ** Preservation! *)
(** Now that we've got everything set up right, the proof of
preservation is actually quite straightforward. *)
Theorem preservation : forall ST t t' T st st',
empty; ST |- t \in T ->
store_well_typed ST st ->
t / st ==> t' / st' ->
exists ST',
(extends ST' ST /\
empty; ST' |- t' \in T /\
store_well_typed ST' st').
Proof with eauto using store_weakening, extends_refl.
remember (@empty ty) as Gamma.
intros ST t t' T st st' Ht.
generalize dependent t'.
has_type_cases (induction Ht) Case; intros t' HST Hstep;
subst; try (solve by inversion); inversion Hstep; subst;
try (eauto using store_weakening, extends_refl).
Case "T_App".
SCase "ST_AppAbs". exists ST.
inversion Ht1; subst.
split; try split... eapply substitution_preserves_typing...
SCase "ST_App1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_App2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Succ".
SCase "ST_Succ".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Pred".
SCase "ST_Pred".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Mult".
SCase "ST_Mult1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Mult2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_If0".
SCase "ST_If0_1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'... split...
Case "T_Ref".
SCase "ST_RefValue".
exists (snoc ST T1).
inversion HST; subst.
split.
apply extends_snoc.
split.
replace (TRef T1)
with (TRef (store_Tlookup (length st) (snoc ST T1))).
apply T_Loc.
rewrite <- H. rewrite length_snoc. omega.
unfold store_Tlookup. rewrite <- H. rewrite nth_eq_snoc...
apply store_well_typed_snoc; assumption.
SCase "ST_Ref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Deref".
SCase "ST_DerefLoc".
exists ST. split; try split...
inversion HST as [_ Hsty].
replace T11 with (store_Tlookup l ST).
apply Hsty...
inversion Ht; subst...
SCase "ST_Deref".
eapply IHHt in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Case "T_Assign".
SCase "ST_Assign".
exists ST. split; try split...
eapply assign_pres_store_typing...
inversion Ht1; subst...
SCase "ST_Assign1".
eapply IHHt1 in H0...
inversion H0 as [ST' [Hext [Hty Hsty]]].
exists ST'...
SCase "ST_Assign2".
eapply IHHt2 in H5...
inversion H5 as [ST' [Hext [Hty Hsty]]].
exists ST'...
Qed.
(** **** Exercise: 3 stars (preservation_informal) *)
(** Write a careful informal proof of the preservation theorem,
concentrating on the [T_App], [T_Deref], [T_Assign], and [T_Ref]
cases.
(* FILL IN HERE *)
[] *)
(* ################################### *)
(** ** Progress *)
(** Fortunately, progress for this system is pretty easy to prove; the
proof is very similar to the proof of progress for the STLC, with
a few new cases for the new syntactic constructs. *)
Theorem progress : forall ST t T st,
empty; ST |- t \in T ->
store_well_typed ST st ->
(value t \/ exists t', exists st', t / st ==> t' / st').
Proof with eauto.
intros ST t T st Ht HST. remember (@empty ty) as Gamma.
has_type_cases (induction Ht) Case; subst; try solve by inversion...
Case "T_App".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tapp (tabs x T t) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tapp t1' t2). exists st'...
Case "T_Succ".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [ inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (S n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tsucc t1'). exists st'...
Case "T_Pred".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht ].
SSCase "t1 is a tnat".
exists (tnat (pred n)). exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tpred t1'). exists st'...
Case "T_Mult".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct IHHt2 as [Ht2p | Ht2p]...
SSCase "t2 is a value".
inversion Ht2p; subst; try solve [inversion Ht2].
exists (tnat (mult n n0)). exists st...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tmult (tnat n) t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tmult t1' t2). exists st'...
Case "T_If0".
right. destruct IHHt1 as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve [inversion Ht1].
destruct n.
SSCase "n = 0". exists t2. exists st...
SSCase "n = S n'". exists t3. exists st...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tif0 t1' t2 t3). exists st'...
Case "T_Ref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tref t1'). exists st'...
Case "T_Deref".
right. destruct IHHt as [Ht1p | Ht1p]...
SCase "t1 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_DerefLoc...
inversion Ht; subst. inversion HST; subst.
rewrite <- H...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tderef t1'). exists st'...
Case "T_Assign".
right. destruct IHHt1 as [Ht1p|Ht1p]...
SCase "t1 is a value".
destruct IHHt2 as [Ht2p|Ht2p]...
SSCase "t2 is a value".
inversion Ht1p; subst; try solve by inversion.
eexists. eexists. apply ST_Assign...
inversion HST; subst. inversion Ht1; subst.
rewrite H in H5...
SSCase "t2 steps".
inversion Ht2p as [t2' [st' Hstep]].
exists (tassign t1 t2'). exists st'...
SCase "t1 steps".
inversion Ht1p as [t1' [st' Hstep]].
exists (tassign t1' t2). exists st'...
Qed.
(* ################################### *)
(** * References and Nontermination *)
Section RefsAndNontermination.
Import ExampleVariables.
(** We know that the simply typed lambda calculus is _normalizing_,
that is, every well-typed term can be reduced to a value in a
finite number of steps. What about STLC + references?
Surprisingly, adding references causes us to lose the
normalization property: there exist well-typed terms in the STLC +
references which can continue to reduce forever, without ever
reaching a normal form!
How can we construct such a term? The main idea is to make a
function which calls itself. We first make a function which calls
another function stored in a reference cell; the trick is that we
then smuggle in a reference to itself!
<<
(\r:Ref (Unit -> Unit).
r := (\x:Unit.(!r) unit); (!r) unit)
(ref (\x:Unit.unit))
>>
First, [ref (\x:Unit.unit)] creates a reference to a cell of type
[Unit -> Unit]. We then pass this reference as the argument to a
function which binds it to the name [r], and assigns to it the
function (\x:Unit.(!r) unit) -- that is, the function which
ignores its argument and calls the function stored in [r] on the
argument [unit]; but of course, that function is itself! To get
the ball rolling we finally execute this function with [(!r)
unit].
*)
Definition loop_fun :=
tabs x TUnit (tapp (tderef (tvar r)) tunit).
Definition loop :=
tapp
(tabs r (TRef (TArrow TUnit TUnit))
(tseq (tassign (tvar r) loop_fun)
(tapp (tderef (tvar r)) tunit)))
(tref (tabs x TUnit tunit)).
(** This term is well typed: *)
Lemma loop_typeable : exists T, empty; nil |- loop \in T.
Proof with eauto.
eexists. unfold loop. unfold loop_fun.
eapply T_App...
eapply T_Abs...
eapply T_App...
eapply T_Abs. eapply T_App. eapply T_Deref. eapply T_Var.
unfold extend. simpl. reflexivity. auto.
eapply T_Assign.
eapply T_Var. unfold extend. simpl. reflexivity.
eapply T_Abs.
eapply T_App...
eapply T_Deref. eapply T_Var. reflexivity.
Qed.
(** To show formally that the term diverges, we first define the
[step_closure] of the single-step reduction relation, written
[==>+]. This is just like the reflexive step closure of
single-step reduction (which we're been writing [==>*]), except
that it is not reflexive: [t ==>+ t'] means that [t] can reach
[t'] by _one or more_ steps of reduction. *)
Inductive step_closure {X:Type} (R: relation X) : X -> X -> Prop :=
| sc_one : forall (x y : X),
R x y -> step_closure R x y
| sc_step : forall (x y z : X),
R x y ->
step_closure R y z ->
step_closure R x z.
Definition multistep1 := (step_closure step).
Notation "t1 '/' st '==>+' t2 '/' st'" := (multistep1 (t1,st) (t2,st'))
(at level 40, st at level 39, t2 at level 39).
(** Now, we can show that the expression [loop] reduces to the
expression [!(loc 0) unit] and the size-one store [ [r:=(loc 0)]
loop_fun]. *)
(** As a convenience, we introduce a slight variant of the [normalize]
tactic, called [reduce], which tries solving the goal with
[multi_refl] at each step, instead of waiting until the goal can't
be reduced any more. Of course, the whole point is that [loop]
doesn't normalize, so the old [normalize] tactic would just go
into an infinite loop reducing it forever! *)
Ltac print_goal := match goal with |- ?x => idtac x end.
Ltac reduce :=
repeat (print_goal; eapply multi_step ;
[ (eauto 10; fail) | (instantiate; compute)];
try solve [apply multi_refl]).
Lemma loop_steps_to_loop_fun :
loop / nil ==>*
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop.
reduce.
Qed.
(** Finally, the latter expression reduces in two steps to itself! *)
Lemma loop_fun_step_self :
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil ==>+
tapp (tderef (tloc 0)) tunit / cons ([r:=tloc 0]loop_fun) nil.
Proof with eauto.
unfold loop_fun; simpl.
eapply sc_step. apply ST_App1...
eapply sc_one. compute. apply ST_AppAbs...
Qed.
(** **** Exercise: 4 stars (factorial_ref) *)
(** Use the above ideas to implement a factorial function in STLC with
references. (There is no need to prove formally that it really
behaves like the factorial. Just use the example below to make
sure it gives the correct result when applied to the argument
[4].) *)
Definition factorial : tm :=
(* FILL IN HERE *) admit.
Lemma factorial_type : empty; nil |- factorial \in (TArrow TNat TNat).
Proof with eauto.
(* FILL IN HERE *) Admitted.
(** If your definition is correct, you should be able to just
uncomment the example below; the proof should be fully
automatic using the [reduce] tactic. *)
(*
Lemma factorial_4 : exists st,
tapp factorial (tnat 4) / nil ==>* tnat 24 / st.
Proof.
eexists. unfold factorial. reduce.
Qed.
*)
(** [] *)
(* ################################### *)
(** * Additional Exercises *)
(** **** Exercise: 5 stars, optional (garabage_collector) *)
(** Challenge problem: modify our formalization to include an account
of garbage collection, and prove that it satisfies whatever nice
properties you can think to prove about it. *)
(** [] *)
End RefsAndNontermination.
End STLCRef.
(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)
|
module lsu_bursting_read
(
clk, clk2x, reset, flush, i_nop, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid,
avm_burstcount,
// Profiling
extra_unaligned_reqs,
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=8; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=64; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=$clog2(WIDTH_BYTES); // Request address alignment (address bits)
parameter DEVICE = "Stratix V"; // DEVICE
parameter BURSTCOUNT_WIDTH=5; // MAX BURST = 2**(BURSTCOUNT_WIDTH-1)
parameter KERNEL_SIDE_MEM_LATENCY=1; // Effective Latency in cycles as seen by the kernel pipeline
parameter MEMORY_SIDE_MEM_LATENCY = 1; // Latency in cycles between LSU and memory
parameter MAX_THREADS=64; // Maximum # of threads to group into a burst request
parameter TIME_OUT=8; // Time out counter max
parameter USECACHING = 0; // Enable internal cache
parameter CACHE_SIZE_N=1024; // Cache depth (width = WIDTH_BYTES)
parameter ACL_PROFILE = 0; // Profiler
parameter HIGH_FMAX = 1; // Add pipeline to io if set to 1
parameter UNALIGNED = 0; // Output word unaligned
/*****************
* Local Parameters *
*****************/
localparam MAX_BURST = 2**(BURSTCOUNT_WIDTH-1);
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam A_BYTES = 2**ALIGNMENT_ABITS;
localparam WORD_BYTES = (WIDTH_BYTES >= A_BYTES & (UNALIGNED == 0))? WIDTH_BYTES : A_BYTES;
localparam NUM_WORD = MWIDTH_BYTES / WORD_BYTES;
localparam MB_W=$clog2(MWIDTH_BYTES);
localparam OB_W = $clog2(WIDTH_BYTES);
localparam PAGE_ADDR_WIDTH = AWIDTH - MB_W;
localparam OFFSET_WIDTH = $clog2(NUM_WORD);
localparam CACHE_ADDR_W=$clog2(CACHE_SIZE_N);
localparam CACHE_BASE_ADDR_W = AWIDTH-MB_W-CACHE_ADDR_W;
localparam UNALIGNED_DIV_ALIGN = WIDTH_BYTES / A_BYTES;
localparam UNALIGNED_SELECTION_BITS=$clog2(UNALIGNED_DIV_ALIGN);
// Standard global signals
input clk;
input clk2x;
input reset;
input flush;
input i_nop;
// Upstream interface
output logic o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
// Profiling
output logic extra_unaligned_reqs;
output logic req_cache_hit_count;
// internal signals
logic stall_pre;
wire reg_valid;
wire reg_nop;
wire [AWIDTH-1:0] reg_address;
// registed to help P&R
logic R_valid, R_nop;
wire [AWIDTH-1:0] addr_next_wire;
logic [AWIDTH-1:0] R_addr, R_addr_next, R_addr_next_hold;
// cache status
reg [CACHE_BASE_ADDR_W:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "M20K" */;
wire [1:0] in_cache_pre;
logic [CACHE_BASE_ADDR_W-1:0] cached_tag [2];
wire [CACHE_BASE_ADDR_W-1:0] R_tag [2];
wire [CACHE_ADDR_W-1:0] rd_c_index [2];
wire [CACHE_ADDR_W-1:0] wr_c_index;
logic cached_tag_valid [2];
wire tag_match [2];
wire consecutive;
reg cache_ready;
logic [1:0] in_cache;
wire [MB_W-1:0] byte_offset;
reg include_2nd_part;
logic update_cache;
logic [CACHE_BASE_ADDR_W-1:0] new_tag;
logic issue_2nd_word;
reg issue_2nd_hold;
logic need_2_page;
wire stall_int;
wire need_2_cc;
wire [UNALIGNED_SELECTION_BITS-1:0] shift;
logic [AWIDTH-1:0] lsu_i_address;
reg p_valid;
reg [AWIDTH-1:0] p_addr;
reg [1:0] R_consecutive;
reg [63:0] non_align_hit_cache;
// coalesced addr
wire [BURSTCOUNT_WIDTH-1:0]c_burstcount;
wire [PAGE_ADDR_WIDTH-1:0] c_page_addr;
wire c_req_valid;
wire c_new_page;
logic [OFFSET_WIDTH-1 : 0] p_offset, c_word_offset;
logic p_offset_valid;
reg [CACHE_ADDR_W-1:0] R_cache_addr;
// fifo
reg fifo_din_en;
reg [1:0] fi_in_cache;
reg [CACHE_ADDR_W-1:0] fi_cached_addr;
reg [UNALIGNED_SELECTION_BITS-1:0] fi_shift;
reg fi_second, fi_2nd_valid;
reg [UNALIGNED_SELECTION_BITS-1:0] R_shift;
reg [MB_W-1:0] fi_byte_offset;
wire p_ae;
generate
if(HIGH_FMAX) begin: GEN_PIPE_INPUT
acl_io_pipeline #(
.WIDTH(1+AWIDTH)
) in_pipeline (
.clk(clk),
.reset(reset),
.i_stall(stall_pre),
.i_valid(i_valid),
.i_data({i_nop, i_address}),
.o_stall(o_stall),
.o_valid(reg_valid),
.o_data({reg_nop, reg_address})
);
end
else begin : GEN_FAST_INPUT
assign {reg_valid, reg_nop, reg_address} = {i_valid, i_nop, i_address};
end
if(USECACHING) begin : GEN_ENABLE_CACHE
reg R_flush;
reg [CACHE_ADDR_W:0] flush_cnt;
reg cache_status_ready;
assign rd_c_index[0] = R_addr[CACHE_ADDR_W-1+MB_W:MB_W];
assign rd_c_index[1] = R_addr_next[CACHE_ADDR_W-1+MB_W:MB_W];
assign {cached_tag_valid[0], cached_tag[0]} = cache[rd_c_index[0]];
assign {cached_tag_valid[1], cached_tag[1]} = cache[rd_c_index[1]];
assign wr_c_index = lsu_i_address[CACHE_ADDR_W-1+MB_W:MB_W];
assign R_tag[0] = R_addr[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign R_tag[1] = R_addr_next[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign tag_match[0] = cached_tag[0] == R_tag[0] & cached_tag_valid[0] === 1'b1;
assign tag_match[1] = cached_tag[1] == R_tag[1] & cached_tag_valid[1] === 1'b1;
assign in_cache_pre[0] = tag_match[0] & !issue_2nd_word & cache_ready;
assign in_cache_pre[1] = tag_match[1] & !issue_2nd_word & cache_ready;
assign new_tag = lsu_i_address[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign update_cache = R_valid & !R_nop | issue_2nd_word;
always @(posedge clk or posedge reset) begin
if(reset) cache_status_ready <= 1'b0;
else cache_status_ready <= flush_cnt[CACHE_ADDR_W];
end
always @ (posedge clk) begin
R_flush <= flush;
if(flush & !R_flush) flush_cnt <= '0;
else if(!flush_cnt[CACHE_ADDR_W]) flush_cnt <= flush_cnt + 1'b1;
cache_ready <= flush_cnt[CACHE_ADDR_W];
if(!flush_cnt[CACHE_ADDR_W]) cache[flush_cnt] <= '0;
else if(update_cache) cache[wr_c_index] <= {1'b1, new_tag};
in_cache[0] <= R_valid & (in_cache_pre[0] | R_nop) & !issue_2nd_word;
in_cache[1] <= UNALIGNED? R_valid & (in_cache_pre[1] | R_nop) & !issue_2nd_word & need_2_page : 1'b0;
include_2nd_part <= issue_2nd_word | in_cache_pre[1] & need_2_page;
p_valid <= issue_2nd_word | R_valid & !in_cache_pre[0] & !R_nop; // not include nop
p_offset_valid <= issue_2nd_word | R_valid;
p_addr <= lsu_i_address;
R_cache_addr <= lsu_i_address[MB_W+CACHE_ADDR_W-1:MB_W];
end
if(OFFSET_WIDTH > 0) begin
always @ (posedge clk) begin
p_offset <= R_addr[MB_W-1:MB_W-OFFSET_WIDTH];
end
end
if(ACL_PROFILE == 1) begin
assign req_cache_hit_count = ((|fi_in_cache) & fifo_din_en);
end
else
begin
assign req_cache_hit_count = 1'b0;
end
end // end GEN_ENABLE_CACHE
else begin : GEN_DISABLE_CACHE
assign req_cache_hit_count = 1'b0;
assign in_cache_pre = 2'b0;
assign in_cache = 2'b0;
assign include_2nd_part = issue_2nd_word;
assign p_valid = issue_2nd_word | R_valid & !R_nop; // not include nop
assign p_offset_valid = issue_2nd_word | R_valid;
assign p_addr = lsu_i_address;
if(OFFSET_WIDTH > 0) begin
assign p_offset = R_addr[MB_W-1:MB_W-OFFSET_WIDTH];
end
end // end GEN_DISABLE_CACHE
if (UNALIGNED) begin : GEN_UNALIGN
assign addr_next_wire[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH] = reg_address[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH]+1'b1;
assign addr_next_wire[AWIDTH-PAGE_ADDR_WIDTH-1:0] = '0;
// Look at the higher bits to determine how much we need to shift the two aligned accesses
wire [UNALIGNED_SELECTION_BITS-1:0] temp = NUM_WORD - R_addr[AWIDTH-1:ALIGNMENT_ABITS];
assign shift = UNALIGNED_DIV_ALIGN - temp;
assign consecutive = reg_nop | reg_address[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH] == R_addr_next[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH];
// When do we need to issue the 2nd word ?
// The previous address needed a 2nd page and
// [1] the current requested address isn't in the (previous+1)th page and
// [2] The second page is not in the cache
assign need_2_cc = need_2_page & !in_cache_pre[1] & R_valid & (!issue_2nd_word | R_consecutive[0]); // need 2 clock cycles to combine segments from 2 pages
// simulation only
assign byte_offset = stall_pre? R_addr[MB_W-1:0] : reg_address[MB_W-1:0];
always @(posedge clk or posedge reset) begin
if(reset) begin
issue_2nd_word <= 1'b0;
R_consecutive <= 'x;
stall_pre <= 1'b0;
issue_2nd_hold <= 'x;
end
else begin
issue_2nd_word <= need_2_cc;
if(!stall_pre | issue_2nd_word) issue_2nd_hold <= need_2_cc;
R_consecutive[0] <= reg_valid & !stall_int & consecutive & need_2_cc;
R_consecutive[1] <= R_consecutive[0];
stall_pre <= (stall_int | need_2_cc & reg_valid & !consecutive);
end
end
always @(posedge clk) begin
if(reg_valid & !stall_pre) need_2_page <= !reg_nop & (reg_address[MB_W-1:0] + WIDTH_BYTES) > MWIDTH_BYTES;
if(reg_valid & !stall_pre & !reg_nop) begin
R_addr <= reg_address;
R_addr_next <= addr_next_wire;
end
R_addr_next_hold <= R_addr_next;
if(!issue_2nd_word | !stall_pre) begin
R_valid <= reg_valid & !stall_pre;
R_nop <= reg_nop;
end
end
if(ACL_PROFILE == 1) begin
assign extra_unaligned_reqs = need_2_cc & reg_valid & !consecutive;
always @(posedge clk or posedge reset) begin
if(reset) begin
non_align_hit_cache <= '0;
end
else begin
non_align_hit_cache <= non_align_hit_cache + (need_2_page & in_cache_pre[1] & R_valid & (!issue_2nd_word | R_consecutive[0]) & reg_valid & !consecutive);
end
end
end // end ACL_PROFILE == 1
end // end GEN_UNALIGN
else begin : GEN_ALIGN
assign issue_2nd_word = 1'b0;
assign need_2_page = 1'b0;
assign R_addr = reg_address;
assign R_valid = reg_valid & !stall_int;
assign R_nop = reg_nop;
assign stall_pre = stall_int;
end // end GEN_ALIGN
endgenerate
assign lsu_i_address = issue_2nd_word ? R_addr_next_hold : R_addr;
always @(posedge clk) begin
c_word_offset <= p_offset;
R_shift <= need_2_page? shift : '0;
fifo_din_en <= (|in_cache) | p_offset_valid;
{fi_in_cache, fi_cached_addr, fi_second} <= {in_cache, R_cache_addr, include_2nd_part};
if(!include_2nd_part) fi_byte_offset <= p_addr[MB_W-1:0];
fi_shift <= USECACHING? R_shift : (need_2_page? shift : '0);
fi_2nd_valid <= USECACHING? R_consecutive[1] : R_consecutive[0];
end
acl_stall_free_coalescer #(
.AW(AWIDTH),
.PAGE_AW(PAGE_ADDR_WIDTH),
.MAX_BURST(MAX_BURST),
.TIME_OUT(TIME_OUT),
.CACHE_LAST(USECACHING),
.MAX_THREAD(MAX_THREADS),
.DISABLE_COALESCE(0)
) coalescer(
.clk(clk),
.reset(reset),
.i_valid(p_valid),
.i_addr(p_addr),
.i_empty(p_ae),
.o_page_addr(c_page_addr),
.o_page_addr_valid(c_req_valid),
.o_num_burst(c_burstcount),
.o_new_page(c_new_page)
);
lsu_bursting_pipelined_read #(
.INPUT_AW(PAGE_ADDR_WIDTH),
.AWIDTH(AWIDTH),
.WIDTH(WIDTH),
.MWIDTH(MWIDTH),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.DEVICE(DEVICE),
.CACHE_SIZE_N(CACHE_SIZE_N),
.USECACHING(USECACHING),
.UNALIGNED(UNALIGNED),
.UNALIGNED_SHIFT_WIDTH(UNALIGNED_SELECTION_BITS),
.MAX_BURST(MAX_BURST),
.INCLUDE_BYTE_OFFSET(0), // sim-only
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) pipelined_read(
.clk (clk),
.reset (reset),
.i_address (c_page_addr),
.i_addr_valid (c_req_valid),
.i_burst_count (c_burstcount),
.i_new_page (c_new_page),
.i_word_offset (c_word_offset),
.i_byte_offset (fi_byte_offset),
.i_in_cache (fi_in_cache),
.i_cache_addr (fi_cached_addr),
.i_shift (fi_shift),
.i_second (fi_second),
.i_2nd_valid (fi_2nd_valid), // has two segments' info in one cc
.i_word_offset_valid(fifo_din_en),
.i_stall (i_stall),
.o_ae (p_ae),
.o_empty (p_empty),
.o_readdata (o_readdata),
.o_valid (o_valid),
.o_stall (stall_int),
.avm_address (avm_address),
.avm_read (avm_read),
.avm_readdata (avm_readdata),
.avm_waitrequest (avm_waitrequest),
.avm_byteenable (avm_byteenable),
.avm_readdatavalid(avm_readdatavalid),
.avm_burstcount (avm_burstcount)
);
endmodule
module acl_io_pipeline #(
parameter WIDTH = 1
)(
input clk,
input reset,
input i_stall,
input i_valid,
input [WIDTH-1:0] i_data,
output o_stall,
output reg o_valid,
output reg [WIDTH-1:0] o_data
);
reg R_valid;
assign o_stall = i_stall & R_valid;
always@(posedge clk) begin
if(!o_stall) {o_valid, o_data} <= {i_valid, i_data};
end
always@(posedge clk or posedge reset)begin
if(reset) R_valid <= 1'b0;
else if(!o_stall) R_valid <= i_valid;
end
endmodule
module lsu_bursting_pipelined_read
(
clk, reset,
i_in_cache,
i_cache_addr,
i_addr_valid,
i_address,
i_burst_count,
i_word_offset,
i_byte_offset,
i_shift,
i_second,
i_2nd_valid,
i_word_offset_valid,
i_new_page,
o_readdata,
o_valid,
i_stall,
o_stall,
o_empty,
o_ae,
avm_address,
avm_read,
avm_readdata,
avm_waitrequest,
avm_byteenable,
avm_burstcount,
avm_readdatavalid
);
parameter INPUT_AW = 32;
parameter AWIDTH=32;
parameter WIDTH=32;
parameter MWIDTH=512;
parameter MAX_BURST = 16;
parameter ALIGNMENT_ABITS=2;
parameter DEVICE = "Stratix V";
parameter MEMORY_SIDE_MEM_LATENCY=160;
parameter USECACHING = 0;
parameter CACHE_SIZE_N = 1024;
parameter UNALIGNED = 0;
parameter UNALIGNED_SHIFT_WIDTH = 0;
parameter INCLUDE_BYTE_OFFSET = 0; // testing purpose
localparam ALIGNMENT_WIDTH = 2**ALIGNMENT_ABITS * 8;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH/8);
localparam WORD_WIDTH = (WIDTH >= ALIGNMENT_WIDTH & (UNALIGNED == 0))? WIDTH : ALIGNMENT_WIDTH;
localparam NUM_WORD = MWIDTH / WORD_WIDTH;
localparam OFFSET_WIDTH = (NUM_WORD==1)? 1 : $clog2(NUM_WORD);
localparam WIDE_FIFO_DEPTH = (MEMORY_SIDE_MEM_LATENCY < 256)? 256 : MEMORY_SIDE_MEM_LATENCY;
localparam OFFSET_FIFO_DEPTH = (MEMORY_SIDE_MEM_LATENCY <= 246)? 256 : MEMORY_SIDE_MEM_LATENCY + 10;
localparam REQUEST_FIFO_DEPTH = OFFSET_FIFO_DEPTH;
localparam WIDE_FIFO_DEPTH_THRESH = MEMORY_SIDE_MEM_LATENCY;
localparam WIDE_FIFO_AW = $clog2(WIDE_FIFO_DEPTH);
localparam BURST_CNT_WIDTH = (MAX_BURST == 1)? 1 : $clog2(MAX_BURST + 1);
localparam REQUEST_FIFO_AW = $clog2(REQUEST_FIFO_DEPTH);
localparam OFFSET_FIFO_AW = $clog2(OFFSET_FIFO_DEPTH);
localparam REQUEST_FIFO_WIDTH = INPUT_AW + BURST_CNT_WIDTH;
localparam CACHE_SIZE_LOG2N=$clog2(CACHE_SIZE_N);
localparam CACHE_ADDR_W=$clog2(CACHE_SIZE_N);
localparam OFFSET_FIFO_WIDTH = 1 + ((NUM_WORD > 1)? OFFSET_WIDTH : 0) + (USECACHING? 1 + CACHE_ADDR_W : 0) + (UNALIGNED? UNALIGNED_SHIFT_WIDTH + 3 : 0) + (INCLUDE_BYTE_OFFSET? BYTE_SELECT_BITS : 0);
// I/O
input clk, reset;
input [UNALIGNED:0] i_in_cache;
input [CACHE_ADDR_W-1:0] i_cache_addr;
input [INPUT_AW-1:0] i_address;
input [BURST_CNT_WIDTH-1:0] i_burst_count;
input [OFFSET_WIDTH-1:0] i_word_offset;
input [BYTE_SELECT_BITS-1:0] i_byte_offset; // simulation
input [UNALIGNED_SHIFT_WIDTH-1:0] i_shift; // used only when UNALIGNED = 1
input i_second; // used only when UNALIGNED = 1
input i_2nd_valid; // used only when UNALIGNED = 1
input i_word_offset_valid;
input i_new_page;
input i_addr_valid;
input i_stall;
output logic [WIDTH-1:0] o_readdata;
output logic o_valid;
output reg o_stall;
output reg o_empty;
output o_ae;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output reg avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH/8-1:0] avm_byteenable;
input avm_readdatavalid;
output [BURST_CNT_WIDTH-1:0] avm_burstcount;
// offset fifo
wire [OFFSET_FIFO_WIDTH-1:0] offset_fifo_din;
wire [OFFSET_FIFO_WIDTH-1:0] offset_fifo_dout;
// req FIFO
wire rd_req_en;
wire req_fifo_ae, req_fifo_af, req_overflow, offset_overflow, rd_req_empty; // FIFO status
// end req FIFO
// output FIFO
wire rd_data_fifo;
reg R_rd_data;
wire rd_data_empty;
wire rd_offset;
wire offset_fifo_empty;
wire offset_af;
wire [UNALIGNED:0] d_in_cache;
wire rd_next_page;
wire [CACHE_ADDR_W-1:0] d_cache_addr;
wire [BYTE_SELECT_BITS-1:0] d_byte_offset; // for simulation
reg R_in_cache;
wire d_second, d_2nd_valid;
wire unalign_stall_offset, unalign_stall_data;
wire [UNALIGNED_SHIFT_WIDTH-1:0] d_shift;
wire [OFFSET_WIDTH-1 : 0] d_offset;
reg [OFFSET_WIDTH-1 : 0] R_offset;
reg [MWIDTH-1:0] R_avm_rd_data;
wire [MWIDTH-1:0] rd_data;
// end output FIFO
assign avm_address[AWIDTH - INPUT_AW - 1 : 0] = 0;
assign avm_byteenable = {(MWIDTH/8){1'b1}};
assign o_ae = req_fifo_ae;
assign rd_req_en = !avm_read | !avm_waitrequest;
always @(posedge clk or posedge reset) begin
if(reset) begin
o_empty = 1'b0;
avm_read <= 1'b0;
o_stall <= 1'b0;
end
else begin
o_empty <= rd_req_empty;
o_stall <= offset_af;
if(rd_req_en) avm_read <= !rd_req_empty;
end
end
generate
if(NUM_WORD > 1) begin : GEN_WORD_OFFSET_FIFO
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (OFFSET_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (OFFSET_FIFO_WIDTH),
.lpm_widthu (OFFSET_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON"),
.almost_full_value(OFFSET_FIFO_DEPTH - 10)
) offset_fifo (
.clock (clk),
.data (offset_fifo_din),
.wrreq (i_word_offset_valid),
.rdreq (rd_offset),
.usedw (offset_flv),
.empty (offset_fifo_empty),
.full (offset_overflow),
.q (offset_fifo_dout),
.almost_empty (),
.almost_full (offset_af),
.aclr (reset)
);
end
else begin : GEN_SINGLE_WORD_RD_NEXT
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (OFFSET_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (OFFSET_FIFO_WIDTH),
.lpm_widthu (OFFSET_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "OFF"), // not instantiate block ram
.almost_full_value(OFFSET_FIFO_DEPTH - 10)
) offset_fifo (
.clock (clk),
.data (offset_fifo_din),
.wrreq (i_word_offset_valid),
.rdreq (rd_offset),
.usedw (offset_flv),
.empty (offset_fifo_empty),
.full (offset_overflow),
.q (offset_fifo_dout),
.almost_empty (),
.almost_full (offset_af),
.aclr (reset)
);
end
endgenerate
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (REQUEST_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (REQUEST_FIFO_WIDTH),
.lpm_widthu (REQUEST_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON"),
.almost_full_value(20),
.almost_empty_value(3)
) rd_request_fifo (
.clock (clk),
.data ({i_address, i_burst_count}),
.wrreq (i_addr_valid),
.rdreq (rd_req_en),
.usedw (),
.empty (rd_req_empty),
.full (req_overflow),
.q ({avm_address[AWIDTH - 1: AWIDTH - INPUT_AW], avm_burstcount}),
.almost_empty (req_fifo_ae),
.almost_full (req_fifo_af),
.aclr (reset)
);
/*------------------------------
Generate output data
--------------------------------*/
reg offset_valid;
reg [1:0] o_valid_pre;
wire rd_next_page_en, downstream_stall, wait_data, offset_stall, data_stall, valid_hold;
generate
if(USECACHING) begin : ENABLE_CACHE
reg [MWIDTH-1:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "no_rw_check, M20K" */;
logic [MWIDTH-1:0] reused_data[2] ;
reg [CACHE_ADDR_W-1:0] R_cache_addr, R_cache_next;
if(NUM_WORD == 1) begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_2nd_valid, i_shift, i_second, i_cache_addr, i_in_cache, i_new_page};
assign {d_2nd_valid, d_shift, d_second, d_cache_addr, d_in_cache, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
else begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_byte_offset, i_2nd_valid, i_shift, i_second, i_word_offset, i_cache_addr, i_in_cache, i_new_page};
assign {d_byte_offset, d_2nd_valid, d_shift, d_second, d_offset, d_cache_addr, d_in_cache, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
if(UNALIGNED) begin : GEN_UNALIGNED
wire need_2nd_page;
reg [UNALIGNED_SHIFT_WIDTH-1:0] R_shift [3];
reg hold_dout;
reg R_second;
reg R_need_2nd_page;
reg [WIDTH*2-ALIGNMENT_WIDTH-1:0] data_int;
reg [WIDTH-1:0] R_o_readdata;
reg [1:0] R_2nd_valid;
reg second_part_in_cache;
wire [WIDTH-1:0] c0_data_h, rd_data_h, c0_data_mux, rd_data_mux;
wire [WIDTH-ALIGNMENT_WIDTH-1:0] c1_data_l, rd_data_l;
wire get_new_offset, offset_backpressure_stall ;
wire [CACHE_ADDR_W-1:0] caddr_next;
wire [1:0] rw_wire;
reg [1:0] rw;
reg [WIDTH-ALIGNMENT_WIDTH-1:0] R_c1_data_l;
assign need_2nd_page = |d_shift;
assign valid_hold = |o_valid_pre;
assign rw_wire[0] = d_cache_addr == R_cache_addr & R_rd_data;
assign rw_wire[1] = caddr_next == R_cache_addr & R_rd_data;
assign c0_data_h = rw[0]? rd_data[MWIDTH-1:MWIDTH-WIDTH] : reused_data[0][MWIDTH-1:MWIDTH-WIDTH];
assign c1_data_l = rw[1]? R_c1_data_l : reused_data[1][WIDTH-ALIGNMENT_WIDTH-1:0];
assign rd_data_h = rd_data[MWIDTH-1:MWIDTH-WIDTH];
assign rd_data_l = rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
assign c0_data_mux = rw[0]? rd_data >> R_offset*ALIGNMENT_WIDTH : reused_data[0] >> R_offset*ALIGNMENT_WIDTH ;
assign rd_data_mux = rd_data >> R_offset*ALIGNMENT_WIDTH;
assign caddr_next = d_cache_addr+1;
assign unalign_stall_offset = d_2nd_valid & !offset_backpressure_stall & !R_2nd_valid[0]; //it is a one-cc pulse
assign unalign_stall_data = R_2nd_valid[0];
assign get_new_offset = rd_offset | unalign_stall_offset;
assign offset_backpressure_stall = wait_data | downstream_stall & offset_valid;
assign offset_stall = offset_backpressure_stall | unalign_stall_offset;
assign data_stall = downstream_stall | unalign_stall_data;
assign wait_data = rd_next_page_en & rd_data_empty & !R_2nd_valid[0];
assign o_readdata = hold_dout? R_o_readdata : data_int[R_shift[2]*ALIGNMENT_WIDTH +: WIDTH];
always@(posedge clk or posedge reset)begin
if(reset) begin
o_valid_pre <= 2'b0;
o_valid <= 1'b0;
end
else begin
o_valid_pre[0] <= offset_valid & get_new_offset & (!need_2nd_page | !R_2nd_valid[0] & d_second);
if(i_stall & o_valid & o_valid_pre[0]) o_valid_pre[1] <= 1'b1;
else if(!i_stall) o_valid_pre[1] <= 1'b0;
if(o_valid_pre[0]) o_valid <= 1'b1;
else if(!i_stall) o_valid <= valid_hold;
end
end
always @(posedge clk) begin
if(R_rd_data) cache[R_cache_addr] <= rd_data;
if(get_new_offset) begin
{R_in_cache, R_offset, R_shift[0], R_second} <= {|d_in_cache, d_offset, d_shift, d_second};
R_cache_addr <= d_cache_addr;
R_cache_next <= caddr_next;
R_shift[1] <= R_shift[0];
R_need_2nd_page <= need_2nd_page;
second_part_in_cache <= !d_in_cache[0] & d_in_cache[1];
R_2nd_valid[1] <= R_2nd_valid[0];
`ifdef SIM_ONLY
if(d_in_cache[0]) reused_data[0] <= rw_wire[0]? 'x : cache[d_cache_addr];
reused_data[1] <= rw_wire[1]? 'x : cache[caddr_next];
`else
if(d_in_cache[0]) reused_data[0] <= cache[d_cache_addr];
reused_data[1] <= cache[caddr_next];
`endif
if(d_in_cache[1]) R_c1_data_l <= rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
end
// work-around to deal with read-during-write
if(!downstream_stall & (|d_in_cache)) rw <= rw_wire & d_in_cache;
if(!offset_backpressure_stall) R_2nd_valid[0] <= d_2nd_valid & !R_2nd_valid[0];
R_o_readdata <= o_readdata;
hold_dout <= i_stall & o_valid;
if(R_in_cache) begin
data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= c1_data_l;
data_int[WIDTH-1:0] <= second_part_in_cache? rd_data_h : R_need_2nd_page? c0_data_h : c0_data_mux;
end
else begin
if(R_second) data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= rd_data_l;
if(!R_second | R_2nd_valid[1]) data_int[WIDTH-1:0] <= R_need_2nd_page? rd_data_h : rd_data_mux;
end
R_shift[2] <= (R_in_cache | !R_second | R_2nd_valid[1])? R_shift[0] : R_shift[1];
end
end // end UNALIGNED
else begin : GEN_ALIGNED
reg [MWIDTH-1:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "no_rw_check, M20K" */;
assign valid_hold = o_valid;
assign offset_stall = wait_data | downstream_stall & offset_valid;
assign data_stall = downstream_stall;
assign wait_data = rd_next_page_en & rd_data_empty; // there is a valid offset, need data to demux
if(NUM_WORD == 1) assign o_readdata = R_in_cache? reused_data[0][WIDTH-1:0] : rd_data[WIDTH-1:0];
else assign o_readdata = R_in_cache? reused_data[0] >> R_offset*WORD_WIDTH: rd_data >> R_offset*WORD_WIDTH;
always @(posedge clk) begin
if(rd_offset) begin
R_cache_addr <= d_cache_addr;
R_in_cache <= d_in_cache & !(R_rd_data & R_cache_addr == d_cache_addr);
R_offset <= d_offset;
// registered cache input and output to infer megafunction RAM
`ifdef SIM_ONLY // for simulation accuracy
reused_data[0] <= (d_cache_addr == R_cache_addr & R_rd_data)? 'x : cache[d_cache_addr]; // read during write
`else
reused_data[0] <= cache[d_cache_addr];
`endif
end
else if(R_rd_data & R_cache_addr == d_cache_addr) R_in_cache <= 1'b0; // read during write
if(R_rd_data) cache[R_cache_addr] <= rd_data; // update cache
end
always@(posedge clk or posedge reset)begin
if(reset) o_valid <= 1'b0;
else if(!i_stall | !o_valid) o_valid <= rd_offset & offset_valid;
end
end // end ALIGNED
end // end USECACHING
else begin : DISABLE_CACHE
if(NUM_WORD == 1) begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_2nd_valid, i_shift, i_second, i_new_page};
assign {d_2nd_valid, d_shift, d_second, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
else begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_byte_offset, i_2nd_valid, i_shift, i_second, i_word_offset, i_new_page};
assign {d_byte_offset, d_2nd_valid, d_shift, d_second, d_offset, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
if(UNALIGNED) begin : GEN_UNALIGNED
wire need_2nd_page;
reg [UNALIGNED_SHIFT_WIDTH-1:0] R_shift [3];
reg hold_dout;
reg R_second;
reg R_need_2nd_page;
reg [WIDTH*2-ALIGNMENT_WIDTH-1:0] data_int;
reg [WIDTH-1:0] R_o_readdata;
reg [1:0] R_2nd_valid;
wire [WIDTH-1:0] rd_data_h, rd_data_mux;
wire [WIDTH-ALIGNMENT_WIDTH-1:0] rd_data_l;
wire get_new_offset, offset_backpressure_stall;
assign need_2nd_page = |d_shift;
assign valid_hold = |o_valid_pre;
assign rd_data_h = rd_data[MWIDTH-1:MWIDTH-WIDTH];
assign rd_data_l = rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
assign rd_data_mux = rd_data >> R_offset*ALIGNMENT_WIDTH;
assign unalign_stall_offset = d_2nd_valid & !offset_backpressure_stall & !R_2nd_valid[0]; //it is a one-cc pulse
assign unalign_stall_data = R_2nd_valid[0];
assign get_new_offset = rd_offset | unalign_stall_offset;
assign offset_backpressure_stall = wait_data | downstream_stall & offset_valid;
assign offset_stall = offset_backpressure_stall | unalign_stall_offset;
assign data_stall = downstream_stall | unalign_stall_data;
assign wait_data = rd_next_page_en & rd_data_empty & !R_2nd_valid[0];
assign o_readdata = hold_dout? R_o_readdata : data_int >> R_shift[2]*ALIGNMENT_WIDTH;
always@(posedge clk or posedge reset)begin
if(reset) begin
o_valid_pre <= 2'b0;
o_valid <= 1'b0;
end
else begin
o_valid_pre[0] <= offset_valid & get_new_offset & (!need_2nd_page | !R_2nd_valid[0] & d_second);
if(i_stall & o_valid & o_valid_pre[0]) o_valid_pre[1] <= 1'b1;
else if(!i_stall) o_valid_pre[1] <= 1'b0;
if(o_valid_pre[0]) o_valid <= 1'b1;
else if(!i_stall) o_valid <= valid_hold;
end
end
always @(posedge clk) begin
if(get_new_offset) begin
{R_offset, R_shift[0], R_second} <= {d_offset, d_shift, d_second};
R_shift[1] <= R_shift[0];
R_need_2nd_page <= need_2nd_page;
R_2nd_valid[1] <= R_2nd_valid[0];
end
if(!offset_backpressure_stall) R_2nd_valid[0] <= d_2nd_valid & !R_2nd_valid[0];
R_o_readdata <= o_readdata;
hold_dout <= i_stall & o_valid;
if(R_second) data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= rd_data_l;
if(!R_second | R_2nd_valid[1]) data_int[WIDTH-1:0] <= R_need_2nd_page? rd_data_h : rd_data_mux;
R_shift[2] <= (!R_second | R_2nd_valid[1])? R_shift[0] : R_shift[1];
end
end // end GEN_UNALIGNED
else begin : GEN_ALIGNED
assign valid_hold = o_valid;
assign offset_stall = wait_data | downstream_stall & offset_valid;
assign data_stall = downstream_stall;
assign wait_data = rd_next_page_en & rd_data_empty; // there is a valid offset, need data to demux
if(NUM_WORD == 1) assign o_readdata = rd_data[WIDTH-1:0];
else assign o_readdata = rd_data >> R_offset*WORD_WIDTH;
always @(posedge clk) begin
if(rd_offset) R_offset <= d_offset;
end
always@(posedge clk or posedge reset)begin
if(reset) o_valid <= 1'b0;
else if(!i_stall | !o_valid) o_valid <= rd_offset & offset_valid;
end
end // end GEN_ALIGNED
end // end DISABLE_CACHE
endgenerate
assign downstream_stall = i_stall & valid_hold;
assign rd_next_page_en = offset_valid & rd_next_page;
assign rd_offset = !offset_stall;
assign rd_data_fifo = rd_next_page_en & !data_stall;
always@(posedge clk or posedge reset)begin
if(reset) begin
offset_valid <= 1'b0;
R_rd_data <= 1'b0;
end
else begin
if(rd_offset) offset_valid <= !offset_fifo_empty;
R_rd_data <= rd_data_fifo & !rd_data_empty;
end
end
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (WIDE_FIFO_DEPTH),
.almost_full_value(WIDE_FIFO_DEPTH_THRESH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (MWIDTH),
.lpm_widthu (WIDE_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON")
) rd_back_wfifo (
.clock (clk),
.data (avm_readdata),
.wrreq (avm_readdatavalid),
.rdreq (rd_data_fifo),
.usedw (),
.empty (rd_data_empty),
.full (),
.q (rd_data),
.almost_empty (),
.almost_full (),
.aclr (reset)
);
endmodule
module acl_stall_free_coalescer (
clk, // clock
reset, // reset
i_valid, // valid address
i_empty, // request FIFO is empty
i_addr, // input address
o_page_addr, // output page address
o_page_addr_valid, // page address valid
o_num_burst, // number of burst
o_new_page
);
parameter AW = 1,
PAGE_AW = 1,
MAX_BURST = 1,
TIME_OUT = 1,
MAX_THREAD = 1,
CACHE_LAST = 0,
DISABLE_COALESCE = 0;
localparam BURST_CNT_WIDTH = $clog2(MAX_BURST+1);
localparam TIME_OUT_W = $clog2(TIME_OUT+1);
localparam THREAD_W = $clog2(MAX_THREAD+1);
input clk;
input reset;
input i_valid;
input i_empty;
input [AW-1:0] i_addr;
// all output signals are registered to help P&R
output reg [PAGE_AW-1:0] o_page_addr;
output reg o_page_addr_valid;
output reg [BURST_CNT_WIDTH-1:0] o_num_burst;
output reg o_new_page;
logic init;
wire match_current_wire, match_next_wire, reset_cnt;
reg [BURST_CNT_WIDTH-1:0] num_burst;
reg valid_burst;
wire [PAGE_AW-1:0] page_addr;
reg [PAGE_AW-1:0] R_page_addr = 0;
reg [PAGE_AW-1:0] R_page_addr_next = 0;
reg [PAGE_AW-1:0] addr_hold = 0;
reg [3:0] delay_cnt; // it takes 5 clock cycles from o_page_addr_valid to being read out from FIFO (if avm_stall = 0), assuming 3 extra clock cycles to reach global mem
reg [TIME_OUT_W-1:0] time_out_cnt = 0;
reg [THREAD_W-1:0] thread_cnt = 0;
wire time_out;
wire max_thread;
assign page_addr = i_addr[AW-1:AW-PAGE_AW]; // page address
assign match_current_wire = page_addr == R_page_addr;
assign max_thread = thread_cnt[THREAD_W-1] & i_empty;
assign time_out = time_out_cnt[TIME_OUT_W-1] & i_empty;
assign reset_cnt = valid_burst & (
num_burst[BURST_CNT_WIDTH-1] // reach max burst
| time_out
| max_thread
| !match_current_wire & !match_next_wire & !init & i_valid ); // new burst
generate
if(MAX_BURST == 1) begin : BURST_ONE
assign match_next_wire = 1'b0;
end
else begin : BURST_N
assign match_next_wire = page_addr == R_page_addr_next & !init & i_valid & (|page_addr[BURST_CNT_WIDTH-2:0]);
end
if(DISABLE_COALESCE) begin : GEN_DISABLE_COALESCE
always@(*) begin
o_page_addr = page_addr;
o_page_addr_valid = i_valid;
o_num_burst = 1;
o_new_page = 1'b1;
end
end
else begin : ENABLE_COALESCE
always@(posedge clk) begin
if(i_valid) begin
R_page_addr <= page_addr;
R_page_addr_next <= page_addr + 1'b1;
end
o_num_burst <= num_burst;
o_page_addr <= addr_hold;
if(i_valid | reset_cnt) time_out_cnt <= 0; // nop is valid thread, should reset time_out counter too
else if(!time_out_cnt[TIME_OUT_W-1] & valid_burst) time_out_cnt <= time_out_cnt + 1;
if(reset_cnt) thread_cnt <= i_valid;
else if(i_valid & !thread_cnt[THREAD_W-1]) thread_cnt <= thread_cnt + 1;
if(o_page_addr_valid) delay_cnt <= 1;
else if(!delay_cnt[3]) delay_cnt <= delay_cnt + 1;
if(reset_cnt) begin
num_burst <= i_valid & !match_current_wire;
addr_hold <= page_addr;
end
else if(i_valid) begin
num_burst <= (!valid_burst & !match_current_wire | init)? 1 : num_burst + match_next_wire;
if(!valid_burst | init) addr_hold <= page_addr;
end
o_new_page <= (!match_current_wire| init) & i_valid;
end
always@(posedge clk or posedge reset) begin
if(reset) begin
o_page_addr_valid <= 1'b0;
valid_burst <= 1'b0;
end
else begin
if(reset_cnt) valid_burst <= i_valid & !match_current_wire;
else if(i_valid) begin
if(!valid_burst & !match_current_wire | init) valid_burst <= 1'b1;
else if(match_next_wire) valid_burst <= 1'b1;
end
o_page_addr_valid <= reset_cnt;
end
end
end
if(CACHE_LAST) begin : GEN_ENABLE_CACHE
always@(posedge clk or posedge reset) begin
if(reset) init <= 1'b1;
else begin
if(!valid_burst & !o_page_addr_valid & (!i_valid | match_current_wire & !init)) init <= 1'b1; // set init to 1 when the previous request is read out
else if(i_valid) init <= 1'b0;
end
end
end
else begin : GEN_DISABLE_CACHE
always@(posedge clk or posedge reset) begin
if(reset) init <= 1'b1;
else begin
if(!valid_burst & delay_cnt[3] & !o_page_addr_valid & i_empty & (!i_valid | match_current_wire & !init)) init <= 1'b1; // set init to 1 when the previous request is read out
else if(i_valid) init <= 1'b0;
end
end
end
endgenerate
endmodule
module lsu_bursting_write
(
clk, clk2x, reset, o_stall, i_valid, i_nop, i_address, i_writedata, i_stall, o_valid,
i_2nd_offset,
i_2nd_data,
i_2nd_byte_en,
i_2nd_en,
i_thread_valid,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest,
avm_burstcount,
i_byteenable
);
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // The max number of live threads
parameter MEMORY_SIDE_MEM_LATENCY=32; // The latency to get to the iface (no response needed from DDR, we generate writeack right before the iface).
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter USE_WRITE_ACK=0; // Wait till the write has actually made it to global memory
parameter HIGH_FMAX=1;
parameter USE_BYTE_EN=0;
parameter UNALIGN=0;
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam ALIGNMENT_ABYTES=2**ALIGNMENT_ABITS;
/********
* Ports *
********/
// Standard global signals
input clk;
input clk2x;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// used for unaligned
input [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] i_2nd_offset;
input [WIDTH-1:0] i_2nd_data;
input [WIDTH_BYTES-1:0] i_2nd_byte_en;
input i_2nd_en;
input i_thread_valid;
// Downstream interface
input i_stall;
output o_valid;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
input [WIDTH_BYTES-1:0] i_byteenable;
// Byte enable control
reg reg_lsu_i_valid, reg_lsu_i_thread_valid;
reg [AWIDTH-1:0] reg_lsu_i_address;
reg [WIDTH-1:0] reg_lsu_i_writedata;
reg [WIDTH_BYTES-1:0] reg_lsu_i_byte_enable;
reg reg_common_burst, reg_lsu_i_2nd_en;
reg reg_i_nop;
reg [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] reg_lsu_i_2nd_offset;
reg [WIDTH-1:0]reg_lsu_i_2nd_data;
reg [WIDTH_BYTES-1:0] reg_lsu_i_2nd_byte_en;
wire stall_signal_directly_from_lsu;
assign o_stall = reg_lsu_i_valid & stall_signal_directly_from_lsu;
// --------------- Pipeline stage : Burst Checking --------------------
always@(posedge clk or posedge reset)
begin
if (reset)
begin
reg_lsu_i_valid <= 1'b0;
reg_lsu_i_thread_valid <= 1'b0;
end
else
begin
if (~o_stall) begin
reg_lsu_i_valid <= i_valid;
reg_lsu_i_thread_valid <= i_thread_valid;
end
end
end
always@(posedge clk) begin
if (~o_stall & i_valid & ~i_nop) reg_lsu_i_address <= i_address;
if (~o_stall) begin
reg_i_nop <= i_nop;
reg_lsu_i_writedata <= i_writedata;
reg_lsu_i_byte_enable <= i_byteenable;
reg_lsu_i_2nd_offset <= i_2nd_offset;
reg_lsu_i_2nd_en <= i_2nd_en;
reg_lsu_i_2nd_data <= i_2nd_data;
reg_lsu_i_2nd_byte_en <= i_2nd_byte_en;
reg_common_burst <= i_nop | (reg_lsu_i_address[AWIDTH-1:BYTE_SELECT_BITS+BURSTCOUNT_WIDTH-1] == i_address[AWIDTH-1:BYTE_SELECT_BITS+BURSTCOUNT_WIDTH-1]);
end
end
// -------------------------------------------------------------------
lsu_bursting_write_internal #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USE_WRITE_ACK(USE_WRITE_ACK),
.USE_BYTE_EN(USE_BYTE_EN),
.UNALIGN(UNALIGN),
.HIGH_FMAX(HIGH_FMAX)
) bursting_write (
.clk(clk),
.clk2x(clk2x),
.reset(reset),
.i_nop(reg_i_nop),
.o_stall(stall_signal_directly_from_lsu),
.i_valid(reg_lsu_i_valid),
.i_thread_valid(reg_lsu_i_thread_valid),
.i_address(reg_lsu_i_address),
.i_writedata(reg_lsu_i_writedata),
.i_2nd_offset(reg_lsu_i_2nd_offset),
.i_2nd_data(reg_lsu_i_2nd_data),
.i_2nd_byte_en(reg_lsu_i_2nd_byte_en),
.i_2nd_en(reg_lsu_i_2nd_en),
.i_stall(i_stall),
.o_valid(o_valid),
.o_active(o_active),
.i_byteenable(reg_lsu_i_byte_enable),
.avm_address(avm_address),
.avm_write(avm_write),
.avm_writeack(avm_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_waitrequest(avm_waitrequest),
.common_burst(reg_common_burst)
);
endmodule
//
// Burst coalesced write module
// Again, top level comments later
//
module lsu_bursting_write_internal
(
clk, clk2x, reset, o_stall, i_valid, i_nop, i_address, i_writedata, i_stall, o_valid,
o_active, //Debugging signal
i_2nd_offset,
i_2nd_data,
i_2nd_byte_en,
i_2nd_en,
i_thread_valid,
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest,
avm_burstcount,
i_byteenable,
common_burst
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter MEMORY_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter USE_WRITE_ACK=0; // Wait till the write has actually made it to global memory
parameter HIGH_FMAX=1;
parameter USE_BYTE_EN=0;
parameter UNALIGN=0;
// WARNING: Kernels will hang if InstrDataDep claims that a store
// has more capacity than this number
//
parameter MAX_CAPACITY=128; // Must be a power-of-2 to keep things simple
// Derived parameters
localparam MAX_BURST=2**(BURSTCOUNT_WIDTH-1);
//
// Notice that in the non write ack case, the number of threads seems to be twice the sensible number
// This is because MAX_THREADS is usually the limiter on the counter width. Once one request is assemembled,
// we want to be able to start piplining another burst. Thus the factor of 2.
// The MEMORY_SIDE_MEM_LATENCY will further increase this depth if the compiler
// thinks the lsu will see a lot of contention on the Avalon side.
//
localparam __WRITE_FIFO_DEPTH = (WIDTH_BYTES==MWIDTH_BYTES) ? 3*MAX_BURST : 2*MAX_BURST;
// No reason this should need more than max MLAB depth
localparam _WRITE_FIFO_DEPTH = ( __WRITE_FIFO_DEPTH < 64 ) ? __WRITE_FIFO_DEPTH : 64;
// Need at least 4 to account for fifo push-to-pop latency
localparam WRITE_FIFO_DEPTH = ( _WRITE_FIFO_DEPTH > 8 ) ? _WRITE_FIFO_DEPTH : 8;
// If writeack, make this equal to
localparam MAX_THREADS=(USE_WRITE_ACK ? KERNEL_SIDE_MEM_LATENCY - MEMORY_SIDE_MEM_LATENCY : (2*MWIDTH_BYTES/WIDTH_BYTES*MAX_BURST)); // Maximum # of threads to group into a burst request
//
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH=8*SEGMENT_WIDTH_BYTES;
localparam NUM_WORD = MWIDTH_BYTES/SEGMENT_WIDTH_BYTES;
localparam UNALIGN_BITS = $clog2(WIDTH_BYTES)-ALIGNMENT_ABITS;
// Constants
localparam COUNTER_WIDTH=(($clog2(MAX_THREADS)+1 < $clog2(MAX_CAPACITY+1)) ?
$clog2(MAX_CAPACITY+1) : ($clog2(MAX_THREADS)+1)); // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input clk2x;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// used for unaligned
input [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] i_2nd_offset;
input [WIDTH-1:0] i_2nd_data;
input [WIDTH_BYTES-1:0] i_2nd_byte_en;
input i_2nd_en;
input i_thread_valid;
// Downstream interface
input i_stall;
output o_valid;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
// Byte enable control
input [WIDTH_BYTES-1:0] i_byteenable;
// Help from outside
input common_burst;
/***************
* Architecture *
***************/
wire [WIDTH_BYTES-1:0] word_byte_enable;
wire [WIDTH-1:0] word_bit_enable, word2_bit_enable;
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire c_page_done;
wire c_nop;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
// Replicated version of the occ and stores counters that decrement instead of increment
// This allows me to check the topmost bit to determine if the counter is non-empty
reg [COUNTER_WIDTH-1:0] nop_cnt;
reg [COUNTER_WIDTH-1:0] occ_counter_neg;
reg [COUNTER_WIDTH-1:0] ack_counter_neg;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire w_fifo_full;
wire [BURSTCOUNT_WIDTH-1:0] c_burstcount;
// Track the current item in the write burst since we issue c_burstcount burst reqs
reg [BURSTCOUNT_WIDTH-1:0] burstcounter;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
assign word_byte_enable = i_nop? '0: (USE_BYTE_EN ? i_byteenable :{WIDTH_BYTES{1'b1}}) ;
generate
genvar byte_num;
for( byte_num = 0; byte_num < WIDTH_BYTES; byte_num++)
begin : biten
assign word_bit_enable[(byte_num+1)*8-1: byte_num*8] = {8{word_byte_enable[byte_num]}};
assign word2_bit_enable[(byte_num+1)*8-1: byte_num*8] = {8{i_2nd_byte_en[byte_num]}};
end
endgenerate
wire oc_full;
wire cnt_valid;
wire coalescer_active;
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
bursting_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(16),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.MAXBURSTCOUNT(MAX_BURST),
.MAX_THREADS(MAX_THREADS)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full && !w_fifo_full),
.i_nop(i_nop),
.o_stall(c_stall),
.o_start_nop(c_nop), // new burst starts with nop
.o_new_page(c_new_page),
.o_page_done(c_page_done),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(w_fifo_full),
.o_burstcount(c_burstcount),
.common_burst(common_burst),
.o_active(coalescer_active)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
if(UNALIGN) begin : GEN_UNALIGN
assign cnt_valid = i_thread_valid;
always@(*) begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_bite = {MWIDTH{1'b0}};
if(i_2nd_en) begin
wm_wide_wdata[WIDTH-1:0] = i_2nd_data;
wm_wide_wdata = wm_wide_wdata << (i_2nd_offset*SEGMENT_WIDTH);
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_be[WIDTH_BYTES-1:0] = i_2nd_byte_en;
wm_wide_be = wm_wide_be << (i_2nd_offset*SEGMENT_WIDTH_BYTES);
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_bite[WIDTH-1:0] = word2_bit_enable;
wm_wide_bite = wm_wide_bite << (i_2nd_offset*SEGMENT_WIDTH);
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
end
else begin
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_wdata = wm_wide_wdata << (segment_select*SEGMENT_WIDTH);
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_be = wm_wide_be << (segment_select*SEGMENT_WIDTH_BYTES);
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
wm_wide_bite = wm_wide_bite << (segment_select*SEGMENT_WIDTH);
end
end
end // end GEN_UNALIGN
else begin: GEN_ALIGN
assign cnt_valid = i_valid;
always@(*) begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_wdata = wm_wide_wdata << (segment_select*SEGMENT_WIDTH);
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_be = wm_wide_be << (segment_select*SEGMENT_WIDTH_BYTES);
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
wm_wide_bite = wm_wide_bite << (segment_select*SEGMENT_WIDTH);
end
end
end
else
begin
assign cnt_valid = i_valid;
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = word_byte_enable;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = word_bit_enable;
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
wire [COUNTER_WIDTH-1:0] num_threads_written;
// This FIFO stores the actual data to be written
//
//
wire w_data_fifo_full, req_fifo_empty;
wire wr_page = c_page_done & !w_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(COUNTER_WIDTH+MWIDTH+MWIDTH_BYTES),
.DEPTH(WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) req_fifo (
.clock(clk),
.resetn(~reset),
.data_in( {wm_writedata,wm_byteenable} ),
.valid_in( wr_page ),
.data_out( {avm_writedata,avm_byteenable} ),
.stall_in( ~write_accepted ),
.stall_out( w_data_fifo_full ),
.empty(req_fifo_empty)
);
// This FIFO stores the number of valid's to release with each writeack
//
wire w_ack_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(COUNTER_WIDTH),
.DEPTH(2*WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) ack_fifo (
.clock(clk),
.resetn(~reset),
.data_in( next_counter),
.valid_in( wr_page ),
.data_out( num_threads_written ),
.stall_in( !avm_writeack),
.stall_out( w_ack_fifo_full )
);
// This FIFO hold the request information { address & burstcount }
//
wire w_fifo_stall_in;
assign w_fifo_stall_in = !(write_accepted && (burstcounter == avm_burstcount));
wire w_request_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(PAGE_SELECT_BITS+BURSTCOUNT_WIDTH),
.DEPTH(WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) req_fifo2 (
.clock(clk),
.resetn(~reset),
.data_in( {c_req_addr,c_burstcount} ),
.valid_in( c_req_valid & !w_fifo_full ), // The basical coalescer stalls on w_fifo_full holding c_req_valid high
.data_out( {avm_address[AWIDTH-1: BYTE_SELECT_BITS],avm_burstcount} ),
.valid_out( avm_write ),
.stall_in( w_fifo_stall_in ),
.stall_out( w_request_fifo_full )
);
assign avm_address[BYTE_SELECT_BITS-1:0] = '0;
// The w_fifo_full is the OR of the data or request fifo's being full
assign w_fifo_full = w_data_fifo_full | w_request_fifo_full | w_ack_fifo_full;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
reg pending_nop;
wire pending_cc = nop_cnt != occ_counter;
wire burst_start_nop = cnt_valid & c_nop & !o_stall;
wire start_with_nop = !pending_cc && i_nop && cnt_valid && !o_stall; // nop starts when there are no pending writes
wire normal_cc_valid = cnt_valid && !o_stall && !i_nop;
wire clear_nop_cnt = normal_cc_valid || !pending_cc;
assign input_accepted = cnt_valid && !o_stall && !(c_nop || start_with_nop);
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
wire [8:0] ack_pending = {1'b1, {COUNTER_WIDTH{1'b0}}} - ack_counter;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
occ_counter_neg <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter_neg <= '0;
nop_cnt <= '0;
burstcounter <= 6'b000001;
o_active <= 1'b0;
pending_nop <= 1'b0;
end
else
begin
if(clear_nop_cnt) begin
nop_cnt <= '0;
pending_nop <= 1'b0;
end
else if(!start_with_nop) begin
nop_cnt <= nop_cnt + burst_start_nop;
if(burst_start_nop) pending_nop <= 1'b1;
end
occ_counter <= occ_counter + (cnt_valid && !o_stall) - output_acknowledged;
occ_counter_neg <= occ_counter_neg - (cnt_valid && !o_stall) + output_acknowledged;
next_counter <= input_accepted + (c_page_done ? {COUNTER_WIDTH{1'b0}} : next_counter) + (normal_cc_valid? nop_cnt : 0);
if(USE_WRITE_ACK) begin
ack_counter <= ack_counter
- (avm_writeack? num_threads_written : 0)
- ( (!pending_cc & !normal_cc_valid)? nop_cnt : 0)
- start_with_nop
+ output_acknowledged;
o_active <= occ_counter_neg[COUNTER_WIDTH-1];
end
else begin
ack_counter <= ack_counter - (cnt_valid && !o_stall) + output_acknowledged;
ack_counter_neg <= ack_counter_neg - wr_page + avm_writeack;
o_active <= occ_counter_neg[COUNTER_WIDTH-1] | ack_counter_neg[COUNTER_WIDTH-1] | coalescer_active; // do not use num_threads_written, because it takes extra resource
end
burstcounter <= write_accepted ? ((burstcounter == avm_burstcount) ? 6'b000001 : burstcounter+1) : burstcounter;
end
end
assign oc_full = occ_counter[COUNTER_WIDTH-1];
// Pipeline control signals
assign o_stall = oc_full || c_stall || w_fifo_full;
assign o_valid = ack_counter[COUNTER_WIDTH-1];
endmodule
// BURST COALESCING MODULE
//
// Similar to the basic coalescer but supports checking if accesses are in consecutive DRAM "pages"
// Supports the ad-hocly discovered protocols for bursting efficiently with avalaon
// - Don't burst from an ODD address
// - If not on a burst boundary, then just burst up to the next burst bondary
//
// Yes, I know, this could be incorporated into the basic coalescer. But that's really not my "thing"
//
module bursting_coalescer
(
clk, reset, i_page_addr, i_nop, i_valid, o_stall, o_new_page, o_page_done, o_req_addr, o_burstcount,
o_req_valid, i_stall, o_start_nop,
common_burst,
// For the purposes of maintaining latency correctly, we need to know if total # of threads
// accepted by the caching LSU
i_input_accepted_from_wrapper_lsu,
i_reset_timeout,
o_active
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8;
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter MAXBURSTCOUNT=32; // This isn't the max supported by Avalon, but the max that the instantiating module needs
parameter MAX_THREADS=64; // Must be a power of 2
parameter USECACHING=0;
localparam SLAVE_MAX_BURST=2**(BURSTCOUNT_WIDTH-1);
localparam THREAD_COUNTER_WIDTH=$clog2(MAX_THREADS+1);
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_nop;
input i_valid;
output o_stall;
output o_new_page;
output o_page_done;
output o_start_nop;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
output [BURSTCOUNT_WIDTH-1:0] o_burstcount;
input i_stall;
input common_burst;
input i_input_accepted_from_wrapper_lsu;
input i_reset_timeout;
output o_active;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg [PAGE_ADDR_WIDTH-1:0] last_page_addr;
reg [PAGE_ADDR_WIDTH-1:0] last_page_addr_p1;
reg [BURSTCOUNT_WIDTH-1:0] burstcount;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
reg [THREAD_COUNTER_WIDTH-1:0] thread_counter;
generate if(USECACHING)
begin
assign timeout = timeout_counter[$clog2(TIMEOUT)] | thread_counter[THREAD_COUNTER_WIDTH-1];
end
else
begin
assign timeout = timeout_counter[$clog2(TIMEOUT)];
end
endgenerate
// Internal signal logic
wire match_burst_address;
wire match_next_page;
wire match_current_page;
generate
if ( BURSTCOUNT_WIDTH > 1 )
begin
assign match_next_page = (i_page_addr[BURSTCOUNT_WIDTH-2:0] === last_page_addr_p1[BURSTCOUNT_WIDTH-2:0]) && (|last_page_addr_p1[BURSTCOUNT_WIDTH-2:0]);
assign match_current_page = (i_page_addr[BURSTCOUNT_WIDTH-2:0] === last_page_addr[BURSTCOUNT_WIDTH-2:0]);
end
else
begin
assign match_next_page = 1'b0;
assign match_current_page = 1'b1;
end
endgenerate
assign match_burst_address = common_burst;//(i_page_addr[PAGE_ADDR_WIDTH-1:BURSTCOUNT_WIDTH-1] == last_page_addr[PAGE_ADDR_WIDTH-1:BURSTCOUNT_WIDTH-1]);
assign match = (match_burst_address && (match_current_page || match_next_page)) && !thread_counter[THREAD_COUNTER_WIDTH-1];
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
wire input_accepted = i_valid && !o_stall;
assign o_start_nop = i_nop & ready;
assign o_active = valid;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
last_page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
last_page_addr_p1 <= {PAGE_ADDR_WIDTH{1'b0}};
burstcount <= 1;
valid <= 1'b0;
timeout_counter <= 0;
thread_counter <= {THREAD_COUNTER_WIDTH{1'b0}};
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
last_page_addr <= ready ? i_page_addr : (input_accepted && match_next_page ? i_page_addr : last_page_addr );
last_page_addr_p1 <= ready ? i_page_addr+1 : (input_accepted && match_next_page ? i_page_addr+1 : last_page_addr_p1 );
valid <= ready ? i_valid & !i_nop : valid; // burst should not start with nop thread
burstcount <= ready ? 6'b000001 : (input_accepted && match_next_page ? burstcount+1 : burstcount );
thread_counter <= ready ? 1 : (USECACHING ?
(i_input_accepted_from_wrapper_lsu && !thread_counter[THREAD_COUNTER_WIDTH-1] ? thread_counter+1 : thread_counter ) :
(input_accepted ? thread_counter+1 : thread_counter));
if( USECACHING && i_reset_timeout || !USECACHING && i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = !match && !ready && i_valid;
// We're starting a new page (used by loads)
assign o_new_page = ready || i_valid && match_burst_address && !thread_counter[THREAD_COUNTER_WIDTH-1] && match_next_page;
assign o_req_addr = page_addr;
assign o_burstcount = burstcount;
assign o_req_valid = valid && !waiting;
// We're just finished with a page (used by stores)
assign o_page_done = valid && !waiting && !i_stall || !ready && i_valid && match_burst_address && !thread_counter[THREAD_COUNTER_WIDTH-1] && match_next_page;
endmodule
|
module lsu_bursting_read
(
clk, clk2x, reset, flush, i_nop, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, //Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid,
avm_burstcount,
// Profiling
extra_unaligned_reqs,
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=8; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=64; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=$clog2(WIDTH_BYTES); // Request address alignment (address bits)
parameter DEVICE = "Stratix V"; // DEVICE
parameter BURSTCOUNT_WIDTH=5; // MAX BURST = 2**(BURSTCOUNT_WIDTH-1)
parameter KERNEL_SIDE_MEM_LATENCY=1; // Effective Latency in cycles as seen by the kernel pipeline
parameter MEMORY_SIDE_MEM_LATENCY = 1; // Latency in cycles between LSU and memory
parameter MAX_THREADS=64; // Maximum # of threads to group into a burst request
parameter TIME_OUT=8; // Time out counter max
parameter USECACHING = 0; // Enable internal cache
parameter CACHE_SIZE_N=1024; // Cache depth (width = WIDTH_BYTES)
parameter ACL_PROFILE = 0; // Profiler
parameter HIGH_FMAX = 1; // Add pipeline to io if set to 1
parameter UNALIGNED = 0; // Output word unaligned
/*****************
* Local Parameters *
*****************/
localparam MAX_BURST = 2**(BURSTCOUNT_WIDTH-1);
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam A_BYTES = 2**ALIGNMENT_ABITS;
localparam WORD_BYTES = (WIDTH_BYTES >= A_BYTES & (UNALIGNED == 0))? WIDTH_BYTES : A_BYTES;
localparam NUM_WORD = MWIDTH_BYTES / WORD_BYTES;
localparam MB_W=$clog2(MWIDTH_BYTES);
localparam OB_W = $clog2(WIDTH_BYTES);
localparam PAGE_ADDR_WIDTH = AWIDTH - MB_W;
localparam OFFSET_WIDTH = $clog2(NUM_WORD);
localparam CACHE_ADDR_W=$clog2(CACHE_SIZE_N);
localparam CACHE_BASE_ADDR_W = AWIDTH-MB_W-CACHE_ADDR_W;
localparam UNALIGNED_DIV_ALIGN = WIDTH_BYTES / A_BYTES;
localparam UNALIGNED_SELECTION_BITS=$clog2(UNALIGNED_DIV_ALIGN);
// Standard global signals
input clk;
input clk2x;
input reset;
input flush;
input i_nop;
// Upstream interface
output logic o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
// Profiling
output logic extra_unaligned_reqs;
output logic req_cache_hit_count;
// internal signals
logic stall_pre;
wire reg_valid;
wire reg_nop;
wire [AWIDTH-1:0] reg_address;
// registed to help P&R
logic R_valid, R_nop;
wire [AWIDTH-1:0] addr_next_wire;
logic [AWIDTH-1:0] R_addr, R_addr_next, R_addr_next_hold;
// cache status
reg [CACHE_BASE_ADDR_W:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "M20K" */;
wire [1:0] in_cache_pre;
logic [CACHE_BASE_ADDR_W-1:0] cached_tag [2];
wire [CACHE_BASE_ADDR_W-1:0] R_tag [2];
wire [CACHE_ADDR_W-1:0] rd_c_index [2];
wire [CACHE_ADDR_W-1:0] wr_c_index;
logic cached_tag_valid [2];
wire tag_match [2];
wire consecutive;
reg cache_ready;
logic [1:0] in_cache;
wire [MB_W-1:0] byte_offset;
reg include_2nd_part;
logic update_cache;
logic [CACHE_BASE_ADDR_W-1:0] new_tag;
logic issue_2nd_word;
reg issue_2nd_hold;
logic need_2_page;
wire stall_int;
wire need_2_cc;
wire [UNALIGNED_SELECTION_BITS-1:0] shift;
logic [AWIDTH-1:0] lsu_i_address;
reg p_valid;
reg [AWIDTH-1:0] p_addr;
reg [1:0] R_consecutive;
reg [63:0] non_align_hit_cache;
// coalesced addr
wire [BURSTCOUNT_WIDTH-1:0]c_burstcount;
wire [PAGE_ADDR_WIDTH-1:0] c_page_addr;
wire c_req_valid;
wire c_new_page;
logic [OFFSET_WIDTH-1 : 0] p_offset, c_word_offset;
logic p_offset_valid;
reg [CACHE_ADDR_W-1:0] R_cache_addr;
// fifo
reg fifo_din_en;
reg [1:0] fi_in_cache;
reg [CACHE_ADDR_W-1:0] fi_cached_addr;
reg [UNALIGNED_SELECTION_BITS-1:0] fi_shift;
reg fi_second, fi_2nd_valid;
reg [UNALIGNED_SELECTION_BITS-1:0] R_shift;
reg [MB_W-1:0] fi_byte_offset;
wire p_ae;
generate
if(HIGH_FMAX) begin: GEN_PIPE_INPUT
acl_io_pipeline #(
.WIDTH(1+AWIDTH)
) in_pipeline (
.clk(clk),
.reset(reset),
.i_stall(stall_pre),
.i_valid(i_valid),
.i_data({i_nop, i_address}),
.o_stall(o_stall),
.o_valid(reg_valid),
.o_data({reg_nop, reg_address})
);
end
else begin : GEN_FAST_INPUT
assign {reg_valid, reg_nop, reg_address} = {i_valid, i_nop, i_address};
end
if(USECACHING) begin : GEN_ENABLE_CACHE
reg R_flush;
reg [CACHE_ADDR_W:0] flush_cnt;
reg cache_status_ready;
assign rd_c_index[0] = R_addr[CACHE_ADDR_W-1+MB_W:MB_W];
assign rd_c_index[1] = R_addr_next[CACHE_ADDR_W-1+MB_W:MB_W];
assign {cached_tag_valid[0], cached_tag[0]} = cache[rd_c_index[0]];
assign {cached_tag_valid[1], cached_tag[1]} = cache[rd_c_index[1]];
assign wr_c_index = lsu_i_address[CACHE_ADDR_W-1+MB_W:MB_W];
assign R_tag[0] = R_addr[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign R_tag[1] = R_addr_next[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign tag_match[0] = cached_tag[0] == R_tag[0] & cached_tag_valid[0] === 1'b1;
assign tag_match[1] = cached_tag[1] == R_tag[1] & cached_tag_valid[1] === 1'b1;
assign in_cache_pre[0] = tag_match[0] & !issue_2nd_word & cache_ready;
assign in_cache_pre[1] = tag_match[1] & !issue_2nd_word & cache_ready;
assign new_tag = lsu_i_address[AWIDTH-1:MB_W+CACHE_ADDR_W];
assign update_cache = R_valid & !R_nop | issue_2nd_word;
always @(posedge clk or posedge reset) begin
if(reset) cache_status_ready <= 1'b0;
else cache_status_ready <= flush_cnt[CACHE_ADDR_W];
end
always @ (posedge clk) begin
R_flush <= flush;
if(flush & !R_flush) flush_cnt <= '0;
else if(!flush_cnt[CACHE_ADDR_W]) flush_cnt <= flush_cnt + 1'b1;
cache_ready <= flush_cnt[CACHE_ADDR_W];
if(!flush_cnt[CACHE_ADDR_W]) cache[flush_cnt] <= '0;
else if(update_cache) cache[wr_c_index] <= {1'b1, new_tag};
in_cache[0] <= R_valid & (in_cache_pre[0] | R_nop) & !issue_2nd_word;
in_cache[1] <= UNALIGNED? R_valid & (in_cache_pre[1] | R_nop) & !issue_2nd_word & need_2_page : 1'b0;
include_2nd_part <= issue_2nd_word | in_cache_pre[1] & need_2_page;
p_valid <= issue_2nd_word | R_valid & !in_cache_pre[0] & !R_nop; // not include nop
p_offset_valid <= issue_2nd_word | R_valid;
p_addr <= lsu_i_address;
R_cache_addr <= lsu_i_address[MB_W+CACHE_ADDR_W-1:MB_W];
end
if(OFFSET_WIDTH > 0) begin
always @ (posedge clk) begin
p_offset <= R_addr[MB_W-1:MB_W-OFFSET_WIDTH];
end
end
if(ACL_PROFILE == 1) begin
assign req_cache_hit_count = ((|fi_in_cache) & fifo_din_en);
end
else
begin
assign req_cache_hit_count = 1'b0;
end
end // end GEN_ENABLE_CACHE
else begin : GEN_DISABLE_CACHE
assign req_cache_hit_count = 1'b0;
assign in_cache_pre = 2'b0;
assign in_cache = 2'b0;
assign include_2nd_part = issue_2nd_word;
assign p_valid = issue_2nd_word | R_valid & !R_nop; // not include nop
assign p_offset_valid = issue_2nd_word | R_valid;
assign p_addr = lsu_i_address;
if(OFFSET_WIDTH > 0) begin
assign p_offset = R_addr[MB_W-1:MB_W-OFFSET_WIDTH];
end
end // end GEN_DISABLE_CACHE
if (UNALIGNED) begin : GEN_UNALIGN
assign addr_next_wire[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH] = reg_address[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH]+1'b1;
assign addr_next_wire[AWIDTH-PAGE_ADDR_WIDTH-1:0] = '0;
// Look at the higher bits to determine how much we need to shift the two aligned accesses
wire [UNALIGNED_SELECTION_BITS-1:0] temp = NUM_WORD - R_addr[AWIDTH-1:ALIGNMENT_ABITS];
assign shift = UNALIGNED_DIV_ALIGN - temp;
assign consecutive = reg_nop | reg_address[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH] == R_addr_next[AWIDTH-1:AWIDTH-PAGE_ADDR_WIDTH];
// When do we need to issue the 2nd word ?
// The previous address needed a 2nd page and
// [1] the current requested address isn't in the (previous+1)th page and
// [2] The second page is not in the cache
assign need_2_cc = need_2_page & !in_cache_pre[1] & R_valid & (!issue_2nd_word | R_consecutive[0]); // need 2 clock cycles to combine segments from 2 pages
// simulation only
assign byte_offset = stall_pre? R_addr[MB_W-1:0] : reg_address[MB_W-1:0];
always @(posedge clk or posedge reset) begin
if(reset) begin
issue_2nd_word <= 1'b0;
R_consecutive <= 'x;
stall_pre <= 1'b0;
issue_2nd_hold <= 'x;
end
else begin
issue_2nd_word <= need_2_cc;
if(!stall_pre | issue_2nd_word) issue_2nd_hold <= need_2_cc;
R_consecutive[0] <= reg_valid & !stall_int & consecutive & need_2_cc;
R_consecutive[1] <= R_consecutive[0];
stall_pre <= (stall_int | need_2_cc & reg_valid & !consecutive);
end
end
always @(posedge clk) begin
if(reg_valid & !stall_pre) need_2_page <= !reg_nop & (reg_address[MB_W-1:0] + WIDTH_BYTES) > MWIDTH_BYTES;
if(reg_valid & !stall_pre & !reg_nop) begin
R_addr <= reg_address;
R_addr_next <= addr_next_wire;
end
R_addr_next_hold <= R_addr_next;
if(!issue_2nd_word | !stall_pre) begin
R_valid <= reg_valid & !stall_pre;
R_nop <= reg_nop;
end
end
if(ACL_PROFILE == 1) begin
assign extra_unaligned_reqs = need_2_cc & reg_valid & !consecutive;
always @(posedge clk or posedge reset) begin
if(reset) begin
non_align_hit_cache <= '0;
end
else begin
non_align_hit_cache <= non_align_hit_cache + (need_2_page & in_cache_pre[1] & R_valid & (!issue_2nd_word | R_consecutive[0]) & reg_valid & !consecutive);
end
end
end // end ACL_PROFILE == 1
end // end GEN_UNALIGN
else begin : GEN_ALIGN
assign issue_2nd_word = 1'b0;
assign need_2_page = 1'b0;
assign R_addr = reg_address;
assign R_valid = reg_valid & !stall_int;
assign R_nop = reg_nop;
assign stall_pre = stall_int;
end // end GEN_ALIGN
endgenerate
assign lsu_i_address = issue_2nd_word ? R_addr_next_hold : R_addr;
always @(posedge clk) begin
c_word_offset <= p_offset;
R_shift <= need_2_page? shift : '0;
fifo_din_en <= (|in_cache) | p_offset_valid;
{fi_in_cache, fi_cached_addr, fi_second} <= {in_cache, R_cache_addr, include_2nd_part};
if(!include_2nd_part) fi_byte_offset <= p_addr[MB_W-1:0];
fi_shift <= USECACHING? R_shift : (need_2_page? shift : '0);
fi_2nd_valid <= USECACHING? R_consecutive[1] : R_consecutive[0];
end
acl_stall_free_coalescer #(
.AW(AWIDTH),
.PAGE_AW(PAGE_ADDR_WIDTH),
.MAX_BURST(MAX_BURST),
.TIME_OUT(TIME_OUT),
.CACHE_LAST(USECACHING),
.MAX_THREAD(MAX_THREADS),
.DISABLE_COALESCE(0)
) coalescer(
.clk(clk),
.reset(reset),
.i_valid(p_valid),
.i_addr(p_addr),
.i_empty(p_ae),
.o_page_addr(c_page_addr),
.o_page_addr_valid(c_req_valid),
.o_num_burst(c_burstcount),
.o_new_page(c_new_page)
);
lsu_bursting_pipelined_read #(
.INPUT_AW(PAGE_ADDR_WIDTH),
.AWIDTH(AWIDTH),
.WIDTH(WIDTH),
.MWIDTH(MWIDTH),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.DEVICE(DEVICE),
.CACHE_SIZE_N(CACHE_SIZE_N),
.USECACHING(USECACHING),
.UNALIGNED(UNALIGNED),
.UNALIGNED_SHIFT_WIDTH(UNALIGNED_SELECTION_BITS),
.MAX_BURST(MAX_BURST),
.INCLUDE_BYTE_OFFSET(0), // sim-only
.ALIGNMENT_ABITS(ALIGNMENT_ABITS)
) pipelined_read(
.clk (clk),
.reset (reset),
.i_address (c_page_addr),
.i_addr_valid (c_req_valid),
.i_burst_count (c_burstcount),
.i_new_page (c_new_page),
.i_word_offset (c_word_offset),
.i_byte_offset (fi_byte_offset),
.i_in_cache (fi_in_cache),
.i_cache_addr (fi_cached_addr),
.i_shift (fi_shift),
.i_second (fi_second),
.i_2nd_valid (fi_2nd_valid), // has two segments' info in one cc
.i_word_offset_valid(fifo_din_en),
.i_stall (i_stall),
.o_ae (p_ae),
.o_empty (p_empty),
.o_readdata (o_readdata),
.o_valid (o_valid),
.o_stall (stall_int),
.avm_address (avm_address),
.avm_read (avm_read),
.avm_readdata (avm_readdata),
.avm_waitrequest (avm_waitrequest),
.avm_byteenable (avm_byteenable),
.avm_readdatavalid(avm_readdatavalid),
.avm_burstcount (avm_burstcount)
);
endmodule
module acl_io_pipeline #(
parameter WIDTH = 1
)(
input clk,
input reset,
input i_stall,
input i_valid,
input [WIDTH-1:0] i_data,
output o_stall,
output reg o_valid,
output reg [WIDTH-1:0] o_data
);
reg R_valid;
assign o_stall = i_stall & R_valid;
always@(posedge clk) begin
if(!o_stall) {o_valid, o_data} <= {i_valid, i_data};
end
always@(posedge clk or posedge reset)begin
if(reset) R_valid <= 1'b0;
else if(!o_stall) R_valid <= i_valid;
end
endmodule
module lsu_bursting_pipelined_read
(
clk, reset,
i_in_cache,
i_cache_addr,
i_addr_valid,
i_address,
i_burst_count,
i_word_offset,
i_byte_offset,
i_shift,
i_second,
i_2nd_valid,
i_word_offset_valid,
i_new_page,
o_readdata,
o_valid,
i_stall,
o_stall,
o_empty,
o_ae,
avm_address,
avm_read,
avm_readdata,
avm_waitrequest,
avm_byteenable,
avm_burstcount,
avm_readdatavalid
);
parameter INPUT_AW = 32;
parameter AWIDTH=32;
parameter WIDTH=32;
parameter MWIDTH=512;
parameter MAX_BURST = 16;
parameter ALIGNMENT_ABITS=2;
parameter DEVICE = "Stratix V";
parameter MEMORY_SIDE_MEM_LATENCY=160;
parameter USECACHING = 0;
parameter CACHE_SIZE_N = 1024;
parameter UNALIGNED = 0;
parameter UNALIGNED_SHIFT_WIDTH = 0;
parameter INCLUDE_BYTE_OFFSET = 0; // testing purpose
localparam ALIGNMENT_WIDTH = 2**ALIGNMENT_ABITS * 8;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH/8);
localparam WORD_WIDTH = (WIDTH >= ALIGNMENT_WIDTH & (UNALIGNED == 0))? WIDTH : ALIGNMENT_WIDTH;
localparam NUM_WORD = MWIDTH / WORD_WIDTH;
localparam OFFSET_WIDTH = (NUM_WORD==1)? 1 : $clog2(NUM_WORD);
localparam WIDE_FIFO_DEPTH = (MEMORY_SIDE_MEM_LATENCY < 256)? 256 : MEMORY_SIDE_MEM_LATENCY;
localparam OFFSET_FIFO_DEPTH = (MEMORY_SIDE_MEM_LATENCY <= 246)? 256 : MEMORY_SIDE_MEM_LATENCY + 10;
localparam REQUEST_FIFO_DEPTH = OFFSET_FIFO_DEPTH;
localparam WIDE_FIFO_DEPTH_THRESH = MEMORY_SIDE_MEM_LATENCY;
localparam WIDE_FIFO_AW = $clog2(WIDE_FIFO_DEPTH);
localparam BURST_CNT_WIDTH = (MAX_BURST == 1)? 1 : $clog2(MAX_BURST + 1);
localparam REQUEST_FIFO_AW = $clog2(REQUEST_FIFO_DEPTH);
localparam OFFSET_FIFO_AW = $clog2(OFFSET_FIFO_DEPTH);
localparam REQUEST_FIFO_WIDTH = INPUT_AW + BURST_CNT_WIDTH;
localparam CACHE_SIZE_LOG2N=$clog2(CACHE_SIZE_N);
localparam CACHE_ADDR_W=$clog2(CACHE_SIZE_N);
localparam OFFSET_FIFO_WIDTH = 1 + ((NUM_WORD > 1)? OFFSET_WIDTH : 0) + (USECACHING? 1 + CACHE_ADDR_W : 0) + (UNALIGNED? UNALIGNED_SHIFT_WIDTH + 3 : 0) + (INCLUDE_BYTE_OFFSET? BYTE_SELECT_BITS : 0);
// I/O
input clk, reset;
input [UNALIGNED:0] i_in_cache;
input [CACHE_ADDR_W-1:0] i_cache_addr;
input [INPUT_AW-1:0] i_address;
input [BURST_CNT_WIDTH-1:0] i_burst_count;
input [OFFSET_WIDTH-1:0] i_word_offset;
input [BYTE_SELECT_BITS-1:0] i_byte_offset; // simulation
input [UNALIGNED_SHIFT_WIDTH-1:0] i_shift; // used only when UNALIGNED = 1
input i_second; // used only when UNALIGNED = 1
input i_2nd_valid; // used only when UNALIGNED = 1
input i_word_offset_valid;
input i_new_page;
input i_addr_valid;
input i_stall;
output logic [WIDTH-1:0] o_readdata;
output logic o_valid;
output reg o_stall;
output reg o_empty;
output o_ae;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output reg avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH/8-1:0] avm_byteenable;
input avm_readdatavalid;
output [BURST_CNT_WIDTH-1:0] avm_burstcount;
// offset fifo
wire [OFFSET_FIFO_WIDTH-1:0] offset_fifo_din;
wire [OFFSET_FIFO_WIDTH-1:0] offset_fifo_dout;
// req FIFO
wire rd_req_en;
wire req_fifo_ae, req_fifo_af, req_overflow, offset_overflow, rd_req_empty; // FIFO status
// end req FIFO
// output FIFO
wire rd_data_fifo;
reg R_rd_data;
wire rd_data_empty;
wire rd_offset;
wire offset_fifo_empty;
wire offset_af;
wire [UNALIGNED:0] d_in_cache;
wire rd_next_page;
wire [CACHE_ADDR_W-1:0] d_cache_addr;
wire [BYTE_SELECT_BITS-1:0] d_byte_offset; // for simulation
reg R_in_cache;
wire d_second, d_2nd_valid;
wire unalign_stall_offset, unalign_stall_data;
wire [UNALIGNED_SHIFT_WIDTH-1:0] d_shift;
wire [OFFSET_WIDTH-1 : 0] d_offset;
reg [OFFSET_WIDTH-1 : 0] R_offset;
reg [MWIDTH-1:0] R_avm_rd_data;
wire [MWIDTH-1:0] rd_data;
// end output FIFO
assign avm_address[AWIDTH - INPUT_AW - 1 : 0] = 0;
assign avm_byteenable = {(MWIDTH/8){1'b1}};
assign o_ae = req_fifo_ae;
assign rd_req_en = !avm_read | !avm_waitrequest;
always @(posedge clk or posedge reset) begin
if(reset) begin
o_empty = 1'b0;
avm_read <= 1'b0;
o_stall <= 1'b0;
end
else begin
o_empty <= rd_req_empty;
o_stall <= offset_af;
if(rd_req_en) avm_read <= !rd_req_empty;
end
end
generate
if(NUM_WORD > 1) begin : GEN_WORD_OFFSET_FIFO
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (OFFSET_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (OFFSET_FIFO_WIDTH),
.lpm_widthu (OFFSET_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON"),
.almost_full_value(OFFSET_FIFO_DEPTH - 10)
) offset_fifo (
.clock (clk),
.data (offset_fifo_din),
.wrreq (i_word_offset_valid),
.rdreq (rd_offset),
.usedw (offset_flv),
.empty (offset_fifo_empty),
.full (offset_overflow),
.q (offset_fifo_dout),
.almost_empty (),
.almost_full (offset_af),
.aclr (reset)
);
end
else begin : GEN_SINGLE_WORD_RD_NEXT
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (OFFSET_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (OFFSET_FIFO_WIDTH),
.lpm_widthu (OFFSET_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "OFF"), // not instantiate block ram
.almost_full_value(OFFSET_FIFO_DEPTH - 10)
) offset_fifo (
.clock (clk),
.data (offset_fifo_din),
.wrreq (i_word_offset_valid),
.rdreq (rd_offset),
.usedw (offset_flv),
.empty (offset_fifo_empty),
.full (offset_overflow),
.q (offset_fifo_dout),
.almost_empty (),
.almost_full (offset_af),
.aclr (reset)
);
end
endgenerate
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (REQUEST_FIFO_DEPTH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (REQUEST_FIFO_WIDTH),
.lpm_widthu (REQUEST_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON"),
.almost_full_value(20),
.almost_empty_value(3)
) rd_request_fifo (
.clock (clk),
.data ({i_address, i_burst_count}),
.wrreq (i_addr_valid),
.rdreq (rd_req_en),
.usedw (),
.empty (rd_req_empty),
.full (req_overflow),
.q ({avm_address[AWIDTH - 1: AWIDTH - INPUT_AW], avm_burstcount}),
.almost_empty (req_fifo_ae),
.almost_full (req_fifo_af),
.aclr (reset)
);
/*------------------------------
Generate output data
--------------------------------*/
reg offset_valid;
reg [1:0] o_valid_pre;
wire rd_next_page_en, downstream_stall, wait_data, offset_stall, data_stall, valid_hold;
generate
if(USECACHING) begin : ENABLE_CACHE
reg [MWIDTH-1:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "no_rw_check, M20K" */;
logic [MWIDTH-1:0] reused_data[2] ;
reg [CACHE_ADDR_W-1:0] R_cache_addr, R_cache_next;
if(NUM_WORD == 1) begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_2nd_valid, i_shift, i_second, i_cache_addr, i_in_cache, i_new_page};
assign {d_2nd_valid, d_shift, d_second, d_cache_addr, d_in_cache, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
else begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_byte_offset, i_2nd_valid, i_shift, i_second, i_word_offset, i_cache_addr, i_in_cache, i_new_page};
assign {d_byte_offset, d_2nd_valid, d_shift, d_second, d_offset, d_cache_addr, d_in_cache, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
if(UNALIGNED) begin : GEN_UNALIGNED
wire need_2nd_page;
reg [UNALIGNED_SHIFT_WIDTH-1:0] R_shift [3];
reg hold_dout;
reg R_second;
reg R_need_2nd_page;
reg [WIDTH*2-ALIGNMENT_WIDTH-1:0] data_int;
reg [WIDTH-1:0] R_o_readdata;
reg [1:0] R_2nd_valid;
reg second_part_in_cache;
wire [WIDTH-1:0] c0_data_h, rd_data_h, c0_data_mux, rd_data_mux;
wire [WIDTH-ALIGNMENT_WIDTH-1:0] c1_data_l, rd_data_l;
wire get_new_offset, offset_backpressure_stall ;
wire [CACHE_ADDR_W-1:0] caddr_next;
wire [1:0] rw_wire;
reg [1:0] rw;
reg [WIDTH-ALIGNMENT_WIDTH-1:0] R_c1_data_l;
assign need_2nd_page = |d_shift;
assign valid_hold = |o_valid_pre;
assign rw_wire[0] = d_cache_addr == R_cache_addr & R_rd_data;
assign rw_wire[1] = caddr_next == R_cache_addr & R_rd_data;
assign c0_data_h = rw[0]? rd_data[MWIDTH-1:MWIDTH-WIDTH] : reused_data[0][MWIDTH-1:MWIDTH-WIDTH];
assign c1_data_l = rw[1]? R_c1_data_l : reused_data[1][WIDTH-ALIGNMENT_WIDTH-1:0];
assign rd_data_h = rd_data[MWIDTH-1:MWIDTH-WIDTH];
assign rd_data_l = rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
assign c0_data_mux = rw[0]? rd_data >> R_offset*ALIGNMENT_WIDTH : reused_data[0] >> R_offset*ALIGNMENT_WIDTH ;
assign rd_data_mux = rd_data >> R_offset*ALIGNMENT_WIDTH;
assign caddr_next = d_cache_addr+1;
assign unalign_stall_offset = d_2nd_valid & !offset_backpressure_stall & !R_2nd_valid[0]; //it is a one-cc pulse
assign unalign_stall_data = R_2nd_valid[0];
assign get_new_offset = rd_offset | unalign_stall_offset;
assign offset_backpressure_stall = wait_data | downstream_stall & offset_valid;
assign offset_stall = offset_backpressure_stall | unalign_stall_offset;
assign data_stall = downstream_stall | unalign_stall_data;
assign wait_data = rd_next_page_en & rd_data_empty & !R_2nd_valid[0];
assign o_readdata = hold_dout? R_o_readdata : data_int[R_shift[2]*ALIGNMENT_WIDTH +: WIDTH];
always@(posedge clk or posedge reset)begin
if(reset) begin
o_valid_pre <= 2'b0;
o_valid <= 1'b0;
end
else begin
o_valid_pre[0] <= offset_valid & get_new_offset & (!need_2nd_page | !R_2nd_valid[0] & d_second);
if(i_stall & o_valid & o_valid_pre[0]) o_valid_pre[1] <= 1'b1;
else if(!i_stall) o_valid_pre[1] <= 1'b0;
if(o_valid_pre[0]) o_valid <= 1'b1;
else if(!i_stall) o_valid <= valid_hold;
end
end
always @(posedge clk) begin
if(R_rd_data) cache[R_cache_addr] <= rd_data;
if(get_new_offset) begin
{R_in_cache, R_offset, R_shift[0], R_second} <= {|d_in_cache, d_offset, d_shift, d_second};
R_cache_addr <= d_cache_addr;
R_cache_next <= caddr_next;
R_shift[1] <= R_shift[0];
R_need_2nd_page <= need_2nd_page;
second_part_in_cache <= !d_in_cache[0] & d_in_cache[1];
R_2nd_valid[1] <= R_2nd_valid[0];
`ifdef SIM_ONLY
if(d_in_cache[0]) reused_data[0] <= rw_wire[0]? 'x : cache[d_cache_addr];
reused_data[1] <= rw_wire[1]? 'x : cache[caddr_next];
`else
if(d_in_cache[0]) reused_data[0] <= cache[d_cache_addr];
reused_data[1] <= cache[caddr_next];
`endif
if(d_in_cache[1]) R_c1_data_l <= rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
end
// work-around to deal with read-during-write
if(!downstream_stall & (|d_in_cache)) rw <= rw_wire & d_in_cache;
if(!offset_backpressure_stall) R_2nd_valid[0] <= d_2nd_valid & !R_2nd_valid[0];
R_o_readdata <= o_readdata;
hold_dout <= i_stall & o_valid;
if(R_in_cache) begin
data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= c1_data_l;
data_int[WIDTH-1:0] <= second_part_in_cache? rd_data_h : R_need_2nd_page? c0_data_h : c0_data_mux;
end
else begin
if(R_second) data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= rd_data_l;
if(!R_second | R_2nd_valid[1]) data_int[WIDTH-1:0] <= R_need_2nd_page? rd_data_h : rd_data_mux;
end
R_shift[2] <= (R_in_cache | !R_second | R_2nd_valid[1])? R_shift[0] : R_shift[1];
end
end // end UNALIGNED
else begin : GEN_ALIGNED
reg [MWIDTH-1:0] cache [CACHE_SIZE_N] /* synthesis ramstyle = "no_rw_check, M20K" */;
assign valid_hold = o_valid;
assign offset_stall = wait_data | downstream_stall & offset_valid;
assign data_stall = downstream_stall;
assign wait_data = rd_next_page_en & rd_data_empty; // there is a valid offset, need data to demux
if(NUM_WORD == 1) assign o_readdata = R_in_cache? reused_data[0][WIDTH-1:0] : rd_data[WIDTH-1:0];
else assign o_readdata = R_in_cache? reused_data[0] >> R_offset*WORD_WIDTH: rd_data >> R_offset*WORD_WIDTH;
always @(posedge clk) begin
if(rd_offset) begin
R_cache_addr <= d_cache_addr;
R_in_cache <= d_in_cache & !(R_rd_data & R_cache_addr == d_cache_addr);
R_offset <= d_offset;
// registered cache input and output to infer megafunction RAM
`ifdef SIM_ONLY // for simulation accuracy
reused_data[0] <= (d_cache_addr == R_cache_addr & R_rd_data)? 'x : cache[d_cache_addr]; // read during write
`else
reused_data[0] <= cache[d_cache_addr];
`endif
end
else if(R_rd_data & R_cache_addr == d_cache_addr) R_in_cache <= 1'b0; // read during write
if(R_rd_data) cache[R_cache_addr] <= rd_data; // update cache
end
always@(posedge clk or posedge reset)begin
if(reset) o_valid <= 1'b0;
else if(!i_stall | !o_valid) o_valid <= rd_offset & offset_valid;
end
end // end ALIGNED
end // end USECACHING
else begin : DISABLE_CACHE
if(NUM_WORD == 1) begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_2nd_valid, i_shift, i_second, i_new_page};
assign {d_2nd_valid, d_shift, d_second, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
else begin
assign offset_fifo_din[OFFSET_FIFO_WIDTH-1:0] = {i_byte_offset, i_2nd_valid, i_shift, i_second, i_word_offset, i_new_page};
assign {d_byte_offset, d_2nd_valid, d_shift, d_second, d_offset, rd_next_page} = offset_fifo_dout[OFFSET_FIFO_WIDTH-1:0];
end
if(UNALIGNED) begin : GEN_UNALIGNED
wire need_2nd_page;
reg [UNALIGNED_SHIFT_WIDTH-1:0] R_shift [3];
reg hold_dout;
reg R_second;
reg R_need_2nd_page;
reg [WIDTH*2-ALIGNMENT_WIDTH-1:0] data_int;
reg [WIDTH-1:0] R_o_readdata;
reg [1:0] R_2nd_valid;
wire [WIDTH-1:0] rd_data_h, rd_data_mux;
wire [WIDTH-ALIGNMENT_WIDTH-1:0] rd_data_l;
wire get_new_offset, offset_backpressure_stall;
assign need_2nd_page = |d_shift;
assign valid_hold = |o_valid_pre;
assign rd_data_h = rd_data[MWIDTH-1:MWIDTH-WIDTH];
assign rd_data_l = rd_data[WIDTH-ALIGNMENT_WIDTH-1:0];
assign rd_data_mux = rd_data >> R_offset*ALIGNMENT_WIDTH;
assign unalign_stall_offset = d_2nd_valid & !offset_backpressure_stall & !R_2nd_valid[0]; //it is a one-cc pulse
assign unalign_stall_data = R_2nd_valid[0];
assign get_new_offset = rd_offset | unalign_stall_offset;
assign offset_backpressure_stall = wait_data | downstream_stall & offset_valid;
assign offset_stall = offset_backpressure_stall | unalign_stall_offset;
assign data_stall = downstream_stall | unalign_stall_data;
assign wait_data = rd_next_page_en & rd_data_empty & !R_2nd_valid[0];
assign o_readdata = hold_dout? R_o_readdata : data_int >> R_shift[2]*ALIGNMENT_WIDTH;
always@(posedge clk or posedge reset)begin
if(reset) begin
o_valid_pre <= 2'b0;
o_valid <= 1'b0;
end
else begin
o_valid_pre[0] <= offset_valid & get_new_offset & (!need_2nd_page | !R_2nd_valid[0] & d_second);
if(i_stall & o_valid & o_valid_pre[0]) o_valid_pre[1] <= 1'b1;
else if(!i_stall) o_valid_pre[1] <= 1'b0;
if(o_valid_pre[0]) o_valid <= 1'b1;
else if(!i_stall) o_valid <= valid_hold;
end
end
always @(posedge clk) begin
if(get_new_offset) begin
{R_offset, R_shift[0], R_second} <= {d_offset, d_shift, d_second};
R_shift[1] <= R_shift[0];
R_need_2nd_page <= need_2nd_page;
R_2nd_valid[1] <= R_2nd_valid[0];
end
if(!offset_backpressure_stall) R_2nd_valid[0] <= d_2nd_valid & !R_2nd_valid[0];
R_o_readdata <= o_readdata;
hold_dout <= i_stall & o_valid;
if(R_second) data_int[WIDTH*2-ALIGNMENT_WIDTH-1:WIDTH] <= rd_data_l;
if(!R_second | R_2nd_valid[1]) data_int[WIDTH-1:0] <= R_need_2nd_page? rd_data_h : rd_data_mux;
R_shift[2] <= (!R_second | R_2nd_valid[1])? R_shift[0] : R_shift[1];
end
end // end GEN_UNALIGNED
else begin : GEN_ALIGNED
assign valid_hold = o_valid;
assign offset_stall = wait_data | downstream_stall & offset_valid;
assign data_stall = downstream_stall;
assign wait_data = rd_next_page_en & rd_data_empty; // there is a valid offset, need data to demux
if(NUM_WORD == 1) assign o_readdata = rd_data[WIDTH-1:0];
else assign o_readdata = rd_data >> R_offset*WORD_WIDTH;
always @(posedge clk) begin
if(rd_offset) R_offset <= d_offset;
end
always@(posedge clk or posedge reset)begin
if(reset) o_valid <= 1'b0;
else if(!i_stall | !o_valid) o_valid <= rd_offset & offset_valid;
end
end // end GEN_ALIGNED
end // end DISABLE_CACHE
endgenerate
assign downstream_stall = i_stall & valid_hold;
assign rd_next_page_en = offset_valid & rd_next_page;
assign rd_offset = !offset_stall;
assign rd_data_fifo = rd_next_page_en & !data_stall;
always@(posedge clk or posedge reset)begin
if(reset) begin
offset_valid <= 1'b0;
R_rd_data <= 1'b0;
end
else begin
if(rd_offset) offset_valid <= !offset_fifo_empty;
R_rd_data <= rd_data_fifo & !rd_data_empty;
end
end
scfifo #(
.add_ram_output_register ( "ON"),
.intended_device_family ( DEVICE),
.lpm_numwords (WIDE_FIFO_DEPTH),
.almost_full_value(WIDE_FIFO_DEPTH_THRESH),
.lpm_showahead ( "OFF"),
.lpm_type ( "scfifo"),
.lpm_width (MWIDTH),
.lpm_widthu (WIDE_FIFO_AW),
.overflow_checking ( "OFF"),
.underflow_checking ( "ON"),
.use_eab ( "ON")
) rd_back_wfifo (
.clock (clk),
.data (avm_readdata),
.wrreq (avm_readdatavalid),
.rdreq (rd_data_fifo),
.usedw (),
.empty (rd_data_empty),
.full (),
.q (rd_data),
.almost_empty (),
.almost_full (),
.aclr (reset)
);
endmodule
module acl_stall_free_coalescer (
clk, // clock
reset, // reset
i_valid, // valid address
i_empty, // request FIFO is empty
i_addr, // input address
o_page_addr, // output page address
o_page_addr_valid, // page address valid
o_num_burst, // number of burst
o_new_page
);
parameter AW = 1,
PAGE_AW = 1,
MAX_BURST = 1,
TIME_OUT = 1,
MAX_THREAD = 1,
CACHE_LAST = 0,
DISABLE_COALESCE = 0;
localparam BURST_CNT_WIDTH = $clog2(MAX_BURST+1);
localparam TIME_OUT_W = $clog2(TIME_OUT+1);
localparam THREAD_W = $clog2(MAX_THREAD+1);
input clk;
input reset;
input i_valid;
input i_empty;
input [AW-1:0] i_addr;
// all output signals are registered to help P&R
output reg [PAGE_AW-1:0] o_page_addr;
output reg o_page_addr_valid;
output reg [BURST_CNT_WIDTH-1:0] o_num_burst;
output reg o_new_page;
logic init;
wire match_current_wire, match_next_wire, reset_cnt;
reg [BURST_CNT_WIDTH-1:0] num_burst;
reg valid_burst;
wire [PAGE_AW-1:0] page_addr;
reg [PAGE_AW-1:0] R_page_addr = 0;
reg [PAGE_AW-1:0] R_page_addr_next = 0;
reg [PAGE_AW-1:0] addr_hold = 0;
reg [3:0] delay_cnt; // it takes 5 clock cycles from o_page_addr_valid to being read out from FIFO (if avm_stall = 0), assuming 3 extra clock cycles to reach global mem
reg [TIME_OUT_W-1:0] time_out_cnt = 0;
reg [THREAD_W-1:0] thread_cnt = 0;
wire time_out;
wire max_thread;
assign page_addr = i_addr[AW-1:AW-PAGE_AW]; // page address
assign match_current_wire = page_addr == R_page_addr;
assign max_thread = thread_cnt[THREAD_W-1] & i_empty;
assign time_out = time_out_cnt[TIME_OUT_W-1] & i_empty;
assign reset_cnt = valid_burst & (
num_burst[BURST_CNT_WIDTH-1] // reach max burst
| time_out
| max_thread
| !match_current_wire & !match_next_wire & !init & i_valid ); // new burst
generate
if(MAX_BURST == 1) begin : BURST_ONE
assign match_next_wire = 1'b0;
end
else begin : BURST_N
assign match_next_wire = page_addr == R_page_addr_next & !init & i_valid & (|page_addr[BURST_CNT_WIDTH-2:0]);
end
if(DISABLE_COALESCE) begin : GEN_DISABLE_COALESCE
always@(*) begin
o_page_addr = page_addr;
o_page_addr_valid = i_valid;
o_num_burst = 1;
o_new_page = 1'b1;
end
end
else begin : ENABLE_COALESCE
always@(posedge clk) begin
if(i_valid) begin
R_page_addr <= page_addr;
R_page_addr_next <= page_addr + 1'b1;
end
o_num_burst <= num_burst;
o_page_addr <= addr_hold;
if(i_valid | reset_cnt) time_out_cnt <= 0; // nop is valid thread, should reset time_out counter too
else if(!time_out_cnt[TIME_OUT_W-1] & valid_burst) time_out_cnt <= time_out_cnt + 1;
if(reset_cnt) thread_cnt <= i_valid;
else if(i_valid & !thread_cnt[THREAD_W-1]) thread_cnt <= thread_cnt + 1;
if(o_page_addr_valid) delay_cnt <= 1;
else if(!delay_cnt[3]) delay_cnt <= delay_cnt + 1;
if(reset_cnt) begin
num_burst <= i_valid & !match_current_wire;
addr_hold <= page_addr;
end
else if(i_valid) begin
num_burst <= (!valid_burst & !match_current_wire | init)? 1 : num_burst + match_next_wire;
if(!valid_burst | init) addr_hold <= page_addr;
end
o_new_page <= (!match_current_wire| init) & i_valid;
end
always@(posedge clk or posedge reset) begin
if(reset) begin
o_page_addr_valid <= 1'b0;
valid_burst <= 1'b0;
end
else begin
if(reset_cnt) valid_burst <= i_valid & !match_current_wire;
else if(i_valid) begin
if(!valid_burst & !match_current_wire | init) valid_burst <= 1'b1;
else if(match_next_wire) valid_burst <= 1'b1;
end
o_page_addr_valid <= reset_cnt;
end
end
end
if(CACHE_LAST) begin : GEN_ENABLE_CACHE
always@(posedge clk or posedge reset) begin
if(reset) init <= 1'b1;
else begin
if(!valid_burst & !o_page_addr_valid & (!i_valid | match_current_wire & !init)) init <= 1'b1; // set init to 1 when the previous request is read out
else if(i_valid) init <= 1'b0;
end
end
end
else begin : GEN_DISABLE_CACHE
always@(posedge clk or posedge reset) begin
if(reset) init <= 1'b1;
else begin
if(!valid_burst & delay_cnt[3] & !o_page_addr_valid & i_empty & (!i_valid | match_current_wire & !init)) init <= 1'b1; // set init to 1 when the previous request is read out
else if(i_valid) init <= 1'b0;
end
end
end
endgenerate
endmodule
module lsu_bursting_write
(
clk, clk2x, reset, o_stall, i_valid, i_nop, i_address, i_writedata, i_stall, o_valid,
i_2nd_offset,
i_2nd_data,
i_2nd_byte_en,
i_2nd_en,
i_thread_valid,
o_active, //Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest,
avm_burstcount,
i_byteenable
);
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // The max number of live threads
parameter MEMORY_SIDE_MEM_LATENCY=32; // The latency to get to the iface (no response needed from DDR, we generate writeack right before the iface).
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter USE_WRITE_ACK=0; // Wait till the write has actually made it to global memory
parameter HIGH_FMAX=1;
parameter USE_BYTE_EN=0;
parameter UNALIGN=0;
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam ALIGNMENT_ABYTES=2**ALIGNMENT_ABITS;
/********
* Ports *
********/
// Standard global signals
input clk;
input clk2x;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// used for unaligned
input [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] i_2nd_offset;
input [WIDTH-1:0] i_2nd_data;
input [WIDTH_BYTES-1:0] i_2nd_byte_en;
input i_2nd_en;
input i_thread_valid;
// Downstream interface
input i_stall;
output o_valid;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
input [WIDTH_BYTES-1:0] i_byteenable;
// Byte enable control
reg reg_lsu_i_valid, reg_lsu_i_thread_valid;
reg [AWIDTH-1:0] reg_lsu_i_address;
reg [WIDTH-1:0] reg_lsu_i_writedata;
reg [WIDTH_BYTES-1:0] reg_lsu_i_byte_enable;
reg reg_common_burst, reg_lsu_i_2nd_en;
reg reg_i_nop;
reg [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] reg_lsu_i_2nd_offset;
reg [WIDTH-1:0]reg_lsu_i_2nd_data;
reg [WIDTH_BYTES-1:0] reg_lsu_i_2nd_byte_en;
wire stall_signal_directly_from_lsu;
assign o_stall = reg_lsu_i_valid & stall_signal_directly_from_lsu;
// --------------- Pipeline stage : Burst Checking --------------------
always@(posedge clk or posedge reset)
begin
if (reset)
begin
reg_lsu_i_valid <= 1'b0;
reg_lsu_i_thread_valid <= 1'b0;
end
else
begin
if (~o_stall) begin
reg_lsu_i_valid <= i_valid;
reg_lsu_i_thread_valid <= i_thread_valid;
end
end
end
always@(posedge clk) begin
if (~o_stall & i_valid & ~i_nop) reg_lsu_i_address <= i_address;
if (~o_stall) begin
reg_i_nop <= i_nop;
reg_lsu_i_writedata <= i_writedata;
reg_lsu_i_byte_enable <= i_byteenable;
reg_lsu_i_2nd_offset <= i_2nd_offset;
reg_lsu_i_2nd_en <= i_2nd_en;
reg_lsu_i_2nd_data <= i_2nd_data;
reg_lsu_i_2nd_byte_en <= i_2nd_byte_en;
reg_common_burst <= i_nop | (reg_lsu_i_address[AWIDTH-1:BYTE_SELECT_BITS+BURSTCOUNT_WIDTH-1] == i_address[AWIDTH-1:BYTE_SELECT_BITS+BURSTCOUNT_WIDTH-1]);
end
end
// -------------------------------------------------------------------
lsu_bursting_write_internal #(
.KERNEL_SIDE_MEM_LATENCY(KERNEL_SIDE_MEM_LATENCY),
.MEMORY_SIDE_MEM_LATENCY(MEMORY_SIDE_MEM_LATENCY),
.AWIDTH(AWIDTH),
.WIDTH_BYTES(WIDTH_BYTES),
.MWIDTH_BYTES(MWIDTH_BYTES),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.ALIGNMENT_ABITS(ALIGNMENT_ABITS),
.USE_WRITE_ACK(USE_WRITE_ACK),
.USE_BYTE_EN(USE_BYTE_EN),
.UNALIGN(UNALIGN),
.HIGH_FMAX(HIGH_FMAX)
) bursting_write (
.clk(clk),
.clk2x(clk2x),
.reset(reset),
.i_nop(reg_i_nop),
.o_stall(stall_signal_directly_from_lsu),
.i_valid(reg_lsu_i_valid),
.i_thread_valid(reg_lsu_i_thread_valid),
.i_address(reg_lsu_i_address),
.i_writedata(reg_lsu_i_writedata),
.i_2nd_offset(reg_lsu_i_2nd_offset),
.i_2nd_data(reg_lsu_i_2nd_data),
.i_2nd_byte_en(reg_lsu_i_2nd_byte_en),
.i_2nd_en(reg_lsu_i_2nd_en),
.i_stall(i_stall),
.o_valid(o_valid),
.o_active(o_active),
.i_byteenable(reg_lsu_i_byte_enable),
.avm_address(avm_address),
.avm_write(avm_write),
.avm_writeack(avm_writeack),
.avm_writedata(avm_writedata),
.avm_byteenable(avm_byteenable),
.avm_burstcount(avm_burstcount),
.avm_waitrequest(avm_waitrequest),
.common_burst(reg_common_burst)
);
endmodule
//
// Burst coalesced write module
// Again, top level comments later
//
module lsu_bursting_write_internal
(
clk, clk2x, reset, o_stall, i_valid, i_nop, i_address, i_writedata, i_stall, o_valid,
o_active, //Debugging signal
i_2nd_offset,
i_2nd_data,
i_2nd_byte_en,
i_2nd_en,
i_thread_valid,
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest,
avm_burstcount,
i_byteenable,
common_burst
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
parameter KERNEL_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter MEMORY_SIDE_MEM_LATENCY=32; // Memory latency in cycles
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter USE_WRITE_ACK=0; // Wait till the write has actually made it to global memory
parameter HIGH_FMAX=1;
parameter USE_BYTE_EN=0;
parameter UNALIGN=0;
// WARNING: Kernels will hang if InstrDataDep claims that a store
// has more capacity than this number
//
parameter MAX_CAPACITY=128; // Must be a power-of-2 to keep things simple
// Derived parameters
localparam MAX_BURST=2**(BURSTCOUNT_WIDTH-1);
//
// Notice that in the non write ack case, the number of threads seems to be twice the sensible number
// This is because MAX_THREADS is usually the limiter on the counter width. Once one request is assemembled,
// we want to be able to start piplining another burst. Thus the factor of 2.
// The MEMORY_SIDE_MEM_LATENCY will further increase this depth if the compiler
// thinks the lsu will see a lot of contention on the Avalon side.
//
localparam __WRITE_FIFO_DEPTH = (WIDTH_BYTES==MWIDTH_BYTES) ? 3*MAX_BURST : 2*MAX_BURST;
// No reason this should need more than max MLAB depth
localparam _WRITE_FIFO_DEPTH = ( __WRITE_FIFO_DEPTH < 64 ) ? __WRITE_FIFO_DEPTH : 64;
// Need at least 4 to account for fifo push-to-pop latency
localparam WRITE_FIFO_DEPTH = ( _WRITE_FIFO_DEPTH > 8 ) ? _WRITE_FIFO_DEPTH : 8;
// If writeack, make this equal to
localparam MAX_THREADS=(USE_WRITE_ACK ? KERNEL_SIDE_MEM_LATENCY - MEMORY_SIDE_MEM_LATENCY : (2*MWIDTH_BYTES/WIDTH_BYTES*MAX_BURST)); // Maximum # of threads to group into a burst request
//
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam PAGE_SELECT_BITS=AWIDTH-BYTE_SELECT_BITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH=8*SEGMENT_WIDTH_BYTES;
localparam NUM_WORD = MWIDTH_BYTES/SEGMENT_WIDTH_BYTES;
localparam UNALIGN_BITS = $clog2(WIDTH_BYTES)-ALIGNMENT_ABITS;
// Constants
localparam COUNTER_WIDTH=(($clog2(MAX_THREADS)+1 < $clog2(MAX_CAPACITY+1)) ?
$clog2(MAX_CAPACITY+1) : ($clog2(MAX_THREADS)+1)); // Determines the max writes 'in-flight'
/********
* Ports *
********/
// Standard global signals
input clk;
input clk2x;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
// used for unaligned
input [BYTE_SELECT_BITS-1-ALIGNMENT_ABITS:0] i_2nd_offset;
input [WIDTH-1:0] i_2nd_data;
input [WIDTH_BYTES-1:0] i_2nd_byte_en;
input i_2nd_en;
input i_thread_valid;
// Downstream interface
input i_stall;
output o_valid;
output reg o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output [MWIDTH-1:0] avm_writedata;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
// Byte enable control
input [WIDTH_BYTES-1:0] i_byteenable;
// Help from outside
input common_burst;
/***************
* Architecture *
***************/
wire [WIDTH_BYTES-1:0] word_byte_enable;
wire [WIDTH-1:0] word_bit_enable, word2_bit_enable;
wire input_accepted;
wire output_acknowledged;
wire write_accepted;
wire [PAGE_SELECT_BITS-1:0] page_addr;
wire c_new_page;
wire c_page_done;
wire c_nop;
wire [PAGE_SELECT_BITS-1:0] c_req_addr;
wire c_req_valid;
wire c_stall;
reg [COUNTER_WIDTH-1:0] occ_counter;
// Replicated version of the occ and stores counters that decrement instead of increment
// This allows me to check the topmost bit to determine if the counter is non-empty
reg [COUNTER_WIDTH-1:0] nop_cnt;
reg [COUNTER_WIDTH-1:0] occ_counter_neg;
reg [COUNTER_WIDTH-1:0] ack_counter_neg;
reg [COUNTER_WIDTH-1:0] ack_counter;
reg [COUNTER_WIDTH-1:0] next_counter;
reg [MWIDTH-1:0] wm_writedata;
reg [MWIDTH_BYTES-1:0] wm_byteenable;
reg [MWIDTH-1:0] wm_wide_wdata;
reg [MWIDTH_BYTES-1:0] wm_wide_be;
reg [MWIDTH-1:0] wm_wide_bite;
wire w_fifo_full;
wire [BURSTCOUNT_WIDTH-1:0] c_burstcount;
// Track the current item in the write burst since we issue c_burstcount burst reqs
reg [BURSTCOUNT_WIDTH-1:0] burstcounter;
// The address components
assign page_addr = i_address[AWIDTH-1:BYTE_SELECT_BITS];
assign word_byte_enable = i_nop? '0: (USE_BYTE_EN ? i_byteenable :{WIDTH_BYTES{1'b1}}) ;
generate
genvar byte_num;
for( byte_num = 0; byte_num < WIDTH_BYTES; byte_num++)
begin : biten
assign word_bit_enable[(byte_num+1)*8-1: byte_num*8] = {8{word_byte_enable[byte_num]}};
assign word2_bit_enable[(byte_num+1)*8-1: byte_num*8] = {8{i_2nd_byte_en[byte_num]}};
end
endgenerate
wire oc_full;
wire cnt_valid;
wire coalescer_active;
// Coalescer - Groups subsequent requests together if they are compatible
// and the output register stage is stalled
bursting_coalescer #(
.PAGE_ADDR_WIDTH(PAGE_SELECT_BITS),
.TIMEOUT(16),
.BURSTCOUNT_WIDTH(BURSTCOUNT_WIDTH),
.MAXBURSTCOUNT(MAX_BURST),
.MAX_THREADS(MAX_THREADS)
) coalescer (
.clk(clk),
.reset(reset),
.i_page_addr(page_addr),
.i_valid(i_valid && !oc_full && !w_fifo_full),
.i_nop(i_nop),
.o_stall(c_stall),
.o_start_nop(c_nop), // new burst starts with nop
.o_new_page(c_new_page),
.o_page_done(c_page_done),
.o_req_addr(c_req_addr),
.o_req_valid(c_req_valid),
.i_stall(w_fifo_full),
.o_burstcount(c_burstcount),
.common_burst(common_burst),
.o_active(coalescer_active)
);
// Writedata MUX
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
if(UNALIGN) begin : GEN_UNALIGN
assign cnt_valid = i_thread_valid;
always@(*) begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_bite = {MWIDTH{1'b0}};
if(i_2nd_en) begin
wm_wide_wdata[WIDTH-1:0] = i_2nd_data;
wm_wide_wdata = wm_wide_wdata << (i_2nd_offset*SEGMENT_WIDTH);
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_be[WIDTH_BYTES-1:0] = i_2nd_byte_en;
wm_wide_be = wm_wide_be << (i_2nd_offset*SEGMENT_WIDTH_BYTES);
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_bite[WIDTH-1:0] = word2_bit_enable;
wm_wide_bite = wm_wide_bite << (i_2nd_offset*SEGMENT_WIDTH);
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
end
else begin
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_wdata = wm_wide_wdata << (segment_select*SEGMENT_WIDTH);
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_be = wm_wide_be << (segment_select*SEGMENT_WIDTH_BYTES);
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
wm_wide_bite = wm_wide_bite << (segment_select*SEGMENT_WIDTH);
end
end
end // end GEN_UNALIGN
else begin: GEN_ALIGN
assign cnt_valid = i_valid;
always@(*) begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[WIDTH-1:0] = i_writedata;
wm_wide_wdata = wm_wide_wdata << (segment_select*SEGMENT_WIDTH);
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[WIDTH_BYTES-1:0] = word_byte_enable;
wm_wide_be = wm_wide_be << (segment_select*SEGMENT_WIDTH_BYTES);
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[WIDTH-1:0] = word_bit_enable;
wm_wide_bite = wm_wide_bite << (segment_select*SEGMENT_WIDTH);
end
end
end
else
begin
assign cnt_valid = i_valid;
always@(*)
begin
wm_wide_wdata = {MWIDTH{1'bx}};
wm_wide_wdata[0 +: WIDTH] = i_writedata;
wm_wide_be = {MWIDTH_BYTES{1'b0}};
wm_wide_be[0 +: WIDTH_BYTES] = word_byte_enable;
wm_wide_bite = {MWIDTH{1'b0}};
wm_wide_bite[0 +: WIDTH] = word_bit_enable;
end
end
endgenerate
// Track the current write burst data - coalesce writes together until the
// output registers are ready for a new request.
always@(posedge clk or posedge reset)
begin
if(reset)
begin
wm_writedata <= {MWIDTH{1'b0}};
wm_byteenable <= {MWIDTH_BYTES{1'b0}};
end
else
begin
if(c_new_page)
begin
wm_writedata <= wm_wide_wdata;
wm_byteenable <= wm_wide_be;
end
else if(input_accepted)
begin
wm_writedata <= (wm_wide_wdata & wm_wide_bite) | (wm_writedata & ~wm_wide_bite);
wm_byteenable <= wm_wide_be | wm_byteenable;
end
end
end
wire [COUNTER_WIDTH-1:0] num_threads_written;
// This FIFO stores the actual data to be written
//
//
wire w_data_fifo_full, req_fifo_empty;
wire wr_page = c_page_done & !w_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(COUNTER_WIDTH+MWIDTH+MWIDTH_BYTES),
.DEPTH(WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) req_fifo (
.clock(clk),
.resetn(~reset),
.data_in( {wm_writedata,wm_byteenable} ),
.valid_in( wr_page ),
.data_out( {avm_writedata,avm_byteenable} ),
.stall_in( ~write_accepted ),
.stall_out( w_data_fifo_full ),
.empty(req_fifo_empty)
);
// This FIFO stores the number of valid's to release with each writeack
//
wire w_ack_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(COUNTER_WIDTH),
.DEPTH(2*WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) ack_fifo (
.clock(clk),
.resetn(~reset),
.data_in( next_counter),
.valid_in( wr_page ),
.data_out( num_threads_written ),
.stall_in( !avm_writeack),
.stall_out( w_ack_fifo_full )
);
// This FIFO hold the request information { address & burstcount }
//
wire w_fifo_stall_in;
assign w_fifo_stall_in = !(write_accepted && (burstcounter == avm_burstcount));
wire w_request_fifo_full;
acl_data_fifo #(
.DATA_WIDTH(PAGE_SELECT_BITS+BURSTCOUNT_WIDTH),
.DEPTH(WRITE_FIFO_DEPTH),
.IMPL(HIGH_FMAX ? "ram_plus_reg" : "ram")
) req_fifo2 (
.clock(clk),
.resetn(~reset),
.data_in( {c_req_addr,c_burstcount} ),
.valid_in( c_req_valid & !w_fifo_full ), // The basical coalescer stalls on w_fifo_full holding c_req_valid high
.data_out( {avm_address[AWIDTH-1: BYTE_SELECT_BITS],avm_burstcount} ),
.valid_out( avm_write ),
.stall_in( w_fifo_stall_in ),
.stall_out( w_request_fifo_full )
);
assign avm_address[BYTE_SELECT_BITS-1:0] = '0;
// The w_fifo_full is the OR of the data or request fifo's being full
assign w_fifo_full = w_data_fifo_full | w_request_fifo_full | w_ack_fifo_full;
// Occupancy counter - track the number of successfully transmitted writes
// and the number of writes pending in the next request.
// occ_counter - the total occupancy (in threads) of the unit
// next_counter - the number of threads coalesced into the next transfer
// ack_counter - the number of pending threads with write completion acknowledged
reg pending_nop;
wire pending_cc = nop_cnt != occ_counter;
wire burst_start_nop = cnt_valid & c_nop & !o_stall;
wire start_with_nop = !pending_cc && i_nop && cnt_valid && !o_stall; // nop starts when there are no pending writes
wire normal_cc_valid = cnt_valid && !o_stall && !i_nop;
wire clear_nop_cnt = normal_cc_valid || !pending_cc;
assign input_accepted = cnt_valid && !o_stall && !(c_nop || start_with_nop);
assign write_accepted = avm_write && !avm_waitrequest;
assign output_acknowledged = o_valid && !i_stall;
wire [8:0] ack_pending = {1'b1, {COUNTER_WIDTH{1'b0}}} - ack_counter;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
occ_counter <= {COUNTER_WIDTH{1'b0}};
occ_counter_neg <= {COUNTER_WIDTH{1'b0}};
ack_counter <= {COUNTER_WIDTH{1'b0}};
next_counter <= {COUNTER_WIDTH{1'b0}};
ack_counter_neg <= '0;
nop_cnt <= '0;
burstcounter <= 6'b000001;
o_active <= 1'b0;
pending_nop <= 1'b0;
end
else
begin
if(clear_nop_cnt) begin
nop_cnt <= '0;
pending_nop <= 1'b0;
end
else if(!start_with_nop) begin
nop_cnt <= nop_cnt + burst_start_nop;
if(burst_start_nop) pending_nop <= 1'b1;
end
occ_counter <= occ_counter + (cnt_valid && !o_stall) - output_acknowledged;
occ_counter_neg <= occ_counter_neg - (cnt_valid && !o_stall) + output_acknowledged;
next_counter <= input_accepted + (c_page_done ? {COUNTER_WIDTH{1'b0}} : next_counter) + (normal_cc_valid? nop_cnt : 0);
if(USE_WRITE_ACK) begin
ack_counter <= ack_counter
- (avm_writeack? num_threads_written : 0)
- ( (!pending_cc & !normal_cc_valid)? nop_cnt : 0)
- start_with_nop
+ output_acknowledged;
o_active <= occ_counter_neg[COUNTER_WIDTH-1];
end
else begin
ack_counter <= ack_counter - (cnt_valid && !o_stall) + output_acknowledged;
ack_counter_neg <= ack_counter_neg - wr_page + avm_writeack;
o_active <= occ_counter_neg[COUNTER_WIDTH-1] | ack_counter_neg[COUNTER_WIDTH-1] | coalescer_active; // do not use num_threads_written, because it takes extra resource
end
burstcounter <= write_accepted ? ((burstcounter == avm_burstcount) ? 6'b000001 : burstcounter+1) : burstcounter;
end
end
assign oc_full = occ_counter[COUNTER_WIDTH-1];
// Pipeline control signals
assign o_stall = oc_full || c_stall || w_fifo_full;
assign o_valid = ack_counter[COUNTER_WIDTH-1];
endmodule
// BURST COALESCING MODULE
//
// Similar to the basic coalescer but supports checking if accesses are in consecutive DRAM "pages"
// Supports the ad-hocly discovered protocols for bursting efficiently with avalaon
// - Don't burst from an ODD address
// - If not on a burst boundary, then just burst up to the next burst bondary
//
// Yes, I know, this could be incorporated into the basic coalescer. But that's really not my "thing"
//
module bursting_coalescer
(
clk, reset, i_page_addr, i_nop, i_valid, o_stall, o_new_page, o_page_done, o_req_addr, o_burstcount,
o_req_valid, i_stall, o_start_nop,
common_burst,
// For the purposes of maintaining latency correctly, we need to know if total # of threads
// accepted by the caching LSU
i_input_accepted_from_wrapper_lsu,
i_reset_timeout,
o_active
);
parameter PAGE_ADDR_WIDTH=32;
parameter TIMEOUT=8;
parameter BURSTCOUNT_WIDTH=6; // Size of Avalon burst count port
parameter MAXBURSTCOUNT=32; // This isn't the max supported by Avalon, but the max that the instantiating module needs
parameter MAX_THREADS=64; // Must be a power of 2
parameter USECACHING=0;
localparam SLAVE_MAX_BURST=2**(BURSTCOUNT_WIDTH-1);
localparam THREAD_COUNTER_WIDTH=$clog2(MAX_THREADS+1);
input clk;
input reset;
input [PAGE_ADDR_WIDTH-1:0] i_page_addr;
input i_nop;
input i_valid;
output o_stall;
output o_new_page;
output o_page_done;
output o_start_nop;
output [PAGE_ADDR_WIDTH-1:0] o_req_addr;
output o_req_valid;
output [BURSTCOUNT_WIDTH-1:0] o_burstcount;
input i_stall;
input common_burst;
input i_input_accepted_from_wrapper_lsu;
input i_reset_timeout;
output o_active;
reg [PAGE_ADDR_WIDTH-1:0] page_addr;
reg [PAGE_ADDR_WIDTH-1:0] last_page_addr;
reg [PAGE_ADDR_WIDTH-1:0] last_page_addr_p1;
reg [BURSTCOUNT_WIDTH-1:0] burstcount;
reg valid;
wire ready;
wire waiting;
wire match;
wire timeout;
reg [$clog2(TIMEOUT):0] timeout_counter;
reg [THREAD_COUNTER_WIDTH-1:0] thread_counter;
generate if(USECACHING)
begin
assign timeout = timeout_counter[$clog2(TIMEOUT)] | thread_counter[THREAD_COUNTER_WIDTH-1];
end
else
begin
assign timeout = timeout_counter[$clog2(TIMEOUT)];
end
endgenerate
// Internal signal logic
wire match_burst_address;
wire match_next_page;
wire match_current_page;
generate
if ( BURSTCOUNT_WIDTH > 1 )
begin
assign match_next_page = (i_page_addr[BURSTCOUNT_WIDTH-2:0] === last_page_addr_p1[BURSTCOUNT_WIDTH-2:0]) && (|last_page_addr_p1[BURSTCOUNT_WIDTH-2:0]);
assign match_current_page = (i_page_addr[BURSTCOUNT_WIDTH-2:0] === last_page_addr[BURSTCOUNT_WIDTH-2:0]);
end
else
begin
assign match_next_page = 1'b0;
assign match_current_page = 1'b1;
end
endgenerate
assign match_burst_address = common_burst;//(i_page_addr[PAGE_ADDR_WIDTH-1:BURSTCOUNT_WIDTH-1] == last_page_addr[PAGE_ADDR_WIDTH-1:BURSTCOUNT_WIDTH-1]);
assign match = (match_burst_address && (match_current_page || match_next_page)) && !thread_counter[THREAD_COUNTER_WIDTH-1];
assign ready = !valid || !(i_stall || waiting);
assign waiting = !timeout && (!i_valid || match);
wire input_accepted = i_valid && !o_stall;
assign o_start_nop = i_nop & ready;
assign o_active = valid;
always@(posedge clk or posedge reset)
begin
if(reset)
begin
page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
last_page_addr <= {PAGE_ADDR_WIDTH{1'b0}};
last_page_addr_p1 <= {PAGE_ADDR_WIDTH{1'b0}};
burstcount <= 1;
valid <= 1'b0;
timeout_counter <= 0;
thread_counter <= {THREAD_COUNTER_WIDTH{1'b0}};
end
else
begin
page_addr <= ready ? i_page_addr : page_addr;
last_page_addr <= ready ? i_page_addr : (input_accepted && match_next_page ? i_page_addr : last_page_addr );
last_page_addr_p1 <= ready ? i_page_addr+1 : (input_accepted && match_next_page ? i_page_addr+1 : last_page_addr_p1 );
valid <= ready ? i_valid & !i_nop : valid; // burst should not start with nop thread
burstcount <= ready ? 6'b000001 : (input_accepted && match_next_page ? burstcount+1 : burstcount );
thread_counter <= ready ? 1 : (USECACHING ?
(i_input_accepted_from_wrapper_lsu && !thread_counter[THREAD_COUNTER_WIDTH-1] ? thread_counter+1 : thread_counter ) :
(input_accepted ? thread_counter+1 : thread_counter));
if( USECACHING && i_reset_timeout || !USECACHING && i_valid )
timeout_counter <= 'd1;
else if( valid && !timeout )
timeout_counter <= timeout_counter + 'd1;
end
end
// Outputs
assign o_stall = !match && !ready && i_valid;
// We're starting a new page (used by loads)
assign o_new_page = ready || i_valid && match_burst_address && !thread_counter[THREAD_COUNTER_WIDTH-1] && match_next_page;
assign o_req_addr = page_addr;
assign o_burstcount = burstcount;
assign o_req_valid = valid && !waiting;
// We're just finished with a page (used by stores)
assign o_page_done = valid && !waiting && !i_stall || !ready && i_valid && match_burst_address && !thread_counter[THREAD_COUNTER_WIDTH-1] && match_next_page;
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;
integer v = 19;
initial begin
if (v==1) begin end
else if (v==2) begin end
else if (v==3) begin end
else if (v==4) begin end
else if (v==5) begin end
else if (v==6) begin end
else if (v==7) begin end
else if (v==8) begin end
else if (v==9) begin end
else if (v==10) begin end
else if (v==11) begin end // Warn about this one
else if (v==12) begin end
end
initial begin
unique0 if (v==1) begin end
else if (v==2) begin end
else if (v==3) begin end
else if (v==4) begin end
else if (v==5) begin end
else if (v==6) begin end
else if (v==7) begin end
else if (v==8) begin end
else if (v==9) begin end
else if (v==10) begin end
else if (v==11) begin end // Warn about this one
else if (v==12) begin end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
module t;
integer v = 19;
initial begin
if (v==1) begin end
else if (v==2) begin end
else if (v==3) begin end
else if (v==4) begin end
else if (v==5) begin end
else if (v==6) begin end
else if (v==7) begin end
else if (v==8) begin end
else if (v==9) begin end
else if (v==10) begin end
else if (v==11) begin end // Warn about this one
else if (v==12) begin end
end
initial begin
unique0 if (v==1) begin end
else if (v==2) begin end
else if (v==3) begin end
else if (v==4) begin end
else if (v==5) begin end
else if (v==6) begin end
else if (v==7) begin end
else if (v==8) begin end
else if (v==9) begin end
else if (v==10) begin end
else if (v==11) begin end // Warn about this one
else if (v==12) begin end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2010 by Wilson Snyder.
module t;
integer v = 19;
initial begin
if (v==1) begin end
else if (v==2) begin end
else if (v==3) begin end
else if (v==4) begin end
else if (v==5) begin end
else if (v==6) begin end
else if (v==7) begin end
else if (v==8) begin end
else if (v==9) begin end
else if (v==10) begin end
else if (v==11) begin end // Warn about this one
else if (v==12) begin end
end
initial begin
unique0 if (v==1) begin end
else if (v==2) begin end
else if (v==3) begin end
else if (v==4) begin end
else if (v==5) begin end
else if (v==6) begin end
else if (v==7) begin end
else if (v==8) begin end
else if (v==9) begin end
else if (v==10) begin end
else if (v==11) begin end // Warn about this one
else if (v==12) begin end
end
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2003 by Wilson Snyder.
module t;
reg [40:0] quad; initial quad = 41'ha_bbbb_cccc;
reg [80:0] wide; initial wide = 81'habc_1234_5678_1234_5678;
reg [31:0] str; initial str = "\000\277\021\n";
reg [47:0] str2; initial str2 = "\000what!";
reg [79:0] str3; initial str3 = "\000hmmm!1234";
reg [8:0] nine;
sub sub ();
sub2 sub2 ();
initial begin
$write("[%0t] In %m: Hi\n", $time);
sub.write_m;
sub2.write_m;
// Escapes
$display("[%0t] Back \\ Quote \"", $time); // Old bug when \" last on the line.
// Display formatting
nine = {3'd0,quad[5:0]};
$display("[%0t] %%X=%X %%0X=%0X %%0O=%0O %%B=%B", $time,
nine, nine, nine, nine);
$display("[%0t] %%x=%x %%0x=%0x %%0o=%0o %%b=%b", $time,
nine, nine, nine, nine);
$display("[%0t] %%D=%D %%d=%d %%01d=%01d %%06d=%06d %%6d=%6d", $time,
nine, nine, nine, nine, nine);
$display("[%0t] %%x=%x %%0x=%0x %%o=%o %%b=%b", $time,
quad, quad, quad, quad);
$display("[%0t] %%x=%x %%0x=%0x %%o=%o %%b=%b", $time,
wide, wide, wide, wide);
$display("[%0t] %%t=%t %%03t=%03t %%0t=%0t", $time,
$time, $time, $time);
$display;
// Not testing %0s, it does different things in different simulators
$display("[%0t] %%s=%s %%s=%s %%s=%s", $time,
str2[7:0], str2, str3);
$display("[%0t] %s%s%s", $time,
"hel", "lo, fr", "om a very long string. Percent %s are literally substituted in.");
$write("[%0t] Embedded \r return\n", $time);
$display("[%0t] Embedded\
multiline", $time);
// Str check
`ifndef NC // NC-Verilog 5.3 chokes on this test
if (str !== 32'h00_bf_11_0a) $stop;
`endif
$write("*-* All Finished *-*\n");
$finish;
end
endmodule
module sub;
task write_m;
begin
$write("[%0t] In %m\n", $time);
begin : subblock
$write("[%0t] In %M\n", $time); // Uppercase %M test
end
end
endtask
endmodule
module sub2;
// verilator no_inline_module
task write_m;
begin
$write("[%0t] In %m\n", $time);
begin : subblock2
$write("[%0t] In %m\n", $time);
end
end
endtask
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for the "cached" lsu
// Latency = 2
// Capacity = 1
//
// Description:
//
// This is essentially a streaming unit where threads can enter out of order
// It is organized as a direct mapped cache where there are N cache lines
// Each cache line is CACHESIZE bytes long
//
// By default, the values of N=8 and CACHESIZE=1024 bytes
//
// Feel free to change the parameters as determined by the data access patterns
//
// Note that this is a read only cache so one has to guarantee that data isn't
// going to get overwritten by some store within the kernel. The start signal
// is brought into this LSU to "flush" the cache once the kernel is started
//
// You'll notice that there are many similarities to the streaming unit including
// a FIFO size. Well, think of a cache as a FIFO where it can be accessed in any
// order :-)
//
// Note2: It is slightly different from other lsu's in that it needs a kernel start
// signal that tells it to invalidate it's contents
//
module lsu_read_cache
(
clk, reset, flush, o_stall, i_valid, i_stall, i_nop, o_valid, o_readdata,
o_active, //Debugging signal
i_address, avm_address, avm_burstcount, avm_read,
avm_readdata, avm_waitrequest, avm_byteenable, avm_readdatavalid,
// profile
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32;
parameter WIDTH_BYTES=32;
parameter MWIDTH_BYTES=32;
parameter ALIGNMENT_ABITS=6;
parameter BURSTCOUNT_WIDTH=6;
parameter KERNEL_SIDE_MEM_LATENCY=1;
parameter REQUESTED_SIZE=1024;
parameter ACL_BUFFER_ALIGNMENT=128;
parameter ACL_PROFILE=0;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam MBYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam BYTE_SELECT_BITS=$clog2(WIDTH_BYTES);
localparam MAXBURSTCOUNT=2**(BURSTCOUNT_WIDTH-1);
localparam CACHESIZE=ACL_BUFFER_ALIGNMENT/MWIDTH_BYTES > 1 ? ACL_BUFFER_ALIGNMENT : MWIDTH_BYTES*2 ;
localparam FIFO_DEPTH= CACHESIZE/MWIDTH_BYTES;
localparam FIFO_DEPTH_LOG2=$clog2(FIFO_DEPTH);
localparam CACHE_ADDRBITS=MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2;
localparam N=( (REQUESTED_SIZE+CACHESIZE-1) / CACHESIZE) ;
localparam LOG2N=$clog2(N);
localparam LOG2N_P=(LOG2N == 0)? 1 : LOG2N;
/********
* Ports *
********/
// Standard globals
input clk;
input reset;
input flush;
// Upstream pipeline interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
// Downstream pipeline interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
// ACL PROFILE
output req_cache_hit_count;
/***************
* Architecture *
***************/
wire stall_out;
wire prefetch_new_block;
reg [AWIDTH-1:0] reg_i_address;
reg reg_i_valid;
reg reg_i_nop;
reg [N-1:0] cache_valid;
wire cache_available;
reg cache_available_d1;
wire [MWIDTH-1:0] cache_data;
wire [WIDTH-1:0] extracted_cache_data;
wire [LOG2N_P-1:0] in_cache, in_cache_unreg;
generate
if(N==1) begin : GEN_N_IS_1
assign in_cache = 1'b0;
assign in_cache_unreg = 1'b0;
end
else begin : GEN_N_GREATER_THAN_1
assign in_cache = reg_i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
assign in_cache_unreg = i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
end
if(ACL_PROFILE) begin: GEN_ACL_PROFILE
reg R_thread_valid;
assign req_cache_hit_count = R_thread_valid && cache_valid[in_cache];
always@(posedge clk) begin
R_thread_valid <= i_valid & !i_nop & !stall_out;
end
end
endgenerate
assign o_stall = stall_out;
assign prefetch_new_block = reg_i_valid && !reg_i_nop && !cache_valid[in_cache];
wire stall_out_from_output_reg;
assign stall_out = reg_i_valid && !reg_i_nop && (prefetch_new_block || !cache_available || !cache_available_d1) || reg_i_valid && stall_out_from_output_reg;
reg output_reg_valid;
reg [WIDTH-1:0] output_reg;
assign stall_out_from_output_reg = output_reg_valid && i_stall;
integer i;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
cache_valid <= {N{1'b0}};
reg_i_address <=0;
reg_i_valid <= 1'b0;
reg_i_nop <= 1'b0;
output_reg_valid <= 1'b0;
output_reg <= 0;
cache_available_d1 <= 1'b0;
end
else
begin
cache_available_d1 <= cache_available;
if (flush)
begin
cache_valid <= {N{1'b0}};
$display("Flushing Cache\n");
end
else if (prefetch_new_block)
begin
$display("%m is Prefetching a cache block for address {%x} in line%d\n", reg_i_address, in_cache);
cache_valid[in_cache] <= 1'b1;
end
if (!stall_out)
begin
reg_i_valid <= i_valid;
reg_i_address <= i_address;
reg_i_nop <= i_nop;
end
if (!stall_out_from_output_reg)
begin
output_reg <= extracted_cache_data;
output_reg_valid <= reg_i_valid && !stall_out;
end
end
end
wire prefetch_active;
lsu_prefetch_block #(
.DATAWIDTH( MWIDTH ),
.MAXBURSTCOUNT( MAXBURSTCOUNT ),
.BURSTCOUNTWIDTH( BURSTCOUNT_WIDTH ),
.BYTEENABLEWIDTH( MWIDTH_BYTES ),
.ADDRESSWIDTH( AWIDTH ),
.FIFODEPTH( FIFO_DEPTH ),
.FIFODEPTH_LOG2( FIFO_DEPTH_LOG2 ),
.FIFOUSEMEMORY( 1 ),
.N(N),
.LOG2N(LOG2N)
) read_master (
.clk(clk),
.reset(reset),
.o_active(prefetch_active),
.control_fixed_location( 1'b0 ),
.control_read_base( {reg_i_address[AWIDTH-1:CACHE_ADDRBITS],{CACHE_ADDRBITS{1'b0}}} ),
.control_read_length( CACHESIZE ),
.control_go( prefetch_new_block ),
.cache_line_to_write_to( in_cache ),
.control_done(),
.control_early_done(),
.cache_line_to_read_from( in_cache_unreg ),
.user_buffer_address( i_address[MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2-1:MBYTE_SELECT_BITS] ),
.user_buffer_data( cache_data ),
.user_data_available( cache_available ),
.read_reg_enable(~stall_out),
.master_address( avm_address ),
.master_read( avm_read ),
.master_byteenable( avm_byteenable ),
.master_readdata( avm_readdata ),
.master_readdatavalid( avm_readdatavalid ),
.master_burstcount( avm_burstcount ),
.master_waitrequest( avm_waitrequest )
);
// Our RAM holds cache lines in chunks of MWIDTH (256 bits) so we need
// to extract the relevant bits with a mux for the user data
//
generate
if(MBYTE_SELECT_BITS != BYTE_SELECT_BITS)
begin
assign extracted_cache_data = cache_data[reg_i_address[MBYTE_SELECT_BITS-1:BYTE_SELECT_BITS] * WIDTH +: WIDTH];
end
else
begin
assign extracted_cache_data = cache_data;
end
endgenerate
assign o_readdata = output_reg;
assign o_valid = output_reg_valid;
assign o_active = reg_i_valid | prefetch_active;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for the "cached" lsu
// Latency = 2
// Capacity = 1
//
// Description:
//
// This is essentially a streaming unit where threads can enter out of order
// It is organized as a direct mapped cache where there are N cache lines
// Each cache line is CACHESIZE bytes long
//
// By default, the values of N=8 and CACHESIZE=1024 bytes
//
// Feel free to change the parameters as determined by the data access patterns
//
// Note that this is a read only cache so one has to guarantee that data isn't
// going to get overwritten by some store within the kernel. The start signal
// is brought into this LSU to "flush" the cache once the kernel is started
//
// You'll notice that there are many similarities to the streaming unit including
// a FIFO size. Well, think of a cache as a FIFO where it can be accessed in any
// order :-)
//
// Note2: It is slightly different from other lsu's in that it needs a kernel start
// signal that tells it to invalidate it's contents
//
module lsu_read_cache
(
clk, reset, flush, o_stall, i_valid, i_stall, i_nop, o_valid, o_readdata,
o_active, //Debugging signal
i_address, avm_address, avm_burstcount, avm_read,
avm_readdata, avm_waitrequest, avm_byteenable, avm_readdatavalid,
// profile
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32;
parameter WIDTH_BYTES=32;
parameter MWIDTH_BYTES=32;
parameter ALIGNMENT_ABITS=6;
parameter BURSTCOUNT_WIDTH=6;
parameter KERNEL_SIDE_MEM_LATENCY=1;
parameter REQUESTED_SIZE=1024;
parameter ACL_BUFFER_ALIGNMENT=128;
parameter ACL_PROFILE=0;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam MBYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam BYTE_SELECT_BITS=$clog2(WIDTH_BYTES);
localparam MAXBURSTCOUNT=2**(BURSTCOUNT_WIDTH-1);
localparam CACHESIZE=ACL_BUFFER_ALIGNMENT/MWIDTH_BYTES > 1 ? ACL_BUFFER_ALIGNMENT : MWIDTH_BYTES*2 ;
localparam FIFO_DEPTH= CACHESIZE/MWIDTH_BYTES;
localparam FIFO_DEPTH_LOG2=$clog2(FIFO_DEPTH);
localparam CACHE_ADDRBITS=MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2;
localparam N=( (REQUESTED_SIZE+CACHESIZE-1) / CACHESIZE) ;
localparam LOG2N=$clog2(N);
localparam LOG2N_P=(LOG2N == 0)? 1 : LOG2N;
/********
* Ports *
********/
// Standard globals
input clk;
input reset;
input flush;
// Upstream pipeline interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
// Downstream pipeline interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
// ACL PROFILE
output req_cache_hit_count;
/***************
* Architecture *
***************/
wire stall_out;
wire prefetch_new_block;
reg [AWIDTH-1:0] reg_i_address;
reg reg_i_valid;
reg reg_i_nop;
reg [N-1:0] cache_valid;
wire cache_available;
reg cache_available_d1;
wire [MWIDTH-1:0] cache_data;
wire [WIDTH-1:0] extracted_cache_data;
wire [LOG2N_P-1:0] in_cache, in_cache_unreg;
generate
if(N==1) begin : GEN_N_IS_1
assign in_cache = 1'b0;
assign in_cache_unreg = 1'b0;
end
else begin : GEN_N_GREATER_THAN_1
assign in_cache = reg_i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
assign in_cache_unreg = i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
end
if(ACL_PROFILE) begin: GEN_ACL_PROFILE
reg R_thread_valid;
assign req_cache_hit_count = R_thread_valid && cache_valid[in_cache];
always@(posedge clk) begin
R_thread_valid <= i_valid & !i_nop & !stall_out;
end
end
endgenerate
assign o_stall = stall_out;
assign prefetch_new_block = reg_i_valid && !reg_i_nop && !cache_valid[in_cache];
wire stall_out_from_output_reg;
assign stall_out = reg_i_valid && !reg_i_nop && (prefetch_new_block || !cache_available || !cache_available_d1) || reg_i_valid && stall_out_from_output_reg;
reg output_reg_valid;
reg [WIDTH-1:0] output_reg;
assign stall_out_from_output_reg = output_reg_valid && i_stall;
integer i;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
cache_valid <= {N{1'b0}};
reg_i_address <=0;
reg_i_valid <= 1'b0;
reg_i_nop <= 1'b0;
output_reg_valid <= 1'b0;
output_reg <= 0;
cache_available_d1 <= 1'b0;
end
else
begin
cache_available_d1 <= cache_available;
if (flush)
begin
cache_valid <= {N{1'b0}};
$display("Flushing Cache\n");
end
else if (prefetch_new_block)
begin
$display("%m is Prefetching a cache block for address {%x} in line%d\n", reg_i_address, in_cache);
cache_valid[in_cache] <= 1'b1;
end
if (!stall_out)
begin
reg_i_valid <= i_valid;
reg_i_address <= i_address;
reg_i_nop <= i_nop;
end
if (!stall_out_from_output_reg)
begin
output_reg <= extracted_cache_data;
output_reg_valid <= reg_i_valid && !stall_out;
end
end
end
wire prefetch_active;
lsu_prefetch_block #(
.DATAWIDTH( MWIDTH ),
.MAXBURSTCOUNT( MAXBURSTCOUNT ),
.BURSTCOUNTWIDTH( BURSTCOUNT_WIDTH ),
.BYTEENABLEWIDTH( MWIDTH_BYTES ),
.ADDRESSWIDTH( AWIDTH ),
.FIFODEPTH( FIFO_DEPTH ),
.FIFODEPTH_LOG2( FIFO_DEPTH_LOG2 ),
.FIFOUSEMEMORY( 1 ),
.N(N),
.LOG2N(LOG2N)
) read_master (
.clk(clk),
.reset(reset),
.o_active(prefetch_active),
.control_fixed_location( 1'b0 ),
.control_read_base( {reg_i_address[AWIDTH-1:CACHE_ADDRBITS],{CACHE_ADDRBITS{1'b0}}} ),
.control_read_length( CACHESIZE ),
.control_go( prefetch_new_block ),
.cache_line_to_write_to( in_cache ),
.control_done(),
.control_early_done(),
.cache_line_to_read_from( in_cache_unreg ),
.user_buffer_address( i_address[MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2-1:MBYTE_SELECT_BITS] ),
.user_buffer_data( cache_data ),
.user_data_available( cache_available ),
.read_reg_enable(~stall_out),
.master_address( avm_address ),
.master_read( avm_read ),
.master_byteenable( avm_byteenable ),
.master_readdata( avm_readdata ),
.master_readdatavalid( avm_readdatavalid ),
.master_burstcount( avm_burstcount ),
.master_waitrequest( avm_waitrequest )
);
// Our RAM holds cache lines in chunks of MWIDTH (256 bits) so we need
// to extract the relevant bits with a mux for the user data
//
generate
if(MBYTE_SELECT_BITS != BYTE_SELECT_BITS)
begin
assign extracted_cache_data = cache_data[reg_i_address[MBYTE_SELECT_BITS-1:BYTE_SELECT_BITS] * WIDTH +: WIDTH];
end
else
begin
assign extracted_cache_data = cache_data;
end
endgenerate
assign o_readdata = output_reg;
assign o_valid = output_reg_valid;
assign o_active = reg_i_valid | prefetch_active;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for the "cached" lsu
// Latency = 2
// Capacity = 1
//
// Description:
//
// This is essentially a streaming unit where threads can enter out of order
// It is organized as a direct mapped cache where there are N cache lines
// Each cache line is CACHESIZE bytes long
//
// By default, the values of N=8 and CACHESIZE=1024 bytes
//
// Feel free to change the parameters as determined by the data access patterns
//
// Note that this is a read only cache so one has to guarantee that data isn't
// going to get overwritten by some store within the kernel. The start signal
// is brought into this LSU to "flush" the cache once the kernel is started
//
// You'll notice that there are many similarities to the streaming unit including
// a FIFO size. Well, think of a cache as a FIFO where it can be accessed in any
// order :-)
//
// Note2: It is slightly different from other lsu's in that it needs a kernel start
// signal that tells it to invalidate it's contents
//
module lsu_read_cache
(
clk, reset, flush, o_stall, i_valid, i_stall, i_nop, o_valid, o_readdata,
o_active, //Debugging signal
i_address, avm_address, avm_burstcount, avm_read,
avm_readdata, avm_waitrequest, avm_byteenable, avm_readdatavalid,
// profile
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32;
parameter WIDTH_BYTES=32;
parameter MWIDTH_BYTES=32;
parameter ALIGNMENT_ABITS=6;
parameter BURSTCOUNT_WIDTH=6;
parameter KERNEL_SIDE_MEM_LATENCY=1;
parameter REQUESTED_SIZE=1024;
parameter ACL_BUFFER_ALIGNMENT=128;
parameter ACL_PROFILE=0;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam MBYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam BYTE_SELECT_BITS=$clog2(WIDTH_BYTES);
localparam MAXBURSTCOUNT=2**(BURSTCOUNT_WIDTH-1);
localparam CACHESIZE=ACL_BUFFER_ALIGNMENT/MWIDTH_BYTES > 1 ? ACL_BUFFER_ALIGNMENT : MWIDTH_BYTES*2 ;
localparam FIFO_DEPTH= CACHESIZE/MWIDTH_BYTES;
localparam FIFO_DEPTH_LOG2=$clog2(FIFO_DEPTH);
localparam CACHE_ADDRBITS=MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2;
localparam N=( (REQUESTED_SIZE+CACHESIZE-1) / CACHESIZE) ;
localparam LOG2N=$clog2(N);
localparam LOG2N_P=(LOG2N == 0)? 1 : LOG2N;
/********
* Ports *
********/
// Standard globals
input clk;
input reset;
input flush;
// Upstream pipeline interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
// Downstream pipeline interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
// ACL PROFILE
output req_cache_hit_count;
/***************
* Architecture *
***************/
wire stall_out;
wire prefetch_new_block;
reg [AWIDTH-1:0] reg_i_address;
reg reg_i_valid;
reg reg_i_nop;
reg [N-1:0] cache_valid;
wire cache_available;
reg cache_available_d1;
wire [MWIDTH-1:0] cache_data;
wire [WIDTH-1:0] extracted_cache_data;
wire [LOG2N_P-1:0] in_cache, in_cache_unreg;
generate
if(N==1) begin : GEN_N_IS_1
assign in_cache = 1'b0;
assign in_cache_unreg = 1'b0;
end
else begin : GEN_N_GREATER_THAN_1
assign in_cache = reg_i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
assign in_cache_unreg = i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
end
if(ACL_PROFILE) begin: GEN_ACL_PROFILE
reg R_thread_valid;
assign req_cache_hit_count = R_thread_valid && cache_valid[in_cache];
always@(posedge clk) begin
R_thread_valid <= i_valid & !i_nop & !stall_out;
end
end
endgenerate
assign o_stall = stall_out;
assign prefetch_new_block = reg_i_valid && !reg_i_nop && !cache_valid[in_cache];
wire stall_out_from_output_reg;
assign stall_out = reg_i_valid && !reg_i_nop && (prefetch_new_block || !cache_available || !cache_available_d1) || reg_i_valid && stall_out_from_output_reg;
reg output_reg_valid;
reg [WIDTH-1:0] output_reg;
assign stall_out_from_output_reg = output_reg_valid && i_stall;
integer i;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
cache_valid <= {N{1'b0}};
reg_i_address <=0;
reg_i_valid <= 1'b0;
reg_i_nop <= 1'b0;
output_reg_valid <= 1'b0;
output_reg <= 0;
cache_available_d1 <= 1'b0;
end
else
begin
cache_available_d1 <= cache_available;
if (flush)
begin
cache_valid <= {N{1'b0}};
$display("Flushing Cache\n");
end
else if (prefetch_new_block)
begin
$display("%m is Prefetching a cache block for address {%x} in line%d\n", reg_i_address, in_cache);
cache_valid[in_cache] <= 1'b1;
end
if (!stall_out)
begin
reg_i_valid <= i_valid;
reg_i_address <= i_address;
reg_i_nop <= i_nop;
end
if (!stall_out_from_output_reg)
begin
output_reg <= extracted_cache_data;
output_reg_valid <= reg_i_valid && !stall_out;
end
end
end
wire prefetch_active;
lsu_prefetch_block #(
.DATAWIDTH( MWIDTH ),
.MAXBURSTCOUNT( MAXBURSTCOUNT ),
.BURSTCOUNTWIDTH( BURSTCOUNT_WIDTH ),
.BYTEENABLEWIDTH( MWIDTH_BYTES ),
.ADDRESSWIDTH( AWIDTH ),
.FIFODEPTH( FIFO_DEPTH ),
.FIFODEPTH_LOG2( FIFO_DEPTH_LOG2 ),
.FIFOUSEMEMORY( 1 ),
.N(N),
.LOG2N(LOG2N)
) read_master (
.clk(clk),
.reset(reset),
.o_active(prefetch_active),
.control_fixed_location( 1'b0 ),
.control_read_base( {reg_i_address[AWIDTH-1:CACHE_ADDRBITS],{CACHE_ADDRBITS{1'b0}}} ),
.control_read_length( CACHESIZE ),
.control_go( prefetch_new_block ),
.cache_line_to_write_to( in_cache ),
.control_done(),
.control_early_done(),
.cache_line_to_read_from( in_cache_unreg ),
.user_buffer_address( i_address[MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2-1:MBYTE_SELECT_BITS] ),
.user_buffer_data( cache_data ),
.user_data_available( cache_available ),
.read_reg_enable(~stall_out),
.master_address( avm_address ),
.master_read( avm_read ),
.master_byteenable( avm_byteenable ),
.master_readdata( avm_readdata ),
.master_readdatavalid( avm_readdatavalid ),
.master_burstcount( avm_burstcount ),
.master_waitrequest( avm_waitrequest )
);
// Our RAM holds cache lines in chunks of MWIDTH (256 bits) so we need
// to extract the relevant bits with a mux for the user data
//
generate
if(MBYTE_SELECT_BITS != BYTE_SELECT_BITS)
begin
assign extracted_cache_data = cache_data[reg_i_address[MBYTE_SELECT_BITS-1:BYTE_SELECT_BITS] * WIDTH +: WIDTH];
end
else
begin
assign extracted_cache_data = cache_data;
end
endgenerate
assign o_readdata = output_reg;
assign o_valid = output_reg_valid;
assign o_active = reg_i_valid | prefetch_active;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for the "cached" lsu
// Latency = 2
// Capacity = 1
//
// Description:
//
// This is essentially a streaming unit where threads can enter out of order
// It is organized as a direct mapped cache where there are N cache lines
// Each cache line is CACHESIZE bytes long
//
// By default, the values of N=8 and CACHESIZE=1024 bytes
//
// Feel free to change the parameters as determined by the data access patterns
//
// Note that this is a read only cache so one has to guarantee that data isn't
// going to get overwritten by some store within the kernel. The start signal
// is brought into this LSU to "flush" the cache once the kernel is started
//
// You'll notice that there are many similarities to the streaming unit including
// a FIFO size. Well, think of a cache as a FIFO where it can be accessed in any
// order :-)
//
// Note2: It is slightly different from other lsu's in that it needs a kernel start
// signal that tells it to invalidate it's contents
//
module lsu_read_cache
(
clk, reset, flush, o_stall, i_valid, i_stall, i_nop, o_valid, o_readdata,
o_active, //Debugging signal
i_address, avm_address, avm_burstcount, avm_read,
avm_readdata, avm_waitrequest, avm_byteenable, avm_readdatavalid,
// profile
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32;
parameter WIDTH_BYTES=32;
parameter MWIDTH_BYTES=32;
parameter ALIGNMENT_ABITS=6;
parameter BURSTCOUNT_WIDTH=6;
parameter KERNEL_SIDE_MEM_LATENCY=1;
parameter REQUESTED_SIZE=1024;
parameter ACL_BUFFER_ALIGNMENT=128;
parameter ACL_PROFILE=0;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam MBYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam BYTE_SELECT_BITS=$clog2(WIDTH_BYTES);
localparam MAXBURSTCOUNT=2**(BURSTCOUNT_WIDTH-1);
localparam CACHESIZE=ACL_BUFFER_ALIGNMENT/MWIDTH_BYTES > 1 ? ACL_BUFFER_ALIGNMENT : MWIDTH_BYTES*2 ;
localparam FIFO_DEPTH= CACHESIZE/MWIDTH_BYTES;
localparam FIFO_DEPTH_LOG2=$clog2(FIFO_DEPTH);
localparam CACHE_ADDRBITS=MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2;
localparam N=( (REQUESTED_SIZE+CACHESIZE-1) / CACHESIZE) ;
localparam LOG2N=$clog2(N);
localparam LOG2N_P=(LOG2N == 0)? 1 : LOG2N;
/********
* Ports *
********/
// Standard globals
input clk;
input reset;
input flush;
// Upstream pipeline interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
// Downstream pipeline interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
// ACL PROFILE
output req_cache_hit_count;
/***************
* Architecture *
***************/
wire stall_out;
wire prefetch_new_block;
reg [AWIDTH-1:0] reg_i_address;
reg reg_i_valid;
reg reg_i_nop;
reg [N-1:0] cache_valid;
wire cache_available;
reg cache_available_d1;
wire [MWIDTH-1:0] cache_data;
wire [WIDTH-1:0] extracted_cache_data;
wire [LOG2N_P-1:0] in_cache, in_cache_unreg;
generate
if(N==1) begin : GEN_N_IS_1
assign in_cache = 1'b0;
assign in_cache_unreg = 1'b0;
end
else begin : GEN_N_GREATER_THAN_1
assign in_cache = reg_i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
assign in_cache_unreg = i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
end
if(ACL_PROFILE) begin: GEN_ACL_PROFILE
reg R_thread_valid;
assign req_cache_hit_count = R_thread_valid && cache_valid[in_cache];
always@(posedge clk) begin
R_thread_valid <= i_valid & !i_nop & !stall_out;
end
end
endgenerate
assign o_stall = stall_out;
assign prefetch_new_block = reg_i_valid && !reg_i_nop && !cache_valid[in_cache];
wire stall_out_from_output_reg;
assign stall_out = reg_i_valid && !reg_i_nop && (prefetch_new_block || !cache_available || !cache_available_d1) || reg_i_valid && stall_out_from_output_reg;
reg output_reg_valid;
reg [WIDTH-1:0] output_reg;
assign stall_out_from_output_reg = output_reg_valid && i_stall;
integer i;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
cache_valid <= {N{1'b0}};
reg_i_address <=0;
reg_i_valid <= 1'b0;
reg_i_nop <= 1'b0;
output_reg_valid <= 1'b0;
output_reg <= 0;
cache_available_d1 <= 1'b0;
end
else
begin
cache_available_d1 <= cache_available;
if (flush)
begin
cache_valid <= {N{1'b0}};
$display("Flushing Cache\n");
end
else if (prefetch_new_block)
begin
$display("%m is Prefetching a cache block for address {%x} in line%d\n", reg_i_address, in_cache);
cache_valid[in_cache] <= 1'b1;
end
if (!stall_out)
begin
reg_i_valid <= i_valid;
reg_i_address <= i_address;
reg_i_nop <= i_nop;
end
if (!stall_out_from_output_reg)
begin
output_reg <= extracted_cache_data;
output_reg_valid <= reg_i_valid && !stall_out;
end
end
end
wire prefetch_active;
lsu_prefetch_block #(
.DATAWIDTH( MWIDTH ),
.MAXBURSTCOUNT( MAXBURSTCOUNT ),
.BURSTCOUNTWIDTH( BURSTCOUNT_WIDTH ),
.BYTEENABLEWIDTH( MWIDTH_BYTES ),
.ADDRESSWIDTH( AWIDTH ),
.FIFODEPTH( FIFO_DEPTH ),
.FIFODEPTH_LOG2( FIFO_DEPTH_LOG2 ),
.FIFOUSEMEMORY( 1 ),
.N(N),
.LOG2N(LOG2N)
) read_master (
.clk(clk),
.reset(reset),
.o_active(prefetch_active),
.control_fixed_location( 1'b0 ),
.control_read_base( {reg_i_address[AWIDTH-1:CACHE_ADDRBITS],{CACHE_ADDRBITS{1'b0}}} ),
.control_read_length( CACHESIZE ),
.control_go( prefetch_new_block ),
.cache_line_to_write_to( in_cache ),
.control_done(),
.control_early_done(),
.cache_line_to_read_from( in_cache_unreg ),
.user_buffer_address( i_address[MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2-1:MBYTE_SELECT_BITS] ),
.user_buffer_data( cache_data ),
.user_data_available( cache_available ),
.read_reg_enable(~stall_out),
.master_address( avm_address ),
.master_read( avm_read ),
.master_byteenable( avm_byteenable ),
.master_readdata( avm_readdata ),
.master_readdatavalid( avm_readdatavalid ),
.master_burstcount( avm_burstcount ),
.master_waitrequest( avm_waitrequest )
);
// Our RAM holds cache lines in chunks of MWIDTH (256 bits) so we need
// to extract the relevant bits with a mux for the user data
//
generate
if(MBYTE_SELECT_BITS != BYTE_SELECT_BITS)
begin
assign extracted_cache_data = cache_data[reg_i_address[MBYTE_SELECT_BITS-1:BYTE_SELECT_BITS] * WIDTH +: WIDTH];
end
else
begin
assign extracted_cache_data = cache_data;
end
endgenerate
assign o_readdata = output_reg;
assign o_valid = output_reg_valid;
assign o_active = reg_i_valid | prefetch_active;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for the "cached" lsu
// Latency = 2
// Capacity = 1
//
// Description:
//
// This is essentially a streaming unit where threads can enter out of order
// It is organized as a direct mapped cache where there are N cache lines
// Each cache line is CACHESIZE bytes long
//
// By default, the values of N=8 and CACHESIZE=1024 bytes
//
// Feel free to change the parameters as determined by the data access patterns
//
// Note that this is a read only cache so one has to guarantee that data isn't
// going to get overwritten by some store within the kernel. The start signal
// is brought into this LSU to "flush" the cache once the kernel is started
//
// You'll notice that there are many similarities to the streaming unit including
// a FIFO size. Well, think of a cache as a FIFO where it can be accessed in any
// order :-)
//
// Note2: It is slightly different from other lsu's in that it needs a kernel start
// signal that tells it to invalidate it's contents
//
module lsu_read_cache
(
clk, reset, flush, o_stall, i_valid, i_stall, i_nop, o_valid, o_readdata,
o_active, //Debugging signal
i_address, avm_address, avm_burstcount, avm_read,
avm_readdata, avm_waitrequest, avm_byteenable, avm_readdatavalid,
// profile
req_cache_hit_count
);
/*************
* Parameters *
*************/
parameter AWIDTH=32;
parameter WIDTH_BYTES=32;
parameter MWIDTH_BYTES=32;
parameter ALIGNMENT_ABITS=6;
parameter BURSTCOUNT_WIDTH=6;
parameter KERNEL_SIDE_MEM_LATENCY=1;
parameter REQUESTED_SIZE=1024;
parameter ACL_BUFFER_ALIGNMENT=128;
parameter ACL_PROFILE=0;
// Derived parameters
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam MBYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam BYTE_SELECT_BITS=$clog2(WIDTH_BYTES);
localparam MAXBURSTCOUNT=2**(BURSTCOUNT_WIDTH-1);
localparam CACHESIZE=ACL_BUFFER_ALIGNMENT/MWIDTH_BYTES > 1 ? ACL_BUFFER_ALIGNMENT : MWIDTH_BYTES*2 ;
localparam FIFO_DEPTH= CACHESIZE/MWIDTH_BYTES;
localparam FIFO_DEPTH_LOG2=$clog2(FIFO_DEPTH);
localparam CACHE_ADDRBITS=MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2;
localparam N=( (REQUESTED_SIZE+CACHESIZE-1) / CACHESIZE) ;
localparam LOG2N=$clog2(N);
localparam LOG2N_P=(LOG2N == 0)? 1 : LOG2N;
/********
* Ports *
********/
// Standard globals
input clk;
input reset;
input flush;
// Upstream pipeline interface
output o_stall;
input i_valid;
input i_nop;
input [AWIDTH-1:0] i_address;
// Downstream pipeline interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output [BURSTCOUNT_WIDTH-1:0] avm_burstcount;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
// ACL PROFILE
output req_cache_hit_count;
/***************
* Architecture *
***************/
wire stall_out;
wire prefetch_new_block;
reg [AWIDTH-1:0] reg_i_address;
reg reg_i_valid;
reg reg_i_nop;
reg [N-1:0] cache_valid;
wire cache_available;
reg cache_available_d1;
wire [MWIDTH-1:0] cache_data;
wire [WIDTH-1:0] extracted_cache_data;
wire [LOG2N_P-1:0] in_cache, in_cache_unreg;
generate
if(N==1) begin : GEN_N_IS_1
assign in_cache = 1'b0;
assign in_cache_unreg = 1'b0;
end
else begin : GEN_N_GREATER_THAN_1
assign in_cache = reg_i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
assign in_cache_unreg = i_address[CACHE_ADDRBITS+LOG2N-1:CACHE_ADDRBITS];
end
if(ACL_PROFILE) begin: GEN_ACL_PROFILE
reg R_thread_valid;
assign req_cache_hit_count = R_thread_valid && cache_valid[in_cache];
always@(posedge clk) begin
R_thread_valid <= i_valid & !i_nop & !stall_out;
end
end
endgenerate
assign o_stall = stall_out;
assign prefetch_new_block = reg_i_valid && !reg_i_nop && !cache_valid[in_cache];
wire stall_out_from_output_reg;
assign stall_out = reg_i_valid && !reg_i_nop && (prefetch_new_block || !cache_available || !cache_available_d1) || reg_i_valid && stall_out_from_output_reg;
reg output_reg_valid;
reg [WIDTH-1:0] output_reg;
assign stall_out_from_output_reg = output_reg_valid && i_stall;
integer i;
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
cache_valid <= {N{1'b0}};
reg_i_address <=0;
reg_i_valid <= 1'b0;
reg_i_nop <= 1'b0;
output_reg_valid <= 1'b0;
output_reg <= 0;
cache_available_d1 <= 1'b0;
end
else
begin
cache_available_d1 <= cache_available;
if (flush)
begin
cache_valid <= {N{1'b0}};
$display("Flushing Cache\n");
end
else if (prefetch_new_block)
begin
$display("%m is Prefetching a cache block for address {%x} in line%d\n", reg_i_address, in_cache);
cache_valid[in_cache] <= 1'b1;
end
if (!stall_out)
begin
reg_i_valid <= i_valid;
reg_i_address <= i_address;
reg_i_nop <= i_nop;
end
if (!stall_out_from_output_reg)
begin
output_reg <= extracted_cache_data;
output_reg_valid <= reg_i_valid && !stall_out;
end
end
end
wire prefetch_active;
lsu_prefetch_block #(
.DATAWIDTH( MWIDTH ),
.MAXBURSTCOUNT( MAXBURSTCOUNT ),
.BURSTCOUNTWIDTH( BURSTCOUNT_WIDTH ),
.BYTEENABLEWIDTH( MWIDTH_BYTES ),
.ADDRESSWIDTH( AWIDTH ),
.FIFODEPTH( FIFO_DEPTH ),
.FIFODEPTH_LOG2( FIFO_DEPTH_LOG2 ),
.FIFOUSEMEMORY( 1 ),
.N(N),
.LOG2N(LOG2N)
) read_master (
.clk(clk),
.reset(reset),
.o_active(prefetch_active),
.control_fixed_location( 1'b0 ),
.control_read_base( {reg_i_address[AWIDTH-1:CACHE_ADDRBITS],{CACHE_ADDRBITS{1'b0}}} ),
.control_read_length( CACHESIZE ),
.control_go( prefetch_new_block ),
.cache_line_to_write_to( in_cache ),
.control_done(),
.control_early_done(),
.cache_line_to_read_from( in_cache_unreg ),
.user_buffer_address( i_address[MBYTE_SELECT_BITS+FIFO_DEPTH_LOG2-1:MBYTE_SELECT_BITS] ),
.user_buffer_data( cache_data ),
.user_data_available( cache_available ),
.read_reg_enable(~stall_out),
.master_address( avm_address ),
.master_read( avm_read ),
.master_byteenable( avm_byteenable ),
.master_readdata( avm_readdata ),
.master_readdatavalid( avm_readdatavalid ),
.master_burstcount( avm_burstcount ),
.master_waitrequest( avm_waitrequest )
);
// Our RAM holds cache lines in chunks of MWIDTH (256 bits) so we need
// to extract the relevant bits with a mux for the user data
//
generate
if(MBYTE_SELECT_BITS != BYTE_SELECT_BITS)
begin
assign extracted_cache_data = cache_data[reg_i_address[MBYTE_SELECT_BITS-1:BYTE_SELECT_BITS] * WIDTH +: WIDTH];
end
else
begin
assign extracted_cache_data = cache_data;
end
endgenerate
assign o_readdata = output_reg;
assign o_valid = output_reg_valid;
assign o_active = reg_i_valid | prefetch_active;
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.
// This module generates the finish signal for the entire kernel.
// There are two main ports on this module:
// 1. From work-group dispatcher: to detect when a work-GROUP is issued
// It is ASSUMED that the work-group dispatcher issues at most one work-group
// per cycle.
// 2. From exit points of each kernel copy: to detect when a work-ITEM is completed.
module acl_kernel_finish_detector #(
parameter integer NUM_COPIES = 1, // >0
parameter integer WG_SIZE_W = 1, // >0
parameter integer GLOBAL_ID_W = 32 // >0, number of bits for one global id dimension
)
(
input logic clock,
input logic resetn,
input logic start,
input logic [WG_SIZE_W-1:0] wg_size,
// From work-group dispatcher. It is ASSUMED that
// at most one work-group is dispatched per cycle.
input logic [NUM_COPIES-1:0] wg_dispatch_valid_out,
input logic [NUM_COPIES-1:0] wg_dispatch_stall_in,
input logic dispatched_all_groups,
// From copies of the kernel pipeline.
input logic [NUM_COPIES-1:0] kernel_copy_valid_out,
input logic [NUM_COPIES-1:0] kernel_copy_stall_in,
input logic pending_writes,
// The finish signal is a single-cycle pulse.
output logic finish
);
localparam NUM_GLOBAL_DIMS = 3;
localparam MAX_NDRANGE_SIZE_W = NUM_GLOBAL_DIMS * GLOBAL_ID_W;
// Count the total number of work-items in the entire ND-range. This count
// is incremented as work-groups are issued.
// This value is not final until dispatched_all_groups has been asserted.
logic [MAX_NDRANGE_SIZE_W-1:0] ndrange_items;
logic wg_dispatched;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
ndrange_items <= '0;
else if( start ) // ASSUME start and wg_dispatched are mutually exclusive
ndrange_items <= '0;
else if( wg_dispatched )
// This is where the one work-group per cycle assumption is used.
ndrange_items <= ndrange_items + wg_size;
end
// Here we ASSUME that at most one work-group is dispatched per cycle.
// This depends on the acl_work_group_dispatcher.
assign wg_dispatched = |(wg_dispatch_valid_out & ~wg_dispatch_stall_in);
// Count the number of work-items that have exited all kernel pipelines.
logic [NUM_COPIES-1:0] kernel_copy_item_exit;
logic [MAX_NDRANGE_SIZE_W-1:0] completed_items;
logic [$clog2(NUM_COPIES+1)-1:0] completed_items_incr_comb, completed_items_incr;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
begin
kernel_copy_item_exit <= '0;
completed_items_incr <= '0;
end
else
begin
kernel_copy_item_exit <= kernel_copy_valid_out & ~kernel_copy_stall_in;
completed_items_incr <= completed_items_incr_comb;
end
end
// This is not the best representation, but hopefully synthesis will do something
// intelligent here (e.g. use compressors?). Assuming that the number of
// copies will never be that high to have to pipeline this addition.
always @(*)
begin
completed_items_incr_comb = '0;
for( integer i = 0; i < NUM_COPIES; ++i )
completed_items_incr_comb = completed_items_incr_comb + kernel_copy_item_exit[i];
end
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
completed_items <= '0;
else if( start ) // ASSUME that work-items do not complete on the same cycle as start
completed_items <= '0;
else
completed_items <= completed_items + completed_items_incr;
end
// Determine if the ND-range has completed. This is true when
// the ndrange_items counter is complete (i.e. dispatched_all_groups)
// and the completed_items counter is equal to the ndrang_items counter.
logic ndrange_done;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
ndrange_done <= 1'b0;
else if( start )
ndrange_done <= 1'b0;
else
// ASSUMING that dispatched_all_groups is asserted at least one cycle
// after the last work-group is issued
ndrange_done <= dispatched_all_groups & (ndrange_items == completed_items);
end
// The finish output needs to be a one-cycle pulse when the ndrange is completed
// AND there are no pending writes.
logic finish_asserted;
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
finish <= 1'b0;
else
finish <= ~finish_asserted & ndrange_done & ~pending_writes;
end
always @(posedge clock or negedge resetn)
begin
if( ~resetn )
finish_asserted <= 1'b0;
else if( start )
finish_asserted <= 1'b0;
else if( finish )
finish_asserted <= 1'b1;
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for simple memory access. See lsu_top.v.
//
// Properties - Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: No
// (see lsu_top.v for details)
//
// Description: Simple un-pipelined memory access. Low throughput.
//
// Simple read unit:
// Accept read requests on the upstream interface. When a request is
// received, set the pending register to true to stall any subsequent
// requests until the transaction is complete. Since an avalon master
// cannot stall a response, staging registers are used at the output to
// provide a storage location until the downstream block is ready to accept
// data. Once the output registers are cleared and there are no pending
// requests, accept a new transaction.
module lsu_simple_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, // Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
// - indicates how many bits of the address
// are '0' due to the request alignment
parameter HIGH_FMAX=1;
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam MIN_BYTE_SELECT_BITS = BYTE_SELECT_BITS == 0 ? 1 : BYTE_SELECT_BITS;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
reg pending;
wire read_accepted;
wire rdata_accepted;
wire sr_stall;
wire ready;
wire [WIDTH-1:0] rdata;
wire [MIN_BYTE_SELECT_BITS-1:0] byte_address;
reg [MIN_BYTE_SELECT_BITS-1:0] byte_select;
// Ready for new data if we have access to the downstream registers and there
// is no pending memory transaction
assign ready = !sr_stall && !pending;
wire [AWIDTH-1:0] f_avm_address;
wire f_avm_read;
wire f_avm_waitrequest;
// Avalon signals - passed through from inputs
assign f_avm_address = (i_address[AWIDTH-1:BYTE_SELECT_BITS] << BYTE_SELECT_BITS);
assign f_avm_read = i_valid && ready;
assign avm_byteenable = {MWIDTH_BYTES{1'b1}};
// Upstream stall if we aren't ready for new data, or the avalon interface
// is stalling.
assign o_stall = f_avm_waitrequest || !ready;
// Pick out the byte address
// Explicitly set alignment address bits to 0 to help synthesis optimizations.
generate
if (BYTE_SELECT_BITS == 0) begin
assign byte_address = 1'b0;
end
else begin
assign byte_address = ((i_address[MIN_BYTE_SELECT_BITS-1:0] >> ALIGNMENT_ABITS) << ALIGNMENT_ABITS);
end
endgenerate
// State registers
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
pending <= 1'b0;
byte_select <= 'x; // don't need to reset
end
else
begin
// A requst remains pending until we receive valid data; and a request
// becomes pending if we accept a new valid input
pending <= pending ? !avm_readdatavalid : (i_valid && !o_stall && !avm_readdatavalid);
// Remember which bytes to select out of the wider global memory bus.
byte_select <= pending ? byte_select : byte_address;
end
end
// Mux in the appropriate response bits
assign rdata = avm_readdata[8*byte_select +: WIDTH];
// Output staging register - required so that we can guarantee there is
// a place to store the readdata response
acl_staging_reg #(
.WIDTH(WIDTH)
) staging_reg (
.clk(clk),
.reset(reset),
.i_data(rdata),
.i_valid(avm_readdatavalid),
.o_stall(sr_stall),
.o_data(o_readdata),
.o_valid(o_valid),
.i_stall (i_stall)
);
generate
if(HIGH_FMAX)
begin
// Pipeline the interface
acl_data_fifo #(
.DATA_WIDTH(AWIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) avm_buffer (
.clock(clk),
.resetn(!reset),
.data_in(f_avm_address),
.valid_in(f_avm_read),
.data_out(avm_address),
.valid_out( avm_read ),
.stall_in( avm_waitrequest ),
.stall_out( f_avm_waitrequest )
);
end
else
begin
// No interface pipelining
assign f_avm_waitrequest = avm_waitrequest;
assign avm_address = f_avm_address;
assign avm_read = f_avm_read;
end
endgenerate
assign o_active=pending;
endmodule
// Simple write unit:
// Accept write requests on the upstream interface. When a request is
// received, pass it through to the avalon bus. Once avalon accepts
// the request, set the output valid bit to true and stall until
// the downstream block acknowledges the successful write.
module lsu_simple_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, // Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the request
parameter MWIDTH_BYTES=32; // Width of the global memory bus
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
parameter USE_BYTE_EN=0;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
input [WIDTH_BYTES-1:0] i_byteenable;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output reg [MWIDTH-1:0] avm_writedata;
output reg [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
/***************
* Architecture *
***************/
reg write_pending;
wire write_accepted;
wire ready;
wire sr_stall;
// Avalon interface
assign avm_address = ((i_address >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS);
assign avm_write = ready && i_valid;
// Mux in the correct data
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
end
else
begin
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[0 +: WIDTH] = i_writedata;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
end
endgenerate
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
write_pending <= 1'b0;
end
else
begin
write_pending <= (write_accepted || write_pending) && !avm_writeack;
end
end
// Control logic
assign ready = !sr_stall && !write_pending;
assign write_accepted = avm_write && !avm_waitrequest;
assign o_stall = !ready || avm_waitrequest;
// Output staging register - required so that we can guarantee there is
// a place to store the valid bit
acl_staging_reg #(
.WIDTH(1)
) staging_reg (
.clk(clk),
.reset(reset),
.i_data(1'b0),
.i_valid(avm_writeack),
.o_stall(sr_stall),
.o_data(),
.o_valid(o_valid),
.i_stall (i_stall)
);
assign o_active=write_pending;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//
// Top level module for simple memory access. See lsu_top.v.
//
// Properties - Coalesced: No, Ordered: N/A, Hazard-Safe: Yes, Pipelined: No
// (see lsu_top.v for details)
//
// Description: Simple un-pipelined memory access. Low throughput.
//
// Simple read unit:
// Accept read requests on the upstream interface. When a request is
// received, set the pending register to true to stall any subsequent
// requests until the transaction is complete. Since an avalon master
// cannot stall a response, staging registers are used at the output to
// provide a storage location until the downstream block is ready to accept
// data. Once the output registers are cleared and there are no pending
// requests, accept a new transaction.
module lsu_simple_read
(
clk, reset, o_stall, i_valid, i_address, i_stall, o_valid, o_readdata,
o_active, // Debugging signal
avm_address, avm_read, avm_readdata, avm_waitrequest, avm_byteenable,
avm_readdatavalid
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the memory access (bytes)
parameter MWIDTH_BYTES=32; // Width of the global memory bus (bytes)
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
// - indicates how many bits of the address
// are '0' due to the request alignment
parameter HIGH_FMAX=1;
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam MIN_BYTE_SELECT_BITS = BYTE_SELECT_BITS == 0 ? 1 : BYTE_SELECT_BITS;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
// Downstream interface
input i_stall;
output o_valid;
output [WIDTH-1:0] o_readdata;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_read;
input [MWIDTH-1:0] avm_readdata;
input avm_waitrequest;
output [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_readdatavalid;
/***************
* Architecture *
***************/
reg pending;
wire read_accepted;
wire rdata_accepted;
wire sr_stall;
wire ready;
wire [WIDTH-1:0] rdata;
wire [MIN_BYTE_SELECT_BITS-1:0] byte_address;
reg [MIN_BYTE_SELECT_BITS-1:0] byte_select;
// Ready for new data if we have access to the downstream registers and there
// is no pending memory transaction
assign ready = !sr_stall && !pending;
wire [AWIDTH-1:0] f_avm_address;
wire f_avm_read;
wire f_avm_waitrequest;
// Avalon signals - passed through from inputs
assign f_avm_address = (i_address[AWIDTH-1:BYTE_SELECT_BITS] << BYTE_SELECT_BITS);
assign f_avm_read = i_valid && ready;
assign avm_byteenable = {MWIDTH_BYTES{1'b1}};
// Upstream stall if we aren't ready for new data, or the avalon interface
// is stalling.
assign o_stall = f_avm_waitrequest || !ready;
// Pick out the byte address
// Explicitly set alignment address bits to 0 to help synthesis optimizations.
generate
if (BYTE_SELECT_BITS == 0) begin
assign byte_address = 1'b0;
end
else begin
assign byte_address = ((i_address[MIN_BYTE_SELECT_BITS-1:0] >> ALIGNMENT_ABITS) << ALIGNMENT_ABITS);
end
endgenerate
// State registers
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
pending <= 1'b0;
byte_select <= 'x; // don't need to reset
end
else
begin
// A requst remains pending until we receive valid data; and a request
// becomes pending if we accept a new valid input
pending <= pending ? !avm_readdatavalid : (i_valid && !o_stall && !avm_readdatavalid);
// Remember which bytes to select out of the wider global memory bus.
byte_select <= pending ? byte_select : byte_address;
end
end
// Mux in the appropriate response bits
assign rdata = avm_readdata[8*byte_select +: WIDTH];
// Output staging register - required so that we can guarantee there is
// a place to store the readdata response
acl_staging_reg #(
.WIDTH(WIDTH)
) staging_reg (
.clk(clk),
.reset(reset),
.i_data(rdata),
.i_valid(avm_readdatavalid),
.o_stall(sr_stall),
.o_data(o_readdata),
.o_valid(o_valid),
.i_stall (i_stall)
);
generate
if(HIGH_FMAX)
begin
// Pipeline the interface
acl_data_fifo #(
.DATA_WIDTH(AWIDTH),
.DEPTH(2),
.IMPL("ll_reg")
) avm_buffer (
.clock(clk),
.resetn(!reset),
.data_in(f_avm_address),
.valid_in(f_avm_read),
.data_out(avm_address),
.valid_out( avm_read ),
.stall_in( avm_waitrequest ),
.stall_out( f_avm_waitrequest )
);
end
else
begin
// No interface pipelining
assign f_avm_waitrequest = avm_waitrequest;
assign avm_address = f_avm_address;
assign avm_read = f_avm_read;
end
endgenerate
assign o_active=pending;
endmodule
// Simple write unit:
// Accept write requests on the upstream interface. When a request is
// received, pass it through to the avalon bus. Once avalon accepts
// the request, set the output valid bit to true and stall until
// the downstream block acknowledges the successful write.
module lsu_simple_write
(
clk, reset, o_stall, i_valid, i_address, i_writedata, i_stall, o_valid, i_byteenable,
o_active, // Debugging signal
avm_address, avm_write, avm_writeack, avm_writedata, avm_byteenable, avm_waitrequest
);
/*************
* Parameters *
*************/
parameter AWIDTH=32; // Address width (32-bits for Avalon)
parameter WIDTH_BYTES=4; // Width of the request
parameter MWIDTH_BYTES=32; // Width of the global memory bus
parameter ALIGNMENT_ABITS=2; // Request address alignment (address bits)
localparam WIDTH=8*WIDTH_BYTES;
localparam MWIDTH=8*MWIDTH_BYTES;
localparam BYTE_SELECT_BITS=$clog2(MWIDTH_BYTES);
localparam SEGMENT_SELECT_BITS=BYTE_SELECT_BITS-ALIGNMENT_ABITS;
localparam NUM_SEGMENTS=2**SEGMENT_SELECT_BITS;
localparam SEGMENT_WIDTH=8*(2**ALIGNMENT_ABITS);
localparam SEGMENT_WIDTH_BYTES=(2**ALIGNMENT_ABITS);
parameter USE_BYTE_EN=0;
/********
* Ports *
********/
// Standard global signals
input clk;
input reset;
// Upstream interface
output o_stall;
input i_valid;
input [AWIDTH-1:0] i_address;
input [WIDTH-1:0] i_writedata;
input [WIDTH_BYTES-1:0] i_byteenable;
// Downstream interface
input i_stall;
output o_valid;
output o_active;
// Avalon interface
output [AWIDTH-1:0] avm_address;
output avm_write;
input avm_writeack;
output reg [MWIDTH-1:0] avm_writedata;
output reg [MWIDTH_BYTES-1:0] avm_byteenable;
input avm_waitrequest;
/***************
* Architecture *
***************/
reg write_pending;
wire write_accepted;
wire ready;
wire sr_stall;
// Avalon interface
assign avm_address = ((i_address >> BYTE_SELECT_BITS) << BYTE_SELECT_BITS);
assign avm_write = ready && i_valid;
// Mux in the correct data
generate if( SEGMENT_SELECT_BITS > 0 )
begin
wire [SEGMENT_SELECT_BITS-1:0] segment_select;
assign segment_select = i_address[BYTE_SELECT_BITS-1:ALIGNMENT_ABITS];
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[segment_select*SEGMENT_WIDTH +: WIDTH] = i_writedata;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[segment_select*SEGMENT_WIDTH_BYTES +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
end
else
begin
always@(*)
begin
avm_writedata = {MWIDTH{1'bx}};
avm_writedata[0 +: WIDTH] = i_writedata;
avm_byteenable = {MWIDTH_BYTES{1'b0}};
avm_byteenable[0 +: WIDTH_BYTES] = USE_BYTE_EN ? i_byteenable : {WIDTH_BYTES{1'b1}};
end
end
endgenerate
always@(posedge clk or posedge reset)
begin
if(reset == 1'b1)
begin
write_pending <= 1'b0;
end
else
begin
write_pending <= (write_accepted || write_pending) && !avm_writeack;
end
end
// Control logic
assign ready = !sr_stall && !write_pending;
assign write_accepted = avm_write && !avm_waitrequest;
assign o_stall = !ready || avm_waitrequest;
// Output staging register - required so that we can guarantee there is
// a place to store the valid bit
acl_staging_reg #(
.WIDTH(1)
) staging_reg (
.clk(clk),
.reset(reset),
.i_data(1'b0),
.i_valid(avm_writeack),
.o_stall(sr_stall),
.o_data(),
.o_valid(o_valid),
.i_stall (i_stall)
);
assign o_active=write_pending;
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.
// This module dispatches group ids to possibly multiple work item iterators.
// Each work-item iterator should be separated by a fifo from the dispatcher.
module acl_work_group_dispatcher
#(
parameter WIDTH = 32, // width of all the counters
parameter NUM_COPIES = 1, // number of kernel copies to manage
parameter RUN_FOREVER = 0 // flag for infinitely running kernel
)
(
input clock,
input resetn,
input start, // Assert to restart the iterators
// Populated during kernel startup
input [WIDTH-1:0] num_groups[2:0],
input [WIDTH-1:0] local_size[2:0],
// Handshaking with iterators for each kernel copy
input [NUM_COPIES-1:0] stall_in,
output [NUM_COPIES-1:0] valid_out,
// Export group_id to iterators.
output reg [WIDTH-1:0] group_id_out[2:0],
output reg [WIDTH-1:0] global_id_base_out[2:0],
output start_out,
// High when all groups have been dispatched to id iterators
output reg dispatched_all_groups
);
//////////////////////////////////
// Group id register updates.
reg started; // one cycle delayed after start goes high. stays high
reg delayed_start; // two cycles delayed after start goes high. stays high
reg [WIDTH-1:0] max_group_id[2:0];
reg [WIDTH-1:0] group_id[2:0];
wire last_group_id[2:0];
assign last_group_id[0] = (group_id[0] == max_group_id[0] );
assign last_group_id[1] = (group_id[1] == max_group_id[1] );
assign last_group_id[2] = (group_id[2] == max_group_id[2] );
wire last_group = last_group_id[0] & last_group_id[1] & last_group_id[2];
wire group_id_ready;
wire bump_group_id[2:0];
assign bump_group_id[0] = 1'b1;
assign bump_group_id[1] = last_group_id[0];
assign bump_group_id[2] = last_group_id[0] && last_group_id[1];
always @(posedge clock or negedge resetn) begin
if ( ~resetn ) begin
group_id[0] <= {WIDTH{1'b0}};
group_id[1] <= {WIDTH{1'b0}};
group_id[2] <= {WIDTH{1'b0}};
global_id_base_out[0] <= {WIDTH{1'b0}};
global_id_base_out[1] <= {WIDTH{1'b0}};
global_id_base_out[2] <= {WIDTH{1'b0}};
max_group_id[0] <= {WIDTH{1'b0}};
max_group_id[1] <= {WIDTH{1'b0}};
max_group_id[2] <= {WIDTH{1'b0}};
started <= 1'b0;
delayed_start <= 1'b0;
dispatched_all_groups <= 1'b0;
end else if ( start ) begin
group_id[0] <= {WIDTH{1'b0}};
group_id[1] <= {WIDTH{1'b0}};
group_id[2] <= {WIDTH{1'b0}};
global_id_base_out[0] <= {WIDTH{1'b0}};
global_id_base_out[1] <= {WIDTH{1'b0}};
global_id_base_out[2] <= {WIDTH{1'b0}};
max_group_id[0] <= num_groups[0] - 2'b01;
max_group_id[1] <= num_groups[1] - 2'b01;
max_group_id[2] <= num_groups[2] - 2'b01;
started <= 1'b1;
delayed_start <= started;
dispatched_all_groups <= 1'b0;
end else // We presume that start and issue are mutually exclusive.
begin
if ( started & stall_in != {NUM_COPIES{1'b1}} & ~dispatched_all_groups ) begin
if ( bump_group_id[0] ) group_id[0] <= last_group_id[0] ? {WIDTH{1'b0}} : (group_id[0] + 2'b01);
if ( bump_group_id[1] ) group_id[1] <= last_group_id[1] ? {WIDTH{1'b0}} : (group_id[1] + 2'b01);
if ( bump_group_id[2] ) group_id[2] <= last_group_id[2] ? {WIDTH{1'b0}} : (group_id[2] + 2'b01);
// increment global_id_base here so it's always equal to
// group_id x local_size.
// without using any multipliers.
if ( bump_group_id[0] ) global_id_base_out[0] <= last_group_id[0] ? {WIDTH{1'b0}} : (global_id_base_out[0] + local_size[0]);
if ( bump_group_id[1] ) global_id_base_out[1] <= last_group_id[1] ? {WIDTH{1'b0}} : (global_id_base_out[1] + local_size[1]);
if ( bump_group_id[2] ) global_id_base_out[2] <= last_group_id[2] ? {WIDTH{1'b0}} : (global_id_base_out[2] + local_size[2]);
if ( last_group && RUN_FOREVER == 0 )
dispatched_all_groups <= 1'b1;
end
// reset these registers so that next kernel invocation will work.
if ( dispatched_all_groups ) begin
started <= 1'b0;
delayed_start <= 1'b0;
end
end
end
// will have 1 at the lowest position where stall_in has 0.
wire [NUM_COPIES-1:0] single_one_from_stall_in = ~stall_in & (stall_in + 1'b1);
assign group_id_ready = delayed_start & ~dispatched_all_groups;
assign start_out = start;
assign group_id_out = group_id;
assign valid_out = single_one_from_stall_in & {NUM_COPIES{group_id_ready}};
endmodule
// vim:set filetype=verilog:
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports.
//
//===----------------------------------------------------------------------===//
module acl_fifo (
clock,
resetn,
data_in,
data_out,
valid_in,
valid_out,
stall_in,
stall_out,
usedw,
empty,
full,
almost_full);
function integer my_local_log;
input [31:0] value;
for (my_local_log=0; value>0; my_local_log=my_local_log+1)
value = value>>1;
endfunction
parameter DATA_WIDTH = 32;
parameter DEPTH = 256;
parameter NUM_BITS_USED_WORDS = DEPTH == 1 ? 1 : my_local_log(DEPTH-1);
parameter ALMOST_FULL_VALUE = 0;
input clock, stall_in, valid_in, resetn;
output stall_out, valid_out;
input [DATA_WIDTH-1:0] data_in;
output [DATA_WIDTH-1:0] data_out;
output [NUM_BITS_USED_WORDS-1:0] usedw;
output empty, full, almost_full;
// add a register stage prior to the acl_fifo.
//reg [DATA_WIDTH-1:0] data_input /* synthesis preserve */;
//reg valid_input /* synthesis preserve */;
//always@(posedge clock or negedge resetn)
//begin
// if (~resetn)
// begin
// data_input <= {DATA_WIDTH{1'bx}};
// valid_input <= 1'b0;
// end
// else if (~valid_input | ~full)
// begin
// valid_input <= valid_in;
// data_input <= data_in;
// end
//end
scfifo scfifo_component (
.clock (clock),
.data (data_in),
.rdreq ((~stall_in) & (~empty)),
.sclr (),
.wrreq (valid_in & (~full)),
.empty (empty),
.full (full),
.q (data_out),
.aclr (~resetn),
.almost_empty (),
.almost_full (almost_full),
.usedw (usedw));
defparam
scfifo_component.add_ram_output_register = "ON",
scfifo_component.intended_device_family = "Stratix IV",
scfifo_component.lpm_numwords = DEPTH,
scfifo_component.lpm_showahead = "ON",
scfifo_component.lpm_type = "scfifo",
scfifo_component.lpm_width = DATA_WIDTH,
scfifo_component.lpm_widthu = NUM_BITS_USED_WORDS,
scfifo_component.overflow_checking = "ON",
scfifo_component.underflow_checking = "ON",
scfifo_component.use_eab = "ON",
scfifo_component.almost_full_value = ALMOST_FULL_VALUE;
assign stall_out = full;
assign valid_out = ~empty;
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports.
//
//===----------------------------------------------------------------------===//
module acl_fifo (
clock,
resetn,
data_in,
data_out,
valid_in,
valid_out,
stall_in,
stall_out,
usedw,
empty,
full,
almost_full);
function integer my_local_log;
input [31:0] value;
for (my_local_log=0; value>0; my_local_log=my_local_log+1)
value = value>>1;
endfunction
parameter DATA_WIDTH = 32;
parameter DEPTH = 256;
parameter NUM_BITS_USED_WORDS = DEPTH == 1 ? 1 : my_local_log(DEPTH-1);
parameter ALMOST_FULL_VALUE = 0;
input clock, stall_in, valid_in, resetn;
output stall_out, valid_out;
input [DATA_WIDTH-1:0] data_in;
output [DATA_WIDTH-1:0] data_out;
output [NUM_BITS_USED_WORDS-1:0] usedw;
output empty, full, almost_full;
// add a register stage prior to the acl_fifo.
//reg [DATA_WIDTH-1:0] data_input /* synthesis preserve */;
//reg valid_input /* synthesis preserve */;
//always@(posedge clock or negedge resetn)
//begin
// if (~resetn)
// begin
// data_input <= {DATA_WIDTH{1'bx}};
// valid_input <= 1'b0;
// end
// else if (~valid_input | ~full)
// begin
// valid_input <= valid_in;
// data_input <= data_in;
// end
//end
scfifo scfifo_component (
.clock (clock),
.data (data_in),
.rdreq ((~stall_in) & (~empty)),
.sclr (),
.wrreq (valid_in & (~full)),
.empty (empty),
.full (full),
.q (data_out),
.aclr (~resetn),
.almost_empty (),
.almost_full (almost_full),
.usedw (usedw));
defparam
scfifo_component.add_ram_output_register = "ON",
scfifo_component.intended_device_family = "Stratix IV",
scfifo_component.lpm_numwords = DEPTH,
scfifo_component.lpm_showahead = "ON",
scfifo_component.lpm_type = "scfifo",
scfifo_component.lpm_width = DATA_WIDTH,
scfifo_component.lpm_widthu = NUM_BITS_USED_WORDS,
scfifo_component.overflow_checking = "ON",
scfifo_component.underflow_checking = "ON",
scfifo_component.use_eab = "ON",
scfifo_component.almost_full_value = ALMOST_FULL_VALUE;
assign stall_out = full;
assign valid_out = ~empty;
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.
//
// Helper module to handle bursting large sequential blocks of memory to or
// from global memory.
//
/*****************************************************************************/
// Burst read master:
// Keeps a local buffer populated with data from a sequential block of
// global memory. The block of global memory is specified by a base address
// and size.
/*****************************************************************************/
module lsu_burst_read_master (
clk,
reset,
o_active, //Debugging signal
// control inputs and outputs
control_fixed_location,
control_read_base,
control_read_length,
control_go,
control_done,
control_early_done,
// user logic inputs and outputs
user_read_buffer,
user_buffer_data,
user_data_available,
// master inputs and outputs
master_address,
master_read,
master_byteenable,
master_readdata,
master_readdatavalid,
master_burstcount,
master_waitrequest
);
/*************
* Parameters *
*************/
parameter DATAWIDTH = 32;
parameter MAXBURSTCOUNT = 4;
parameter BURSTCOUNTWIDTH = 3;
parameter BYTEENABLEWIDTH = 4;
parameter ADDRESSWIDTH = 32;
parameter FIFODEPTH = 32;
parameter FIFODEPTH_LOG2 = 5;
parameter FIFOUSEMEMORY = 1; // set to 0 to use LEs instead
parameter READTHRESHOLD = FIFODEPTH - MAXBURSTCOUNT - 4;
/********
* Ports *
********/
input clk;
input reset;
output o_active;
// control inputs and outputs
input control_fixed_location;
input [ADDRESSWIDTH-1:0] control_read_base;
input [ADDRESSWIDTH-1:0] control_read_length;
input control_go;
output wire control_done;
output wire control_early_done; // don't use this unless you know what you are doing, it's going to fire when the last read is posted, not when the last data returns!
// user logic inputs and outputs
input user_read_buffer;
output wire [DATAWIDTH-1:0] user_buffer_data;
output wire user_data_available;
// master inputs and outputs
input master_waitrequest;
input master_readdatavalid;
input [DATAWIDTH-1:0] master_readdata;
output wire [ADDRESSWIDTH-1:0] master_address;
output wire master_read;
output wire [BYTEENABLEWIDTH-1:0] master_byteenable;
output wire [BURSTCOUNTWIDTH-1:0] master_burstcount;
/***************
* Architecture *
***************/
// internal control signals
reg control_fixed_location_d1;
wire fifo_empty;
reg [ADDRESSWIDTH-1:0] address;
reg [ADDRESSWIDTH-1:0] length;
reg [FIFODEPTH_LOG2-1:0] reads_pending;
wire increment_address;
wire [BURSTCOUNTWIDTH-1:0] burst_count;
wire [BURSTCOUNTWIDTH-1:0] first_short_burst_count;
wire first_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] final_short_burst_count;
wire final_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] burst_boundary_word_address;
wire too_many_reads_pending;
wire [FIFODEPTH_LOG2-1:0] fifo_used;
// registering the control_fixed_location bit
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
control_fixed_location_d1 <= 0;
end
else
begin
if (control_go == 1)
begin
control_fixed_location_d1 <= control_fixed_location;
end
end
end
// master address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
address <= 0;
end
else
begin
if(control_go == 1)
begin
address <= control_read_base;
end
else if((increment_address == 1) & (control_fixed_location_d1 == 0))
begin
address <= address + (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, increment by the burst count presented
end
end
end
// master length logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
length <= 0;
end
else
begin
if(control_go == 1)
begin
length <= control_read_length;
end
else if(increment_address == 1)
begin
length <= length - (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, decrement by the burst count presented
end
end
end
// controlled signals going to the master/control ports
assign master_address = address;
assign master_byteenable = -1; // all ones, always performing word size accesses
assign master_burstcount = burst_count;
assign control_done = (length == 0) & (reads_pending == 0); // need to make sure that the reads have returned before firing the done bit
assign control_early_done = (length == 0); // advanced feature, you should use 'control_done' if you need all the reads to return first
assign master_read = (too_many_reads_pending == 0) & (length != 0);
assign burst_boundary_word_address = ((address / BYTEENABLEWIDTH) & (MAXBURSTCOUNT - 1));
assign first_short_burst_enable = (burst_boundary_word_address != 0);
assign final_short_burst_enable = (length < (MAXBURSTCOUNT * BYTEENABLEWIDTH));
assign first_short_burst_count = ((burst_boundary_word_address & 1'b1) == 1'b1)? 1 : // if the burst boundary isn't a multiple of 2 then must post a burst of 1 to get to a multiple of 2 for the next burst
(((MAXBURSTCOUNT - burst_boundary_word_address) < (length / BYTEENABLEWIDTH))?
(MAXBURSTCOUNT - burst_boundary_word_address) : (length / BYTEENABLEWIDTH));
assign final_short_burst_count = (length / BYTEENABLEWIDTH);
assign burst_count = (first_short_burst_enable == 1)? first_short_burst_count : // this will get the transfer back on a burst boundary,
(final_short_burst_enable == 1)? final_short_burst_count : MAXBURSTCOUNT;
assign increment_address = (too_many_reads_pending == 0) & (master_waitrequest == 0) & (length != 0);
assign too_many_reads_pending = (reads_pending + fifo_used) >= READTHRESHOLD; // make sure there are fewer reads posted than room in the FIFO
// tracking FIFO
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
reads_pending <= 0;
end
else
begin
if(increment_address == 1)
begin
if(master_readdatavalid == 0)
begin
reads_pending <= reads_pending + burst_count;
end
else
begin
reads_pending <= reads_pending + burst_count - 1; // a burst read was posted, but a word returned
end
end
else
begin
if(master_readdatavalid == 0)
begin
reads_pending <= reads_pending; // burst read was not posted and no read returned
end
else
begin
reads_pending <= reads_pending - 1; // burst read was not posted but a word returned
end
end
end
end
assign o_active = |reads_pending;
// read data feeding user logic
assign user_data_available = !fifo_empty;
scfifo the_master_to_user_fifo (
.aclr (reset),
.clock (clk),
.data (master_readdata),
.empty (fifo_empty),
.q (user_buffer_data),
.rdreq (user_read_buffer),
.usedw (fifo_used),
.wrreq (master_readdatavalid),
.almost_empty(),
.almost_full(),
.full(),
.sclr()
);
defparam the_master_to_user_fifo.lpm_width = DATAWIDTH;
defparam the_master_to_user_fifo.lpm_widthu = FIFODEPTH_LOG2;
defparam the_master_to_user_fifo.lpm_numwords = FIFODEPTH;
defparam the_master_to_user_fifo.lpm_showahead = "ON";
defparam the_master_to_user_fifo.use_eab = (FIFOUSEMEMORY == 1)? "ON" : "OFF";
defparam the_master_to_user_fifo.add_ram_output_register = "OFF";
defparam the_master_to_user_fifo.underflow_checking = "OFF";
defparam the_master_to_user_fifo.overflow_checking = "OFF";
initial
if ( READTHRESHOLD > FIFODEPTH ||
READTHRESHOLD > FIFODEPTH - 4 ||
READTHRESHOLD < 1 )
$error("Invalid FIFODEPTH and MAXBURSTCOUNT comination. Produced READTHRESHOLD = %d\n",READTHRESHOLD);
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.
//
// Helper module to handle bursting large sequential blocks of memory to or
// from global memory.
//
/*****************************************************************************/
// Burst read master:
// Keeps a local buffer populated with data from a sequential block of
// global memory. The block of global memory is specified by a base address
// and size.
/*****************************************************************************/
module lsu_burst_read_master (
clk,
reset,
o_active, //Debugging signal
// control inputs and outputs
control_fixed_location,
control_read_base,
control_read_length,
control_go,
control_done,
control_early_done,
// user logic inputs and outputs
user_read_buffer,
user_buffer_data,
user_data_available,
// master inputs and outputs
master_address,
master_read,
master_byteenable,
master_readdata,
master_readdatavalid,
master_burstcount,
master_waitrequest
);
/*************
* Parameters *
*************/
parameter DATAWIDTH = 32;
parameter MAXBURSTCOUNT = 4;
parameter BURSTCOUNTWIDTH = 3;
parameter BYTEENABLEWIDTH = 4;
parameter ADDRESSWIDTH = 32;
parameter FIFODEPTH = 32;
parameter FIFODEPTH_LOG2 = 5;
parameter FIFOUSEMEMORY = 1; // set to 0 to use LEs instead
parameter READTHRESHOLD = FIFODEPTH - MAXBURSTCOUNT - 4;
/********
* Ports *
********/
input clk;
input reset;
output o_active;
// control inputs and outputs
input control_fixed_location;
input [ADDRESSWIDTH-1:0] control_read_base;
input [ADDRESSWIDTH-1:0] control_read_length;
input control_go;
output wire control_done;
output wire control_early_done; // don't use this unless you know what you are doing, it's going to fire when the last read is posted, not when the last data returns!
// user logic inputs and outputs
input user_read_buffer;
output wire [DATAWIDTH-1:0] user_buffer_data;
output wire user_data_available;
// master inputs and outputs
input master_waitrequest;
input master_readdatavalid;
input [DATAWIDTH-1:0] master_readdata;
output wire [ADDRESSWIDTH-1:0] master_address;
output wire master_read;
output wire [BYTEENABLEWIDTH-1:0] master_byteenable;
output wire [BURSTCOUNTWIDTH-1:0] master_burstcount;
/***************
* Architecture *
***************/
// internal control signals
reg control_fixed_location_d1;
wire fifo_empty;
reg [ADDRESSWIDTH-1:0] address;
reg [ADDRESSWIDTH-1:0] length;
reg [FIFODEPTH_LOG2-1:0] reads_pending;
wire increment_address;
wire [BURSTCOUNTWIDTH-1:0] burst_count;
wire [BURSTCOUNTWIDTH-1:0] first_short_burst_count;
wire first_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] final_short_burst_count;
wire final_short_burst_enable;
wire [BURSTCOUNTWIDTH-1:0] burst_boundary_word_address;
wire too_many_reads_pending;
wire [FIFODEPTH_LOG2-1:0] fifo_used;
// registering the control_fixed_location bit
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
control_fixed_location_d1 <= 0;
end
else
begin
if (control_go == 1)
begin
control_fixed_location_d1 <= control_fixed_location;
end
end
end
// master address logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
address <= 0;
end
else
begin
if(control_go == 1)
begin
address <= control_read_base;
end
else if((increment_address == 1) & (control_fixed_location_d1 == 0))
begin
address <= address + (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, increment by the burst count presented
end
end
end
// master length logic
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
length <= 0;
end
else
begin
if(control_go == 1)
begin
length <= control_read_length;
end
else if(increment_address == 1)
begin
length <= length - (burst_count * BYTEENABLEWIDTH); // always performing word size accesses, decrement by the burst count presented
end
end
end
// controlled signals going to the master/control ports
assign master_address = address;
assign master_byteenable = -1; // all ones, always performing word size accesses
assign master_burstcount = burst_count;
assign control_done = (length == 0) & (reads_pending == 0); // need to make sure that the reads have returned before firing the done bit
assign control_early_done = (length == 0); // advanced feature, you should use 'control_done' if you need all the reads to return first
assign master_read = (too_many_reads_pending == 0) & (length != 0);
assign burst_boundary_word_address = ((address / BYTEENABLEWIDTH) & (MAXBURSTCOUNT - 1));
assign first_short_burst_enable = (burst_boundary_word_address != 0);
assign final_short_burst_enable = (length < (MAXBURSTCOUNT * BYTEENABLEWIDTH));
assign first_short_burst_count = ((burst_boundary_word_address & 1'b1) == 1'b1)? 1 : // if the burst boundary isn't a multiple of 2 then must post a burst of 1 to get to a multiple of 2 for the next burst
(((MAXBURSTCOUNT - burst_boundary_word_address) < (length / BYTEENABLEWIDTH))?
(MAXBURSTCOUNT - burst_boundary_word_address) : (length / BYTEENABLEWIDTH));
assign final_short_burst_count = (length / BYTEENABLEWIDTH);
assign burst_count = (first_short_burst_enable == 1)? first_short_burst_count : // this will get the transfer back on a burst boundary,
(final_short_burst_enable == 1)? final_short_burst_count : MAXBURSTCOUNT;
assign increment_address = (too_many_reads_pending == 0) & (master_waitrequest == 0) & (length != 0);
assign too_many_reads_pending = (reads_pending + fifo_used) >= READTHRESHOLD; // make sure there are fewer reads posted than room in the FIFO
// tracking FIFO
always @ (posedge clk or posedge reset)
begin
if (reset == 1)
begin
reads_pending <= 0;
end
else
begin
if(increment_address == 1)
begin
if(master_readdatavalid == 0)
begin
reads_pending <= reads_pending + burst_count;
end
else
begin
reads_pending <= reads_pending + burst_count - 1; // a burst read was posted, but a word returned
end
end
else
begin
if(master_readdatavalid == 0)
begin
reads_pending <= reads_pending; // burst read was not posted and no read returned
end
else
begin
reads_pending <= reads_pending - 1; // burst read was not posted but a word returned
end
end
end
end
assign o_active = |reads_pending;
// read data feeding user logic
assign user_data_available = !fifo_empty;
scfifo the_master_to_user_fifo (
.aclr (reset),
.clock (clk),
.data (master_readdata),
.empty (fifo_empty),
.q (user_buffer_data),
.rdreq (user_read_buffer),
.usedw (fifo_used),
.wrreq (master_readdatavalid),
.almost_empty(),
.almost_full(),
.full(),
.sclr()
);
defparam the_master_to_user_fifo.lpm_width = DATAWIDTH;
defparam the_master_to_user_fifo.lpm_widthu = FIFODEPTH_LOG2;
defparam the_master_to_user_fifo.lpm_numwords = FIFODEPTH;
defparam the_master_to_user_fifo.lpm_showahead = "ON";
defparam the_master_to_user_fifo.use_eab = (FIFOUSEMEMORY == 1)? "ON" : "OFF";
defparam the_master_to_user_fifo.add_ram_output_register = "OFF";
defparam the_master_to_user_fifo.underflow_checking = "OFF";
defparam the_master_to_user_fifo.overflow_checking = "OFF";
initial
if ( READTHRESHOLD > FIFODEPTH ||
READTHRESHOLD > FIFODEPTH - 4 ||
READTHRESHOLD < 1 )
$error("Invalid FIFODEPTH and MAXBURSTCOUNT comination. Produced READTHRESHOLD = %d\n",READTHRESHOLD);
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_rrp_reg
(
input logic clock,
input logic resetn,
acl_ic_rrp_intf rrp_in,
(* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_rrp_intf rrp_out
);
always @(posedge clock or negedge resetn)
if( ~resetn ) begin
rrp_out.datavalid <= 1'b0;
rrp_out.id <= 'x;
rrp_out.data <= 'x;
end
else begin
rrp_out.datavalid <= rrp_in.datavalid;
rrp_out.id <= rrp_in.id;
rrp_out.data <= rrp_in.data;
end
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_rrp_reg
(
input logic clock,
input logic resetn,
acl_ic_rrp_intf rrp_in,
(* dont_merge, altera_attribute = "-name auto_shift_register_recognition OFF" *) acl_ic_rrp_intf rrp_out
);
always @(posedge clock or negedge resetn)
if( ~resetn ) begin
rrp_out.datavalid <= 1'b0;
rrp_out.id <= 'x;
rrp_out.data <= 'x;
end
else begin
rrp_out.datavalid <= rrp_in.datavalid;
rrp_out.id <= rrp_in.id;
rrp_out.data <= rrp_in.data;
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;
integer cyc=0;
wire one = '1;
wire z0 = 'z;
wire z1 = 'z;
wire z2 = 'z;
wire z3 = 'z;
wire tog = cyc[0];
// verilator lint_off PINMISSING
t_tri0 tri0a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri0 tri0b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri0 tri0z (.line(`__LINE__), .expval(1'b0), .tn(z0));
t_tri0 tri0Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri0 tri0c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri0 tri0d (.line(`__LINE__), .expval(1'b1), .tn(1'b1)); // Warning would be reasonable given tri0 connect
t_tri0 tri0e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri0 tri0f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri0 tri0g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri0 tri0h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri1 tri1a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri1 tri1b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri1 tri1z (.line(`__LINE__), .expval(1'b1), .tn(z1));
t_tri1 tri1Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri1 tri1c (.line(`__LINE__), .expval(1'b0), .tn(1'b0)); // Warning would be reasonable given tri1 connect
t_tri1 tri1d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri1 tri1e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri1 tri1f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri1 tri1g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri1 tri1h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri2 tri2a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri2 tri2b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri2 tri2z (.line(`__LINE__), .expval(1'b0), .tn(z2));
t_tri2 tri2Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri2 tri2c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri2 tri2d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri2 tri2e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri2 tri2f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri2 tri2g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri2 tri2h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri3 tri3a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri3 tri3b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri3 tri3z (.line(`__LINE__), .expval(1'b1), .tn(z3));
t_tri3 tri3Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri3 tri3c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri3 tri3d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri3 tri3e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri3 tri3f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri3 tri3g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri3 tri3h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
// verilator lint_on PINMISSING
// Test loop
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==99) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module t_tri0
(line, expval, tn);
input integer line;
input expval;
input tn; // Illegal to be inout; spec requires net connection to any inout
tri0 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri1
(line, expval, tn);
input integer line;
input expval;
input tn;
tri1 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri2
(line, expval, tn);
input integer line;
input expval;
input tn;
pulldown(tn);
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri3
(line, expval, tn);
input integer line;
input expval;
input tn;
pullup(tn);
wire clk = t.clk;
always @(negedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
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;
integer cyc=0;
wire one = '1;
wire z0 = 'z;
wire z1 = 'z;
wire z2 = 'z;
wire z3 = 'z;
wire tog = cyc[0];
// verilator lint_off PINMISSING
t_tri0 tri0a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri0 tri0b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri0 tri0z (.line(`__LINE__), .expval(1'b0), .tn(z0));
t_tri0 tri0Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri0 tri0c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri0 tri0d (.line(`__LINE__), .expval(1'b1), .tn(1'b1)); // Warning would be reasonable given tri0 connect
t_tri0 tri0e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri0 tri0f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri0 tri0g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri0 tri0h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri1 tri1a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri1 tri1b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri1 tri1z (.line(`__LINE__), .expval(1'b1), .tn(z1));
t_tri1 tri1Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri1 tri1c (.line(`__LINE__), .expval(1'b0), .tn(1'b0)); // Warning would be reasonable given tri1 connect
t_tri1 tri1d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri1 tri1e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri1 tri1f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri1 tri1g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri1 tri1h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri2 tri2a (.line(`__LINE__), .expval(1'b0)); // Pin missing
t_tri2 tri2b (.line(`__LINE__), .expval(1'b0), .tn());
t_tri2 tri2z (.line(`__LINE__), .expval(1'b0), .tn(z2));
t_tri2 tri2Z (.line(`__LINE__), .expval(1'b0), .tn(1'bz));
t_tri2 tri2c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri2 tri2d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri2 tri2e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri2 tri2f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri2 tri2g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri2 tri2h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
t_tri3 tri3a (.line(`__LINE__), .expval(1'b1)); // Pin missing
t_tri3 tri3b (.line(`__LINE__), .expval(1'b1), .tn());
t_tri3 tri3z (.line(`__LINE__), .expval(1'b1), .tn(z3));
t_tri3 tri3Z (.line(`__LINE__), .expval(1'b1), .tn(1'bz));
t_tri3 tri3c (.line(`__LINE__), .expval(1'b0), .tn(1'b0));
t_tri3 tri3d (.line(`__LINE__), .expval(1'b1), .tn(1'b1));
t_tri3 tri3e (.line(`__LINE__), .expval(1'b0), .tn(~one));
t_tri3 tri3f (.line(`__LINE__), .expval(1'b1), .tn(one));
t_tri3 tri3g (.line(`__LINE__), .expval(~cyc[0]), .tn(~tog));
t_tri3 tri3h (.line(`__LINE__), .expval(cyc[0]), .tn(tog));
// verilator lint_on PINMISSING
// Test loop
always @ (posedge clk) begin
cyc <= cyc + 1;
if (cyc==99) begin
$write("*-* All Finished *-*\n");
$finish;
end
end
endmodule
module t_tri0
(line, expval, tn);
input integer line;
input expval;
input tn; // Illegal to be inout; spec requires net connection to any inout
tri0 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri1
(line, expval, tn);
input integer line;
input expval;
input tn;
tri1 tn;
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri2
(line, expval, tn);
input integer line;
input expval;
input tn;
pulldown(tn);
wire clk = t.clk;
always @(posedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
end
endmodule
module t_tri3
(line, expval, tn);
input integer line;
input expval;
input tn;
pullup(tn);
wire clk = t.clk;
always @(negedge clk) if (tn !== expval) begin
$display("%%Error: from line %0d got=%x exp=%x",line,tn,expval); $stop;
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.
//===----------------------------------------------------------------------===//
//
// C backend 'pipeline' primitive
//
//===----------------------------------------------------------------------===//
module acl_pipeline (
clock,
resetn,
data_in,
valid_out,
stall_in,
stall_out,
valid_in,
data_out,
initeration_in,
initeration_stall_out,
initeration_valid_in,
not_exitcond_in,
not_exitcond_stall_out,
not_exitcond_valid_in,
pipeline_valid_out,
pipeline_stall_in,
exiting_valid_out
);
parameter FIFO_DEPTH = 1;
parameter string STYLE = "SPECULATIVE"; // "NON_SPECULATIVE"/"SPECULATIVE"
input clock, resetn, stall_in, valid_in, initeration_valid_in, not_exitcond_valid_in, pipeline_stall_in;
output stall_out, valid_out, initeration_stall_out, not_exitcond_stall_out, pipeline_valid_out;
input data_in, initeration_in, not_exitcond_in;
output data_out;
output exiting_valid_out;
generate
// Instantiate 2 pops and 1 push
if (STYLE == "SPECULATIVE")
begin
wire valid_pop1, valid_pop2;
wire stall_push, stall_pop2;
wire data_pop2, data_push;
acl_pop pop1(
.clock(clock),
.resetn(resetn),
.dir(data_in),
.predicate(1'b0),
.data_in(1'b1),
.valid_out(valid_pop1),
.stall_in(stall_pop2),
.stall_out(stall_out),
.valid_in(valid_in),
.data_out(data_pop2),
.feedback_in(initeration_in),
.feedback_valid_in(initeration_valid_in),
.feedback_stall_out(initeration_stall_out)
);
defparam pop1.DATA_WIDTH = 1;
acl_pop pop2(
.clock(clock),
.resetn(resetn),
.dir(data_pop2),
.predicate(1'b0),
.data_in(1'b0),
.valid_out(valid_pop2),
.stall_in(stall_push),
.stall_out(stall_pop2),
.valid_in(valid_pop1),
.data_out(data_push),
.feedback_in(~not_exitcond_in),
.feedback_valid_in(not_exitcond_valid_in),
.feedback_stall_out(not_exitcond_stall_out)
);
defparam pop2.DATA_WIDTH = 1;
wire p_out, p_valid_out, p_stall_in;
acl_push push(
.clock(clock),
.resetn(resetn),
.dir(1'b1),
.predicate(1'b0),
.data_in(~data_push),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_push),
.valid_in(valid_pop2),
.data_out(data_out),
.feedback_out(p_out),
.feedback_valid_out(p_valid_out),
.feedback_stall_in(p_stall_in)
);
// signal when to spawn a new iteration
assign pipeline_valid_out = p_out & p_valid_out;
assign p_stall_in = pipeline_stall_in;
// signal when the last iteration is exiting
assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in;
defparam push.DATA_WIDTH = 1;
defparam push.FIFO_DEPTH = FIFO_DEPTH;
end
// Instantiate 1 pop and 1 push
else
begin
//////////////////////////////////////////////////////
// If there is no speculation, directly connect
// exit condition to valid
wire valid_pop2;
wire stall_push;
wire data_push;
wire p_out, p_valid_out, p_stall_in;
assign p_out = not_exitcond_in;
assign p_valid_out = not_exitcond_valid_in ;
assign not_exitcond_stall_out = p_stall_in;
acl_staging_reg asr(
.clk(clock), .reset(~resetn),
.i_valid( valid_in ), .o_stall(stall_out),
.o_valid( valid_out), .i_stall(stall_in)
);
// signal when to spawn a new iteration
assign pipeline_valid_out = p_out & p_valid_out;
assign p_stall_in = pipeline_stall_in;
// signal when the last iteration is exiting
assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in;
assign initeration_stall_out = 1'b0; // never stall
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// C backend 'pipeline' primitive
//
//===----------------------------------------------------------------------===//
module acl_pipeline (
clock,
resetn,
data_in,
valid_out,
stall_in,
stall_out,
valid_in,
data_out,
initeration_in,
initeration_stall_out,
initeration_valid_in,
not_exitcond_in,
not_exitcond_stall_out,
not_exitcond_valid_in,
pipeline_valid_out,
pipeline_stall_in,
exiting_valid_out
);
parameter FIFO_DEPTH = 1;
parameter string STYLE = "SPECULATIVE"; // "NON_SPECULATIVE"/"SPECULATIVE"
input clock, resetn, stall_in, valid_in, initeration_valid_in, not_exitcond_valid_in, pipeline_stall_in;
output stall_out, valid_out, initeration_stall_out, not_exitcond_stall_out, pipeline_valid_out;
input data_in, initeration_in, not_exitcond_in;
output data_out;
output exiting_valid_out;
generate
// Instantiate 2 pops and 1 push
if (STYLE == "SPECULATIVE")
begin
wire valid_pop1, valid_pop2;
wire stall_push, stall_pop2;
wire data_pop2, data_push;
acl_pop pop1(
.clock(clock),
.resetn(resetn),
.dir(data_in),
.predicate(1'b0),
.data_in(1'b1),
.valid_out(valid_pop1),
.stall_in(stall_pop2),
.stall_out(stall_out),
.valid_in(valid_in),
.data_out(data_pop2),
.feedback_in(initeration_in),
.feedback_valid_in(initeration_valid_in),
.feedback_stall_out(initeration_stall_out)
);
defparam pop1.DATA_WIDTH = 1;
acl_pop pop2(
.clock(clock),
.resetn(resetn),
.dir(data_pop2),
.predicate(1'b0),
.data_in(1'b0),
.valid_out(valid_pop2),
.stall_in(stall_push),
.stall_out(stall_pop2),
.valid_in(valid_pop1),
.data_out(data_push),
.feedback_in(~not_exitcond_in),
.feedback_valid_in(not_exitcond_valid_in),
.feedback_stall_out(not_exitcond_stall_out)
);
defparam pop2.DATA_WIDTH = 1;
wire p_out, p_valid_out, p_stall_in;
acl_push push(
.clock(clock),
.resetn(resetn),
.dir(1'b1),
.predicate(1'b0),
.data_in(~data_push),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_push),
.valid_in(valid_pop2),
.data_out(data_out),
.feedback_out(p_out),
.feedback_valid_out(p_valid_out),
.feedback_stall_in(p_stall_in)
);
// signal when to spawn a new iteration
assign pipeline_valid_out = p_out & p_valid_out;
assign p_stall_in = pipeline_stall_in;
// signal when the last iteration is exiting
assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in;
defparam push.DATA_WIDTH = 1;
defparam push.FIFO_DEPTH = FIFO_DEPTH;
end
// Instantiate 1 pop and 1 push
else
begin
//////////////////////////////////////////////////////
// If there is no speculation, directly connect
// exit condition to valid
wire valid_pop2;
wire stall_push;
wire data_push;
wire p_out, p_valid_out, p_stall_in;
assign p_out = not_exitcond_in;
assign p_valid_out = not_exitcond_valid_in ;
assign not_exitcond_stall_out = p_stall_in;
acl_staging_reg asr(
.clk(clock), .reset(~resetn),
.i_valid( valid_in ), .o_stall(stall_out),
.o_valid( valid_out), .i_stall(stall_in)
);
// signal when to spawn a new iteration
assign pipeline_valid_out = p_out & p_valid_out;
assign p_stall_in = pipeline_stall_in;
// signal when the last iteration is exiting
assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in;
assign initeration_stall_out = 1'b0; // never stall
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// C backend 'pipeline' primitive
//
//===----------------------------------------------------------------------===//
module acl_pipeline (
clock,
resetn,
data_in,
valid_out,
stall_in,
stall_out,
valid_in,
data_out,
initeration_in,
initeration_stall_out,
initeration_valid_in,
not_exitcond_in,
not_exitcond_stall_out,
not_exitcond_valid_in,
pipeline_valid_out,
pipeline_stall_in,
exiting_valid_out
);
parameter FIFO_DEPTH = 1;
parameter string STYLE = "SPECULATIVE"; // "NON_SPECULATIVE"/"SPECULATIVE"
input clock, resetn, stall_in, valid_in, initeration_valid_in, not_exitcond_valid_in, pipeline_stall_in;
output stall_out, valid_out, initeration_stall_out, not_exitcond_stall_out, pipeline_valid_out;
input data_in, initeration_in, not_exitcond_in;
output data_out;
output exiting_valid_out;
generate
// Instantiate 2 pops and 1 push
if (STYLE == "SPECULATIVE")
begin
wire valid_pop1, valid_pop2;
wire stall_push, stall_pop2;
wire data_pop2, data_push;
acl_pop pop1(
.clock(clock),
.resetn(resetn),
.dir(data_in),
.predicate(1'b0),
.data_in(1'b1),
.valid_out(valid_pop1),
.stall_in(stall_pop2),
.stall_out(stall_out),
.valid_in(valid_in),
.data_out(data_pop2),
.feedback_in(initeration_in),
.feedback_valid_in(initeration_valid_in),
.feedback_stall_out(initeration_stall_out)
);
defparam pop1.DATA_WIDTH = 1;
acl_pop pop2(
.clock(clock),
.resetn(resetn),
.dir(data_pop2),
.predicate(1'b0),
.data_in(1'b0),
.valid_out(valid_pop2),
.stall_in(stall_push),
.stall_out(stall_pop2),
.valid_in(valid_pop1),
.data_out(data_push),
.feedback_in(~not_exitcond_in),
.feedback_valid_in(not_exitcond_valid_in),
.feedback_stall_out(not_exitcond_stall_out)
);
defparam pop2.DATA_WIDTH = 1;
wire p_out, p_valid_out, p_stall_in;
acl_push push(
.clock(clock),
.resetn(resetn),
.dir(1'b1),
.predicate(1'b0),
.data_in(~data_push),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_push),
.valid_in(valid_pop2),
.data_out(data_out),
.feedback_out(p_out),
.feedback_valid_out(p_valid_out),
.feedback_stall_in(p_stall_in)
);
// signal when to spawn a new iteration
assign pipeline_valid_out = p_out & p_valid_out;
assign p_stall_in = pipeline_stall_in;
// signal when the last iteration is exiting
assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in;
defparam push.DATA_WIDTH = 1;
defparam push.FIFO_DEPTH = FIFO_DEPTH;
end
// Instantiate 1 pop and 1 push
else
begin
//////////////////////////////////////////////////////
// If there is no speculation, directly connect
// exit condition to valid
wire valid_pop2;
wire stall_push;
wire data_push;
wire p_out, p_valid_out, p_stall_in;
assign p_out = not_exitcond_in;
assign p_valid_out = not_exitcond_valid_in ;
assign not_exitcond_stall_out = p_stall_in;
acl_staging_reg asr(
.clk(clock), .reset(~resetn),
.i_valid( valid_in ), .o_stall(stall_out),
.o_valid( valid_out), .i_stall(stall_in)
);
// signal when to spawn a new iteration
assign pipeline_valid_out = p_out & p_valid_out;
assign p_stall_in = pipeline_stall_in;
// signal when the last iteration is exiting
assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in;
assign initeration_stall_out = 1'b0; // never stall
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// C backend 'pipeline' primitive
//
//===----------------------------------------------------------------------===//
module acl_pipeline (
clock,
resetn,
data_in,
valid_out,
stall_in,
stall_out,
valid_in,
data_out,
initeration_in,
initeration_stall_out,
initeration_valid_in,
not_exitcond_in,
not_exitcond_stall_out,
not_exitcond_valid_in,
pipeline_valid_out,
pipeline_stall_in,
exiting_valid_out
);
parameter FIFO_DEPTH = 1;
parameter string STYLE = "SPECULATIVE"; // "NON_SPECULATIVE"/"SPECULATIVE"
input clock, resetn, stall_in, valid_in, initeration_valid_in, not_exitcond_valid_in, pipeline_stall_in;
output stall_out, valid_out, initeration_stall_out, not_exitcond_stall_out, pipeline_valid_out;
input data_in, initeration_in, not_exitcond_in;
output data_out;
output exiting_valid_out;
generate
// Instantiate 2 pops and 1 push
if (STYLE == "SPECULATIVE")
begin
wire valid_pop1, valid_pop2;
wire stall_push, stall_pop2;
wire data_pop2, data_push;
acl_pop pop1(
.clock(clock),
.resetn(resetn),
.dir(data_in),
.predicate(1'b0),
.data_in(1'b1),
.valid_out(valid_pop1),
.stall_in(stall_pop2),
.stall_out(stall_out),
.valid_in(valid_in),
.data_out(data_pop2),
.feedback_in(initeration_in),
.feedback_valid_in(initeration_valid_in),
.feedback_stall_out(initeration_stall_out)
);
defparam pop1.DATA_WIDTH = 1;
acl_pop pop2(
.clock(clock),
.resetn(resetn),
.dir(data_pop2),
.predicate(1'b0),
.data_in(1'b0),
.valid_out(valid_pop2),
.stall_in(stall_push),
.stall_out(stall_pop2),
.valid_in(valid_pop1),
.data_out(data_push),
.feedback_in(~not_exitcond_in),
.feedback_valid_in(not_exitcond_valid_in),
.feedback_stall_out(not_exitcond_stall_out)
);
defparam pop2.DATA_WIDTH = 1;
wire p_out, p_valid_out, p_stall_in;
acl_push push(
.clock(clock),
.resetn(resetn),
.dir(1'b1),
.predicate(1'b0),
.data_in(~data_push),
.valid_out(valid_out),
.stall_in(stall_in),
.stall_out(stall_push),
.valid_in(valid_pop2),
.data_out(data_out),
.feedback_out(p_out),
.feedback_valid_out(p_valid_out),
.feedback_stall_in(p_stall_in)
);
// signal when to spawn a new iteration
assign pipeline_valid_out = p_out & p_valid_out;
assign p_stall_in = pipeline_stall_in;
// signal when the last iteration is exiting
assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in;
defparam push.DATA_WIDTH = 1;
defparam push.FIFO_DEPTH = FIFO_DEPTH;
end
// Instantiate 1 pop and 1 push
else
begin
//////////////////////////////////////////////////////
// If there is no speculation, directly connect
// exit condition to valid
wire valid_pop2;
wire stall_push;
wire data_push;
wire p_out, p_valid_out, p_stall_in;
assign p_out = not_exitcond_in;
assign p_valid_out = not_exitcond_valid_in ;
assign not_exitcond_stall_out = p_stall_in;
acl_staging_reg asr(
.clk(clock), .reset(~resetn),
.i_valid( valid_in ), .o_stall(stall_out),
.o_valid( valid_out), .i_stall(stall_in)
);
// signal when to spawn a new iteration
assign pipeline_valid_out = p_out & p_valid_out;
assign p_stall_in = pipeline_stall_in;
// signal when the last iteration is exiting
assign exiting_valid_out = ~p_out & p_valid_out & ~pipeline_stall_in;
assign initeration_stall_out = 1'b0; // never stall
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
//===----------------------------------------------------------------------===//
//
// C backend 'push' primitive
//
// Upstream are signals that go to the feedback (snk node is a acl_pop),
// downstream are signals that continue into our "normal" pipeline.
//
// dir indicates if you want to push it to the feedback
// 1 - push to feedback
// 0 - bypass, just push out to downstream
//===----------------------------------------------------------------------===//
module acl_push (
clock,
resetn,
// interface from kernel pipeline, input stream
dir,
data_in,
valid_in,
stall_out,
predicate,
// interface to kernel pipeline, downstream
valid_out,
stall_in,
data_out,
// interface to pipeline feedback, upstream
feedback_out,
feedback_valid_out,
feedback_stall_in
);
parameter DATA_WIDTH = 32;
parameter FIFO_DEPTH = 1;
parameter MIN_FIFO_LATENCY = 0;
// style can be "REGULAR", for a regular push
// or "TOKEN" for a special fifo that hands out tokens
parameter string STYLE = "REGULAR"; // "REGULAR"/"TOKEN"
parameter STALLFREE = 0;
input clock, resetn, stall_in, valid_in, feedback_stall_in;
output stall_out, valid_out, feedback_valid_out;
input [DATA_WIDTH-1:0] data_in;
input dir;
input predicate;
output [DATA_WIDTH-1:0] data_out, feedback_out;
wire [DATA_WIDTH-1:0] feedback;
wire data_downstream, data_upstream;
wire push_upstream;
assign push_upstream = dir & ~predicate;
assign data_upstream = valid_in & push_upstream;
assign data_downstream = valid_in;
wire feedback_stall, feedback_valid;
reg consumed_downstream, consumed_upstream;
assign valid_out = data_downstream & !consumed_downstream;
assign feedback_valid = data_upstream & !consumed_upstream;
assign data_out = data_in;
assign feedback = data_in;
//assign stall_out = valid_in & ( ~(data_downstream & ~stall_in) & ~(data_upstream & ~feedback_stall));
// assign stall_out = valid_in & ( ~(data_downstream & ~stall_in) | ~(data_upstream & ~feedback_stall));
assign stall_out = stall_in | (feedback_stall & push_upstream );
always @(posedge clock or negedge resetn) begin
if (!resetn) begin
consumed_downstream <= 1'b0;
consumed_upstream <= 1'b0;
end else begin
if (consumed_downstream)
consumed_downstream <= stall_out;
else
consumed_downstream <= stall_out & (data_downstream & ~stall_in);
if (consumed_upstream)
consumed_upstream <= stall_out;
else
consumed_upstream <= stall_out & (data_upstream & ~feedback_stall);
end
end
localparam TYPE = MIN_FIFO_LATENCY < 1 ? (FIFO_DEPTH < 8 ? "zl_reg" : "zl_ram") : (MIN_FIFO_LATENCY < 3 ? (FIFO_DEPTH < 8 ? "ll_reg" : "ll_ram") : (FIFO_DEPTH < 8 ? "ll_reg" : "ram"));
generate
if ( STYLE == "TOKEN" )
begin
acl_token_fifo_counter
#(
.DEPTH(FIFO_DEPTH)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_out(feedback_out),
.valid_in(feedback_valid),
.valid_out(feedback_valid_out),
.stall_in(feedback_stall_in),
.stall_out(feedback_stall)
);
end
else if (FIFO_DEPTH == 0) begin
// if no FIFO depth is requested, just connect
// feedback directly to output
assign feedback_out = feedback;
assign feedback_valid_out = feedback_valid;
assign feedback_stall = feedback_stall_in;
end
else if (FIFO_DEPTH == 1 && MIN_FIFO_LATENCY == 0) begin
// simply add a staging register if the requested depth is 1
// and the latency must be 0
acl_staging_reg #(
.WIDTH(DATA_WIDTH)
) staging_reg (
.clk(clock),
.reset(~resetn),
.i_data(feedback),
.i_valid(feedback_valid),
.o_stall(feedback_stall),
.o_data(feedback_out),
.o_valid(feedback_valid_out),
.i_stall(feedback_stall_in)
);
end
else
begin
// only allow full write in stall free clusters if you're an ll_reg
// otherwise, comb cycles can form, since stall_out depends on
// stall_in the acl_data_fifo. To make up for the last space, we
// add a capacity of 1 to the FIFO
localparam OFFSET = ( (TYPE == "ll_reg") && !STALLFREE ) ? 1 : 0;
localparam ALLOW_FULL_WRITE = ( (TYPE == "ll_reg") && !STALLFREE ) ? 0 : 1;
acl_data_fifo #(
.DATA_WIDTH(DATA_WIDTH),
.DEPTH(((TYPE == "ram") || (TYPE == "ll_ram") || (TYPE == "zl_ram")) ? FIFO_DEPTH + 1 : FIFO_DEPTH + OFFSET),
.IMPL(TYPE),
.ALLOW_FULL_WRITE(ALLOW_FULL_WRITE)
)
fifo (
.clock(clock),
.resetn(resetn),
.data_in(feedback),
.data_out(feedback_out),
.valid_in(feedback_valid),
.valid_out(feedback_valid_out),
.stall_in(feedback_stall_in),
.stall_out(feedback_stall)
);
end
endgenerate
endmodule
|
//===----------------------------------------------------------------------===//
//
// Parameterized FIFO with input and output registers and ACL pipeline
// protocol ports. This "FIFO" stores no data and only hands out a sequence of
// numbers from 0..DEPTH-1 (tokens) in round robin fashion.
//
//===----------------------------------------------------------------------===//
module acl_token_fifo_counter
#(
parameter integer DEPTH = 32, // >0
parameter integer STRICT_DEPTH = 1, // 0|1
parameter integer ALLOW_FULL_WRITE = 0 // 0|1
)
(
clock,
resetn,
data_out, // the width of this signal is set by this module, it is the
// responsibility of the top module to make sure the signal
// widths match across this interface.
valid_in,
valid_out,
stall_in,
stall_out,
empty,
full
);
// This fifo is based on acl_valid_fifo
// However, there are 2 differences:
// 1. The fifo is intialized as full
// 2. We keep another counter to serve as the actual token
// STRICT_DEPTH increases FIFO depth to a power of 2 + 1 depth.
// No data, so just build a counter to count the number of valids stored in this "FIFO".
//
// The counter is constructed to count up to a MINIMUM value of DEPTH entries.
// * Logical range of the counter C0 is [0, DEPTH].
// * empty = (C0 <= 0)
// * full = (C0 >= DEPTH)
//
// To have efficient detection of the empty condition (C0 == 0), the range is offset
// by -1 so that a negative number indicates empty.
// * Logical range of the counter C1 is [-1, DEPTH-1].
// * empty = (C1 < 0)
// * full = (C1 >= DEPTH-1)
// The size of counter C1 is $clog2((DEPTH-1) + 1) + 1 => $clog2(DEPTH) + 1.
//
// To have efficient detection of the full condition (C1 >= DEPTH-1), change the
// full condition to C1 == 2^$clog2(DEPTH-1), which is DEPTH-1 rounded up
// to the next power of 2. This is only done if STRICT_DEPTH == 0, otherwise
// the full condition is comparison vs. DEPTH-1.
// * Logical range of the counter C2 is [-1, 2^$clog2(DEPTH-1)]
// * empty = (C2 < 0)
// * full = (C2 == 2^$clog2(DEPTH - 1))
// The size of counter C2 is $clog2(DEPTH-1) + 2.
// * empty = MSB
// * full = ~[MSB] & [MSB-1]
localparam COUNTER_WIDTH = (STRICT_DEPTH == 0) ?
((DEPTH > 1 ? $clog2(DEPTH-1) : 0) + 2) :
($clog2(DEPTH) + 1);
input clock;
input resetn;
output [COUNTER_WIDTH-1:0] data_out;
input valid_in;
output valid_out;
input stall_in;
output stall_out;
output empty;
output full;
logic [COUNTER_WIDTH - 1:0] valid_counter /* synthesis maxfan=1 dont_merge */;
logic incr, decr;
// The logical range for the token is [0,REAL_DEPTH-1], where REAL_DEPTH
// is the actual depth of the fifo taking STRICT_DEPTH into account
// This counter is 1-bit less wide than valid_counter because it is
// unsigned
logic [COUNTER_WIDTH - 2:0] token;
logic token_max;
assign data_out = token;
assign token_max = (STRICT_DEPTH == 0) ?
(~token[$bits(token) - 1] & token[$bits(token) - 2]) :
(token == DEPTH - 1);
assign empty = valid_counter[$bits(valid_counter) - 1];
assign full = (STRICT_DEPTH == 0) ?
(~valid_counter[$bits(valid_counter) - 1] & valid_counter[$bits(valid_counter) - 2]) :
(valid_counter == DEPTH - 1);
assign incr = valid_in & ~stall_out; // push
assign decr = valid_out & ~stall_in; // pop
assign valid_out = ~empty;
assign stall_out = ALLOW_FULL_WRITE ? (full & stall_in) : full;
always @( posedge clock or negedge resetn )
if( !resetn )
begin
valid_counter <= (STRICT_DEPTH == 0) ? (2^$clog2(DEPTH-1)) : DEPTH - 1; // full
token <= 0;
end
else
begin
valid_counter <= valid_counter + incr - decr;
if (decr) // increment token, if popping
token <= token_max ? 0 : token+1;
end
endmodule
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
`timescale 1ps/1ps
module altera_pll_reconfig_top
#(
parameter reconf_width = 64,
parameter device_family = "Stratix V",
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter ROM_ADDR_WIDTH = 9,
parameter ROM_DATA_WIDTH = 32,
parameter ROM_NUM_WORDS = 512,
parameter ENABLE_MIF = 0,
parameter MIF_FILE_NAME = ""
) (
//input
input wire mgmt_clk,
input wire mgmt_reset,
//conduits
output wire [reconf_width-1:0] reconfig_to_pll,
input wire [reconf_width-1:0] reconfig_from_pll,
// user data (avalon-MM slave interface)
output wire [31:0] mgmt_readdata,
output wire mgmt_waitrequest,
input wire [5:0] mgmt_address,
input wire mgmt_read,
input wire mgmt_write,
input wire [31:0] mgmt_writedata
);
localparam MIF_ADDR_REG = 6'b011111;
localparam START_REG = 6'b000010;
generate
if (ENABLE_MIF == 1)
begin:mif_reconfig // Generate Reconfig with MIF
// MIF-related regs/wires
reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_mgmt_addr;
reg reconfig_mgmt_read;
reg reconfig_mgmt_write;
reg [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_writedata;
wire reconfig_mgmt_waitrequest;
wire [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_readdata;
wire [RECONFIG_ADDR_WIDTH-1:0] mif2reconfig_addr;
wire mif2reconfig_busy;
wire mif2reconfig_read;
wire mif2reconfig_write;
wire [RECONFIG_DATA_WIDTH-1:0] mif2reconfig_writedata;
wire [ROM_ADDR_WIDTH-1:0] mif_base_addr;
reg mif_select;
reg user_start;
wire reconfig2mif_start_out;
assign mgmt_waitrequest = reconfig_mgmt_waitrequest | mif2reconfig_busy | user_start;
// Don't output readdata if MIF streaming is taking place
assign mgmt_readdata = (mif_select) ? 32'b0 : reconfig_mgmt_readdata;
always @(posedge mgmt_clk)
begin
if (mgmt_reset)
begin
reconfig_mgmt_addr <= 0;
reconfig_mgmt_read <= 0;
reconfig_mgmt_write <= 0;
reconfig_mgmt_writedata <= 0;
user_start <= 0;
end
else
begin
reconfig_mgmt_addr <= (mif_select) ? mif2reconfig_addr : mgmt_address;
reconfig_mgmt_read <= (mif_select) ? mif2reconfig_read : mgmt_read;
reconfig_mgmt_write <= (mif_select) ? mif2reconfig_write : mgmt_write;
reconfig_mgmt_writedata <= (mif_select) ? mif2reconfig_writedata : mgmt_writedata;
user_start <= (mgmt_address == START_REG && mgmt_write == 1'b1) ? 1'b1 : 1'b0;
end
end
always @(*)
begin
if (mgmt_reset)
begin
mif_select <= 0;
end
else
begin
mif_select <= (reconfig2mif_start_out || mif2reconfig_busy) ? 1'b1 : 1'b0;
end
end
altera_pll_reconfig_mif_reader
#(
.RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH),
.RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH),
.ROM_ADDR_WIDTH(ROM_ADDR_WIDTH),
.ROM_DATA_WIDTH(ROM_DATA_WIDTH),
.ROM_NUM_WORDS(ROM_NUM_WORDS),
.DEVICE_FAMILY(device_family),
.ENABLE_MIF(ENABLE_MIF),
.MIF_FILE_NAME(MIF_FILE_NAME)
) altera_pll_reconfig_mif_reader_inst0 (
.mif_clk(mgmt_clk),
.mif_rst(mgmt_reset),
//Altera_PLL Reconfig interface
//inputs
.reconfig_busy(reconfig_mgmt_waitrequest),
.reconfig_read_data(reconfig_mgmt_readdata),
//outputs
.reconfig_write_data(mif2reconfig_writedata),
.reconfig_addr(mif2reconfig_addr),
.reconfig_write(mif2reconfig_write),
.reconfig_read(mif2reconfig_read),
//MIF Ctrl Interface
//inputs
.mif_base_addr(mif_base_addr),
.mif_start(reconfig2mif_start_out),
//outputs
.mif_busy(mif2reconfig_busy)
);
// ------ END MIF-RELATED MANAGEMENT ------
altera_pll_reconfig_core
#(
.reconf_width(reconf_width),
.device_family(device_family),
.RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH),
.RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH),
.ROM_ADDR_WIDTH(ROM_ADDR_WIDTH),
.ROM_DATA_WIDTH(ROM_DATA_WIDTH),
.ROM_NUM_WORDS(ROM_NUM_WORDS)
) altera_pll_reconfig_core_inst0 (
//inputs
.mgmt_clk(mgmt_clk),
.mgmt_reset(mgmt_reset),
//PLL interface conduits
.reconfig_to_pll(reconfig_to_pll),
.reconfig_from_pll(reconfig_from_pll),
//User data outputs
.mgmt_readdata(reconfig_mgmt_readdata),
.mgmt_waitrequest(reconfig_mgmt_waitrequest),
//User data inputs
.mgmt_address(reconfig_mgmt_addr),
.mgmt_read(reconfig_mgmt_read),
.mgmt_write(reconfig_mgmt_write),
.mgmt_writedata(reconfig_mgmt_writedata),
// other
.mif_start_out(reconfig2mif_start_out),
.mif_base_addr(mif_base_addr)
);
end // End generate reconfig with MIF
else
begin:reconfig_core // Generate Reconfig core only
wire reconfig2mif_start_out;
wire [ROM_ADDR_WIDTH-1:0] mif_base_addr;
altera_pll_reconfig_core
#(
.reconf_width(reconf_width),
.device_family(device_family),
.RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH),
.RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH),
.ROM_ADDR_WIDTH(ROM_ADDR_WIDTH),
.ROM_DATA_WIDTH(ROM_DATA_WIDTH),
.ROM_NUM_WORDS(ROM_NUM_WORDS)
) altera_pll_reconfig_core_inst0 (
//inputs
.mgmt_clk(mgmt_clk),
.mgmt_reset(mgmt_reset),
//PLL interface conduits
.reconfig_to_pll(reconfig_to_pll),
.reconfig_from_pll(reconfig_from_pll),
//User data outputs
.mgmt_readdata(mgmt_readdata),
.mgmt_waitrequest(mgmt_waitrequest),
//User data inputs
.mgmt_address(mgmt_address),
.mgmt_read(mgmt_read),
.mgmt_write(mgmt_write),
.mgmt_writedata(mgmt_writedata),
// other
.mif_start_out(reconfig2mif_start_out),
.mif_base_addr(mif_base_addr)
);
end // End generate reconfig core only
endgenerate
endmodule
|
// (C) 2001-2012 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
`timescale 1ps/1ps
module altera_pll_reconfig_top
#(
parameter reconf_width = 64,
parameter device_family = "Stratix V",
parameter RECONFIG_ADDR_WIDTH = 6,
parameter RECONFIG_DATA_WIDTH = 32,
parameter ROM_ADDR_WIDTH = 9,
parameter ROM_DATA_WIDTH = 32,
parameter ROM_NUM_WORDS = 512,
parameter ENABLE_MIF = 0,
parameter MIF_FILE_NAME = ""
) (
//input
input wire mgmt_clk,
input wire mgmt_reset,
//conduits
output wire [reconf_width-1:0] reconfig_to_pll,
input wire [reconf_width-1:0] reconfig_from_pll,
// user data (avalon-MM slave interface)
output wire [31:0] mgmt_readdata,
output wire mgmt_waitrequest,
input wire [5:0] mgmt_address,
input wire mgmt_read,
input wire mgmt_write,
input wire [31:0] mgmt_writedata
);
localparam MIF_ADDR_REG = 6'b011111;
localparam START_REG = 6'b000010;
generate
if (ENABLE_MIF == 1)
begin:mif_reconfig // Generate Reconfig with MIF
// MIF-related regs/wires
reg [RECONFIG_ADDR_WIDTH-1:0] reconfig_mgmt_addr;
reg reconfig_mgmt_read;
reg reconfig_mgmt_write;
reg [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_writedata;
wire reconfig_mgmt_waitrequest;
wire [RECONFIG_DATA_WIDTH-1:0] reconfig_mgmt_readdata;
wire [RECONFIG_ADDR_WIDTH-1:0] mif2reconfig_addr;
wire mif2reconfig_busy;
wire mif2reconfig_read;
wire mif2reconfig_write;
wire [RECONFIG_DATA_WIDTH-1:0] mif2reconfig_writedata;
wire [ROM_ADDR_WIDTH-1:0] mif_base_addr;
reg mif_select;
reg user_start;
wire reconfig2mif_start_out;
assign mgmt_waitrequest = reconfig_mgmt_waitrequest | mif2reconfig_busy | user_start;
// Don't output readdata if MIF streaming is taking place
assign mgmt_readdata = (mif_select) ? 32'b0 : reconfig_mgmt_readdata;
always @(posedge mgmt_clk)
begin
if (mgmt_reset)
begin
reconfig_mgmt_addr <= 0;
reconfig_mgmt_read <= 0;
reconfig_mgmt_write <= 0;
reconfig_mgmt_writedata <= 0;
user_start <= 0;
end
else
begin
reconfig_mgmt_addr <= (mif_select) ? mif2reconfig_addr : mgmt_address;
reconfig_mgmt_read <= (mif_select) ? mif2reconfig_read : mgmt_read;
reconfig_mgmt_write <= (mif_select) ? mif2reconfig_write : mgmt_write;
reconfig_mgmt_writedata <= (mif_select) ? mif2reconfig_writedata : mgmt_writedata;
user_start <= (mgmt_address == START_REG && mgmt_write == 1'b1) ? 1'b1 : 1'b0;
end
end
always @(*)
begin
if (mgmt_reset)
begin
mif_select <= 0;
end
else
begin
mif_select <= (reconfig2mif_start_out || mif2reconfig_busy) ? 1'b1 : 1'b0;
end
end
altera_pll_reconfig_mif_reader
#(
.RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH),
.RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH),
.ROM_ADDR_WIDTH(ROM_ADDR_WIDTH),
.ROM_DATA_WIDTH(ROM_DATA_WIDTH),
.ROM_NUM_WORDS(ROM_NUM_WORDS),
.DEVICE_FAMILY(device_family),
.ENABLE_MIF(ENABLE_MIF),
.MIF_FILE_NAME(MIF_FILE_NAME)
) altera_pll_reconfig_mif_reader_inst0 (
.mif_clk(mgmt_clk),
.mif_rst(mgmt_reset),
//Altera_PLL Reconfig interface
//inputs
.reconfig_busy(reconfig_mgmt_waitrequest),
.reconfig_read_data(reconfig_mgmt_readdata),
//outputs
.reconfig_write_data(mif2reconfig_writedata),
.reconfig_addr(mif2reconfig_addr),
.reconfig_write(mif2reconfig_write),
.reconfig_read(mif2reconfig_read),
//MIF Ctrl Interface
//inputs
.mif_base_addr(mif_base_addr),
.mif_start(reconfig2mif_start_out),
//outputs
.mif_busy(mif2reconfig_busy)
);
// ------ END MIF-RELATED MANAGEMENT ------
altera_pll_reconfig_core
#(
.reconf_width(reconf_width),
.device_family(device_family),
.RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH),
.RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH),
.ROM_ADDR_WIDTH(ROM_ADDR_WIDTH),
.ROM_DATA_WIDTH(ROM_DATA_WIDTH),
.ROM_NUM_WORDS(ROM_NUM_WORDS)
) altera_pll_reconfig_core_inst0 (
//inputs
.mgmt_clk(mgmt_clk),
.mgmt_reset(mgmt_reset),
//PLL interface conduits
.reconfig_to_pll(reconfig_to_pll),
.reconfig_from_pll(reconfig_from_pll),
//User data outputs
.mgmt_readdata(reconfig_mgmt_readdata),
.mgmt_waitrequest(reconfig_mgmt_waitrequest),
//User data inputs
.mgmt_address(reconfig_mgmt_addr),
.mgmt_read(reconfig_mgmt_read),
.mgmt_write(reconfig_mgmt_write),
.mgmt_writedata(reconfig_mgmt_writedata),
// other
.mif_start_out(reconfig2mif_start_out),
.mif_base_addr(mif_base_addr)
);
end // End generate reconfig with MIF
else
begin:reconfig_core // Generate Reconfig core only
wire reconfig2mif_start_out;
wire [ROM_ADDR_WIDTH-1:0] mif_base_addr;
altera_pll_reconfig_core
#(
.reconf_width(reconf_width),
.device_family(device_family),
.RECONFIG_ADDR_WIDTH(RECONFIG_ADDR_WIDTH),
.RECONFIG_DATA_WIDTH(RECONFIG_DATA_WIDTH),
.ROM_ADDR_WIDTH(ROM_ADDR_WIDTH),
.ROM_DATA_WIDTH(ROM_DATA_WIDTH),
.ROM_NUM_WORDS(ROM_NUM_WORDS)
) altera_pll_reconfig_core_inst0 (
//inputs
.mgmt_clk(mgmt_clk),
.mgmt_reset(mgmt_reset),
//PLL interface conduits
.reconfig_to_pll(reconfig_to_pll),
.reconfig_from_pll(reconfig_from_pll),
//User data outputs
.mgmt_readdata(mgmt_readdata),
.mgmt_waitrequest(mgmt_waitrequest),
//User data inputs
.mgmt_address(mgmt_address),
.mgmt_read(mgmt_read),
.mgmt_write(mgmt_write),
.mgmt_writedata(mgmt_writedata),
// other
.mif_start_out(reconfig2mif_start_out),
.mif_base_addr(mif_base_addr)
);
end // End generate reconfig core only
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_mem_router #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer NUM_BANKS = 2
)
(
input logic clock,
input logic resetn,
// Bank select (one-hot)
input logic [NUM_BANKS-1:0] bank_select,
// Master
input logic m_arb_request,
input logic m_arb_read,
input logic m_arb_write,
input logic [DATA_W-1:0] m_arb_writedata,
input logic [BURSTCOUNT_W-1:0] m_arb_burstcount,
input logic [ADDRESS_W-1:0] m_arb_address,
input logic [BYTEENA_W-1:0] m_arb_byteenable,
output logic m_arb_stall,
output logic m_wrp_ack,
output logic m_rrp_datavalid,
output logic [DATA_W-1:0] m_rrp_data,
// To each bank
output logic b_arb_request [NUM_BANKS],
output logic b_arb_read [NUM_BANKS],
output logic b_arb_write [NUM_BANKS],
output logic [DATA_W-1:0] b_arb_writedata [NUM_BANKS],
output logic [BURSTCOUNT_W-1:0] b_arb_burstcount [NUM_BANKS],
output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] b_arb_address [NUM_BANKS],
output logic [BYTEENA_W-1:0] b_arb_byteenable [NUM_BANKS],
input logic b_arb_stall [NUM_BANKS],
input logic b_wrp_ack [NUM_BANKS],
input logic b_rrp_datavalid [NUM_BANKS],
input logic [DATA_W-1:0] b_rrp_data [NUM_BANKS]
);
integer i;
localparam PENDING_COUNT_WIDTH=11;
reg [PENDING_COUNT_WIDTH-1:0] b_pending_count[NUM_BANKS];
logic [NUM_BANKS-1:0] pending;
//Given a bank number, makes sure no other bank has pending requests
function [0:0] none_pending ( input integer i );
none_pending = ~|(pending & ~({{PENDING_COUNT_WIDTH-1{1'b0}},1'b1}<<i));
endfunction
always_comb
begin
m_arb_stall = 1'b0;
m_wrp_ack = 1'b0;
m_rrp_datavalid = 1'b0;
m_rrp_data = '0;
for( i = 0; i < NUM_BANKS; i = i + 1 )
begin:bank
b_arb_request[i] = m_arb_request & bank_select[i] & none_pending(i);
b_arb_read[i] = m_arb_read & bank_select[i] & none_pending(i);
b_arb_write[i] = m_arb_write & bank_select[i] & none_pending(i);
b_arb_writedata[i] = m_arb_writedata;
b_arb_burstcount[i] = m_arb_burstcount;
b_arb_address[i] = m_arb_address[ADDRESS_W-$clog2(NUM_BANKS)-1:0];
b_arb_byteenable[i] = m_arb_byteenable;
m_arb_stall |= (b_arb_stall[i] | !none_pending(i)) & bank_select[i];
m_wrp_ack |= b_wrp_ack[i];
m_rrp_datavalid |= b_rrp_datavalid[i];
m_rrp_data |= (b_rrp_datavalid[i] ? b_rrp_data[i] : '0);
end
end
wire add_burst[NUM_BANKS];
wire incr[NUM_BANKS];
wire decr_rd[NUM_BANKS];
wire decr_wr[NUM_BANKS];
reg [BURSTCOUNT_W-1:0] next_incr[NUM_BANKS];
reg [1:0] next_decr[NUM_BANKS];
reg [NUM_BANKS-1:0] last_banksel;
always@(posedge clock or negedge resetn)
if (!resetn)
last_banksel <= {NUM_BANKS{1'b0}};
else
last_banksel <= {NUM_BANKS{m_arb_request}} & bank_select;
// A counter tracks how many outstanding word transfers are needed. When a
// request is accepted its burstcount is added to the counter. When data
// is returned or writeack'ed, the counter is decremented.
// This used to be simple - but manual retiming makes it less so
generate
genvar b;
for ( b = 0; b < NUM_BANKS; b = b + 1 )
begin:bankgen
assign add_burst[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_read[b];
assign incr[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_write[b];
assign decr_rd[b] = b_rrp_datavalid[b];
assign decr_wr[b] = b_wrp_ack[b];
always@(posedge clock or negedge resetn)
if (!resetn)
begin
next_incr[b] = {BURSTCOUNT_W{1'b0}};
next_decr[b] = 2'b0;
end
else
begin
if (add_burst[b])
next_incr[b] = m_arb_burstcount;
else if (incr[b])
next_incr[b] = 2'b01;
else
next_incr[b] = {BURSTCOUNT_W{1'b0}};
next_decr[b] = decr_rd[b] + decr_wr[b];
end
always@(posedge clock or negedge resetn)
if (!resetn)
begin
b_pending_count[b] <= {PENDING_COUNT_WIDTH{1'b0}};
end
else
begin
b_pending_count[b] <= b_pending_count[b] + next_incr[b] - next_decr[b];
end
always_comb
begin
pending[b] = |b_pending_count[b] || last_banksel[b];
end
end
endgenerate
endmodule
|
// (C) 1992-2014 Altera Corporation. All rights reserved.
// Your use of Altera Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Altera MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Altera and sold by
// Altera or its authorized distributors. Please refer to the applicable
// agreement for further details.
module acl_ic_mem_router #(
parameter integer DATA_W = 256,
parameter integer BURSTCOUNT_W = 6,
parameter integer ADDRESS_W = 32,
parameter integer BYTEENA_W = DATA_W / 8,
parameter integer NUM_BANKS = 2
)
(
input logic clock,
input logic resetn,
// Bank select (one-hot)
input logic [NUM_BANKS-1:0] bank_select,
// Master
input logic m_arb_request,
input logic m_arb_read,
input logic m_arb_write,
input logic [DATA_W-1:0] m_arb_writedata,
input logic [BURSTCOUNT_W-1:0] m_arb_burstcount,
input logic [ADDRESS_W-1:0] m_arb_address,
input logic [BYTEENA_W-1:0] m_arb_byteenable,
output logic m_arb_stall,
output logic m_wrp_ack,
output logic m_rrp_datavalid,
output logic [DATA_W-1:0] m_rrp_data,
// To each bank
output logic b_arb_request [NUM_BANKS],
output logic b_arb_read [NUM_BANKS],
output logic b_arb_write [NUM_BANKS],
output logic [DATA_W-1:0] b_arb_writedata [NUM_BANKS],
output logic [BURSTCOUNT_W-1:0] b_arb_burstcount [NUM_BANKS],
output logic [ADDRESS_W-$clog2(NUM_BANKS)-1:0] b_arb_address [NUM_BANKS],
output logic [BYTEENA_W-1:0] b_arb_byteenable [NUM_BANKS],
input logic b_arb_stall [NUM_BANKS],
input logic b_wrp_ack [NUM_BANKS],
input logic b_rrp_datavalid [NUM_BANKS],
input logic [DATA_W-1:0] b_rrp_data [NUM_BANKS]
);
integer i;
localparam PENDING_COUNT_WIDTH=11;
reg [PENDING_COUNT_WIDTH-1:0] b_pending_count[NUM_BANKS];
logic [NUM_BANKS-1:0] pending;
//Given a bank number, makes sure no other bank has pending requests
function [0:0] none_pending ( input integer i );
none_pending = ~|(pending & ~({{PENDING_COUNT_WIDTH-1{1'b0}},1'b1}<<i));
endfunction
always_comb
begin
m_arb_stall = 1'b0;
m_wrp_ack = 1'b0;
m_rrp_datavalid = 1'b0;
m_rrp_data = '0;
for( i = 0; i < NUM_BANKS; i = i + 1 )
begin:bank
b_arb_request[i] = m_arb_request & bank_select[i] & none_pending(i);
b_arb_read[i] = m_arb_read & bank_select[i] & none_pending(i);
b_arb_write[i] = m_arb_write & bank_select[i] & none_pending(i);
b_arb_writedata[i] = m_arb_writedata;
b_arb_burstcount[i] = m_arb_burstcount;
b_arb_address[i] = m_arb_address[ADDRESS_W-$clog2(NUM_BANKS)-1:0];
b_arb_byteenable[i] = m_arb_byteenable;
m_arb_stall |= (b_arb_stall[i] | !none_pending(i)) & bank_select[i];
m_wrp_ack |= b_wrp_ack[i];
m_rrp_datavalid |= b_rrp_datavalid[i];
m_rrp_data |= (b_rrp_datavalid[i] ? b_rrp_data[i] : '0);
end
end
wire add_burst[NUM_BANKS];
wire incr[NUM_BANKS];
wire decr_rd[NUM_BANKS];
wire decr_wr[NUM_BANKS];
reg [BURSTCOUNT_W-1:0] next_incr[NUM_BANKS];
reg [1:0] next_decr[NUM_BANKS];
reg [NUM_BANKS-1:0] last_banksel;
always@(posedge clock or negedge resetn)
if (!resetn)
last_banksel <= {NUM_BANKS{1'b0}};
else
last_banksel <= {NUM_BANKS{m_arb_request}} & bank_select;
// A counter tracks how many outstanding word transfers are needed. When a
// request is accepted its burstcount is added to the counter. When data
// is returned or writeack'ed, the counter is decremented.
// This used to be simple - but manual retiming makes it less so
generate
genvar b;
for ( b = 0; b < NUM_BANKS; b = b + 1 )
begin:bankgen
assign add_burst[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_read[b];
assign incr[b] = b_arb_request[b] & !b_arb_stall[b] & b_arb_write[b];
assign decr_rd[b] = b_rrp_datavalid[b];
assign decr_wr[b] = b_wrp_ack[b];
always@(posedge clock or negedge resetn)
if (!resetn)
begin
next_incr[b] = {BURSTCOUNT_W{1'b0}};
next_decr[b] = 2'b0;
end
else
begin
if (add_burst[b])
next_incr[b] = m_arb_burstcount;
else if (incr[b])
next_incr[b] = 2'b01;
else
next_incr[b] = {BURSTCOUNT_W{1'b0}};
next_decr[b] = decr_rd[b] + decr_wr[b];
end
always@(posedge clock or negedge resetn)
if (!resetn)
begin
b_pending_count[b] <= {PENDING_COUNT_WIDTH{1'b0}};
end
else
begin
b_pending_count[b] <= b_pending_count[b] + next_incr[b] - next_decr[b];
end
always_comb
begin
pending[b] = |b_pending_count[b] || last_banksel[b];
end
end
endgenerate
endmodule
|
// DESCRIPTION: Verilator: Verilog Test module
//
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2012 by Iztok Jeras.
module t (/*AUTOARG*/
// Inputs
clk
);
input clk;
parameter SIZE = 8;
integer cnt = 0;
logic [SIZE-1:0] vld_for;
logic vld_if = 1'b0;
logic vld_else = 1'b0;
genvar i;
// event counter
always @ (posedge clk) begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if (cnt==SIZE) begin : if_cnt_finish
$write("*-* All Finished *-*\n");
$finish;
end : if_cnt_finish_bad
generate
for (i=0; i<SIZE; i=i+1) begin : generate_for
always @ (posedge clk)
if (cnt == i) vld_for[i] <= 1'b1;
end : generate_for_bad
endgenerate
generate
if (SIZE>0) begin : generate_if_if
always @ (posedge clk)
vld_if <= 1'b1;
end : generate_if_if_bad
else begin : generate_if_else
always @ (posedge clk)
vld_else <= 1'b1;
end : generate_if_else_bad
endgenerate
endmodule : t_bad
|
// 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;
parameter SIZE = 8;
integer cnt = 0;
logic [SIZE-1:0] vld_for;
logic vld_if = 1'b0;
logic vld_else = 1'b0;
genvar i;
// event counter
always @ (posedge clk) begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if (cnt==SIZE) begin : if_cnt_finish
$write("*-* All Finished *-*\n");
$finish;
end : if_cnt_finish_bad
generate
for (i=0; i<SIZE; i=i+1) begin : generate_for
always @ (posedge clk)
if (cnt == i) vld_for[i] <= 1'b1;
end : generate_for_bad
endgenerate
generate
if (SIZE>0) begin : generate_if_if
always @ (posedge clk)
vld_if <= 1'b1;
end : generate_if_if_bad
else begin : generate_if_else
always @ (posedge clk)
vld_else <= 1'b1;
end : generate_if_else_bad
endgenerate
endmodule : t_bad
|
// 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;
parameter SIZE = 8;
integer cnt = 0;
logic [SIZE-1:0] vld_for;
logic vld_if = 1'b0;
logic vld_else = 1'b0;
genvar i;
// event counter
always @ (posedge clk) begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if (cnt==SIZE) begin : if_cnt_finish
$write("*-* All Finished *-*\n");
$finish;
end : if_cnt_finish_bad
generate
for (i=0; i<SIZE; i=i+1) begin : generate_for
always @ (posedge clk)
if (cnt == i) vld_for[i] <= 1'b1;
end : generate_for_bad
endgenerate
generate
if (SIZE>0) begin : generate_if_if
always @ (posedge clk)
vld_if <= 1'b1;
end : generate_if_if_bad
else begin : generate_if_else
always @ (posedge clk)
vld_else <= 1'b1;
end : generate_if_else_bad
endgenerate
endmodule : t_bad
|
// 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;
parameter SIZE = 8;
integer cnt = 0;
logic [SIZE-1:0] vld_for;
logic vld_if = 1'b0;
logic vld_else = 1'b0;
genvar i;
// event counter
always @ (posedge clk) begin
cnt <= cnt + 1;
end
// finish report
always @ (posedge clk)
if (cnt==SIZE) begin : if_cnt_finish
$write("*-* All Finished *-*\n");
$finish;
end : if_cnt_finish_bad
generate
for (i=0; i<SIZE; i=i+1) begin : generate_for
always @ (posedge clk)
if (cnt == i) vld_for[i] <= 1'b1;
end : generate_for_bad
endgenerate
generate
if (SIZE>0) begin : generate_if_if
always @ (posedge clk)
vld_if <= 1'b1;
end : generate_if_if_bad
else begin : generate_if_else
always @ (posedge clk)
vld_else <= 1'b1;
end : generate_if_else_bad
endgenerate
endmodule : t_bad
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Lane Brooks
module top (input SEL, input[1:0] A, output W, output X, output Y, output Z);
mux mux2 (.A(A), .SEL(SEL), .Z(W));
pass mux1 (.A(A), .SEL(SEL), .Z(X));
tbuf mux0[1:0] (.A(A), .OE({SEL,!SEL}), .Z(Y));
assign Z = ( SEL) ? A[1] : 1'bz;
tbuf tbuf (.A(A[0]), .OE(!SEL), .Z(Z));
endmodule
module pass (input[1:0] A, input SEL, output Z);
tbuf tbuf1 (.A(A[1]), .OE(SEL), .Z(Z));
tbuf tbuf0 (.A(A[0]), .OE(!SEL),.Z(Z));
endmodule
module tbuf (input A, input OE, output Z);
`ifdef T_BUFIF0
bufif0 (Z, A, !OE);
`elsif T_BUFIF1
bufif1 (Z, A, OE);
`elsif T_NOTIF0
notif0 (Z, !A, !OE);
`elsif T_NOTIF1
notif1 (Z, !A, OE);
`elsif T_PMOS
pmos (Z, A, !OE);
`elsif T_NMOS
nmos (Z, A, OE);
`elsif T_COND
assign Z = (OE) ? A : 1'bz;
`else
`error "Unknown test name"
`endif
endmodule
module mux (input[1:0] A, input SEL, output Z);
assign Z = (SEL) ? A[1] : 1'bz;
assign Z = (!SEL)? A[0] : 1'bz;
assign Z = 1'bz;
endmodule
|
// This file ONLY is placed into the Public Domain, for any use,
// without warranty, 2008 by Lane Brooks
module top (input SEL, input[1:0] A, output W, output X, output Y, output Z);
mux mux2 (.A(A), .SEL(SEL), .Z(W));
pass mux1 (.A(A), .SEL(SEL), .Z(X));
tbuf mux0[1:0] (.A(A), .OE({SEL,!SEL}), .Z(Y));
assign Z = ( SEL) ? A[1] : 1'bz;
tbuf tbuf (.A(A[0]), .OE(!SEL), .Z(Z));
endmodule
module pass (input[1:0] A, input SEL, output Z);
tbuf tbuf1 (.A(A[1]), .OE(SEL), .Z(Z));
tbuf tbuf0 (.A(A[0]), .OE(!SEL),.Z(Z));
endmodule
module tbuf (input A, input OE, output Z);
`ifdef T_BUFIF0
bufif0 (Z, A, !OE);
`elsif T_BUFIF1
bufif1 (Z, A, OE);
`elsif T_NOTIF0
notif0 (Z, !A, !OE);
`elsif T_NOTIF1
notif1 (Z, !A, OE);
`elsif T_PMOS
pmos (Z, A, !OE);
`elsif T_NMOS
nmos (Z, A, OE);
`elsif T_COND
assign Z = (OE) ? A : 1'bz;
`else
`error "Unknown test name"
`endif
endmodule
module mux (input[1:0] A, input SEL, output Z);
assign Z = (SEL) ? A[1] : 1'bz;
assign Z = (!SEL)? A[0] : 1'bz;
assign Z = 1'bz;
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/27/2016 08:26:13 AM
// Design Name:
// Module Name: Mux_8x1
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Mux_8x1
(
//Input Signals
input wire [2:0] select,
input wire [7:0] ch_0,
input wire [7:0] ch_1,
input wire [7:0] ch_2,
input wire [7:0] ch_3,
input wire [7:0] ch_4,
input wire [7:0] ch_5,
input wire [7:0] ch_6,
input wire [7:0] ch_7,
//Output Signals
output reg [7:0] data_out
);
always @*
begin
case(select)
3'b111: data_out = ch_0;
3'b110: data_out = ch_1;
3'b101: data_out = ch_2;
3'b100: data_out = ch_3;
3'b011: data_out = ch_4;
3'b010: data_out = ch_5;
3'b001: data_out = ch_6;
3'b000: data_out = ch_7;
default : data_out = ch_0;
endcase
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/27/2016 08:26:13 AM
// Design Name:
// Module Name: Mux_8x1
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Mux_8x1
(
//Input Signals
input wire [2:0] select,
input wire [7:0] ch_0,
input wire [7:0] ch_1,
input wire [7:0] ch_2,
input wire [7:0] ch_3,
input wire [7:0] ch_4,
input wire [7:0] ch_5,
input wire [7:0] ch_6,
input wire [7:0] ch_7,
//Output Signals
output reg [7:0] data_out
);
always @*
begin
case(select)
3'b111: data_out = ch_0;
3'b110: data_out = ch_1;
3'b101: data_out = ch_2;
3'b100: data_out = ch_3;
3'b011: data_out = ch_4;
3'b010: data_out = ch_5;
3'b001: data_out = ch_6;
3'b000: data_out = ch_7;
default : data_out = ch_0;
endcase
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/27/2016 08:26:13 AM
// Design Name:
// Module Name: Mux_8x1
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Mux_8x1
(
//Input Signals
input wire [2:0] select,
input wire [7:0] ch_0,
input wire [7:0] ch_1,
input wire [7:0] ch_2,
input wire [7:0] ch_3,
input wire [7:0] ch_4,
input wire [7:0] ch_5,
input wire [7:0] ch_6,
input wire [7:0] ch_7,
//Output Signals
output reg [7:0] data_out
);
always @*
begin
case(select)
3'b111: data_out = ch_0;
3'b110: data_out = ch_1;
3'b101: data_out = ch_2;
3'b100: data_out = ch_3;
3'b011: data_out = ch_4;
3'b010: data_out = ch_5;
3'b001: data_out = ch_6;
3'b000: data_out = ch_7;
default : data_out = ch_0;
endcase
end
endmodule
|
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 04/27/2016 08:26:13 AM
// Design Name:
// Module Name: Mux_8x1
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Mux_8x1
(
//Input Signals
input wire [2:0] select,
input wire [7:0] ch_0,
input wire [7:0] ch_1,
input wire [7:0] ch_2,
input wire [7:0] ch_3,
input wire [7:0] ch_4,
input wire [7:0] ch_5,
input wire [7:0] ch_6,
input wire [7:0] ch_7,
//Output Signals
output reg [7:0] data_out
);
always @*
begin
case(select)
3'b111: data_out = ch_0;
3'b110: data_out = ch_1;
3'b101: data_out = ch_2;
3'b100: data_out = ch_3;
3'b011: data_out = ch_4;
3'b010: data_out = ch_5;
3'b001: data_out = ch_6;
3'b000: data_out = ch_7;
default : data_out = ch_0;
endcase
end
endmodule
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.