Edits
[satune.git] / src / csolver.cc
index 51d8c7fb0c991f0e9e31bddd690be33e91b67119..be4a3a88063882cc05f5cfafca9218724b870f72 100644 (file)
 #include "satencoder.h"
 #include "sattranslator.h"
 #include "tunable.h"
-#include "orderencoder.h"
 #include "polarityassignment.h"
-
-CSolver *allocCSolver() {
-       CSolver *This = (CSolver *) ourmalloc(sizeof(CSolver));
-       This->unsat = false;
-       This->constraints = allocDefHashSetBoolean();
-       This->allBooleans = allocDefVectorBoolean();
-       This->allSets = allocDefVectorSet();
-       This->allElements = allocDefVectorElement();
-       This->allPredicates = allocDefVectorPredicate();
-       This->allTables = allocDefVectorTable();
-       This->allOrders = allocDefVectorOrder();
-       This->allFunctions = allocDefVectorFunction();
-       This->tuner = allocTuner();
-       This->satEncoder = allocSATEncoder(This);
-       return This;
+#include "decomposeordertransform.h"
+#include "autotuner.h"
+#include "astops.h"
+#include "structs.h"
+#include "orderresolver.h"
+#include "integerencoding.h"
+#include "qsort.h"
+#include "preprocess.h"
+#include "serializer.h"
+#include "deserializer.h"
+#include "encodinggraph.h"
+
+CSolver::CSolver() :
+       boolTrue(BooleanEdge(new BooleanConst(true))),
+       boolFalse(boolTrue.negate()),
+       unsat(false),
+       tuner(NULL),
+       elapsedTime(0)
+{
+       satEncoder = new SATEncoder(this);
 }
 
 /** This function tears down the solver and the entire AST */
 
-void deleteSolver(CSolver *This) {
-       deleteHashSetBoolean(This->constraints);
-
-       uint size = getSizeVectorBoolean(This->allBooleans);
+CSolver::~CSolver() {
+       uint size = allBooleans.getSize();
        for (uint i = 0; i < size; i++) {
-               deleteBoolean(getVectorBoolean(This->allBooleans, i));
+               delete allBooleans.get(i);
        }
-       deleteVectorBoolean(This->allBooleans);
 
-       size = getSizeVectorSet(This->allSets);
+       size = allSets.getSize();
        for (uint i = 0; i < size; i++) {
-               deleteSet(getVectorSet(This->allSets, i));
+               delete allSets.get(i);
        }
-       deleteVectorSet(This->allSets);
 
-       size = getSizeVectorElement(This->allElements);
+       size = allElements.getSize();
        for (uint i = 0; i < size; i++) {
-               delete getVectorElement(This->allElements, i);
+               delete allElements.get(i);
        }
-       deleteVectorElement(This->allElements);
 
-       size = getSizeVectorTable(This->allTables);
+       size = allTables.getSize();
        for (uint i = 0; i < size; i++) {
-               deleteTable(getVectorTable(This->allTables, i));
+               delete allTables.get(i);
        }
-       deleteVectorTable(This->allTables);
 
-       size = getSizeVectorPredicate(This->allPredicates);
+       size = allPredicates.getSize();
        for (uint i = 0; i < size; i++) {
-               deletePredicate(getVectorPredicate(This->allPredicates, i));
+               delete allPredicates.get(i);
        }
-       deleteVectorPredicate(This->allPredicates);
 
-       size = getSizeVectorOrder(This->allOrders);
+       size = allOrders.getSize();
        for (uint i = 0; i < size; i++) {
-               deleteOrder(getVectorOrder(This->allOrders, i));
+               delete allOrders.get(i);
        }
-       deleteVectorOrder(This->allOrders);
 
-       size = getSizeVectorFunction(This->allFunctions);
+       size = allFunctions.getSize();
        for (uint i = 0; i < size; i++) {
-               deleteFunction(getVectorFunction(This->allFunctions, i));
+               delete allFunctions.get(i);
+       }
+
+       delete boolTrue.getBoolean();
+       delete satEncoder;
+}
+
+CSolver *CSolver::clone() {
+       CSolver *copy = new CSolver();
+       CloneMap map;
+       SetIteratorBooleanEdge *it = getConstraints();
+       while (it->hasNext()) {
+               BooleanEdge b = it->next();
+               copy->addConstraint(cloneEdge(copy, &map, b));
        }
-       deleteVectorFunction(This->allFunctions);
-       deleteSATEncoder(This->satEncoder);
-       deleteTuner(This->tuner);
-       ourfree(This);
+       delete it;
+       return copy;
 }
 
-Set *createSet(CSolver *This, VarType type, uint64_t *elements, uint numelements) {
-       Set *set = allocSet(type, elements, numelements);
-       pushVectorSet(This->allSets, set);
+void CSolver::serialize() {
+       model_print("serializing ...\n");
+       {
+               Serializer serializer("dump");
+               SetIteratorBooleanEdge *it = getConstraints();
+               while (it->hasNext()) {
+                       BooleanEdge b = it->next();
+                       serializeBooleanEdge(&serializer, b);
+               }
+               delete it;
+       }
+       model_print("deserializing ...\n");
+       {
+               Deserializer deserializer("dump");
+               deserializer.deserialize();
+       }
+
+}
+
+Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
+       Set *set = new Set(type, elements, numelements);
+       allSets.push(set);
        return set;
 }
 
-Set *createRangeSet(CSolver *This, VarType type, uint64_t lowrange, uint64_t highrange) {
-       Set *set = allocSetRange(type, lowrange, highrange);
-       pushVectorSet(This->allSets, set);
+Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
+       Set *set = new Set(type, lowrange, highrange);
+       allSets.push(set);
        return set;
 }
 
-MutableSet *createMutableSet(CSolver *This, VarType type) {
-       MutableSet *set = allocMutableSet(type);
-       pushVectorSet(This->allSets, set);
+VarType CSolver::getSetVarType(Set *set) {
+       return set->getType();
+}
+
+Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
+       Set *s = createRangeSet(type, lowrange, highrange);
+       return getElementVar(s);
+}
+
+MutableSet *CSolver::createMutableSet(VarType type) {
+       MutableSet *set = new MutableSet(type);
+       allSets.push(set);
        return set;
 }
 
-void addItem(CSolver *This, MutableSet *set, uint64_t element) {
-       addElementMSet(set, element);
+void CSolver::addItem(MutableSet *set, uint64_t element) {
+       set->addElementMSet(element);
 }
 
-uint64_t createUniqueItem(CSolver *This, MutableSet *set) {
-       uint64_t element = set->low++;
-       addElementMSet(set, element);
+uint64_t CSolver::createUniqueItem(MutableSet *set) {
+       uint64_t element = set->getNewUniqueItem();
+       set->addElementMSet(element);
        return element;
 }
 
-Element *getElementVar(CSolver *This, Set *set) {
+void CSolver::finalizeMutableSet(MutableSet *set) {
+       set->finalize();
+}
+
+Element *CSolver::getElementVar(Set *set) {
        Element *element = new ElementSet(set);
-       pushVectorElement(This->allElements, element);
+       allElements.push(element);
        return element;
 }
 
-Element *getElementConst(CSolver *This, VarType type, uint64_t value) {
-       Element *element = new ElementConst(value, type);
-       pushVectorElement(This->allElements, element);
-       return element;
+Set *CSolver::getElementRange (Element *element) {
+       return element->getRange();
 }
 
-Boolean *getBooleanVar(CSolver *This, VarType type) {
-       Boolean *boolean = allocBooleanVar(type);
-       pushVectorBoolean(This->allBooleans, boolean);
-       return boolean;
+
+Element *CSolver::getElementConst(VarType type, uint64_t value) {
+       uint64_t array[] = {value};
+       Set *set = new Set(type, array, 1);
+       Element *element = new ElementConst(value, set);
+       Element *e = elemMap.get(element);
+       if (e == NULL) {
+               allSets.push(set);
+               allElements.push(element);
+               elemMap.put(element, element);
+               return element;
+       } else {
+               delete set;
+               delete element;
+               return e;
+       }
+}
+
+Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
+       Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
+       Element *e = elemMap.get(element);
+       if (e == NULL) {
+               element->updateParents();
+               allElements.push(element);
+               elemMap.put(element, element);
+               return element;
+       } else {
+               delete element;
+               return e;
+       }
 }
 
-Function *createFunctionOperator(CSolver *This, ArithOp op, Set **domain, uint numDomain, Set *range,OverFlowBehavior overflowbehavior) {
-       Function *function = allocFunctionOperator(op, domain, numDomain, range, overflowbehavior);
-       pushVectorFunction(This->allFunctions, function);
+Function *CSolver::createFunctionOperator(ArithOp op, Set **domain, uint numDomain, Set *range,OverFlowBehavior overflowbehavior) {
+       Function *function = new FunctionOperator(op, domain, numDomain, range, overflowbehavior);
+       allFunctions.push(function);
        return function;
 }
 
-Predicate *createPredicateOperator(CSolver *This, CompOp op, Set **domain, uint numDomain) {
-       Predicate *predicate = allocPredicateOperator(op, domain,numDomain);
-       pushVectorPredicate(This->allPredicates, predicate);
+Predicate *CSolver::createPredicateOperator(CompOp op, Set **domain, uint numDomain) {
+       Predicate *predicate = new PredicateOperator(op, domain,numDomain);
+       allPredicates.push(predicate);
        return predicate;
 }
 
-Predicate *createPredicateTable(CSolver *This, Table *table, UndefinedBehavior behavior) {
-       Predicate *predicate = allocPredicateTable(table, behavior);
-       pushVectorPredicate(This->allPredicates, predicate);
+Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
+       Predicate *predicate = new PredicateTable(table, behavior);
+       allPredicates.push(predicate);
        return predicate;
 }
 
-Table *createTable(CSolver *This, Set **domains, uint numDomain, Set *range) {
-       Table *table = allocTable(domains,numDomain,range);
-       pushVectorTable(This->allTables, table);
+Table *CSolver::createTable(Set **domains, uint numDomain, Set *range) {
+       Table *table = new Table(domains,numDomain,range);
+       allTables.push(table);
        return table;
 }
 
-Table *createTableForPredicate(CSolver *solver, Set **domains, uint numDomain) {
-       return createTable(solver, domains, numDomain, NULL);
+Table *CSolver::createTableForPredicate(Set **domains, uint numDomain) {
+       return createTable(domains, numDomain, NULL);
 }
 
-void addTableEntry(CSolver *This, Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
-       addNewTableEntry(table,inputs, inputSize,result);
+void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
+       table->addNewTableEntry(inputs, inputSize, result);
 }
 
-Function *completeTable(CSolver *This, Table *table, UndefinedBehavior behavior) {
-       Function *function = allocFunctionTable(table, behavior);
-       pushVectorFunction(This->allFunctions,function);
+Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
+       Function *function = new FunctionTable(table, behavior);
+       allFunctions.push(function);
        return function;
 }
 
-Element *applyFunction(CSolver *This, Function *function, Element **array, uint numArrays, Boolean *overflowstatus) {
-       Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
-       pushVectorElement(This->allElements, element);
-       return element;
+BooleanEdge CSolver::getBooleanVar(VarType type) {
+       Boolean *boolean = new BooleanVar(type);
+       allBooleans.push(boolean);
+       return BooleanEdge(boolean);
+}
+
+BooleanEdge CSolver::getBooleanTrue() {
+       return boolTrue;
 }
 
-Boolean *applyPredicate(CSolver *This, Predicate *predicate, Element **inputs, uint numInputs) {
-       return applyPredicateTable(This, predicate, inputs, numInputs, NULL);
+BooleanEdge CSolver::getBooleanFalse() {
+       return boolFalse;
 }
-Boolean *applyPredicateTable(CSolver *This, Predicate *predicate, Element **inputs, uint numInputs, Boolean *undefinedStatus) {
-       Boolean *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
-       pushVectorBoolean(This->allBooleans, boolean);
-       return boolean;
+
+BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
+       return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
 }
 
-Boolean *applyLogicalOperation(CSolver *This, LogicOp op, Boolean **array, uint asize) {
-       return new BooleanLogic(This, op, array, asize);
+BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
+       BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
+       Boolean *b = boolMap.get(boolean);
+       if (b == NULL) {
+               boolean->updateParents();
+               boolMap.put(boolean, boolean);
+               allBooleans.push(boolean);
+               return BooleanEdge(boolean);
+       } else {
+               delete boolean;
+               return BooleanEdge(b);
+       }
 }
 
-void addConstraint(CSolver *This, Boolean *constraint) {
-       addHashSetBoolean(This->constraints, constraint);
+bool CSolver::isTrue(BooleanEdge b) {
+       return b.isNegated() ? b->isFalse() : b->isTrue();
 }
 
-Order *createOrder(CSolver *This, OrderType type, Set *set) {
-       Order *order = allocOrder(type, set);
-       pushVectorOrder(This->allOrders, order);
-       return order;
+bool CSolver::isFalse(BooleanEdge b) {
+       return b.isNegated() ? b->isTrue() : b->isFalse();
+}
+
+BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
+       BooleanEdge array[] = {arg1, arg2};
+       return applyLogicalOperation(op, array, 2);
+}
+
+BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
+       BooleanEdge array[] = {arg};
+       return applyLogicalOperation(op, array, 1);
+}
+
+static int ptrcompares(const void *p1, const void *p2) {
+       uintptr_t b1 = *(uintptr_t const *) p1;
+       uintptr_t b2 = *(uintptr_t const *) p2;
+       if (b1 < b2)
+               return -1;
+       else if (b1 == b2)
+               return 0;
+       else
+               return 1;
 }
 
-Boolean *orderConstraint(CSolver *This, Order *order, uint64_t first, uint64_t second) {
+BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
+       BooleanEdge newarray[asize];
+       memcpy(newarray, array, asize * sizeof(BooleanEdge));
+       for (uint i = 0; i < asize; i++) {
+               BooleanEdge b = newarray[i];
+               if (b->type == LOGICOP) {
+                       if (((BooleanLogic *) b.getBoolean())->replaced) {
+                               newarray[i] = doRewrite(newarray[i]);
+                               i--;//Check again
+                       }
+               }
+       }
+       return applyLogicalOperation(op, newarray, asize);
+}
+
+BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
+       BooleanEdge newarray[asize];
+       switch (op) {
+       case SATC_NOT: {
+               return array[0].negate();
+       }
+       case SATC_IFF: {
+               for (uint i = 0; i < 2; i++) {
+                       if (array[i]->type == BOOLCONST) {
+                               if (isTrue(array[i])) { // It can be undefined
+                                       return array[1 - i];
+                               } else if (isFalse(array[i])) {
+                                       newarray[0] = array[1 - i];
+                                       return applyLogicalOperation(SATC_NOT, newarray, 1);
+                               }
+                       } else if (array[i]->type == LOGICOP) {
+                               BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
+                               if (b->replaced) {
+                                       return rewriteLogicalOperation(op, array, asize);
+                               }
+                       }
+               }
+               break;
+       }
+       case SATC_OR: {
+               for (uint i = 0; i < asize; i++) {
+                       newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
+               }
+               return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
+       }
+       case SATC_AND: {
+               uint newindex = 0;
+               for (uint i = 0; i < asize; i++) {
+                       BooleanEdge b = array[i];
+                       if (b->type == LOGICOP) {
+                               if (((BooleanLogic *)b.getBoolean())->replaced)
+                                       return rewriteLogicalOperation(op, array, asize);
+                       }
+                       if (b->type == BOOLCONST) {
+                               if (isTrue(b))
+                                       continue;
+                               else {
+                                       return boolFalse;
+                               }
+                       } else
+                               newarray[newindex++] = b;
+               }
+               if (newindex == 0) {
+                       return boolTrue;
+               } else if (newindex == 1) {
+                       return newarray[0];
+               } else {
+                       bsdqsort(newarray, newindex, sizeof(BooleanEdge), ptrcompares);
+                       array = newarray;
+                       asize = newindex;
+               }
+               break;
+       }
+       case SATC_XOR: {
+               //handle by translation
+               return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
+       }
+       case SATC_IMPLIES: {
+               //handle by translation
+               return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
+       }
+       }
+
+       ASSERT(asize != 0);
+       Boolean *boolean = new BooleanLogic(this, op, array, asize);
+       Boolean *b = boolMap.get(boolean);
+       if (b == NULL) {
+               boolean->updateParents();
+               boolMap.put(boolean, boolean);
+               allBooleans.push(boolean);
+               return BooleanEdge(boolean);
+       } else {
+               delete boolean;
+               return BooleanEdge(b);
+       }
+}
+
+BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
+       //      ASSERT(first != second);
+       if (first == second)
+               return getBooleanFalse();
+       
+       bool negate = false;
+       if (order->type == SATC_TOTAL) {
+               if (first > second) {
+                       uint64_t tmp = first;
+                       first = second;
+                       second = tmp;
+                       negate = true;
+               }
+       }
        Boolean *constraint = new BooleanOrder(order, first, second);
-       pushVectorBoolean(This->allBooleans,constraint);
-       return constraint;
+       Boolean *b = boolMap.get(constraint);
+
+       if (b == NULL) {
+               allBooleans.push(constraint);
+               boolMap.put(constraint, constraint);
+               constraint->updateParents();
+       } else {
+               delete constraint;
+               constraint = b;
+       }
+
+       BooleanEdge be = BooleanEdge(constraint);
+       return negate ? be.negate() : be;
 }
 
-int startEncoding(CSolver *This) {
-       naiveEncodingDecision(This);
-       SATEncoder *satEncoder = This->satEncoder;
-       computePolarities(This);
-       orderAnalysis(This);
-       encodeAllSATEncoder(This, satEncoder);
-       int result = solveCNF(satEncoder->cnf);
-       model_print("sat_solver's result:%d\tsolutionSize=%d\n", result, satEncoder->cnf->solver->solutionsize);
-       for (int i = 1; i <= satEncoder->cnf->solver->solutionsize; i++) {
-               model_print("%d, ", satEncoder->cnf->solver->solution[i]);
+void CSolver::addConstraint(BooleanEdge constraint) {
+       if (isTrue(constraint))
+               return;
+       else if (isFalse(constraint)) {
+               int t = 0;
+               setUnSAT();
+       }
+       else {
+               if (constraint->type == LOGICOP) {
+                       BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
+                       if (!constraint.isNegated()) {
+                               if (b->op == SATC_AND) {
+                                       for (uint i = 0; i < b->inputs.getSize(); i++) {
+                                               addConstraint(b->inputs.get(i));
+                                       }
+                                       return;
+                               }
+                       }
+                       if (b->replaced) {
+                               addConstraint(doRewrite(constraint));
+                               return;
+                       }
+               }
+               constraints.add(constraint);
+               Boolean *ptr = constraint.getBoolean();
+
+               if (ptr->boolVal == BV_UNSAT) {
+                       setUnSAT();
+               }
+
+               replaceBooleanWithTrueNoRemove(constraint);
+               constraint->parents.clear();
+       }
+}
+
+Order *CSolver::createOrder(OrderType type, Set *set) {
+       Order *order = new Order(type, set);
+       allOrders.push(order);
+       activeOrders.add(order);
+       return order;
+}
+
+int CSolver::solve() {
+       bool deleteTuner = false;
+       if (tuner == NULL) {
+               tuner = new DefaultTuner();
+               deleteTuner = true;
+       }
+
+       long long startTime = getTimeNano();
+       computePolarities(this);
+
+       Preprocess pp(this);
+       pp.doTransform();
+
+       DecomposeOrderTransform dot(this);
+       dot.doTransform();
+
+       //IntegerEncodingTransform iet(this);
+       //iet.doTransform();
+
+       //EncodingGraph eg(this);
+       //eg.buildGraph();
+       //eg.encode();
+       //printConstraints();
+       naiveEncodingDecision(this);
+       satEncoder->encodeAllSATEncoder(this);
+       model_print("Is problem UNSAT after encoding: %d\n", unsat);
+       int result = unsat ? IS_UNSAT : satEncoder->solve();
+       model_print("Result Computed in CSolver: %d\n", result);
+       long long finishTime = getTimeNano();
+       elapsedTime = finishTime - startTime;
+       if (deleteTuner) {
+               delete tuner;
+               tuner = NULL;
        }
-       model_print("\n");
        return result;
 }
 
-uint64_t getElementValue(CSolver *This, Element *element) {
-       switch (GETELEMENTTYPE(element)) {
+void CSolver::printConstraints() {
+       SetIteratorBooleanEdge *it = getConstraints();
+       while (it->hasNext()) {
+               BooleanEdge b = it->next();
+               if (b.isNegated())
+                       model_print("!");
+               b->print();
+               model_print("\n");
+       }
+       delete it;
+
+}
+
+void CSolver::printConstraint(BooleanEdge b) {
+       if (b.isNegated())
+               model_print("!");
+       b->print();
+       model_print("\n");
+}
+
+uint64_t CSolver::getElementValue(Element *element) {
+       switch (element->type) {
        case ELEMSET:
        case ELEMCONST:
        case ELEMFUNCRETURN:
-               return getElementValueSATTranslator(This, element);
+               return getElementValueSATTranslator(this, element);
        default:
                ASSERT(0);
        }
        exit(-1);
 }
 
-bool getBooleanValue( CSolver *This, Boolean *boolean) {
-       switch (GETBOOLEANTYPE(boolean)) {
+bool CSolver::getBooleanValue(BooleanEdge bedge) {
+       Boolean *boolean = bedge.getBoolean();
+       switch (boolean->type) {
        case BOOLEANVAR:
-               return getBooleanVariableValueSATTranslator(This, boolean);
+               return getBooleanVariableValueSATTranslator(this, boolean);
        default:
                ASSERT(0);
        }
        exit(-1);
 }
 
-HappenedBefore getOrderConstraintValue(CSolver *This, Order *order, uint64_t first, uint64_t second) {
-       return getOrderConstraintValueSATTranslator(This, order, first, second);
+bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
+       return order->encoding.resolver->resolveOrder(first, second);
 }
 
+long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
+
+long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
+
+void CSolver::autoTune(uint budget) {
+       AutoTuner *autotuner = new AutoTuner(budget);
+       autotuner->addProblem(this);
+       autotuner->tune();
+       delete autotuner;
+}