Don't do unnecessary work in polarity computation
[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
22 CSolver::CSolver() :
23         boolTrue(BooleanEdge(new BooleanConst(true))),
24         boolFalse(boolTrue.negate()),
25         unsat(false),
26         tuner(NULL),
27         elapsedTime(0)
28 {
29         satEncoder = new SATEncoder(this);
30 }
31
32 /** This function tears down the solver and the entire AST */
33
34 CSolver::~CSolver() {
35         uint size = allBooleans.getSize();
36         for (uint i = 0; i < size; i++) {
37                 delete allBooleans.get(i);
38         }
39
40         size = allSets.getSize();
41         for (uint i = 0; i < size; i++) {
42                 delete allSets.get(i);
43         }
44
45         size = allElements.getSize();
46         for (uint i = 0; i < size; i++) {
47                 delete allElements.get(i);
48         }
49
50         size = allTables.getSize();
51         for (uint i = 0; i < size; i++) {
52                 delete allTables.get(i);
53         }
54
55         size = allPredicates.getSize();
56         for (uint i = 0; i < size; i++) {
57                 delete allPredicates.get(i);
58         }
59
60         size = allOrders.getSize();
61         for (uint i = 0; i < size; i++) {
62                 delete allOrders.get(i);
63         }
64
65         size = allFunctions.getSize();
66         for (uint i = 0; i < size; i++) {
67                 delete allFunctions.get(i);
68         }
69
70         delete boolTrue.getBoolean();
71         delete satEncoder;
72 }
73
74 CSolver *CSolver::clone() {
75         CSolver *copy = new CSolver();
76         CloneMap map;
77         SetIteratorBooleanEdge *it = getConstraints();
78         while (it->hasNext()) {
79                 BooleanEdge b = it->next();
80                 copy->addConstraint(cloneEdge(copy, &map, b));
81         }
82         delete it;
83         return copy;
84 }
85
86 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
87         Set *set = new Set(type, elements, numelements);
88         allSets.push(set);
89         return set;
90 }
91
92 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
93         Set *set = new Set(type, lowrange, highrange);
94         allSets.push(set);
95         return set;
96 }
97
98 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
99         Set *s = createRangeSet(type, lowrange, highrange);
100         return getElementVar(s);
101 }
102
103 MutableSet *CSolver::createMutableSet(VarType type) {
104         MutableSet *set = new MutableSet(type);
105         allSets.push(set);
106         return set;
107 }
108
109 void CSolver::addItem(MutableSet *set, uint64_t element) {
110         set->addElementMSet(element);
111 }
112
113 uint64_t CSolver::createUniqueItem(MutableSet *set) {
114         uint64_t element = set->getNewUniqueItem();
115         set->addElementMSet(element);
116         return element;
117 }
118
119 Element *CSolver::getElementVar(Set *set) {
120         Element *element = new ElementSet(set);
121         allElements.push(element);
122         return element;
123 }
124
125 Element *CSolver::getElementConst(VarType type, uint64_t value) {
126         uint64_t array[] = {value};
127         Set *set = new Set(type, array, 1);
128         Element *element = new ElementConst(value, type, set);
129         Element *e = elemMap.get(element);
130         if (e == NULL) {
131                 allSets.push(set);
132                 allElements.push(element);
133                 elemMap.put(element, element);
134                 return element;
135         } else {
136                 delete set;
137                 delete element;
138                 return e;
139         }
140 }
141
142 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
143         Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
144         Element *e = elemMap.get(element);
145         if (e == NULL) {
146                 element->updateParents();
147                 allElements.push(element);
148                 elemMap.put(element, element);
149                 return element;
150         } else {
151                 delete element;
152                 return e;
153         }
154 }
155
156 Function *CSolver::createFunctionOperator(ArithOp op, Set **domain, uint numDomain, Set *range,OverFlowBehavior overflowbehavior) {
157         Function *function = new FunctionOperator(op, domain, numDomain, range, overflowbehavior);
158         allFunctions.push(function);
159         return function;
160 }
161
162 Predicate *CSolver::createPredicateOperator(CompOp op, Set **domain, uint numDomain) {
163         Predicate *predicate = new PredicateOperator(op, domain,numDomain);
164         allPredicates.push(predicate);
165         return predicate;
166 }
167
168 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
169         Predicate *predicate = new PredicateTable(table, behavior);
170         allPredicates.push(predicate);
171         return predicate;
172 }
173
174 Table *CSolver::createTable(Set **domains, uint numDomain, Set *range) {
175         Table *table = new Table(domains,numDomain,range);
176         allTables.push(table);
177         return table;
178 }
179
180 Table *CSolver::createTableForPredicate(Set **domains, uint numDomain) {
181         return createTable(domains, numDomain, NULL);
182 }
183
184 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
185         table->addNewTableEntry(inputs, inputSize, result);
186 }
187
188 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
189         Function *function = new FunctionTable(table, behavior);
190         allFunctions.push(function);
191         return function;
192 }
193
194 BooleanEdge CSolver::getBooleanVar(VarType type) {
195         Boolean *boolean = new BooleanVar(type);
196         allBooleans.push(boolean);
197         return BooleanEdge(boolean);
198 }
199
200 BooleanEdge CSolver::getBooleanTrue() {
201         return boolTrue;
202 }
203
204 BooleanEdge CSolver::getBooleanFalse() {
205         return boolFalse;
206 }
207
208 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
209         return applyPredicateTable(predicate, inputs, numInputs, NULL);
210 }
211
212 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
213         BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
214         Boolean *b = boolMap.get(boolean);
215         if (b == NULL) {
216                 boolean->updateParents();
217                 boolMap.put(boolean, boolean);
218                 allBooleans.push(boolean);
219                 return BooleanEdge(boolean);
220         } else {
221                 delete boolean;
222                 return BooleanEdge(b);
223         }
224 }
225
226 bool CSolver::isTrue(BooleanEdge b) {
227         return b.isNegated()?b->isFalse():b->isTrue();
228 }
229
230 bool CSolver::isFalse(BooleanEdge b) {
231         return b.isNegated()?b->isTrue():b->isFalse();
232 }
233
234 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
235         BooleanEdge array[] = {arg1, arg2};
236         return applyLogicalOperation(op, array, 2);
237 }
238
239 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
240         BooleanEdge array[] = {arg};
241         return applyLogicalOperation(op, array, 1);
242 }
243
244 static int ptrcompares(const void *p1, const void *p2) {
245         uintptr_t b1 = *(uintptr_t const *) p1;
246   uintptr_t b2 = *(uintptr_t const *) p2;
247         if (b1 < b2)
248                 return -1;
249         else if (b1 == b2)
250                 return 0;
251         else
252                 return 1;
253 }
254
255 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge * array, uint asize) {
256         BooleanEdge newarray[asize];
257         memcpy(newarray, array, asize * sizeof(BooleanEdge));
258         for(uint i=0; i < asize; i++) {
259                 BooleanEdge b=newarray[i];
260                 if (b->type == LOGICOP) {
261                         if (((BooleanLogic *) b.getBoolean())->replaced) {
262                                 newarray[i] = doRewrite(newarray[i]);
263                                 i--;//Check again
264                         }
265                 }
266         }
267         return applyLogicalOperation(op, newarray, asize);
268 }
269
270 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
271         BooleanEdge newarray[asize];
272         switch (op) {
273         case SATC_NOT: {
274                 return array[0].negate();
275         }
276         case SATC_IFF: {
277                 for (uint i = 0; i < 2; i++) {
278                         if (array[i]->type == BOOLCONST) {
279                                 if (array[i]->isTrue()) {
280                                         return array[1 - i];
281                                 } else {
282                                         newarray[0] = array[1 - i];
283                                         return applyLogicalOperation(SATC_NOT, newarray, 1);
284                                 }
285                         } else if (array[i]->type == LOGICOP) {
286                                 BooleanLogic *b =(BooleanLogic *)array[i].getBoolean();
287                                 if (b->replaced) {
288                                         return rewriteLogicalOperation(op, array, asize);
289                                 }
290                         }
291                 }
292                 break;
293         }
294         case SATC_OR: {
295                 for (uint i =0; i <asize; i++) {
296                         newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
297                 }
298                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
299         }
300         case SATC_AND: {
301                 uint newindex = 0;
302                 for (uint i = 0; i < asize; i++) {
303                         BooleanEdge b = array[i];
304                         if (b->type == LOGICOP) {
305                                 if (((BooleanLogic *)b.getBoolean())->replaced)
306                                         return rewriteLogicalOperation(op, array, asize);
307                         }
308                         if (b->type == BOOLCONST) {
309                                 if (b->isTrue())
310                                         continue;
311                                 else
312                                         return boolFalse;
313                         } else
314                                 newarray[newindex++] = b;
315                 }
316                 if (newindex == 0) {
317                         return boolTrue;
318                 } else if (newindex == 1) {
319                         return newarray[0];
320                 } else {
321                         bsdqsort(newarray, newindex, sizeof(BooleanEdge), ptrcompares);
322                         array = newarray;
323                         asize = newindex;
324                 }
325                 break;
326         }
327         case SATC_XOR: {
328                 //handle by translation
329                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
330         }
331         case SATC_IMPLIES: {
332                 //handle by translation
333                 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
334         }
335         }
336
337         ASSERT(asize != 0);
338         Boolean *boolean = new BooleanLogic(this, op, array, asize);
339         Boolean *b = boolMap.get(boolean);
340         if (b == NULL) {
341                 boolean->updateParents();
342                 boolMap.put(boolean, boolean);
343                 allBooleans.push(boolean);
344                 return BooleanEdge(boolean);
345         } else {
346                 delete boolean;
347                 return BooleanEdge(b);
348         }
349 }
350
351 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
352         Boolean *constraint = new BooleanOrder(order, first, second);
353         allBooleans.push(constraint);
354         return BooleanEdge(constraint);
355 }
356
357 void CSolver::addConstraint(BooleanEdge constraint) {
358         if (isTrue(constraint))
359                 return;
360         else if (isFalse(constraint))
361                 setUnSAT();
362         else {
363                 if (constraint->type == LOGICOP) {
364                         BooleanLogic *b=(BooleanLogic *) constraint.getBoolean();
365                         if (!constraint.isNegated()) {
366                                 if (b->op==SATC_AND) {
367                                         for(uint i=0;i<b->inputs.getSize();i++) {
368                                                 addConstraint(b->inputs.get(i));
369                                         }
370                                         return;
371                                 }
372                         }
373                         if (b->replaced) {
374                                 addConstraint(doRewrite(constraint));
375                                 return;
376                         }
377                 }
378                 constraints.add(constraint);
379                 Boolean *ptr=constraint.getBoolean();
380                 
381                 if (ptr->boolVal == BV_UNSAT)
382                         setUnSAT();
383                 
384                 replaceBooleanWithTrueNoRemove(constraint);
385                 constraint->parents.clear();
386         }
387 }
388
389 Order *CSolver::createOrder(OrderType type, Set *set) {
390         Order *order = new Order(type, set);
391         allOrders.push(order);
392         activeOrders.add(order);
393         return order;
394 }
395
396 int CSolver::solve() {
397         bool deleteTuner = false;
398         if (tuner == NULL) {
399                 tuner = new DefaultTuner();
400                 deleteTuner = true;
401         }
402
403         long long startTime = getTimeNano();
404         computePolarities(this);
405
406         DecomposeOrderTransform dot(this);
407         dot.doTransform();
408
409         IntegerEncodingTransform iet(this);
410         iet.doTransform();
411
412         naiveEncodingDecision(this);
413         satEncoder->encodeAllSATEncoder(this);
414         int result = unsat ? IS_UNSAT : satEncoder->solve();
415         long long finishTime = getTimeNano();
416         elapsedTime = finishTime - startTime;
417         if (deleteTuner) {
418                 delete tuner;
419                 tuner = NULL;
420         }
421         return result;
422 }
423
424 uint64_t CSolver::getElementValue(Element *element) {
425         switch (element->type) {
426         case ELEMSET:
427         case ELEMCONST:
428         case ELEMFUNCRETURN:
429                 return getElementValueSATTranslator(this, element);
430         default:
431                 ASSERT(0);
432         }
433         exit(-1);
434 }
435
436 bool CSolver::getBooleanValue(BooleanEdge bedge) {
437         Boolean *boolean=bedge.getBoolean();
438         switch (boolean->type) {
439         case BOOLEANVAR:
440                 return getBooleanVariableValueSATTranslator(this, boolean);
441         default:
442                 ASSERT(0);
443         }
444         exit(-1);
445 }
446
447 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
448         return order->encoding.resolver->resolveOrder(first, second);
449 }
450
451 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
452
453 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
454
455 void CSolver::autoTune(uint budget) {
456         AutoTuner *autotuner = new AutoTuner(budget);
457         autotuner->addProblem(this);
458         autotuner->tune();
459         delete autotuner;
460 }