Bug with time instrumentation code.
[repair.git] / Repair / RepairCompiler / MCC / IR / RepairGenerator.java
index cce92d29c3f569a197b8475e0f7eaf20aa4a54c7..06252cd6764a4484bc88edca126e7a5f6b8f4288 100755 (executable)
@@ -3,6 +3,7 @@ package MCC.IR;
 import java.io.*;
 import java.util.*;
 import MCC.State;
+import MCC.Compiler;
 
 public class RepairGenerator {
     State state;
@@ -24,7 +25,6 @@ public class RepairGenerator {
     HashSet togenerate;
     static boolean DEBUG=false;
     Cost cost;
-    Sources sources;
     ModelRuleDependence mrd;
 
     public RepairGenerator(State state, Termination t) {
@@ -35,10 +35,10 @@ public class RepairGenerator {
        removed=t.removedset;
        togenerate=new HashSet();
         togenerate.addAll(termination.conjunctions);
-        togenerate.removeAll(removed);
+       if (Compiler.REPAIR)
+           togenerate.removeAll(removed);
         GraphNode.computeclosure(togenerate,removed);
        cost=new Cost();
-       sources=new Sources(state);
        mrd=ModelRuleDependence.doAnalysis(state);
        Repair.repairgenerator=this;
     }
@@ -86,12 +86,20 @@ public class RepairGenerator {
        generate_call();
        generate_start();
         generate_rules();
+       if (!Compiler.REPAIR||Compiler.GENERATEDEBUGPRINT) {
+           generate_print();
+       }
         generate_checks();
         generate_teardown();
        CodeWriter crhead = new StandardCodeWriter(this.outputhead);
        CodeWriter craux = new StandardCodeWriter(this.outputaux);
        crhead.outputline("};");
        craux.outputline("}");
+
+       if (Compiler.GENERATEDEBUGHOOKS) {
+           crhead.outputline("void debughook();");
+           craux.outputline("void debughook() {}");
+       }
        generatetypechecks(false);
        generate_computesizes();
        generatetypechecks(true);
@@ -108,11 +116,14 @@ public class RepairGenerator {
     String strepairtable="repairtable";
     String stleft="left";
     String stright="right";
+    String stnew="newvalue";
 
     private void generate_updates() {
        int count=0;
         CodeWriter crhead = new StandardCodeWriter(outputhead);        
         CodeWriter craux = new StandardCodeWriter(outputaux);        
+       RelationDescriptor.prefix = "model->";
+       SetDescriptor.prefix = "model->";
 
        /* Rewrite globals */
 
@@ -142,15 +153,18 @@ public class RepairGenerator {
                    }
                    craux.startblock();
                    craux.outputline("int maybe=0;");
+                   if (Compiler.GENERATEINSTRUMENT)
+                       craux.outputline("updatecount++;");
+
                    final SymbolTable st = un.getRule().getSymbolTable();                
                    CodeWriter cr = new StandardCodeWriter(outputaux) {
                         public SymbolTable getSymbolTable() { return st; }
                     };
-                   un.generate(cr, false, stleft,stright,this);
+                   un.generate(cr, false, false, stleft,stright, null,this);
                    craux.outputline("if (maybe) printf(\"REALLY BAD\");");
                    craux.endblock();
                    break;
-               case MultUpdateNode.REMOVE:
+               case MultUpdateNode.REMOVE: {
                    Rule r=un.getRule();
                    String methodcall="void "+methodname+"("+name+"_state * "+ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable;
                    for(int j=0;j<r.numQuantifiers();j++) {
@@ -173,15 +187,53 @@ public class RepairGenerator {
                    craux.outputline(methodcall);
                    craux.startblock();
                    craux.outputline("int maybe=0;");
+                   if (Compiler.GENERATEINSTRUMENT)
+                       craux.outputline("updatecount++;");
                    final SymbolTable st2 = un.getRule().getSymbolTable();
                    CodeWriter cr2 = new StandardCodeWriter(outputaux) {
                         public SymbolTable getSymbolTable() { return st2; }
                     };
-                   un.generate(cr2, true, null,null,this);
+                   un.generate(cr2, true, false, null,null, null,this);
                    craux.outputline("if (maybe) printf(\"REALLY BAD\");");
                    craux.endblock();
+               }
                    break;
-               case MultUpdateNode.MODIFY:
+               case MultUpdateNode.MODIFY: {
+                   Rule r=un.getRule();
+                   String methodcall="void "+methodname+"("+name+"_state * "+ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable;
+                   for(int j=0;j<r.numQuantifiers();j++) {
+                       Quantifier q=r.getQuantifier(j);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getType().getGenerateType().getSafeSymbol()+" "+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           
+                           methodcall+=", "+rq.x.getType().getGenerateType().getSafeSymbol()+" "+rq.x.getSafeSymbol();
+                           methodcall+=", "+rq.y.getType().getGenerateType().getSafeSymbol()+" "+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=", int "+fq.getVar().getSafeSymbol();
+                       }
+                   }
+                   methodcall+=", int "+stleft+", int "+stright+", int "+stnew;
+                   methodcall+=")";
+                   crhead.outputline(methodcall+";");
+                   craux.outputline(methodcall);
+                   craux.startblock();
+                   craux.outputline("int maybe=0;");
+                   if (Compiler.GENERATEINSTRUMENT)
+                       craux.outputline("updatecount++;");
+                   final SymbolTable st2 = un.getRule().getSymbolTable();
+                   CodeWriter cr2 = new StandardCodeWriter(outputaux) {
+                        public SymbolTable getSymbolTable() { return st2; }
+                    };
+                   un.generate(cr2, false, true, stleft, stright, stnew, this);
+                   craux.outputline("if (maybe) printf(\"REALLY BAD\");");
+                   craux.endblock();
+               }
+                   break;
+
                default:
                    throw new Error("Nonimplement Update");
                }
@@ -245,8 +297,13 @@ public class RepairGenerator {
            TypeDescriptor ttd=(TypeDescriptor)it.next();
            tdarray[ttd.getId()]=ttd;
        }
-       CodeWriter cr=new StandardCodeWriter(outputaux);
+       final SymbolTable st = state.stGlobals;
+       CodeWriter cr = new StandardCodeWriter(outputaux) {
+               public SymbolTable getSymbolTable() { return st; }
+           };
+
        cr.outputline("void "+name+"_state::computesizes(int *sizearray,int **numele) {");
+       cr.outputline("int maybe=0;");
        for(int i=0;i<max;i++) {
            TypeDescriptor td=tdarray[i];
            Expr size=td.getSizeExpr();
@@ -270,6 +327,7 @@ public class RepairGenerator {
                }
            }
        }
+       cr.outputline("if (maybe) printf(\"BAD ERROR\");");
        cr.outputline("}");
     }
 
@@ -280,8 +338,12 @@ public class RepairGenerator {
            TypeDescriptor ttd=(TypeDescriptor)it.next();
            tdarray[ttd.getId()]=ttd;
        }
-       CodeWriter cr=new StandardCodeWriter(outputaux);
+       final SymbolTable st = state.stGlobals;
+       CodeWriter cr = new StandardCodeWriter(outputaux) {
+               public SymbolTable getSymbolTable() { return st; }
+           };
        cr.outputline("void "+name+"_state::recomputesizes() {");
+       cr.outputline("int maybe=0;");
        for(int i=0;i<max;i++) {
            TypeDescriptor td=tdarray[i];
            Expr size=td.getSizeExpr();
@@ -303,6 +365,7 @@ public class RepairGenerator {
                }
            }
        }
+       cr.outputline("if (maybe) printf(\"BAD ERROR\");");
        cr.outputline("}");
     }
 
@@ -324,7 +387,25 @@ public class RepairGenerator {
        crhead.outputline("~"+name+"();");
         craux.outputline("#include \""+headername+"\"");
         craux.outputline("#include \"size.h\"");
-
+       if (Compiler.TIME) {
+           craux.outputline("#include <sys/time.h>");
+       }
+       if (Compiler.ALLOCATECPLUSPLUS) {
+           for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
+               TypeDescriptor td=(TypeDescriptor)it.next();
+               if (td instanceof StructureTypeDescriptor) {
+                   if (((StructureTypeDescriptor)td).size()>0) {
+                       FieldDescriptor fd=((StructureTypeDescriptor)td).get(0);
+                       if (fd.getSymbol().startsWith("_vptr_")) {
+                           String vtable="_ZTV";
+                           vtable+=td.getSymbol().length();
+                           vtable+=td.getSymbol();
+                           craux.outputline("extern void * "+vtable+";");
+                       }
+                   }
+               }
+           }
+       }
         craux.outputline(name+"::"+name+"() {");
         craux.outputline("// creating hashtables ");
         
@@ -409,9 +490,26 @@ public class RepairGenerator {
        worklist=VarDescriptor.makeNew("worklist");
        goodflag=VarDescriptor.makeNew("goodflag");
        repairtable=VarDescriptor.makeNew("repairtable");
+
+       if (Compiler.GENERATEINSTRUMENT) {
+           craux.outputline("int updatecount;");
+           craux.outputline("int rebuildcount;");
+           craux.outputline("int abstractcount;");
+       }
+       
        crhead.outputline("void doanalysis();");
        craux.outputline("void "+name +"_state::doanalysis()");
        craux.startblock();
+       if (Compiler.TIME) {
+           craux.outputline("struct timeval _begin_time,_end_time;");
+           craux.outputline("gettimeofday(&_begin_time,NULL);");
+       }
+
+       if (Compiler.GENERATEINSTRUMENT) {
+           craux.outputline("updatecount=0;");
+           craux.outputline("rebuildcount=0;");
+           craux.outputline("abstractcount=0;");
+       }
        craux.outputline("int highmark;");
        craux.outputline("initializestack(&highmark);");
        craux.outputline("typeobject *typeobject1=gettypeobject();");
@@ -423,11 +521,71 @@ public class RepairGenerator {
        craux.outputline("while (1)");
        craux.startblock();
        craux.outputline(name+ " * "+newmodel.getSafeSymbol()+"=new "+name+"();");
+       craux.outputline(worklist.getSafeSymbol()+"->reset();");
+       if (Compiler.GENERATEINSTRUMENT)
+           craux.outputline("rebuildcount++;");
     }
     
     private void generate_teardown() {
        CodeWriter cr = new StandardCodeWriter(outputaux);        
        cr.endblock();
+       if (Compiler.TIME) {
+           cr.outputline("gettimeofday(&_end_time,NULL);");
+           cr.outputline("printf(\"time=%ld uS\\n\",(_end_time.tv_sec-_begin_time.tv_sec)*1000000+_end_time.tv_usec-_begin_time.tv_usec);");
+       }
+
+       if (Compiler.GENERATEINSTRUMENT) {
+           cr.outputline("printf(\"updatecount=%d\\n\",updatecount);");
+           cr.outputline("printf(\"rebuildcount=%d\\n\",rebuildcount);");
+           cr.outputline("printf(\"abstractcount=%d\\n\",abstractcount);");
+       }
+
+    }
+
+    private void generate_print() {
+       
+       final SymbolTable st = new SymbolTable();
+
+       CodeWriter cr = new StandardCodeWriter(outputaux) {
+               public SymbolTable getSymbolTable() { return st; }
+           };
+
+       cr.outputline("// printing sets!");
+       cr.outputline("printf(\"\\n\\nPRINTING SETS AND RELATIONS\\n\");");
+
+        Iterator setiterator = state.stSets.descriptors();
+       while (setiterator.hasNext()) {
+           SetDescriptor sd = (SetDescriptor) setiterator.next();
+           if (sd.getSymbol().equals("int") || sd.getSymbol().equals("token")) {
+               continue;
+           }
+
+           String setname = sd.getSafeSymbol();
+
+           cr.startblock();
+           cr.outputline("// printing set " + setname);
+           cr.outputline("printf(\"\\nPrinting set " + sd.getSymbol() + " - %d elements \\n\", " + setname + "_hash->count());");
+           cr.outputline("SimpleIterator __setiterator;");
+           cr.outputline("" + setname + "_hash->iterator(__setiterator);");
+           cr.outputline("while (__setiterator.hasNext())");
+           cr.startblock();
+           cr.outputline("int __setval = (int) __setiterator.next();");
+
+           TypeDescriptor td = sd.getType();
+           if (td instanceof StructureTypeDescriptor) {
+               StructureTypeDescriptor std = (StructureTypeDescriptor) td;
+               VarDescriptor vd = new VarDescriptor ("__setval", "__setval", td, false);
+               std.generate_printout(cr, vd);
+           } else { // Missing type descriptor or reserved type, just print int
+               cr.outputline("printf(\"<%d> \", __setval);");                  
+           }
+
+
+           cr.endblock();
+           cr.endblock();
+       }
+
+       cr.outputline("printf(\"\\n\\n------------------- END PRINTING\\n\");");
     }
 
     Set ruleset=null;
@@ -444,15 +602,54 @@ public class RepairGenerator {
                Iterator iterator_rs = ruleset.iterator();
                while (iterator_rs.hasNext()) {
                    Rule rule = (Rule) iterator_rs.next();
+                   if (rule.getnogenerate())
+                       continue;
                    {
                        final SymbolTable st = rule.getSymbolTable();
                        CodeWriter cr = new StandardCodeWriter(outputaux) {
                                public SymbolTable getSymbolTable() { return st; }
                            };
+                       InvariantValue ivalue=new InvariantValue();
+                       cr.setInvariantValue(ivalue);
+
                        cr.outputline("// build " +escape(rule.toString()));
                        cr.startblock();
                        cr.outputline("int maybe=0;");
-                       ListIterator quantifiers = rule.quantifiers();
+
+                       Expr ruleexpr=rule.getGuardExpr();
+                       HashSet invariantvars=new HashSet();
+                       Set invariants=ruleexpr.findInvariants(invariantvars);
+
+                       if ((ruleexpr instanceof BooleanLiteralExpr)&&
+                           ((BooleanLiteralExpr)ruleexpr).getValue()) {
+                           if (rule.getInclusion() instanceof SetInclusion) {
+                               invariants.addAll(((SetInclusion)rule.getInclusion()).getExpr().findInvariants(invariantvars));
+                           } else if (rule.getInclusion() instanceof RelationInclusion) {
+                               invariants.addAll(((RelationInclusion)rule.getInclusion()).getLeftExpr().findInvariants(invariantvars));
+                               invariants.addAll(((RelationInclusion)rule.getInclusion()).getRightExpr().findInvariants(invariantvars));
+                           }
+                       }
+                       ListIterator quantifiers = rule.quantifiers();                  
+                       while (quantifiers.hasNext()) {
+                           Quantifier quantifier = (Quantifier) quantifiers.next();
+                           if (quantifier instanceof ForQuantifier) {
+                               ForQuantifier fq=(ForQuantifier)quantifier;
+                               invariants.addAll(fq.lower.findInvariants(invariantvars));
+                               invariants.addAll(fq.upper.findInvariants(invariantvars));
+                           }
+                       }
+
+                       for(Iterator invit=invariants.iterator();invit.hasNext();) {
+                           Expr invexpr=(Expr)invit.next();
+                           VarDescriptor tmpvd=VarDescriptor.makeNew("tmpvar");
+                           VarDescriptor maybevd=VarDescriptor.makeNew("maybevar");
+                           invexpr.generate(cr,tmpvd);
+                           cr.outputline("int "+maybevd.getSafeSymbol()+"=maybe;");
+                           cr.outputline("maybe=0;");
+                           ivalue.assignPair(invexpr,tmpvd,maybevd);
+                       }
+
+                       quantifiers = rule.quantifiers();
                        while (quantifiers.hasNext()) {
                            Quantifier quantifier = (Quantifier) quantifiers.next();
                            quantifier.generate_open(cr);
@@ -533,15 +730,15 @@ public class RepairGenerator {
                        
                        rule.getGuardExpr().prettyPrint(cr);
                        cr.outputline("");
-
+                       
                        /* now we have to generate the guard test */
-        
+                       
                        VarDescriptor guardval = VarDescriptor.makeNew();
                        rule.getGuardExpr().generate(cr, guardval);
                        
                        cr.outputline("if (" + guardval.getSafeSymbol() + ")");
                        cr.startblock();
-
+                       
                        /* now we have to generate the inclusion code */
                        currentrule=rule;
                        rule.getInclusion().generate(cr);
@@ -550,10 +747,10 @@ public class RepairGenerator {
                        for (int j=0;j<rule.numQuantifiers();j++) {
                            cr.endblock();
                        }
-
+                       
                        // close startblocks generated by DotExpr memory checks
                        //DotExpr.generate_memory_endblocks(cr);
-
+                       
                        cr.endblock(); // end else-if WORKLIST ladder
                        
                        elseladder = "else if";
@@ -584,31 +781,33 @@ public class RepairGenerator {
     }
 
     private void generate_checks() {
-
         /* do constraint checks */
-        Vector constraints = state.vConstraints;
-
-        for (int i = 0; i < constraints.size(); i++) {
-
-            Constraint constraint = (Constraint) constraints.elementAt(i); 
-
+       Iterator i;
+       if (Compiler.REPAIR)
+           i=termination.constraintdependence.computeOrdering().iterator();
+       else
+           i=state.vConstraints.iterator();
+       for (; i.hasNext();) {
+           Constraint constraint;
+           if (Compiler.REPAIR)
+               constraint= (Constraint) ((GraphNode)i.next()).getOwner();
+           else
+               constraint=(Constraint)i.next();
+           
             {
+               final SymbolTable st = constraint.getSymbolTable();
+               CodeWriter cr = new StandardCodeWriter(outputaux);
+               cr.pushSymbolTable(constraint.getSymbolTable());
 
-                final SymbolTable st = constraint.getSymbolTable();
-                
-                CodeWriter cr = new StandardCodeWriter(outputaux) {
-                        public SymbolTable getSymbolTable() { return st; }
-                    };
-
-                cr.outputline("// checking " + escape(constraint.toString()));
+               cr.outputline("// checking " + escape(constraint.toString()));
                 cr.startblock();
 
                 ListIterator quantifiers = constraint.quantifiers();
 
                 while (quantifiers.hasNext()) {
-                    Quantifier quantifier = (Quantifier) quantifiers.next();                   
+                    Quantifier quantifier = (Quantifier) quantifiers.next();
                     quantifier.generate_open(cr);
-                }            
+                }
 
                 cr.outputline("int maybe = 0;");
                         
@@ -619,26 +818,30 @@ public class RepairGenerator {
                 
                 cr.outputline("if (maybe)");
                 cr.startblock();
-                cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \");");
-                cr.outputline("exit(1);");
+                cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \\n\");");
+               //cr.outputline("exit(1);");
                 cr.endblock();
 
                 cr.outputline("else if (!" + constraintboolean.getSafeSymbol() + ")");
                 cr.startblock();
-                if (DEBUG)
-                   cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \");");
-
+                if (!Compiler.REPAIR||Compiler.GENERATEDEBUGHOOKS)
+                   cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \\n\");");
+               
+               if (Compiler.REPAIR) {
                /* Do repairs */
                /* Build new repair table */
                cr.outputline("if ("+repairtable.getSafeSymbol()+")");
                cr.outputline("delete "+repairtable.getSafeSymbol()+";");
                 cr.outputline(repairtable.getSafeSymbol()+"=new RepairHash();");
-
                
+               if (Compiler.GENERATEDEBUGHOOKS)
+                   cr.outputline("debughook();");
                /* Compute cost of each repair */
                VarDescriptor mincost=VarDescriptor.makeNew("mincost");
                VarDescriptor mincostindex=VarDescriptor.makeNew("mincostindex");
-               DNFConstraint dnfconst=constraint.dnfconstraint;
+               Vector dnfconst=new Vector();
+               dnfconst.addAll((Set)termination.conjunctionmap.get(constraint));
+
                if (dnfconst.size()<=1) {
                    cr.outputline("int "+mincostindex.getSafeSymbol()+"=0;");
                }
@@ -646,8 +849,8 @@ public class RepairGenerator {
                    cr.outputline("int "+mincostindex.getSafeSymbol()+";");
                    boolean first=true;
                    for(int j=0;j<dnfconst.size();j++) {
-                       Conjunction conj=dnfconst.get(j);
-                       GraphNode gn=(GraphNode)termination.conjtonodemap.get(conj);
+                       GraphNode gn=(GraphNode)dnfconst.get(j);
+                       Conjunction conj=((TermNode)gn.getOwner()).getConjunction();
                        if (removed.contains(gn))
                            continue;
                        
@@ -662,16 +865,16 @@ public class RepairGenerator {
                            boolean negate=dpred.isNegated();
                            VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
                            p.generate(cr,predvalue);
+                           if (k==0)
+                               cr.outputline("int "+costvar.getSafeSymbol()+"=0;");
+                           
                            if (negate)
                                cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
                            else
                                cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
-                           if (k==0)
-                               cr.outputline("int "+costvar.getSafeSymbol()+"="+cost.getCost(dpred)+";");
-                           else
-                               cr.outputline(costvar.getSafeSymbol()+"+="+cost.getCost(dpred)+";");
+                           cr.outputline(costvar.getSafeSymbol()+"+="+cost.getCost(dpred)+";");
                        }
-
+                       
                        if(!first) {
                            cr.outputline("if ("+costvar.getSafeSymbol()+"<"+mincost.getSafeSymbol()+")");
                            cr.startblock();
@@ -685,11 +888,12 @@ public class RepairGenerator {
                }
                cr.outputline("switch("+mincostindex.getSafeSymbol()+") {");
                for(int j=0;j<dnfconst.size();j++) {
-                   Conjunction conj=dnfconst.get(j);
-                   GraphNode gn=(GraphNode)termination.conjtonodemap.get(conj);
+                   GraphNode gn=(GraphNode)dnfconst.get(j);
+                   Conjunction conj=((TermNode)gn.getOwner()).getConjunction();
                    if (removed.contains(gn))
                        continue;
                    cr.outputline("case "+j+":");
+                   cr.startblock();
                    for(int k=0;k<conj.size();k++) {
                        DNFPredicate dpred=conj.get(k);
                        Predicate p=dpred.getPredicate();
@@ -701,6 +905,8 @@ public class RepairGenerator {
                        else
                            cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
                        cr.startblock();
+                       if (Compiler.GENERATEINSTRUMENT)
+                           cr.outputline("abstractcount++;");
                        if (p instanceof InclusionPredicate)
                            generateinclusionrepair(conj,dpred, cr);
                        else if (p instanceof ExprPredicate) {
@@ -713,17 +919,18 @@ public class RepairGenerator {
                        cr.endblock();
                    }
                    /* Update model */
+                   cr.endblock();
                    cr.outputline("break;");
                }
                cr.outputline("}");
-
+               
                cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
                cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
                cr.outputline(oldmodel.getSafeSymbol()+"="+newmodel.getSafeSymbol()+";");
                cr.outputline("goto rebuild;");  /* Rebuild model and all */
-
+               }
                 cr.endblock();
-
+               
                 while (quantifiers.hasPrevious()) {
                     Quantifier quantifier = (Quantifier) quantifiers.previous();
                     cr.endblock();
@@ -746,13 +953,21 @@ public class RepairGenerator {
        cr.endblock();
        cr.outputline("rebuild:");
        cr.outputline(";");     
-       
     }
     
     private MultUpdateNode getmultupdatenode(Conjunction conj, DNFPredicate dpred, int repairtype) {
-       MultUpdateNode mun=null;
+       Set nodes=getmultupdatenodeset(conj,dpred,repairtype);
+       Iterator it=nodes.iterator();
+       if (it.hasNext())
+           return (MultUpdateNode)it.next();
+       else
+           return null;
+    }
+
+    private Set getmultupdatenodeset(Conjunction conj, DNFPredicate dpred, int repairtype) {
+       HashSet hs=new HashSet();
        GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
-       for(Iterator edgeit=gn.edges();(mun==null)&&edgeit.hasNext();) {
+       for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
            GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
            TermNode tn2=(TermNode)gn2.getOwner();
            if (tn2.getType()==TermNode.ABSTRACT) {
@@ -764,20 +979,54 @@ public class RepairGenerator {
                        if (!removed.contains(gn3)) {
                            TermNode tn3=(TermNode)gn3.getOwner();
                            if (tn3.getType()==TermNode.UPDATE) {
-                               mun=tn3.getUpdate();
-                               break;
+                               hs.add(tn3.getUpdate());
                            }
                        }
                    }
                }
            }
        }
-       return mun;
+       return hs;
+    }
+
+    private AbstractRepair getabstractrepair(Conjunction conj, DNFPredicate dpred, int repairtype) {
+       HashSet hs=new HashSet();
+       MultUpdateNode mun=null;
+       GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
+       for(Iterator edgeit=gn.edges();(mun==null)&&edgeit.hasNext();) {
+           GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
+           TermNode tn2=(TermNode)gn2.getOwner();
+           if (tn2.getType()==TermNode.ABSTRACT) {
+               AbstractRepair ar=tn2.getAbstract();
+               if (((repairtype==-1)||(ar.getType()==repairtype))&&
+                   ar.getPredicate()==dpred) {
+                   return ar;
+               }
+           }
+       }
+       return null;
     }
 
-    public void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
-       MultUpdateNode munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
-       MultUpdateNode munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
+
+    /** Generates abstract (and concrete) repair for a comparison */
+
+    private void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
+       Set updates=getmultupdatenodeset(conj,dpred,AbstractRepair.MODIFYRELATION);
+       AbstractRepair ar=getabstractrepair(conj,dpred,AbstractRepair.MODIFYRELATION);
+       MultUpdateNode munmodify=null;
+       MultUpdateNode munadd=null;
+       MultUpdateNode munremove=null;
+       for(Iterator it=updates.iterator();it.hasNext();) {
+           MultUpdateNode mun=(MultUpdateNode)it.next();
+           if (mun.getType()==MultUpdateNode.ADD) {
+               munadd=mun;
+           } else if (mun.getType()==MultUpdateNode.REMOVE) { 
+               munremove=mun;
+           } else if (mun.getType()==MultUpdateNode.MODIFY) {
+               munmodify=mun;
+           }
+       }
+       
        ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
        RelationDescriptor rd=(RelationDescriptor)ep.getDescriptor();
        boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
@@ -789,33 +1038,28 @@ public class RepairGenerator {
        VarDescriptor leftside=VarDescriptor.makeNew("leftside");
        VarDescriptor rightside=VarDescriptor.makeNew("rightside");
        VarDescriptor newvalue=VarDescriptor.makeNew("newvalue");
-       if (!inverted) {
-           expr.getLeftExpr().generate(cr,leftside);
+       boolean needremoveloop=ar.mayNeedFunctionEnforcement(state)&&ar.needsRemoves(state);
+
+       if (needremoveloop&&((munadd==null)||(munremove==null))) {
+           System.out.println("Warning:  need to have individual remove operations for"+dpred.name());
+           needremoveloop=false;
+       }
+       if (needremoveloop)
+           cr.outputline("while (1) {");
+
+       if (!inverted) {
+           ((RelationExpr)expr.getLeftExpr()).getExpr().generate(cr,leftside);
            expr.getRightExpr().generate(cr,newvalue);
            cr.outputline(rd.getRange().getType().getGenerateType().getSafeSymbol()+" "+rightside.getSafeSymbol()+";");
            cr.outputline(rd.getSafeSymbol()+"_hash->get("+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
        } else {
-           expr.getLeftExpr().generate(cr,rightside);
+           ((RelationExpr)expr.getLeftExpr()).getExpr().generate(cr,rightside);
            expr.getRightExpr().generate(cr,newvalue);
            cr.outputline(rd.getDomain().getType().getGenerateType().getSafeSymbol()+" "+leftside.getSafeSymbol()+";");
-           cr.outputline(rd.getSafeSymbol()+"_hashinv->get("+leftside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
+           cr.outputline(rd.getSafeSymbol()+"_hashinv->get("+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
        }
-       if (negated)
-           if (opcode==Opcode.GT) {
-               opcode=Opcode.LE;
-           } else if (opcode==Opcode.GE) {
-               opcode=Opcode.LT;
-           } else if (opcode==Opcode.LT) {
-               opcode=Opcode.GE;
-           } else if (opcode==Opcode.LE) {
-               opcode=Opcode.GT;
-           } else if (opcode==Opcode.EQ) {
-               opcode=Opcode.NE;
-           } else if (opcode==Opcode.NE) {
-               opcode=Opcode.EQ;
-           } else {
-               throw new Error("Unrecognized Opcode");
-           }
+
+       opcode=Opcode.translateOpcode(negated,opcode);
 
        if (opcode==Opcode.GT) {
            cr.outputline(newvalue.getSafeSymbol()+"++;");
@@ -827,7 +1071,7 @@ public class RepairGenerator {
            /* Equal */
        } else if (opcode==Opcode.EQ) {
            /* Equal */
-       } else if (opcode==Opcode.NE) {
+       } else if (opcode==Opcode.NE) { /* search for FLAGNE if this is changed*/
            cr.outputline(newvalue.getSafeSymbol()+"++;");
        } else {
            throw new Error("Unrecognized Opcode");
@@ -835,6 +1079,35 @@ public class RepairGenerator {
        /* Do abstract repairs */
        if (usageimage) {
            cr.outputline(rd.getSafeSymbol()+"_hash->remove("+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
+       }
+       if (usageinvimage) {
+           cr.outputline(rd.getSafeSymbol()+"_hashinv->remove("+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
+       }
+
+       if (needremoveloop) {
+           if (!inverted) {
+               cr.outputline("if ("+rd.getSafeSymbol()+"_hash->contains("+leftside.getSafeSymbol()+")) {");
+           } else {
+               cr.outputline("if ("+rd.getSafeSymbol()+"_hashinv->contains("+rightside.getSafeSymbol()+")) {");
+           }
+           for(int i=0;i<state.vRules.size();i++) {
+               Rule r=(Rule)state.vRules.get(i);
+               if (r.getInclusion().getTargetDescriptors().contains(rd)) {
+                   for(int j=0;j<munremove.numUpdates();j++) {
+                       UpdateNode un=munremove.getUpdate(i);
+                       if (un.getRule()==r) {
+                               /* Update for rule r */
+                           String name=(String)updatenames.get(un);
+                           cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
+                       }
+                   }
+               }
+           }
+           cr.outputline("continue;");
+           cr.outputline("}");
+       }
+
+       if (usageimage) {
            if (!inverted) {
                cr.outputline(rd.getSafeSymbol()+"_hash->add("+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
            } else {
@@ -842,7 +1115,6 @@ public class RepairGenerator {
            }
        }
        if (usageinvimage) {
-           cr.outputline(rd.getSafeSymbol()+"_hashinv->remove("+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
            if (!inverted) {
                cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+newvalue.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
            } else {
@@ -850,27 +1122,48 @@ public class RepairGenerator {
            }
        }
        /* Do concrete repairs */
-       /* Start with scheduling removal */
-       for(int i=0;i<state.vRules.size();i++) {
-           Rule r=(Rule)state.vRules.get(i);
-           if (r.getInclusion().getTargetDescriptors().contains(rd)) {
-               for(int j=0;j<munremove.numUpdates();j++) {
-                   UpdateNode un=munremove.getUpdate(i);
-                   if (un.getRule()==r) {
-                       /* Update for rule r */
-                       String name=(String)updatenames.get(un);
-                       cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
+       if (munmodify!=null&&(!ar.mayNeedFunctionEnforcement(state))||(munadd==null)||(ar.needsRemoves(state)&&(munremove==null))) {
+           for(int i=0;i<state.vRules.size();i++) {
+               Rule r=(Rule)state.vRules.get(i);
+               if (r.getInclusion().getTargetDescriptors().contains(rd)) {
+                   for(int j=0;j<munmodify.numUpdates();j++) {
+                       UpdateNode un=munmodify.getUpdate(j);
+                       if (un.getRule()==r) {
+                           /* Update for rule r */
+                           String name=(String)updatenames.get(un);
+                           cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+","+newvalue.getSafeSymbol()+");");
+                       }
                    }
                }
            }
-       }
-       /* Now do addition */
-       UpdateNode un=munadd.getUpdate(0);
-       String name=(String)updatenames.get(un);
-       if (!inverted) {
-           cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
        } else {
-           cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
+           /* Start with scheduling removal */
+           if (ar.needsRemoves(state))
+               for(int i=0;i<state.vRules.size();i++) {
+                   Rule r=(Rule)state.vRules.get(i);
+                   if (r.getInclusion().getTargetDescriptors().contains(rd)) {
+                       for(int j=0;j<munremove.numUpdates();j++) {
+                           UpdateNode un=munremove.getUpdate(i);
+                           if (un.getRule()==r) {
+                               /* Update for rule r */
+                               String name=(String)updatenames.get(un);
+                               cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
+                           }
+                       }
+                   }
+               }
+           /* Now do addition */
+           UpdateNode un=munadd.getUpdate(0);
+           String name=(String)updatenames.get(un);
+           if (!inverted) {
+               cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
+           } else {
+               cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
+           }
+       }
+       if (needremoveloop) {
+           cr.outputline("break;");
+           cr.outputline("}");
        }
     }
 
@@ -878,25 +1171,8 @@ public class RepairGenerator {
        ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
        OpExpr expr=(OpExpr)ep.expr;
        Opcode opcode=expr.getOpcode();
-       {
-           boolean negated=dpred.isNegated();
-           if (negated)
-               if (opcode==Opcode.GT) {
-                   opcode=Opcode.LE;
-               } else if (opcode==Opcode.GE) {
-                   opcode=Opcode.LT;
-               } else if (opcode==Opcode.LT) {
-                   opcode=Opcode.GE;
-               } else if (opcode==Opcode.LE) {
-                   opcode=Opcode.GT;
-               } else if (opcode==Opcode.EQ) {
-                   opcode=Opcode.NE;
-               } else if (opcode==Opcode.NE) {
-                   opcode=Opcode.EQ;
-               } else {
-                   throw new Error("Unrecognized Opcode");
-               }       
-       }
+       opcode=Opcode.translateOpcode(dpred.isNegated(),opcode);
+
        MultUpdateNode munremove;
 
        MultUpdateNode munadd;
@@ -907,7 +1183,7 @@ public class RepairGenerator {
            munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMSET);
            munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTOSET);
        }
-       int size=ep.leftsize();
+       int size=ep.rightSize();
        VarDescriptor sizevar=VarDescriptor.makeNew("size");
        ((OpExpr)expr).left.generate(cr, sizevar);
        VarDescriptor change=VarDescriptor.makeNew("change");
@@ -944,6 +1220,12 @@ public class RepairGenerator {
        } else {
            throw new Error("Unrecognized Opcode");
        }
+
+// In some cases the analysis has determined that generating removes
+// is unnecessary
+       if (generateremove&&munremove==null) 
+           generateremove=false;
+
        Descriptor d=ep.getDescriptor();
        if (generateremove) {
            cr.outputline("for(;"+change.getSafeSymbol()+"<0;"+change.getSafeSymbol()+"++)");
@@ -953,11 +1235,11 @@ public class RepairGenerator {
            VarDescriptor rightvar=VarDescriptor.makeNew("rightvar");
            if (d instanceof RelationDescriptor) {
                if (ep.inverted()) {
-                   rightvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
+                   ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,rightvar);
                    cr.outputline("int "+leftvar.getSafeSymbol()+";");
                    cr.outputline(d.getSafeSymbol()+"_hashinv->get((int)"+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
                } else {
-                   leftvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
+                   ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,leftvar);
                    cr.outputline("int "+rightvar.getSafeSymbol()+"=0;");
                    cr.outputline(d.getSafeSymbol()+"_hash->get((int)"+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
                }
@@ -996,32 +1278,41 @@ public class RepairGenerator {
            }
            cr.endblock();
        }
+
+// In some cases the analysis has determined that generating removes
+// is unnecessary
+       if (generateadd&&munadd==null) 
+           generateadd=false;
+
        if (generateadd) {
 
            cr.outputline("for(;"+change.getSafeSymbol()+">0;"+change.getSafeSymbol()+"--)");
            cr.startblock();
            VarDescriptor newobject=VarDescriptor.makeNew("newobject");
            if (d instanceof RelationDescriptor) {
-               VarDescriptor otherside=((ImageSetExpr)((SizeofExpr)((OpExpr)ep.expr).left).setexpr).vd;
+               VarDescriptor otherside=VarDescriptor.makeNew("otherside");
+               ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,otherside);
+               
                RelationDescriptor rd=(RelationDescriptor)d;
-               if (sources.relsetSource(rd,!ep.inverted())) {
+               if (termination.sources.relsetSource(rd,!ep.inverted())) {
                    /* Set Source */
-                   SetDescriptor sd=sources.relgetSourceSet(rd,!ep.inverted());
+                   SetDescriptor sd=termination.sources.relgetSourceSet(rd,!ep.inverted());
                    VarDescriptor iterator=VarDescriptor.makeNew("iterator");
                    cr.outputline(sd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
-                   cr.outputline("for("+iterator.getSafeSymbol()+"="+sd.getSafeSymbol()+"_hash->iterator();"+iterator.getSafeSymbol()+".hasNext();)");
+                   cr.outputline("SimpleIterator "+iterator.getSafeSymbol()+";");
+                   cr.outputline("for("+sd.getSafeSymbol()+"_hash->iterator("+ iterator.getSafeSymbol() +");"+iterator.getSafeSymbol()+".hasNext();)");
                    cr.startblock();
                    if (ep.inverted()) {
-                       cr.outputline("if !"+rd.getSafeSymbol()+"_hashinv->contains("+iterator.getSafeSymbol()+"->key(),"+otherside.getSafeSymbol()+")");
+                       cr.outputline("if (!"+rd.getSafeSymbol()+"_hashinv->contains("+iterator.getSafeSymbol()+".key(),"+otherside.getSafeSymbol()+"))");
                    } else {
-                       cr.outputline("if !"+rd.getSafeSymbol()+"_hash->contains("+otherside.getSafeSymbol()+","+iterator.getSafeSymbol()+"->key())");
+                       cr.outputline("if (!"+rd.getSafeSymbol()+"_hash->contains("+otherside.getSafeSymbol()+","+iterator.getSafeSymbol()+".key()))");
                    }
                    cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
-                   cr.outputline(iterator.getSafeSymbol()+"->next();");
+                   cr.outputline(iterator.getSafeSymbol()+".next();");
                    cr.endblock();
-               } else if (sources.relallocSource(rd,!ep.inverted())) {
+               } else if (termination.sources.relallocSource(rd,!ep.inverted())) {
                    /* Allocation Source*/
-                   sources.relgenerateSourceAlloc(cr,newobject,rd,!ep.inverted());
+                   termination.sources.relgenerateSourceAlloc(cr,newobject,rd,!ep.inverted());
                } else throw new Error("No source for adding to Relation");
                if (ep.inverted()) {
                    boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
@@ -1047,21 +1338,22 @@ public class RepairGenerator {
                }
            } else {
                SetDescriptor sd=(SetDescriptor)d;
-               if (sources.setSource(sd)) {
+               if (termination.sources.setSource(sd)) {
                    /* Set Source */
                    /* Set Source */
-                   SetDescriptor sourcesd=sources.getSourceSet(sd);
+                   SetDescriptor sourcesd=termination.sources.getSourceSet(sd);
                    VarDescriptor iterator=VarDescriptor.makeNew("iterator");
                    cr.outputline(sourcesd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
-                   cr.outputline("for("+iterator.getSafeSymbol()+"="+sourcesd.getSafeSymbol()+"_hash->iterator();"+iterator.getSafeSymbol()+".hasNext();)");
+                   cr.outputline("SimpleIterator "+iterator.getSafeSymbol()+";");
+                   cr.outputline("for("+sourcesd.getSafeSymbol()+"_hash->iterator("+iterator.getSafeSymbol()+");"+iterator.getSafeSymbol()+".hasNext();)");
                    cr.startblock();
-                   cr.outputline("if !"+sd.getSafeSymbol()+"_hash->contains("+iterator.getSafeSymbol()+"->key())");
+                   cr.outputline("if (!"+sd.getSafeSymbol()+"_hash->contains("+iterator.getSafeSymbol()+".key()))");
                    cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
-                   cr.outputline(iterator.getSafeSymbol()+"->next();");
+                   cr.outputline(iterator.getSafeSymbol()+".next();");
                    cr.endblock();
-               } else if (sources.allocSource(sd)) {
+               } else if (termination.sources.allocSource(sd)) {
                    /* Allocation Source*/
-                   sources.generateSourceAlloc(cr,newobject,sd);
+                   termination.sources.generateSourceAlloc(cr,newobject,sd);
                } else throw new Error("No source for adding to Set");
                cr.outputline(sd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
                UpdateNode un=munadd.getUpdate(0);
@@ -1102,7 +1394,7 @@ public class RepairGenerator {
                    Rule r=(Rule)state.vRules.get(i);
                    if (r.getInclusion().getTargetDescriptors().contains(rd)) {
                        for(int j=0;j<mun.numUpdates();j++) {
-                           UpdateNode un=mun.getUpdate(i);
+                           UpdateNode un=mun.getUpdate(j);
                            if (un.getRule()==r) {
                                /* Update for rule rule r */
                                String name=(String)updatenames.get(un);
@@ -1123,7 +1415,7 @@ public class RepairGenerator {
                    Rule r=(Rule)state.vRules.get(i);
                    if (r.getInclusion().getTargetDescriptors().contains(sd)) {
                        for(int j=0;j<mun.numUpdates();j++) {
-                           UpdateNode un=mun.getUpdate(i);
+                           UpdateNode un=mun.getUpdate(j);
                            if (un.getRule()==r) {
                                /* Update for rule rule r */
                                String name=(String)updatenames.get(un);
@@ -1192,6 +1484,8 @@ public class RepairGenerator {
     }
 
     private boolean need_compensation(Rule r) {
+       if (!Compiler.REPAIR)
+           return false;
        GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
        for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
            GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
@@ -1233,87 +1527,136 @@ public class RepairGenerator {
            return;
 
         cr.outputline("// RELATION DISPATCH ");
-       cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
-       if (usageimage)
-           cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hash->contains("+leftvar+","+rightvar+"))");
-       else
-           cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv->contains("+rightvar+","+leftvar+"))");
-       cr.startblock(); {
-           /* Adding new item */
-           /* Perform safety checks */
-           cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
-           cr.outputline(repairtable.getSafeSymbol()+"->containsrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
+       if (Compiler.REPAIR) {
+           cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
+           if (usageimage)
+               cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hash->contains("+leftvar+","+rightvar+"))");
+           else
+               cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv->contains("+rightvar+","+leftvar+"))");
+
            cr.startblock(); {
-               /* Have update to call into */
-               VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
-               String parttype="";
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
-                       parttype=parttype+", int, int";
-                   else
-                       parttype=parttype+", int";
-               }
-               cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
-               cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
-               String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   Quantifier q=currentrule.getQuantifier(i);
-                   if (q instanceof SetQuantifier) {
-                       SetQuantifier sq=(SetQuantifier) q;
-                       methodcall+=","+sq.getVar().getSafeSymbol();
-                   } else if (q instanceof RelationQuantifier) {
-                       RelationQuantifier rq=(RelationQuantifier) q;
-                       methodcall+=","+rq.x.getSafeSymbol();
-                       methodcall+=","+rq.y.getSafeSymbol();
-                   } else if (q instanceof ForQuantifier) {
-                       ForQuantifier fq=(ForQuantifier) q;
-                       methodcall+=","+fq.getVar().getSafeSymbol();
+               /* Adding new item */
+               /* Perform safety checks */
+               cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
+               cr.outputline(repairtable.getSafeSymbol()+"->containsrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
+               cr.startblock(); {
+                   /* Have update to call into */
+                   VarDescriptor mdfyptr=VarDescriptor.makeNew("modifyptr");
+                   VarDescriptor ismdfyptr=VarDescriptor.makeNew("ismodifyptr");
+                   cr.outputline("int "+ismdfyptr.getSafeSymbol()+"="+repairtable.getSafeSymbol()+"->ismodify("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
+
+
+
+                   
+                   String parttype="";
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
+                           parttype=parttype+", int, int";
+                       else
+                           parttype=parttype+", int";
                    }
+                   VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
+                   VarDescriptor tmpptr=VarDescriptor.makeNew("tempupdateptr");
+                   
+                   String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       Quantifier q=currentrule.getQuantifier(i);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           methodcall+=","+rq.x.getSafeSymbol();
+                           methodcall+=","+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=","+fq.getVar().getSafeSymbol();
+                       }
+                   }
+                   
+                   
+                   
+                   cr.outputline("void *"+tmpptr.getSafeSymbol()+"=");
+                   cr.outputline("(void *) "+repairtable.getSafeSymbol()+"->getrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
+                   cr.outputline("if ("+ismdfyptr.getSafeSymbol()+")");
+                   {
+                       cr.startblock();
+                       cr.outputline("int "+mdfyptr.getSafeSymbol()+"="+repairtable.getSafeSymbol()+"->getrelation2("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
+                       cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)) "+tmpptr.getSafeSymbol()+";");
+                       cr.outputline(methodcall+","+leftvar+", "+rightvar+", "+mdfyptr.getSafeSymbol() +");");
+                       cr.endblock();
+                   }
+                   cr.outputline("else ");
+                   {
+                       cr.startblock();
+                       cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+tmpptr.getSafeSymbol()+";");
+                       cr.outputline(methodcall+");");
+                       cr.endblock();
+                   }
+                   cr.outputline("delete "+newmodel.getSafeSymbol()+";");
+                   cr.outputline("goto rebuild;");
                }
-               methodcall+=");";
-               cr.outputline(methodcall);
-               cr.outputline("goto rebuild;");
-           }
-           cr.endblock();
-           /* Build standard compensation actions */
-           if (need_compensation(currentrule)) {
-               UpdateNode un=find_compensation(currentrule);
-               String name=(String)updatenames.get(un);
-               usedupdates.add(un); /* Mark as used */
-               String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   Quantifier q=currentrule.getQuantifier(i);
-                   if (q instanceof SetQuantifier) {
-                       SetQuantifier sq=(SetQuantifier) q;
-                       methodcall+=","+sq.getVar().getSafeSymbol();
-                   } else if (q instanceof RelationQuantifier) {
-                       RelationQuantifier rq=(RelationQuantifier) q;
-                       methodcall+=","+rq.x.getSafeSymbol();
-                       methodcall+=","+rq.y.getSafeSymbol();
-                   } else if (q instanceof ForQuantifier) {
-                       ForQuantifier fq=(ForQuantifier) q;
-                       methodcall+=","+fq.getVar().getSafeSymbol();
+               cr.endblock();
+               
+               /* Build standard compensation actions */
+               if (need_compensation(currentrule)) {
+                   UpdateNode un=find_compensation(currentrule);
+                   String name=(String)updatenames.get(un);
+                   usedupdates.add(un); /* Mark as used */
+                   String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       Quantifier q=currentrule.getQuantifier(i);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           methodcall+=","+rq.x.getSafeSymbol();
+                           methodcall+=","+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=","+fq.getVar().getSafeSymbol();
+                       }
                    }
+                   methodcall+=");";
+                   cr.outputline(methodcall);
+                   cr.outputline("delete "+newmodel.getSafeSymbol()+";");
+                   cr.outputline("goto rebuild;");
                }
-               methodcall+=");";
-               cr.outputline(methodcall);
-               cr.outputline("goto rebuild;");
            }
+           cr.endblock();
        }
-       cr.endblock();
 
         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
-       cr.outputline("int " + addeditem + ";");
+       cr.outputline("int " + addeditem + "=0;");
+
+       String ifstring="if (!maybe&&";
+       boolean dogenerate=false;
+       if (rd.getDomain().getType() instanceof StructureTypeDescriptor)  {
+           dogenerate=true;
+           ifstring+=leftvar;
+       }
+
+       if (rd.getRange().getType() instanceof StructureTypeDescriptor)  {
+           if (dogenerate)
+               ifstring+="&&"+rightvar;
+           else
+               ifstring+=rightvar;
+           dogenerate=true;
+       }
+
+       ifstring+=")";
+
        if (rd.testUsage(RelationDescriptor.IMAGE)) {
+           cr.outputline(ifstring);
            cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar+ ");");
        }
        
        if (rd.testUsage(RelationDescriptor.INVIMAGE)) {
+           cr.outputline(ifstring);
            cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar + ", (int)" + leftvar + ");");
        }
        
-       cr.outputline("if (" + addeditem + ")");
-       cr.startblock();
 
         Vector dispatchrules = getrulelist(rd);
         
@@ -1326,12 +1669,12 @@ public class RepairGenerator {
        dispatchrules.removeAll(toremove);
         if (dispatchrules.size() == 0) {
             cr.outputline("// nothing to dispatch");
-           cr.endblock();
             return;
         }
-       
-       cr.outputline("if ("+addeditem+")");
+
+       cr.outputline("if (" + addeditem + ")");
        cr.startblock();
+       
         for(int i = 0; i < dispatchrules.size(); i++) {
             Rule rule = (Rule) dispatchrules.elementAt(i);
            if (rule.getGuardExpr().getRequiredDescriptors().contains(rd)) {
@@ -1347,86 +1690,108 @@ public class RepairGenerator {
                }
            }
         }
-       cr.endblock();
+
        cr.endblock();
     }
 
 
     public void generate_dispatch(CodeWriter cr, SetDescriptor sd, String setvar) {
-               
-        cr.outputline("// SET DISPATCH ");
-
-       cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
-       cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
-       cr.startblock(); {
-           /* Adding new item */
-           /* Perform safety checks */
-           cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
-           cr.outputline(repairtable.getSafeSymbol()+"->containsset("+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
+       cr.outputline("// SET DISPATCH ");
+       if (Compiler.REPAIR) {
+           cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
+           cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
            cr.startblock(); {
-               /* Have update to call into */
-               VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
-               String parttype="";
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
-                       parttype=parttype+", int, int";
-                   else
-                       parttype=parttype+", int";
-               }
-               cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
-               cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getset("+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
-               String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+
-                             repairtable.getSafeSymbol();
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   Quantifier q=currentrule.getQuantifier(i);
-                   if (q instanceof SetQuantifier) {
-                       SetQuantifier sq=(SetQuantifier) q;
-                       methodcall+=","+sq.getVar().getSafeSymbol();
-                   } else if (q instanceof RelationQuantifier) {
-                       RelationQuantifier rq=(RelationQuantifier) q;
-                       methodcall+=","+rq.x.getSafeSymbol();
-                       methodcall+=","+rq.y.getSafeSymbol();
-                   } else if (q instanceof ForQuantifier) {
-                       ForQuantifier fq=(ForQuantifier) q;
-                       methodcall+=","+fq.getVar().getSafeSymbol();
+               /* Adding new item */
+               /* See if there is an outstanding update in the repairtable */
+               cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
+               cr.outputline(repairtable.getSafeSymbol()+"->containsset("+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
+               cr.startblock(); {
+                   /* Have update to call into */
+                   VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
+                   String parttype="";
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
+                           parttype=parttype+", int, int";
+                       else
+                           parttype=parttype+", int";
+                   }
+                   cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
+                   cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getset("+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
+                   String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+
+                       repairtable.getSafeSymbol();
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       Quantifier q=currentrule.getQuantifier(i);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           methodcall+=","+rq.x.getSafeSymbol();
+                           methodcall+=","+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=","+fq.getVar().getSafeSymbol();
+                       }
                    }
+                   methodcall+=");";
+                   cr.outputline(methodcall);
+                   cr.outputline("delete "+newmodel.getSafeSymbol()+";");
+                   cr.outputline("goto rebuild;");
                }
-               methodcall+=");";
-               cr.outputline(methodcall);
-               cr.outputline("goto rebuild;");
-           }
-           cr.endblock();
-           /* Build standard compensation actions */
-           if (need_compensation(currentrule)) {
-               UpdateNode un=find_compensation(currentrule);
-               String name=(String)updatenames.get(un);
-               usedupdates.add(un); /* Mark as used */
-
-               String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+
-                             repairtable.getSafeSymbol();
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   Quantifier q=currentrule.getQuantifier(i);
-                   if (q instanceof SetQuantifier) {
-                       SetQuantifier sq=(SetQuantifier) q;
-                       methodcall+=","+sq.getVar().getSafeSymbol();
-                   } else if (q instanceof RelationQuantifier) {
-                       RelationQuantifier rq=(RelationQuantifier) q;
-                       methodcall+=","+rq.x.getSafeSymbol();
-                       methodcall+=","+rq.y.getSafeSymbol();
-                   } else if (q instanceof ForQuantifier) {
-                       ForQuantifier fq=(ForQuantifier) q;
-                       methodcall+=","+fq.getVar().getSafeSymbol();
+               cr.endblock();
+               /* Build standard compensation actions */
+               Vector ruleset=new Vector();
+               ruleset.add(currentrule);
+               if (state.implicitruleinv.containsKey(currentrule))
+                   ruleset.addAll((Set)state.implicitruleinv.get(currentrule));
+               for(int i=0;i<ruleset.size();i++) {
+                   Rule itrule=(Rule)ruleset.get(i);
+                   
+                   if (need_compensation(itrule)) {
+                       UpdateNode un=find_compensation(itrule);
+                       String name=(String)updatenames.get(un);
+                       usedupdates.add(un); /* Mark as used */
+                       
+                       String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+
+                           repairtable.getSafeSymbol();
+                       for(int j=0;j<currentrule.numQuantifiers();j++) {
+                           Quantifier q=currentrule.getQuantifier(j);
+                           if (q instanceof SetQuantifier) {
+                               SetQuantifier sq=(SetQuantifier) q;
+                               methodcall+=","+sq.getVar().getSafeSymbol();
+                           } else if (q instanceof RelationQuantifier) {
+                               RelationQuantifier rq=(RelationQuantifier) q;
+                               methodcall+=","+rq.x.getSafeSymbol();
+                               methodcall+=","+rq.y.getSafeSymbol();
+                           } else if (q instanceof ForQuantifier) {
+                               ForQuantifier fq=(ForQuantifier) q;
+                               methodcall+=","+fq.getVar().getSafeSymbol();
+                           }
+                       }
+                       methodcall+=");";
+                       if (currentrule!=itrule) {
+                           SetDescriptor sdrule=((SetInclusion)itrule.getInclusion()).getSet();
+                           cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
+                           cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sdrule.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
+                           cr.startblock();
+                       }
+                       cr.outputline(methodcall);
+                       cr.outputline("delete "+newmodel.getSafeSymbol()+";");
+                       cr.outputline("goto rebuild;");
+                       cr.endblock();
                    }
+                   if (currentrule==itrule)
+                       cr.endblock();
                }
-               methodcall+=");";
-               cr.outputline(methodcall);
-               cr.outputline("goto rebuild;");
            }
        }
-       cr.endblock();
 
         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
-       cr.outputline("int " + addeditem + " = 1;");
+       cr.outputline("int " + addeditem + " = 0;");
+       if (sd.getType() instanceof StructureTypeDescriptor)  {
+           cr.outputline("if (!maybe&&"+setvar+")");
+       } else
+           cr.outputline("if (!maybe)");
        cr.outputline(addeditem + " = " + sd.getSafeSymbol() + "_hash->add((int)" + setvar +  ", (int)" + setvar + ");");
        cr.startblock();
         Vector dispatchrules = getrulelist(sd);
@@ -1444,6 +1809,7 @@ public class RepairGenerator {
            cr.endblock();
             return;
         }
+       /* Add item to worklist if new */
        cr.outputline("if ("+addeditem+")");
        cr.startblock();
         for(int i = 0; i < dispatchrules.size(); i++) {
@@ -1461,7 +1827,6 @@ public class RepairGenerator {
                }
            }
        }
-
        cr.endblock();
        cr.endblock();
     }