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