-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathsynlig_simplify.cc
4481 lines (3988 loc) · 229 KB
/
synlig_simplify.cc
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
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* ---
*
* This is the AST frontend library.
*
* The AST frontend library is not a frontend on it's own but provides a
* generic abstract syntax tree (AST) abstraction for HDL code and can be
* used by HDL frontends. See "ast.h" for an overview of the API and the
* Verilog frontend for an usage example.
*
*/
#include "kernel/log.h"
#include "libs/sha1/sha1.h"
#include "synlig_const2ast.h"
#include <math.h>
#include <sstream>
#include <stdarg.h>
#include <stdlib.h>
#include "synlig_simplify.h"
YOSYS_NAMESPACE_BEGIN
namespace VERILOG_FRONTEND
{
extern bool sv_mode;
}
YOSYS_NAMESPACE_END
namespace systemverilog_plugin
{
using namespace ::Yosys;
using namespace ::Yosys::AST_INTERNAL;
void synlig_annotate_typed_enums(Yosys::AST::AstNode *ast_node, Yosys::AST::AstNode *template_node)
{
// check if enum
if (template_node->attributes.count(ID::enum_type)) {
// get reference to enum node:
std::string enum_type = template_node->attributes[ID::enum_type]->str.c_str();
// log("enum_type=%s (count=%lu)\n", enum_type.c_str(), current_scope.count(enum_type));
// log("current scope:\n");
// for (auto &it : current_scope)
// log(" %s\n", it.first.c_str());
log_assert(current_scope.count(enum_type) == 1);
Yosys::AST::AstNode *enum_node = current_scope.at(enum_type);
log_assert(enum_node->type == Yosys::AST::AST_ENUM);
while (synlig_simplify(enum_node, true, false, false, 1, -1, false, true)) {
}
// get width from 1st enum item:
log_assert(enum_node->children.size() >= 1);
Yosys::AST::AstNode *enum_item0 = enum_node->children[0];
log_assert(enum_item0->type == Yosys::AST::AST_ENUM_ITEM);
int width;
if (!enum_item0->range_valid)
width = 1;
else if (enum_item0->range_swapped)
width = enum_item0->range_right - enum_item0->range_left + 1;
else
width = enum_item0->range_left - enum_item0->range_right + 1;
log_assert(width > 0);
// add declared enum items:
for (auto enum_item : enum_node->children) {
log_assert(enum_item->type == Yosys::AST::AST_ENUM_ITEM);
// get is_signed
bool is_signed;
if (enum_item->children.size() == 1) {
is_signed = false;
} else if (enum_item->children.size() == 2) {
log_assert(enum_item->children[1]->type == Yosys::AST::AST_RANGE);
is_signed = enum_item->children[1]->is_signed;
} else {
log_error("enum_item children size==%lu, expected 1 or 2 for %s (%s)\n", enum_item->children.size(), enum_item->str.c_str(),
enum_node->str.c_str());
}
// start building attribute string
std::string enum_item_str = "\\enum_value_";
// get enum item value
if (enum_item->children[0]->type != Yosys::AST::AST_CONSTANT) {
log_error("expected const, got %s for %s (%s)\n", type2str(enum_item->children[0]->type).c_str(), enum_item->str.c_str(),
enum_node->str.c_str());
}
RTLIL::Const val = enum_item->children[0]->bitsAsConst(width, is_signed);
enum_item_str.append(val.as_string());
// set attribute for available val to enum item name mappings
ast_node->attributes[enum_item_str.c_str()] = Yosys::AST::AstNode::mkconst_str(enum_item->str);
}
}
}
static bool synlig_name_has_dot(const std::string &name, std::string &struct_name)
{
// check if plausible struct member name \sss.mmm
std::string::size_type pos;
if (name.substr(0, 1) == "\\" && (pos = name.find('.', 0)) != std::string::npos) {
struct_name = name.substr(0, pos);
return true;
}
return false;
}
static Yosys::AST::AstNode *synlig_make_range(int left, int right, bool is_signed = false)
{
// generate a pre-validated range node for a fixed signal range.
auto range = new Yosys::AST::AstNode(Yosys::AST::AST_RANGE);
range->range_left = left;
range->range_right = right;
range->range_valid = true;
range->children.push_back(Yosys::AST::AstNode::mkconst_int(left, true));
range->children.push_back(Yosys::AST::AstNode::mkconst_int(right, true));
range->is_signed = is_signed;
return range;
}
static int synlig_range_width(Yosys::AST::AstNode *node, Yosys::AST::AstNode *rnode)
{
log_assert(rnode->type == Yosys::AST::AST_RANGE);
if (!rnode->range_valid) {
log_file_error(node->filename, node->location.first_line, "Size must be constant in packed struct/union member %s\n", node->str.c_str());
}
// note: range swapping has already been checked for
return rnode->range_left - rnode->range_right + 1;
}
[[noreturn]] static void synlig_struct_array_packing_error(Yosys::AST::AstNode *node)
{
log_file_error(node->filename, node->location.first_line, "Unpacked array in packed struct/union member %s\n", node->str.c_str());
}
static void synlig_save_struct_range_dimensions(Yosys::AST::AstNode *node, Yosys::AST::AstNode *rnode)
{
node->dimensions.push_back({rnode->range_right, synlig_range_width(node, rnode), rnode->range_swapped});
}
static int synlig_get_struct_range_offset(Yosys::AST::AstNode *node, int dimension) { return node->dimensions[dimension].range_right; }
static int synlig_get_struct_range_width(Yosys::AST::AstNode *node, int dimension) { return node->dimensions[dimension].range_width; }
static int synlig_size_packed_struct(Yosys::AST::AstNode *snode, int base_offset)
{
// Struct members will be laid out in the structure contiguously from left to right.
// Union members all have zero offset from the start of the union.
// Determine total packed size and assign offsets. Store these in the member node.
bool is_union = (snode->type == Yosys::AST::AST_UNION);
int offset = 0;
int packed_width = -1;
// embedded struct or union with range?
auto it =
std::remove_if(snode->children.begin(), snode->children.end(), [](Yosys::AST::AstNode *node) { return node->type == Yosys::AST::AST_RANGE; });
std::vector<Yosys::AST::AstNode *> ranges(it, snode->children.end());
snode->children.erase(it, snode->children.end());
if (!ranges.empty()) {
if (ranges.size() > 1) {
log_file_error(ranges[1]->filename, ranges[1]->location.first_line,
"Currently support for custom-type with range is limited to single range\n");
}
for (auto range : ranges) {
auto low = min(range->range_left, range->range_right);
auto high = max(range->range_left, range->range_right);
snode->dimensions.push_back({low, high - low + 1, range->range_swapped});
}
}
// examine members from last to first
for (auto it = snode->children.rbegin(); it != snode->children.rend(); ++it) {
auto node = *it;
int width;
if (node->type == Yosys::AST::AST_STRUCT || node->type == Yosys::AST::AST_UNION) {
// embedded struct or union
width = synlig_size_packed_struct(node, base_offset + offset);
// set range of struct
node->range_right = base_offset + offset;
node->range_left = base_offset + offset + width - 1;
node->range_valid = true;
} else {
log_assert(node->type == Yosys::AST::AST_STRUCT_ITEM);
if (node->children.size() > 0 && node->children[0]->type == Yosys::AST::AST_RANGE) {
// member width e.g. bit [7:0] a
width = synlig_range_width(node, node->children[0]);
if (node->children.size() == 2) {
// Unpacked array. Note that this is a Yosys extension; only packed data types
// and integer data types are allowed in packed structs / unions in SystemVerilog.
if (node->children[1]->type == Yosys::AST::AST_RANGE) {
// Unpacked array, e.g. bit [63:0] a [0:3]
auto rnode = node->children[1];
if (rnode->children.size() == 1) {
// C-style array size, e.g. bit [63:0] a [4]
node->dimensions.push_back({0, rnode->range_left, true});
width *= rnode->range_left;
} else {
synlig_save_struct_range_dimensions(node, rnode);
width *= synlig_range_width(node, rnode);
}
synlig_save_struct_range_dimensions(node, node->children[0]);
} else {
// The Yosys extension for unpacked arrays in packed structs / unions
// only supports memories, i.e. e.g. logic [7:0] a [256] - see above.
synlig_struct_array_packing_error(node);
}
} else {
// Vector
synlig_save_struct_range_dimensions(node, node->children[0]);
}
// range nodes are now redundant
for (Yosys::AST::AstNode *child : node->children)
delete child;
node->children.clear();
} else if (node->children.size() > 0 && node->children[0]->type == Yosys::AST::AST_MULTIRANGE) {
// Packed array, e.g. bit [3:0][63:0] a
if (node->children.size() != 1) {
// The Yosys extension for unpacked arrays in packed structs / unions
// only supports memories, i.e. e.g. logic [7:0] a [256] - see above.
synlig_struct_array_packing_error(node);
}
width = 1;
for (auto rnode : node->children[0]->children) {
synlig_save_struct_range_dimensions(node, rnode);
width *= synlig_range_width(node, rnode);
}
// range nodes are now redundant
for (Yosys::AST::AstNode *child : node->children)
delete child;
node->children.clear();
} else if (node->range_left < 0) {
// 1 bit signal: bit, logic or reg
width = 1;
} else {
// already resolved and compacted
width = node->range_left - node->range_right + 1;
}
if (is_union) {
node->range_right = base_offset;
node->range_left = base_offset + width - 1;
} else {
node->range_right = base_offset + offset;
node->range_left = base_offset + offset + width - 1;
}
node->range_valid = true;
}
if (is_union) {
// check that all members have the same size
if (packed_width == -1) {
// first member
packed_width = width;
} else {
if (packed_width != width) {
log_file_error(node->filename, node->location.first_line, "member %s of a packed union has %d bits, expecting %d\n",
node->str.c_str(), width, packed_width);
}
}
} else {
offset += width;
}
}
return (is_union ? packed_width : offset);
}
Yosys::AST::AstNode *synlig_get_struct_member(const Yosys::AST::AstNode *node)
{
Yosys::AST::AstNode *member_node;
if (node->attributes.count(ID::wiretype) && (member_node = node->attributes.at(ID::wiretype)) &&
(member_node->type == Yosys::AST::AST_STRUCT_ITEM || member_node->type == Yosys::AST::AST_STRUCT ||
member_node->type == Yosys::AST::AST_UNION)) {
return member_node;
}
return NULL;
}
static void synlig_add_members_to_scope(Yosys::AST::AstNode *snode, std::string name)
{
// add all the members in a struct or union to local scope
// in case later referenced in assignments
log_assert(snode->type == Yosys::AST::AST_STRUCT || snode->type == Yosys::AST::AST_UNION);
for (auto *node : snode->children) {
auto member_name = name + "." + node->str;
current_scope[member_name] = node;
if (node->type != Yosys::AST::AST_STRUCT_ITEM) {
// embedded struct or union
synlig_add_members_to_scope(node, name + "." + node->str);
}
}
}
static int synlig_get_max_offset(Yosys::AST::AstNode *node)
{
// get the width from the MS member in the struct
// as members are laid out from left to right in the packed wire
log_assert(node->type == Yosys::AST::AST_STRUCT || node->type == Yosys::AST::AST_UNION);
while (node->type != Yosys::AST::AST_STRUCT_ITEM) {
node = node->children[0];
}
return node->range_left;
}
static Yosys::AST::AstNode *synlig_make_packed_struct(Yosys::AST::AstNode *template_node, std::string &name)
{
// create a wire for the packed struct
auto wnode = new Yosys::AST::AstNode(Yosys::AST::AST_WIRE);
wnode->str = name;
wnode->is_logic = true;
wnode->range_valid = true;
wnode->is_signed = template_node->is_signed;
int offset = synlig_get_max_offset(template_node);
auto range = synlig_make_range(offset, 0);
wnode->children.push_back(range);
// make sure this node is the one in scope for this name
current_scope[name] = wnode;
// add all the struct members to scope under the wire's name
synlig_add_members_to_scope(template_node, name);
return wnode;
}
// check if a node or its children contains an assignment to the given variable
static bool synlig_node_contains_assignment_to(const Yosys::AST::AstNode *node, const Yosys::AST::AstNode *var)
{
if (node->type == Yosys::AST::AST_ASSIGN_EQ || node->type == Yosys::AST::AST_ASSIGN_LE) {
// current node is iteslf an assignment
log_assert(node->children.size() >= 2);
const Yosys::AST::AstNode *lhs = node->children[0];
if (lhs->type == Yosys::AST::AST_IDENTIFIER && lhs->str == var->str)
return false;
}
for (const Yosys::AST::AstNode *child : node->children) {
// if this child shadows the given variable
if (child != var && child->str == var->str && child->type == Yosys::AST::AST_WIRE)
break; // skip the remainder of this block/scope
// depth-first short circuit
if (!synlig_node_contains_assignment_to(child, var))
return false;
}
return true;
}
// returns whether an expression contains an unbased unsized literal; does not
// check the literal exists in a self-determined context
static bool synlig_contains_unbased_unsized(const Yosys::AST::AstNode *node)
{
if (node->type == Yosys::AST::AST_CONSTANT)
return node->is_unsized;
for (const Yosys::AST::AstNode *child : node->children)
if (synlig_contains_unbased_unsized(child))
return true;
return false;
}
// adds a wire to the current module with the given name that matches the
// dimensions of the given wire reference
void synlig_add_wire_for_ref(const RTLIL::Wire *ref, const std::string &str)
{
Yosys::AST::AstNode *left = Yosys::AST::AstNode::mkconst_int(ref->width - 1 + ref->start_offset, true);
Yosys::AST::AstNode *right = Yosys::AST::AstNode::mkconst_int(ref->start_offset, true);
if (ref->upto)
std::swap(left, right);
Yosys::AST::AstNode *range = new Yosys::AST::AstNode(Yosys::AST::AST_RANGE, left, right);
Yosys::AST::AstNode *wire = new Yosys::AST::AstNode(Yosys::AST::AST_WIRE, range);
wire->is_signed = ref->is_signed;
wire->is_logic = true;
wire->str = str;
current_ast_mod->children.push_back(wire);
current_scope[str] = wire;
}
enum class SynligIdentUsage {
NotReferenced, // target variable is neither read or written in the block
Assigned, // target variable is always assigned before use
SyncRequired, // target variable may be used before it has been assigned
};
// determines whether a local variable a block is always assigned before it is
// used, meaning the nosync attribute can automatically be added to that
// variable
static SynligIdentUsage synlig_always_asgn_before_use(const Yosys::AST::AstNode *node, const std::string &target)
{
// This variable has been referenced before it has necessarily been assigned
// a value in this procedure.
if (node->type == Yosys::AST::AST_IDENTIFIER && node->str == target)
return SynligIdentUsage::SyncRequired;
// For case statements (which are also used for if/else), we check each
// possible branch. If the variable is assigned in all branches, then it is
// assigned, and a sync isn't required. If it used before assignment in any
// branch, then a sync is required.
if (node->type == Yosys::AST::AST_CASE) {
bool all_defined = true;
bool any_used = false;
bool has_default = false;
for (const Yosys::AST::AstNode *child : node->children) {
if (child->type == Yosys::AST::AST_COND && child->children.at(0)->type == Yosys::AST::AST_DEFAULT)
has_default = true;
SynligIdentUsage nested = synlig_always_asgn_before_use(child, target);
if (nested != SynligIdentUsage::Assigned && child->type == Yosys::AST::AST_COND)
all_defined = false;
if (nested == SynligIdentUsage::SyncRequired)
any_used = true;
}
if (any_used)
return SynligIdentUsage::SyncRequired;
else if (all_defined && has_default)
return SynligIdentUsage::Assigned;
else
return SynligIdentUsage::NotReferenced;
}
// Check if this is an assignment to the target variable. For simplicity, we
// don't analyze sub-ranges of the variable.
if (node->type == Yosys::AST::AST_ASSIGN_EQ) {
const Yosys::AST::AstNode *ident = node->children.at(0);
if (ident->type == Yosys::AST::AST_IDENTIFIER && ident->str == target)
return SynligIdentUsage::Assigned;
}
for (const Yosys::AST::AstNode *child : node->children) {
SynligIdentUsage nested = synlig_always_asgn_before_use(child, target);
if (nested != SynligIdentUsage::NotReferenced)
return nested;
}
return SynligIdentUsage::NotReferenced;
}
static const std::string synlig_auto_nosync_prefix = "\\AutoNosync";
// mark a local variable in an always_comb block for automatic nosync
// consideration
static void synlig_mark_auto_nosync(Yosys::AST::AstNode *block, const Yosys::AST::AstNode *wire)
{
log_assert(block->type == Yosys::AST::AST_BLOCK);
log_assert(wire->type == Yosys::AST::AST_WIRE);
block->attributes[synlig_auto_nosync_prefix + wire->str] = Yosys::AST::AstNode::mkconst_int(1, false);
}
// block names can be prefixed with an explicit scope during elaboration
static bool synlig_is_autonamed_block(const std::string &str)
{
size_t last_dot = str.rfind('.');
// unprefixed names: autonamed if the first char is a dollar sign
if (last_dot == std::string::npos)
return str.at(0) == '$'; // e.g., `$fordecl_block$1`
// prefixed names: autonamed if the final chunk begins with a dollar sign
return str.rfind(".$") == last_dot; // e.g., `\foo.bar.$fordecl_block$1`
}
// check a procedural block for auto-nosync markings, remove them, and add
// nosync to local variables as necessary
static void synlig_check_auto_nosync(Yosys::AST::AstNode *node)
{
std::vector<RTLIL::IdString> attrs_to_drop;
for (const auto &elem : node->attributes) {
// skip attributes that don't begin with the prefix
if (elem.first.compare(0, synlig_auto_nosync_prefix.size(), synlig_auto_nosync_prefix.c_str()))
continue;
// delete and remove the attribute once we're done iterating
attrs_to_drop.push_back(elem.first);
// find the wire based on the attribute
std::string wire_name = elem.first.substr(synlig_auto_nosync_prefix.size());
auto it = current_scope.find(wire_name);
if (it == current_scope.end())
continue;
// analyze the usage of the local variable in this block
SynligIdentUsage ident_usage = synlig_always_asgn_before_use(node, wire_name);
if (ident_usage != SynligIdentUsage::Assigned)
continue;
// mark the wire with `nosync`
Yosys::AST::AstNode *wire = it->second;
log_assert(wire->type == Yosys::AST::AST_WIRE);
wire->attributes[ID::nosync] = node->mkconst_int(1, false);
}
// remove the attributes we've "consumed"
for (const RTLIL::IdString &str : attrs_to_drop) {
auto it = node->attributes.find(str);
delete it->second;
node->attributes.erase(it);
}
// check local variables in any nested blocks
for (Yosys::AST::AstNode *child : node->children)
synlig_check_auto_nosync(child);
}
static inline std::string synlig_encode_filename(const std::string &filename)
{
std::stringstream val;
if (!std::any_of(filename.begin(), filename.end(),
[](char c) { return static_cast<unsigned char>(c) < 33 || static_cast<unsigned char>(c) > 126; }))
return filename;
for (unsigned char const c : filename) {
if (c < 33 || c > 126)
val << stringf("$%02x", c);
else
val << c;
}
return val.str();
}
void synlig_replace_result_wire_name_in_function(AST::AstNode *current_node, const std::string &from, const std::string &to)
{
for (AST::AstNode *child : current_node->children)
synlig_replace_result_wire_name_in_function(child, from, to);
if (current_node->str == from && current_node->type != AST::AST_FCALL && current_node->type != AST::AST_TCALL)
current_node->str = to;
}
static std::string synlig_prefix_id(const std::string &prefix, const std::string &str)
{
log_assert(!prefix.empty() && (prefix.front() == '$' || prefix.front() == '\\'));
log_assert(!str.empty());
log_assert(prefix.back() == '.');
if (str.front() == '\\')
return prefix + str.substr(1);
if (str.front() == '$')
return prefix + str;
return str;
}
// annotate the names of all wires and other named objects in a named generate
// or procedural block; nested genblocks are themselves annotated such that the
// prefix is carried forward, but resolution of their children is deferred;
// blocks have additionally resolved variables to current scope when possible
void synlig_expand_genblock(AST::AstNode *current_node, const std::string prefix, bool only_resolve_scope)
{
if (current_node->type == AST::AST_IDENTIFIER || current_node->type == AST::AST_FCALL || current_node->type == AST::AST_TCALL ||
current_node->type == AST::AST_WIRETYPE || current_node->type == AST::AST_PREFIX) {
log_assert(!current_node->str.empty());
// search starting in the innermost scope and then stepping outward
for (size_t ppos = prefix.size() - 1; ppos; --ppos) {
if (prefix.at(ppos) != '.')
continue;
std::string new_prefix = prefix.substr(0, ppos + 1);
auto attempt_resolve = [&new_prefix](const std::string &ident) -> std::string {
std::string new_name = synlig_prefix_id(new_prefix, ident);
if (AST_INTERNAL::current_scope.count(new_name))
return new_name;
return {};
};
// attempt to resolve the full identifier
std::string resolved = attempt_resolve(current_node->str);
if (!resolved.empty()) {
current_node->str = resolved;
break;
}
// attempt to resolve hierarchical prefixes within the identifier,
// as the prefix could refer to a local scope which exists but
// hasn't yet been elaborated
for (size_t spos = current_node->str.size() - 1; spos; --spos) {
if (current_node->str.at(spos) != '.')
continue;
resolved = attempt_resolve(current_node->str.substr(0, spos));
if (!resolved.empty()) {
current_node->str = resolved + current_node->str.substr(spos);
ppos = 1; // break outer loop
break;
}
}
}
}
auto prefix_node = [&prefix](AST::AstNode *child) {
if (child->str.empty())
return;
std::string new_name = synlig_prefix_id(prefix, child->str);
if (child->type == AST::AST_FUNCTION)
synlig_replace_result_wire_name_in_function(child, child->str, new_name);
else
child->str = new_name;
AST_INTERNAL::current_scope[new_name] = child;
};
for (size_t i = 0; i < current_node->children.size(); i++) {
AST::AstNode *child = current_node->children[i];
switch (child->type) {
case AST::AST_WIRE:
case AST::AST_MEMORY:
case AST::AST_STRUCT:
case AST::AST_UNION:
case AST::AST_PARAMETER:
case AST::AST_LOCALPARAM:
case AST::AST_FUNCTION:
case AST::AST_TASK:
case AST::AST_CELL:
case AST::AST_TYPEDEF:
case AST::AST_ENUM_ITEM:
case AST::AST_GENVAR:
if (!only_resolve_scope)
prefix_node(child);
break;
case AST::AST_BLOCK:
case AST::AST_GENBLOCK:
if (!child->str.empty() && !only_resolve_scope)
prefix_node(child);
break;
case AST::AST_ENUM:
AST_INTERNAL::current_scope[child->str] = child;
for (auto enode : child->children) {
log_assert(enode->type == AST::AST_ENUM_ITEM);
if (!only_resolve_scope)
prefix_node(enode);
}
break;
default:
break;
}
}
for (size_t i = 0; i < current_node->children.size(); i++) {
AST::AstNode *child = current_node->children[i];
// AST_PREFIX member names should not be prefixed; we recurse into them
// as normal to ensure indices and ranges are properly resolved, and
// then restore the previous string
if (current_node->type == AST::AST_PREFIX && i == 1) {
std::string backup_scope_name = child->str;
synlig_expand_genblock(child, prefix, only_resolve_scope);
child->str = backup_scope_name;
continue;
}
// functions/tasks may reference wires, constants, etc. in this scope
if (child->type == AST::AST_FUNCTION || child->type == AST::AST_TASK)
continue;
// named blocks pick up the current prefix and will expanded later
// blocks additionally resolve variables that are already in scope
if (child->type == AST::AST_BLOCK) {
synlig_expand_genblock(child, prefix, true);
continue;
}
if ((child->type == AST::AST_GENBLOCK) && !child->str.empty())
continue;
// enum was already prefixed
if (child->type == AST::AST_ENUM)
continue;
synlig_expand_genblock(child, prefix, only_resolve_scope);
}
}
// convert the AST into a simpler AST that has all parameters substituted by their
// values, unrolled for-loops, expanded generate blocks, etc. when this function
// is done with an AST it can be converted into RTLIL using genRTLIL().
//
// this function also does all name resolving and sets the id2ast member of all
// nodes that link to a different node using names and lexical scoping.
bool synlig_simplify(Yosys::AST::AstNode *ast_node, bool const_fold, bool at_zero, bool in_lvalue, int stage, int width_hint, bool sign_hint,
bool in_param)
{
static int recursion_counter = 0;
static bool deep_recursion_warning = false;
if (recursion_counter++ == 1000 && deep_recursion_warning) {
log_warning(
"Deep recursion in AST simplifier.\nDoes this design contain overly long or deeply nested expressions, or excessive recursion?\n");
deep_recursion_warning = false;
}
static bool unevaluated_tern_branch = false;
Yosys::AST::AstNode *newNode = NULL;
bool did_something = false;
#if 0
log("-------------\n");
log("AST simplify[%d] depth %d at %s:%d on %s %p:\n", stage, recursion_counter, filename.c_str(), location.first_line, type2str(type).c_str(), this);
log("const_fold=%d, at_zero=%d, in_lvalue=%d, stage=%d, width_hint=%d, sign_hint=%d, in_param=%d\n",
int(const_fold), int(at_zero), int(in_lvalue), int(stage), int(width_hint), int(sign_hint), int(in_param));
// dumpAst(NULL, "> ");
#endif
if (stage == 0) {
log_assert(ast_node->type == Yosys::AST::AST_MODULE || ast_node->type == Yosys::AST::AST_INTERFACE);
deep_recursion_warning = true;
while (synlig_simplify(ast_node, const_fold, at_zero, in_lvalue, 1, width_hint, sign_hint, in_param)) {
}
if (!flag_nomem2reg && !ast_node->get_bool_attribute(ID::nomem2reg)) {
dict<Yosys::AST::AstNode *, pool<std::string>> mem2reg_places;
dict<Yosys::AST::AstNode *, uint32_t> mem2reg_candidates, dummy_proc_flags;
uint32_t flags = flag_mem2reg ? Yosys::AST::AstNode::MEM2REG_FL_ALL : 0;
ast_node->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, dummy_proc_flags, flags); // not sure if correct MAND
pool<Yosys::AST::AstNode *> mem2reg_set;
for (auto &it : mem2reg_candidates) {
Yosys::AST::AstNode *mem = it.first;
uint32_t memflags = it.second;
bool this_nomeminit = flag_nomeminit;
log_assert((memflags & ~0x00ffff00) == 0);
if (mem->get_bool_attribute(ID::nomem2reg))
continue;
if (mem->get_bool_attribute(ID::nomeminit) || ast_node->get_bool_attribute(ID::nomeminit))
this_nomeminit = true;
if (memflags & Yosys::AST::AstNode::MEM2REG_FL_FORCED)
goto silent_activate;
if (memflags & Yosys::AST::AstNode::MEM2REG_FL_EQ2)
goto verbose_activate;
if (memflags & Yosys::AST::AstNode::MEM2REG_FL_SET_ASYNC)
goto verbose_activate;
if ((memflags & Yosys::AST::AstNode::MEM2REG_FL_SET_INIT) && (memflags & Yosys::AST::AstNode::MEM2REG_FL_SET_ELSE) && this_nomeminit)
goto verbose_activate;
if (memflags & Yosys::AST::AstNode::MEM2REG_FL_CMPLX_LHS)
goto verbose_activate;
if ((memflags & Yosys::AST::AstNode::MEM2REG_FL_CONST_LHS) && !(memflags & Yosys::AST::AstNode::MEM2REG_FL_VAR_LHS))
goto verbose_activate;
// log("Note: Not replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
continue;
verbose_activate:
if (mem2reg_set.count(mem) == 0) {
std::string message = stringf("Replacing memory %s with list of registers.", mem->str.c_str());
bool first_element = true;
for (auto &place : mem2reg_places[it.first]) {
message += stringf("%s%s", first_element ? " See " : ", ", place.c_str());
first_element = false;
}
log_warning("%s\n", message.c_str());
}
silent_activate:
// log("Note: Replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
mem2reg_set.insert(mem);
}
for (auto node : mem2reg_set) {
int mem_width, mem_size, addr_bits;
node->meminfo(mem_width, mem_size, addr_bits);
int data_range_left = node->children[0]->range_left;
int data_range_right = node->children[0]->range_right;
if (node->children[0]->range_swapped)
std::swap(data_range_left, data_range_right);
for (int i = 0; i < mem_size; i++) {
Yosys::AST::AstNode *reg = new Yosys::AST::AstNode(
Yosys::AST::AST_WIRE, new Yosys::AST::AstNode(Yosys::AST::AST_RANGE, node->mkconst_int(data_range_left, true),
node->mkconst_int(data_range_right, true)));
reg->str = stringf("%s[%d]", node->str.c_str(), i);
reg->is_reg = true;
reg->is_signed = node->is_signed;
for (auto &it : node->attributes)
if (it.first != ID::mem2reg)
reg->attributes.emplace(it.first, it.second->clone());
reg->filename = node->filename;
reg->location = node->location;
ast_node->children.push_back(reg);
while (synlig_simplify(reg, true, false, false, 1, -1, false, false)) {
} // <- not sure about reg being the first arg here...
}
}
Yosys::AST::AstNode *async_block = NULL;
while (ast_node->mem2reg_as_needed_pass2(mem2reg_set, ast_node, NULL, async_block)) {
}
vector<Yosys::AST::AstNode *> delnodes;
ast_node->mem2reg_remove(mem2reg_set, delnodes);
for (auto node : delnodes)
delete node;
}
while (synlig_simplify(ast_node, const_fold, at_zero, in_lvalue, 2, width_hint, sign_hint, in_param)) {
}
recursion_counter--;
return false;
}
Yosys::AST::current_filename = ast_node->filename;
// we do not look inside a task or function
// (but as soon as a task or function is instantiated we process the generated AST as usual)
if (ast_node->type == Yosys::AST::AST_FUNCTION || ast_node->type == Yosys::AST::AST_TASK) {
recursion_counter--;
return false;
}
// deactivate all calls to non-synthesis system tasks
// note that $display, $finish, and $stop are used for synthesis-time DRC so they're not in this list
if ((ast_node->type == Yosys::AST::AST_FCALL || ast_node->type == Yosys::AST::AST_TCALL) &&
(ast_node->str == "$strobe" || ast_node->str == "$monitor" || ast_node->str == "$time" || ast_node->str == "$dumpfile" ||
ast_node->str == "$dumpvars" || ast_node->str == "$dumpon" || ast_node->str == "$dumpoff" || ast_node->str == "$dumpall")) {
log_file_warning(ast_node->filename, ast_node->location.first_line, "Ignoring call to system %s %s.\n",
ast_node->type == Yosys::AST::AST_FCALL ? "function" : "task", ast_node->str.c_str());
ast_node->delete_children();
ast_node->str = std::string();
}
if ((ast_node->type == Yosys::AST::AST_TCALL) && (ast_node->str == "$display" || ast_node->str == "$write") &&
(!current_always || current_always->type != Yosys::AST::AST_INITIAL)) {
log_file_warning(ast_node->filename, ast_node->location.first_line, "System task `%s' outside initial block is unsupported.\n",
ast_node->str.c_str());
ast_node->delete_children();
ast_node->str = std::string();
}
// print messages if this a call to $display() or $write()
// This code implements only a small subset of Verilog-2005 $display() format specifiers,
// but should be good enough for most uses
if ((ast_node->type == Yosys::AST::AST_TCALL) && ((ast_node->str == "$display") || (ast_node->str == "$write"))) {
if (!current_always) {
log_file_warning(ast_node->filename, ast_node->location.first_line, "System task `%s' outside initial or always block is unsupported.\n",
ast_node->str.c_str());
} else if (current_always->type == Yosys::AST::AST_INITIAL) {
int default_base = 10;
if (ast_node->str.back() == 'b')
default_base = 2;
else if (ast_node->str.back() == 'o')
default_base = 8;
else if (ast_node->str.back() == 'h')
default_base = 16;
// when $display()/$write() functions are used in an initial block, print them during synthesis
Fmt fmt = ast_node->processFormat(stage, /*sformat_like=*/false, default_base);
if (ast_node->str.substr(0, 8) == "$display")
fmt.append_literal("\n");
log("%s", fmt.render().c_str());
} else {
// when $display()/$write() functions are used in an always block, simplify the expressions and
// convert them to a special cell later in genrtlil
for (auto node : ast_node->children)
while (synlig_simplify(node, true, false, false, stage, -1, false, false)) {
}
return false;
}
ast_node->delete_children();
ast_node->str = std::string();
}
// activate const folding if this is anything that must be evaluated statically (ranges, parameters, attributes, etc.)
if (ast_node->type == Yosys::AST::AST_WIRE || ast_node->type == Yosys::AST::AST_PARAMETER || ast_node->type == Yosys::AST::AST_LOCALPARAM ||
ast_node->type == Yosys::AST::AST_ENUM_ITEM || ast_node->type == Yosys::AST::AST_DEFPARAM || ast_node->type == Yosys::AST::AST_PARASET ||
ast_node->type == Yosys::AST::AST_RANGE || ast_node->type == Yosys::AST::AST_PREFIX || ast_node->type == Yosys::AST::AST_TYPEDEF)
const_fold = true;
if (ast_node->type == Yosys::AST::AST_IDENTIFIER && current_scope.count(ast_node->str) > 0 &&
(current_scope[ast_node->str]->type == Yosys::AST::AST_PARAMETER || current_scope[ast_node->str]->type == Yosys::AST::AST_LOCALPARAM ||
current_scope[ast_node->str]->type == Yosys::AST::AST_ENUM_ITEM))
const_fold = true;
// in certain cases a function must be evaluated constant. this is what in_param controls.
if (ast_node->type == Yosys::AST::AST_PARAMETER || ast_node->type == Yosys::AST::AST_LOCALPARAM || ast_node->type == Yosys::AST::AST_DEFPARAM ||
ast_node->type == Yosys::AST::AST_PARASET || ast_node->type == Yosys::AST::AST_PREFIX)
in_param = true;
std::map<std::string, Yosys::AST::AstNode *> backup_scope;
// create name resolution entries for all objects with names
// also merge multiple declarations for the same wire (e.g. "output foobar; reg foobar;")
if (ast_node->type == Yosys::AST::AST_MODULE || ast_node->type == Yosys::AST::AST_INTERFACE) {
current_scope.clear();
std::set<std::string> existing;
int counter = 0;
ast_node->label_genblks(existing, counter);
std::map<std::string, Yosys::AST::AstNode *> this_wire_scope;
for (size_t i = 0; i < ast_node->children.size(); i++) {
Yosys::AST::AstNode *node = ast_node->children[i];
if (node->type == Yosys::AST::AST_WIRE) {
if (node->children.size() == 1 && node->children[0]->type == Yosys::AST::AST_RANGE) {
for (auto c : node->children[0]->children) {
if (!c->is_simple_const_expr()) {
if (ast_node->attributes.count(ID::dynports))
delete ast_node->attributes.at(ID::dynports);
node->attributes[ID::dynports] = node->mkconst_int(1, true);
}
}
}
if (this_wire_scope.count(node->str) > 0) {
Yosys::AST::AstNode *first_node = this_wire_scope[node->str];
if (first_node->is_input && node->is_reg)
goto wires_are_incompatible;
if (!node->is_input && !node->is_output && node->is_reg && node->children.size() == 0)
goto wires_are_compatible;
if (first_node->children.size() == 0 && node->children.size() == 1 && node->children[0]->type == Yosys::AST::AST_RANGE) {
Yosys::AST::AstNode *r = node->children[0];
if (r->range_valid && r->range_left == 0 && r->range_right == 0) {
delete r;
node->children.pop_back();
}
}
if (first_node->children.size() != node->children.size())
goto wires_are_incompatible;
for (size_t j = 0; j < node->children.size(); j++) {
Yosys::AST::AstNode *n1 = first_node->children[j], *n2 = node->children[j];
if (n1->type == Yosys::AST::AST_RANGE && n2->type == Yosys::AST::AST_RANGE && n1->range_valid && n2->range_valid) {
if (n1->range_left != n2->range_left)
goto wires_are_incompatible;
if (n1->range_right != n2->range_right)
goto wires_are_incompatible;
} else if (*n1 != *n2)
goto wires_are_incompatible;
}
if (first_node->range_left != node->range_left)
goto wires_are_incompatible;
if (first_node->range_right != node->range_right)
goto wires_are_incompatible;
if (first_node->port_id == 0 && (node->is_input || node->is_output))
goto wires_are_incompatible;
wires_are_compatible:
if (node->is_input)
first_node->is_input = true;
if (node->is_output)
first_node->is_output = true;
if (node->is_reg)
first_node->is_reg = true;
if (node->is_logic)
first_node->is_logic = true;
if (node->is_signed)
first_node->is_signed = true;
for (auto &it : node->attributes) {
if (first_node->attributes.count(it.first) > 0)
delete first_node->attributes[it.first];
first_node->attributes[it.first] = it.second->clone();
}
ast_node->children.erase(ast_node->children.begin() + (i--));
did_something = true;
delete node;
continue;
wires_are_incompatible:
if (stage > 1)
log_file_error(ast_node->filename, ast_node->location.first_line, "Incompatible re-declaration of wire %s.\n",
node->str.c_str());
continue;
}
this_wire_scope[node->str] = node;
}
// these nodes appear at the top level in a module and can define names
if (node->type == Yosys::AST::AST_PARAMETER || node->type == Yosys::AST::AST_LOCALPARAM || node->type == Yosys::AST::AST_WIRE ||
node->type == Yosys::AST::AST_AUTOWIRE || node->type == Yosys::AST::AST_GENVAR || node->type == Yosys::AST::AST_MEMORY ||
node->type == Yosys::AST::AST_FUNCTION || node->type == Yosys::AST::AST_TASK || node->type == Yosys::AST::AST_DPI_FUNCTION ||
node->type == Yosys::AST::AST_CELL || node->type == Yosys::AST::AST_TYPEDEF) {
backup_scope[node->str] = current_scope[node->str];
current_scope[node->str] = node;
}
if (node->type == Yosys::AST::AST_ENUM) {
current_scope[node->str] = node;
for (auto enode : node->children) {
log_assert(enode->type == Yosys::AST::AST_ENUM_ITEM);
if (current_scope.count(enode->str) == 0)
current_scope[enode->str] = enode;
else
log_file_error(ast_node->filename, ast_node->location.first_line, "enum item %s already exists\n", enode->str.c_str());
}
}
}
for (size_t i = 0; i < ast_node->children.size(); i++) {
Yosys::AST::AstNode *node = ast_node->children[i];
if (node->type == Yosys::AST::AST_PARAMETER || node->type == Yosys::AST::AST_LOCALPARAM || node->type == Yosys::AST::AST_WIRE ||
node->type == Yosys::AST::AST_AUTOWIRE || node->type == Yosys::AST::AST_MEMORY || node->type == Yosys::AST::AST_TYPEDEF)
while (synlig_simplify(node, true, false, false, 1, -1, false,
node->type == Yosys::AST::AST_PARAMETER || node->type == Yosys::AST::AST_LOCALPARAM))
did_something = true;
if (node->type == Yosys::AST::AST_ENUM) {
for (auto enode : node->children) {
log_assert(enode->type == Yosys::AST::AST_ENUM_ITEM);
while (synlig_simplify(node, true, false, false, 1, -1, false, in_param))
did_something = true;
}
}
}