-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathautogen
More file actions
executable file
·4305 lines (3657 loc) · 143 KB
/
autogen
File metadata and controls
executable file
·4305 lines (3657 loc) · 143 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) The mlkem-native project authors
# SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT
import subprocess
import tempfile
import platform
import argparse
import shutil
import pathlib
import re
import sys
import threading
import pyparsing as pp
import os
import yaml
import time
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from rich.console import Console
from rich.progress import (
Progress,
BarColumn,
TextColumn,
TaskProgressColumn,
TimeElapsedColumn,
)
console = Console()
# Global progress bar - initialized in _main()
_progress = None
_main_task = None
_current_task = ""
_progress_lock = threading.Lock()
modulus = 3329
root_of_unity = 17
montgomery_factor = pow(2, 16, modulus)
# Compiled regex patterns
_RE_DEFINED = re.compile(r"defined\(([^)]+)\)")
_RE_MARKDOWN_CITE = re.compile(r"\[\^(?P<id>[\w-]+)\]")
_RE_C_CITE = re.compile(r"@\[(?P<id>[\w-]+)")
_RE_BYTECODE_START = re.compile(
r"=== bytecode start: (?:aarch64|x86_64)/mlkem/([^/\s]+?)\.o"
)
_RE_FUNC_SYMBOL = re.compile(r"MLK_ASM_FN_SYMBOL\((.*)\)")
_RE_LABEL = re.compile(r"^(\w+):")
_RE_CONFIG_NAME = re.compile(r"\* Name:\s+(\w+)")
_RE_MACRO_CHECK = re.compile(r"[^_]((?:MLK_|MLKEM_)\w+)(.*)$", re.M)
_RE_DEFINE = re.compile(r"^\s*#define\s+(\w+)")
_RE_ARGS_COMMENT = re.compile(r"(.*?)(\s*//.*)?$")
_RE_MACRO_DEF = re.compile(r"^\s*\.macro\s+(\w+)")
_RE_MACRO_DEF_ARGS = re.compile(r"^(\s*\.macro\s+\w+)(\s+.*)$")
_RE_LEADING_SPACE = re.compile(r"^(\s*)")
# File cache: {filename: {"content": str, "original": str, "force_format": bool}}
# Caches content of files in preparation/modification to avoid repeated
# read/writes to the file system.
_file_cache = {}
_file_cache_lock = threading.Lock()
_errors = []
_errors_lock = threading.Lock()
def read_file(filename, original=False):
"""Read file content, using cache if available"""
with _file_cache_lock:
if filename in _file_cache:
key = "content" if original is False else "original"
return _file_cache[filename][key]
with open(filename, "r") as f:
content = f.read()
_file_cache[filename] = {
"content": content,
"original": content,
"force_format": False,
}
return content
def update_file(filename, content, force_format=False):
"""Write file content to cache"""
with _file_cache_lock:
if filename not in _file_cache:
try:
with open(filename, "r") as f:
original = f.read()
_file_cache[filename] = {"original": original}
except FileNotFoundError:
_file_cache[filename] = {"original": None}
e = _file_cache[filename]
e["content"] = content
e["force_format"] = e.get("force_format", False) or force_format
def finalize_format_batch(batch):
"""Format a batch of files by passing to clang-format with -i flag"""
if not batch:
return
# Create temp files for each filename in batch
temp_files = []
try:
for filename in batch:
content = read_file(filename)
# Skip files scheduled for deletion
if content is None:
continue
with tempfile.NamedTemporaryFile(mode="w", suffix=".c", delete=False) as f:
f.write(content)
temp_files.append((f.name, filename))
# Call clang-format with -i to update files in-place
clang_format_file = os.path.join(
os.path.dirname(__file__), "..", ".clang-format"
)
p = subprocess.run(
["clang-format", "-i", f"-style=file:{clang_format_file}"]
+ [t[0] for t in temp_files],
capture_output=True,
text=True,
)
if p.returncode != 0:
print(p.stderr)
print(
f"Failed to auto-format autogenerated code (clang-format return code {p.returncode}). Are you running in a nix shell? See CONTRIBUTING.md."
)
exit(1)
# Read formatted files back and update cache
for temp_path, filename in temp_files:
with open(temp_path, "r") as f:
update_file(filename, f.read())
finally:
for temp_path, _ in temp_files:
os.unlink(temp_path)
def finalize_file(item, dry_run):
"""Write a single file or delete it if content is None"""
filename, data = item
content_old = data["original"]
content_new = data["content"]
if content_old == content_new:
return
# Handle deletion (content_new is None)
if content_new is None:
if dry_run is False:
file_updated(filename, removed=True)
os.remove(filename)
else:
error(filename, None)
return
if dry_run is False:
file_updated(filename)
with open(filename, "w") as f:
f.write(content_new)
else:
filename_new = f"{filename}.new"
with open(filename_new, "w") as f:
f.write(content_new)
error(filename, filename_new)
def format_files(dry_run):
"""Apply formatting to files"""
to_format = [
filename
for filename, data in _file_cache.items()
if data["force_format"] or filename.endswith((".c", ".h", ".i"))
]
# Group into batches of max 20
batch_size = 20
batches = [
to_format[i : i + batch_size] for i in range(0, len(to_format), batch_size)
]
run_parallel(batches, finalize_format_batch)
def finalize(dry_run):
"""Write dirty files to filesystem"""
run_parallel(_file_cache.items(), partial(finalize_file, dry_run=dry_run))
# This file re-generated auto-generated source files in mlkem-native.
#
# It currently covers:
# - zeta values for the reference NTT and invNTT
# - lookup tables used for fast rejection sampling
# - source files for monolithic single-CU build
# - simplified assembly sources
# - header guards
# - #undef's for CU-local macros
_step_start_time = time.time()
def high_level_task(msg):
"""Set the current high-level task description"""
global _current_task
_current_task = msg
if _progress:
_progress.update(_main_task, description=f"[cyan]{msg}[/]")
def high_level_status(msg, skipped=False):
"""Complete a high-level step and print status"""
global _step_start_time
elapsed = time.time() - _step_start_time
if skipped:
symbol = "[dim]–[/dim]"
else:
symbol = "[green]✓[/green]"
if _progress:
_progress.print(f"{symbol} {msg} ({elapsed:.1f}s)", highlight=False)
_progress.advance(_main_task)
else:
console.print(f"{symbol} {msg} ({elapsed:.1f}s)", highlight=False)
_step_start_time = time.time()
def run_parallel(files, func):
"""Run func over files in parallel with progress tracking"""
if not files:
return []
files = list(files)
total = len(files)
state = {"completed": 0, "last_file": ""}
def update_progress():
if _progress and total > 0:
suffix = (
f" {os.path.basename(state['last_file'])}" if state["last_file"] else ""
)
_progress.update(
_main_task,
description=f"[cyan]{_current_task}[/] [dim][{state['completed']}/{total}]{suffix}[/]",
)
def wrapped(f):
result = func(f)
with _progress_lock:
state["completed"] += 1
state["last_file"] = str(f[0]) if isinstance(f, tuple) else str(f)
update_progress()
return result
with ThreadPoolExecutor() as executor:
return list(executor.map(wrapped, files))
def error(filename, filename_new):
with _errors_lock:
_errors.append((filename, filename_new))
def print_check_errors():
for filename, filename_new in _errors:
console.print(f"[red]error[/] {filename}")
if filename_new is not None:
console.print(
f"Autogenerated file {filename} needs updating. Have you called scripts/autogen? Wrote new version to {filename_new}."
)
if os.path.exists(filename):
subprocess.run(["diff", filename, filename_new])
else:
console.print(
f"Autogenerated file {filename} needs removing. Have you called scripts/autogen?"
)
return len(_errors) == 0
def file_updated(filename, removed=False):
if removed is False:
console.print(f"[bold]updated {filename}[/]")
else:
console.print(f"[bold]removed {filename}[/]")
def gen_autogen_warning():
yield ""
yield "/*"
yield " * WARNING: This file is auto-generated from scripts/autogen"
yield " * in the mlkem-native repository."
yield " * Do not modify it directly."
yield " */"
def gen_header():
yield "/*"
yield " * Copyright (c) The mlkem-native project authors"
yield " * SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT"
yield " */"
yield from gen_autogen_warning()
yield ""
def gen_hol_light_header():
yield "(*"
yield " * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved."
yield " * SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT-0"
yield " *)"
yield ""
yield "(*"
yield " * WARNING: This file is auto-generated from scripts/autogen"
yield " * in the mlkem-native repository."
yield " * Do not modify it directly."
yield " *)"
yield ""
def gen_yaml_header():
yield "# Copyright (c) The mlkem-native project authors"
yield "# SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT"
yield ""
def format_content(content):
clang_format_file = os.path.join(os.path.dirname(__file__), "..", ".clang-format")
p = subprocess.run(
["clang-format", f"-style=file:{clang_format_file}"],
capture_output=True,
input=content,
text=True,
)
if p.returncode != 0:
print(p.stderr)
print(
f"Failed to auto-format autogenerated code (clang-format return code {p.returncode}). Are you running in a nix shell? See CONTRIBUTING.md."
)
exit(1)
return p.stdout
class CondParser:
"""Rudimentary parser for expressions if `#if .. #else ..` directives"""
def __init__(self):
c_identifier = pp.common.identifier()
c_integer_suffix = pp.one_of("U L LU UL LL ULL LLU", caseless=True)
c_dec_integer = pp.Combine(
pp.Optional(pp.one_of("+ -"))
+ pp.Word(pp.nums)
+ pp.Optional(c_integer_suffix)
)
c_hex_integer = pp.Combine(
pp.Literal("0x") + pp.Word(pp.hexnums) + pp.Optional(c_integer_suffix)
)
self.parser = pp.infix_notation(
c_identifier | c_hex_integer | c_dec_integer,
[
(pp.one_of("!"), 1, pp.opAssoc.RIGHT),
(pp.one_of("!= == <= >= > <"), 2, pp.opAssoc.LEFT),
(pp.one_of("&&"), 2, pp.opAssoc.LEFT),
(pp.one_of("||"), 2, pp.opAssoc.LEFT),
],
)
@staticmethod
def connective(res):
"""Extract the top-level connective for the expression"""
if not isinstance(res, list):
return None
elif len(res) == 2:
# Unary operator (will be "!" in our case)
return res[0]
else:
# Binary operator
return res[1]
@staticmethod
def map_top(f, res):
"""Apply function to arguments of top-level connective"""
if not isinstance(res, list):
return res
else:
# We expect `f` to do nothing on strings, so it is safe
# to apply it everywhere, including the connectives.
return list(map(f, res))
@staticmethod
def args(res):
"""Assuming the argument is a binary operation, return all arguments"""
return res[::2]
@staticmethod
def simplify_double_negation(res):
"""Cancel double negations"""
if CondParser.connective(res) == "!" and CondParser.connective(res[1]) == "!":
res = res[1][1]
res = CondParser.map_top(CondParser.simplify_double_negation, res)
return res
@staticmethod
def simplify_not_eq(res):
"""Replace !(x == y) by x != y, and !(x != y) by x == y"""
if CondParser.connective(res) == "!" and CondParser.connective(res[1]) == "==":
res = res[1]
res[1] = "!="
if CondParser.connective(res) == "!" and CondParser.connective(res[1]) == "!=":
res = res[1]
res[1] = "=="
res = CondParser.map_top(CondParser.simplify_not_eq, res)
return res
@staticmethod
def simplify_neq_chain(res):
"""Check for &&-chains of inequalities followed by an equality
which implies the inequality. This catches patterns like
```
#if MLKEM_K == 2
...
#elif MLKEM_K == 3
...
#elif MLKEM_K == 4
...
#endif
```
"""
if (
CondParser.connective(res) == "&&"
and CondParser.connective(res[-1]) == "=="
):
lhs = res[-1][0]
rhs = res[-1][2]
args = []
for a in CondParser.args(res[:-1]):
if CondParser.connective(a) == "!=" and a[0] == lhs:
args.append(a[2])
else:
args = None
break
if args is None:
return res
# Check if all args are numerical and different
if rhs.isdigit() and all(
map(lambda a: a.isdigit() and int(a) != int(rhs), args)
):
# Success -- just drop all but the final condition
return res[-1]
res = CondParser.map_top(CondParser.simplify_neq_chain, res)
return res
@staticmethod
def print_exp(exp, inner=False):
conn = CondParser.connective(exp)
if conn is None:
return exp
elif conn == "!":
res = f"!{CondParser.print_exp(exp[1], inner=True)}"
else:
padded_conn = f" {conn} "
res = padded_conn.join(
map(lambda e: CondParser.print_exp(e, inner=True), CondParser.args(exp))
)
if inner is True and conn in ["&&", "||"]:
res = f"({res})"
return res
def simplify_assoc(exp):
"""Check for unnecesary bracketing and remove it"""
conn = CondParser.connective(exp)
if conn in ["&&", "||"]:
args = CondParser.args(exp)
new_args = []
for a in args:
if CondParser.connective(a) == conn:
new_args += CondParser.args(a)
else:
new_args.append(a)
exp = [x for y in map(lambda x: [x, conn], new_args) for x in y][:-1]
exp = CondParser.map_top(CondParser.simplify_assoc, exp)
return exp
def simplify_all(exp):
exp = CondParser.simplify_double_negation(exp)
exp = CondParser.simplify_not_eq(exp)
exp = CondParser.simplify_neq_chain(exp)
exp = CondParser.simplify_assoc(exp)
return exp
def parse_condition(self, exp, simplify=True):
try:
exp = self.parser.parseString(exp, parseAll=True).as_list()[0]
except pp.ParseException:
print(f"WARNING: Ignoring condition '{exp}' I cannot parse")
return exp
if simplify is True:
exp = CondParser.simplify_all(exp)
return exp
def normalize_condition(self, exp):
return CondParser.print_exp(self.parse_condition(exp))
def adjust_preprocessor_comments_for_filename(
content, source_file, parser, show_status=False
):
"""Automatically add comments to large `#if ... #else ... #endif`
blocks indicating the guarding conditions.
For example, a block
```c
#if FOO
...
#else
...
#endif
```
will be transformed into
```c
#if FOO
...
#else /* FOO */
...
#endif /* !FOO */
```
except when the distance between the preprocessor directives is
very short, and the annotations would be more harmful than useful.
```
"""
content = content.split("\n")
new_content = []
# Stack of `#if` statements. Every entry is a tuple
# `(conds, line_no, if_or_else, has_children)`, where
# - `conds` is the list of conditions being tested.
# In a normal `#if ... #else ...` braach, this is a singleton list
# containing the condition being tested. In a chain of
# `#if .. #elif ..` it contains all conditions encountered to this point.
# - `line_no` is the line where it started
# - `if_or_else` indicates whether we are in the `#if`
# or the `#else` branch (if present)
# - `force_print` indicates if a comment should be omitted
if_stack = []
def merge_escaped_lines(line, i):
while line.endswith("\\"):
line = line.removesuffix("\\").rstrip() + content[i + 1].lstrip()
i = i + 1
return (line, i)
def merge_commented_lines(line, i):
# Not very robust, but good enough
if "/*" not in line or "*/" in line:
return (line, i)
i += 1
while "*/" not in content[i]:
line += content[i]
i += 1
line += content[i]
return (line, i)
def should_print(cur_line_no, conds, line_no, force_print):
line_threshold = 5
if force_print is True:
return True
if cur_line_no - line_no >= line_threshold:
return True
return False
def format_condition(cond):
cond = _RE_DEFINED.sub(r"\1", cond)
return parser.normalize_condition(cond)
def format_conditions(conds, branch):
prev_conds = list(map(lambda s: f"!({s})", conds[:-1]))
final_cond = conds[-1]
if branch is False:
final_cond = f"!({final_cond})"
full_cond = "&&".join(prev_conds + [final_cond])
return format_condition(full_cond)
def wrap_long_directive(directive, condition, max_len=80):
"""Manually wrap long preprocessor comment lines without subprocess overhead"""
single_line = directive + " " + condition
if len(single_line) <= max_len:
return single_line
# Wrap condition across multiple lines with backslash continuation
words = condition.split()
lines = []
current = f"{directive} "
indent = (len(directive) + 4) * " "
indent_final = (len(directive) + 2) * " "
for word in words:
if len(current) + len(word) + 1 <= max_len:
current += word + " "
else:
lines.append(current.rstrip() + " \\")
if word == "*/":
current = indent_final + word
else:
current = indent + word + " "
lines.append(current.rstrip())
return "\n".join(lines)
def adhoc_format(directive, content):
# .c and .h files are formatted as a whole
if not source_file.endswith(".S"):
return directive + " /* " + content + " */"
# For .S files, manually wrap long lines
return wrap_long_directive(directive, "/* " + content + " */")
i = 0
while i < len(content):
line = content[i].strip()
# Replace #ifdef by #if defined(...)
if line.startswith("#ifdef "):
line = "#if defined(" + line.removeprefix("#ifdef").strip() + ")"
if line.startswith("#ifndef "):
line = "#if !defined(" + line.removeprefix("#ifndef").strip() + ")"
if line.startswith("#if"):
line, _ = merge_escaped_lines(line, i)
cond = line.removeprefix("#if")
if_stack.append(([cond], i, True, False))
new_content.append(content[i])
elif line.startswith("#elif"):
conds, _, _, force_print = if_stack.pop()
line, _ = merge_escaped_lines(line, i)
conds.append(line.removeprefix("#elif"))
if_stack.append((conds, i, True, force_print))
new_content.append(content[i])
elif line.startswith("#else"):
line, i = merge_escaped_lines(line, i)
_, i = merge_commented_lines(line, i)
conds, j, branch, force_print = if_stack.pop()
assert branch is True
print_else = should_print(i, cond, j, force_print)
if_stack.append((conds, i, False, print_else))
if print_else is True:
cond = format_conditions(conds, True)
new_content.append(adhoc_format("#else", cond))
else:
new_content.append("#else")
elif line.startswith("#endif"):
line, i = merge_escaped_lines(line, i)
_, i = merge_commented_lines(line, i)
conds, j, branch, force_print = if_stack.pop()
print_endif = should_print(i, conds, j, force_print)
if print_endif is False:
new_content.append("#endif")
else:
cond = format_conditions(conds, branch)
new_content.append(adhoc_format("#endif", cond))
else:
# Skip over multiline comments -- we don't want to
# handle `#if ...` inside documentation as this would
# lead to nested `/* ... */`.
i_old = i
_, i = merge_commented_lines(line, i_old)
new_content += content[i_old : i + 1]
i += 1
return "\n".join(new_content)
def gen_preprocessor_comments_for(parser, source_file):
content = read_file(source_file)
new_content = adjust_preprocessor_comments_for_filename(
content, source_file, parser, show_status=True
)
update_file(source_file, new_content)
def gen_preprocessor_comments():
files = get_c_source_files() + get_asm_source_files() + get_header_files()
parser = CondParser()
run_parallel(files, partial(gen_preprocessor_comments_for, parser))
def bitreverse(i, n):
r = 0
for _ in range(n):
r = 2 * r + (i & 1)
i >>= 1
return r
def signed_reduce(a):
"""Return signed canonical representative of a mod b"""
c = a % modulus
if c >= modulus / 2:
c -= modulus
return c
def gen_c_zetas():
"""Generate source and header file for zeta values used in
the reference NTT and invNTT"""
# The zeta values are the powers of the chosen root of unity (17),
# converted to Montgomery form.
zeta = []
for i in range(128):
zeta.append(signed_reduce(pow(root_of_unity, i, modulus) * montgomery_factor))
# The source code stores the zeta table in bit reversed form
yield from (zeta[bitreverse(i, 7)] for i in range(128))
def gen_c_zeta_file():
def gen():
yield from gen_header()
yield ""
yield "/*"
yield " * Table of zeta values used in the reference NTT and inverse NTT."
yield " * See autogen for details."
yield " */"
yield "static MLK_ALIGN const int16_t mlk_zetas[128] = {"
yield from map(lambda t: str(t) + ",", gen_c_zetas())
yield "};"
yield ""
update_file("mlkem/src/zetas.inc", "\n".join(gen()), force_format=True)
def prepare_root_for_barrett(root):
"""Takes a constant that the code needs to Barrett-multiply with,
and returns the pair of (a) its signed canonical form, (b) the
twisted constant used in the high-mul part of the Barrett multiplication."""
# Signed canonical reduction
root = signed_reduce(root)
def round_to_even(t):
rt = round(t)
if rt % 2 == 0:
return rt
# Make sure to pick a rounding target
# that's <= 1 away from x in absolute value.
if rt <= t:
return rt + 1
return rt - 1
root_twisted = round_to_even((root * 2**16) / modulus) // 2
return root, root_twisted
def gen_aarch64_root_of_unity_for_block(layer, block, inv=False):
# We are computing a negacyclic NTT; the twiddles needed here is
# the second half of the twiddles for a cyclic NTT of twice the size.
# For ease of calculating the roots, layers are numbers 0 through 6
# in this function.
log = bitreverse(pow(2, layer) + block, 7)
if inv is True:
log = -log
root, root_twisted = prepare_root_for_barrett(pow(root_of_unity, log, modulus))
return root, root_twisted
def gen_aarch64_fwd_ntt_zetas_layer12345():
# Layers 1,2,3 are merged
yield from gen_aarch64_root_of_unity_for_block(0, 0)
yield from gen_aarch64_root_of_unity_for_block(1, 0)
yield from gen_aarch64_root_of_unity_for_block(1, 1)
yield from gen_aarch64_root_of_unity_for_block(2, 0)
yield from gen_aarch64_root_of_unity_for_block(2, 1)
yield from gen_aarch64_root_of_unity_for_block(2, 2)
yield from gen_aarch64_root_of_unity_for_block(2, 3)
yield from (0, 0) # Padding
# Layers 4,5,6,7 are merged, but we emit roots for 4,5
# in separate arrays than those for 6,7
for block in range(8): # There are 8 blocks in Layer 4
yield from gen_aarch64_root_of_unity_for_block(3, block)
yield from gen_aarch64_root_of_unity_for_block(4, 2 * block + 0)
yield from gen_aarch64_root_of_unity_for_block(4, 2 * block + 1)
yield from (0, 0) # Padding
def gen_aarch64_fwd_ntt_zetas_layer67():
# Layers 4,5,6,7 are merged, but we emit roots for 4,5
# in separate arrays than those for 6,7
for block in range(8):
def double_ith(t, i):
yield from (t[i], t[i])
# Ordering of blocks is adjusted to suit the transposed internal
# presentation of the data
for i in range(2):
yield from double_ith(
gen_aarch64_root_of_unity_for_block(5, 4 * block + 0), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(5, 4 * block + 1), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(5, 4 * block + 2), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(5, 4 * block + 3), i
)
for i in range(2):
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 0), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 2), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 4), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 6), i
)
for i in range(2):
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 1), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 3), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 5), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 7), i
)
def gen_aarch64_inv_ntt_zetas_layer12345():
# Layers 4,5,6,7 are merged, but we emit roots for 4,5
# in separate arrays than those for 6,7
for block in range(8): # There are 8 blocks in Layer 4
yield from gen_aarch64_root_of_unity_for_block(3, block, inv=True)
yield from gen_aarch64_root_of_unity_for_block(4, 2 * block + 0, inv=True)
yield from gen_aarch64_root_of_unity_for_block(4, 2 * block + 1, inv=True)
yield from (0, 0) # Padding
# Layers 1,2,3 are merged
yield from gen_aarch64_root_of_unity_for_block(0, 0, inv=True)
yield from gen_aarch64_root_of_unity_for_block(1, 0, inv=True)
yield from gen_aarch64_root_of_unity_for_block(1, 1, inv=True)
yield from gen_aarch64_root_of_unity_for_block(2, 0, inv=True)
yield from gen_aarch64_root_of_unity_for_block(2, 1, inv=True)
yield from gen_aarch64_root_of_unity_for_block(2, 2, inv=True)
yield from gen_aarch64_root_of_unity_for_block(2, 3, inv=True)
yield from (0, 0) # Padding
def gen_aarch64_inv_ntt_zetas_layer67():
# Layers 4,5,6,7 are merged, but we emit roots for 4,5
# in separate arrays than those for 6,7
for block in range(8):
def double_ith(t, i):
yield from (t[i], t[i])
# Ordering of blocks is adjusted to suit the transposed internal
# presentation of the data
for i in range(2):
yield from double_ith(
gen_aarch64_root_of_unity_for_block(5, 4 * block + 0, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(5, 4 * block + 1, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(5, 4 * block + 2, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(5, 4 * block + 3, inv=True), i
)
for i in range(2):
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 0, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 2, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 4, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 6, inv=True), i
)
for i in range(2):
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 1, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 3, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 5, inv=True), i
)
yield from double_ith(
gen_aarch64_root_of_unity_for_block(6, 8 * block + 7, inv=True), i
)
def gen_aarch64_mulcache_twiddles():
for idx in range(0, 128):
root = pow(root_of_unity, 2 * bitreverse(idx, 7) + 1, modulus)
yield prepare_root_for_barrett(root)[0]
def gen_aarch64_mulcache_twiddles_twisted():
for idx in range(0, 128):
root = pow(root_of_unity, 2 * bitreverse(idx, 7) + 1, modulus)
yield prepare_root_for_barrett(root)[1]
def print_hol_light_array(g, as_int=True, entries_per_line=8, pad=0):
# Format of integer list entries, including `;` separator:
# - Positive numbers: &42;
# - Negative numbers: -- &42;
# If as_int is false, we omit `&` and emit constant as numerals.
def format_hol_light_int(n):
prefix = ""
if n < 0:
prefix = "-- "
n = -n
c = "&" if as_int is True else ""
return f"{prefix}{c}{n:>{pad}};"
items = list(map(format_hol_light_int, g))
# Remove `;` from end of last entry
items[-1] = items[-1][:-1]
for i in range(0, len(items), entries_per_line):
yield " " + " ".join(items[i : i + entries_per_line])
def gen_aarch64_hol_light_zeta_file():
def gen():
yield from gen_hol_light_header()
yield "(*"
yield " * Table of zeta values used in the AArch64 NTTs"
yield " * See autogen for details."
yield " *)"
yield ""
yield "let ntt_zetas_layer12345 = define `ntt_zetas_layer12345:int list = ["
yield from print_hol_light_array(gen_aarch64_fwd_ntt_zetas_layer12345())
yield "]`;;"
yield ""
yield "let ntt_zetas_layer67 = define `ntt_zetas_layer67:int list = ["
yield from print_hol_light_array(gen_aarch64_fwd_ntt_zetas_layer67())
yield "]`;;"
yield ""
yield "let intt_zetas_layer12345 = define `intt_zetas_layer12345:int list = ["
yield from print_hol_light_array(gen_aarch64_inv_ntt_zetas_layer12345())
yield "]`;;"
yield ""
yield "let intt_zetas_layer67 = define `intt_zetas_layer67:int list = ["
yield from print_hol_light_array(gen_aarch64_inv_ntt_zetas_layer67())
yield "]`;;"
yield ""
yield "let mulcache_zetas = define `mulcache_zetas:int list = ["
yield from print_hol_light_array(gen_aarch64_mulcache_twiddles())
yield "]`;;"
yield ""
yield ""
yield "let mulcache_zetas_twisted = define `mulcache_zetas_twisted:int list = ["
yield from print_hol_light_array(gen_aarch64_mulcache_twiddles_twisted())
yield "]`;;"
yield ""
update_file("proofs/hol_light/aarch64/proofs/mlkem_zetas.ml", "\n".join(gen()))
def gen_aarch64_zeta_file():
def gen():
yield from gen_header()
yield '#include "../../../common.h"'
yield ""
yield "#if defined(MLK_ARITH_BACKEND_AARCH64) && \\"
yield " !defined(MLK_CONFIG_MULTILEVEL_NO_SHARED)"
yield ""
yield '#include "arith_native_aarch64.h"'