Compute Must Values Automatically
[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 <stdlib.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(b->clone(copy, &map));
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                 allElements.push(element);
147                 elemMap.put(element, element);
148                 return element;
149         } else {
150                 delete element;
151                 return e;
152         }
153 }
154
155 Function *CSolver::createFunctionOperator(ArithOp op, Set **domain, uint numDomain, Set *range,OverFlowBehavior overflowbehavior) {
156         Function *function = new FunctionOperator(op, domain, numDomain, range, overflowbehavior);
157         allFunctions.push(function);
158         return function;
159 }
160
161 Predicate *CSolver::createPredicateOperator(CompOp op, Set **domain, uint numDomain) {
162         Predicate *predicate = new PredicateOperator(op, domain,numDomain);
163         allPredicates.push(predicate);
164         return predicate;
165 }
166
167 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
168         Predicate *predicate = new PredicateTable(table, behavior);
169         allPredicates.push(predicate);
170         return predicate;
171 }
172
173 Table *CSolver::createTable(Set **domains, uint numDomain, Set *range) {
174         Table *table = new Table(domains,numDomain,range);
175         allTables.push(table);
176         return table;
177 }
178
179 Table *CSolver::createTableForPredicate(Set **domains, uint numDomain) {
180         return createTable(domains, numDomain, NULL);
181 }
182
183 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
184         table->addNewTableEntry(inputs, inputSize, result);
185 }
186
187 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
188         Function *function = new FunctionTable(table, behavior);
189         allFunctions.push(function);
190         return function;
191 }
192
193 BooleanEdge CSolver::getBooleanVar(VarType type) {
194         Boolean *boolean = new BooleanVar(type);
195         allBooleans.push(boolean);
196         return BooleanEdge(boolean);
197 }
198
199 BooleanEdge CSolver::getBooleanTrue() {
200         return boolTrue;
201 }
202
203 BooleanEdge CSolver::getBooleanFalse() {
204         return boolFalse;
205 }
206
207 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
208         return applyPredicateTable(predicate, inputs, numInputs, NULL);
209 }
210
211 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
212         BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
213         Boolean *b = boolMap.get(boolean);
214         if (b == NULL) {
215                 boolMap.put(boolean, boolean);
216                 allBooleans.push(boolean);
217                 return BooleanEdge(boolean);
218         } else {
219                 delete boolean;
220                 return BooleanEdge(b);
221         }
222 }
223
224 bool CSolver::isTrue(BooleanEdge b) {
225         return b.isNegated()?b->isFalse():b->isTrue();
226 }
227
228 bool CSolver::isFalse(BooleanEdge b) {
229         return b.isNegated()?b->isTrue():b->isFalse();
230 }
231
232 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
233         BooleanEdge array[] = {arg1, arg2};
234         return applyLogicalOperation(op, array, 2);
235 }
236
237 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
238         BooleanEdge array[] = {arg};
239         return applyLogicalOperation(op, array, 1);
240 }
241
242 static int ptrcompares(const void *p1, const void *p2) {
243         uintptr_t b1 = *(uintptr_t const *) p1;
244   uintptr_t b2 = *(uintptr_t const *) p2;
245         if (b1 < b2)
246                 return -1;
247         else if (b1 == b2)
248                 return 0;
249         else
250                 return 1;
251 }
252
253 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
254         BooleanEdge newarray[asize];
255         switch (op) {
256         case SATC_NOT: {
257                 return array[0].negate();
258         }
259         case SATC_IFF: {
260                 for (uint i = 0; i < 2; i++) {
261                         if (array[i]->type == BOOLCONST) {
262                                 if (array[i]->isTrue()) {
263                                         return array[1 - i];
264                                 } else {
265                                         newarray[0] = array[1 - i];
266                                         return applyLogicalOperation(SATC_NOT, newarray, 1);
267                                 }
268                         }
269                 }
270                 break;
271         }
272         case SATC_OR: {
273                 for (uint i =0; i <asize; i++) {
274                         newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
275                 }
276                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
277         }
278         case SATC_AND: {
279                 uint newindex = 0;
280                 for (uint i = 0; i < asize; i++) {
281                         BooleanEdge b = array[i];
282                         if (b->type == BOOLCONST) {
283                                 if (b->isTrue())
284                                         continue;
285                                 else
286                                         return boolFalse;
287                         } else
288                                 newarray[newindex++] = b;
289                 }
290                 if (newindex == 0) {
291                         return boolTrue;
292                 } else if (newindex == 1) {
293                         return newarray[0];
294                 } else {
295                         qsort(newarray, newindex, sizeof(BooleanEdge), ptrcompares);
296                         array = newarray;
297                         asize = newindex;
298                 }
299                 break;
300         }
301         case SATC_XOR: {
302                 //handle by translation
303                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
304         }
305         case SATC_IMPLIES: {
306                 //handle by translation
307                 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
308         }
309         }
310
311         ASSERT(asize != 0);
312         Boolean *boolean = new BooleanLogic(this, op, array, asize);
313         Boolean *b = boolMap.get(boolean);
314         if (b == NULL) {
315                 boolMap.put(boolean, boolean);
316                 allBooleans.push(boolean);
317                 return BooleanEdge(boolean);
318         } else {
319                 delete boolean;
320                 return BooleanEdge(b);
321         }
322 }
323
324 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
325         Boolean *constraint = new BooleanOrder(order, first, second);
326         allBooleans.push(constraint);
327         return BooleanEdge(constraint);
328 }
329
330 void CSolver::addConstraint(BooleanEdge constraint) {
331         if (constraint == boolTrue)
332                 return;
333         else if (constraint == boolFalse)
334                 setUnSAT();
335         else {
336                 if (!constraint.isNegated() && constraint->type == LOGICOP) {
337                         BooleanLogic *b=(BooleanLogic *) constraint.getBoolean();
338                         if (b->op==SATC_AND) {
339                                 for(uint i=0;i<b->inputs.getSize();i++) {
340                                         addConstraint(b->inputs.get(i));
341                                 }
342                                 return;
343                         }
344                 }
345                 constraints.add(constraint);
346                 Boolean *ptr=constraint.getBoolean();
347                 if (constraint.isNegated())
348                         updateMustValue(ptr, BV_MUSTBEFALSE);
349                 else
350                         updateMustValue(ptr, BV_MUSTBETRUE);
351         }
352 }
353
354 Order *CSolver::createOrder(OrderType type, Set *set) {
355         Order *order = new Order(type, set);
356         allOrders.push(order);
357         activeOrders.add(order);
358         return order;
359 }
360
361 int CSolver::solve() {
362         bool deleteTuner = false;
363         if (tuner == NULL) {
364                 tuner = new DefaultTuner();
365                 deleteTuner = true;
366         }
367
368         long long startTime = getTimeNano();
369         computePolarities(this);
370
371         DecomposeOrderTransform dot(this);
372         dot.doTransform();
373
374         //This leaks like crazy
375         //      IntegerEncodingTransform iet(this);
376         //iet.doTransform();
377
378         naiveEncodingDecision(this);
379         satEncoder->encodeAllSATEncoder(this);
380         int result = unsat ? IS_UNSAT : satEncoder->solve();
381         long long finishTime = getTimeNano();
382         elapsedTime = finishTime - startTime;
383         if (deleteTuner) {
384                 delete tuner;
385                 tuner = NULL;
386         }
387         return result;
388 }
389
390 uint64_t CSolver::getElementValue(Element *element) {
391         switch (element->type) {
392         case ELEMSET:
393         case ELEMCONST:
394         case ELEMFUNCRETURN:
395                 return getElementValueSATTranslator(this, element);
396         default:
397                 ASSERT(0);
398         }
399         exit(-1);
400 }
401
402 bool CSolver::getBooleanValue(BooleanEdge bedge) {
403         Boolean *boolean=bedge.getBoolean();
404         switch (boolean->type) {
405         case BOOLEANVAR:
406                 return getBooleanVariableValueSATTranslator(this, boolean);
407         default:
408                 ASSERT(0);
409         }
410         exit(-1);
411 }
412
413 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
414         return order->encoding.resolver->resolveOrder(first, second);
415 }
416
417 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
418
419 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
420
421 void CSolver::autoTune(uint budget) {
422         AutoTuner *autotuner = new AutoTuner(budget);
423         autotuner->addProblem(this);
424         autotuner->tune();
425         delete autotuner;
426 }