forked from arminbiere/lingeling
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreengeling.c
2399 lines (2182 loc) · 68.3 KB
/
treengeling.c
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 2010-2020 Armin Biere Johannes Kepler University Linz Austria */
/*-------------------------------------------------------------------------*/
#include "lglib.h"
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
/*------------------------------------------------------------------------*/
#if 0
#define LOG(ARGS) do { printf ("c %s\n", ARGS); fflush (stdout); } while (0)
#else
#define LOG(ARGS...) do { } while (0)
#endif
/*------------------------------------------------------------------------*/
#define NCORES 8
#define CORES2WORKERS(C) (C)
#define ACTIVEPERWORKER 8
#define WORKERS2ACTIVE(W) (ACTIVEPERWORKER*(W))
#define CORES2ACTIVE(C) WORKERS2ACTIVE(CORES2WORKERS(C))
#define MAXGB 12ll
#define MAXBYTES (MAXGB<<30)
#define MINCLIM 1000
#define INITCLIM 10000
#define MAXCLIM 100000
#define STOPLKHDRED 20
#define MAXSTOPLKH 128
#define FULLINT 10
#define ASYMMETRIC 1
#define TREELOOKDEPTH 10
#define FULLSIMP 4
#define FULLSEARCH 2
#define DEFBRANCHES 50
#define OPTIMIZE 10
/*------------------------------------------------------------------------*/
#define NEW(PTR,NUM) \
do { \
size_t BYTES = (NUM) * sizeof *(PTR); \
(PTR) = malloc (BYTES); \
if (!(PTR)) { err ("out of memory"); exit (1); } \
memset ((PTR), 0, BYTES); \
incmem (BYTES); \
} while (0)
#define DEL(PTR,NUM) \
do { \
size_t BYTES = (NUM) * sizeof *(PTR); \
decmem (BYTES); \
free (PTR); \
} while (0)
#define PUSH(STACK,ELEM) \
do { \
if (size ## STACK == num ## STACK) { \
size_t NEW_SIZE = size ## STACK; \
size_t OLD_BYTES = NEW_SIZE * sizeof *STACK, NEW_BYTES; \
if (NEW_SIZE) NEW_SIZE *= 2; else NEW_SIZE = 1; \
NEW_BYTES = NEW_SIZE * sizeof *STACK; \
decmem (OLD_BYTES); \
STACK = realloc (STACK, NEW_BYTES); \
if (!STACK) { err ("out of memory"); exit (1); } \
incmem (NEW_BYTES); \
size ## STACK = NEW_SIZE; \
} \
STACK[num ## STACK ++] = (ELEM); \
} while (0)
#define LL long long
/*------------------------------------------------------------------------*/
typedef enum State {
FREE = 0,
READY = 1,
SIMP = 2,
LKHD = 3,
SPLIT = 4,
SEARCH = 5,
} State;
typedef struct Node {
State state;
int pos, lookahead, depth, res, simplified, consumed;
int64_t id, decisions, conflicts, propagations;
int * cube;
LGL * lgl;
} Node;
typedef struct Leaf {
int64_t id;
struct Leaf * next, * prev;
int * lits;
} Leaf;
typedef struct Parallel {
int64_t decisions, conflicts, propagations;
struct { int64_t leafs, units; } consumed, produced;
int res, nunits, *units;
pthread_t thread;
LGL * lgl;
} Parallel;
typedef struct Job {
int pos;
State state;
Node * node;
void * (*fun)(void *);
pthread_t thread;
const char * name;
} Job;
typedef struct Lock {
pthread_mutex_t mutex;
int locked, waited;
} Lock;
/*------------------------------------------------------------------------*/
static int verbose, balance, showstats, nowitness, ncores, randswap;
static int treelookdepth, treelookdepthset, locslkhd, relevancelkhd = 1;
static int reducecache, nosimp, forcesimp, nosearch, noparallel;
static int fullint = FULLINT, asymmetric = ASYMMETRIC, eager = 1;
static int splitsuccessful = 1, branches = -1, portfolio = 0;
static int optimize = -1;
static int clim, newclim, forcedclim, thisclim, initclim, maxclim, minclim;
static int nvars, nclauses;
static LGL * root;
static Node ** nodes;
static int numnodes, maxnumnodes, sizenodes;
static int rootconsumed;
static Parallel parallel;
static int nparallel;
static int maxactive, firstosplit, numtosplit, lastosplit;
static int maxworkers, maxworkers2, numworkers, maxnumworkers;
static Job ** jobs;
static int numjobs, sizejobs;
static struct { int64_t cnt, lkhd, split, simp, search; } js;
static int64_t totalkhd, treelkhd;
static int64_t * confstack;
static int numconfstack, sizeconfstack;
static const char * fname;
static FILE * file;
static int lineno;
size_t maxbytes, hardlimbytes, softlimbytes, splitlimbytes, currentbytes;
static int64_t ids, threads, conflicts, decisions, propagations;
static int64_t sumclims, inclims, declims, forcedclims, sumsimplified;
static struct { double epoch, simp, lkhd, split, search; } wct;
static int round, started, deleted, simplified, added;
static double * startimeptr, startime;
static struct { int64_t set, def; } opts;
struct { int num, max; int64_t count; Leaf * first, * last; } leafs;
static int done, stop;
static struct { unsigned z, w; } rng;
static struct {
Lock confs;
Lock done;
Lock leafs;
Lock mem;
Lock msg;
Lock nodes;
Lock opts;
Lock parleafs;
Lock parstats;
Lock parunits;
Lock simplified;
Lock stats;
Lock workers;
} lock;
static pthread_cond_t workerscond;
/*------------------------------------------------------------------------*/
static double currentime () {
double res = 0;
struct timeval tv;
if (!gettimeofday (&tv, 0))
res = 1e-6 * tv.tv_usec, res += tv.tv_sec;
return res;
}
static double getime () { return currentime () - wct.epoch; }
static void warn (const char * fmt, ...) {
va_list ap;
fputs ("c *** warning *** ", stdout);
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
fputc ('\n', stdout);
fflush (stdout);
}
static void startimer (double * timptr) {
assert (!started);
startimeptr = timptr;
startime = currentime ();
started = 1;
}
static double deltatime (double start) {
double res = currentime () - start;
if (res < 0) res = -res;
return res;
}
static double stoptimer () {
double * ptr, res = deltatime (startime);
assert (started);
assert (startimeptr);
started = 0;
if ((ptr = startimeptr)) *ptr += res;
startimeptr = 0;
return res;
}
/*------------------------------------------------------------------------*/
static void lockgen (Lock * lock, const char * name) {
if (pthread_mutex_lock (&lock->mutex))
warn ("failed to lock '%s' mutex", name);
assert (!lock->locked || lock->waited);
lock->locked++;
}
static void unlockgen (Lock *lock, const char * name) {
assert (lock->locked > 0 || lock->waited);
lock->locked--;
if (pthread_mutex_unlock (&lock->mutex))
warn ("failed to lock '%s' mutex", name);
}
#define LOCK(NAME) \
static void lock ## NAME () { \
lockgen (&lock.NAME, # NAME); \
}
#define UNLOCK(NAME) \
static void unlock ## NAME () { \
unlockgen (&lock.NAME, # NAME); \
}
LOCK (confs)
LOCK (done)
LOCK (leafs)
LOCK (mem)
LOCK (msg)
LOCK (nodes)
LOCK (opts)
LOCK (parleafs)
LOCK (parstats)
LOCK (parunits)
LOCK (simplified)
LOCK (stats)
LOCK (workers)
UNLOCK (confs)
UNLOCK (done)
UNLOCK (leafs)
UNLOCK (mem)
UNLOCK (msg)
UNLOCK (nodes)
UNLOCK (opts)
UNLOCK (parleafs)
UNLOCK (parstats)
UNLOCK (parunits)
UNLOCK (simplified)
UNLOCK (stats)
UNLOCK (workers)
/*------------------------------------------------------------------------*/
static void err (const char * fmt, ...) {
va_list ap;
lockmsg ();
fputs ("c *** ", stdout);
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
fputc ('\n', stdout);
fflush (stdout);
unlockmsg ();
exit (1);
}
static void smsg () {
double t = getime (), m;
lockmem ();
m = currentbytes/(double)(1<<20);
unlockmem ();
printf (
"(%.1f %d %lld %d %d %.0f) ",
t, round, (LL) ids, numnodes, clim, m);
}
static void msg (const char * fmt, ...) {
va_list ap;
lockmsg ();
fputs ("c ", stdout);
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
fputc ('\n', stdout);
fflush (stdout);
unlockmsg ();
}
static void vrb (const char * fmt, ...) {
va_list ap;
if (!verbose) return;
lockmsg ();
fputs ("c ", stdout);
smsg ();
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
fputc ('\n', stdout);
fflush (stdout);
unlockmsg ();
}
static void nmsg (Node * node, const char * fmt, ...) {
va_list ap;
if (!verbose) return;
lockmsg ();
printf ("c [%d %lld] ", node->depth, (LL) node->id);
smsg ();
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
fputc ('\n', stdout);
fflush (stdout);
unlockmsg ();
}
static void jmsg (Job * job, const char * msg) {
Node * node = job->node;
if (!verbose) return;
lockmsg ();
printf ("c [%d %lld] ", node->depth, (LL) node->id);
smsg ();
printf ("%s %s job %d\n", msg, job->name, job->pos);
fflush (stdout);
unlockmsg ();
}
static void mmsg (const char * msg, Node * node) {
if (!verbose) return;
lockmsg ();
printf ("c ");
smsg ();
printf ("%s [%d %lld]\n",
msg, node->depth, (LL) node->id);
fflush (stdout);
unlockmsg ();
}
static void perr (const char * fmt, ...) {
va_list ap;
printf ("c *** parse error in '%s' at line %d: ", fname, lineno);
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
fputc ('\n', stdout);
fflush (stdout);
exit (1);
}
static int skipnode (Node * node) {
assert (node->state != FREE);
if (lglinconsistent (node->lgl)) return 1;
return 0;
}
static void incround () {
round++;
vrb ("");
vrb ("=================== [ round %d ] ===================", round);
vrb ("");
}
static void startphase (const char * phase) {
if (!verbose) return;
vrb ("");
vrb ("------------------- [ %s %d ] -------------------", phase, round);
vrb ("");
}
/*------------------------------------------------------------------------*/
static double avg (double a, double b) { return b > 0 ? a/b : 0.0; }
static double pcnt (double a, double b) { return avg (100.0 * a, b); }
/*------------------------------------------------------------------------*/
static void incmem (size_t bytes) {
lockmem ();
currentbytes += bytes;
if (currentbytes > maxbytes) maxbytes = currentbytes;
unlockmem ();
}
static void decmem (size_t bytes) {
lockmem ();
assert (currentbytes >= bytes);
currentbytes -= bytes;
unlockmem ();
}
static void * alloc (void * dummy, size_t bytes) {
char * res;
NEW (res, bytes);
(void) dummy;
return res;
}
static void dealloc (void * dummy, void * void_ptr, size_t bytes) {
char * char_ptr = void_ptr;
DEL (char_ptr, bytes);
(void) dummy;
}
static void * resize (void * dummy, void * ptr,
size_t old_bytes, size_t new_bytes) {
lockmem ();
assert (currentbytes >= old_bytes);
currentbytes -= old_bytes;
currentbytes += new_bytes;
if (currentbytes > maxbytes) maxbytes = currentbytes;
unlockmem ();
(void) dummy;
return realloc (ptr, new_bytes);
}
static int64_t getotalmem (int explain) {
long long res;
FILE * p = popen ("grep MemTotal /proc/meminfo", "r");
if (p && fscanf (p, "MemTotal: %lld kB", &res) == 1) {
if (explain)
msg ("%lld KB total memory according to '/proc/meminfo'", res);
res <<= 10;
} else {
res = MAXGB << 30;
if (explain)
msg ("assuming compiled in memory size of %d GB", MAXGB);
}
if (p) pclose (p);
return (int64_t) res;
}
static int getcores (int explain) {
int syscores, coreids, physids, procpuinfocores;
int usesyscores, useprocpuinfo, amd, intel, res;
FILE * p;
syscores = sysconf (_SC_NPROCESSORS_ONLN);
if (explain) {
if (syscores > 0)
msg ("'sysconf' reports %d processors online", syscores);
else
msg ("'sysconf' fails to determine number of online processors");
}
p = popen ("grep '^core id' /proc/cpuinfo 2>/dev/null|sort|uniq|wc -l", "r");
if (p) {
if (fscanf (p, "%d", &coreids) != 1) coreids = 0;
if (explain) {
if (coreids > 0)
msg ("found %d unique core ids in '/proc/cpuinfo'", coreids);
else
msg ("failed to extract core ids from '/proc/cpuinfo'");
}
pclose (p);
} else coreids = 0;
p = popen (
"grep '^physical id' /proc/cpuinfo 2>/dev/null|sort|uniq|wc -l", "r");
if (p) {
if (fscanf (p, "%d", &physids) != 1) physids = 0;
if (explain) {
if (physids > 0)
msg ("found %d unique physical ids in '/proc/cpuinfo'",
physids);
else
msg ("failed to extract physical ids from '/proc/cpuinfo'");
}
pclose (p);
} else physids = 0;
if (coreids > 0 && physids > 0 &&
(procpuinfocores = coreids * physids) > 0) {
if (explain)
msg ("%d cores = %d core times %d physical ids in '/proc/cpuinfo'",
procpuinfocores, coreids, physids);
} else procpuinfocores = 0;
usesyscores = useprocpuinfo = 0;
if (procpuinfocores > 0 && procpuinfocores == syscores) {
if (explain) msg ("'sysconf' and '/proc/cpuinfo' results match");
usesyscores = 1;
} else if (procpuinfocores > 0 && syscores <= 0) {
if (explain) msg ("only '/proc/cpuinfo' result valid");
useprocpuinfo = 1;
} else if (procpuinfocores <= 0 && syscores > 0) {
if (explain) msg ("only 'sysconf' result valid");
usesyscores = 1;
} else if (procpuinfocores > 0 && syscores > 0) {
intel = !system ("grep vendor /proc/cpuinfo 2>/dev/null|grep -q Intel");
if (intel && explain)
msg ("found Intel as vendor in '/proc/cpuinfo'");
amd = !system ("grep vendor /proc/cpuinfo 2>/dev/null|grep -q AMD");
if (amd && explain)
msg ("found AMD as vendor in '/proc/cpuinfo'");
assert (syscores > 0);
assert (procpuinfocores > 0);
assert (syscores != procpuinfocores);
if (amd) {
if (explain) msg ("trusting 'sysconf' on AMD");
usesyscores = 1;
} else if (intel) {
if (explain) {
msg ("'sysconf' result off by a factor of %f on Intel",
syscores / (double) procpuinfocores);
msg ("trusting 'sysconf' on Intel (assuming HyperThreading)");
}
usesyscores = 1;
} else {
if (explain)
msg ("trusting 'sysconf' on unknown vendor machine");
usesyscores = 1;
}
}
if (useprocpuinfo) {
if (explain)
msg ("assuming cores = core * physical ids in '/proc/cpuinfo' = %d",
procpuinfocores);
res = procpuinfocores;
} else if (usesyscores) {
if (explain)
msg (
"assuming cores = number of processors reported by 'sysconf' = %d",
syscores);
res = syscores;
} else {
if (explain)
msg ("using compiled in default value of assumed %d cores", NCORES);
res = NCORES;
}
return res;
}
static void usage () {
int64_t b = getotalmem (0);
long long m = ((b+(1<<20)-1) >> 20), g = ((b+(1<<30)-1) >> 30);
int c = getcores (0);
printf (
"usage: treengeling [<option> ...] [<file> [<workers>]]\n"
"\n"
"where <option> is one of the following\n"
"\n"
" -h print option summary\n"
" --version print version and exit\n"
" -v increase verbose level\n"
" -S print statistics for each solver instance too\n"
" -n do not print satisfying assignments\n"
"\n"
" -t <workers> maximum number actual worker threads (system default %d)\n"
" -a <nodes> maximum number active nodes (system default %d)\n"
"\n"
" -m <mb> assumed memory in mega bytes (system default %lld MB)\n"
" -g <gb> assumed memory in giga bytes (system default %lld GB)\n"
"\n"
" -r <posnum> randomize splits by swapping <posnum> nodes\n"
" -s <seed> unsigned 64 bit seed for randomizing splits (default 0)\n"
"\n"
" -b <branches> percentage of nodes split (default %d%%)\n"
"\n"
" --balance split larger nodes first\n"
" --symmetric symmetric splitting%s\n"
" --asymmetric asymmetric splitting%s\n"
" --eager eager splitting by forced reduction of limit (default)\n"
" --lazy disable eager splitting (opposite of '--eager')\n"
" --portfolio use portfolio style option fuzzing (default off)\n"
"\n"
" --locslkhd use local searchf or look-ahead\n"
" --no-relevancelkhd do not use relevance (VSIDS/VMTF) look-ahead\n"
" --treelook=<d> maximum depth for tree-based look-ahead (default %d)\n"
"\n"
" --min=<lim> minimum conflict limit per search (compiled default %d)\n"
" --init=<lim> initial conflict limit per search (compiled default %d)\n"
" --max=<lim> maximum conflict limit per search (compiled default %d)\n"
"\n"
" --reduce reduce learned clause cache for all right branches\n"
" --force-simp force simplification even after light simplification\n"
" --no-simp do not explicitly simplify in each round\n"
" --no-search do not even search in each round\n"
" --no-parallel disable additional parallel solver instance\n"
" --no-full no full rounds every %d rounds\n"
" -f <fullint> full round interval (default %d)\n"
"\n"
"and the <file> is a DIMACS file. If the name of the file has a '.gz'\n"
"respectively '.bz2' suffix, it is assumed to be a file compressed with\n"
"'gzip' respectively 'bzip2'. In this case the parser will open a pipe\n"
"and execute 'gunzip' respectively 'bzcat'.\n",
CORES2WORKERS (c),
CORES2ACTIVE (c),
m,
g,
DEFBRANCHES,
ASYMMETRIC ? "" : " (default)",
ASYMMETRIC ? " (default)" : "",
TREELOOKDEPTH,
MINCLIM,
INITCLIM,
MAXCLIM,
FULLINT,
FULLINT);
fflush (stdout);
exit (0);
}
static void version () { printf ("%s\n", lglversion ()); exit (0); }
static int next () {
int res = getc (file);
if (res == '\n') lineno++;
return res;
}
static int ws (int ch) {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
}
static void parse (LGL * lgl) {
int sclauses, ch, sign, lit, last, nlits;
lineno = 1;
HEADER:
if ((ch = next ()) == EOF) perr ("unexpected end-of-file before header");
if (ch == 'c') {
while ((ch = next ()) != '\n')
if (ch == EOF) perr ("unexpected end-of-file in header comment");
goto HEADER;
}
if (ch != 'p') perr ("unexpected character 0x%02x in header", ch);
if ((fscanf (file, " cnf %d %d", &nvars, &sclauses)) != 2 ||
nvars < 0 || sclauses < 0)
perr ("invalid header");
msg ("found 'p cnf %d %d' header", nvars, sclauses);
nlits = last = 0;
BODY:
ch = next ();
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') goto BODY;
if (ch == EOF) {
if (last) perr ("zero missing after %d in last clause", last);
if (nclauses < sclauses) perr ("%d clauses missing", sclauses - nclauses);
msg ("parsed %d literals in %d clauses in %.2f seconds",
nlits, nclauses, getime ());
return;
}
if (ch == 'c') {
while ((ch = next ()) != '\n')
if (ch == EOF) perr ("unexpected end-of-file in body comment");
goto BODY;
}
sign = 1;
if (ch == '-') {
if (!isdigit (ch = next ())) perr ("expected digit after '-'");
sign = -1;
} else if (!isdigit (ch)) perr ("expected digit or '-'");
lit = ch - '0';
while (isdigit (ch = next ()))
lit = 10*lit + (ch - '0');
if (lit > nvars) perr ("variable %d exceeds maximum %d", lit, nvars);
assert (nclauses <= sclauses);
if (nclauses == sclauses) perr ("too many clauses");
if (lit) lit *= sign, nlits++; else nclauses++;
if (ch != EOF && !ws (ch)) perr ("expected white space after %d", lit);
lgladd (lgl, lit);
last = lit;
goto BODY;
}
static int isnum (const char * str) {
const char * p = str;
if (!isdigit ((int)*p)) return 0;
while (*++p) if (!isdigit ((int)*p)) return 0;
return 1;
}
static int exists (const char * str) {
struct stat buf;
return !stat (str, &buf);
}
static int term (void * dummy) {
int res;
assert (!dummy);
lockdone ();
res = done || stop;
unlockdone ();
(void) dummy;
return res;
}
static void produceunit (void * voidptr, int lit) {
assert (!noparallel);
lockparunits ();
assert (parallel.nunits < nvars);
parallel.units[parallel.nunits++] = lit;
parallel.produced.units++;
unlockparunits ();
(void) voidptr;
}
static void consumeunits (void * voidptr, int ** fromptr, int ** toptr) {
int * consumedptr = voidptr, produced, consumed;
assert (fromptr);
assert (toptr);
lockparunits ();
produced = parallel.nunits;
consumed = produced - *consumedptr;
parallel.consumed.units += consumed;
unlockparunits ();
assert (consumed >= 0);
*fromptr = parallel.units + *consumedptr;
*toptr = parallel.units + produced;
*consumedptr = produced;
}
static int intslen (const int * ints) {
const int * p;
for (p = ints; *p; p++)
;
return p - ints;
}
static int * appendint (int * ints, int i) {
int len, * res, * q, other;
const int * p;
assert (ints);
len = intslen (ints) + 1;
NEW (res, len + 1);
q = res;
for (p = ints; (other = *p); p++) *q++ = other;
assert (p - ints == len - 1);
*q++ = i;
assert (q - res == len);
*q++ = 0;
return res;
}
static void addint (int ** intsptr, int i) {
int * oldints = *intsptr, len = intslen (oldints);
const int * p; int * q, o, * newints;
NEW (newints, len + 2);
q = newints;
for (p = oldints; (o = *p); p++) *q++ = o;
*q++ = i;
DEL (oldints, len + 1);
*intsptr = newints;
}
static void cubemsg (Node * node, const char * str) {
const int * p;
if (!verbose) return;
lockmsg ();
printf ("c [%d %lld] ", node->depth, (LL) node->id);
smsg ();
fputs (str, stdout);
if (node->cube) {
for (p = node->cube; *p; p++) printf (" %d", *p);
fputs (" 0", stdout);
} else fputs (" <cube-already-deleted>", stdout);
fputc ('\n', stdout);
fflush (stdout);
unlockmsg ();
}
static void initroot () {
assert (!root);
msg ("initializing root solver instance");
root = lglminit (0, alloc, resize, dealloc);
lglsetopt (root, "druplig", 0);
lglsetopt (root, "classify", 0);
if (verbose) lglsetopt (root, "verbose", verbose);
else if (!showstats) lglsetopt (root, "profile", 0);
lglsetopt (root, "abstime", 1);
lglsetopt (root, "trep", 0);
lglsetopt (root, "compact", 1);
if (!noparallel) {
lglsetopt (root, "bca", 0);
lglseterm (root, term, 0);
lglsetconsumeunits (root, consumeunits, &rootconsumed);
lglsetmsglock (root, lockmsg, unlockmsg, 0);
}
lglsetime (root, getime);
lglsetprefix (root, "c (root) ");
}
static Node * newnode (Node * parent, int decision) {
char prefix[80];
Node * res;
locknodes ();
NEW (res, 1);
assert (res->state == FREE);
res->state = READY;
if (parent) res->depth = parent->depth + 1;
res->id = ids++;
res->pos = numnodes;
PUSH (nodes, res);
if (numnodes > maxnumnodes) maxnumnodes = numnodes;
unlocknodes ();
nmsg (res, "new node");
if (parent) {
res->lgl = lglclone (parent->lgl);
res->decisions = lglgetdecs (res->lgl);
res->conflicts = lglgetconfs (res->lgl);
res->propagations = lglgetprops (res->lgl);
res->consumed = parent->consumed;
res->cube = appendint (parent->cube, decision);
lgladd (res->lgl, decision);
lgladd (res->lgl, 0);
} else {
msg ("forking root solver instance");
NEW (res->cube, 1);
assert (!intslen (res->cube));
assert (root);
res->lgl = lglfork (root);
}
sprintf (prefix, "c (%d %lld) ", res->depth, (LL) res->id);
lglsetprefix (res->lgl, prefix);
lglseterm (res->lgl, term, 0);
lglsetmsglock (res->lgl, lockmsg, unlockmsg, 0);
if (!noparallel) lglsetconsumeunits (res->lgl, consumeunits, &res->consumed);
cubemsg (res, "opened cube");
added++;
return res;
}
static void updstats (Node * node) {
double * ptr, now, delta;
LGL * lgl = node->lgl;
lockstats ();
decisions += lglgetdecs (lgl) - node->decisions;
conflicts += lglgetconfs (lgl) - node->conflicts;
propagations += lglgetprops (lgl) - node->propagations;
if (started && (ptr = startimeptr)) {
now = currentime ();
delta = now - startime;
startime = now;
*ptr += delta;
}
unlockstats ();
}
static void delnode (Node * node) {
Node * last;
int lastpos;
LGL * lgl;
assert (node);
cubemsg (node, "closed cube");
nmsg (node, "delete node");
locknodes (); // TODO why?
assert (0 <= node->pos && node->pos < sizenodes);
assert (nodes[node->pos] == node);
assert (node->state == READY);
assert (numnodes > 0);
lastpos = --numnodes;
last = nodes[lastpos];
assert (last && last->pos == lastpos);
if (node != last) {
assert (node->pos < lastpos);
nodes[node->pos] = last;
last->pos = node->pos;
}
nodes[lastpos] = 0;
unlocknodes (); // TODO why?
lgl = node->lgl;
updstats (node);
node->lgl = 0;
if (node->cube) DEL (node->cube, intslen (node->cube) + 1);
DEL (node, 1);
assert (lgl);
if (showstats) lglstats (lgl);
lglrelease (lgl);
deleted++;
}
/*------------------------------------------------------------------------*/
static void leafmsg (Leaf * leaf, const char * str) {
const int * p;
if (!verbose) return;
lockmsg ();
printf ("c %s leaf %lld clause", str, (LL) leaf->id);
if (leaf->lits) {
for (p = leaf->lits; *p; p++)
printf (" %d", *p);
printf (" 0");
} else fputs (" <literals-already-deleted>", stdout);
fputc ('\n', stdout);
fflush (stdout);
unlockmsg ();
}
static Leaf * newleaf (Node * node) {
int * p, lit;
Leaf * res;
NEW (res, 1);
if (++leafs.num > leafs.max) leafs.max = leafs.num;
res->id = ++leafs.count;
res->lits = node->cube;
node->cube = 0;
for (p = res->lits; (lit = *p); p++) *p = -lit;
leafmsg (res, "new");
return res;
}
static void deleaf (Leaf * leaf) {
leafmsg (leaf, "delete");
if (leaf->lits) DEL (leaf->lits, intslen (leaf->lits) + 1);
DEL (leaf, 1);
assert (leafs.num > 0);
leafs.count--;
}
static void enqleaf (Leaf * leaf) {
leafmsg (leaf, "enqueue");
lockleafs ();
if (leafs.last) leafs.last->next = leaf;
else leafs.first = leaf;
leaf->prev = leafs.last;
leafs.last = leaf;
assert (!leaf->next);
unlockleafs ();
lockparleafs ();
parallel.produced.leafs++;
unlockparleafs ();
}
static Leaf * deqleaf () {
Leaf * res;
lockleafs ();
res = leafs.first;
if (res) {
if (res->next) res->next->prev = 0;
else leafs.last = 0;
leafs.first = res->next;
}
unlockleafs ();
if (res) leafmsg (res, "dequeue");
return res;
}
static void enqnewleafromnode (Node * node) { enqleaf (newleaf (node)); }
/*------------------------------------------------------------------------*/
static int * clausetoconsume;
static void consumecls (void * voidptr, int ** cptr, int * glueptr) {
Leaf * leaf = deqleaf ();
if (leaf) {
if (clausetoconsume)
DEL (clausetoconsume, intslen (clausetoconsume) + 1);
clausetoconsume = leaf->lits;
leaf->lits = 0;
*cptr = clausetoconsume;
*glueptr = 0;
deleaf (leaf);
parallel.consumed.leafs++;
} else *cptr = 0;
(void) voidptr;