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"
35 boolTrue(BooleanEdge(new BooleanConst(true))),
36 boolFalse(boolTrue.negate()),
38 booleanVarUsed(false),
41 satsolverTimeout(NOTIMEOUT),
44 satEncoder = new SATEncoder(this);
47 /** This function tears down the solver and the entire AST */
51 uint size = allBooleans.getSize();
52 for (uint i = 0; i < size; i++) {
53 delete allBooleans.get(i);
56 size = allSets.getSize();
57 for (uint i = 0; i < size; i++) {
58 delete allSets.get(i);
61 size = allElements.getSize();
62 for (uint i = 0; i < size; i++) {
63 Element *el = allElements.get(i);
67 size = allTables.getSize();
68 for (uint i = 0; i < size; i++) {
69 delete allTables.get(i);
72 size = allPredicates.getSize();
73 for (uint i = 0; i < size; i++) {
74 delete allPredicates.get(i);
77 size = allOrders.getSize();
78 for (uint i = 0; i < size; i++) {
79 delete allOrders.get(i);
81 size = allFunctions.getSize();
82 for (uint i = 0; i < size; i++) {
83 delete allFunctions.get(i);
86 delete boolTrue.getBoolean();
90 void CSolver::resetSolver() {
92 uint size = allBooleans.getSize();
93 for (uint i = 0; i < size; i++) {
94 delete allBooleans.get(i);
97 size = allSets.getSize();
98 for (uint i = 0; i < size; i++) {
99 delete allSets.get(i);
102 size = allElements.getSize();
103 for (uint i = 0; i < size; i++) {
104 Element *el = allElements.get(i);
108 size = allTables.getSize();
109 for (uint i = 0; i < size; i++) {
110 delete allTables.get(i);
113 size = allPredicates.getSize();
114 for (uint i = 0; i < size; i++) {
115 delete allPredicates.get(i);
118 size = allOrders.getSize();
119 for (uint i = 0; i < size; i++) {
120 delete allOrders.get(i);
122 size = allFunctions.getSize();
123 for (uint i = 0; i < size; i++) {
124 delete allFunctions.get(i);
126 delete boolTrue.getBoolean();
131 allPredicates.clear();
133 allFunctions.clear();
135 activeOrders.reset();
139 boolTrue = BooleanEdge(new BooleanConst(true));
140 boolFalse = boolTrue.negate();
142 booleanVarUsed = false;
145 satEncoder->resetSATEncoder();
149 CSolver *CSolver::clone() {
150 CSolver *copy = new CSolver();
152 SetIteratorBooleanEdge *it = getConstraints();
153 while (it->hasNext()) {
154 BooleanEdge b = it->next();
155 copy->addConstraint(cloneEdge(copy, &map, b));
161 CSolver *CSolver::deserialize(const char *file, bool alloy) {
162 model_print("deserializing %s ...\n", file);
163 Deserializer deserializer(file, alloy);
164 return deserializer.deserialize();
167 void CSolver::serialize() {
168 model_print("serializing ...\n");
170 long long nanotime = getTimeNano();
171 int numchars = sprintf(buffer, "DUMP%llu", nanotime);
172 Serializer serializer(buffer);
173 SetIteratorBooleanEdge *it = getConstraints();
174 while (it->hasNext()) {
175 BooleanEdge b = it->next();
176 serializeBooleanEdge(&serializer, b, true);
181 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
182 Set *set = new Set(type, elements, numelements);
187 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
188 Set *set = new Set(type, lowrange, highrange);
193 bool CSolver::itemExistInSet(Set *set, uint64_t item) {
194 return set->exists(item);
197 VarType CSolver::getSetVarType(Set *set) {
198 return set->getType();
201 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
202 Set *s = createRangeSet(type, lowrange, highrange);
203 return getElementVar(s);
206 MutableSet *CSolver::createMutableSet(VarType type) {
207 MutableSet *set = new MutableSet(type);
212 void CSolver::addItem(MutableSet *set, uint64_t element) {
213 set->addElementMSet(element);
216 uint64_t CSolver::createUniqueItem(MutableSet *set) {
217 uint64_t element = set->getNewUniqueItem();
218 set->addElementMSet(element);
222 void CSolver::finalizeMutableSet(MutableSet *set) {
226 Element *CSolver::getElementVar(Set *set) {
227 Element *element = new ElementSet(set);
228 allElements.push(element);
232 void CSolver::mustHaveValue(Element *element) {
233 element->anyValue = true;
236 Set *CSolver::getElementRange (Element *element) {
237 return element->getRange();
241 Element *CSolver::getElementConst(VarType type, uint64_t value) {
242 uint64_t array[] = {value};
243 Set *set = new Set(type, array, 1);
244 Element *element = new ElementConst(value, set);
245 Element *e = elemMap.get(element);
248 allElements.push(element);
249 elemMap.put(element, element);
259 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
260 ASSERT(numArrays == 2);
261 Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
262 Element *e = elemMap.get(element);
264 element->updateParents();
265 allElements.push(element);
266 elemMap.put(element, element);
274 Function *CSolver::createFunctionOperator(ArithOp op, Set *range, OverFlowBehavior overflowbehavior) {
275 Function *function = new FunctionOperator(op, range, overflowbehavior);
276 allFunctions.push(function);
280 Predicate *CSolver::createPredicateOperator(CompOp op) {
281 Predicate *predicate = new PredicateOperator(op);
282 allPredicates.push(predicate);
286 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
287 Predicate *predicate = new PredicateTable(table, behavior);
288 allPredicates.push(predicate);
292 Table *CSolver::createTable(Set *range) {
293 Table *table = new Table(range);
294 allTables.push(table);
298 Table *CSolver::createTableForPredicate() {
299 return createTable(NULL);
302 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
303 table->addNewTableEntry(inputs, inputSize, result);
306 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
307 Function *function = new FunctionTable(table, behavior);
308 allFunctions.push(function);
312 BooleanEdge CSolver::getBooleanVar(VarType type) {
313 Boolean *boolean = new BooleanVar(type);
314 allBooleans.push(boolean);
316 booleanVarUsed = true;
317 return BooleanEdge(boolean);
320 BooleanEdge CSolver::getBooleanTrue() {
324 BooleanEdge CSolver::getBooleanFalse() {
328 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
329 return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
332 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
333 BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
334 Boolean *b = boolMap.get(boolean);
336 boolean->updateParents();
337 boolMap.put(boolean, boolean);
338 allBooleans.push(boolean);
339 return BooleanEdge(boolean);
342 return BooleanEdge(b);
346 bool CSolver::isTrue(BooleanEdge b) {
347 return b.isNegated() ? b->isFalse() : b->isTrue();
350 bool CSolver::isFalse(BooleanEdge b) {
351 return b.isNegated() ? b->isTrue() : b->isFalse();
354 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
355 BooleanEdge array[] = {arg1, arg2};
356 return applyLogicalOperation(op, array, 2);
359 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
360 BooleanEdge array[] = {arg};
361 return applyLogicalOperation(op, array, 1);
364 static int booleanEdgeCompares(const void *p1, const void *p2) {
365 BooleanEdge be1 = *(BooleanEdge const *) p1;
366 BooleanEdge be2 = *(BooleanEdge const *) p2;
367 uint64_t b1 = be1->id;
368 uint64_t b2 = be2->id;
377 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
378 BooleanEdge newarray[asize];
379 memcpy(newarray, array, asize * sizeof(BooleanEdge));
380 for (uint i = 0; i < asize; i++) {
381 BooleanEdge b = newarray[i];
382 if (b->type == LOGICOP) {
383 if (((BooleanLogic *) b.getBoolean())->replaced) {
384 newarray[i] = doRewrite(newarray[i]);
389 return applyLogicalOperation(op, newarray, asize);
392 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
393 if(!useAlloyCompiler()){
394 BooleanEdge newarray[asize];
397 return array[0].negate();
400 for (uint i = 0; i < 2; i++) {
401 if (isTrue(array[i])) { // It can be undefined
403 } else if (isFalse(array[i])) {
404 newarray[0] = array[1 - i];
405 return applyLogicalOperation(SATC_NOT, newarray, 1);
406 } else if (array[i]->type == LOGICOP) {
407 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
409 return rewriteLogicalOperation(op, array, asize);
416 for (uint i = 0; i < asize; i++) {
417 newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
419 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
423 for (uint i = 0; i < asize; i++) {
424 BooleanEdge b = array[i];
425 if (b->type == LOGICOP) {
426 if (((BooleanLogic *)b.getBoolean())->replaced)
427 return rewriteLogicalOperation(op, array, asize);
431 else if (isFalse(b)) {
434 newarray[newindex++] = b;
438 } else if (newindex == 1) {
441 bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
448 //handle by translation
449 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
452 //handle by translation
453 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
458 Boolean *boolean = new BooleanLogic(this, op, array, asize);
459 Boolean *b = boolMap.get(boolean);
461 boolean->updateParents();
462 boolMap.put(boolean, boolean);
463 allBooleans.push(boolean);
464 return BooleanEdge(boolean);
467 return BooleanEdge(b);
471 Boolean *boolean = new BooleanLogic(this, op, array, asize);
472 allBooleans.push(boolean);
473 return BooleanEdge(boolean);
478 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
479 // ASSERT(first != second);
481 return getBooleanFalse();
484 if (order->type == SATC_TOTAL) {
485 if (first > second) {
486 uint64_t tmp = first;
492 Boolean *constraint = new BooleanOrder(order, first, second);
493 if (!useAlloyCompiler() ){
494 Boolean *b = boolMap.get(constraint);
497 allBooleans.push(constraint);
498 boolMap.put(constraint, constraint);
499 constraint->updateParents();
500 if ( order->graph != NULL) {
501 OrderGraph *graph = order->graph;
502 OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
504 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
506 OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
509 if (edge != NULL && edge->mustPos) {
510 replaceBooleanWithTrueNoRemove(constraint);
511 } else if (edge != NULL && edge->mustNeg) {
512 replaceBooleanWithFalseNoRemove(constraint);
513 } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
514 && invedge->mustPos) {
515 replaceBooleanWithFalseNoRemove(constraint);
525 BooleanEdge be = BooleanEdge(constraint);
526 return negate ? be.negate() : be;
529 void CSolver::addConstraint(BooleanEdge constraint) {
530 if(!useAlloyCompiler()){
531 if (isTrue(constraint))
533 else if (isFalse(constraint)) {
537 if (constraint->type == LOGICOP) {
538 BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
539 if (!constraint.isNegated()) {
540 if (b->op == SATC_AND) {
541 uint size = b->inputs.getSize();
542 //Handle potential concurrent modification
543 BooleanEdge array[size];
544 for (uint i = 0; i < size; i++) {
545 array[i] = b->inputs.get(i);
547 for (uint i = 0; i < size; i++) {
548 addConstraint(array[i]);
554 addConstraint(doRewrite(constraint));
558 constraints.add(constraint);
559 Boolean *ptr = constraint.getBoolean();
561 if (ptr->boolVal == BV_UNSAT) {
565 replaceBooleanWithTrueNoRemove(constraint);
566 constraint->parents.clear();
569 constraints.add(constraint);
570 constraint->parents.clear();
574 Order *CSolver::createOrder(OrderType type, Set *set) {
575 Order *order = new Order(type, set);
576 allOrders.push(order);
577 activeOrders.add(order);
581 /** Computes static ordering information to allow isTrue/isFalse
582 queries on newly created orders to work. */
584 void CSolver::inferFixedOrder(Order *order) {
585 if (order->graph != NULL) {
588 order->graph = buildMustOrderGraph(order);
589 reachMustAnalysis(this, order->graph, true);
592 void CSolver::inferFixedOrders() {
593 SetIteratorOrder *orderit = activeOrders.iterator();
594 while (orderit->hasNext()) {
595 Order *order = orderit->next();
596 inferFixedOrder(order);
600 int CSolver::solve() {
601 long long startTime = getTimeNano();
602 bool deleteTuner = false;
604 tuner = new DefaultTuner();
607 int result = IS_INDETER;
608 if(useAlloyCompiler()){
609 alloyEncoder->encode();
610 model_print("Problem encoded in Alloy\n");
611 result = alloyEncoder->solve();
612 model_print("Problem solved by Alloy\n");
616 SetIteratorOrder *orderit = activeOrders.iterator();
617 while (orderit->hasNext()) {
618 Order *order = orderit->next();
619 if (order->graph != NULL) {
626 computePolarities(this);
627 long long time1 = getTimeNano();
628 model_print("Polarity time: %f\n", (time1 - startTime) / NANOSEC);
631 long long time2 = getTimeNano();
632 model_print("Preprocess time: %f\n", (time2 - time1) / NANOSEC);
634 DecomposeOrderTransform dot(this);
636 time1 = getTimeNano();
637 model_print("Decompose Order: %f\n", (time1 - time2) / NANOSEC);
639 IntegerEncodingTransform iet(this);
642 ElementOpt eop(this);
645 EncodingGraph eg(this);
648 naiveEncodingDecision(this);
651 VarOrderingOpt bor(this, satEncoder);
654 time2 = getTimeNano();
655 model_print("Encoding Graph Time: %f\n", (time2 - time1) / NANOSEC);
657 satEncoder->encodeAllSATEncoder(this);
658 time1 = getTimeNano();
660 model_print("Elapse Encode time: %f\n", (time1 - startTime) / NANOSEC);
662 model_print("Is problem UNSAT after encoding: %d\n", unsat);
665 result = unsat ? IS_UNSAT : satEncoder->solve(satsolverTimeout);
666 model_print("Result Computed in SAT solver:\t%s\n", result == IS_SAT ? "SAT" : result == IS_INDETER ? "INDETERMINATE" : " UNSAT");
667 time2 = getTimeNano();
668 elapsedTime = time2 - startTime;
669 model_print("CSOLVER solve time: %f\n", elapsedTime / NANOSEC);
678 void CSolver::setAlloyEncoder(){
679 if(alloyEncoder == NULL){
680 alloyEncoder = new AlloyEnc(this);
684 void CSolver::printConstraints() {
685 SetIteratorBooleanEdge *it = getConstraints();
686 while (it->hasNext()) {
687 BooleanEdge b = it->next();
693 void CSolver::printConstraint(BooleanEdge b) {
697 uint64_t CSolver::getElementValue(Element *element) {
698 switch (element->type) {
702 return useAlloyCompiler()? alloyEncoder->getValue(element):
703 getElementValueSATTranslator(this, element);
710 bool CSolver::getBooleanValue(BooleanEdge bedge) {
711 Boolean *boolean = bedge.getBoolean();
712 switch (boolean->type) {
714 return useAlloyCompiler()? alloyEncoder->getBooleanValue(boolean):
715 getBooleanVariableValueSATTranslator(this, boolean);
722 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
723 return order->encoding.resolver->resolveOrder(first, second);
726 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
728 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
730 void CSolver::autoTune(uint budget) {
731 AutoTuner *autotuner = new AutoTuner(budget);
732 autotuner->addProblem(this);