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