a2163a0c839103179fc6a31df3608ea71651d8a9
[satune.git] / src / csolver.cc
1 #include "csolver.h"
2 #include "set.h"
3 #include "mutableset.h"
4 #include "element.h"
5 #include "boolean.h"
6 #include "predicate.h"
7 #include "order.h"
8 #include "table.h"
9 #include "function.h"
10 #include "satencoder.h"
11 #include "sattranslator.h"
12 #include "tunable.h"
13 #include "polarityassignment.h"
14 #include "decomposeordertransform.h"
15 #include "autotuner.h"
16 #include "astops.h"
17 #include "structs.h"
18 #include "orderresolver.h"
19 #include "integerencoding.h"
20 #include "qsort.h"
21 #include "preprocess.h"
22 #include "serializer.h"
23 #include "deserializer.h"
24 #include "encodinggraph.h"
25
26 CSolver::CSolver() :
27         boolTrue(BooleanEdge(new BooleanConst(true))),
28         boolFalse(boolTrue.negate()),
29         unsat(false),
30         tuner(NULL),
31         elapsedTime(0)
32 {
33         satEncoder = new SATEncoder(this);
34 }
35
36 /** This function tears down the solver and the entire AST */
37
38 CSolver::~CSolver() {
39         uint size = allBooleans.getSize();
40         for (uint i = 0; i < size; i++) {
41                 delete allBooleans.get(i);
42         }
43
44         size = allSets.getSize();
45         for (uint i = 0; i < size; i++) {
46                 delete allSets.get(i);
47         }
48
49         size = allElements.getSize();
50         for (uint i = 0; i < size; i++) {
51                 delete allElements.get(i);
52         }
53
54         size = allTables.getSize();
55         for (uint i = 0; i < size; i++) {
56                 delete allTables.get(i);
57         }
58
59         size = allPredicates.getSize();
60         for (uint i = 0; i < size; i++) {
61                 delete allPredicates.get(i);
62         }
63
64         size = allOrders.getSize();
65         for (uint i = 0; i < size; i++) {
66                 delete allOrders.get(i);
67         }
68         size = allFunctions.getSize();
69         for (uint i = 0; i < size; i++) {
70                 delete allFunctions.get(i);
71         }
72
73         delete boolTrue.getBoolean();
74         delete satEncoder;
75 }
76
77 CSolver *CSolver::clone() {
78         CSolver *copy = new CSolver();
79         CloneMap map;
80         SetIteratorBooleanEdge *it = getConstraints();
81         while (it->hasNext()) {
82                 BooleanEdge b = it->next();
83                 copy->addConstraint(cloneEdge(copy, &map, b));
84         }
85         delete it;
86         return copy;
87 }
88
89 void CSolver::serialize() {
90         model_print("serializing ...\n");
91         {
92                 Serializer serializer("dump");
93                 SetIteratorBooleanEdge *it = getConstraints();
94                 while (it->hasNext()) {
95                         BooleanEdge b = it->next();
96                         serializeBooleanEdge(&serializer, b);
97                 }
98                 delete it;
99         }
100         model_print("deserializing ...\n");
101         {
102                 Deserializer deserializer("dump");
103                 deserializer.deserialize();
104         }
105 }
106
107 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
108         Set *set = new Set(type, elements, numelements);
109         allSets.push(set);
110         return set;
111 }
112
113 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
114         Set *set = new Set(type, lowrange, highrange);
115         allSets.push(set);
116         return set;
117 }
118
119 VarType CSolver::getSetVarType(Set *set) {
120         return set->getType();
121 }
122
123 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
124         Set *s = createRangeSet(type, lowrange, highrange);
125         return getElementVar(s);
126 }
127
128 MutableSet *CSolver::createMutableSet(VarType type) {
129         MutableSet *set = new MutableSet(type);
130         allSets.push(set);
131         return set;
132 }
133
134 void CSolver::addItem(MutableSet *set, uint64_t element) {
135         set->addElementMSet(element);
136 }
137
138 uint64_t CSolver::createUniqueItem(MutableSet *set) {
139         uint64_t element = set->getNewUniqueItem();
140         set->addElementMSet(element);
141         return element;
142 }
143
144 void CSolver::finalizeMutableSet(MutableSet *set) {
145         set->finalize();
146 }
147
148 Element *CSolver::getElementVar(Set *set) {
149         Element *element = new ElementSet(set);
150         allElements.push(element);
151         return element;
152 }
153
154 Set *CSolver::getElementRange (Element *element) {
155         return element->getRange();
156 }
157
158
159 Element *CSolver::getElementConst(VarType type, uint64_t value) {
160         uint64_t array[] = {value};
161         Set *set = new Set(type, array, 1);
162         Element *element = new ElementConst(value, set);
163         Element *e = elemMap.get(element);
164         if (e == NULL) {
165                 allSets.push(set);
166                 allElements.push(element);
167                 elemMap.put(element, element);
168                 return element;
169         } else {
170                 delete set;
171                 delete element;
172                 return e;
173         }
174 }
175
176
177 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
178         Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
179         Element *e = elemMap.get(element);
180         if (e == NULL) {
181                 element->updateParents();
182                 allElements.push(element);
183                 elemMap.put(element, element);
184                 return element;
185         } else {
186                 delete element;
187                 return e;
188         }
189 }
190
191 Function *CSolver::createFunctionOperator(ArithOp op, Set **domain, uint numDomain, Set *range,OverFlowBehavior overflowbehavior) {
192         Function *function = new FunctionOperator(op, domain, numDomain, range, overflowbehavior);
193         allFunctions.push(function);
194         return function;
195 }
196
197 Predicate *CSolver::createPredicateOperator(CompOp op, Set **domain, uint numDomain) {
198         Predicate *predicate = new PredicateOperator(op, domain,numDomain);
199         allPredicates.push(predicate);
200         return predicate;
201 }
202
203 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
204         Predicate *predicate = new PredicateTable(table, behavior);
205         allPredicates.push(predicate);
206         return predicate;
207 }
208
209 Table *CSolver::createTable(Set **domains, uint numDomain, Set *range) {
210         Table *table = new Table(domains,numDomain,range);
211         allTables.push(table);
212         return table;
213 }
214
215 Table *CSolver::createTableForPredicate(Set **domains, uint numDomain) {
216         return createTable(domains, numDomain, NULL);
217 }
218
219 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
220         table->addNewTableEntry(inputs, inputSize, result);
221 }
222
223 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
224         Function *function = new FunctionTable(table, behavior);
225         allFunctions.push(function);
226         return function;
227 }
228
229 BooleanEdge CSolver::getBooleanVar(VarType type) {
230         Boolean *boolean = new BooleanVar(type);
231         allBooleans.push(boolean);
232         return BooleanEdge(boolean);
233 }
234
235 BooleanEdge CSolver::getBooleanTrue() {
236         return boolTrue;
237 }
238
239 BooleanEdge CSolver::getBooleanFalse() {
240         return boolFalse;
241 }
242
243 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
244         return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
245 }
246
247 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
248         BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
249         Boolean *b = boolMap.get(boolean);
250         if (b == NULL) {
251                 boolean->updateParents();
252                 boolMap.put(boolean, boolean);
253                 allBooleans.push(boolean);
254                 return BooleanEdge(boolean);
255         } else {
256                 delete boolean;
257                 return BooleanEdge(b);
258         }
259 }
260
261 bool CSolver::isTrue(BooleanEdge b) {
262         return b.isNegated() ? b->isFalse() : b->isTrue();
263 }
264
265 bool CSolver::isFalse(BooleanEdge b) {
266         return b.isNegated() ? b->isTrue() : b->isFalse();
267 }
268
269 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
270         BooleanEdge array[] = {arg1, arg2};
271         return applyLogicalOperation(op, array, 2);
272 }
273
274 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
275         BooleanEdge array[] = {arg};
276         return applyLogicalOperation(op, array, 1);
277 }
278
279 static int ptrcompares(const void *p1, const void *p2) {
280         uintptr_t b1 = *(uintptr_t const *) p1;
281         uintptr_t b2 = *(uintptr_t const *) p2;
282         if (b1 < b2)
283                 return -1;
284         else if (b1 == b2)
285                 return 0;
286         else
287                 return 1;
288 }
289
290 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
291         BooleanEdge newarray[asize];
292         memcpy(newarray, array, asize * sizeof(BooleanEdge));
293         for (uint i = 0; i < asize; i++) {
294                 BooleanEdge b = newarray[i];
295                 if (b->type == LOGICOP) {
296                         if (((BooleanLogic *) b.getBoolean())->replaced) {
297                                 newarray[i] = doRewrite(newarray[i]);
298                                 i--;//Check again
299                         }
300                 }
301         }
302         return applyLogicalOperation(op, newarray, asize);
303 }
304
305 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
306         BooleanEdge newarray[asize];
307         switch (op) {
308         case SATC_NOT: {
309                 return array[0].negate();
310         }
311         case SATC_IFF: {
312                 for (uint i = 0; i < 2; i++) {
313                         if (isTrue(array[i])) { // It can be undefined
314                                 return array[1 - i];
315                         } else if (isFalse(array[i])) {
316                                 newarray[0] = array[1 - i];
317                                 return applyLogicalOperation(SATC_NOT, newarray, 1);
318                         } else if (array[i]->type == LOGICOP) {
319                                 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
320                                 if (b->replaced) {
321                                         return rewriteLogicalOperation(op, array, asize);
322                                 }
323                         }
324                 }
325                 break;
326         }
327         case SATC_OR: {
328                 for (uint i = 0; i < asize; i++) {
329                         newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
330                 }
331                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
332         }
333         case SATC_AND: {
334                 uint newindex = 0;
335                 for (uint i = 0; i < asize; i++) {
336                         BooleanEdge b = array[i];
337                         if (b->type == LOGICOP) {
338                                 if (((BooleanLogic *)b.getBoolean())->replaced)
339                                         return rewriteLogicalOperation(op, array, asize);
340                         }
341                         if (isTrue(b))
342                                 continue;
343                         else if (isFalse(b)) {
344                                 return boolFalse;
345                         } else
346                                 newarray[newindex++] = b;
347                 }
348                 if (newindex == 0) {
349                         return boolTrue;
350                 } else if (newindex == 1) {
351                         return newarray[0];
352                 } else {
353                         bsdqsort(newarray, newindex, sizeof(BooleanEdge), ptrcompares);
354                         array = newarray;
355                         asize = newindex;
356                 }
357                 break;
358         }
359         case SATC_XOR: {
360                 //handle by translation
361                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
362         }
363         case SATC_IMPLIES: {
364                 //handle by translation
365                 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
366         }
367         }
368
369         ASSERT(asize != 0);
370         Boolean *boolean = new BooleanLogic(this, op, array, asize);
371         Boolean *b = boolMap.get(boolean);
372         if (b == NULL) {
373                 boolean->updateParents();
374                 boolMap.put(boolean, boolean);
375                 allBooleans.push(boolean);
376                 return BooleanEdge(boolean);
377         } else {
378                 delete boolean;
379                 return BooleanEdge(b);
380         }
381 }
382
383 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
384         //      ASSERT(first != second);
385         if (first == second)
386                 return getBooleanFalse();
387
388         bool negate = false;
389         if (order->type == SATC_TOTAL) {
390                 if (first > second) {
391                         uint64_t tmp = first;
392                         first = second;
393                         second = tmp;
394                         negate = true;
395                 }
396         }
397         Boolean *constraint = new BooleanOrder(order, first, second);
398         Boolean *b = boolMap.get(constraint);
399
400         if (b == NULL) {
401                 allBooleans.push(constraint);
402                 boolMap.put(constraint, constraint);
403                 constraint->updateParents();
404         } else {
405                 delete constraint;
406                 constraint = b;
407         }
408
409         BooleanEdge be = BooleanEdge(constraint);
410         return negate ? be.negate() : be;
411 }
412
413 void CSolver::addConstraint(BooleanEdge constraint) {
414         if (isTrue(constraint))
415                 return;
416         else if (isFalse(constraint)) {
417                 int t = 0;
418                 setUnSAT();
419         }
420         else {
421                 if (constraint->type == LOGICOP) {
422                         BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
423                         if (!constraint.isNegated()) {
424                                 if (b->op == SATC_AND) {
425                                         for (uint i = 0; i < b->inputs.getSize(); i++) {
426                                                 addConstraint(b->inputs.get(i));
427                                         }
428                                         return;
429                                 }
430                         }
431                         if (b->replaced) {
432                                 addConstraint(doRewrite(constraint));
433                                 return;
434                         }
435                 }
436                 constraints.add(constraint);
437                 Boolean *ptr = constraint.getBoolean();
438
439                 if (ptr->boolVal == BV_UNSAT) {
440                         setUnSAT();
441                 }
442
443                 replaceBooleanWithTrueNoRemove(constraint);
444                 constraint->parents.clear();
445         }
446 }
447
448 Order *CSolver::createOrder(OrderType type, Set *set) {
449         Order *order = new Order(type, set);
450         allOrders.push(order);
451         activeOrders.add(order);
452         return order;
453 }
454
455 int CSolver::solve() {
456         bool deleteTuner = false;
457         if (tuner == NULL) {
458                 tuner = new DefaultTuner();
459                 deleteTuner = true;
460         }
461
462         long long startTime = getTimeNano();
463         computePolarities(this);
464
465         Preprocess pp(this);
466         pp.doTransform();
467
468         DecomposeOrderTransform dot(this);
469         dot.doTransform();
470
471         //IntegerEncodingTransform iet(this);
472         //iet.doTransform();
473
474         //EncodingGraph eg(this);
475         //eg.buildGraph();
476         //eg.encode();
477         //printConstraints();
478         naiveEncodingDecision(this);
479         satEncoder->encodeAllSATEncoder(this);
480         model_print("Is problem UNSAT after encoding: %d\n", unsat);
481         int result = unsat ? IS_UNSAT : satEncoder->solve();
482         model_print("Result Computed in CSolver: %d\n", result);
483         long long finishTime = getTimeNano();
484         elapsedTime = finishTime - startTime;
485         if (deleteTuner) {
486                 delete tuner;
487                 tuner = NULL;
488         }
489         return result;
490 }
491
492 void CSolver::printConstraints() {
493         SetIteratorBooleanEdge *it = getConstraints();
494         while (it->hasNext()) {
495                 BooleanEdge b = it->next();
496                 if (b.isNegated())
497                         model_print("!");
498                 b->print();
499                 model_print("\n");
500         }
501         delete it;
502
503 }
504
505 void CSolver::printConstraint(BooleanEdge b) {
506         if (b.isNegated())
507                 model_print("!");
508         b->print();
509         model_print("\n");
510 }
511
512 uint64_t CSolver::getElementValue(Element *element) {
513         switch (element->type) {
514         case ELEMSET:
515         case ELEMCONST:
516         case ELEMFUNCRETURN:
517                 return getElementValueSATTranslator(this, element);
518         default:
519                 ASSERT(0);
520         }
521         exit(-1);
522 }
523
524 bool CSolver::getBooleanValue(BooleanEdge bedge) {
525         Boolean *boolean = bedge.getBoolean();
526         switch (boolean->type) {
527         case BOOLEANVAR:
528                 return getBooleanVariableValueSATTranslator(this, boolean);
529         default:
530                 ASSERT(0);
531         }
532         exit(-1);
533 }
534
535 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
536         return order->encoding.resolver->resolveOrder(first, second);
537 }
538
539 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
540
541 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
542
543 void CSolver::autoTune(uint budget) {
544         AutoTuner *autotuner = new AutoTuner(budget);
545         autotuner->addProblem(this);
546         autotuner->tune();
547         delete autotuner;
548 }