Сколько стоит арифметика
Вы узнаете
Почему умножитель дорогой, а сумматор дешёвый, — по измерениям на настоящем чипе.
В логике у каждой операции есть цена, которую платят ресурсами чипа. Сумматор — это цепочка переноса, дешёвая и быстрая. Умножитель из LUT огромен; на чипе есть DSP-блоки, сделанные для умножения, и синтезатор использует их, когда ему можно. Эти кривые — настоящие подсчёты yosys от 4 до 64 битов. Выключите и включите DSP и увидите, почему в железе так заботятся о ширине каждого числа.
Попробуйте
Выберите Multiply, переключите DSP48E1 на -nodsp и сравните LUT на 32 битах с DSP и без них.

Real yosys synth_xilinx counts for add, multiply, MAC and compare from 4 to 64 bits, with and without DSPs, against a whole XC7A200T, and t27 ternary specs beside them.
specs/tutorial/05_widths_and_casts.t27
// SPDX-License-Identifier: Apache-2.0
; 05 — Widths and casts, and the one that catches everybody
; Lesson 5. Converting between widths, and the single sharpest edge in the
; language today: an integer literal types as i32, so arithmetic on a narrower
; mutable local fails the type check unless you say what you mean.
; .
; Everything below is measured against the compiler in this repository, not
; guessed. The failing forms are written out as comments rather than as code,
; because a spec that does not compile teaches nothing.
; phi^2 + 1/phi^2 = 3 | TRINITY
module tutorial-05-widths;
// ============================================================================
// Casting
//
// @as(TYPE, value) assert a type
// @intCast(value) change integer width
//
// They are usually written together: @as names the destination, @intCast does
// the narrowing.
// ============================================================================
pub fn narrow(wide: u16) u8 {
return @as(u8, @intCast(wide));
}
pub fn widen(small: u8) u16 {
return @as(u16, small);
}
// ============================================================================
// The rule
//
// An integer literal is typed i32. So `x + 1` where x is an i8 is an i32
// expression, and assigning it back to an i8 is a type error.
//
// This does NOT compile -- do not copy it:
//
// var x : i8 = a;
// x = x + 1; // type mismatch: cannot assign I32 to I8
//
// Nor does the compound form:
//
// var x : i8 = a;
// x += 1; // same mismatch
//
// It affects every width narrower than i32, signed or unsigned. At i32 and
// wider there is nothing to convert and the plain form is fine -- which is why
// lesson 04's loops all count in i32.
// ============================================================================
// ── Fix 1: say what you mean with a cast ────────────────────────────────────
pub fn increment_narrow(a: i8) i8 {
var x : i8 = a;
x = @as(i8, @intCast(x + 1));
return x;
}
// ── Fix 2: don't mutate; bind a new value ───────────────────────────────────
// Usually the better answer. An immutable local sidesteps the assignment
// entirely, and the arithmetic still happens at i32 where it is safe.
pub fn increment_by_binding(a: i8) i8 {
const stepped = a + 1;
return @as(i8, @intCast(stepped));
}
// ── Fix 3: do the arithmetic wide, narrow once at the end ───────────────────
// The habit to build for anything with more than one step: stay at i32 while
// computing, convert once when you are done.
pub fn average_of_three(a: i8, b: i8, c: i8) i8 {
const total : i32 = a + b + c;
return @as(i8, @intCast(total / 3));
}
// ============================================================================
// The loop exception
//
// A `while` continue-expression accepts `i += 1` on a narrow counter, where
// the same statement in the body would not:
//
// while (i < limit) : (i += 1) { ... } // u8 counter: fine
//
// Worth knowing, but not worth relying on: the continue-expression is stored
// as text rather than as a node in the tree, so the type checker never sees
// it. It is not that this form is checked and passes -- it is that it is not
// checked at all. Prefer an i32 counter when the width is yours to choose.
// ============================================================================
pub fn sum_narrow_counter(limit: u8) u8 {
var total : u8 = 0;
var i : u8 = 0;
while (i < limit) : (i += 1) {
total = total + i;
}
return total;
}
// ============================================================================
// Tests
// ============================================================================
test "the three fixes agree with each other" {
try std.testing.expectEqual(@as(i8, 4), increment_narrow(3));
try std.testing.expectEqual(@as(i8, 4), increment_by_binding(3));
}
test "wide arithmetic then one narrowing" {
try std.testing.expectEqual(@as(i8, 2), average_of_three(1, 2, 3));
}
test "narrowing keeps the low bits" {
try std.testing.expectEqual(@as(u8, 0x34), narrow(0x1234));
try std.testing.expectEqual(@as(u16, 7), widen(7));
}
Все уроки
Модуль 1 · Чип
Что такое FPGA, какой чип у нас и как его выводы встречаются с платой.
Модуль 2 · Числа в железе
Биты, триты и форматы чисел, и сколько стоит арифметика в логике.
Модуль 3 · Ваша программа на t27
Напишите спеку, проверьте её и увидьте, почему «компилируется» не значит «верно».
Модуль 4 · Внутри t27c
Как компилятор читает спеку и что он пишет, включая нативный t27b.
Модуль 5 · От спеки к железу
Verilog, который пишет t27c, ячейки, в которые он превращается, и что делает одна LUT.
Модуль 6 · Читаем синтез
Что yosys сообщает о вашем дизайне и какие предупреждения важны.
Модуль 7 · Размещение, трассировка, тайминг
Где ячейки оказываются на кристалле и успевает ли тактовая частота.
Модуль 8 · Битстрим
Как оттрассированный дизайн становится битами, которые загружает чип, без Vivado.
Модуль 9 · На плате
Спросите чип, кто он, загрузите биты и проверьте их.