3 #include "mutableset.h"
10 #include "satencoder.h"
11 #include "sattranslator.h"
13 #include "polarityassignment.h"
14 #include "decomposeordertransform.h"
15 #include "autotuner.h"
18 #include "orderresolver.h"
19 #include "integerencoding.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"
33 boolTrue(BooleanEdge(new BooleanConst(true))),
34 boolFalse(boolTrue.negate()),
38 satsolverTimeout(NOTIMEOUT)
40 satEncoder = new SATEncoder(this);
43 /** This function tears down the solver and the entire AST */
47 uint size = allBooleans.getSize();
48 for (uint i = 0; i < size; i++) {
49 delete allBooleans.get(i);
52 size = allSets.getSize();
53 for (uint i = 0; i < size; i++) {
54 delete allSets.get(i);
57 size = allElements.getSize();
58 for (uint i = 0; i < size; i++) {
59 Element *el = allElements.get(i);
63 size = allTables.getSize();
64 for (uint i = 0; i < size; i++) {
65 delete allTables.get(i);
68 size = allPredicates.getSize();
69 for (uint i = 0; i < size; i++) {
70 delete allPredicates.get(i);
73 size = allOrders.getSize();
74 for (uint i = 0; i < size; i++) {
75 delete allOrders.get(i);
77 size = allFunctions.getSize();
78 for (uint i = 0; i < size; i++) {
79 delete allFunctions.get(i);
82 delete boolTrue.getBoolean();
86 void CSolver::resetSolver() {
88 uint size = allBooleans.getSize();
89 for (uint i = 0; i < size; i++) {
90 delete allBooleans.get(i);
93 size = allSets.getSize();
94 for (uint i = 0; i < size; i++) {
95 delete allSets.get(i);
98 size = allElements.getSize();
99 for (uint i = 0; i < size; i++) {
100 Element *el = allElements.get(i);
104 size = allTables.getSize();
105 for (uint i = 0; i < size; i++) {
106 delete allTables.get(i);
109 size = allPredicates.getSize();
110 for (uint i = 0; i < size; i++) {
111 delete allPredicates.get(i);
114 size = allOrders.getSize();
115 for (uint i = 0; i < size; i++) {
116 delete allOrders.get(i);
118 size = allFunctions.getSize();
119 for (uint i = 0; i < size; i++) {
120 delete allFunctions.get(i);
122 delete boolTrue.getBoolean();
127 allPredicates.clear();
129 allFunctions.clear();
131 activeOrders.reset();
135 boolTrue = BooleanEdge(new BooleanConst(true));
136 boolFalse = boolTrue.negate();
140 satEncoder->resetSATEncoder();
144 CSolver *CSolver::clone() {
145 CSolver *copy = new CSolver();
147 SetIteratorBooleanEdge *it = getConstraints();
148 while (it->hasNext()) {
149 BooleanEdge b = it->next();
150 copy->addConstraint(cloneEdge(copy, &map, b));
156 CSolver *CSolver::deserialize(const char *file) {
157 model_print("deserializing %s ...\n", file);
158 Deserializer deserializer(file);
159 return deserializer.deserialize();
162 void CSolver::serialize() {
163 model_print("serializing ...\n");
165 long long nanotime = getTimeNano();
166 int numchars = sprintf(buffer, "DUMP%llu", nanotime);
167 Serializer serializer(buffer);
168 SetIteratorBooleanEdge *it = getConstraints();
169 while (it->hasNext()) {
170 BooleanEdge b = it->next();
171 serializeBooleanEdge(&serializer, b, true);
176 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
177 Set *set = new Set(type, elements, numelements);
182 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
183 Set *set = new Set(type, lowrange, highrange);
188 bool CSolver::itemExistInSet(Set *set, uint64_t item) {
189 return set->exists(item);
192 VarType CSolver::getSetVarType(Set *set) {
193 return set->getType();
196 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
197 Set *s = createRangeSet(type, lowrange, highrange);
198 return getElementVar(s);
201 MutableSet *CSolver::createMutableSet(VarType type) {
202 MutableSet *set = new MutableSet(type);
207 void CSolver::addItem(MutableSet *set, uint64_t element) {
208 set->addElementMSet(element);
211 uint64_t CSolver::createUniqueItem(MutableSet *set) {
212 uint64_t element = set->getNewUniqueItem();
213 set->addElementMSet(element);
217 void CSolver::finalizeMutableSet(MutableSet *set) {
221 Element *CSolver::getElementVar(Set *set) {
222 Element *element = new ElementSet(set);
223 allElements.push(element);
227 void CSolver::mustHaveValue(Element *element) {
228 element->anyValue = true;
231 Set *CSolver::getElementRange (Element *element) {
232 return element->getRange();
236 Element *CSolver::getElementConst(VarType type, uint64_t value) {
237 uint64_t array[] = {value};
238 Set *set = new Set(type, array, 1);
239 Element *element = new ElementConst(value, set);
240 Element *e = elemMap.get(element);
243 allElements.push(element);
244 elemMap.put(element, element);
254 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
255 ASSERT(numArrays == 2);
256 Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
257 Element *e = elemMap.get(element);
259 element->updateParents();
260 allElements.push(element);
261 elemMap.put(element, element);
269 Function *CSolver::createFunctionOperator(ArithOp op, Set *range, OverFlowBehavior overflowbehavior) {
270 Function *function = new FunctionOperator(op, range, overflowbehavior);
271 allFunctions.push(function);
275 Predicate *CSolver::createPredicateOperator(CompOp op) {
276 Predicate *predicate = new PredicateOperator(op);
277 allPredicates.push(predicate);
281 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
282 Predicate *predicate = new PredicateTable(table, behavior);
283 allPredicates.push(predicate);
287 Table *CSolver::createTable(Set *range) {
288 Table *table = new Table(range);
289 allTables.push(table);
293 Table *CSolver::createTableForPredicate() {
294 return createTable(NULL);
297 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
298 table->addNewTableEntry(inputs, inputSize, result);
301 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
302 Function *function = new FunctionTable(table, behavior);
303 allFunctions.push(function);
307 BooleanEdge CSolver::getBooleanVar(VarType type) {
308 Boolean *boolean = new BooleanVar(type);
309 allBooleans.push(boolean);
310 return BooleanEdge(boolean);
313 BooleanEdge CSolver::getBooleanTrue() {
317 BooleanEdge CSolver::getBooleanFalse() {
321 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
322 return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
325 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
326 BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
327 Boolean *b = boolMap.get(boolean);
329 boolean->updateParents();
330 boolMap.put(boolean, boolean);
331 allBooleans.push(boolean);
332 return BooleanEdge(boolean);
335 return BooleanEdge(b);
339 bool CSolver::isTrue(BooleanEdge b) {
340 return b.isNegated() ? b->isFalse() : b->isTrue();
343 bool CSolver::isFalse(BooleanEdge b) {
344 return b.isNegated() ? b->isTrue() : b->isFalse();
347 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
348 BooleanEdge array[] = {arg1, arg2};
349 return applyLogicalOperation(op, array, 2);
352 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
353 BooleanEdge array[] = {arg};
354 return applyLogicalOperation(op, array, 1);
357 static int booleanEdgeCompares(const void *p1, const void *p2) {
358 BooleanEdge be1 = *(BooleanEdge const *) p1;
359 BooleanEdge be2 = *(BooleanEdge const *) p2;
360 uint64_t b1 = be1->id;
361 uint64_t b2 = be2->id;
370 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
371 BooleanEdge newarray[asize];
372 memcpy(newarray, array, asize * sizeof(BooleanEdge));
373 for (uint i = 0; i < asize; i++) {
374 BooleanEdge b = newarray[i];
375 if (b->type == LOGICOP) {
376 if (((BooleanLogic *) b.getBoolean())->replaced) {
377 newarray[i] = doRewrite(newarray[i]);
382 return applyLogicalOperation(op, newarray, asize);
385 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
386 BooleanEdge newarray[asize];
389 return array[0].negate();
392 for (uint i = 0; i < 2; i++) {
393 if (isTrue(array[i])) { // It can be undefined
395 } else if (isFalse(array[i])) {
396 newarray[0] = array[1 - i];
397 return applyLogicalOperation(SATC_NOT, newarray, 1);
398 } else if (array[i]->type == LOGICOP) {
399 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
401 return rewriteLogicalOperation(op, array, asize);
408 for (uint i = 0; i < asize; i++) {
409 newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
411 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
415 for (uint i = 0; i < asize; i++) {
416 BooleanEdge b = array[i];
417 if (b->type == LOGICOP) {
418 if (((BooleanLogic *)b.getBoolean())->replaced)
419 return rewriteLogicalOperation(op, array, asize);
423 else if (isFalse(b)) {
426 newarray[newindex++] = b;
430 } else if (newindex == 1) {
433 bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
440 //handle by translation
441 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
444 //handle by translation
445 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
450 Boolean *boolean = new BooleanLogic(this, op, array, asize);
451 Boolean *b = boolMap.get(boolean);
453 boolean->updateParents();
454 boolMap.put(boolean, boolean);
455 allBooleans.push(boolean);
456 return BooleanEdge(boolean);
459 return BooleanEdge(b);
463 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
464 // ASSERT(first != second);
466 return getBooleanFalse();
469 if (order->type == SATC_TOTAL) {
470 if (first > second) {
471 uint64_t tmp = first;
477 Boolean *constraint = new BooleanOrder(order, first, second);
478 Boolean *b = boolMap.get(constraint);
481 allBooleans.push(constraint);
482 boolMap.put(constraint, constraint);
483 constraint->updateParents();
484 if (order->graph != NULL) {
485 OrderGraph *graph = order->graph;
486 OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
488 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
490 OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
493 if (edge != NULL && edge->mustPos) {
494 replaceBooleanWithTrueNoRemove(constraint);
495 } else if (edge != NULL && edge->mustNeg) {
496 replaceBooleanWithFalseNoRemove(constraint);
497 } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
498 && invedge->mustPos) {
499 replaceBooleanWithFalseNoRemove(constraint);
509 BooleanEdge be = BooleanEdge(constraint);
510 return negate ? be.negate() : be;
513 void CSolver::addConstraint(BooleanEdge constraint) {
514 if (isTrue(constraint))
516 else if (isFalse(constraint)) {
520 if (constraint->type == LOGICOP) {
521 BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
522 if (!constraint.isNegated()) {
523 if (b->op == SATC_AND) {
524 uint size = b->inputs.getSize();
525 //Handle potential concurrent modification
526 BooleanEdge array[size];
527 for (uint i = 0; i < size; i++) {
528 array[i] = b->inputs.get(i);
530 for (uint i = 0; i < size; i++) {
531 addConstraint(array[i]);
537 addConstraint(doRewrite(constraint));
541 constraints.add(constraint);
542 Boolean *ptr = constraint.getBoolean();
544 if (ptr->boolVal == BV_UNSAT) {
548 replaceBooleanWithTrueNoRemove(constraint);
549 constraint->parents.clear();
553 Order *CSolver::createOrder(OrderType type, Set *set) {
554 Order *order = new Order(type, set);
555 allOrders.push(order);
556 activeOrders.add(order);
560 /** Computes static ordering information to allow isTrue/isFalse
561 queries on newly created orders to work. */
563 void CSolver::inferFixedOrder(Order *order) {
564 if (order->graph != NULL) {
567 order->graph = buildMustOrderGraph(order);
568 reachMustAnalysis(this, order->graph, true);
571 void CSolver::inferFixedOrders() {
572 SetIteratorOrder *orderit = activeOrders.iterator();
573 while (orderit->hasNext()) {
574 Order *order = orderit->next();
575 inferFixedOrder(order);
579 #define NANOSEC 1000000000.0
580 int CSolver::solve() {
581 long long startTime = getTimeNano();
582 bool deleteTuner = false;
584 tuner = new DefaultTuner();
590 SetIteratorOrder *orderit = activeOrders.iterator();
591 while (orderit->hasNext()) {
592 Order *order = orderit->next();
593 if (order->graph != NULL) {
600 computePolarities(this);
601 long long time1 = getTimeNano();
602 model_print("Polarity time: %f\n", (time1 - startTime) / NANOSEC);
605 long long time2 = getTimeNano();
606 model_print("Preprocess time: %f\n", (time2 - time1) / NANOSEC);
608 DecomposeOrderTransform dot(this);
610 time1 = getTimeNano();
611 model_print("Decompose Order: %f\n", (time1 - time2) / NANOSEC);
613 IntegerEncodingTransform iet(this);
616 ElementOpt eop(this);
619 EncodingGraph eg(this);
622 naiveEncodingDecision(this);
625 time2 = getTimeNano();
626 model_print("Encoding Graph Time: %f\n", (time2 - time1) / NANOSEC);
628 satEncoder->encodeAllSATEncoder(this);
629 time1 = getTimeNano();
631 model_print("Elapse Encode time: %f\n", (time1 - startTime) / NANOSEC);
633 model_print("Is problem UNSAT after encoding: %d\n", unsat);
634 int result = unsat ? IS_UNSAT : satEncoder->solve(satsolverTimeout);
635 model_print("Result Computed in SAT solver:\t%s\n", result == IS_SAT ? "SAT" : result == IS_INDETER ? "INDETERMINATE" : " UNSAT");
636 time2 = getTimeNano();
637 elapsedTime = time2 - startTime;
638 model_print("CSOLVER solve time: %f\n", elapsedTime / NANOSEC);
646 void CSolver::printConstraints() {
647 SetIteratorBooleanEdge *it = getConstraints();
648 while (it->hasNext()) {
649 BooleanEdge b = it->next();
655 void CSolver::printConstraint(BooleanEdge b) {
659 uint64_t CSolver::getElementValue(Element *element) {
660 switch (element->type) {
664 return getElementValueSATTranslator(this, element);
671 bool CSolver::getBooleanValue(BooleanEdge bedge) {
672 Boolean *boolean = bedge.getBoolean();
673 switch (boolean->type) {
675 return getBooleanVariableValueSATTranslator(this, boolean);
682 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
683 return order->encoding.resolver->resolveOrder(first, second);
686 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
688 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
690 void CSolver::autoTune(uint budget) {
691 AutoTuner *autotuner = new AutoTuner(budget);
692 autotuner->addProblem(this);