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"
29 #include "varorderingopt.h"
32 #include "alloyinterpreter.h"
33 #include "smtinterpreter.h"
34 #include "mathsatinterpreter.h"
35 #include "smtratinterpreter.h"
38 boolTrue(BooleanEdge(new BooleanConst(true))),
39 boolFalse(boolTrue.negate()),
41 booleanVarUsed(false),
42 incrementalMode(false),
43 optimizationsOff(false),
46 satsolverTimeout(NOTIMEOUT),
49 satEncoder = new SATEncoder(this);
52 /** This function tears down the solver and the entire AST */
56 uint size = allBooleans.getSize();
57 for (uint i = 0; i < size; i++) {
58 delete allBooleans.get(i);
61 size = allSets.getSize();
62 for (uint i = 0; i < size; i++) {
63 delete allSets.get(i);
66 size = allElements.getSize();
67 for (uint i = 0; i < size; i++) {
68 Element *el = allElements.get(i);
72 size = allTables.getSize();
73 for (uint i = 0; i < size; i++) {
74 delete allTables.get(i);
77 size = allPredicates.getSize();
78 for (uint i = 0; i < size; i++) {
79 delete allPredicates.get(i);
82 size = allOrders.getSize();
83 for (uint i = 0; i < size; i++) {
84 delete allOrders.get(i);
86 size = allFunctions.getSize();
87 for (uint i = 0; i < size; i++) {
88 delete allFunctions.get(i);
91 if (interpreter != NULL) {
95 delete boolTrue.getBoolean();
99 void CSolver::resetSolver() {
101 uint size = allBooleans.getSize();
102 for (uint i = 0; i < size; i++) {
103 delete allBooleans.get(i);
106 size = allSets.getSize();
107 for (uint i = 0; i < size; i++) {
108 delete allSets.get(i);
111 size = allElements.getSize();
112 for (uint i = 0; i < size; i++) {
113 Element *el = allElements.get(i);
117 size = allTables.getSize();
118 for (uint i = 0; i < size; i++) {
119 delete allTables.get(i);
122 size = allPredicates.getSize();
123 for (uint i = 0; i < size; i++) {
124 delete allPredicates.get(i);
127 size = allOrders.getSize();
128 for (uint i = 0; i < size; i++) {
129 delete allOrders.get(i);
131 size = allFunctions.getSize();
132 for (uint i = 0; i < size; i++) {
133 delete allFunctions.get(i);
135 delete boolTrue.getBoolean();
140 allPredicates.clear();
142 allFunctions.clear();
144 encodedConstraints.reset();
145 activeOrders.reset();
149 boolTrue = BooleanEdge(new BooleanConst(true));
150 boolFalse = boolTrue.negate();
152 booleanVarUsed = false;
155 satEncoder->resetSATEncoder();
159 CSolver *CSolver::clone() {
160 CSolver *copy = new CSolver();
162 SetIteratorBooleanEdge *it = getConstraints();
163 while (it->hasNext()) {
164 BooleanEdge b = it->next();
165 copy->addConstraint(cloneEdge(copy, &map, b));
171 CSolver *CSolver::deserialize(const char *file, InterpreterType itype) {
172 model_print("deserializing %s ...\n", file);
173 Deserializer deserializer(file, itype);
174 return deserializer.deserialize();
177 void CSolver::serialize() {
178 model_print("serializing ...\n");
180 long long nanotime = getTimeNano();
181 int numchars = sprintf(buffer, "DUMP%llu", nanotime);
182 Serializer serializer(buffer);
183 SetIteratorBooleanEdge *it = getConstraints();
184 while (it->hasNext()) {
185 BooleanEdge b = it->next();
186 serializeBooleanEdge(&serializer, b, true);
191 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
192 Set *set = new Set(type, elements, numelements);
197 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
198 Set *set = new Set(type, lowrange, highrange);
203 bool CSolver::itemExistInSet(Set *set, uint64_t item) {
204 return set->exists(item);
207 VarType CSolver::getSetVarType(Set *set) {
208 return set->getType();
211 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
212 Set *s = createRangeSet(type, lowrange, highrange);
213 return getElementVar(s);
216 MutableSet *CSolver::createMutableSet(VarType type) {
217 MutableSet *set = new MutableSet(type);
222 void CSolver::addItem(MutableSet *set, uint64_t element) {
223 set->addElementMSet(element);
226 uint64_t CSolver::createUniqueItem(MutableSet *set) {
227 uint64_t element = set->getNewUniqueItem();
228 set->addElementMSet(element);
232 void CSolver::finalizeMutableSet(MutableSet *set) {
236 Element *CSolver::getElementVar(Set *set) {
237 Element *element = new ElementSet(set);
238 allElements.push(element);
242 void CSolver::mustHaveValue(Element *element) {
243 element->anyValue = true;
246 void CSolver::freezeElementsVariables() {
248 for (uint i = 0; i < allElements.getSize(); i++) {
249 Element *e = allElements.get(i);
251 satEncoder->freezeElementVariables(&e->encoding);
257 Set *CSolver::getElementRange (Element *element) {
258 return element->getRange();
262 Element *CSolver::getElementConst(VarType type, uint64_t value) {
263 uint64_t array[] = {value};
264 Set *set = new Set(type, array, 1);
265 Element *element = new ElementConst(value, set);
266 Element *e = elemMap.get(element);
269 allElements.push(element);
270 elemMap.put(element, element);
280 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
281 Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
282 Element *e = elemMap.get(element);
284 element->updateParents();
285 allElements.push(element);
286 elemMap.put(element, element);
294 Function *CSolver::createFunctionOperator(ArithOp op, Set *range, OverFlowBehavior overflowbehavior) {
295 Function *function = new FunctionOperator(op, range, overflowbehavior);
296 allFunctions.push(function);
300 Predicate *CSolver::createPredicateOperator(CompOp op) {
301 Predicate *predicate = new PredicateOperator(op);
302 allPredicates.push(predicate);
306 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
307 Predicate *predicate = new PredicateTable(table, behavior);
308 allPredicates.push(predicate);
312 Table *CSolver::createTable(Set *range) {
313 Table *table = new Table(range);
314 allTables.push(table);
318 Table *CSolver::createTableForPredicate() {
319 return createTable(NULL);
322 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
323 table->addNewTableEntry(inputs, inputSize, result);
326 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
327 Function *function = new FunctionTable(table, behavior);
328 allFunctions.push(function);
332 BooleanEdge CSolver::getBooleanVar(VarType type) {
333 Boolean *boolean = new BooleanVar(type);
334 allBooleans.push(boolean);
336 booleanVarUsed = true;
337 return BooleanEdge(boolean);
340 BooleanEdge CSolver::getBooleanTrue() {
344 BooleanEdge CSolver::getBooleanFalse() {
348 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
349 return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
352 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
353 BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
354 Boolean *b = boolMap.get(boolean);
356 boolean->updateParents();
357 boolMap.put(boolean, boolean);
358 allBooleans.push(boolean);
359 return BooleanEdge(boolean);
362 return BooleanEdge(b);
366 bool CSolver::isTrue(BooleanEdge b) {
367 return b.isNegated() ? b->isFalse() : b->isTrue();
370 bool CSolver::isFalse(BooleanEdge b) {
371 return b.isNegated() ? b->isTrue() : b->isFalse();
374 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
375 BooleanEdge array[] = {arg1, arg2};
376 return applyLogicalOperation(op, array, 2);
379 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
380 BooleanEdge array[] = {arg};
381 return applyLogicalOperation(op, array, 1);
384 static int booleanEdgeCompares(const void *p1, const void *p2) {
385 BooleanEdge be1 = *(BooleanEdge const *) p1;
386 BooleanEdge be2 = *(BooleanEdge const *) p2;
387 uint64_t b1 = be1->id;
388 uint64_t b2 = be2->id;
397 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
398 BooleanEdge newarray[asize];
399 memcpy(newarray, array, asize * sizeof(BooleanEdge));
400 for (uint i = 0; i < asize; i++) {
401 BooleanEdge b = newarray[i];
402 if (b->type == LOGICOP) {
403 if (((BooleanLogic *) b.getBoolean())->replaced) {
404 newarray[i] = doRewrite(newarray[i]);
409 return applyLogicalOperation(op, newarray, asize);
412 BooleanEdge CSolver::applyExactlyOneConstraint (BooleanEdge *array, uint asize) {
413 BooleanEdge newarray[asize + 1];
415 newarray[asize] = applyLogicalOperation(SATC_OR, array, asize);
416 for (uint i = 0; i < asize; i++) {
417 BooleanEdge oprand1 = array[i];
418 BooleanEdge carray [asize - 1];
420 for ( uint j = 0; j < asize; j++) {
422 BooleanEdge oprand2 = applyLogicalOperation(SATC_NOT, array[j]);
423 carray[index++] = applyLogicalOperation(SATC_IMPLIES, oprand1, oprand2);
426 ASSERT(index == asize - 1);
427 newarray[i] = applyLogicalOperation(SATC_AND, carray, asize - 1);
429 return applyLogicalOperation(SATC_AND, newarray, asize + 1);
432 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
433 if (!useInterpreter()) {
434 BooleanEdge newarray[asize];
437 return array[0].negate();
440 for (uint i = 0; i < 2; i++) {
441 if (isTrue(array[i])) { // It can be undefined
443 } else if (isFalse(array[i])) {
444 newarray[0] = array[1 - i];
445 return applyLogicalOperation(SATC_NOT, newarray, 1);
446 } else if (array[i]->type == LOGICOP) {
447 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
449 return rewriteLogicalOperation(op, array, asize);
456 for (uint i = 0; i < asize; i++) {
457 newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
459 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
463 for (uint i = 0; i < asize; i++) {
464 BooleanEdge b = array[i];
465 if (b->type == LOGICOP) {
466 if (((BooleanLogic *)b.getBoolean())->replaced)
467 return rewriteLogicalOperation(op, array, asize);
471 else if (isFalse(b)) {
474 newarray[newindex++] = b;
478 } else if (newindex == 1) {
481 bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
488 //handle by translation
489 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
492 //handle by translation
493 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
498 Boolean *boolean = new BooleanLogic(this, op, array, asize);
499 Boolean *b = boolMap.get(boolean);
501 boolean->updateParents();
502 boolMap.put(boolean, boolean);
503 allBooleans.push(boolean);
504 return BooleanEdge(boolean);
507 return BooleanEdge(b);
511 Boolean *boolean = new BooleanLogic(this, op, array, asize);
512 allBooleans.push(boolean);
513 return BooleanEdge(boolean);
518 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
519 // ASSERT(first != second);
521 return getBooleanFalse();
524 if (order->type == SATC_TOTAL) {
525 if (first > second) {
526 uint64_t tmp = first;
532 Boolean *constraint = new BooleanOrder(order, first, second);
533 if (!useInterpreter() ) {
534 Boolean *b = boolMap.get(constraint);
537 allBooleans.push(constraint);
538 boolMap.put(constraint, constraint);
539 constraint->updateParents();
540 if ( order->graph != NULL) {
541 OrderGraph *graph = order->graph;
542 OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
544 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
546 OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
549 if (edge != NULL && edge->mustPos) {
550 replaceBooleanWithTrueNoRemove(constraint);
551 } else if (edge != NULL && edge->mustNeg) {
552 replaceBooleanWithFalseNoRemove(constraint);
553 } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
554 && invedge->mustPos) {
555 replaceBooleanWithFalseNoRemove(constraint);
565 BooleanEdge be = BooleanEdge(constraint);
566 return negate ? be.negate() : be;
569 void CSolver::addConstraint(BooleanEdge constraint) {
570 if (!useInterpreter() && !optimizationsOff) {
571 if (isTrue(constraint))
573 else if (isFalse(constraint)) {
577 if (constraint->type == LOGICOP) {
578 BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
579 if (!constraint.isNegated()) {
580 if (b->op == SATC_AND) {
581 uint size = b->inputs.getSize();
582 //Handle potential concurrent modification
583 BooleanEdge array[size];
584 for (uint i = 0; i < size; i++) {
585 array[i] = b->inputs.get(i);
587 for (uint i = 0; i < size; i++) {
588 addConstraint(array[i]);
594 addConstraint(doRewrite(constraint));
598 constraints.add(constraint);
599 Boolean *ptr = constraint.getBoolean();
601 if (ptr->boolVal == BV_UNSAT) {
605 replaceBooleanWithTrueNoRemove(constraint);
606 constraint->parents.clear();
609 constraints.add(constraint);
610 constraint->parents.clear();
614 Order *CSolver::createOrder(OrderType type, Set *set) {
615 Order *order = new Order(type, set);
616 allOrders.push(order);
617 activeOrders.add(order);
621 /** Computes static ordering information to allow isTrue/isFalse
622 queries on newly created orders to work. */
624 void CSolver::inferFixedOrder(Order *order) {
625 if (order->graph != NULL) {
628 order->graph = buildMustOrderGraph(order);
629 reachMustAnalysis(this, order->graph, true);
632 void CSolver::inferFixedOrders() {
633 SetIteratorOrder *orderit = activeOrders.iterator();
634 while (orderit->hasNext()) {
635 Order *order = orderit->next();
636 inferFixedOrder(order);
640 int CSolver::solveIncremental() {
646 long long startTime = getTimeNano();
647 bool deleteTuner = false;
649 tuner = new DefaultTuner();
652 int result = IS_INDETER;
653 ASSERT (!useInterpreter());
654 if(!optimizationsOff){
655 computePolarities(this);
657 // long long time1 = getTimeNano();
658 // model_print("Polarity time: %f\n", (time1 - startTime) / NANOSEC);
659 // Preprocess pp(this);
661 // long long time2 = getTimeNano();
662 // model_print("Preprocess time: %f\n", (time2 - time1) / NANOSEC);
664 // DecomposeOrderTransform dot(this);
665 // dot.doTransform();
666 // time1 = getTimeNano();
667 // model_print("Decompose Order: %f\n", (time1 - time2) / NANOSEC);
669 // IntegerEncodingTransform iet(this);
670 // iet.doTransform();
672 //Doing element optimization on new constraints
673 // ElementOpt eop(this);
674 // eop.doTransform();
676 //Since no new element is added, we assuming adding new constraint
677 //has no impact on previous encoding decisions
678 // EncodingGraph eg(this);
681 naiveEncodingDecision(this);
683 //Order of sat solver variables don't change!
684 // VarOrderingOpt bor(this, satEncoder);
685 // bor.doTransform();
687 long long time2 = getTimeNano();
688 //Encoding newly added constraints
689 satEncoder->encodeAllSATEncoder(this);
690 long long time1 = getTimeNano();
692 model_print("Elapse Encode time: %f\n", (time1 - startTime) / NANOSEC);
694 model_print("Is problem UNSAT after encoding: %d\n", unsat);
696 result = unsat ? IS_UNSAT : satEncoder->solve(satsolverTimeout);
697 model_print("Result Computed in SAT solver:\t%s\n", result == IS_SAT ? "SAT" : result == IS_INDETER ? "INDETERMINATE" : " UNSAT");
698 time2 = getTimeNano();
699 elapsedTime = time2 - startTime;
700 model_print("CSOLVER solve time: %f\n", elapsedTime / NANOSEC);
709 int CSolver::solve() {
713 long long startTime = getTimeNano();
714 bool deleteTuner = false;
716 tuner = new DefaultTuner();
719 int result = IS_INDETER;
720 if (useInterpreter()) {
721 interpreter->encode();
722 model_print("Problem encoded in Interpreter\n");
723 result = interpreter->solve();
724 model_print("Problem solved by Interpreter\n");
728 SetIteratorOrder *orderit = activeOrders.iterator();
729 while (orderit->hasNext()) {
730 Order *order = orderit->next();
731 if (order->graph != NULL) {
738 long long time1, time2;
740 computePolarities(this);
741 time1 = getTimeNano();
742 model_print("Polarity time: %f\n", (time1 - startTime) / NANOSEC);
743 if(!optimizationsOff){
746 time2 = getTimeNano();
747 model_print("Preprocess time: %f\n", (time2 - time1) / NANOSEC);
749 DecomposeOrderTransform dot(this);
751 time1 = getTimeNano();
752 model_print("Decompose Order: %f\n", (time1 - time2) / NANOSEC);
754 IntegerEncodingTransform iet(this);
757 ElementOpt eop(this);
760 EncodingGraph eg(this);
763 naiveEncodingDecision(this);
765 if(!optimizationsOff){
766 VarOrderingOpt bor(this, satEncoder);
768 time2 = getTimeNano();
769 model_print("Encoding Graph Time: %f\n", (time2 - time1) / NANOSEC);
772 satEncoder->encodeAllSATEncoder(this);
773 time1 = getTimeNano();
775 model_print("Elapse Encode time: %f\n", (time1 - startTime) / NANOSEC);
777 model_print("Is problem UNSAT after encoding: %d\n", unsat);
780 result = unsat ? IS_UNSAT : satEncoder->solve(satsolverTimeout);
781 model_print("Result Computed in SAT solver:\t%s\n", result == IS_SAT ? "SAT" : result == IS_INDETER ? "INDETERMINATE" : " UNSAT");
782 time2 = getTimeNano();
783 elapsedTime = time2 - startTime;
784 model_print("CSOLVER solve time: %f\n", elapsedTime / NANOSEC);
793 void CSolver::setInterpreter(InterpreterType type) {
794 if (interpreter == NULL) {
799 interpreter = new AlloyInterpreter(this);
802 interpreter = new SMTInterpreter(this);
806 interpreter = new MathSATInterpreter(this);
810 interpreter = new SMTRatInterpreter(this);
819 void CSolver::printConstraints() {
820 SetIteratorBooleanEdge *it = getConstraints();
821 while (it->hasNext()) {
822 BooleanEdge b = it->next();
828 void CSolver::printConstraint(BooleanEdge b) {
832 uint64_t CSolver::getElementValue(Element *element) {
833 switch (element->type) {
837 return useInterpreter() ? interpreter->getValue(element) :
838 getElementValueSATTranslator(this, element);
845 void CSolver::freezeElement(Element *e) {
847 if (!incrementalMode) {
848 incrementalMode = true;
852 bool CSolver::getBooleanValue(BooleanEdge bedge) {
853 Boolean *boolean = bedge.getBoolean();
854 switch (boolean->type) {
856 return useInterpreter() ? interpreter->getBooleanValue(boolean) :
857 getBooleanVariableValueSATTranslator(this, boolean);
864 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
865 return order->encoding.resolver->resolveOrder(first, second);
868 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
870 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
872 void CSolver::autoTune(uint budget) {
873 AutoTuner *autotuner = new AutoTuner(budget);
874 autotuner->addProblem(this);