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