533fc4b8dfd0023c3b66498c898599056fb7b2c4
[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 #include <time.h>
26
27 CSolver::CSolver() :
28         boolTrue(BooleanEdge(new BooleanConst(true))),
29         boolFalse(boolTrue.negate()),
30         unsat(false),
31         tuner(NULL),
32         elapsedTime(0)
33 {
34         satEncoder = new SATEncoder(this);
35 }
36
37 /** This function tears down the solver and the entire AST */
38
39 CSolver::~CSolver() {
40         uint size = allBooleans.getSize();
41         for (uint i = 0; i < size; i++) {
42                 delete allBooleans.get(i);
43         }
44
45         size = allSets.getSize();
46         for (uint i = 0; i < size; i++) {
47                 delete allSets.get(i);
48         }
49
50         size = allElements.getSize();
51         for (uint i = 0; i < size; i++) {
52                 Element* el = allElements.get(i);
53                 delete el;
54         }
55
56         size = allTables.getSize();
57         for (uint i = 0; i < size; i++) {
58                 delete allTables.get(i);
59         }
60
61         size = allPredicates.getSize();
62         for (uint i = 0; i < size; i++) {
63                 delete allPredicates.get(i);
64         }
65
66         size = allOrders.getSize();
67         for (uint i = 0; i < size; i++) {
68                 delete allOrders.get(i);
69         }
70         size = allFunctions.getSize();
71         for (uint i = 0; i < size; i++) {
72                 delete allFunctions.get(i);
73         }
74
75         delete boolTrue.getBoolean();
76         delete satEncoder;
77 }
78
79 CSolver *CSolver::clone() {
80         CSolver *copy = new CSolver();
81         CloneMap map;
82         SetIteratorBooleanEdge *it = getConstraints();
83         while (it->hasNext()) {
84                 BooleanEdge b = it->next();
85                 copy->addConstraint(cloneEdge(copy, &map, b));
86         }
87         delete it;
88         return copy;
89 }
90
91 CSolver* CSolver::deserialize(const char * file){
92         model_print("deserializing ...\n");
93         Deserializer deserializer(file);
94         return deserializer.deserialize();
95 }
96
97 void CSolver::serialize() {
98         model_print("serializing ...\n");
99         char buffer[255];
100         struct timespec t;
101         clock_gettime(CLOCK_REALTIME, &t);
102
103         unsigned long long nanotime=t.tv_sec*1000000000+t.tv_nsec;
104         int numchars=sprintf(buffer, "DUMP%llu", nanotime);
105         Serializer serializer(buffer);
106         SetIteratorBooleanEdge *it = getConstraints();
107         while (it->hasNext()) {
108                 BooleanEdge b = it->next();
109                 serializeBooleanEdge(&serializer, b, true);
110         }
111         delete it;
112 }
113
114 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
115         Set *set = new Set(type, elements, numelements);
116         allSets.push(set);
117         return set;
118 }
119
120 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
121         Set *set = new Set(type, lowrange, highrange);
122         allSets.push(set);
123         return set;
124 }
125
126 VarType CSolver::getSetVarType(Set *set) {
127         return set->getType();
128 }
129
130 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
131         Set *s = createRangeSet(type, lowrange, highrange);
132         return getElementVar(s);
133 }
134
135 MutableSet *CSolver::createMutableSet(VarType type) {
136         MutableSet *set = new MutableSet(type);
137         allSets.push(set);
138         return set;
139 }
140
141 void CSolver::addItem(MutableSet *set, uint64_t element) {
142         set->addElementMSet(element);
143 }
144
145 uint64_t CSolver::createUniqueItem(MutableSet *set) {
146         uint64_t element = set->getNewUniqueItem();
147         set->addElementMSet(element);
148         return element;
149 }
150
151 void CSolver::finalizeMutableSet(MutableSet *set) {
152         set->finalize();
153 }
154
155 Element *CSolver::getElementVar(Set *set) {
156         Element *element = new ElementSet(set);
157         allElements.push(element);
158         return element;
159 }
160
161 Set *CSolver::getElementRange (Element *element) {
162         return element->getRange();
163 }
164
165
166 Element *CSolver::getElementConst(VarType type, uint64_t value) {
167         uint64_t array[] = {value};
168         Set *set = new Set(type, array, 1);
169         Element *element = new ElementConst(value, set);
170         Element *e = elemMap.get(element);
171         if (e == NULL) {
172                 allSets.push(set);
173                 allElements.push(element);
174                 elemMap.put(element, element);
175                 return element;
176         } else {
177                 delete set;
178                 delete element;
179                 return e;
180         }
181 }
182
183
184 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
185         Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
186         Element *e = elemMap.get(element);
187         if (e == NULL) {
188                 element->updateParents();
189                 allElements.push(element);
190                 elemMap.put(element, element);
191                 return element;
192         } else {
193                 delete element;
194                 return e;
195         }
196 }
197
198 Function *CSolver::createFunctionOperator(ArithOp op, Set **domain, uint numDomain, Set *range,OverFlowBehavior overflowbehavior) {
199         Function *function = new FunctionOperator(op, domain, numDomain, range, overflowbehavior);
200         allFunctions.push(function);
201         return function;
202 }
203
204 Predicate *CSolver::createPredicateOperator(CompOp op, Set **domain, uint numDomain) {
205         Predicate *predicate = new PredicateOperator(op, domain,numDomain);
206         allPredicates.push(predicate);
207         return predicate;
208 }
209
210 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
211         Predicate *predicate = new PredicateTable(table, behavior);
212         allPredicates.push(predicate);
213         return predicate;
214 }
215
216 Table *CSolver::createTable(Set **domains, uint numDomain, Set *range) {
217         Table *table = new Table(domains,numDomain,range);
218         allTables.push(table);
219         return table;
220 }
221
222 Table *CSolver::createTableForPredicate(Set **domains, uint numDomain) {
223         return createTable(domains, numDomain, NULL);
224 }
225
226 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
227         table->addNewTableEntry(inputs, inputSize, result);
228 }
229
230 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
231         Function *function = new FunctionTable(table, behavior);
232         allFunctions.push(function);
233         return function;
234 }
235
236 BooleanEdge CSolver::getBooleanVar(VarType type) {
237         Boolean *boolean = new BooleanVar(type);
238         allBooleans.push(boolean);
239         return BooleanEdge(boolean);
240 }
241
242 BooleanEdge CSolver::getBooleanTrue() {
243         return boolTrue;
244 }
245
246 BooleanEdge CSolver::getBooleanFalse() {
247         return boolFalse;
248 }
249
250 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
251         return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
252 }
253
254 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
255         BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
256         Boolean *b = boolMap.get(boolean);
257         if (b == NULL) {
258                 boolean->updateParents();
259                 boolMap.put(boolean, boolean);
260                 allBooleans.push(boolean);
261                 return BooleanEdge(boolean);
262         } else {
263                 delete boolean;
264                 return BooleanEdge(b);
265         }
266 }
267
268 bool CSolver::isTrue(BooleanEdge b) {
269         return b.isNegated() ? b->isFalse() : b->isTrue();
270 }
271
272 bool CSolver::isFalse(BooleanEdge b) {
273         return b.isNegated() ? b->isTrue() : b->isFalse();
274 }
275
276 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
277         BooleanEdge array[] = {arg1, arg2};
278         return applyLogicalOperation(op, array, 2);
279 }
280
281 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
282         BooleanEdge array[] = {arg};
283         return applyLogicalOperation(op, array, 1);
284 }
285
286 static int ptrcompares(const void *p1, const void *p2) {
287         uintptr_t b1 = *(uintptr_t const *) p1;
288         uintptr_t b2 = *(uintptr_t const *) p2;
289         if (b1 < b2)
290                 return -1;
291         else if (b1 == b2)
292                 return 0;
293         else
294                 return 1;
295 }
296
297 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
298         BooleanEdge newarray[asize];
299         memcpy(newarray, array, asize * sizeof(BooleanEdge));
300         for (uint i = 0; i < asize; i++) {
301                 BooleanEdge b = newarray[i];
302                 if (b->type == LOGICOP) {
303                         if (((BooleanLogic *) b.getBoolean())->replaced) {
304                                 newarray[i] = doRewrite(newarray[i]);
305                                 i--;//Check again
306                         }
307                 }
308         }
309         return applyLogicalOperation(op, newarray, asize);
310 }
311
312 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
313         BooleanEdge newarray[asize];
314         switch (op) {
315         case SATC_NOT: {
316                 return array[0].negate();
317         }
318         case SATC_IFF: {
319                 for (uint i = 0; i < 2; i++) {
320                         if (isTrue(array[i])) { // It can be undefined
321                                 return array[1 - i];
322                         } else if (isFalse(array[i])) {
323                                 newarray[0] = array[1 - i];
324                                 return applyLogicalOperation(SATC_NOT, newarray, 1);
325                         } else if (array[i]->type == LOGICOP) {
326                                 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
327                                 if (b->replaced) {
328                                         return rewriteLogicalOperation(op, array, asize);
329                                 }
330                         }
331                 }
332                 break;
333         }
334         case SATC_OR: {
335                 for (uint i = 0; i < asize; i++) {
336                         newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
337                 }
338                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
339         }
340         case SATC_AND: {
341                 uint newindex = 0;
342                 for (uint i = 0; i < asize; i++) {
343                         BooleanEdge b = array[i];
344                         if (b->type == LOGICOP) {
345                                 if (((BooleanLogic *)b.getBoolean())->replaced)
346                                         return rewriteLogicalOperation(op, array, asize);
347                         }
348                         if (isTrue(b))
349                                 continue;
350                         else if (isFalse(b)) {
351                                 return boolFalse;
352                         } else
353                                 newarray[newindex++] = b;
354                 }
355                 if (newindex == 0) {
356                         return boolTrue;
357                 } else if (newindex == 1) {
358                         return newarray[0];
359                 } else {
360                         bsdqsort(newarray, newindex, sizeof(BooleanEdge), ptrcompares);
361                         array = newarray;
362                         asize = newindex;
363                 }
364                 break;
365         }
366         case SATC_XOR: {
367                 //handle by translation
368                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
369         }
370         case SATC_IMPLIES: {
371                 //handle by translation
372                 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
373         }
374         }
375
376         ASSERT(asize != 0);
377         Boolean *boolean = new BooleanLogic(this, op, array, asize);
378         Boolean *b = boolMap.get(boolean);
379         if (b == NULL) {
380                 boolean->updateParents();
381                 boolMap.put(boolean, boolean);
382                 allBooleans.push(boolean);
383                 return BooleanEdge(boolean);
384         } else {
385                 delete boolean;
386                 return BooleanEdge(b);
387         }
388 }
389
390 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
391         //      ASSERT(first != second);
392         if (first == second)
393                 return getBooleanFalse();
394
395         bool negate = false;
396         if (order->type == SATC_TOTAL) {
397                 if (first > second) {
398                         uint64_t tmp = first;
399                         first = second;
400                         second = tmp;
401                         negate = true;
402                 }
403         }
404         Boolean *constraint = new BooleanOrder(order, first, second);
405         Boolean *b = boolMap.get(constraint);
406
407         if (b == NULL) {
408                 allBooleans.push(constraint);
409                 boolMap.put(constraint, constraint);
410                 constraint->updateParents();
411         } else {
412                 delete constraint;
413                 constraint = b;
414         }
415
416         BooleanEdge be = BooleanEdge(constraint);
417         return negate ? be.negate() : be;
418 }
419
420 void CSolver::addConstraint(BooleanEdge constraint) {
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 }