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