Fixing missing 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
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                 delete allElements.get(i);
52         }
53
54         size = allTables.getSize();
55         for (uint i = 0; i < size; i++) {
56                 delete allTables.get(i);
57         }
58
59         size = allPredicates.getSize();
60         for (uint i = 0; i < size; i++) {
61                 delete allPredicates.get(i);
62         }
63
64         size = allOrders.getSize();
65         for (uint i = 0; i < size; i++) {
66                 delete allOrders.get(i);
67         }
68
69         size = allFunctions.getSize();
70         for (uint i = 0; i < size; i++) {
71                 delete allFunctions.get(i);
72         }
73
74         delete boolTrue.getBoolean();
75         delete satEncoder;
76 }
77
78 CSolver *CSolver::clone() {
79         CSolver *copy = new CSolver();
80         CloneMap map;
81         SetIteratorBooleanEdge *it = getConstraints();
82         while (it->hasNext()) {
83                 BooleanEdge b = it->next();
84                 copy->addConstraint(cloneEdge(copy, &map, b));
85         }
86         delete it;
87         return copy;
88 }
89
90 void CSolver::serialize() {
91         model_print("serializing ...\n");
92         {
93                 Serializer serializer("dump");
94                 SetIteratorBooleanEdge *it = getConstraints();
95                 while (it->hasNext()) {
96                         BooleanEdge b = it->next();
97                         serializeBooleanEdge(&serializer, b);
98                 }
99                 delete it;
100         }
101         model_print("deserializing ...\n");
102         {
103                 Deserializer deserializer("dump");
104                 deserializer.deserialize();
105         }
106         
107 }
108
109 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
110         Set *set = new Set(type, elements, numelements);
111         allSets.push(set);
112         return set;
113 }
114
115 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
116         Set *set = new Set(type, lowrange, highrange);
117         allSets.push(set);
118         return set;
119 }
120
121 VarType CSolver::getSetVarType(Set *set){
122         return set->getType();
123 }
124
125 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
126         Set *s = createRangeSet(type, lowrange, highrange);
127         return getElementVar(s);
128 }
129
130 MutableSet *CSolver::createMutableSet(VarType type) {
131         MutableSet *set = new MutableSet(type);
132         allSets.push(set);
133         return set;
134 }
135
136 void CSolver::addItem(MutableSet *set, uint64_t element) {
137         set->addElementMSet(element);
138 }
139
140 uint64_t CSolver::createUniqueItem(MutableSet *set) {
141         uint64_t element = set->getNewUniqueItem();
142         set->addElementMSet(element);
143         return element;
144 }
145
146 void CSolver::finalizeMutableSet(MutableSet* set){
147         set->finalize();
148 }
149
150 Element *CSolver::getElementVar(Set *set) {
151         Element *element = new ElementSet(set);
152         allElements.push(element);
153         return element;
154 }
155
156 Set* CSolver::getElementRange (Element* element){
157         return element->getRange();
158 }
159
160
161 Element *CSolver::getElementConst(VarType type, uint64_t value) {
162         uint64_t array[] = {value};
163         Set *set = new Set(type, array, 1);
164         Element *element = new ElementConst(value, set);
165         Element *e = elemMap.get(element);
166         if (e == NULL) {
167                 allSets.push(set);
168                 allElements.push(element);
169                 elemMap.put(element, element);
170                 return element;
171         } else {
172                 delete set;
173                 delete element;
174                 return e;
175         }
176 }
177
178 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
179         Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
180         Element *e = elemMap.get(element);
181         if (e == NULL) {
182                 element->updateParents();
183                 allElements.push(element);
184                 elemMap.put(element, element);
185                 return element;
186         } else {
187                 delete element;
188                 return e;
189         }
190 }
191
192 Function *CSolver::createFunctionOperator(ArithOp op, Set **domain, uint numDomain, Set *range,OverFlowBehavior overflowbehavior) {
193         Function *function = new FunctionOperator(op, domain, numDomain, range, overflowbehavior);
194         allFunctions.push(function);
195         return function;
196 }
197
198 Predicate *CSolver::createPredicateOperator(CompOp op, Set **domain, uint numDomain) {
199         Predicate *predicate = new PredicateOperator(op, domain,numDomain);
200         allPredicates.push(predicate);
201         return predicate;
202 }
203
204 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
205         Predicate *predicate = new PredicateTable(table, behavior);
206         allPredicates.push(predicate);
207         return predicate;
208 }
209
210 Table *CSolver::createTable(Set **domains, uint numDomain, Set *range) {
211         Table *table = new Table(domains,numDomain,range);
212         allTables.push(table);
213         return table;
214 }
215
216 Table *CSolver::createTableForPredicate(Set **domains, uint numDomain) {
217         return createTable(domains, numDomain, NULL);
218 }
219
220 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
221         table->addNewTableEntry(inputs, inputSize, result);
222 }
223
224 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
225         Function *function = new FunctionTable(table, behavior);
226         allFunctions.push(function);
227         return function;
228 }
229
230 BooleanEdge CSolver::getBooleanVar(VarType type) {
231         Boolean *boolean = new BooleanVar(type);
232         allBooleans.push(boolean);
233         return BooleanEdge(boolean);
234 }
235
236 BooleanEdge CSolver::getBooleanTrue() {
237         return boolTrue;
238 }
239
240 BooleanEdge CSolver::getBooleanFalse() {
241         return boolFalse;
242 }
243
244 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
245         return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
246 }
247
248 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
249         BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
250         Boolean *b = boolMap.get(boolean);
251         if (b == NULL) {
252                 boolean->updateParents();
253                 boolMap.put(boolean, boolean);
254                 allBooleans.push(boolean);
255                 return BooleanEdge(boolean);
256         } else {
257                 delete boolean;
258                 return BooleanEdge(b);
259         }
260 }
261
262 bool CSolver::isTrue(BooleanEdge b) {
263         return b.isNegated()?b->isFalse():b->isTrue();
264 }
265
266 bool CSolver::isFalse(BooleanEdge b) {
267         return b.isNegated()?b->isTrue():b->isFalse();
268 }
269
270 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
271         BooleanEdge array[] = {arg1, arg2};
272         return applyLogicalOperation(op, array, 2);
273 }
274
275 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
276         BooleanEdge array[] = {arg};
277         return applyLogicalOperation(op, array, 1);
278 }
279
280 static int ptrcompares(const void *p1, const void *p2) {
281         uintptr_t b1 = *(uintptr_t const *) p1;
282   uintptr_t b2 = *(uintptr_t const *) p2;
283         if (b1 < b2)
284                 return -1;
285         else if (b1 == b2)
286                 return 0;
287         else
288                 return 1;
289 }
290
291 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge * array, uint asize) {
292         BooleanEdge newarray[asize];
293         memcpy(newarray, array, asize * sizeof(BooleanEdge));
294         for(uint i=0; i < asize; i++) {
295                 BooleanEdge b=newarray[i];
296                 if (b->type == LOGICOP) {
297                         if (((BooleanLogic *) b.getBoolean())->replaced) {
298                                 newarray[i] = doRewrite(newarray[i]);
299                                 i--;//Check again
300                         }
301                 }
302         }
303         return applyLogicalOperation(op, newarray, asize);
304 }
305
306 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
307         BooleanEdge newarray[asize];
308         switch (op) {
309         case SATC_NOT: {
310                 return array[0].negate();
311         }
312         case SATC_IFF: {
313                 for (uint i = 0; i < 2; i++) {
314                         if (array[i]->type == BOOLCONST) {
315                                 if (array[i]->isTrue()) {
316                                         return array[1 - i];
317                                 } else {
318                                         newarray[0] = array[1 - i];
319                                         return applyLogicalOperation(SATC_NOT, newarray, 1);
320                                 }
321                         } else if (array[i]->type == LOGICOP) {
322                                 BooleanLogic *b =(BooleanLogic *)array[i].getBoolean();
323                                 if (b->replaced) {
324                                         return rewriteLogicalOperation(op, array, asize);
325                                 }
326                         }
327                 }
328                 break;
329         }
330         case SATC_OR: {
331                 for (uint i =0; i <asize; i++) {
332                         newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
333                 }
334                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
335         }
336         case SATC_AND: {
337                 uint newindex = 0;
338                 for (uint i = 0; i < asize; i++) {
339                         BooleanEdge b = array[i];
340                         if (b->type == LOGICOP) {
341                                 if (((BooleanLogic *)b.getBoolean())->replaced)
342                                         return rewriteLogicalOperation(op, array, asize);
343                         }
344                         if (b->type == BOOLCONST) {
345                                 if (b->isTrue())
346                                         continue;
347                                 else
348                                         return boolFalse;
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         Boolean *constraint = new BooleanOrder(order, first, second);
389         allBooleans.push(constraint);
390         return BooleanEdge(constraint);
391 }
392
393 void CSolver::addConstraint(BooleanEdge constraint) {
394         if (isTrue(constraint))
395                 return;
396         else if (isFalse(constraint))
397                 setUnSAT();
398         else {
399                 if (constraint->type == LOGICOP) {
400                         BooleanLogic *b=(BooleanLogic *) constraint.getBoolean();
401                         if (!constraint.isNegated()) {
402                                 if (b->op==SATC_AND) {
403                                         for(uint i=0;i<b->inputs.getSize();i++) {
404                                                 addConstraint(b->inputs.get(i));
405                                         }
406                                         return;
407                                 }
408                         }
409                         if (b->replaced) {
410                                 addConstraint(doRewrite(constraint));
411                                 return;
412                         }
413                 }
414                 constraints.add(constraint);
415                 Boolean *ptr=constraint.getBoolean();
416                 
417                 if (ptr->boolVal == BV_UNSAT)
418                         setUnSAT();
419                 
420                 replaceBooleanWithTrueNoRemove(constraint);
421                 constraint->parents.clear();
422         }
423 }
424
425 Order *CSolver::createOrder(OrderType type, Set *set) {
426         Order *order = new Order(type, set);
427         allOrders.push(order);
428         activeOrders.add(order);
429         return order;
430 }
431
432 int CSolver::solve() {
433         bool deleteTuner = false;
434         if (tuner == NULL) {
435                 tuner = new DefaultTuner();
436                 deleteTuner = true;
437         }
438
439         long long startTime = getTimeNano();
440         computePolarities(this);
441
442 //      Preprocess pp(this);
443 //      pp.doTransform();
444         
445         DecomposeOrderTransform dot(this);
446         dot.doTransform();
447
448         IntegerEncodingTransform iet(this);
449         iet.doTransform();
450
451 //      EncodingGraph eg(this);
452 //      eg.buildGraph();
453 //      eg.encode();
454         
455         naiveEncodingDecision(this);
456         satEncoder->encodeAllSATEncoder(this);
457         int result = unsat ? IS_UNSAT : satEncoder->solve();
458         long long finishTime = getTimeNano();
459         elapsedTime = finishTime - startTime;
460         if (deleteTuner) {
461                 delete tuner;
462                 tuner = NULL;
463         }
464         return result;
465 }
466
467 uint64_t CSolver::getElementValue(Element *element) {
468         switch (element->type) {
469         case ELEMSET:
470         case ELEMCONST:
471         case ELEMFUNCRETURN:
472                 return getElementValueSATTranslator(this, element);
473         default:
474                 ASSERT(0);
475         }
476         exit(-1);
477 }
478
479 bool CSolver::getBooleanValue(BooleanEdge bedge) {
480         Boolean *boolean=bedge.getBoolean();
481         switch (boolean->type) {
482         case BOOLEANVAR:
483                 return getBooleanVariableValueSATTranslator(this, boolean);
484         default:
485                 ASSERT(0);
486         }
487         exit(-1);
488 }
489
490 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
491         return order->encoding.resolver->resolveOrder(first, second);
492 }
493
494 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
495
496 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
497
498 void CSolver::autoTune(uint budget) {
499         AutoTuner *autotuner = new AutoTuner(budget);
500         autotuner->addProblem(this);
501         autotuner->tune();
502         delete autotuner;
503 }