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),
44 satsolverTimeout(NOTIMEOUT),
47 satEncoder = new SATEncoder(this);
50 /** This function tears down the solver and the entire AST */
54 uint size = allBooleans.getSize();
55 for (uint i = 0; i < size; i++) {
56 delete allBooleans.get(i);
59 size = allSets.getSize();
60 for (uint i = 0; i < size; i++) {
61 delete allSets.get(i);
64 size = allElements.getSize();
65 for (uint i = 0; i < size; i++) {
66 Element *el = allElements.get(i);
70 size = allTables.getSize();
71 for (uint i = 0; i < size; i++) {
72 delete allTables.get(i);
75 size = allPredicates.getSize();
76 for (uint i = 0; i < size; i++) {
77 delete allPredicates.get(i);
80 size = allOrders.getSize();
81 for (uint i = 0; i < size; i++) {
82 delete allOrders.get(i);
84 size = allFunctions.getSize();
85 for (uint i = 0; i < size; i++) {
86 delete allFunctions.get(i);
89 if (interpreter != NULL) {
93 delete boolTrue.getBoolean();
97 void CSolver::resetSolver() {
99 uint size = allBooleans.getSize();
100 for (uint i = 0; i < size; i++) {
101 delete allBooleans.get(i);
104 size = allSets.getSize();
105 for (uint i = 0; i < size; i++) {
106 delete allSets.get(i);
109 size = allElements.getSize();
110 for (uint i = 0; i < size; i++) {
111 Element *el = allElements.get(i);
115 size = allTables.getSize();
116 for (uint i = 0; i < size; i++) {
117 delete allTables.get(i);
120 size = allPredicates.getSize();
121 for (uint i = 0; i < size; i++) {
122 delete allPredicates.get(i);
125 size = allOrders.getSize();
126 for (uint i = 0; i < size; i++) {
127 delete allOrders.get(i);
129 size = allFunctions.getSize();
130 for (uint i = 0; i < size; i++) {
131 delete allFunctions.get(i);
133 delete boolTrue.getBoolean();
138 allPredicates.clear();
140 allFunctions.clear();
142 activeOrders.reset();
146 boolTrue = BooleanEdge(new BooleanConst(true));
147 boolFalse = boolTrue.negate();
149 booleanVarUsed = false;
152 satEncoder->resetSATEncoder();
156 CSolver *CSolver::clone() {
157 CSolver *copy = new CSolver();
159 SetIteratorBooleanEdge *it = getConstraints();
160 while (it->hasNext()) {
161 BooleanEdge b = it->next();
162 copy->addConstraint(cloneEdge(copy, &map, b));
168 CSolver *CSolver::deserialize(const char *file, InterpreterType itype) {
169 model_print("deserializing %s ...\n", file);
170 Deserializer deserializer(file, itype);
171 return deserializer.deserialize();
174 void CSolver::serialize() {
175 model_print("serializing ...\n");
177 long long nanotime = getTimeNano();
178 int numchars = sprintf(buffer, "DUMP%llu", nanotime);
179 Serializer serializer(buffer);
180 SetIteratorBooleanEdge *it = getConstraints();
181 while (it->hasNext()) {
182 BooleanEdge b = it->next();
183 serializeBooleanEdge(&serializer, b, true);
188 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
189 Set *set = new Set(type, elements, numelements);
194 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
195 Set *set = new Set(type, lowrange, highrange);
200 bool CSolver::itemExistInSet(Set *set, uint64_t item) {
201 return set->exists(item);
204 VarType CSolver::getSetVarType(Set *set) {
205 return set->getType();
208 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
209 Set *s = createRangeSet(type, lowrange, highrange);
210 return getElementVar(s);
213 MutableSet *CSolver::createMutableSet(VarType type) {
214 MutableSet *set = new MutableSet(type);
219 void CSolver::addItem(MutableSet *set, uint64_t element) {
220 set->addElementMSet(element);
223 uint64_t CSolver::createUniqueItem(MutableSet *set) {
224 uint64_t element = set->getNewUniqueItem();
225 set->addElementMSet(element);
229 void CSolver::finalizeMutableSet(MutableSet *set) {
233 Element *CSolver::getElementVar(Set *set) {
234 Element *element = new ElementSet(set);
235 allElements.push(element);
239 void CSolver::mustHaveValue(Element *element) {
240 element->anyValue = true;
243 Set *CSolver::getElementRange (Element *element) {
244 return element->getRange();
248 Element *CSolver::getElementConst(VarType type, uint64_t value) {
249 uint64_t array[] = {value};
250 Set *set = new Set(type, array, 1);
251 Element *element = new ElementConst(value, set);
252 Element *e = elemMap.get(element);
255 allElements.push(element);
256 elemMap.put(element, element);
266 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
267 Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
268 Element *e = elemMap.get(element);
270 element->updateParents();
271 allElements.push(element);
272 elemMap.put(element, element);
280 Function *CSolver::createFunctionOperator(ArithOp op, Set *range, OverFlowBehavior overflowbehavior) {
281 Function *function = new FunctionOperator(op, range, overflowbehavior);
282 allFunctions.push(function);
286 Predicate *CSolver::createPredicateOperator(CompOp op) {
287 Predicate *predicate = new PredicateOperator(op);
288 allPredicates.push(predicate);
292 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
293 Predicate *predicate = new PredicateTable(table, behavior);
294 allPredicates.push(predicate);
298 Table *CSolver::createTable(Set *range) {
299 Table *table = new Table(range);
300 allTables.push(table);
304 Table *CSolver::createTableForPredicate() {
305 return createTable(NULL);
308 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
309 table->addNewTableEntry(inputs, inputSize, result);
312 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
313 Function *function = new FunctionTable(table, behavior);
314 allFunctions.push(function);
318 BooleanEdge CSolver::getBooleanVar(VarType type) {
319 Boolean *boolean = new BooleanVar(type);
320 allBooleans.push(boolean);
322 booleanVarUsed = true;
323 return BooleanEdge(boolean);
326 BooleanEdge CSolver::getBooleanTrue() {
330 BooleanEdge CSolver::getBooleanFalse() {
334 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
335 return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
338 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
339 BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
340 Boolean *b = boolMap.get(boolean);
342 boolean->updateParents();
343 boolMap.put(boolean, boolean);
344 allBooleans.push(boolean);
345 return BooleanEdge(boolean);
348 return BooleanEdge(b);
352 bool CSolver::isTrue(BooleanEdge b) {
353 return b.isNegated() ? b->isFalse() : b->isTrue();
356 bool CSolver::isFalse(BooleanEdge b) {
357 return b.isNegated() ? b->isTrue() : b->isFalse();
360 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
361 BooleanEdge array[] = {arg1, arg2};
362 return applyLogicalOperation(op, array, 2);
365 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
366 BooleanEdge array[] = {arg};
367 return applyLogicalOperation(op, array, 1);
370 static int booleanEdgeCompares(const void *p1, const void *p2) {
371 BooleanEdge be1 = *(BooleanEdge const *) p1;
372 BooleanEdge be2 = *(BooleanEdge const *) p2;
373 uint64_t b1 = be1->id;
374 uint64_t b2 = be2->id;
383 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
384 BooleanEdge newarray[asize];
385 memcpy(newarray, array, asize * sizeof(BooleanEdge));
386 for (uint i = 0; i < asize; i++) {
387 BooleanEdge b = newarray[i];
388 if (b->type == LOGICOP) {
389 if (((BooleanLogic *) b.getBoolean())->replaced) {
390 newarray[i] = doRewrite(newarray[i]);
395 return applyLogicalOperation(op, newarray, asize);
398 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
399 if (!useInterpreter()) {
400 BooleanEdge newarray[asize];
403 return array[0].negate();
406 for (uint i = 0; i < 2; i++) {
407 if (isTrue(array[i])) { // It can be undefined
409 } else if (isFalse(array[i])) {
410 newarray[0] = array[1 - i];
411 return applyLogicalOperation(SATC_NOT, newarray, 1);
412 } else if (array[i]->type == LOGICOP) {
413 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
415 return rewriteLogicalOperation(op, array, asize);
422 for (uint i = 0; i < asize; i++) {
423 newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
425 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
429 for (uint i = 0; i < asize; i++) {
430 BooleanEdge b = array[i];
431 if (b->type == LOGICOP) {
432 if (((BooleanLogic *)b.getBoolean())->replaced)
433 return rewriteLogicalOperation(op, array, asize);
437 else if (isFalse(b)) {
440 newarray[newindex++] = b;
444 } else if (newindex == 1) {
447 bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
454 //handle by translation
455 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
458 //handle by translation
459 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
464 Boolean *boolean = new BooleanLogic(this, op, array, asize);
465 Boolean *b = boolMap.get(boolean);
467 boolean->updateParents();
468 boolMap.put(boolean, boolean);
469 allBooleans.push(boolean);
470 return BooleanEdge(boolean);
473 return BooleanEdge(b);
477 Boolean *boolean = new BooleanLogic(this, op, array, asize);
478 allBooleans.push(boolean);
479 return BooleanEdge(boolean);
484 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
485 // ASSERT(first != second);
487 return getBooleanFalse();
490 if (order->type == SATC_TOTAL) {
491 if (first > second) {
492 uint64_t tmp = first;
498 Boolean *constraint = new BooleanOrder(order, first, second);
499 if (!useInterpreter() ) {
500 Boolean *b = boolMap.get(constraint);
503 allBooleans.push(constraint);
504 boolMap.put(constraint, constraint);
505 constraint->updateParents();
506 if ( order->graph != NULL) {
507 OrderGraph *graph = order->graph;
508 OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
510 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
512 OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
515 if (edge != NULL && edge->mustPos) {
516 replaceBooleanWithTrueNoRemove(constraint);
517 } else if (edge != NULL && edge->mustNeg) {
518 replaceBooleanWithFalseNoRemove(constraint);
519 } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
520 && invedge->mustPos) {
521 replaceBooleanWithFalseNoRemove(constraint);
531 BooleanEdge be = BooleanEdge(constraint);
532 return negate ? be.negate() : be;
535 void CSolver::addConstraint(BooleanEdge constraint) {
536 if (!useInterpreter()) {
537 if (isTrue(constraint))
539 else if (isFalse(constraint)) {
543 if (constraint->type == LOGICOP) {
544 BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
545 if (!constraint.isNegated()) {
546 if (b->op == SATC_AND) {
547 uint size = b->inputs.getSize();
548 //Handle potential concurrent modification
549 BooleanEdge array[size];
550 for (uint i = 0; i < size; i++) {
551 array[i] = b->inputs.get(i);
553 for (uint i = 0; i < size; i++) {
554 addConstraint(array[i]);
560 addConstraint(doRewrite(constraint));
564 constraints.add(constraint);
565 Boolean *ptr = constraint.getBoolean();
567 if (ptr->boolVal == BV_UNSAT) {
571 replaceBooleanWithTrueNoRemove(constraint);
572 constraint->parents.clear();
575 constraints.add(constraint);
576 constraint->parents.clear();
580 Order *CSolver::createOrder(OrderType type, Set *set) {
581 Order *order = new Order(type, set);
582 allOrders.push(order);
583 activeOrders.add(order);
587 /** Computes static ordering information to allow isTrue/isFalse
588 queries on newly created orders to work. */
590 void CSolver::inferFixedOrder(Order *order) {
591 if (order->graph != NULL) {
594 order->graph = buildMustOrderGraph(order);
595 reachMustAnalysis(this, order->graph, true);
598 void CSolver::inferFixedOrders() {
599 SetIteratorOrder *orderit = activeOrders.iterator();
600 while (orderit->hasNext()) {
601 Order *order = orderit->next();
602 inferFixedOrder(order);
606 int CSolver::solve() {
610 long long startTime = getTimeNano();
611 bool deleteTuner = false;
613 tuner = new DefaultTuner();
616 int result = IS_INDETER;
617 if (useInterpreter()) {
618 interpreter->encode();
619 model_print("Problem encoded in Interpreter\n");
620 result = interpreter->solve();
621 model_print("Problem solved by Interpreter\n");
625 SetIteratorOrder *orderit = activeOrders.iterator();
626 while (orderit->hasNext()) {
627 Order *order = orderit->next();
628 if (order->graph != NULL) {
635 computePolarities(this);
636 long long time1 = getTimeNano();
637 model_print("Polarity time: %f\n", (time1 - startTime) / NANOSEC);
640 long long time2 = getTimeNano();
641 model_print("Preprocess time: %f\n", (time2 - time1) / NANOSEC);
643 DecomposeOrderTransform dot(this);
645 time1 = getTimeNano();
646 model_print("Decompose Order: %f\n", (time1 - time2) / NANOSEC);
648 IntegerEncodingTransform iet(this);
651 ElementOpt eop(this);
654 EncodingGraph eg(this);
657 naiveEncodingDecision(this);
660 VarOrderingOpt bor(this, satEncoder);
663 time2 = getTimeNano();
664 model_print("Encoding Graph Time: %f\n", (time2 - time1) / NANOSEC);
666 satEncoder->encodeAllSATEncoder(this);
667 time1 = getTimeNano();
669 model_print("Elapse Encode time: %f\n", (time1 - startTime) / NANOSEC);
671 model_print("Is problem UNSAT after encoding: %d\n", unsat);
674 result = unsat ? IS_UNSAT : satEncoder->solve(satsolverTimeout);
675 model_print("Result Computed in SAT solver:\t%s\n", result == IS_SAT ? "SAT" : result == IS_INDETER ? "INDETERMINATE" : " UNSAT");
676 time2 = getTimeNano();
677 elapsedTime = time2 - startTime;
678 model_print("CSOLVER solve time: %f\n", elapsedTime / NANOSEC);
687 void CSolver::setInterpreter(InterpreterType type) {
688 if (interpreter == NULL) {
693 interpreter = new AlloyInterpreter(this);
696 interpreter = new SMTInterpreter(this);
700 interpreter = new MathSATInterpreter(this);
704 interpreter = new SMTRatInterpreter(this);
713 void CSolver::printConstraints() {
714 SetIteratorBooleanEdge *it = getConstraints();
715 while (it->hasNext()) {
716 BooleanEdge b = it->next();
722 void CSolver::printConstraint(BooleanEdge b) {
726 uint64_t CSolver::getElementValue(Element *element) {
727 switch (element->type) {
731 return useInterpreter() ? interpreter->getValue(element) :
732 getElementValueSATTranslator(this, element);
739 bool CSolver::getBooleanValue(BooleanEdge bedge) {
740 Boolean *boolean = bedge.getBoolean();
741 switch (boolean->type) {
743 return useInterpreter() ? interpreter->getBooleanValue(boolean) :
744 getBooleanVariableValueSATTranslator(this, boolean);
751 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
752 return order->encoding.resolver->resolveOrder(first, second);
755 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
757 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
759 void CSolver::autoTune(uint budget) {
760 AutoTuner *autotuner = new AutoTuner(budget);
761 autotuner->addProblem(this);