Adding a new testcase ... -Shows bugs that need to be fixed
[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
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         Serializer serializer("dump");
100         SetIteratorBooleanEdge *it = getConstraints();
101         while (it->hasNext()) {
102                 BooleanEdge b = it->next();
103                 serializeBooleanEdge(&serializer, b);
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 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 (array[i]->type == BOOLCONST) {
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                                 }
320                         } else if (array[i]->type == LOGICOP) {
321                                 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
322                                 if (b->replaced) {
323                                         return rewriteLogicalOperation(op, array, asize);
324                                 }
325                         }
326                 }
327                 break;
328         }
329         case SATC_OR: {
330                 for (uint i = 0; i < asize; i++) {
331                         newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
332                 }
333                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
334         }
335         case SATC_AND: {
336                 uint newindex = 0;
337                 for (uint i = 0; i < asize; i++) {
338                         BooleanEdge b = array[i];
339                         if (b->type == LOGICOP) {
340                                 if (((BooleanLogic *)b.getBoolean())->replaced)
341                                         return rewriteLogicalOperation(op, array, asize);
342                         }
343                         if (b->type == BOOLCONST) {
344                                 if (isTrue(b))
345                                         continue;
346                                 else {
347                                         return boolFalse;
348                                 }
349                         } else
350                                 newarray[newindex++] = b;
351                 }
352                 if (newindex == 0) {
353                         return boolTrue;
354                 } else if (newindex == 1) {
355                         return newarray[0];
356                 } else {
357                         bsdqsort(newarray, newindex, sizeof(BooleanEdge), ptrcompares);
358                         array = newarray;
359                         asize = newindex;
360                 }
361                 break;
362         }
363         case SATC_XOR: {
364                 //handle by translation
365                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
366         }
367         case SATC_IMPLIES: {
368                 //handle by translation
369                 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
370         }
371         }
372
373         ASSERT(asize != 0);
374         Boolean *boolean = new BooleanLogic(this, op, array, asize);
375         Boolean *b = boolMap.get(boolean);
376         if (b == NULL) {
377                 boolean->updateParents();
378                 boolMap.put(boolean, boolean);
379                 allBooleans.push(boolean);
380                 return BooleanEdge(boolean);
381         } else {
382                 delete boolean;
383                 return BooleanEdge(b);
384         }
385 }
386
387 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
388         ASSERT(first != second);
389         Boolean *constraint = new BooleanOrder(order, first, second);
390         allBooleans.push(constraint);
391         return BooleanEdge(constraint);
392 }
393
394 void CSolver::addConstraint(BooleanEdge constraint) {
395 #ifdef TRACE_DEBUG
396         model_println("****New Constraint******");
397 #endif
398         if (isTrue(constraint))
399                 return;
400         else if (isFalse(constraint)) {
401                 int t = 0;
402                 setUnSAT();
403         }
404         else {
405                 if (constraint->type == LOGICOP) {
406                         BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
407                         if (!constraint.isNegated()) {
408                                 if (b->op == SATC_AND) {
409                                         for (uint i = 0; i < b->inputs.getSize(); i++) {
410                                                 addConstraint(b->inputs.get(i));
411                                         }
412                                         return;
413                                 }
414                         }
415                         if (b->replaced) {
416                                 addConstraint(doRewrite(constraint));
417                                 return;
418                         }
419                 }
420                 constraints.add(constraint);
421                 Boolean *ptr = constraint.getBoolean();
422
423                 if (ptr->boolVal == BV_UNSAT) {
424                         setUnSAT();
425                 }
426
427                 replaceBooleanWithTrueNoRemove(constraint);
428                 constraint->parents.clear();
429         }
430 }
431
432 Order *CSolver::createOrder(OrderType type, Set *set) {
433         Order *order = new Order(type, set);
434         allOrders.push(order);
435         activeOrders.add(order);
436         return order;
437 }
438
439 int CSolver::solve() {
440         bool deleteTuner = false;
441         if (tuner == NULL) {
442                 tuner = new DefaultTuner();
443                 deleteTuner = true;
444         }
445
446         long long startTime = getTimeNano();
447         computePolarities(this);
448
449         Preprocess pp(this);
450         pp.doTransform();
451
452         DecomposeOrderTransform dot(this);
453         dot.doTransform();
454
455         IntegerEncodingTransform iet(this);
456         iet.doTransform();
457
458         EncodingGraph eg(this);
459         eg.buildGraph();
460         eg.encode();
461         printConstraints();
462         naiveEncodingDecision(this);
463         satEncoder->encodeAllSATEncoder(this);
464         model_print("Is problem UNSAT after encoding: %d\n", unsat);
465         int result = unsat ? IS_UNSAT : satEncoder->solve();
466         model_print("Result Computed in CSolver: %d\n", result);
467         long long finishTime = getTimeNano();
468         elapsedTime = finishTime - startTime;
469         if (deleteTuner) {
470                 delete tuner;
471                 tuner = NULL;
472         }
473         return result;
474 }
475
476 void CSolver::printConstraints() {
477         SetIteratorBooleanEdge *it = getConstraints();
478         while (it->hasNext()) {
479                 BooleanEdge b = it->next();
480                 if (b.isNegated())
481                         model_print("!");
482                 b->print();
483                 model_print("\n");
484         }
485         delete it;
486
487 }
488
489 uint64_t CSolver::getElementValue(Element *element) {
490         switch (element->type) {
491         case ELEMSET:
492         case ELEMCONST:
493         case ELEMFUNCRETURN:
494                 return getElementValueSATTranslator(this, element);
495         default:
496                 ASSERT(0);
497         }
498         exit(-1);
499 }
500
501 bool CSolver::getBooleanValue(BooleanEdge bedge) {
502         Boolean *boolean = bedge.getBoolean();
503         switch (boolean->type) {
504         case BOOLEANVAR:
505                 return getBooleanVariableValueSATTranslator(this, boolean);
506         default:
507                 ASSERT(0);
508         }
509         exit(-1);
510 }
511
512 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
513         return order->encoding.resolver->resolveOrder(first, second);
514 }
515
516 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
517
518 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
519
520 void CSolver::autoTune(uint budget) {
521         AutoTuner *autotuner = new AutoTuner(budget);
522         autotuner->addProblem(this);
523         autotuner->tune();
524         delete autotuner;
525 }