forked from VectorCamp/vectorscan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrose_build_merge.cpp
More file actions
2809 lines (2364 loc) · 89.5 KB
/
Copy pathrose_build_merge.cpp
File metadata and controls
2809 lines (2364 loc) · 89.5 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
/*
* Copyright (c) 2015-2018, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** \file
* \brief Rose Build: functions for reducing the size of the Rose graph
* through merging.
*/
#include "rose_build_merge.h"
#include "grey.h"
#include "rose_build.h"
#include "rose_build_impl.h"
#include "rose_build_util.h"
#include "ue2common.h"
#include "nfa/castlecompile.h"
#include "nfa/goughcompile.h"
#include "nfa/limex_limits.h"
#include "nfa/mcclellancompile.h"
#include "nfa/nfa_build_util.h"
#include "nfa/rdfa_merge.h"
#include "nfagraph/ng_holder.h"
#include "nfagraph/ng_haig.h"
#include "nfagraph/ng_is_equal.h"
#include "nfagraph/ng_lbr.h"
#include "nfagraph/ng_limex.h"
#include "nfagraph/ng_mcclellan.h"
#include "nfagraph/ng_puff.h"
#include "nfagraph/ng_redundancy.h"
#include "nfagraph/ng_repeat.h"
#include "nfagraph/ng_reports.h"
#include "nfagraph/ng_stop.h"
#include "nfagraph/ng_uncalc_components.h"
#include "nfagraph/ng_util.h"
#include "nfagraph/ng_width.h"
#include "util/bitutils.h"
#include "util/charreach.h"
#include "util/compile_context.h"
#include "util/container.h"
#include "util/dump_charclass.h"
#include "util/graph_range.h"
#include "util/hash.h"
#include "util/insertion_ordered.h"
#include "util/order_check.h"
#include "util/report_manager.h"
#include "util/ue2string.h"
#include "util/unordered.h"
#include <algorithm>
#include <functional>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#include <utility>
#include <boost/range/adaptor/map.hpp>
using namespace std;
using boost::adaptors::map_values;
using boost::adaptors::map_keys;
namespace ue2 {
static const size_t NARROW_START_MAX = 10;
static const size_t SMALL_MERGE_MAX_VERTICES_STREAM = 128;
static const size_t SMALL_MERGE_MAX_VERTICES_BLOCK = 64;
static const size_t SMALL_ROSE_THRESHOLD_STREAM = 32;
static const size_t SMALL_ROSE_THRESHOLD_BLOCK = 10;
static const size_t MERGE_GROUP_SIZE_MAX = 200;
static const size_t MERGE_CASTLE_GROUP_SIZE_MAX = 1000;
/** \brief Max number of DFAs (McClellan, Haig) to pairwise merge together. */
static const size_t DFA_CHUNK_SIZE_MAX = 200;
/** \brief Max DFA states in a merged DFA. */
static const size_t DFA_MERGE_MAX_STATES = 8000;
/** \brief In block mode, merge two prefixes even if they don't have identical
* literal sets if they have fewer than this many states and the merged graph
* is also small. */
static constexpr size_t MAX_BLOCK_PREFIX_MERGE_VERTICES = 32;
static
size_t small_merge_max_vertices(const CompileContext &cc) {
return cc.streaming ? SMALL_MERGE_MAX_VERTICES_STREAM
: SMALL_MERGE_MAX_VERTICES_BLOCK;
}
static
size_t small_rose_threshold(const CompileContext &cc) {
return cc.streaming ? SMALL_ROSE_THRESHOLD_STREAM
: SMALL_ROSE_THRESHOLD_BLOCK;
}
/**
* Returns a loose hash of a leftfix for use in dedupeLeftfixes. Note that
* reports should not contribute to the hash.
*/
static
size_t hashLeftfix(const left_id &left) {
size_t val = 0;
if (left.castle()) {
hash_combine(val, left.castle()->reach());
for (const auto &pr : left.castle()->repeats) {
hash_combine(val, pr.first); // top
hash_combine(val, pr.second.bounds);
}
} else if (left.graph()) {
hash_combine(val, hash_holder(*left.graph()));
}
return val;
}
namespace {
/** Key used to group sets of leftfixes by the dedupeLeftfixes path. */
struct RoseGroup {
RoseGroup(const RoseBuildImpl &build, RoseVertex v)
: left_hash(hashLeftfix(left_id(build.g[v].left))),
lag(build.g[v].left.lag), eod_table(build.isInETable(v)) {
const RoseGraph &g = build.g;
assert(in_degree(v, g) == 1);
RoseVertex u = *inv_adjacent_vertices(v, g).first;
parent = g[u].index;
}
bool operator<(const RoseGroup &b) const {
const RoseGroup &a = *this;
ORDER_CHECK(parent);
ORDER_CHECK(left_hash);
ORDER_CHECK(lag);
ORDER_CHECK(eod_table);
return false;
}
private:
/** Parent vertex index. We must use the index, rather than the descriptor,
* for compile determinism. */
size_t parent;
/** Quick hash of the leftfix itself. Must be identical for a given pair of
* graphs if is_equal would return true. */
size_t left_hash;
/** Leftfix lag value. */
u32 lag;
/** True if associated vertex (successor) is in the EOD table. We don't
* allow sharing of leftfix engines between "normal" and EOD operation. */
bool eod_table;
};
/**
* Intended to find graphs that are identical except for their report
* IDs. Relies on vertex and edge indices to pick up graphs that have been
* messily put together in different orderings. Only implemented for castles and
* holders.
*/
static
bool is_equal(const left_id &u_left, ReportID u_report,
const left_id &v_left, ReportID v_report) {
if (u_left.castle() && v_left.castle()) {
return is_equal(*u_left.castle(), u_report, *v_left.castle(), v_report);
}
if (!u_left.graph() || !v_left.graph()) {
return false;
}
return is_equal(*u_left.graph(), u_report, *v_left.graph(), v_report);
}
} // namespace
/**
* This pass performs work similar to \ref dedupeSuffixes - it removes
* duplicate prefix/infixes (that is, leftfixes) which are identical graphs and
* share the same trigger vertex and lag. Leftfixes are first grouped by
* parent role and lag to reduce the number of candidates to be inspected
* for each leftfix. The graphs in each cluster are then compared with each
* other and the graph is updated to only refer to a canonical version of each
* graph.
*
* Note: only roles with a single predecessor vertex are considered for this
* transform - it should probably be generalised to work for roles which share
* the same set of predecessor roles as for \ref dedupeLeftfixesVariableLag or
* it should be retired entirely.
*/
bool dedupeLeftfixes(RoseBuildImpl &tbi) {
DEBUG_PRINTF("deduping leftfixes\n");
map<RoseGroup, deque<RoseVertex>> roses;
bool work_done = false;
/* Note: a leftfix's transientness will not be altered by deduping */
// Collect leftfixes into groups.
RoseGraph &g = tbi.g;
for (auto v : vertices_range(g)) {
if (!g[v].left) {
continue;
}
const left_id left(g[v].left);
if (left.haig()) {
/* TODO: allow merging of identical haigs */
continue;
}
if (in_degree(v, g) != 1) {
continue;
}
roses[RoseGroup(tbi, v)].emplace_back(v);
}
DEBUG_PRINTF("collected %zu rose groups\n", roses.size());
// Walk groups and dedupe the roses therein.
for (deque<RoseVertex> &verts : roses | map_values) {
DEBUG_PRINTF("group has %zu vertices\n", verts.size());
unordered_set<left_id> seen;
for (auto jt = verts.begin(), jte = verts.end(); jt != jte; ++jt) {
RoseVertex v = *jt;
left_id left(g[v].left);
// Skip cases we've already handled, and mark as seen otherwise.
if (!seen.insert(left).second) {
continue;
}
// Scan the rest of the list for dupes.
for (auto kt = std::next(jt); kt != jte; ++kt) {
if (g[v].left == g[*kt].left
|| !is_equal(left_id(g[v].left), g[v].left.leftfix_report,
left_id(g[*kt].left), g[*kt].left.leftfix_report)) {
continue;
}
// Dupe found.
DEBUG_PRINTF("rose at vertex %zu is a dupe of %zu\n",
g[*kt].index, g[v].index);
assert(g[v].left.lag == g[*kt].left.lag);
g[*kt].left = g[v].left;
work_done = true;
}
}
}
return work_done;
}
/**
* \brief Returns a numeric key that can be used to group this suffix with
* others that may be its duplicate.
*/
static
size_t suffix_size_key(const suffix_id &s) {
if (s.graph()) {
return num_vertices(*s.graph());
}
if (s.castle()) {
return s.castle()->repeats.size();
}
return 0;
}
static
bool is_equal(const suffix_id &s1, const suffix_id &s2) {
if (s1.graph() && s2.graph()) {
return is_equal(*s1.graph(), *s2.graph());
} else if (s1.castle() && s2.castle()) {
return is_equal(*s1.castle(), *s2.castle());
}
return false;
}
/**
* This function simply looks for suffix NGHolder graphs which are identical
* and updates the roles in the RoseGraph to refer to only a single copy. This
* obviously has benefits in terms of both performance (as we don't run
* multiple engines doing the same work) and stream state. This function first
* groups all suffixes by number of vertices and report set to restrict the set
* of possible candidates. Each group is then walked to find duplicates using
* the \ref is_equal comparator for NGHolders and updating the RoseGraph as it
* goes.
*
* Note: does not dedupe suffixes of vertices in the EOD table.
*/
void dedupeSuffixes(RoseBuildImpl &tbi) {
DEBUG_PRINTF("deduping suffixes\n");
unordered_map<suffix_id, set<RoseVertex>> suffix_map;
map<pair<size_t, set<ReportID>>, vector<suffix_id>> part;
// Collect suffixes into groups.
RoseGraph &g = tbi.g;
for (auto v : vertices_range(g)) {
if (!g[v].suffix || tbi.isInETable(v)) {
continue;
}
const suffix_id s(g[v].suffix);
if (!(s.graph() || s.castle())) {
continue; // e.g. Haig
}
set<RoseVertex> &verts = suffix_map[s];
if (verts.empty()) {
part[make_pair(suffix_size_key(s), all_reports(s))].emplace_back(s);
}
verts.insert(v);
}
DEBUG_PRINTF("collected %zu groups\n", part.size());
for (const auto &cand : part | map_values) {
if (cand.size() <= 1) {
continue;
}
DEBUG_PRINTF("deduping cand set of size %zu\n", cand.size());
for (auto jt = cand.begin(); jt != cand.end(); ++jt) {
if (suffix_map[*jt].empty()) {
continue;
}
for (auto kt = next(jt); kt != cand.end(); ++kt) {
if (suffix_map[*kt].empty() || !is_equal(*jt, *kt)) {
continue;
}
DEBUG_PRINTF("found dupe\n");
for (auto v : suffix_map[*kt]) {
RoseVertex dupe = *suffix_map[*jt].begin();
assert(dupe != v);
g[v].suffix.graph = g[dupe].suffix.graph;
g[v].suffix.castle = g[dupe].suffix.castle;
assert(suffix_id(g[v].suffix) ==
suffix_id(g[dupe].suffix));
suffix_map[*jt].insert(v);
}
suffix_map[*kt].clear();
}
}
}
}
namespace {
/**
* This class stores a mapping from an engine reference (left_id, suffix_id,
* etc) to a list of vertices, and also allows us to iterate over the set of
* engine references in insertion order -- we add to the mapping in vertex
* iteration order, so this allows us to provide a consistent ordering.
*/
template<class EngineRef>
class Bouquet {
private:
list<EngineRef> ordering; // Unique list in insert order.
using BouquetMap = ue2_unordered_map<EngineRef, deque<RoseVertex>>;
BouquetMap bouquet;
public:
void insert(const EngineRef &h, RoseVertex v) {
typename BouquetMap::iterator f = bouquet.find(h);
if (f == bouquet.end()) {
ordering.emplace_back(h);
bouquet[h].emplace_back(v);
} else {
f->second.emplace_back(v);
}
}
void insert(const EngineRef &h, const deque<RoseVertex> &verts) {
typename BouquetMap::iterator f = bouquet.find(h);
if (f == bouquet.end()) {
ordering.emplace_back(h);
bouquet.insert(make_pair(h, verts));
} else {
f->second.insert(f->second.end(), verts.begin(), verts.end());
}
}
const deque<RoseVertex> &vertices(const EngineRef &h) const {
typename BouquetMap::const_iterator it = bouquet.find(h);
assert(it != bouquet.end()); // must be present
return it->second;
}
void erase(const EngineRef &h) {
assert(bouquet.find(h) != bouquet.end());
bouquet.erase(h);
ordering.remove(h);
}
/** Remove all the elements in the given iterator range. */
template <class Iter>
void erase_all(Iter erase_begin, Iter erase_end) {
for (Iter it = erase_begin; it != erase_end; ++it) {
bouquet.erase(*it);
}
// Use a quick-lookup container so that we only have to traverse the
// 'ordering' list once.
const set<EngineRef> dead(erase_begin, erase_end);
for (iterator it = begin(); it != end(); /* incremented inside */) {
if (contains(dead, *it)) {
ordering.erase(it++);
} else {
++it;
}
}
}
void clear() {
ordering.clear();
bouquet.clear();
}
size_t size() const { return bouquet.size(); }
// iterate over holders in insert order
typedef typename list<EngineRef>::iterator iterator;
iterator begin() { return ordering.begin(); }
iterator end() { return ordering.end(); }
// const iterate over holders in insert order
typedef typename list<EngineRef>::const_iterator const_iterator;
const_iterator begin() const { return ordering.begin(); }
const_iterator end() const { return ordering.end(); }
};
typedef Bouquet<left_id> LeftfixBouquet;
typedef Bouquet<suffix_id> SuffixBouquet;
} // namespace
/**
* Split a \ref Bouquet of some type into several smaller ones.
*/
template <class EngineRef>
static void chunkBouquets(const Bouquet<EngineRef> &in,
deque<Bouquet<EngineRef>> &out,
const size_t chunk_size) {
if (in.size() <= chunk_size) {
out.emplace_back(in);
return;
}
out.emplace_back(Bouquet<EngineRef>());
for (const auto &engine : in) {
if (out.back().size() >= chunk_size) {
out.emplace_back(Bouquet<EngineRef>());
}
out.back().insert(engine, in.vertices(engine));
}
}
static
bool stringsCanFinishAtSameSpot(const ue2_literal &u,
ue2_literal::const_iterator v_b,
ue2_literal::const_iterator v_e) {
ue2_literal::const_iterator u_e = u.end();
ue2_literal::const_iterator u_b = u.begin();
while (u_e != u_b && v_e != v_b) {
--u_e;
--v_e;
if (!overlaps(*u_e, *v_e)) {
return false;
}
}
return true;
}
/**
* Check that if after u has been seen, that it is impossible for the arrival of
* v to require the inspection of an engine earlier than u did.
*
* Let delta be the earliest that v can be seen after u (may be zero)
*
* ie, we require u_loc - ulag <= v_loc - vlag (v_loc = u_loc + delta)
* ==> - ulag <= delta - vlag
* ==> vlag - ulag <= delta
*/
static
bool checkPrefix(const rose_literal_id &ul, const u32 ulag,
const rose_literal_id &vl, const u32 vlag) {
DEBUG_PRINTF("'%s'-%u '%s'-%u\n", escapeString(ul.s).c_str(), ulag,
escapeString(vl.s).c_str(), vlag);
if (vl.delay || ul.delay) {
/* engine related literals should not be delayed anyway */
return false;
}
if (ulag >= vlag) {
assert(maxOverlap(ul, vl) <= vl.elength() - vlag + ulag);
return true;
}
size_t min_allowed_delta = vlag - ulag;
DEBUG_PRINTF("min allow distace %zu\n", min_allowed_delta);
for (size_t i = 0; i < min_allowed_delta; i++) {
if (stringsCanFinishAtSameSpot(ul.s, vl.s.begin(), vl.s.end() - i)) {
DEBUG_PRINTF("v can follow u at a (too close) distance of %zu\n", i);
return false;
}
}
DEBUG_PRINTF("OK\n");
return true;
}
static
bool hasSameEngineType(const RoseVertexProps &u_prop,
const RoseVertexProps &v_prop) {
const left_id u_left = left_id(u_prop.left);
const left_id v_left = left_id(v_prop.left);
return !u_left.haig() == !v_left.haig()
&& !u_left.dfa() == !v_left.dfa()
&& !u_left.castle() == !v_left.castle()
&& !u_left.graph() == !v_left.graph();
}
/**
* Verifies that merging the leftfix of vertices does not cause conflicts due
* to the literals on the right.
*
* The main concern is that the lags of the literals and overlap between them
* allow the engine check offset to potentially regress.
*
* Parameters are vectors of literals + lag pairs.
*
* Note: if more constraints of when the leftfixes were going to be checked
* (mandatory lookarounds passing, offset checks), more merges may be allowed.
*/
static
bool compatibleLiteralsForMerge(
const vector<pair<const rose_literal_id *, u32>> &ulits,
const vector<pair<const rose_literal_id *, u32>> &vlits) {
assert(!ulits.empty());
assert(!vlits.empty());
// We cannot merge engines that prefix literals in different tables.
if (ulits[0].first->table != vlits[0].first->table) {
DEBUG_PRINTF("literals in different tables\n");
return false;
}
// We don't handle delayed cases yet.
// cppcheck-suppress useStlAlgorithm
for (const auto &ue : ulits) {
const rose_literal_id &ul = *ue.first;
if (ul.delay) {
return false;
}
}
// cppcheck-suppress useStlAlgorithm
for (const auto &ve : vlits) {
const rose_literal_id &vl = *ve.first;
if (vl.delay) {
return false;
}
}
/* An engine requires that all accesses to it are ordered by offsets. (ie,
we can not check an engine's state at offset Y, if we have already
checked its status at offset X and X > Y). If we can not establish that
the literals used for triggering will satisfy this property, then it is
not safe to merge the engine. */
// cppcheck-suppress useStlAlgorithm
for (const auto &ue : ulits) {
const rose_literal_id &ul = *ue.first;
u32 ulag = ue.second;
// cppcheck-suppress useStlAlgorithm
for (const auto &ve : vlits) {
const rose_literal_id &vl = *ve.first;
u32 vlag = ve.second;
if (!checkPrefix(ul, ulag, vl, vlag)
|| !checkPrefix(vl, vlag, ul, ulag)) {
DEBUG_PRINTF("prefix check failed\n");
return false;
}
}
}
return true;
}
/**
* True if this graph has few enough accel states to be implemented as an NFA
* with all of those states actually becoming accel schemes.
*/
static
bool isAccelerableLeftfix(const RoseBuildImpl &build, const NGHolder &g) {
u32 num = countAccelStates(g, &build.rm, build.cc);
DEBUG_PRINTF("graph with %zu vertices has %u accel states\n",
num_vertices(g), num);
return num <= NFA_MAX_ACCEL_STATES;
}
/**
* In block mode, we want to be a little more selective -- We will only merge
* prefix engines when the literal sets are the same or if the merged graph
* has only grown by a small amount.
*/
static
bool safeBlockModeMerge(const RoseBuildImpl &build, RoseVertex u,
RoseVertex v) {
assert(!build.cc.streaming);
assert(build.isRootSuccessor(u) == build.isRootSuccessor(v));
// Always merge infixes if we can (subject to the other criteria in
// mergeableRoseVertices).
if (!build.isRootSuccessor(u)) {
return true;
}
const RoseGraph &g = build.g;
// Merge prefixes with identical literal sets (as we'd have to run them
// both when we see those literals anyway).
if (g[u].literals == g[v].literals) {
return true;
}
// The rest of this function only deals with the case when both vertices
// have graph leftfixes.
if (!g[u].left.graph || !g[v].left.graph) {
return false;
}
const size_t u_count = num_vertices(*g[u].left.graph);
const size_t v_count = num_vertices(*g[v].left.graph);
DEBUG_PRINTF("u prefix has %zu vertices, v prefix has %zu vertices\n",
u_count, v_count);
if (u_count > MAX_BLOCK_PREFIX_MERGE_VERTICES ||
v_count > MAX_BLOCK_PREFIX_MERGE_VERTICES) {
DEBUG_PRINTF("prefixes too big already\n");
return false;
}
DEBUG_PRINTF("trying merge\n");
NGHolder h;
cloneHolder(h, *g[v].left.graph);
if (!mergeNfaPair(*g[u].left.graph, h, nullptr, build.cc)) {
DEBUG_PRINTF("couldn't merge\n");
return false;
}
const size_t merged_count = num_vertices(h);
DEBUG_PRINTF("merged result has %zu vertices\n", merged_count);
if (merged_count > MAX_BLOCK_PREFIX_MERGE_VERTICES) {
DEBUG_PRINTF("exceeded limit\n");
return false;
}
// We want to only perform merges that take advantage of some
// commonality in the two input graphs, so we check that the number of
// vertices has only grown a small amount: somewhere between the sum
// (no commonality) and the max (no growth at all) of the vertex counts
// of the input graphs.
const size_t max_size = u_count + v_count;
const size_t min_size = max(u_count, v_count);
const size_t max_growth = ((max_size - min_size) * 25) / 100;
if (merged_count > min_size + max_growth) {
DEBUG_PRINTF("grew too much\n");
return false;
}
// We don't want to squander any chances at accelerating.
if (!isAccelerableLeftfix(build, h) &&
(isAccelerableLeftfix(build, *g[u].left.graph) ||
isAccelerableLeftfix(build, *g[v].left.graph))) {
DEBUG_PRINTF("would lose accel property\n");
return false;
}
DEBUG_PRINTF("safe to merge\n");
return true;
}
bool mergeableRoseVertices(const RoseBuildImpl &tbi, RoseVertex u,
RoseVertex v) {
assert(u != v);
if (!hasSameEngineType(tbi.g[u], tbi.g[v])) {
return false;
}
if (!tbi.cc.streaming && !safeBlockModeMerge(tbi, u, v)) {
return false;
}
/* We cannot merge prefixes/vertices if they are successors of different
* root vertices */
if (tbi.isRootSuccessor(u)) {
assert(tbi.isRootSuccessor(v));
set<RoseVertex> u_preds;
set<RoseVertex> v_preds;
insert(&u_preds, inv_adjacent_vertices(u, tbi.g));
insert(&v_preds, inv_adjacent_vertices(v, tbi.g));
if (u_preds != v_preds) {
return false;
}
}
u32 ulag = tbi.g[u].left.lag;
vector<pair<const rose_literal_id *, u32>> ulits;
ulits.reserve(tbi.g[u].literals.size());
for (u32 id : tbi.g[u].literals) {
// cppcheck-suppress useStlAlgorithm
ulits.emplace_back(&tbi.literals.at(id), ulag);
}
u32 vlag = tbi.g[v].left.lag;
vector<pair<const rose_literal_id *, u32>> vlits;
vlits.reserve(tbi.g[v].literals.size());
for (u32 id : tbi.g[v].literals) {
// cppcheck-suppress useStlAlgorithm
vlits.emplace_back(&tbi.literals.at(id), vlag);
}
if (!compatibleLiteralsForMerge(ulits, vlits)) {
return false;
}
DEBUG_PRINTF("roses on %zu and %zu are mergeable\n", tbi.g[u].index,
tbi.g[v].index);
return true;
}
/* We cannot merge an engine, if a trigger literal and a post literal overlap
* in such a way that engine status needs to be check at a point before the
* engine's current location.
*
* i.e., for a trigger literal u and a pos literal v,
* where delta is the earliest v can appear after t,
* we require that v_loc - v_lag >= u_loc
* ==> u_loc + delta - v_lag >= u_loc
* ==> delta >= v_lag
*
*/
static
bool checkPredDelay(const rose_literal_id &ul, const rose_literal_id &vl,
u32 vlag) {
DEBUG_PRINTF("%s %s (lag %u)\n", escapeString(ul.s).c_str(),
escapeString(vl.s).c_str(), vlag);
for (size_t i = 0; i < vlag; i++) {
if (stringsCanFinishAtSameSpot(ul.s, vl.s.begin(), vl.s.end() - i)) {
DEBUG_PRINTF("v can follow u at a (too close) distance of %zu\n", i);
return false;
}
}
DEBUG_PRINTF("OK\n");
return true;
}
template<typename VertexCont>
static never_inline
bool checkPredDelays(const RoseBuildImpl &build, const VertexCont &v1,
const VertexCont &v2) {
flat_set<RoseVertex> fpreds;
for (auto v : v1) {
insert(&fpreds, inv_adjacent_vertices(v, build.g));
}
flat_set<u32> pred_lits;
/* No need to examine delays of a common pred - as it must already have
* survived the delay checks.
*
* This is important when the pred is in the anchored table as
* the literal is no longer available. */
flat_set<RoseVertex> known_good_preds;
for (auto v : v2) {
insert(&known_good_preds, inv_adjacent_vertices(v, build.g));
}
for (auto u : fpreds) {
if (!contains(known_good_preds, u)) {
insert(&pred_lits, build.g[u].literals);
}
}
vector<const rose_literal_id *> pred_rose_lits;
pred_rose_lits.reserve(pred_lits.size());
for (const auto &p : pred_lits) {
// cppcheck-suppress useStlAlgorithm
pred_rose_lits.emplace_back(&build.literals.at(p));
}
for (auto v : v2) {
u32 vlag = build.g[v].left.lag;
if (!vlag) {
continue;
}
for (const u32 vlit : build.g[v].literals) {
const rose_literal_id &vl = build.literals.at(vlit);
assert(!vl.delay); // this should never have got this far?
for (const auto &ul : pred_rose_lits) {
assert(!ul->delay); // this should never have got this far?
if (!checkPredDelay(*ul, vl, vlag)) {
return false;
}
}
}
}
return true;
}
static
bool mergeableRoseVertices(const RoseBuildImpl &tbi,
const deque<RoseVertex> &verts1,
const deque<RoseVertex> &verts2) {
assert(!verts1.empty());
assert(!verts2.empty());
RoseVertex u_front = verts1.front();
RoseVertex v_front = verts2.front();
/* all vertices must have the same engine type: assume all verts in each
* group are already of the same type */
if (!hasSameEngineType(tbi.g[u_front], tbi.g[v_front])) {
return false;
}
bool is_prefix = tbi.isRootSuccessor(u_front);
/* We cannot merge prefixes/vertices if they are successors of different
* root vertices: similarly, assume the grouped vertices are compatible */
if (is_prefix) {
assert(tbi.isRootSuccessor(v_front));
set<RoseVertex> u_preds;
set<RoseVertex> v_preds;
insert(&u_preds, inv_adjacent_vertices(u_front, tbi.g));
insert(&v_preds, inv_adjacent_vertices(v_front, tbi.g));
if (u_preds != v_preds) {
return false;
}
}
vector<pair<const rose_literal_id *, u32>> ulits; /* lit + lag pairs */
for (auto a : verts1) {
if (!tbi.cc.streaming && !safeBlockModeMerge(tbi, v_front, a)) {
return false;
}
u32 ulag = tbi.g[a].left.lag;
for (u32 id : tbi.g[a].literals) {
// cppcheck-suppress useStlAlgorithm
ulits.emplace_back(&tbi.literals.at(id), ulag);
}
}
vector<pair<const rose_literal_id *, u32>> vlits;
for (auto a : verts2) {
if (!tbi.cc.streaming && !safeBlockModeMerge(tbi, u_front, a)) {
return false;
}
u32 vlag = tbi.g[a].left.lag;
for (u32 id : tbi.g[a].literals) {
// cppcheck-suppress useStlAlgorithm
vlits.emplace_back(&tbi.literals.at(id), vlag);
}
}
if (!compatibleLiteralsForMerge(ulits, vlits)) {
return false;
}
// Check preds are compatible as well.
if (!checkPredDelays(tbi, verts1, verts2)
|| !checkPredDelays(tbi, verts2, verts1)) {
return false;
}
DEBUG_PRINTF("vertex sets are mergeable\n");
return true;
}
bool mergeableRoseVertices(const RoseBuildImpl &tbi, const set<RoseVertex> &v1,
const set<RoseVertex> &v2) {
const deque<RoseVertex> vv1(v1.begin(), v1.end());
const deque<RoseVertex> vv2(v2.begin(), v2.end());
return mergeableRoseVertices(tbi, vv1, vv2);
}
/** \brief Priority queue element for Rose merges. */
namespace {
struct RoseMergeCandidate {
RoseMergeCandidate(const left_id &r1_in, const left_id &r2_in, u32 cpl_in,
u32 tb)
: r1(r1_in), r2(r2_in), stopxor(0), cpl(cpl_in), states(0),
tie_breaker(tb) {
if (r1.graph() && r2.graph()) {
const NGHolder &h1 = *r1.graph(), &h2 = *r2.graph();
/* som_none as haigs don't merge and just a guiding heuristic */
CharReach stop1 = findStopAlphabet(h1, SOM_NONE);
CharReach stop2 = findStopAlphabet(h2, SOM_NONE);
stopxor = (stop1 ^ stop2).count();
// We use the number of vertices as an approximation of the state
// count here, as this is just feeding a comparison.
u32 vertex_count = num_vertices(h1) + num_vertices(h2);
states = vertex_count - min(vertex_count, cpl);
} else if (r1.castle() && r2.castle()) {
// FIXME
}
}
bool operator<(const RoseMergeCandidate &a) const {
if (stopxor != a.stopxor) {
return stopxor > a.stopxor;
}
if (cpl != a.cpl) {
return cpl < a.cpl;
}
if (states != a.states) {
return states > a.states;
}
return tie_breaker < a.tie_breaker;
}
left_id r1;
left_id r2;
u32 stopxor;
u32 cpl; //!< common prefix length
u32 states;
u32 tie_breaker; //!< determinism
};
}
static
bool mergeLeftfixPair(RoseBuildImpl &build, left_id &r1, left_id &r2,
const vector<RoseVertex> &verts1,
const vector<RoseVertex> &verts2) {
assert(!verts1.empty() && !verts2.empty());
DEBUG_PRINTF("merging pair of leftfixes:\n");
DEBUG_PRINTF(" A:%016zx: tops %s\n", r1.hash(),
as_string_list(all_tops(r1)).c_str());
DEBUG_PRINTF(" B:%016zx: tops %s\n", r2.hash(),
as_string_list(all_tops(r2)).c_str());
RoseGraph &g = build.g;
if (r1.graph()) {
assert(r2.graph());
assert(r1.graph()->kind == r2.graph()->kind);
if (!mergeNfaPair(*r1.graph(), *r2.graph(), nullptr, build.cc)) {
DEBUG_PRINTF("nfa merge failed\n");
return false;
}