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::applyExactlyOneConstraint (BooleanEdge *array, uint asize){
399 BooleanEdge newarray[asize + 1];
401 newarray[asize] = applyLogicalOperation(SATC_OR, array, asize);
402 for (uint i=0; i< asize; i++){
403 BooleanEdge oprand1 = array[i];
404 BooleanEdge carray [asize -1];
406 for( uint j =0; j< asize; j++){
408 BooleanEdge oprand2 = applyLogicalOperation(SATC_NOT, array[j]);
409 carray[index++] = applyLogicalOperation(SATC_IMPLIES, oprand1, oprand2);
412 ASSERT(index == asize -1);
413 newarray[i] = applyLogicalOperation(SATC_AND, carray, asize-1);
415 return applyLogicalOperation(SATC_AND, newarray, asize+1);
418 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
419 if (!useInterpreter()) {
420 BooleanEdge newarray[asize];
423 return array[0].negate();
426 for (uint i = 0; i < 2; i++) {
427 if (isTrue(array[i])) { // It can be undefined
429 } else if (isFalse(array[i])) {
430 newarray[0] = array[1 - i];
431 return applyLogicalOperation(SATC_NOT, newarray, 1);
432 } else if (array[i]->type == LOGICOP) {
433 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
435 return rewriteLogicalOperation(op, array, asize);
442 for (uint i = 0; i < asize; i++) {
443 newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
445 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
449 for (uint i = 0; i < asize; i++) {
450 BooleanEdge b = array[i];
451 if (b->type == LOGICOP) {
452 if (((BooleanLogic *)b.getBoolean())->replaced)
453 return rewriteLogicalOperation(op, array, asize);
457 else if (isFalse(b)) {
460 newarray[newindex++] = b;
464 } else if (newindex == 1) {
467 bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
474 //handle by translation
475 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
478 //handle by translation
479 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
484 Boolean *boolean = new BooleanLogic(this, op, array, asize);
485 Boolean *b = boolMap.get(boolean);
487 boolean->updateParents();
488 boolMap.put(boolean, boolean);
489 allBooleans.push(boolean);
490 return BooleanEdge(boolean);
493 return BooleanEdge(b);
497 Boolean *boolean = new BooleanLogic(this, op, array, asize);
498 allBooleans.push(boolean);
499 return BooleanEdge(boolean);
504 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
505 // ASSERT(first != second);
507 return getBooleanFalse();
510 if (order->type == SATC_TOTAL) {
511 if (first > second) {
512 uint64_t tmp = first;
518 Boolean *constraint = new BooleanOrder(order, first, second);
519 if (!useInterpreter() ) {
520 Boolean *b = boolMap.get(constraint);
523 allBooleans.push(constraint);
524 boolMap.put(constraint, constraint);
525 constraint->updateParents();
526 if ( order->graph != NULL) {
527 OrderGraph *graph = order->graph;
528 OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
530 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
532 OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
535 if (edge != NULL && edge->mustPos) {
536 replaceBooleanWithTrueNoRemove(constraint);
537 } else if (edge != NULL && edge->mustNeg) {
538 replaceBooleanWithFalseNoRemove(constraint);
539 } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
540 && invedge->mustPos) {
541 replaceBooleanWithFalseNoRemove(constraint);
551 BooleanEdge be = BooleanEdge(constraint);
552 return negate ? be.negate() : be;
555 void CSolver::addConstraint(BooleanEdge constraint) {
556 if (!useInterpreter()) {
557 if (isTrue(constraint))
559 else if (isFalse(constraint)) {
563 if (constraint->type == LOGICOP) {
564 BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
565 if (!constraint.isNegated()) {
566 if (b->op == SATC_AND) {
567 uint size = b->inputs.getSize();
568 //Handle potential concurrent modification
569 BooleanEdge array[size];
570 for (uint i = 0; i < size; i++) {
571 array[i] = b->inputs.get(i);
573 for (uint i = 0; i < size; i++) {
574 addConstraint(array[i]);
580 addConstraint(doRewrite(constraint));
584 constraints.add(constraint);
585 Boolean *ptr = constraint.getBoolean();
587 if (ptr->boolVal == BV_UNSAT) {
591 replaceBooleanWithTrueNoRemove(constraint);
592 constraint->parents.clear();
595 constraints.add(constraint);
596 constraint->parents.clear();
600 Order *CSolver::createOrder(OrderType type, Set *set) {
601 Order *order = new Order(type, set);
602 allOrders.push(order);
603 activeOrders.add(order);
607 /** Computes static ordering information to allow isTrue/isFalse
608 queries on newly created orders to work. */
610 void CSolver::inferFixedOrder(Order *order) {
611 if (order->graph != NULL) {
614 order->graph = buildMustOrderGraph(order);
615 reachMustAnalysis(this, order->graph, true);
618 void CSolver::inferFixedOrders() {
619 SetIteratorOrder *orderit = activeOrders.iterator();
620 while (orderit->hasNext()) {
621 Order *order = orderit->next();
622 inferFixedOrder(order);
626 int CSolver::solve() {
630 long long startTime = getTimeNano();
631 bool deleteTuner = false;
633 tuner = new DefaultTuner();
636 int result = IS_INDETER;
637 if (useInterpreter()) {
638 interpreter->encode();
639 model_print("Problem encoded in Interpreter\n");
640 result = interpreter->solve();
641 model_print("Problem solved by Interpreter\n");
645 SetIteratorOrder *orderit = activeOrders.iterator();
646 while (orderit->hasNext()) {
647 Order *order = orderit->next();
648 if (order->graph != NULL) {
655 computePolarities(this);
656 long long time1 = getTimeNano();
657 model_print("Polarity time: %f\n", (time1 - startTime) / NANOSEC);
660 long long time2 = getTimeNano();
661 model_print("Preprocess time: %f\n", (time2 - time1) / NANOSEC);
663 DecomposeOrderTransform dot(this);
665 time1 = getTimeNano();
666 model_print("Decompose Order: %f\n", (time1 - time2) / NANOSEC);
668 IntegerEncodingTransform iet(this);
671 ElementOpt eop(this);
674 EncodingGraph eg(this);
677 naiveEncodingDecision(this);
680 VarOrderingOpt bor(this, satEncoder);
683 time2 = getTimeNano();
684 model_print("Encoding Graph Time: %f\n", (time2 - time1) / NANOSEC);
686 satEncoder->encodeAllSATEncoder(this);
687 time1 = getTimeNano();
689 model_print("Elapse Encode time: %f\n", (time1 - startTime) / NANOSEC);
691 model_print("Is problem UNSAT after encoding: %d\n", unsat);
694 result = unsat ? IS_UNSAT : satEncoder->solve(satsolverTimeout);
695 model_print("Result Computed in SAT solver:\t%s\n", result == IS_SAT ? "SAT" : result == IS_INDETER ? "INDETERMINATE" : " UNSAT");
696 time2 = getTimeNano();
697 elapsedTime = time2 - startTime;
698 model_print("CSOLVER solve time: %f\n", elapsedTime / NANOSEC);
707 void CSolver::setInterpreter(InterpreterType type) {
708 if (interpreter == NULL) {
713 interpreter = new AlloyInterpreter(this);
716 interpreter = new SMTInterpreter(this);
720 interpreter = new MathSATInterpreter(this);
724 interpreter = new SMTRatInterpreter(this);
733 void CSolver::printConstraints() {
734 SetIteratorBooleanEdge *it = getConstraints();
735 while (it->hasNext()) {
736 BooleanEdge b = it->next();
742 void CSolver::printConstraint(BooleanEdge b) {
746 uint64_t CSolver::getElementValue(Element *element) {
747 switch (element->type) {
751 return useInterpreter() ? interpreter->getValue(element) :
752 getElementValueSATTranslator(this, element);
759 bool CSolver::getBooleanValue(BooleanEdge bedge) {
760 Boolean *boolean = bedge.getBoolean();
761 switch (boolean->type) {
763 return useInterpreter() ? interpreter->getBooleanValue(boolean) :
764 getBooleanVariableValueSATTranslator(this, boolean);
771 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
772 return order->encoding.resolver->resolveOrder(first, second);
775 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
777 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
779 void CSolver::autoTune(uint budget) {
780 AutoTuner *autotuner = new AutoTuner(budget);
781 autotuner->addProblem(this);