2.4 Verilog 表达式
全面解析 Verilog 表达式操作数规范、9 大类操作符的优先级与结合性、算术位宽与 x 传播、关系与全等比较、四值逻辑/按位/归约真值表、逻辑与算术移位、位拼接复制及嵌套条件运算符。
学完这一章,你能够
- 全面解析 Verilog 表达式操作数规范、9 大类操作符的优先级与结合性、算术位宽与 x 传播、关系与全等比较、四值逻辑/按位/归约真值表、逻辑与算术移位、位拼接复制及嵌套条件运算符。
表达式、操作数合法性与操作符优先级
表达式由操作符与操作数构成,用于求值并可在任何需要数值的上下文中使用(如 `a ^ b`、`address[9:0] + 10'b1`、`flag1 && flag2`)。操作数可涵盖常数、整数、实数、线网、寄存器、时间、位选、域选、存储器元素与函数调用;但左值必须遵守语法位置约束,例如在 `always` 过程块内只能对寄存器族变量赋值,不能直接对 `wire` 型变量执行过程赋值。
Verilog 共提供算术、关系、等价、逻辑、按位、归约、移位、拼接与条件等 9 大类操作符。同优先级操作符除条件运算符 `?:` 自右向左结合(`A ? B : C ? D : F` 等价于 `A ? B : (C ? D : F)`,不等价于 `(A ? B : C) ? D : F`)外,其余均自左向右结合(如 `A + B - C` 等价于 `(A + B) - C`)。尽管下表给出了完整优先级梯度,工程中遇到复合表达式仍强烈建议显式加圆括号以杜绝歧义。
算术操作符、位宽规划与负数陷阱
双目算术操作符包括乘 `*`、除 `/`(整数除法向零取整)、加 `+`、减 `-`、求幂 `**` 与取模 `%`。算术运算遵循严格的未知态传播规则:只要任一操作数的任意比特为 `x` 或 `z`,整个计算结果的所有位都将变为 `x`(如 `4'b0010 + 4'b100x` 结果全为 `x`)。位宽声明必须预留足够余量以防高位截断——两个 4 bit 无符号数相加至少需 5 bit 结果位宽,而 4 bit 与 2 bit 无符号数相乘(如 `4'he * 2'h3 = 6'h2a`)需以两操作数位宽之和(6 bit)承接。
单目 `+` 与 `-` 具有最高优先级,用于标识正负号。负数在底层按二进制补码运算,切忌在表达式中混用未指明位宽的负进制常数(如 `-'d4` 会按 32 位无符号补码 `32'hffff_fffc` 参与运算,导致乘积位宽与数值严重偏离预期),而应使用明确位宽的有符号变量或 `signed` 修饰。
关系、等价、逻辑与按位操作符
关系操作符(`>`、`<`、`>=`、`<=`)在确定输入下返回 1 bit 真(`1`)或假(`0`),一旦任一操作数含 `x` 或 `z` 即返回 `x`。等价操作符分为两对:逻辑相等/不等(`==`/`!=`)遇到 `x`/`z` 时通常输出 `x`(例如 `4 == 4'bxxxx` 得 `x`);而全等/非全等(`===`/`!==`)执行逐位严格四值匹配(将 `x`、`z` 视作确定符号比较),因此结果永远为 `0` 或 `1`(`4 === 4'bxxxx` 为 `0`,`4'bxxxx === 4'hx` 为 `1`),常用于测试平台检查未知态。
逻辑操作符 `&&`(与)、`||`(或)、`!`(非)产出 1 bit 三值结果(`0`/`1`/`x`):非零值按真处理、全零按假处理,仅含 `0` 与 `x`/`z` 时按不确定 `x` 处理;且支持四值短路吸收(例如真值 `3` 与含 `x` 操作数执行 `||` 时结果确定为 `1`,而与全 `0` 执行 `&&` 结果确定为 `0`)。
按位操作符包括单目取反 `~` 以及双目按位与 `&`、或 `|`、异或 `^`、同或 `~^`(`^~`)。双目按位运算若两操作数位宽不等,则对较短操作数高位左侧补 `0` 对齐后逐位按四值真值表求值(见下方两张真值表);例如 `4'b1001 | 4'bx010` 中最高位 `1 | x = 1` 得 `4'b1011`,而 `4'b1001 & 4'bx010` 得 `4'bx000`。
归约、移位、拼接复制与条件操作符
归约操作符(单目 `&`、`~&`、`|`、`~|`、`^`、`~^`)对单个向量的所有比特依次折叠运算并产出 1 bit 结果(如 `&A` 判断全 1、`~|A` 判断全 0、`^A` 求奇偶校验位);它与按位、逻辑运算符共用符号,区分关键在于操作数个数与结果位宽。移位操作符分为逻辑移位(`<<`、`>>`,空位一律补 `0`)与算术移位(`<<<`、`>>>`,左移低位补 `0`,而对 `signed` 有符号数执行算术右移 `>>>` 时高位补符号位以保持有符号数除 `2^n` 的数值语义)。
拼接操作符 `{op1, op2, ...}` 将多个明确位宽的操作数组合为新向量(其中的常数必须显式标注位宽),配合复制语法 `{N{expr}}` 可便捷构造重复位段(如 `{4{B}, 3'd4}` 得 `7'b111_1100`,`{32{1'b0}}` 生成 32 位零常量)。条件操作符 `cond ? true_expr : false_expr` 是三目选择器,本质对应 2 路多路器,通过嵌套可实现多路地址译码与选择,功能与组合 `if-else` 等价。
Verilog 操作符优先级顺序表(由高到低)
| 类别 | 代表操作符 | 优先级定位 |
|---|---|---|
| 单目运算(含归约) | `+` `-` `!` `~` `&` `~&` `|` `~|` `^` `~^` | 最高 |
| 乘、除、取模 | `*` `/` `%` | 次高 |
| 双目加减 | `+` `-` | 低于乘除 |
| 逻辑与算术移位 | `<<` `>>` `<<<` `>>>` | 低于加减 |
| 大小关系比较 | `<` `<=` `>` `>=` | 低于移位 |
| 逻辑相等与全等 | `==` `!=` `===` `!==` | 低于关系 |
| 按位与 | `&`(双目按位与) | 低于等价 |
| 按位异或 / 同或 | `^` `~^`(`^~`) | 低于按位与 |
| 按位或 | `|`(双目按位或) | 低于按位异或 |
| 逻辑与 | `&&` | 低于按位或 |
| 逻辑或 | `||` | 低于逻辑与 |
| 三目条件选择 | `?:`(右结合) | 最低 |
按位与(&)与按位或(|)四值真值表(z 同 x 规则)
| 左操作数(&) | & 0 | & 1 | & x | 左操作数(|) | | 0 | | 1 | | x |
|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 1 | x |
| 1 | 0 | 1 | x | 1 | 1 | 1 | 1 |
| x | 0 | x | x | x | x | 1 | x |
按位异或(^)与按位同或(~^)四值真值表(z 同 x 规则)
| 左操作数(^) | ^ 0 | ^ 1 | ^ x | 左操作数(~^) | ~^ 0 | ~^ 1 | ~^ x |
|---|---|---|---|---|---|---|---|
| 0 | 0 | 1 | x | 0 | 1 | 0 | x |
| 1 | 1 | 0 | x | 1 | 0 | 1 | x |
| x | x | x | x | x | x | x | x |
离线校验 Verilog 操作符优先级、四值算术/比较/按位真值表、移位与拼接复制
"""Offline Verilog semantic verification lab for Chapter 07 (expression)."""
import json
VERSION = "CPython 3.12.14 offline IEEE 1364 Verilog semantic verifier (native simulator absent)"
def bit_and(a, b):
if a == "0" or b == "0":
return "0"
if a == "1" and b == "1":
return "1"
return "x"
def bit_or(a, b):
if a == "1" or b == "1":
return "1"
if a == "0" and b == "0":
return "0"
return "x"
def bit_xor(a, b):
if a in ("0", "1") and b in ("0", "1"):
return "1" if a != b else "0"
return "x"
def bit_xnor(a, b):
r = bit_xor(a, b)
return "x" if r == "x" else ("1" if r == "0" else "0")
def bit_not(a):
return {"0": "1", "1": "0"}.get(a, "x")
def vec_op(va, vb, fn):
w = max(len(va), len(vb))
pa = va.rjust(w, "0")
pb = vb.rjust(w, "0")
return "".join(fn(x, y) for x, y in zip(pa, pb))
def case_precedence_associativity_and_operands():
# Procedural LHS check: reg legal, wire illegal inside always @*
def can_assign_in_always(var_type):
return var_type in ("reg", "integer", "real", "time")
# Left-associative arithmetic vs right-associative ternary
A, B, C, D, F = 0, 1, 1, 2, 3
arith_eq = (10 + 5 - 3) == ((10 + 5) - 3)
# Right-associative: A ? B : (C ? D : F) -> A=0 => C?D:F => D=2
ternary_right = B if A else (D if C else F)
# Left-grouped: (A ? B : C) ? D : F -> (0?1:1)=1 => D=2; test with A=1, B=0, C=1, D=2, F=3
A2, B2, C2, D2, F2 = 1, 0, 1, 2, 3
right_val = B2 if A2 else (D2 if C2 else F2) # 0
left_val = D2 if (B2 if A2 else C2) else F2 # (1?0:1)=0 => F2=3
precedence_levels = [
"unary(+ - ! ~)", "mul_div_mod(* / %)", "add_sub(+ -)", "shift(<< >> <<< >>>)",
"relational(< <= > >=)", "equality(== != === !==)",
"bitwise_and(& ~&)", "bitwise_xor(^ ~^)", "bitwise_or(| ~|)",
"logical_and(&&)", "logical_or(||)", "conditional(?:)",
]
expected = {
"reg_legal_in_always": True,
"wire_illegal_in_always": True,
"arith_left_assoc": True,
"ternary_right_val": 0,
"ternary_left_grouped_val": 3,
"precedence_level_count": 12,
"ternary_lowest": True,
}
actual = {
"reg_legal_in_always": can_assign_in_always("reg"),
"wire_illegal_in_always": not can_assign_in_always("wire"),
"arith_left_assoc": arith_eq and ternary_right == 2,
"ternary_right_val": right_val,
"ternary_left_grouped_val": left_val,
"precedence_level_count": len(precedence_levels),
"ternary_lowest": precedence_levels[-1] == "conditional(?:)",
}
return {
"name": "precedence_associativity_and_operands",
"summary": "校验操作数合法性(wire 不可在 always 中赋值)、12 级优先级顺序及条件运算符右结合性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_arithmetic_x_propagation_and_width():
def arith_add(va, vb, width):
if any(c in "xz" for c in va + vb):
return "x" * width
val = (int(va, 2) + int(vb, 2)) & ((1 << width) - 1)
return format(val, f"0{width}b")
a, b = "0010", "1001" # 2, 9
c_add = arith_add(a, b, 5) # 5'b01011 = 11
c_div = int(b, 2) // int(a, 2) # 4
c_x = arith_add(a, "100x", 5) # 5'bxxxxx
# Unsigned multiply width: 4-bit (0xE=14) * 2-bit (0x3=3) = 42 = 6'h2a
mul_res = 0xE * 0x3
# Signed negative width: -4'd4 in 6-bit context -> -4 * 2 = -8 -> 6'b111000 = 6'h38
signed_mul_6b = ((-4) * 2) & 0x3F
# Unsized negative literal (-'d4) in 32-bit unsigned context -> (2**32 - 4)
unsized_neg4 = (-4) & 0xFFFFFFFF
expected = {
"add_5b": "01011",
"div_int": 4,
"x_propagates_all_bits": "xxxxx",
"mul_6b_hex": "0x2a",
"signed_neg4_times_2_6b_hex": "0x38",
"unsized_neg4_u32_hex": "0xfffffffc",
}
actual = {
"add_5b": c_add,
"div_int": c_div,
"x_propagates_all_bits": c_x,
"mul_6b_hex": hex(mul_res),
"signed_neg4_times_2_6b_hex": hex(signed_mul_6b),
"unsized_neg4_u32_hex": hex(unsized_neg4),
}
return {
"name": "arithmetic_x_propagation_and_width",
"summary": "验证算术运算位宽扩展、整数除法截断、x 全位污染及有符号/未定宽负数补码陷阱",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_relational_equality_logical_and_bitwise_tables():
def rel_cmp(va, vb, op):
if any(c in "xz" for c in va + vb):
return "x"
ia, ib = int(va, 2), int(vb, 2)
res = {"gt": ia > ib, "le": ia <= ib, "ge": ia >= ib}[op]
return "1" if res else "0"
def eq_logical(va, vb):
if any(c in "xz" for c in va + vb):
return "x"
return "1" if int(va, 2) == int(vb, 2) else "0"
def eq_case(va, vb):
w = max(len(va), len(vb))
return "1" if va.rjust(w, "0") == vb.rjust(w, "0") else "0"
def to_bool4(v):
if "1" in v:
return "1"
if any(c in "xz" for c in v):
return "x"
return "0"
def log_and(va, vb):
return bit_and(to_bool4(va), to_bool4(vb))
def log_or(va, vb):
return bit_or(to_bool4(va), to_bool4(vb))
def log_not(va):
return bit_not(to_bool4(va))
# Verify full 3x3 bitwise tables for &, |, ^, ~^
vals = ("0", "1", "x")
tbl_and = [[bit_and(r, c) for c in vals] for r in vals]
tbl_or = [[bit_or(r, c) for c in vals] for r in vals]
tbl_xor = [[bit_xor(r, c) for c in vals] for r in vals]
tbl_xnor = [[bit_xnor(r, c) for c in vals] for r in vals]
A_bw, B_bw, C_bw = "0101", "1001", "x010"
expected = {
"rel_4_gt_3": "1",
"rel_4_le_3": "0",
"rel_with_x": "x",
"eq_4_vs_8h04": "1",
"eq_4_vs_xxxx": "x",
"case_eq_4_vs_xxxx": "0",
"case_eq_xxxx_vs_4hx": "1",
"log_3_and_1x": "1", # Note: IEEE 1364: 2'b1x has a '1' bit so nonzero -> true! Wait: check 2'b0x too
"log_3_and_0x": "x",
"log_3_or_0x": "1",
"log_not_0": "1",
"bw_not_A": "1010",
"bw_B_or_C": "1011",
"bw_B_and_C": "x000",
"tbl_and": [["0", "0", "0"], ["0", "1", "x"], ["0", "x", "x"]],
"tbl_or": [["0", "1", "x"], ["1", "1", "1"], ["x", "1", "x"]],
"tbl_xor": [["0", "1", "x"], ["1", "0", "x"], ["x", "x", "x"]],
"tbl_xnor": [["1", "0", "x"], ["0", "1", "x"], ["x", "x", "x"]],
}
actual = {
"rel_4_gt_3": rel_cmp("100", "011", "gt"),
"rel_4_le_3": rel_cmp("100", "011", "le"),
"rel_with_x": rel_cmp("100", "1xx", "ge"),
"eq_4_vs_8h04": eq_logical("0100", "00000100"),
"eq_4_vs_xxxx": eq_logical("0100", "xxxx"),
"case_eq_4_vs_xxxx": eq_case("0100", "xxxx"),
"case_eq_xxxx_vs_4hx": eq_case("xxxx", "xxxx"),
"log_3_and_1x": log_and("11", "1x"),
"log_3_and_0x": log_and("11", "0x"),
"log_3_or_0x": log_or("11", "0x"),
"log_not_0": log_not("0"),
"bw_not_A": "".join(bit_not(c) for c in A_bw),
"bw_B_or_C": vec_op(B_bw, C_bw, bit_or),
"bw_B_and_C": vec_op(B_bw, C_bw, bit_and),
"tbl_and": tbl_and,
"tbl_or": tbl_or,
"tbl_xor": tbl_xor,
"tbl_xnor": tbl_xnor,
}
return {
"name": "relational_equality_logical_and_bitwise_tables",
"summary": "校验关系、逻辑相等 == 与全等 ===、逻辑短路与四值按位真值表(&、|、^、~^)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_reduction_shift_concat_and_conditional():
# Reduction on 4'b1010
A_bits = "1010"
red_and = A_bits[0]
red_or = A_bits[0]
red_xor = A_bits[0]
for ch in A_bits[1:]:
red_and = bit_and(red_and, ch)
red_or = bit_or(red_or, ch)
red_xor = bit_xor(red_xor, ch)
red_nor = bit_not(red_or)
# Shift: logical vs signed arithmetic right shift
a_val = 0b1100 # 12 unsigned, -4 in 4-bit signed
lshr = (a_val >> 2) & 0xF # 4'b0011 = 3
lshl = (a_val << 1) & 0xF # 4'b1000 = 8
# Arithmetic right shift on signed 4'b1100 (-4) >>> 2 = -1 = 4'b1111
a_signed = -4
ashr_4b = (a_signed >> 2) & 0xF # 4'b1111
c_val = (0b0010 + ashr_4b) & 0xF # 2 + (-1) mod 16 = 1 = 4'b0001
# Concatenation and replication
A = "1010" # [3]=1,[2]=0,[1]=1,[0]=0
B = "1"
y1 = B + A[0:2] + A[3] + "0011" # 1_10_0_0011 = 11000011
y2 = (B * 4) + "100" # 1111_100 = 1111100
y3 = "0" * 32
# 4-way nested conditional mux
def mux4(addr_hi):
return "p1" if addr_hi == 0 else ("p2" if addr_hi == 1 else ("p3" if addr_hi == 2 else "p4"))
expected = {
"red_and": "0",
"red_nor": "0",
"red_xor": "0",
"lshr_4b": "0011",
"lshl_4b": "1000",
"ashr_signed_4b": "1111",
"b_plus_ashr_4b": "0001",
"y1": "11000011",
"y2": "1111100",
"y3_zero_width": 32,
"mux4_outputs": ["p1", "p2", "p3", "p4"],
}
actual = {
"red_and": red_and,
"red_nor": red_nor,
"red_xor": red_xor,
"lshr_4b": format(lshr, "04b"),
"lshl_4b": format(lshl, "04b"),
"ashr_signed_4b": format(ashr_4b, "04b"),
"b_plus_ashr_4b": format(c_val, "04b"),
"y1": y1,
"y2": y2,
"y3_zero_width": len(y3),
"mux4_outputs": [mux4(i) for i in range(4)],
}
return {
"name": "reduction_shift_concat_and_conditional",
"summary": "验证归约运算、逻辑移位与有符号算术右移 >>>、位拼接/复制及嵌套条件运算符多路选择",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_precedence_associativity_and_operands(),
case_arithmetic_x_propagation_and_width(),
case_relational_equality_logical_and_bitwise_tables(),
case_reduction_shift_concat_and_conditional(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在 CPython 3.12.14 离线脚本中验证 12 级优先级与条件右结合、x 全位污染与位宽溢出、== vs ===、&/|/^/~^ 完整 3×3 真值表、归约/有符号算术右移与位拼接复制全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。
当前源码 SHA256:78af2f7a0d82eafc6e4ed22d7e39103cfa6c4ec27650a19962457930b113cbd9
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。
ZIP SHA256:d612a45755fa7c2d464e8ccc5f3119a1ac8cf6cc8a1ec24432503108d25ced89
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Verilog 测试平台中检查某信号是否处于未知态 `4'bxxxx` 时,为什么必须使用 `===` 而不是 `==`?
展开参考解答
使用 `==` 比较含 `x` 或 `z` 的向量时,表达式本身会返回未知态 `x`(在 `if` 中按假分支处理),无法准确判断相等;而全等操作符 `===` 逐位严格比对四值符号,一定返回确定的 `1` 或 `0`。