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()),
39 satEncoder = new SATEncoder(this);
42 /** This function tears down the solver and the entire AST */
46 uint size = allBooleans.getSize();
47 for (uint i = 0; i < size; i++) {
48 delete allBooleans.get(i);
51 size = allSets.getSize();
52 for (uint i = 0; i < size; i++) {
53 delete allSets.get(i);
56 size = allElements.getSize();
57 for (uint i = 0; i < size; i++) {
58 Element *el = allElements.get(i);
62 size = allTables.getSize();
63 for (uint i = 0; i < size; i++) {
64 delete allTables.get(i);
67 size = allPredicates.getSize();
68 for (uint i = 0; i < size; i++) {
69 delete allPredicates.get(i);
72 size = allOrders.getSize();
73 for (uint i = 0; i < size; i++) {
74 delete allOrders.get(i);
76 size = allFunctions.getSize();
77 for (uint i = 0; i < size; i++) {
78 delete allFunctions.get(i);
81 delete boolTrue.getBoolean();
85 void CSolver::resetSolver() {
87 uint size = allBooleans.getSize();
88 for (uint i = 0; i < size; i++) {
89 delete allBooleans.get(i);
92 size = allSets.getSize();
93 for (uint i = 0; i < size; i++) {
94 delete allSets.get(i);
97 size = allElements.getSize();
98 for (uint i = 0; i < size; i++) {
99 Element *el = allElements.get(i);
103 size = allTables.getSize();
104 for (uint i = 0; i < size; i++) {
105 delete allTables.get(i);
108 size = allPredicates.getSize();
109 for (uint i = 0; i < size; i++) {
110 delete allPredicates.get(i);
113 size = allOrders.getSize();
114 for (uint i = 0; i < size; i++) {
115 delete allOrders.get(i);
117 size = allFunctions.getSize();
118 for (uint i = 0; i < size; i++) {
119 delete allFunctions.get(i);
121 delete boolTrue.getBoolean();
126 allPredicates.clear();
128 allFunctions.clear();
130 activeOrders.reset();
134 boolTrue = BooleanEdge(new BooleanConst(true));
135 boolFalse = boolTrue.negate();
139 satEncoder->resetSATEncoder();
143 CSolver *CSolver::clone() {
144 CSolver *copy = new CSolver();
146 SetIteratorBooleanEdge *it = getConstraints();
147 while (it->hasNext()) {
148 BooleanEdge b = it->next();
149 copy->addConstraint(cloneEdge(copy, &map, b));
155 CSolver *CSolver::deserialize(const char *file) {
156 model_print("deserializing ...\n");
157 Deserializer deserializer(file);
158 return deserializer.deserialize();
161 void CSolver::serialize() {
162 model_print("serializing ...\n");
164 long long nanotime = getTimeNano();
165 int numchars = sprintf(buffer, "DUMP%llu", nanotime);
166 Serializer serializer(buffer);
167 SetIteratorBooleanEdge *it = getConstraints();
168 while (it->hasNext()) {
169 BooleanEdge b = it->next();
170 serializeBooleanEdge(&serializer, b, true);
175 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
176 Set *set = new Set(type, elements, numelements);
181 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
182 Set *set = new Set(type, lowrange, highrange);
187 bool CSolver::itemExistInSet(Set *set, uint64_t item){
188 return set->exists(item);
191 VarType CSolver::getSetVarType(Set *set) {
192 return set->getType();
195 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
196 Set *s = createRangeSet(type, lowrange, highrange);
197 return getElementVar(s);
200 MutableSet *CSolver::createMutableSet(VarType type) {
201 MutableSet *set = new MutableSet(type);
206 void CSolver::addItem(MutableSet *set, uint64_t element) {
207 set->addElementMSet(element);
210 uint64_t CSolver::createUniqueItem(MutableSet *set) {
211 uint64_t element = set->getNewUniqueItem();
212 set->addElementMSet(element);
216 void CSolver::finalizeMutableSet(MutableSet *set) {
220 Element *CSolver::getElementVar(Set *set) {
221 Element *element = new ElementSet(set);
222 allElements.push(element);
226 void CSolver::mustHaveValue(Element *element){
227 element->getElementEncoding()->anyValue = true;
230 Set *CSolver::getElementRange (Element *element) {
231 return element->getRange();
235 Element *CSolver::getElementConst(VarType type, uint64_t value) {
236 uint64_t array[] = {value};
237 Set *set = new Set(type, array, 1);
238 Element *element = new ElementConst(value, set);
239 Element *e = elemMap.get(element);
242 allElements.push(element);
243 elemMap.put(element, element);
253 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
254 Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
255 Element *e = elemMap.get(element);
257 element->updateParents();
258 allElements.push(element);
259 elemMap.put(element, element);
267 Function *CSolver::createFunctionOperator(ArithOp op, Set *range, OverFlowBehavior overflowbehavior) {
268 Function *function = new FunctionOperator(op, range, overflowbehavior);
269 allFunctions.push(function);
273 Predicate *CSolver::createPredicateOperator(CompOp op) {
274 Predicate *predicate = new PredicateOperator(op);
275 allPredicates.push(predicate);
279 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
280 Predicate *predicate = new PredicateTable(table, behavior);
281 allPredicates.push(predicate);
285 Table *CSolver::createTable(Set *range) {
286 Table *table = new Table(range);
287 allTables.push(table);
291 Table *CSolver::createTableForPredicate() {
292 return createTable(NULL);
295 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
296 table->addNewTableEntry(inputs, inputSize, result);
299 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
300 Function *function = new FunctionTable(table, behavior);
301 allFunctions.push(function);
305 BooleanEdge CSolver::getBooleanVar(VarType type) {
306 Boolean *boolean = new BooleanVar(type);
307 allBooleans.push(boolean);
308 return BooleanEdge(boolean);
311 BooleanEdge CSolver::getBooleanTrue() {
315 BooleanEdge CSolver::getBooleanFalse() {
319 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
320 return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
323 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
324 BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
325 Boolean *b = boolMap.get(boolean);
327 boolean->updateParents();
328 boolMap.put(boolean, boolean);
329 allBooleans.push(boolean);
330 return BooleanEdge(boolean);
333 return BooleanEdge(b);
337 bool CSolver::isTrue(BooleanEdge b) {
338 return b.isNegated() ? b->isFalse() : b->isTrue();
341 bool CSolver::isFalse(BooleanEdge b) {
342 return b.isNegated() ? b->isTrue() : b->isFalse();
345 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
346 BooleanEdge array[] = {arg1, arg2};
347 return applyLogicalOperation(op, array, 2);
350 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
351 BooleanEdge array[] = {arg};
352 return applyLogicalOperation(op, array, 1);
355 static int booleanEdgeCompares(const void *p1, const void *p2) {
356 BooleanEdge be1 = *(BooleanEdge const *) p1;
357 BooleanEdge be2 = *(BooleanEdge const *) p2;
358 uint64_t b1 = be1->id;
359 uint64_t b2 = be2->id;
368 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
369 BooleanEdge newarray[asize];
370 memcpy(newarray, array, asize * sizeof(BooleanEdge));
371 for (uint i = 0; i < asize; i++) {
372 BooleanEdge b = newarray[i];
373 if (b->type == LOGICOP) {
374 if (((BooleanLogic *) b.getBoolean())->replaced) {
375 newarray[i] = doRewrite(newarray[i]);
380 return applyLogicalOperation(op, newarray, asize);
383 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
384 BooleanEdge newarray[asize];
387 return array[0].negate();
390 for (uint i = 0; i < 2; i++) {
391 if (isTrue(array[i])) { // It can be undefined
393 } else if (isFalse(array[i])) {
394 newarray[0] = array[1 - i];
395 return applyLogicalOperation(SATC_NOT, newarray, 1);
396 } else if (array[i]->type == LOGICOP) {
397 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
399 return rewriteLogicalOperation(op, array, asize);
406 for (uint i = 0; i < asize; i++) {
407 newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
409 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
413 for (uint i = 0; i < asize; i++) {
414 BooleanEdge b = array[i];
415 if (b->type == LOGICOP) {
416 if (((BooleanLogic *)b.getBoolean())->replaced)
417 return rewriteLogicalOperation(op, array, asize);
421 else if (isFalse(b)) {
424 newarray[newindex++] = b;
428 } else if (newindex == 1) {
431 bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
438 //handle by translation
439 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
442 //handle by translation
443 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
448 Boolean *boolean = new BooleanLogic(this, op, array, asize);
449 Boolean *b = boolMap.get(boolean);
451 boolean->updateParents();
452 boolMap.put(boolean, boolean);
453 allBooleans.push(boolean);
454 return BooleanEdge(boolean);
457 return BooleanEdge(b);
461 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
462 // ASSERT(first != second);
464 return getBooleanFalse();
467 if (order->type == SATC_TOTAL) {
468 if (first > second) {
469 uint64_t tmp = first;
475 Boolean *constraint = new BooleanOrder(order, first, second);
476 Boolean *b = boolMap.get(constraint);
479 allBooleans.push(constraint);
480 boolMap.put(constraint, constraint);
481 constraint->updateParents();
482 if (order->graph != NULL) {
483 OrderGraph *graph = order->graph;
484 OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
486 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
488 OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
491 if (edge != NULL && edge->mustPos) {
492 replaceBooleanWithTrueNoRemove(constraint);
493 } else if (edge != NULL && edge->mustNeg) {
494 replaceBooleanWithFalseNoRemove(constraint);
495 } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
496 && invedge->mustPos) {
497 replaceBooleanWithFalseNoRemove(constraint);
507 BooleanEdge be = BooleanEdge(constraint);
508 return negate ? be.negate() : be;
511 void CSolver::addConstraint(BooleanEdge constraint) {
512 if (isTrue(constraint))
514 else if (isFalse(constraint)) {
519 if (constraint->type == LOGICOP) {
520 BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
521 if (!constraint.isNegated()) {
522 if (b->op == SATC_AND) {
523 for (uint i = 0; i < b->inputs.getSize(); i++) {
524 addConstraint(b->inputs.get(i));
530 addConstraint(doRewrite(constraint));
534 constraints.add(constraint);
535 Boolean *ptr = constraint.getBoolean();
537 if (ptr->boolVal == BV_UNSAT) {
541 replaceBooleanWithTrueNoRemove(constraint);
542 constraint->parents.clear();
546 Order *CSolver::createOrder(OrderType type, Set *set) {
547 Order *order = new Order(type, set);
548 allOrders.push(order);
549 activeOrders.add(order);
553 /** Computes static ordering information to allow isTrue/isFalse
554 queries on newly created orders to work. */
556 void CSolver::inferFixedOrder(Order *order) {
557 if (order->graph != NULL) {
560 order->graph = buildMustOrderGraph(order);
561 reachMustAnalysis(this, order->graph, true);
564 void CSolver::inferFixedOrders() {
565 SetIteratorOrder *orderit = activeOrders.iterator();
566 while (orderit->hasNext()) {
567 Order *order = orderit->next();
568 inferFixedOrder(order);
572 #define NANOSEC 1000000000.0
573 int CSolver::solve() {
574 long long starttime = getTimeNano();
575 bool deleteTuner = false;
577 tuner = new DefaultTuner();
583 SetIteratorOrder *orderit = activeOrders.iterator();
584 while (orderit->hasNext()) {
585 Order *order = orderit->next();
586 if (order->graph != NULL) {
593 computePolarities(this);
594 long long time2 = getTimeNano();
595 model_print("Polarity time: %f\n", (time2 - starttime) / NANOSEC);
598 long long time3 = getTimeNano();
599 model_print("Preprocess time: %f\n", (time3 - time2) / NANOSEC);
601 DecomposeOrderTransform dot(this);
603 long long time4 = getTimeNano();
604 model_print("Decompose Order: %f\n", (time4 - time3) / NANOSEC);
606 IntegerEncodingTransform iet(this);
609 ElementOpt eop(this);
612 EncodingGraph eg(this);
616 naiveEncodingDecision(this);
617 long long time5 = getTimeNano();
618 model_print("Encoding Graph Time: %f\n", (time5 - time4) / NANOSEC);
620 long long startTime = getTimeNano();
621 satEncoder->encodeAllSATEncoder(this);
622 long long endTime = getTimeNano();
624 elapsedTime = endTime - startTime;
625 model_print("Elapse Encode time: %f\n", elapsedTime / NANOSEC);
627 model_print("Is problem UNSAT after encoding: %d\n", unsat);
628 int result = unsat ? IS_UNSAT : satEncoder->solve();
629 model_print("Result Computed in SAT solver: %d\n", result);
638 void CSolver::printConstraints() {
639 SetIteratorBooleanEdge *it = getConstraints();
640 while (it->hasNext()) {
641 BooleanEdge b = it->next();
650 void CSolver::printConstraint(BooleanEdge b) {
657 uint64_t CSolver::getElementValue(Element *element) {
658 switch (element->type) {
662 return getElementValueSATTranslator(this, element);
669 bool CSolver::getBooleanValue(BooleanEdge bedge) {
670 Boolean *boolean = bedge.getBoolean();
671 switch (boolean->type) {
673 return getBooleanVariableValueSATTranslator(this, boolean);
680 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
681 return order->encoding.resolver->resolveOrder(first, second);
684 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
686 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
688 void CSolver::autoTune(uint budget) {
689 AutoTuner *autotuner = new AutoTuner(budget);
690 autotuner->addProblem(this);
695 //Set* CSolver::addItemsToRange(Element* element, uint num, ...){
697 // va_start(args, num);
698 // element->getRange()
699 // uint setSize = set->getSize();
700 // uint newSize = setSize+ num;
701 // uint64_t members[newSize];
702 // for(uint i=0; i<setSize; i++){
703 // members[i] = set->getElement(i);
705 // for( uint i=0; i< num; i++){
706 // uint64_t arg = va_arg(args, uint64_t);
707 // members[setSize+i] = arg;
710 // return createSet(set->getType(), members, newSize);