forked from YosysHQ/nextpnr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpack.cc
2728 lines (2455 loc) · 118 KB
/
pack.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
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2020 gatecat <[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.
*
*/
#include "design_utils.h"
#include "log.h"
#include "nextpnr.h"
#include "util.h"
#include <boost/algorithm/string.hpp>
#include <queue>
#include <set>
NEXTPNR_NAMESPACE_BEGIN
namespace {
bool is_enabled(CellInfo *ci, IdString prop) { return str_or_default(ci->params, prop, "") == "ENABLED"; }
} // namespace
Property Arch::parse_lattice_param_from_cell(const CellInfo *ci, IdString prop, int width, int64_t defval) const
{
auto fnd = ci->params.find(prop);
if (fnd == ci->params.end())
return Property(defval, width);
return this->parse_lattice_param(fnd->second, prop, width, nameOf(ci));
}
// Parse a possibly-Lattice-style (C literal in Verilog string) style parameter
Property Arch::parse_lattice_param(const Property &val, IdString prop, int width, const char *ci) const
{
if (val.is_string && !prop.in(id_CSDECODE_A, id_CSDECODE_B, id_CSDECODE_R, id_CSDECODE_W)) {
const std::string &s = val.str;
Property temp;
if (boost::starts_with(s, "0b")) {
for (int i = int(s.length()) - 1; i >= 2; i--) {
char c = s.at(i);
if (c != '0' && c != '1' && c != 'x')
log_error("Invalid binary digit '%c' in property %s.%s\n", c, ci, nameOf(prop));
temp.str.push_back(c);
}
} else if (boost::starts_with(s, "0x")) {
for (int i = int(s.length()) - 1; i >= 2; i--) {
char c = s.at(i);
int nibble;
if (c >= '0' && c <= '9')
nibble = (c - '0');
else if (c >= 'a' && c <= 'f')
nibble = (c - 'a') + 10;
else if (c >= 'A' && c <= 'F')
nibble = (c - 'A') + 10;
else
log_error("Invalid hex digit '%c' in property %s.%s\n", c, ci, nameOf(prop));
for (int j = 0; j < 4; j++)
temp.str.push_back(((nibble >> j) & 0x1) ? Property::S1 : Property::S0);
}
} else {
int64_t ival = 0;
try {
if (boost::starts_with(s, "0d"))
ival = std::stoll(s.substr(2));
else
ival = std::stoll(s);
} catch (std::runtime_error &e) {
log_error("Invalid decimal value for property %s.%s", ci, nameOf(prop));
}
temp = Property(ival);
}
if (int(temp.size()) > width) {
for (auto b : temp.str.substr(width)) {
if (b == Property::S1)
log_error("Found value for property %s.%s with width greater than %d\n", ci, nameOf(prop), width);
}
}
temp.update_intval();
return temp.extract(0, width);
} else {
if (int(val.str.size()) > width) {
for (auto b : val.str.substr(width)) {
if (b == Property::S1)
log_error("Found bitvector value for property %s.%s with width greater than %d - perhaps a string "
"was "
"converted to bits?\n",
ci, nameOf(prop), width);
}
}
return val.extract(0, width);
}
}
struct NexusPacker
{
Context *ctx;
// Generic cell transformation
// Given cell name map and port map
// If port name is not found in port map; it will be copied as-is but stripping []
struct XFormRule
{
IdString new_type;
dict<IdString, IdString> port_xform;
dict<IdString, std::vector<IdString>> port_multixform;
dict<IdString, IdString> param_xform;
std::vector<std::pair<IdString, std::string>> set_attrs;
std::vector<std::pair<IdString, Property>> set_params;
std::vector<std::pair<IdString, Property>> default_params;
std::vector<std::tuple<IdString, IdString, int, int64_t>> parse_params;
};
void xform_cell(const dict<IdString, XFormRule> &rules, CellInfo *ci)
{
auto &rule = rules.at(ci->type);
ci->type = rule.new_type;
std::vector<IdString> orig_port_names;
for (auto &port : ci->ports)
orig_port_names.push_back(port.first);
for (auto pname : orig_port_names) {
if (rule.port_multixform.count(pname)) {
auto old_port = ci->ports.at(pname);
ci->disconnectPort(pname);
ci->ports.erase(pname);
for (auto new_name : rule.port_multixform.at(pname)) {
ci->ports[new_name].name = new_name;
ci->ports[new_name].type = old_port.type;
ci->connectPort(new_name, old_port.net);
}
} else {
IdString new_name;
if (rule.port_xform.count(pname)) {
new_name = rule.port_xform.at(pname);
} else {
std::string stripped_name;
for (auto c : pname.str(ctx))
if (c != '[' && c != ']')
stripped_name += c;
new_name = ctx->id(stripped_name);
}
if (new_name != pname) {
ci->renamePort(pname, new_name);
}
}
}
std::vector<IdString> xform_params;
for (auto ¶m : ci->params)
if (rule.param_xform.count(param.first))
xform_params.push_back(param.first);
for (auto param : xform_params)
ci->params[rule.param_xform.at(param)] = ci->params[param];
for (auto &attr : rule.set_attrs)
ci->attrs[attr.first] = attr.second;
for (auto ¶m : rule.default_params)
if (!ci->params.count(param.first))
ci->params[param.first] = param.second;
{
IdString old_param, new_param;
int width;
int64_t def;
for (const auto &p : rule.parse_params) {
std::tie(old_param, new_param, width, def) = p;
ci->params[new_param] = ctx->parse_lattice_param_from_cell(ci, old_param, width, def);
}
}
for (auto ¶m : rule.set_params)
ci->params[param.first] = param.second;
}
void generic_xform(const dict<IdString, XFormRule> &rules, bool print_summary = false)
{
std::map<std::string, int> cell_count;
std::map<std::string, int> new_types;
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
if (rules.count(ci->type)) {
cell_count[ci->type.str(ctx)]++;
xform_cell(rules, ci);
new_types[ci->type.str(ctx)]++;
}
}
if (print_summary) {
for (auto &nt : new_types) {
log_info(" Created %d %s cells from:\n", nt.second, nt.first.c_str());
for (auto &cc : cell_count) {
if (rules.at(ctx->id(cc.first)).new_type != ctx->id(nt.first))
continue;
log_info(" %6dx %s\n", cc.second, cc.first.c_str());
}
}
}
}
void pack_luts()
{
log_info("Packing LUTs...\n");
dict<IdString, XFormRule> lut_rules;
lut_rules[id_LUT4].new_type = id_OXIDE_COMB;
lut_rules[id_LUT4].port_xform[id_Z] = id_F;
lut_rules[id_LUT4].parse_params.emplace_back(id_INIT, id_INIT, 16, 0);
lut_rules[id_INV].new_type = id_OXIDE_COMB;
lut_rules[id_INV].port_xform[id_Z] = id_F;
lut_rules[id_INV].port_xform[id_A] = id_A;
lut_rules[id_INV].set_params.emplace_back(id_INIT, 0x5555);
lut_rules[id_VHI].new_type = id_OXIDE_COMB;
lut_rules[id_VHI].port_xform[id_Z] = id_F;
lut_rules[id_VHI].set_params.emplace_back(id_INIT, 0xFFFF);
lut_rules[id_VLO].new_type = id_OXIDE_COMB;
lut_rules[id_VLO].port_xform[id_Z] = id_F;
lut_rules[id_VLO].set_params.emplace_back(id_INIT, 0x0000);
generic_xform(lut_rules);
}
void pack_ffs()
{
log_info("Packing FFs...\n");
dict<IdString, XFormRule> ff_rules;
for (auto type : {id_FD1P3BX, id_FD1P3DX, id_FD1P3IX, id_FD1P3JX}) {
ff_rules[type].new_type = id_OXIDE_FF;
ff_rules[type].port_xform[id_CK] = id_CLK;
ff_rules[type].port_xform[id_D] = id_M; // will be rerouted to DI later if applicable
ff_rules[type].port_xform[id_SP] = id_CE;
ff_rules[type].port_xform[id_Q] = id_Q;
ff_rules[type].default_params.emplace_back(id_CLKMUX, std::string("CLK"));
ff_rules[type].default_params.emplace_back(id_CEMUX, std::string("CE"));
ff_rules[type].default_params.emplace_back(id_LSRMUX, std::string("LSR"));
ff_rules[type].set_params.emplace_back(id_LSRMODE, std::string("LSR"));
}
// Async preload
ff_rules[id_FD1P3BX].set_params.emplace_back(id_SRMODE, std::string("ASYNC"));
ff_rules[id_FD1P3BX].set_params.emplace_back(id_REGSET, std::string("SET"));
ff_rules[id_FD1P3BX].port_xform[id_PD] = id_LSR;
// Async clear
ff_rules[id_FD1P3DX].set_params.emplace_back(id_SRMODE, std::string("ASYNC"));
ff_rules[id_FD1P3DX].set_params.emplace_back(id_REGSET, std::string("RESET"));
ff_rules[id_FD1P3DX].port_xform[id_CD] = id_LSR;
// Sync preload
ff_rules[id_FD1P3JX].set_params.emplace_back(id_SRMODE, std::string("LSR_OVER_CE"));
ff_rules[id_FD1P3JX].set_params.emplace_back(id_REGSET, std::string("SET"));
ff_rules[id_FD1P3JX].port_xform[id_PD] = id_LSR;
// Sync clear
ff_rules[id_FD1P3IX].set_params.emplace_back(id_SRMODE, std::string("LSR_OVER_CE"));
ff_rules[id_FD1P3IX].set_params.emplace_back(id_REGSET, std::string("RESET"));
ff_rules[id_FD1P3IX].port_xform[id_CD] = id_LSR;
generic_xform(ff_rules, true);
}
dict<IdString, BelId> reference_bels;
void autocreate_ports(CellInfo *cell)
{
// Automatically create ports for all inputs, and maybe outputs, of a cell; even if they were left off the
// instantiation so we can tie them to constants as appropriate This also checks for any cells that don't have
// corresponding bels
if (!reference_bels.count(cell->type)) {
// We need to look up a corresponding bel to get the list of input ports
BelId ref_bel;
for (BelId bel : ctx->getBels()) {
if (ctx->getBelType(bel) != cell->type)
continue;
ref_bel = bel;
break;
}
if (ref_bel == BelId())
log_error("Cell type '%s' instantiated as '%s' is not supported by this device.\n",
ctx->nameOf(cell->type), ctx->nameOf(cell));
reference_bels[cell->type] = ref_bel;
}
BelId bel = reference_bels.at(cell->type);
for (IdString pin : ctx->getBelPins(bel)) {
PortType dir = ctx->getBelPinType(bel, pin);
if (dir != PORT_IN)
continue;
if (cell->ports.count(pin))
continue;
if (cell->type == id_OXIDE_COMB && pin == id_SEL)
continue; // doesn't always exist and not needed
cell->ports[pin].name = pin;
cell->ports[pin].type = dir;
}
}
NetInfo *get_const_net(IdString type)
{
// Gets a constant net, given the driver type (VHI or VLO)
// If one doesn't exist already; then create it
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
if (ci->type != type)
continue;
NetInfo *z = ci->getPort(id_Z);
if (z == nullptr)
continue;
return z;
}
NetInfo *new_net = ctx->createNet(ctx->idf("$CONST_%s_NET_", type.c_str(ctx)));
CellInfo *new_cell = ctx->createCell(ctx->idf("$CONST_%s_DRV_", type.c_str(ctx)), type);
new_cell->addOutput(id_Z);
new_cell->connectPort(id_Z, new_net);
if (type == id_VCC_DRV)
new_net->constant_value = id_VCC_DRV;
return new_net;
}
CellPinMux get_pin_needed_muxval(CellInfo *cell, IdString port)
{
NetInfo *net = cell->getPort(port);
if (net == nullptr || net->driver.cell == nullptr) {
// Pin is disconnected
// If a mux value exists already, honour it
CellPinMux exist_mux = ctx->get_cell_pinmux(cell, port);
if (exist_mux != PINMUX_SIG)
return exist_mux;
// Otherwise, look up the default value and use that
CellPinStyle pin_style = ctx->get_cell_pin_style(cell, port);
if ((pin_style & PINDEF_MASK) == PINDEF_0)
return PINMUX_0;
else if ((pin_style & PINDEF_MASK) == PINDEF_1)
return PINMUX_1;
else
return PINMUX_SIG;
}
// Look to see if the driver is an inverter or constant
IdString drv_type = net->driver.cell->type;
if (drv_type == id_INV)
return PINMUX_INV;
else if (drv_type == id_VLO)
return PINMUX_0;
else if (drv_type == id_VHI)
return PINMUX_1;
else
return PINMUX_SIG;
}
void uninvert_port(CellInfo *cell, IdString port)
{
// Rewire a port so it is driven by the input to an inverter
NetInfo *net = cell->getPort(port);
NPNR_ASSERT(net != nullptr && net->driver.cell != nullptr && net->driver.cell->type == id_INV);
CellInfo *inv = net->driver.cell;
cell->disconnectPort(port);
NetInfo *inv_a = inv->getPort(id_A);
if (inv_a != nullptr) {
cell->connectPort(port, inv_a);
}
}
void trim_design()
{
// Remove unused inverters and high/low drivers
std::vector<IdString> trim_cells;
std::vector<IdString> trim_nets;
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
if (ci->type != id_INV && ci->type != id_VLO && ci->type != id_VHI && ci->type != id_VCC_DRV)
continue;
NetInfo *z = ci->getPort(id_Z);
if (z == nullptr) {
trim_cells.push_back(ci->name);
continue;
}
if (!z->users.empty())
continue;
ci->disconnectPort(id_A);
trim_cells.push_back(ci->name);
trim_nets.push_back(z->name);
}
for (IdString rem_net : trim_nets)
ctx->nets.erase(rem_net);
for (IdString rem_cell : trim_cells)
ctx->cells.erase(rem_cell);
}
std::string remove_brackets(const std::string &name)
{
std::string new_name;
new_name.reserve(name.size());
for (char c : name)
if (c != '[' && c != ']')
new_name.push_back(c);
return new_name;
}
void prim_to_core(CellInfo *cell, IdString new_type = {})
{
// Convert a primitive to a '_CORE' variant
if (new_type == IdString())
new_type = ctx->id(cell->type.str(ctx) + "_CORE");
cell->type = new_type;
std::set<IdString> port_names;
for (auto port : cell->ports)
port_names.insert(port.first);
for (IdString port : port_names) {
IdString new_name = ctx->id(remove_brackets(port.str(ctx)));
if (new_name != port)
cell->renamePort(port, new_name);
}
}
NetInfo *gnd_net = nullptr, *vcc_net = nullptr, *dedi_vcc_net = nullptr;
void process_inv_constants(CellInfo *cell)
{
// Automatically create any extra inputs needed; so we can set them accordingly
autocreate_ports(cell);
for (auto &port : cell->ports) {
// Iterate over all inputs
if (port.second.type != PORT_IN)
continue;
IdString port_name = port.first;
CellPinMux req_mux = get_pin_needed_muxval(cell, port_name);
if (req_mux == PINMUX_SIG) {
// No special setting required, ignore
continue;
}
CellPinStyle pin_style = ctx->get_cell_pin_style(cell, port_name);
if (req_mux == PINMUX_INV) {
// Pin is inverted. If there is a hard inverter; then use it
if (pin_style & PINOPT_INV) {
uninvert_port(cell, port_name);
ctx->set_cell_pinmux(cell, port_name, PINMUX_INV);
}
} else if (req_mux == PINMUX_0 || req_mux == PINMUX_1) {
// Pin is tied to a constant
// If there is a hard constant option; use it
if ((pin_style & int(req_mux)) == req_mux) {
if ((cell->type == id_OXIDE_COMB) && (req_mux == PINMUX_1)) {
// We need to add a connection to the dedicated Vcc resource that can feed these cell ports
cell->disconnectPort(port_name);
cell->connectPort(port_name, dedi_vcc_net);
continue;
}
cell->disconnectPort(port_name);
ctx->set_cell_pinmux(cell, port_name, req_mux);
} else if (port.second.net == nullptr) {
// If the port is disconnected; and there is no hard constant
// then we need to connect it to the relevant soft-constant net
cell->connectPort(port_name, (req_mux == PINMUX_1) ? vcc_net : gnd_net);
}
}
}
}
void prepare_io()
{
// Find the actual IO buffer corresponding to a port; and copy attributes across to it
// Note that this relies on Yosys to do IO buffer inference, to match vendor tooling behaviour
// In all cases the nextpnr-inserted IO buffers are removed as redundant.
for (auto &port : ctx->ports) {
if (!ctx->cells.count(port.first))
log_error("Port '%s' doesn't seem to have a corresponding top level IO\n", ctx->nameOf(port.first));
CellInfo *ci = ctx->cells.at(port.first).get();
PortRef top_port;
top_port.cell = nullptr;
bool is_npnr_iob = false;
if (ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_iobuf")) {
// Might have an input buffer (IB etc) connected to it
is_npnr_iob = true;
NetInfo *o = ci->getPort(id_O);
if (o == nullptr)
;
else if (o->users.entries() > 1)
log_error("Top level pin '%s' has multiple input buffers\n", ctx->nameOf(port.first));
else if (o->users.entries() == 1)
top_port = *o->users.begin();
}
if (ci->type == ctx->id("$nextpnr_obuf") || ci->type == ctx->id("$nextpnr_iobuf")) {
// Might have an output buffer (OB etc) connected to it
is_npnr_iob = true;
NetInfo *i = ci->getPort(id_I);
if (i != nullptr && i->driver.cell != nullptr) {
if (top_port.cell != nullptr)
log_error("Top level pin '%s' has multiple input/output buffers\n", ctx->nameOf(port.first));
top_port = i->driver;
}
// Edge case of a bidirectional buffer driving an output pin
if (i->users.entries() > 2) {
log_error("Top level pin '%s' has illegal buffer configuration\n", ctx->nameOf(port.first));
} else if (i->users.entries() == 2) {
if (top_port.cell != nullptr)
log_error("Top level pin '%s' has illegal buffer configuration\n", ctx->nameOf(port.first));
for (auto &usr : i->users) {
if (usr.cell->type == ctx->id("$nextpnr_obuf") || usr.cell->type == ctx->id("$nextpnr_iobuf"))
continue;
top_port = usr;
break;
}
}
}
if (!is_npnr_iob)
log_error("Port '%s' doesn't seem to have a corresponding top level IO (internal cell type mismatch)\n",
ctx->nameOf(port.first));
if (top_port.cell == nullptr) {
log_info("Trimming port '%s' as it is unused.\n", ctx->nameOf(port.first));
} else {
// Copy attributes to real IO buffer
if (ctx->io_attr.count(port.first)) {
for (auto &kv : ctx->io_attr.at(port.first)) {
top_port.cell->attrs[kv.first] = kv.second;
}
}
// Make sure that top level net is set correctly
port.second.net = top_port.cell->ports.at(top_port.port).net;
}
// Now remove the nextpnr-inserted buffer
ci->disconnectPort(id_I);
ci->disconnectPort(id_O);
ctx->cells.erase(port.first);
}
}
BelId get_bel_attr(const CellInfo *ci)
{
if (!ci->attrs.count(id_BEL))
return BelId();
return ctx->getBelByNameStr(ci->attrs.at(id_BEL).as_string());
}
void pack_io()
{
pool<IdString> iob_types = {id_IB, id_OB, id_OBZ, id_BB, id_BB_I3C_A, id_SEIO33,
id_SEIO18, id_DIFFIO18, id_SEIO33_CORE, id_SEIO18_CORE, id_DIFFIO18_CORE};
dict<IdString, XFormRule> io_rules;
// For the low level primitives, make sure we always preserve their type
io_rules[id_SEIO33_CORE].new_type = id_SEIO33_CORE;
io_rules[id_SEIO18_CORE].new_type = id_SEIO18_CORE;
io_rules[id_DIFFIO18_CORE].new_type = id_DIFFIO18_CORE;
// Some IO buffer types need a bit of pin renaming, too
io_rules[id_SEIO33].new_type = id_SEIO33_CORE;
io_rules[id_SEIO33].port_xform[id_PADDI] = id_O;
io_rules[id_SEIO33].port_xform[id_PADDO] = id_I;
io_rules[id_SEIO33].port_xform[id_PADDT] = id_T;
io_rules[id_SEIO33].port_xform[id_IOPAD] = id_B;
io_rules[id_BB_I3C_A] = XFormRule(io_rules[id_SEIO33]);
io_rules[id_SEIO18] = XFormRule(io_rules[id_SEIO33]);
io_rules[id_SEIO18].new_type = id_SEIO18_CORE;
io_rules[id_DIFFIO18] = XFormRule(io_rules[id_SEIO33]);
io_rules[id_DIFFIO18].new_type = id_DIFFIO18_CORE;
// Stage 0: deal with top level inserted IO buffers
prepare_io();
// Stage 1: setup constraints
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
// Iterate through all IO buffer primitives
if (!iob_types.count(ci->type))
continue;
// We need all IO constrained so we can pick the right IO bel type
// An improvement would be to allocate unconstrained IO here
if (!ci->attrs.count(id_LOC))
log_error("Found unconstrained IO '%s', these are currently unsupported\n", ctx->nameOf(ci));
// Convert package pin constraint to bel constraint
std::string loc = ci->attrs.at(id_LOC).as_string();
auto pad_info = ctx->get_pkg_pin_data(loc);
if (pad_info == nullptr)
log_error("IO '%s' is constrained to invalid pin '%s'\n", ctx->nameOf(ci), loc.c_str());
auto func = ctx->get_pad_functions(pad_info);
BelId bel = ctx->get_pad_pio_bel(pad_info);
if (bel == BelId()) {
log_error("IO '%s' is constrained to pin %s (%s) which is not a general purpose IO pin.\n",
ctx->nameOf(ci), loc.c_str(), func.c_str());
} else {
// Get IO type for reporting purposes
std::string io_type = str_or_default(ci->attrs, id_IO_TYPE, "LVCMOS33");
bool is_wr_bel = (ctx->getBelType(bel) == id_SEIO33_CORE);
if (!ctx->io_types.count(io_type))
log_error("IO '%s' has an unsupported IO type '%s'\n", ctx->nameOf(ci), io_type.c_str());
bool is_wr_io = (ctx->io_types.at(io_type).style & IOBANK_WR);
if (is_wr_io != is_wr_bel) {
log_error("%s IO '%s' requires a %s bank but is placed on pin %s in a %s bank.\n", io_type.c_str(),
ctx->nameOf(ci), (is_wr_io ? "wide-range" : "high-performance"), loc.c_str(),
(is_wr_bel ? "wide-range" : "high-performance"));
}
if (ctx->is_io_type_diff(io_type)) {
// Convert from SEIO18 to DIFFIO18
if (ctx->getBelType(bel) != id_SEIO18_CORE)
log_error("IO '%s' uses differential type '%s' but is placed on wide range pin '%s'\n",
ctx->nameOf(ci), io_type.c_str(), loc.c_str());
Loc bel_loc = ctx->getBelLocation(bel);
if (bel_loc.z != 0)
log_error("IO '%s' uses differential type '%s' but is placed on 'B' side pin '%s'\n",
ctx->nameOf(ci), io_type.c_str(), loc.c_str());
bel_loc.z = 2;
bel = ctx->getBelByLocation(bel_loc);
}
log_info("Constraining %s IO '%s' to pin %s (%s%sbel %s)\n", io_type.c_str(), ctx->nameOf(ci),
loc.c_str(), func.c_str(), func.empty() ? "" : "; ", ctx->nameOfBel(bel));
ci->attrs[id_BEL] = ctx->getBelName(bel).str(ctx);
}
}
// Stage 2: apply rules for primitives that need them
generic_xform(io_rules, false);
// Stage 3: all other IO primitives become their bel type
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
// Iterate through all IO buffer primitives
if (!iob_types.count(ci->type))
continue;
// Skip those dealt with in stage 2
if (io_rules.count(ci->type))
continue;
// For non-bidirectional IO, we also need to configure tristate and rename B
if (ci->type == id_IB) {
ctx->set_cell_pinmux(ci, id_T, PINMUX_1);
ci->renamePort(id_I, id_B);
} else if (ci->type == id_OB) {
ctx->set_cell_pinmux(ci, id_T, PINMUX_0);
ci->renamePort(id_O, id_B);
} else if (ci->type == id_OBZ) {
ctx->set_cell_pinmux(ci, id_T, PINMUX_SIG);
ci->renamePort(id_O, id_B);
}
// Get the IO bel
BelId bel = get_bel_attr(ci);
// Set the cell type to the bel type
IdString type = ctx->getBelType(bel);
NPNR_ASSERT(type != IdString());
ci->type = type;
}
}
void pack_constants()
{
// Make sure we have high and low nets available
vcc_net = get_const_net(id_VHI);
gnd_net = get_const_net(id_VLO);
dedi_vcc_net = get_const_net(id_VCC_DRV);
// Iterate through cells
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
// Skip certain cells at this point
if (ci->type != id_LUT4 && ci->type != id_INV && ci->type != id_VHI && ci->type != id_VLO &&
ci->type != id_VCC_DRV)
process_inv_constants(ci);
}
// Remove superfluous inverters and constant drivers
trim_design();
}
// Using a BFS, search for bels of a given type either upstream or downstream of another cell
void find_connected_bels(const CellInfo *cell, IdString port, IdString dest_type, IdString dest_pin, int iter_limit,
std::vector<BelId> &candidates)
{
int iter = 0;
std::queue<WireId> visit;
pool<WireId> seen_wires;
pool<BelId> seen_bels;
BelId bel = get_bel_attr(cell);
if (bel == BelId())
return;
WireId start_wire = ctx->getBelPinWire(bel, port);
NPNR_ASSERT(start_wire != WireId());
PortType dir = ctx->getBelPinType(bel, port);
visit.push(start_wire);
while (!visit.empty() && (iter++ < iter_limit)) {
WireId cursor = visit.front();
visit.pop();
// Check to see if we have reached a valid bel pin
for (auto bp : ctx->getWireBelPins(cursor)) {
if (ctx->getBelType(bp.bel) != dest_type)
continue;
if (dest_pin != IdString() && bp.pin != dest_pin)
continue;
if (seen_bels.count(bp.bel))
continue;
seen_bels.insert(bp.bel);
candidates.push_back(bp.bel);
}
// Search in the appropriate direction up/downstream of the cursor
if (dir == PORT_OUT) {
for (PipId p : ctx->getPipsDownhill(cursor))
if (ctx->checkPipAvail(p)) {
WireId dst = ctx->getPipDstWire(p);
if (seen_wires.count(dst))
continue;
seen_wires.insert(dst);
visit.push(dst);
}
} else {
for (PipId p : ctx->getPipsUphill(cursor))
if (ctx->checkPipAvail(p)) {
WireId src = ctx->getPipSrcWire(p);
if (seen_wires.count(src))
continue;
seen_wires.insert(src);
visit.push(src);
}
}
}
}
// Find the nearest bel of a given type; matching a closure predicate
template <typename Tpred> BelId find_nearest_bel(const CellInfo *cell, IdString dest_type, Tpred predicate)
{
BelId origin = get_bel_attr(cell);
if (origin == BelId())
return BelId();
Loc origin_loc = ctx->getBelLocation(origin);
int best_distance = std::numeric_limits<int>::max();
BelId best_bel = BelId();
for (BelId bel : ctx->getBels()) {
if (ctx->getBelType(bel) != dest_type)
continue;
if (!predicate(bel))
continue;
Loc bel_loc = ctx->getBelLocation(bel);
int dist = std::abs(origin_loc.x - bel_loc.x) + std::abs(origin_loc.y - bel_loc.y);
if (dist < best_distance) {
best_distance = dist;
best_bel = bel;
}
}
return best_bel;
}
pool<BelId> used_bels;
// Pre-place a primitive based on routeability first and distance second
bool preplace_prim(CellInfo *cell, IdString pin, bool strict_routing)
{
std::vector<BelId> routeability_candidates;
if (cell->attrs.count(id_BEL))
return false;
NetInfo *pin_net = cell->getPort(pin);
if (pin_net == nullptr)
return false;
CellInfo *pin_drv = pin_net->driver.cell;
if (pin_drv == nullptr)
return false;
// Check based on routeability
find_connected_bels(pin_drv, pin_net->driver.port, cell->type, pin, 25000, routeability_candidates);
for (BelId cand : routeability_candidates) {
if (used_bels.count(cand))
continue;
log_info(" constraining %s '%s' to bel '%s' based on dedicated routing\n", ctx->nameOf(cell),
ctx->nameOf(cell->type), ctx->nameOfBel(cand));
cell->attrs[id_BEL] = ctx->getBelName(cand).str(ctx);
used_bels.insert(cand);
return true;
}
// Unless in strict mode; check based on simple distance too
BelId nearest = find_nearest_bel(pin_drv, cell->type, [&](BelId bel) { return !used_bels.count(bel); });
if (nearest != BelId()) {
log_info(" constraining %s '%s' to bel '%s'\n", ctx->nameOf(cell), ctx->nameOf(cell->type),
ctx->nameOfBel(nearest));
cell->attrs[id_BEL] = ctx->getBelName(nearest).str(ctx);
used_bels.insert(nearest);
return true;
}
return false;
}
// Pre-place a singleton primitive; so decisions can be made on routeability downstream of it
bool preplace_singleton(CellInfo *cell)
{
if (cell->attrs.count(id_BEL))
return false;
bool did_something = false;
for (BelId bel : ctx->getBels()) {
if (ctx->getBelType(bel) != cell->type)
continue;
// Check that the bel really is a singleton...
NPNR_ASSERT(!cell->attrs.count(id_BEL));
cell->attrs[id_BEL] = ctx->getBelName(bel).str(ctx);
log_info(" constraining %s '%s' to bel '%s'\n", ctx->nameOf(cell), ctx->nameOf(cell->type),
ctx->nameOfBel(bel));
did_something = true;
}
return did_something;
}
// Insert a buffer primitive in a signal; moving all users that match a predicate behind it
template <typename Tpred>
CellInfo *insert_buffer(NetInfo *net, IdString buffer_type, std::string name_postfix, IdString i, IdString o,
Tpred pred)
{
// Create the buffered net
NetInfo *buffered_net = ctx->createNet(ctx->idf("%s$%s", ctx->nameOf(net), name_postfix.c_str()));
// Create the buffer cell
CellInfo *buffer = ctx->createCell(ctx->idf("%s$drv_%s", ctx->nameOf(buffered_net), ctx->nameOf(buffer_type)),
buffer_type);
buffer->addInput(i);
buffer->addOutput(o);
// Drive the buffered net with the buffer
buffer->connectPort(o, buffered_net);
// Filter users
std::vector<PortRef> remaining_users;
for (auto &usr : net->users) {
if (pred(usr)) {
usr.cell->ports[usr.port].net = buffered_net;
usr.cell->ports[usr.port].user_idx = buffered_net->users.add(usr);
} else {
remaining_users.push_back(usr);
}
}
net->users.clear();
for (auto &usr : remaining_users)
usr.cell->ports.at(usr.port).user_idx = net->users.add(usr);
// Connect buffer input to original net
buffer->connectPort(i, net);
return buffer;
}
// Insert global buffers
void promote_globals()
{
std::vector<std::pair<int, IdString>> clk_fanout;
int available_globals = 16;
for (auto &net : ctx->nets) {
NetInfo *ni = net.second.get();
// Skip undriven nets; and nets that are already global
if (ni->driver.cell == nullptr)
continue;
if (ni->driver.cell->type == id_DCS) {
continue;
}
if (ni->driver.cell->type == id_DCC) {
--available_globals;
continue;
}
// Count the number of clock ports
int clk_count = 0;
for (const auto &usr : ni->users) {
auto port_style = ctx->get_cell_pin_style(usr.cell, usr.port);
if (port_style & PINGLB_CLK)
++clk_count;
}
if (clk_count > 0)
clk_fanout.emplace_back(clk_count, ni->name);
}
if (available_globals <= 0)
return;
// Sort clocks by max fanout
std::sort(clk_fanout.begin(), clk_fanout.end(), std::greater<std::pair<int, IdString>>());
log_info("Promoting globals...\n");
// Promote the N highest fanout clocks
for (size_t i = 0; i < std::min<size_t>(clk_fanout.size(), available_globals); i++) {
NetInfo *net = ctx->nets.at(clk_fanout.at(i).second).get();
log_info(" promoting clock net '%s'\n", ctx->nameOf(net));
insert_buffer(net, id_DCC, "glb_clk", id_CLKI, id_CLKO,
[&](const PortRef &port) { return port.cell->type != id_DCC; });
}
}
// Place certain global cells
void place_globals()
{
// Keep running until we reach a fixed point
log_info("Placing globals...\n");
TopoSort<IdString> sorter;
auto is_glb_cell = [&](const CellInfo *cell) {
return cell->type.in(id_OSC_CORE, id_DCC, id_PLL_CORE, id_DCS);
};
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
if (is_glb_cell(ci)) {
sorter.node(ci->name);
auto do_pin = [&](IdString pin) {
NetInfo *net = ci->getPort(pin);
if (!net || !net->driver.cell || !is_glb_cell(net->driver.cell))
return;
sorter.edge(net->driver.cell->name, ci->name);
};
if (ci->type == id_PLL_CORE) {
do_pin(id_REFCK);
} else if (ci->type == id_DCC) {
do_pin(id_CLKI);
} else if (ci->type == id_DCS) {
do_pin(id_CLK0);
do_pin(id_CLK1);
}
}
}
sorter.sort();
for (IdString cell_name : sorter.sorted) {
CellInfo *ci = ctx->cells.at(cell_name).get();
if (ci->type == id_OSC_CORE)
preplace_singleton(ci);
else if (ci->type == id_DCC)
preplace_prim(ci, id_CLKI, false);
else if (ci->type == id_PLL_CORE)
preplace_prim(ci, id_REFCK, false);
else if (ci->type == id_DCS)
preplace_prim(ci, id_CLK0, false);
}
}
// Get a bus port name
IdString bus(const std::string &base, int i) { return ctx->idf("%s[%d]", base.c_str(), i); }
IdString bus_flat(const std::string &base, int i) { return ctx->idf("%s%d", base.c_str(), i); }
// Pack a LUTRAM into COMB and RAMW cells
void pack_lutram()
{
// Do this so we don't have an iterate-and-modfiy situation
std::vector<CellInfo *> lutrams;
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
if (ci->type != id_DPR16X4)
continue;
lutrams.push_back(ci);
}
// Port permutation vectors
IdString ramw_wdo[4] = {id_D1, id_C1, id_A1, id_B1};
IdString ramw_wado[4] = {id_D0, id_B0, id_C0, id_A0};
IdString comb0_rad[4] = {id_D, id_B, id_C, id_A};
IdString comb1_rad[4] = {id_C, id_B, id_D, id_A};
for (CellInfo *ci : lutrams) {
// Create constituent cells
CellInfo *ramw = ctx->createCell(ctx->idf("%s$lutram_ramw$", ctx->nameOf(ci)), id_RAMW);
std::vector<CellInfo *> combs;
for (int i = 0; i < 4; i++)
combs.push_back(ctx->createCell(ctx->idf("%s$lutram_comb[%d]$", ctx->nameOf(ci), i), id_OXIDE_COMB));
// Rewiring - external WCK and WRE
ci->movePortTo(id_WCK, ramw, id_CLK);
ci->movePortTo(id_WRE, ramw, id_LSR);
// Internal WCK and WRE signals
ramw->addOutput(id_WCKO);
ramw->addOutput(id_WREO);
NetInfo *int_wck = ctx->createNet(ctx->idf("%s$lutram_wck$", ctx->nameOf(ci)));
NetInfo *int_wre = ctx->createNet(ctx->idf("%s$lutram_wre$", ctx->nameOf(ci)));
ramw->connectPort(id_WCKO, int_wck);