cf2b98d22604ef4cc0a10b788470315a9e9dca97
[repair.git] / Repair / RepairCompiler / MCC / IR / RepairGenerator.java
1 package MCC.IR;
2
3 import java.io.*;
4 import java.util.*;
5 import MCC.State;
6 import MCC.Compiler;
7
8 public class RepairGenerator {
9     State state;
10     PrintWrapper outputrepair = null;
11     PrintWrapper outputaux = null;
12     PrintWrapper outputhead = null;
13     String name="foo";
14     String headername;
15     static VarDescriptor oldmodel=null;
16     static VarDescriptor newmodel=null;
17     static VarDescriptor worklist=null;
18     static VarDescriptor repairtable=null;
19     static VarDescriptor goodflag=null;
20     Rule currentrule=null;
21     Hashtable updatenames;
22     HashSet usedupdates;
23     Termination termination;
24     Set removed;
25     HashSet togenerate;
26     static boolean DEBUG=false;
27     Cost cost;
28     ModelRuleDependence mrd;
29
30     public RepairGenerator(State state, Termination t) {
31         this.state = state;
32         updatenames=new Hashtable();
33         usedupdates=new HashSet();
34         termination=t;
35         removed=t.removedset;
36         togenerate=new HashSet();
37         togenerate.addAll(termination.conjunctions);
38         if (Compiler.REPAIR)
39             togenerate.removeAll(removed);
40         GraphNode.computeclosure(togenerate,removed);
41         cost=new Cost();
42         mrd=ModelRuleDependence.doAnalysis(state);
43         Repair.repairgenerator=this;
44     }
45
46     private void generatetypechecks(boolean flag) {
47         if (flag) {
48             DotExpr.DOTYPECHECKS=true;
49             VarExpr.DOTYPECHECKS=true;
50             DotExpr.DONULL=true;
51             VarExpr.DONULL=true;
52         } else {
53             VarExpr.DOTYPECHECKS=false;
54             DotExpr.DOTYPECHECKS=false;
55             VarExpr.DONULL=true;
56             DotExpr.DONULL=true;
57         }
58     }
59
60     private void name_updates() {
61         int count=0;
62         for(Iterator it=termination.updatenodes.iterator();it.hasNext();) {
63             GraphNode gn=(GraphNode) it.next();
64             TermNode tn=(TermNode) gn.getOwner();
65             MultUpdateNode mun=tn.getUpdate();
66             if (togenerate.contains(gn))
67             for (int i=0;i<mun.numUpdates();i++) {
68                 UpdateNode un=mun.getUpdate(i);
69                 String name="update"+String.valueOf(count++);
70                 updatenames.put(un,name);
71             }
72         }
73     }
74
75     public void generate(OutputStream outputrepair, OutputStream outputaux,OutputStream outputhead, String st) {
76         this.outputrepair = new PrintWrapper(new java.io.PrintWriter(outputrepair, true));
77         this.outputaux = new PrintWrapper(new java.io.PrintWriter(outputaux, true));
78         this.outputhead = new PrintWrapper(new java.io.PrintWriter(outputhead, true));
79
80         headername=st;
81         name_updates();
82         generatetypechecks(true);
83         generate_tokentable();
84         RelationDescriptor.prefix = "thisvar->";
85         SetDescriptor.prefix = "thisvar->";
86
87         generate_hashtables();
88         generate_stateobject();
89
90
91         /* Rewrite globals */
92         CodeWriter craux = new StandardCodeWriter(this.outputaux);
93         for (Iterator it=this.state.stGlobals.descriptors();it.hasNext();) {
94             VarDescriptor vd=(VarDescriptor)it.next();
95             craux.outputline("#define "+vd.getSafeSymbol()+" thisvar->"+vd.getSafeSymbol());
96         }
97
98
99         generate_call();
100         generate_start();
101         generate_rules();
102         if (!Compiler.REPAIR||Compiler.GENERATEDEBUGPRINT) {
103             generate_print();
104         }
105         generate_checks();
106         generate_teardown();
107         CodeWriter crhead = new StandardCodeWriter(this.outputhead);
108         craux = new StandardCodeWriter(this.outputaux);
109         craux.emptyBuffer();
110         craux.endblock();
111
112         if (Compiler.GENERATEDEBUGHOOKS) {
113             crhead.outputline("void debughook();");
114             craux.outputline("void debughook() {}");
115         }
116         generatetypechecks(false);
117         generate_computesizes();
118         generatetypechecks(true);
119         generate_recomputesizes();
120         generatetypechecks(false);
121         generate_updates();
122         StructureGenerator sg=new StructureGenerator(state,this);
123         sg.buildall();
124         crhead.outputline("#endif");
125     }
126
127     String ststate="state";
128     String stmodel="model";
129     String strepairtable="repairtable";
130     String stleft="left";
131     String stright="right";
132     String stnew="newvalue";
133
134     private void generate_updates() {
135         int count=0;
136         CodeWriter crhead = new StandardCodeWriter(outputhead);
137         CodeWriter craux = new StandardCodeWriter(outputaux);
138         RelationDescriptor.prefix = "model->";
139         SetDescriptor.prefix = "model->";
140
141         /* Rewrite globals */
142
143         for (Iterator it=this.state.stGlobals.descriptors();it.hasNext();) {
144             VarDescriptor vd=(VarDescriptor)it.next();
145             craux.outputline("#undef "+vd.getSafeSymbol());
146             craux.outputline("#define "+vd.getSafeSymbol()+" "+ststate+"->"+vd.getSafeSymbol());
147         }
148
149         for(Iterator it=termination.updatenodes.iterator();it.hasNext();) {
150             GraphNode gn=(GraphNode) it.next();
151             TermNode tn=(TermNode) gn.getOwner();
152             MultUpdateNode mun=tn.getUpdate();
153             boolean isrelation=(mun.getDescriptor() instanceof RelationDescriptor);
154             if (togenerate.contains(gn))
155             for (int i=0;i<mun.numUpdates();i++) {
156                 UpdateNode un=mun.getUpdate(i);
157                 String methodname=(String)updatenames.get(un);
158
159                 switch(mun.op) {
160                 case MultUpdateNode.ADD:
161                     if (isrelation) {
162                         crhead.outputline("void "+methodname+"(struct "+name+"_state * " +ststate+",struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable+", int "+stleft+", int "+stright+");");
163                         craux.outputline("void "+methodname+"(struct "+name+"_state * "+ ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable+", int "+stleft+", int "+stright+")");
164                     } else {
165                         crhead.outputline("void "+methodname+"(struct "+name+"_state * "+ ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable+", int "+stleft+");");
166                         craux.outputline("void "+methodname+"(struct "+name+"_state * "+ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable+", int "+stleft+")");
167                     }
168                     craux.startblock();
169                     craux.startBuffer();
170                     craux.addDeclaration("int","maybe");
171                     craux.outputline("maybe=0;");
172                     if (Compiler.GENERATEINSTRUMENT)
173                         craux.outputline("updatecount++;");
174
175                     final SymbolTable st = un.getRule().getSymbolTable();
176                     CodeWriter cr = new StandardCodeWriter(outputaux) {
177                         public SymbolTable getSymbolTable() { return st; }
178                     };
179                     un.generate(cr, false, false, stleft,stright, null,this);
180                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
181                     craux.emptyBuffer();
182                     craux.endblock();
183                     break;
184                 case MultUpdateNode.REMOVE: {
185                     Rule r=un.getRule();
186                     String methodcall="void "+methodname+"(struct "+name+"_state * "+ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable;
187                     for(int j=0;j<r.numQuantifiers();j++) {
188                         Quantifier q=r.getQuantifier(j);
189                         if (q instanceof SetQuantifier) {
190                             SetQuantifier sq=(SetQuantifier) q;
191                             methodcall+=","+sq.getVar().getType().getGenerateType().getSafeSymbol()+" "+sq.getVar().getSafeSymbol();
192                         } else if (q instanceof RelationQuantifier) {
193                             RelationQuantifier rq=(RelationQuantifier) q;
194
195                             methodcall+=","+rq.x.getType().getGenerateType().getSafeSymbol()+" "+rq.x.getSafeSymbol();
196                             methodcall+=","+rq.y.getType().getGenerateType().getSafeSymbol()+" "+rq.y.getSafeSymbol();
197                         } else if (q instanceof ForQuantifier) {
198                             ForQuantifier fq=(ForQuantifier) q;
199                             methodcall+=",int "+fq.getVar().getSafeSymbol();
200                         }
201                     }
202                     methodcall+=")";
203                     crhead.outputline(methodcall+";");
204                     craux.outputline(methodcall);
205                     craux.startblock();
206                     craux.startBuffer();
207                     craux.addDeclaration("int","maybe");
208                     craux.outputline("maybe=0;");
209                     if (Compiler.GENERATEINSTRUMENT)
210                         craux.outputline("updatecount++;");
211                     final SymbolTable st2 = un.getRule().getSymbolTable();
212                     CodeWriter cr2 = new StandardCodeWriter(outputaux) {
213                         public SymbolTable getSymbolTable() { return st2; }
214                     };
215                     un.generate(cr2, true, false, null,null, null,this);
216                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
217                     craux.emptyBuffer();
218                     craux.endblock();
219                 }
220                     break;
221                 case MultUpdateNode.MODIFY: {
222                     Rule r=un.getRule();
223                     String methodcall="void "+methodname+"(struct "+name+"_state * "+ststate+", struct "+name+" * "+stmodel+", struct RepairHash * "+strepairtable;
224                     for(int j=0;j<r.numQuantifiers();j++) {
225                         Quantifier q=r.getQuantifier(j);
226                         if (q instanceof SetQuantifier) {
227                             SetQuantifier sq=(SetQuantifier) q;
228                             methodcall+=","+sq.getVar().getType().getGenerateType().getSafeSymbol()+" "+sq.getVar().getSafeSymbol();
229                         } else if (q instanceof RelationQuantifier) {
230                             RelationQuantifier rq=(RelationQuantifier) q;
231
232                             methodcall+=", "+rq.x.getType().getGenerateType().getSafeSymbol()+" "+rq.x.getSafeSymbol();
233                             methodcall+=", "+rq.y.getType().getGenerateType().getSafeSymbol()+" "+rq.y.getSafeSymbol();
234                         } else if (q instanceof ForQuantifier) {
235                             ForQuantifier fq=(ForQuantifier) q;
236                             methodcall+=", int "+fq.getVar().getSafeSymbol();
237                         }
238                     }
239                     methodcall+=", int "+stleft+", int "+stright+", int "+stnew;
240                     methodcall+=")";
241                     crhead.outputline(methodcall+";");
242                     craux.outputline(methodcall);
243                     craux.startblock();
244                     craux.startBuffer();
245                     craux.outputline("int maybe=0;");
246                     if (Compiler.GENERATEINSTRUMENT)
247                         craux.outputline("updatecount++;");
248                     final SymbolTable st2 = un.getRule().getSymbolTable();
249                     CodeWriter cr2 = new StandardCodeWriter(outputaux) {
250                         public SymbolTable getSymbolTable() { return st2; }
251                     };
252                     un.generate(cr2, false, true, stleft, stright, stnew, this);
253                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
254                     craux.emptyBuffer();
255                     craux.endblock();
256                 }
257                     break;
258
259                 default:
260                     throw new Error("Nonimplement Update");
261                 }
262             }
263         }
264     }
265
266     private void generate_call() {
267         CodeWriter cr = new StandardCodeWriter(outputrepair);
268         VarDescriptor vdstate=VarDescriptor.makeNew("repairstate");
269         cr.addDeclaration("struct "+ name+"_state *", vdstate.getSafeSymbol());
270         cr.outputline(vdstate.getSafeSymbol()+"=allocate"+name+"_state();");
271         Iterator globals=state.stGlobals.descriptors();
272         while (globals.hasNext()) {
273             VarDescriptor vd=(VarDescriptor) globals.next();
274             cr.outputline(vdstate.getSafeSymbol()+"->"+vd.getSafeSymbol()+"=("+vd.getType().getGenerateType().getSafeSymbol()+")"+vd.getSafeSymbol()+";");
275         }
276         /* Insert repair here */
277         cr.outputline("doanalysis("+vdstate.getSafeSymbol()+");");
278         globals=state.stGlobals.descriptors();
279         while (globals.hasNext()) {
280             VarDescriptor vd=(VarDescriptor) globals.next();
281             cr.outputline("*(("+vd.getType().getGenerateType().getSafeSymbol()+"*) &"+vd.getSafeSymbol()+")="+vdstate.getSafeSymbol()+"->"+vd.getSafeSymbol()+";");
282         }
283         cr.outputline("free"+name+"_state("+vdstate.getSafeSymbol()+");");
284     }
285
286     private void generate_tokentable() {
287         CodeWriter cr = new StandardCodeWriter(outputrepair);
288         Iterator tokens = TokenLiteralExpr.tokens.keySet().iterator();
289
290         cr.outputline("");
291         cr.outputline("/* Token values*/");
292         cr.outputline("");
293
294         while (tokens.hasNext()) {
295             Object token = tokens.next();
296             cr.outputline("/* " + token.toString() + " = " + TokenLiteralExpr.tokens.get(token).toString()+"*/");
297         }
298
299         cr.outputline("");
300         cr.outputline("");
301     }
302
303     private void generate_stateobject() {
304         CodeWriter crhead = new StandardCodeWriter(outputhead);
305         CodeWriter craux = new StandardCodeWriter(outputaux);
306         crhead.outputline("struct "+name+"_state {");
307         Iterator globals=state.stGlobals.descriptors();
308         while (globals.hasNext()) {
309             VarDescriptor vd=(VarDescriptor) globals.next();
310             crhead.outputline(vd.getType().getGenerateType().getSafeSymbol()+" "+vd.getSafeSymbol()+";");
311         }
312         crhead.outputline("};");
313         crhead.outputline("struct "+name+"_state * allocate"+name+"_state();");
314         craux.outputline("struct "+name+"_state * allocate"+name+"_state()");
315         craux.startblock();
316         craux.outputline("return (struct "+name+"_state *) malloc(sizeof(struct "+name+"_state));");
317         craux.endblock();
318
319         crhead.outputline("void free"+name+"_state(struct "+name+"_state *);");
320         craux.outputline("void free"+name+"_state(struct "+name+"_state * thisvar)");
321         craux.startblock();
322         craux.outputline("free(thisvar);");
323         craux.endblock();
324
325         crhead.outputline("void "+name+"_statecomputesizes(struct "+name+"_state * ,int *,int **);");
326         crhead.outputline("void "+name+"_staterecomputesizes(struct "+name+"_state *);");
327     }
328
329     private void generate_computesizes() {
330         int max=TypeDescriptor.counter;
331         TypeDescriptor[] tdarray=new TypeDescriptor[max];
332         for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
333             TypeDescriptor ttd=(TypeDescriptor)it.next();
334             tdarray[ttd.getId()]=ttd;
335         }
336         final SymbolTable st = state.stGlobals;
337         CodeWriter cr = new StandardCodeWriter(outputaux) {
338                 public SymbolTable getSymbolTable() { return st; }
339             };
340
341         cr.outputline("void "+name+"_statecomputesizes(struct "+name+"_state * thisvar,int *sizearray,int **numele)");
342         cr.startblock();
343         cr.startBuffer();
344         cr.addDeclaration("int","maybe");
345         cr.outputline("maybe=0;");
346         for(int i=0;i<max;i++) {
347             TypeDescriptor td=tdarray[i];
348             Expr size=td.getSizeExpr();
349             VarDescriptor vd=VarDescriptor.makeNew("size");
350             size.generate(cr,vd);
351             cr.outputline("sizearray["+i+"]="+vd.getSafeSymbol()+";");
352         }
353         for(int i=0;i<max;i++) {
354             TypeDescriptor td=tdarray[i];
355             if (td instanceof StructureTypeDescriptor) {
356                 StructureTypeDescriptor std=(StructureTypeDescriptor) td;
357                 for(int j=0;j<std.fieldlist.size();j++) {
358                     FieldDescriptor fd=(FieldDescriptor)std.fieldlist.get(j);
359                     if (fd instanceof ArrayDescriptor) {
360                         ArrayDescriptor ad=(ArrayDescriptor)fd;
361                         Expr index=ad.getIndexBound();
362                         VarDescriptor vd=VarDescriptor.makeNew("index");
363                         index.generate(cr,vd);
364                         cr.outputline("numele["+i+"]["+j+"]="+vd.getSafeSymbol()+";");
365                     }
366                 }
367             }
368         }
369         cr.outputline("if (maybe) printf(\"BAD ERROR\");");
370         cr.emptyBuffer();
371         cr.endblock();
372     }
373
374     private void generate_recomputesizes() {
375         int max=TypeDescriptor.counter;
376         TypeDescriptor[] tdarray=new TypeDescriptor[max];
377         for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
378             TypeDescriptor ttd=(TypeDescriptor)it.next();
379             tdarray[ttd.getId()]=ttd;
380         }
381         final SymbolTable st = state.stGlobals;
382         CodeWriter cr = new StandardCodeWriter(outputaux) {
383                 public SymbolTable getSymbolTable() { return st; }
384             };
385         cr.outputline("void "+name+"_staterecomputesizes(struct "+name+"_state * thisvar)");
386         cr.startblock();
387         cr.startBuffer();
388         cr.addDeclaration("int","maybe");
389         cr.outputline("maybe=0;");
390         for(int i=0;i<max;i++) {
391             TypeDescriptor td=tdarray[i];
392             Expr size=td.getSizeExpr();
393             VarDescriptor vd=VarDescriptor.makeNew("size");
394             size.generate(cr,vd);
395         }
396         for(int i=0;i<max;i++) {
397             TypeDescriptor td=tdarray[i];
398             if (td instanceof StructureTypeDescriptor) {
399                 StructureTypeDescriptor std=(StructureTypeDescriptor) td;
400                 for(int j=0;j<std.fieldlist.size();j++) {
401                     FieldDescriptor fd=(FieldDescriptor)std.fieldlist.get(j);
402                     if (fd instanceof ArrayDescriptor) {
403                         ArrayDescriptor ad=(ArrayDescriptor)fd;
404                         Expr index=ad.getIndexBound();
405                         VarDescriptor vd=VarDescriptor.makeNew("index");
406                         index.generate(cr,vd);
407                     }
408                 }
409             }
410         }
411         cr.outputline("if (maybe) printf(\"BAD ERROR\");");
412         cr.emptyBuffer();
413         cr.endblock();
414     }
415
416
417     private void generate_hashtables() {
418         CodeWriter craux = new StandardCodeWriter(outputaux);
419         CodeWriter crhead = new StandardCodeWriter(outputhead);
420         crhead.outputline("#ifndef "+name+"_h");
421         crhead.outputline("#define "+name+"_h");
422         crhead.outputline("#include \"SimpleHash.h\"");
423         crhead.outputline("#include \"instrument.h\"");
424         crhead.outputline("#include <stdio.h>");
425         crhead.outputline("#include <stdlib.h>");
426         crhead.outputline("struct "+name+" * allocate"+name+"();");
427         crhead.outputline("void free"+name+"(struct "+name+" *);");
428         crhead.outputline("struct "+name+" {");
429         craux.outputline("#include \""+headername+"\"");
430         craux.outputline("#include \"size.h\"");
431         if (Compiler.TIME) {
432             craux.outputline("#include <sys/time.h>");
433         }
434         if (Compiler.ALLOCATECPLUSPLUS) {
435             for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
436                 TypeDescriptor td=(TypeDescriptor)it.next();
437                 if (td instanceof StructureTypeDescriptor) {
438                     if (((StructureTypeDescriptor)td).size()>0) {
439                         FieldDescriptor fd=((StructureTypeDescriptor)td).get(0);
440                         if (fd.getSymbol().startsWith("_vptr_")) {
441                             String vtable="_ZTV";
442                             vtable+=td.getSymbol().length();
443                             vtable+=td.getSymbol();
444                             craux.outputline("extern void * "+vtable+";");
445                         }
446                     }
447                 }
448             }
449         }
450         craux.outputline("struct "+ name+"* allocate"+name+"()");
451         craux.startblock();
452         craux.outputline("/* creating hashtables */");
453
454         /* build sets */
455         Iterator sets = state.stSets.descriptors();
456         craux.addDeclaration("struct "+name+"*", "thisvar");
457         craux.outputline("thisvar=(struct "+name+"*) malloc(sizeof(struct "+name+"));");
458
459         /* first pass create all the hash tables */
460         while (sets.hasNext()) {
461             SetDescriptor set = (SetDescriptor) sets.next();
462             crhead.outputline("struct SimpleHash* " + set.getJustSafeSymbol() + "_hash;");
463             craux.outputline(set.getSafeSymbol() + "_hash = noargallocateSimpleHash();");
464         }
465
466         /* second pass build relationships between hashtables */
467         sets = state.stSets.descriptors();
468
469         while (sets.hasNext()) {
470             SetDescriptor set = (SetDescriptor) sets.next();
471             Iterator subsets = set.subsets();
472
473             while (subsets.hasNext()) {
474                 SetDescriptor subset = (SetDescriptor) subsets.next();
475                 craux.outputline("SimpleHashaddParent("+subset.getSafeSymbol() +"_hash ,"+ set.getSafeSymbol() + "_hash);");
476             }
477         }
478
479         /* build relations */
480         Iterator relations = state.stRelations.descriptors();
481
482         /* first pass create all the hash tables */
483         while (relations.hasNext()) {
484             RelationDescriptor relation = (RelationDescriptor) relations.next();
485
486             if (relation.testUsage(RelationDescriptor.IMAGE)) {
487                 crhead.outputline("struct SimpleHash* " + relation.getJustSafeSymbol() + "_hash;");
488                 craux.outputline(relation.getSafeSymbol() + "_hash = noargallocateSimpleHash();");
489             }
490
491             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
492                 crhead.outputline("struct SimpleHash* " + relation.getJustSafeSymbol() + "_hashinv;");
493                 craux.outputline(relation.getSafeSymbol() + "_hashinv = noargallocateSimpleHash();");
494             }
495         }
496         craux.outputline("return thisvar;");
497         craux.endblock();
498         crhead.outputline("};");
499         craux.outputline("void free"+name+"(struct "+ name +"* thisvar)");
500         craux.startblock();
501         craux.outputline("/* deleting hashtables */");
502
503         /* build destructor */
504         sets = state.stSets.descriptors();
505
506         /* first pass create all the hash tables */
507         while (sets.hasNext()) {
508             SetDescriptor set = (SetDescriptor) sets.next();
509             craux.outputline("freeSimpleHash("+set.getSafeSymbol() + "_hash);");
510         }
511
512         /* destroy relations */
513         relations = state.stRelations.descriptors();
514
515         /* first pass create all the hash tables */
516         while (relations.hasNext()) {
517             RelationDescriptor relation = (RelationDescriptor) relations.next();
518
519             if (relation.testUsage(RelationDescriptor.IMAGE)) {
520                 craux.outputline("freeSimpleHash("+relation.getSafeSymbol() + "_hash);");
521             }
522
523             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
524                 craux.outputline("freeSimpleHash(" + relation.getSafeSymbol() + "_hashinv);");
525             }
526         }
527         craux.outputline("free(thisvar);");
528         craux.endblock();
529     }
530
531     private void generate_start() {
532         CodeWriter crhead = new StandardCodeWriter(outputhead);
533         CodeWriter craux = new StandardCodeWriter(outputaux);
534         oldmodel=VarDescriptor.makeNew("oldmodel");
535         newmodel=VarDescriptor.makeNew("newmodel");
536         worklist=VarDescriptor.makeNew("worklist");
537         goodflag=VarDescriptor.makeNew("goodflag");
538         repairtable=VarDescriptor.makeNew("repairtable");
539
540         if (Compiler.GENERATEINSTRUMENT) {
541             craux.outputline("int updatecount;");
542             craux.outputline("int rebuildcount;");
543             craux.outputline("int abstractcount;");
544         }
545
546         crhead.outputline("void doanalysis(struct "+name+"_state *);");
547         craux.outputline("void doanalysis(struct "+name+"_state * thisvar)");
548         craux.startblock();
549         craux.outputline("int highmark;"); /* This declaration is special...need it to be first */
550         craux.startBuffer();
551
552         if (Compiler.TIME) {
553             craux.outputline("struct timeval _begin_time,_end_time;");
554             craux.outputline("gettimeofday(&_begin_time,NULL);");
555         }
556         if (Compiler.GENERATEINSTRUMENT) {
557             craux.outputline("updatecount=0;");
558             craux.outputline("rebuildcount=0;");
559             craux.outputline("abstractcount=0;");
560         }
561
562
563         craux.addDeclaration("struct "+name+ " * ",oldmodel.getSafeSymbol());
564         craux.outputline(oldmodel.getSafeSymbol()+"=0;");
565         craux.addDeclaration("struct WorkList * ",worklist.getSafeSymbol());
566         craux.outputline(worklist.getSafeSymbol()+" = allocateWorkList();");
567         craux.addDeclaration("struct RepairHash * ",repairtable.getSafeSymbol());
568         craux.outputline(repairtable.getSafeSymbol()+"=0;");
569         craux.outputline("initializestack(&highmark);");
570         craux.outputline("computesizes(thisvar);");
571         craux.outputline(name+"_staterecomputesizes(thisvar);");
572         craux.outputline("while (1)");
573         craux.startblock();
574         craux.addDeclaration("struct "+name+ " * ",newmodel.getSafeSymbol());
575         craux.outputline(newmodel.getSafeSymbol()+"=allocate"+name+"();");
576         craux.outputline("WorkListreset("+worklist.getSafeSymbol()+");");
577         if (Compiler.GENERATEINSTRUMENT)
578             craux.outputline("rebuildcount++;");
579     }
580
581     private void generate_teardown() {
582         CodeWriter cr = new StandardCodeWriter(outputaux);
583         cr.endblock();
584         if (Compiler.TIME) {
585             cr.outputline("gettimeofday(&_end_time,NULL);");
586             cr.outputline("printf(\"time=%ld uS\\n\",(_end_time.tv_sec-_begin_time.tv_sec)*1000000+_end_time.tv_usec-_begin_time.tv_usec);");
587         }
588
589         if (Compiler.GENERATEINSTRUMENT) {
590             cr.outputline("printf(\"updatecount=%d\\n\",updatecount);");
591             cr.outputline("printf(\"rebuildcount=%d\\n\",rebuildcount);");
592             cr.outputline("printf(\"abstractcount=%d\\n\",abstractcount);");
593         }
594
595     }
596
597     private void generate_print() {
598
599         final SymbolTable st = new SymbolTable();
600
601         CodeWriter cr = new StandardCodeWriter(outputaux) {
602                 public SymbolTable getSymbolTable() { return st; }
603             };
604
605         cr.outputline("/* printing sets!*/");
606         cr.outputline("printf(\"\\n\\nPRINTING SETS AND RELATIONS\\n\");");
607
608         Iterator setiterator = state.stSets.descriptors();
609         while (setiterator.hasNext()) {
610             SetDescriptor sd = (SetDescriptor) setiterator.next();
611             if (sd.getSymbol().equals("int") || sd.getSymbol().equals("token")) {
612                 continue;
613             }
614
615             String setname = sd.getSafeSymbol();
616
617             cr.startblock();
618             cr.outputline("/* printing set " + setname+"*/");
619             cr.outputline("printf(\"\\nPrinting set " + sd.getSymbol() + " - %d elements \\n\", SimpleHashcountset("+setname+"_hash));");
620             cr.addDeclaration("struct SimpleIterator","__setiterator");
621             cr.outputline("SimpleHashiterator("+setname+"_hash,&__setiterator);");
622             cr.outputline("while (hasNext(&__setiterator))");
623             cr.startblock();
624             cr.addDeclaration("int","__setval");
625             cr.outputline("__setval = (int) next(&__setiterator);");
626
627             TypeDescriptor td = sd.getType();
628             if (td instanceof StructureTypeDescriptor) {
629                 StructureTypeDescriptor std = (StructureTypeDescriptor) td;
630                 VarDescriptor vd = new VarDescriptor ("__setval", "__setval", td, false);
631                 std.generate_printout(cr, vd);
632             } else { // Missing type descriptor or reserved type, just print int
633                 cr.outputline("printf(\"<%d> \", __setval);");
634             }
635
636
637             cr.endblock();
638             cr.endblock();
639         }
640
641         cr.outputline("printf(\"\\n\\n------------------- END PRINTING\\n\");");
642     }
643
644     Set ruleset=null;
645     private void generate_rules() {
646         /* first we must sort the rules */
647         RelationDescriptor.prefix = newmodel.getSafeSymbol()+"->";
648         SetDescriptor.prefix = newmodel.getSafeSymbol()+"->";
649         System.out.println("SCC="+(mrd.numSCC()-1));
650         for(int sccindex=0;sccindex<mrd.numSCC();sccindex++) {
651             ruleset=mrd.getSCC(sccindex);
652             boolean needworklist=mrd.hasCycle(sccindex);
653
654             if (!needworklist) {
655                 Iterator iterator_rs = ruleset.iterator();
656                 while (iterator_rs.hasNext()) {
657                     Rule rule = (Rule) iterator_rs.next();
658                     if (rule.getnogenerate())
659                         continue;
660                     {
661                         final SymbolTable st = rule.getSymbolTable();
662                         CodeWriter cr = new StandardCodeWriter(outputaux) {
663                                 public SymbolTable getSymbolTable() { return st; }
664                             };
665                         InvariantValue ivalue=new InvariantValue();
666                         cr.setInvariantValue(ivalue);
667
668                         cr.outputline("/* build " +escape(rule.toString())+"*/");
669                         cr.startblock();
670                         cr.addDeclaration("int","maybe");
671                         cr.outputline("maybe=0;");
672
673                         Expr ruleexpr=rule.getGuardExpr();
674                         HashSet invariantvars=new HashSet();
675                         Set invariants=ruleexpr.findInvariants(invariantvars);
676
677                         if ((ruleexpr instanceof BooleanLiteralExpr)&&
678                             ((BooleanLiteralExpr)ruleexpr).getValue()) {
679                             if (rule.getInclusion() instanceof SetInclusion) {
680                                 invariants.addAll(((SetInclusion)rule.getInclusion()).getExpr().findInvariants(invariantvars));
681                             } else if (rule.getInclusion() instanceof RelationInclusion) {
682                                 invariants.addAll(((RelationInclusion)rule.getInclusion()).getLeftExpr().findInvariants(invariantvars));
683                                 invariants.addAll(((RelationInclusion)rule.getInclusion()).getRightExpr().findInvariants(invariantvars));
684                             }
685                         }
686                         ListIterator quantifiers = rule.quantifiers();
687                         while (quantifiers.hasNext()) {
688                             Quantifier quantifier = (Quantifier) quantifiers.next();
689                             if (quantifier instanceof ForQuantifier) {
690                                 ForQuantifier fq=(ForQuantifier)quantifier;
691                                 invariants.addAll(fq.lower.findInvariants(invariantvars));
692                                 invariants.addAll(fq.upper.findInvariants(invariantvars));
693                             }
694                         }
695
696                         int openparencount=0;
697                         for(Iterator invit=invariants.iterator();invit.hasNext();) {
698                             Expr invexpr=(Expr)invit.next();
699                             VarDescriptor tmpvd=VarDescriptor.makeNew("tmpvar");
700                             VarDescriptor maybevd=VarDescriptor.makeNew("maybevar");
701                             invexpr.generate(cr,tmpvd);
702                             cr.addDeclaration("int ",maybevd.getSafeSymbol());
703                             cr.outputline(maybevd.getSafeSymbol()+"=maybe;");
704                             cr.outputline("maybe=0;");
705                             ivalue.assignPair(invexpr,tmpvd,maybevd);
706                             openparencount++;
707                             cr.startblock();
708                         }
709                         quantifiers = rule.quantifiers();
710                         while (quantifiers.hasNext()) {
711                             Quantifier quantifier = (Quantifier) quantifiers.next();
712                             quantifier.generate_open(cr);
713                         }
714
715                         /* pretty print! */
716                         cr.output("/*");
717                         rule.getGuardExpr().prettyPrint(cr);
718                         cr.outputline("*/");
719
720                         /* now we have to generate the guard test */
721                         VarDescriptor guardval = VarDescriptor.makeNew();
722                         rule.getGuardExpr().generate(cr, guardval);
723                         cr.outputline("if (" + guardval.getSafeSymbol() + ")");
724                         cr.startblock();
725
726                         /* now we have to generate the inclusion code */
727                         currentrule=rule;
728                         rule.getInclusion().generate(cr);
729                         cr.endblock();
730                         while (quantifiers.hasPrevious()) {
731                             Quantifier quantifier = (Quantifier) quantifiers.previous();
732                             cr.endblock();
733                         }
734                         cr.endblock();
735                         while((openparencount--)>0)
736                             cr.endblock();
737                         cr.outputline("");
738                         cr.outputline("");
739                     }
740                 }
741             } else {
742                 CodeWriter cr2 = new StandardCodeWriter(outputaux);
743
744                 for(Iterator initialworklist=ruleset.iterator();initialworklist.hasNext();) {
745                     /** Construct initial worklist set */
746                     Rule rule=(Rule)initialworklist.next();
747                     cr2.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+",-1,0,0);");
748                 }
749
750                 cr2.outputline("while (WorkListhasMoreElements("+worklist.getSafeSymbol()+"))");
751                 cr2.startblock();
752                 VarDescriptor idvar=VarDescriptor.makeNew("id");
753                 cr2.addDeclaration("int ",idvar.getSafeSymbol());
754                 cr2.outputline(idvar.getSafeSymbol()+"=WorkListgetid("+worklist.getSafeSymbol()+");");
755
756                 String elseladder = "if";
757
758                 Iterator iterator_rules = ruleset.iterator();
759                 while (iterator_rules.hasNext()) {
760
761                     Rule rule = (Rule) iterator_rules.next();
762                     int dispatchid = rule.getNum();
763
764                     {
765                         final SymbolTable st = rule.getSymbolTable();
766                         CodeWriter cr = new StandardCodeWriter(outputaux) {
767                                 public SymbolTable getSymbolTable() { return st; }
768                             };
769
770                         cr.indent();
771                         cr.outputline(elseladder + " ("+idvar.getSafeSymbol()+" == " + dispatchid + ")");
772                         cr.startblock();
773                         cr.addDeclaration("int","maybe");
774                         cr.outputline("maybe=0;");
775                         VarDescriptor typevar=VarDescriptor.makeNew("type");
776                         VarDescriptor leftvar=VarDescriptor.makeNew("left");
777                         VarDescriptor rightvar=VarDescriptor.makeNew("right");
778                         cr.addDeclaration("int",typevar.getSafeSymbol());
779                         cr.outputline(typevar.getSafeSymbol()+"= WorkListgettype("+worklist.getSafeSymbol()+");");
780                         cr.addDeclaration("int",leftvar.getSafeSymbol());
781                         cr.outputline(leftvar.getSafeSymbol()+"= WorkListgetlvalue("+worklist.getSafeSymbol()+");");
782                         cr.addDeclaration("int",rightvar.getSafeSymbol());
783                         cr.outputline(rightvar.getSafeSymbol()+"= WorkListgetrvalue("+worklist.getSafeSymbol()+");");
784                         cr.outputline("/* build " +escape(rule.toString())+"*/");
785
786
787                         for (int j=0;j<rule.numQuantifiers();j++) {
788                             Quantifier quantifier = rule.getQuantifier(j);
789                             quantifier.generate_open(cr, typevar.getSafeSymbol(),j,leftvar.getSafeSymbol(),rightvar.getSafeSymbol());
790                         }
791
792                         /* pretty print! */
793                         cr.output("/*");
794
795                         rule.getGuardExpr().prettyPrint(cr);
796                         cr.outputline("*/");
797
798                         /* now we have to generate the guard test */
799
800                         VarDescriptor guardval = VarDescriptor.makeNew();
801                         rule.getGuardExpr().generate(cr, guardval);
802
803                         cr.outputline("if (" + guardval.getSafeSymbol() + ")");
804                         cr.startblock();
805
806                         /* now we have to generate the inclusion code */
807                         currentrule=rule;
808                         rule.getInclusion().generate(cr);
809                         cr.endblock();
810
811                         for (int j=0;j<rule.numQuantifiers();j++) {
812                             cr.endblock();
813                         }
814
815                         // close startblocks generated by DotExpr memory checks
816                         //DotExpr.generate_memory_endblocks(cr);
817
818                         cr.endblock(); // end else-if WORKLIST ladder
819
820                         elseladder = "else if";
821                     }
822                 }
823                 cr2.outputline("else");
824                 cr2.startblock();
825                 cr2.outputline("printf(\"VERY BAD !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\\n\");");
826                 cr2.outputline("exit(1);");
827                 cr2.endblock();
828                 // end block created for worklist
829                 cr2.outputline("WorkListpop("+worklist.getSafeSymbol()+");");
830                 cr2.endblock();
831             }
832         }
833     }
834
835     public static String escape(String s) {
836         String newstring="";
837         for(int i=0;i<s.length();i++) {
838             char c=s.charAt(i);
839             if (c=='"')
840                 newstring+="\"";
841             else
842                 newstring+=c;
843         }
844         return newstring;
845     }
846
847     private void generate_checks() {
848         /* do constraint checks */
849         Iterator i;
850         if (Compiler.REPAIR)
851             i=termination.constraintdependence.computeOrdering().iterator();
852         else
853             i=state.vConstraints.iterator();
854         for (; i.hasNext();) {
855             Constraint constraint;
856             if (Compiler.REPAIR)
857                 constraint= (Constraint) ((GraphNode)i.next()).getOwner();
858             else
859                 constraint=(Constraint)i.next();
860
861             {
862                 final SymbolTable st = constraint.getSymbolTable();
863                 CodeWriter cr = new StandardCodeWriter(outputaux);
864                 cr.pushSymbolTable(constraint.getSymbolTable());
865
866                 cr.outputline("/* checking " + escape(constraint.toString())+"*/");
867                 cr.startblock();
868
869                 ListIterator quantifiers = constraint.quantifiers();
870
871                 while (quantifiers.hasNext()) {
872                     Quantifier quantifier = (Quantifier) quantifiers.next();
873                     quantifier.generate_open(cr);
874                 }
875
876                 cr.addDeclaration("int","maybe");
877                 cr.outputline("maybe = 0;");
878
879                 /* now we have to generate the guard test */
880
881                 VarDescriptor constraintboolean = VarDescriptor.makeNew("constraintboolean");
882                 constraint.getLogicStatement().generate(cr, constraintboolean);
883
884                 cr.outputline("if (maybe)");
885                 cr.startblock();
886                 cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \\n\");");
887                 //cr.outputline("exit(1);");
888                 cr.endblock();
889
890                 cr.outputline("else if (!" + constraintboolean.getSafeSymbol() + ")");
891                 cr.startblock();
892                 if (!Compiler.REPAIR||Compiler.GENERATEDEBUGHOOKS)
893                     cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \\n\");");
894
895                 if (Compiler.REPAIR) {
896                 /* Do repairs */
897                 /* Build new repair table */
898
899                 cr.outputline("if ("+repairtable.getSafeSymbol()+")");
900                 cr.outputline("freeRepairHash("+repairtable.getSafeSymbol()+");");
901                 cr.outputline(repairtable.getSafeSymbol()+"=noargallocateRepairHash();");
902
903                 if (Compiler.GENERATEDEBUGHOOKS)
904                     cr.outputline("debughook();");
905                 /* Compute cost of each repair */
906                 VarDescriptor mincost=VarDescriptor.makeNew("mincost");
907                 VarDescriptor mincostindex=VarDescriptor.makeNew("mincostindex");
908                 Vector dnfconst=new Vector();
909                 dnfconst.addAll((Set)termination.conjunctionmap.get(constraint));
910
911                 if (dnfconst.size()<=1) {
912                     cr.addDeclaration("int",mincostindex.getSafeSymbol());
913                     cr.outputline(mincostindex.getSafeSymbol()+"=0;");
914                 }
915                 if (dnfconst.size()>1) {
916                     cr.addDeclaration("int",mincostindex.getSafeSymbol());
917                     boolean first=true;
918                     for(int j=0;j<dnfconst.size();j++) {
919                         GraphNode gn=(GraphNode)dnfconst.get(j);
920                         Conjunction conj=((TermNode)gn.getOwner()).getConjunction();
921                         if (removed.contains(gn))
922                             continue;
923
924                         VarDescriptor costvar;
925                         if (first) {
926                             costvar=mincost;
927                         } else
928                             costvar=VarDescriptor.makeNew("cost");
929                         for(int k=0;k<conj.size();k++) {
930                             DNFPredicate dpred=conj.get(k);
931                             Predicate p=dpred.getPredicate();
932                             boolean negate=dpred.isNegated();
933                             VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
934                             p.generate(cr,predvalue);
935                             if (k==0) {
936                                 cr.addDeclaration("int",costvar.getSafeSymbol());
937                                 cr.outputline(costvar.getSafeSymbol()+"=0;");
938                             }
939                             if (negate)
940                                 cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
941                             else
942                                 cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
943                             cr.outputline(costvar.getSafeSymbol()+"+="+cost.getCost(dpred)+";");
944                         }
945
946                         if(!first) {
947                             cr.outputline("if ("+costvar.getSafeSymbol()+"<"+mincost.getSafeSymbol()+")");
948                             cr.startblock();
949                             cr.outputline(mincost.getSafeSymbol()+"="+costvar.getSafeSymbol()+";");
950                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
951                             cr.endblock();
952                         } else
953                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
954                         first=false;
955                     }
956                 }
957                 cr.outputline("switch("+mincostindex.getSafeSymbol()+")");
958                 cr.startblock();
959                 for(int j=0;j<dnfconst.size();j++) {
960                     GraphNode gn=(GraphNode)dnfconst.get(j);
961                     Conjunction conj=((TermNode)gn.getOwner()).getConjunction();
962                     if (removed.contains(gn))
963                         continue;
964                     cr.outputline("case "+j+":");
965                     cr.startblock();
966                     for(int k=0;k<conj.size();k++) {
967                         DNFPredicate dpred=conj.get(k);
968                         Predicate p=dpred.getPredicate();
969                         boolean negate=dpred.isNegated();
970                         VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
971                         p.generate(cr,predvalue);
972                         if (negate)
973                             cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
974                         else
975                             cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
976                         cr.startblock();
977                         if (Compiler.GENERATEINSTRUMENT)
978                             cr.outputline("abstractcount++;");
979                         if (p instanceof InclusionPredicate)
980                             generateinclusionrepair(conj,dpred, cr);
981                         else if (p instanceof ExprPredicate) {
982                             ExprPredicate ep=(ExprPredicate)p;
983                             if (ep.getType()==ExprPredicate.SIZE)
984                                 generatesizerepair(conj,dpred,cr);
985                             else if (ep.getType()==ExprPredicate.COMPARISON)
986                                 generatecomparisonrepair(conj,dpred,cr);
987                         } else throw new Error("Unrecognized Predicate");
988                         cr.endblock();
989                     }
990                     /* Update model */
991                     cr.endblock();
992                     cr.outputline("break;");
993                 }
994                 cr.endblock();
995
996                 cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
997                 cr.outputline("free"+name+"("+oldmodel.getSafeSymbol()+");");
998                 cr.outputline(oldmodel.getSafeSymbol()+"="+newmodel.getSafeSymbol()+";");
999                 cr.outputline("goto rebuild;");  /* Rebuild model and all */
1000                 }
1001                 cr.endblock();
1002
1003                 while (quantifiers.hasPrevious()) {
1004                     Quantifier quantifier = (Quantifier) quantifiers.previous();
1005                     cr.endblock();
1006                 }
1007                 cr.endblock();
1008                 cr.outputline("");
1009                 cr.outputline("");
1010             }
1011         }
1012         CodeWriter cr = new StandardCodeWriter(outputaux);
1013         cr.startblock();
1014         cr.outputline("if ("+repairtable.getSafeSymbol()+")");
1015         cr.outputline("freeRepairHash("+repairtable.getSafeSymbol()+");");
1016         cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
1017         cr.outputline("free"+name+"("+oldmodel.getSafeSymbol()+");");
1018         cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1019         cr.outputline("freeWorkList("+worklist.getSafeSymbol()+");");
1020         cr.outputline("resettypemap();");
1021         cr.outputline("break;");
1022         cr.endblock();
1023         cr.outputline("rebuild:");
1024         cr.outputline(";");
1025     }
1026
1027     private MultUpdateNode getmultupdatenode(Conjunction conj, DNFPredicate dpred, int repairtype) {
1028         Set nodes=getmultupdatenodeset(conj,dpred,repairtype);
1029         Iterator it=nodes.iterator();
1030         if (it.hasNext())
1031             return (MultUpdateNode)it.next();
1032         else
1033             return null;
1034     }
1035
1036     private Set getmultupdatenodeset(Conjunction conj, DNFPredicate dpred, int repairtype) {
1037         HashSet hs=new HashSet();
1038         GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
1039         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1040             GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
1041             TermNode tn2=(TermNode)gn2.getOwner();
1042             if (tn2.getType()==TermNode.ABSTRACT) {
1043                 AbstractRepair ar=tn2.getAbstract();
1044                 if (((repairtype==-1)||(ar.getType()==repairtype))&&
1045                     ar.getPredicate()==dpred) {
1046                     for(Iterator edgeit2=gn2.edges();edgeit2.hasNext();) {
1047                         GraphNode gn3=((GraphNode.Edge) edgeit2.next()).getTarget();
1048                         if (!removed.contains(gn3)) {
1049                             TermNode tn3=(TermNode)gn3.getOwner();
1050                             if (tn3.getType()==TermNode.UPDATE) {
1051                                 hs.add(tn3.getUpdate());
1052                             }
1053                         }
1054                     }
1055                 }
1056             }
1057         }
1058         return hs;
1059     }
1060
1061     private AbstractRepair getabstractrepair(Conjunction conj, DNFPredicate dpred, int repairtype) {
1062         HashSet hs=new HashSet();
1063         MultUpdateNode mun=null;
1064         GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
1065         for(Iterator edgeit=gn.edges();(mun==null)&&edgeit.hasNext();) {
1066             GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
1067             TermNode tn2=(TermNode)gn2.getOwner();
1068             if (tn2.getType()==TermNode.ABSTRACT) {
1069                 AbstractRepair ar=tn2.getAbstract();
1070                 if (((repairtype==-1)||(ar.getType()==repairtype))&&
1071                     ar.getPredicate()==dpred) {
1072                     return ar;
1073                 }
1074             }
1075         }
1076         return null;
1077     }
1078
1079
1080     /** Generates abstract (and concrete) repair for a comparison */
1081
1082     private void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1083         Set updates=getmultupdatenodeset(conj,dpred,AbstractRepair.MODIFYRELATION);
1084         AbstractRepair ar=getabstractrepair(conj,dpred,AbstractRepair.MODIFYRELATION);
1085         MultUpdateNode munmodify=null;
1086         MultUpdateNode munadd=null;
1087         MultUpdateNode munremove=null;
1088         for(Iterator it=updates.iterator();it.hasNext();) {
1089             MultUpdateNode mun=(MultUpdateNode)it.next();
1090             if (mun.getType()==MultUpdateNode.ADD) {
1091                 munadd=mun;
1092             } else if (mun.getType()==MultUpdateNode.REMOVE) {
1093                 munremove=mun;
1094             } else if (mun.getType()==MultUpdateNode.MODIFY) {
1095                 munmodify=mun;
1096             }
1097         }
1098
1099         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
1100         RelationDescriptor rd=(RelationDescriptor)ep.getDescriptor();
1101         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1102         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1103         boolean inverted=ep.inverted();
1104         boolean negated=dpred.isNegated();
1105         OpExpr expr=(OpExpr)ep.expr;
1106         Opcode opcode=expr.getOpcode();
1107         VarDescriptor leftside=VarDescriptor.makeNew("leftside");
1108         VarDescriptor rightside=VarDescriptor.makeNew("rightside");
1109         VarDescriptor newvalue=VarDescriptor.makeNew("newvalue");
1110         boolean needremoveloop=ar.mayNeedFunctionEnforcement(state)&&ar.needsRemoves(state);
1111
1112         if (needremoveloop&&((munadd==null)||(munremove==null))) {
1113             System.out.println("Warning:  need to have individual remove operations for"+dpred.name());
1114             needremoveloop=false;
1115         }
1116         if (needremoveloop) {
1117             cr.outputline("while (1)");
1118             cr.startblock();
1119         }
1120         if (!inverted) {
1121             ((RelationExpr)expr.getLeftExpr()).getExpr().generate(cr,leftside);
1122             expr.getRightExpr().generate(cr,newvalue);
1123             cr.addDeclaration(rd.getRange().getType().getGenerateType().getSafeSymbol(),rightside.getSafeSymbol());
1124             cr.outputline("SimpleHashget("+rd.getSafeSymbol()+"_hash,"+leftside.getSafeSymbol()+", &"+rightside.getSafeSymbol()+");");
1125         } else {
1126             ((RelationExpr)expr.getLeftExpr()).getExpr().generate(cr,rightside);
1127             expr.getRightExpr().generate(cr,newvalue);
1128             cr.outputline(rd.getDomain().getType().getGenerateType().getSafeSymbol()+" "+leftside.getSafeSymbol()+";");
1129             cr.outputline("SimpleHashget("+rd.getSafeSymbol()+"_hashinv,"+rightside.getSafeSymbol()+", &"+leftside.getSafeSymbol()+");");
1130         }
1131
1132         opcode=Opcode.translateOpcode(negated,opcode);
1133
1134         if (opcode==Opcode.GT) {
1135             cr.outputline(newvalue.getSafeSymbol()+"++;");
1136         } else if (opcode==Opcode.GE) {
1137             /* Equal */
1138         } else if (opcode==Opcode.LT) {
1139             cr.outputline(newvalue.getSafeSymbol()+"--;");
1140         } else if (opcode==Opcode.LE) {
1141             /* Equal */
1142         } else if (opcode==Opcode.EQ) {
1143             /* Equal */
1144         } else if (opcode==Opcode.NE) { /* search for FLAGNE if this is changed*/
1145             cr.outputline(newvalue.getSafeSymbol()+"++;");
1146         } else {
1147             throw new Error("Unrecognized Opcode");
1148         }
1149         /* Do abstract repairs */
1150         if (usageimage) {
1151             cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hash, "+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1152         }
1153         if (usageinvimage) {
1154             cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hashinv, "+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
1155         }
1156
1157         if (needremoveloop) {
1158             if (!inverted) {
1159                 cr.outputline("if (SimpleHashcontainskey("+rd.getSafeSymbol()+"_hash, "+leftside.getSafeSymbol()+"))");
1160                 cr.startblock();
1161             } else {
1162                 cr.outputline("if (SimpleHashcontainskey("+rd.getSafeSymbol()+"_hashinv, "+rightside.getSafeSymbol()+"))");
1163                 cr.startblock();
1164             }
1165             for(int i=0;i<state.vRules.size();i++) {
1166                 Rule r=(Rule)state.vRules.get(i);
1167                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1168                     for(int j=0;j<munremove.numUpdates();j++) {
1169                         UpdateNode un=munremove.getUpdate(i);
1170                         if (un.getRule()==r) {
1171                                 /* Update for rule r */
1172                             String name=(String)updatenames.get(un);
1173                             cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
1174                         }
1175                     }
1176                 }
1177             }
1178             cr.outputline("continue;");
1179             cr.endblock();
1180         }
1181
1182         if (usageimage) {
1183             if (!inverted) {
1184                 cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash,"+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1185             } else {
1186                 cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, "+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1187             }
1188         }
1189         if (usageinvimage) {
1190             if (!inverted) {
1191                 cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, "+newvalue.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
1192             } else {
1193                 cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv,"+rightside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1194             }
1195         }
1196         /* Do concrete repairs */
1197         if (munmodify!=null&&(!ar.mayNeedFunctionEnforcement(state))||(munadd==null)||(ar.needsRemoves(state)&&(munremove==null))) {
1198             for(int i=0;i<state.vRules.size();i++) {
1199                 Rule r=(Rule)state.vRules.get(i);
1200                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1201                     for(int j=0;j<munmodify.numUpdates();j++) {
1202                         UpdateNode un=munmodify.getUpdate(j);
1203                         if (un.getRule()==r) {
1204                             /* Update for rule r */
1205                             String name=(String)updatenames.get(un);
1206                             cr.outputline("RepairHashaddrelation2("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+","+newvalue.getSafeSymbol()+");");
1207                         }
1208                     }
1209                 }
1210             }
1211         } else {
1212             /* Start with scheduling removal */
1213             if (ar.needsRemoves(state))
1214                 for(int i=0;i<state.vRules.size();i++) {
1215                     Rule r=(Rule)state.vRules.get(i);
1216                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1217                         for(int j=0;j<munremove.numUpdates();j++) {
1218                             UpdateNode un=munremove.getUpdate(i);
1219                             if (un.getRule()==r) {
1220                                 /* Update for rule r */
1221                                 String name=(String)updatenames.get(un);
1222                                 cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
1223                             }
1224                         }
1225                     }
1226                 }
1227             /* Now do addition */
1228             UpdateNode un=munadd.getUpdate(0);
1229             String name=(String)updatenames.get(un);
1230             if (!inverted) {
1231                 cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1232             } else {
1233                 cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1234             }
1235         }
1236         if (needremoveloop) {
1237             cr.outputline("break;");
1238             cr.endblock();
1239         }
1240     }
1241
1242     public void generatesizerepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr) {
1243         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
1244         OpExpr expr=(OpExpr)ep.expr;
1245         Opcode opcode=expr.getOpcode();
1246         opcode=Opcode.translateOpcode(dpred.isNegated(),opcode);
1247
1248         MultUpdateNode munremove;
1249
1250         MultUpdateNode munadd;
1251         if (ep.getDescriptor() instanceof RelationDescriptor) {
1252             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
1253             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
1254         } else {
1255             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMSET);
1256             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTOSET);
1257         }
1258         int size=ep.rightSize();
1259         VarDescriptor sizevar=VarDescriptor.makeNew("size");
1260         ((OpExpr)expr).left.generate(cr, sizevar);
1261         VarDescriptor change=VarDescriptor.makeNew("change");
1262         cr.addDeclaration("int",change.getSafeSymbol());
1263         boolean generateadd=false;
1264         boolean generateremove=false;
1265         if (opcode==Opcode.GT) {
1266             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
1267             generateadd=true;
1268             generateremove=false;
1269         } else if (opcode==Opcode.GE) {
1270             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1271             generateadd=true;
1272             generateremove=false;
1273         } else if (opcode==Opcode.LT) {
1274             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size-1)+"-"+sizevar.getSafeSymbol()+";");
1275             generateadd=false;
1276             generateremove=true;
1277         } else if (opcode==Opcode.LE) {
1278             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1279             generateadd=false;
1280             generateremove=true;
1281         } else if (opcode==Opcode.EQ) {
1282             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1283             if (size==0)
1284                 generateadd=false;
1285             else
1286                 generateadd=true;
1287             generateremove=true;
1288         } else if (opcode==Opcode.NE) {
1289             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
1290             generateadd=true;
1291             generateremove=false;
1292         } else {
1293             throw new Error("Unrecognized Opcode");
1294         }
1295
1296 // In some cases the analysis has determined that generating removes
1297 // is unnecessary
1298         if (generateremove&&munremove==null)
1299             generateremove=false;
1300
1301         Descriptor d=ep.getDescriptor();
1302         if (generateremove) {
1303             cr.outputline("for(;"+change.getSafeSymbol()+"<0;"+change.getSafeSymbol()+"++)");
1304             cr.startblock();
1305             /* Find element to remove */
1306             VarDescriptor leftvar=VarDescriptor.makeNew("leftvar");
1307             VarDescriptor rightvar=VarDescriptor.makeNew("rightvar");
1308             if (d instanceof RelationDescriptor) {
1309                 if (ep.inverted()) {
1310                     ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,rightvar);
1311                     cr.addDeclaration("int",leftvar.getSafeSymbol());
1312                     cr.outputline("SimpleHashget("+d.getSafeSymbol()+"_hashinv,(int)"+rightvar.getSafeSymbol()+", &"+leftvar.getSafeSymbol()+");");
1313                 } else {
1314                     ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,leftvar);
1315                     cr.addDeclaration("int",rightvar.getSafeSymbol());
1316                     cr.outputline("SimpleHashget("+d.getSafeSymbol()+"_hash ,(int)"+leftvar.getSafeSymbol()+", &"+rightvar.getSafeSymbol()+");");
1317                 }
1318             } else {
1319                 cr.addDeclaration("int",leftvar.getSafeSymbol());
1320                 cr.outputline(leftvar.getSafeSymbol()+"= SimpleHashfirstkey("+d.getSafeSymbol()+"_hash);");
1321             }
1322             /* Generate abstract remove instruction */
1323             if (d instanceof RelationDescriptor) {
1324                 RelationDescriptor rd=(RelationDescriptor) d;
1325                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1326                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1327                 if (usageimage)
1328                     cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1329                 if (usageinvimage)
1330                     cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hashinv ,(int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1331             } else {
1332                 cr.outputline("SimpleHashremove("+d.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1333             }
1334             /* Generate concrete remove instruction */
1335             for(int i=0;i<state.vRules.size();i++) {
1336                 Rule r=(Rule)state.vRules.get(i);
1337                 if (r.getInclusion().getTargetDescriptors().contains(d)) {
1338                     for(int j=0;j<munremove.numUpdates();j++) {
1339                         UpdateNode un=munremove.getUpdate(j);
1340                         if (un.getRule()==r) {
1341                                 /* Update for rule rule r */
1342                             String name=(String)updatenames.get(un);
1343                             if (d instanceof RelationDescriptor) {
1344                                 cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1345                             } else {
1346                                 cr.outputline("RepairHashaddset("+repairtable.getSafeSymbol()+","+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1347                             }
1348                         }
1349                     }
1350                 }
1351             }
1352             cr.endblock();
1353         }
1354
1355 // In some cases the analysis has determined that generating removes
1356 // is unnecessary
1357         if (generateadd&&munadd==null)
1358             generateadd=false;
1359
1360         if (generateadd) {
1361
1362             cr.outputline("for(;"+change.getSafeSymbol()+">0;"+change.getSafeSymbol()+"--)");
1363             cr.startblock();
1364             VarDescriptor newobject=VarDescriptor.makeNew("newobject");
1365             if (d instanceof RelationDescriptor) {
1366                 VarDescriptor otherside=VarDescriptor.makeNew("otherside");
1367                 ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,otherside);
1368
1369                 RelationDescriptor rd=(RelationDescriptor)d;
1370                 if (termination.sources.relsetSource(rd,!ep.inverted())) {
1371                     /* Set Source */
1372                     SetDescriptor sd=termination.sources.relgetSourceSet(rd,!ep.inverted());
1373                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1374                     cr.addDeclaration(sd.getType().getGenerateType().getSafeSymbol(),newobject.getSafeSymbol());
1375                     cr.addDeclaration("struct SimpleIterator",iterator.getSafeSymbol());
1376                     cr.outputline("for(SimpleHashiterator("+sd.getSafeSymbol()+"_hash , &"+ iterator.getSafeSymbol() +"); hasNext(&"+iterator.getSafeSymbol()+");)");
1377                     cr.startblock();
1378                     if (ep.inverted()) {
1379                         cr.outputline("if (!SimpleHashcontainskeydata("+rd.getSafeSymbol()+"_hashinv,"+iterator.getSafeSymbol()+".key(),"+otherside.getSafeSymbol()+"))");
1380                     } else {
1381                         cr.outputline("if (!SimpleHashcontainskeydata("+rd.getSafeSymbol()+"_hash, "+otherside.getSafeSymbol()+","+iterator.getSafeSymbol()+".key()))");
1382                     }
1383                     cr.outputline(newobject.getSafeSymbol()+"=key(&"+iterator.getSafeSymbol()+");");
1384                     cr.outputline("next(&"+iterator.getSafeSymbol()+");");
1385                     cr.endblock();
1386                 } else if (termination.sources.relallocSource(rd,!ep.inverted())) {
1387                     /* Allocation Source*/
1388                     termination.sources.relgenerateSourceAlloc(cr,newobject,rd,!ep.inverted());
1389                 } else throw new Error("No source for adding to Relation");
1390                 if (ep.inverted()) {
1391                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1392                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1393                     if (usageimage)
1394                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, "+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1395                     if (usageinvimage)
1396                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, "+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1397
1398                     UpdateNode un=munadd.getUpdate(0);
1399                     String name=(String)updatenames.get(un);
1400                     cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1401                 } else {
1402                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1403                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1404                     if (usageimage)
1405                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, "+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1406                     if (usageinvimage)
1407                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, "+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1408                     UpdateNode un=munadd.getUpdate(0);
1409                     String name=(String)updatenames.get(un);
1410                     cr.outputline(name+"(thisvar, "+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1411                 }
1412             } else {
1413                 SetDescriptor sd=(SetDescriptor)d;
1414                 if (termination.sources.setSource(sd)) {
1415                     /* Set Source */
1416                     /* Set Source */
1417                     SetDescriptor sourcesd=termination.sources.getSourceSet(sd);
1418                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1419                     cr.addDeclaration(sourcesd.getType().getGenerateType().getSafeSymbol(), newobject.getSafeSymbol());
1420                     cr.addDeclaration("struct SimpleIterator",iterator.getSafeSymbol());
1421                     cr.outputline("for(SimpleHashiterator("+sourcesd.getSafeSymbol()+"_hash, &"+iterator.getSafeSymbol()+"); hasNext(&"+iterator.getSafeSymbol()+");)");
1422                     cr.startblock();
1423                     cr.outputline("if (!SimpleHashcontainskey("+sd.getSafeSymbol()+"_hash, key(&"+iterator.getSafeSymbol()+")))");
1424                     cr.outputline(newobject.getSafeSymbol()+"=key(&"+iterator.getSafeSymbol()+");");
1425                     cr.outputline("next(&"+iterator.getSafeSymbol()+");");
1426                     cr.endblock();
1427                 } else if (termination.sources.allocSource(sd)) {
1428                     /* Allocation Source*/
1429                     termination.sources.generateSourceAlloc(cr,newobject,sd);
1430                 } else throw new Error("No source for adding to Set");
1431                 cr.outputline("SimpleHashadd("+sd.getSafeSymbol()+"_hash, "+newobject.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1432                 UpdateNode un=munadd.getUpdate(0);
1433                 String name=(String)updatenames.get(un);
1434                 cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1435             }
1436             cr.endblock();
1437         }
1438     }
1439
1440     public void generateinclusionrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1441         InclusionPredicate ip=(InclusionPredicate) dpred.getPredicate();
1442         boolean negated=dpred.isNegated();
1443         MultUpdateNode mun=getmultupdatenode(conj,dpred,-1);
1444         VarDescriptor leftvar=VarDescriptor.makeNew("left");
1445         ip.expr.generate(cr, leftvar);
1446
1447         if (negated) {
1448             if (ip.setexpr instanceof ImageSetExpr) {
1449                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1450                 VarDescriptor rightvar=ise.getVar();
1451                 boolean inverse=ise.inverted();
1452                 RelationDescriptor rd=ise.getRelation();
1453                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1454                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1455                 if (inverse) {
1456                     if (usageimage)
1457                         cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hash, (int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1458                     if (usageinvimage)
1459                         cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hashinv, (int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1460                 } else {
1461                     if (usageimage)
1462                         cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hash ,(int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1463                     if (usageinvimage)
1464                         cr.outputline("SimpleHashremove("+rd.getSafeSymbol()+"_hashinv, (int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1465                 }
1466                 for(int i=0;i<state.vRules.size();i++) {
1467                     Rule r=(Rule)state.vRules.get(i);
1468                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1469                         for(int j=0;j<mun.numUpdates();j++) {
1470                             UpdateNode un=mun.getUpdate(j);
1471                             if (un.getRule()==r) {
1472                                 /* Update for rule rule r */
1473                                 String name=(String)updatenames.get(un);
1474                                 if (inverse) {
1475                                     cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1476                                 } else {
1477                                     cr.outputline("RepairHashaddrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1478                                 }
1479                             }
1480                         }
1481                     }
1482                 }
1483             } else {
1484                 SetDescriptor sd=ip.setexpr.sd;
1485                 cr.outputline("SimpleHashremove("+sd.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1486
1487                 for(int i=0;i<state.vRules.size();i++) {
1488                     Rule r=(Rule)state.vRules.get(i);
1489                     if (r.getInclusion().getTargetDescriptors().contains(sd)) {
1490                         for(int j=0;j<mun.numUpdates();j++) {
1491                             UpdateNode un=mun.getUpdate(j);
1492                             if (un.getRule()==r) {
1493                                 /* Update for rule rule r */
1494                                 String name=(String)updatenames.get(un);
1495                                 cr.outputline("RepairHashaddset("+repairtable.getSafeSymbol()+","+sd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1496                             }
1497                         }
1498                     }
1499                 }
1500             }
1501         } else {
1502             /* Generate update */
1503             if (ip.setexpr instanceof ImageSetExpr) {
1504                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1505                 VarDescriptor rightvar=ise.getVar();
1506                 boolean inverse=ise.inverted();
1507                 RelationDescriptor rd=ise.getRelation();
1508                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1509                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1510                 if (inverse) {
1511                     if (usageimage)
1512                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, (int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1513                     if (usageinvimage)
1514                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, (int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1515                 } else {
1516                     if (usageimage)
1517                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1518                     if (usageinvimage)
1519                         cr.outputline("SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, (int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1520                 }
1521                 UpdateNode un=mun.getUpdate(0);
1522                 String name=(String)updatenames.get(un);
1523                 if (inverse) {
1524                     cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1525                 } else {
1526                     cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1527                 }
1528             } else {
1529                 SetDescriptor sd=ip.setexpr.sd;
1530                 cr.outputline("SimpleHashadd("+sd.getSafeSymbol()+"_hash, (int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1531
1532                 UpdateNode un=mun.getUpdate(0);
1533                 /* Update for rule rule r */
1534                 String name=(String)updatenames.get(un);
1535                 cr.outputline(name+"(thisvar,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1536             }
1537         }
1538     }
1539
1540     public static Vector getrulelist(Descriptor d) {
1541         Vector dispatchrules = new Vector();
1542         Vector rules = State.currentState.vRules;
1543
1544         for (int i = 0; i < rules.size(); i++) {
1545             Rule rule = (Rule) rules.elementAt(i);
1546             Set requiredsymbols = rule.getRequiredDescriptors();
1547
1548             // #TBD#: in general this is wrong because these descriptors may contain descriptors
1549             // bound in "in?" expressions which need to be dealt with in a topologically sorted
1550             // fashion...
1551
1552             if (rule.getRequiredDescriptors().contains(d)) {
1553                 dispatchrules.addElement(rule);
1554             }
1555         }
1556         return dispatchrules;
1557     }
1558
1559     private boolean need_compensation(Rule r) {
1560         if (!Compiler.REPAIR)
1561             return false;
1562         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1563         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1564             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1565             GraphNode gn2=edge.getTarget();
1566             if (!removed.contains(gn2)) {
1567                 TermNode tn2=(TermNode)gn2.getOwner();
1568                 if (tn2.getType()==TermNode.CONSEQUENCE)
1569                     return false;
1570             }
1571         }
1572         return true;
1573     }
1574
1575     private UpdateNode find_compensation(Rule r) {
1576         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1577         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1578             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1579             GraphNode gn2=edge.getTarget();
1580             if (!removed.contains(gn2)) {
1581                 TermNode tn2=(TermNode)gn2.getOwner();
1582                 if (tn2.getType()==TermNode.UPDATE) {
1583                     MultUpdateNode mun=tn2.getUpdate();
1584                     for(int i=0;i<mun.numUpdates();i++) {
1585                         UpdateNode un=mun.getUpdate(i);
1586                         if (un.getRule()==r)
1587                             return un;
1588                     }
1589                 }
1590             }
1591         }
1592         throw new Error("No Compensation Update could be found");
1593     }
1594
1595     public void generate_dispatch(CodeWriter cr, RelationDescriptor rd, String leftvar, String rightvar) {
1596         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1597         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1598
1599         if (!(usageinvimage||usageimage)) /* not used at all*/
1600             return;
1601
1602         cr.outputline("/* RELATION DISPATCH */");
1603         if (Compiler.REPAIR) {
1604             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1605             if (usageimage)
1606                 cr.outputline("!SimpleHashcontainskeydata("+oldmodel.getSafeSymbol()+"->"+rd.getJustSafeSymbol() + "_hash, "+leftvar+","+rightvar+"))");
1607             else
1608                 cr.outputline("!SimpleHashcontainskeydata("+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv, "+rightvar+","+leftvar+"))");
1609
1610             cr.startblock(); {
1611                 /* Adding new item */
1612                 /* Perform safety checks */
1613                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1614                 cr.outputline("RepairHashcontainsrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
1615                 cr.startblock(); {
1616                     /* Have update to call into */
1617                     VarDescriptor mdfyptr=VarDescriptor.makeNew("modifyptr");
1618                     VarDescriptor ismdfyptr=VarDescriptor.makeNew("ismodifyptr");
1619                     cr.addDeclaration("int ",ismdfyptr.getSafeSymbol());
1620                     cr.outputline(ismdfyptr.getSafeSymbol()+"=RepairHashismodify("+repairtable.getSafeSymbol()+","+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1621
1622
1623
1624
1625                     String parttype="";
1626                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1627                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1628                             parttype=parttype+", int, int";
1629                         else
1630                             parttype=parttype+", int";
1631                     }
1632
1633                     VarDescriptor tmpptr=VarDescriptor.makeNew("tempupdateptr");
1634
1635                     String methodcall="(thisvar,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1636                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1637                         Quantifier q=currentrule.getQuantifier(i);
1638                         if (q instanceof SetQuantifier) {
1639                             SetQuantifier sq=(SetQuantifier) q;
1640                             methodcall+=","+sq.getVar().getSafeSymbol();
1641                         } else if (q instanceof RelationQuantifier) {
1642                             RelationQuantifier rq=(RelationQuantifier) q;
1643                             methodcall+=","+rq.x.getSafeSymbol();
1644                             methodcall+=","+rq.y.getSafeSymbol();
1645                         } else if (q instanceof ForQuantifier) {
1646                             ForQuantifier fq=(ForQuantifier) q;
1647                             methodcall+=","+fq.getVar().getSafeSymbol();
1648                         }
1649                     }
1650
1651
1652
1653                     cr.addDeclaration("void *",tmpptr.getSafeSymbol());
1654                     cr.outputline(tmpptr.getSafeSymbol()+"=");
1655                     cr.outputline("(void *) RepairHashgetrelation("+repairtable.getSafeSymbol()+","+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1656                     cr.outputline("if ("+ismdfyptr.getSafeSymbol()+")");
1657                     {
1658                         VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1659                         String methodcallprefix="("+funptr.getSafeSymbol()+") ";
1660                         cr.startblock();
1661                         cr.addDeclaration("int",mdfyptr.getSafeSymbol());
1662                         cr.outputline(mdfyptr.getSafeSymbol()+"=RepairHashgetrelation2("+repairtable.getSafeSymbol()+","+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1663                         cr.addDeclaration("void (*"+funptr.getSafeSymbol()+") (struct "+name+"_state *, struct "+name+"*, struct RepairHash *"+parttype+",int,int,int);");
1664                         cr.outputline(funptr.getSafeSymbol()+"="+"(void (*) (struct "+name+"_state *, struct "+name+"*, struct RepairHash *"+parttype+",int,int,int)) "+tmpptr.getSafeSymbol()+";");
1665                         cr.outputline(methodcallprefix+methodcall+","+leftvar+", "+rightvar+", "+mdfyptr.getSafeSymbol() +");");
1666                         cr.endblock();
1667                     }
1668                     cr.outputline("else ");
1669                     {
1670                         VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1671                         String methodcallprefix="("+funptr.getSafeSymbol()+") ";
1672                         cr.startblock();
1673                         cr.addDeclaration("void (*"+funptr.getSafeSymbol()+") (struct "+name+"_state *, struct "+name+"*,struct RepairHash *"+parttype+");");
1674                         cr.outputline(funptr.getSafeSymbol()+"="+"(void (*) (struct "+name+"_state *,struct "+name+"*,struct RepairHash *"+parttype+")) "+tmpptr.getSafeSymbol()+";");
1675                         cr.outputline(methodcallprefix+methodcall+");");
1676                         cr.endblock();
1677                     }
1678                     cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1679                     cr.outputline("goto rebuild;");
1680                 }
1681                 cr.endblock();
1682
1683                 /* Build standard compensation actions */
1684                 if (need_compensation(currentrule)) {
1685                     UpdateNode un=find_compensation(currentrule);
1686                     String name=(String)updatenames.get(un);
1687                     usedupdates.add(un); /* Mark as used */
1688                     String methodcall=name+"(thisvar,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1689                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1690                         Quantifier q=currentrule.getQuantifier(i);
1691                         if (q instanceof SetQuantifier) {
1692                             SetQuantifier sq=(SetQuantifier) q;
1693                             methodcall+=","+sq.getVar().getSafeSymbol();
1694                         } else if (q instanceof RelationQuantifier) {
1695                             RelationQuantifier rq=(RelationQuantifier) q;
1696                             methodcall+=","+rq.x.getSafeSymbol();
1697                             methodcall+=","+rq.y.getSafeSymbol();
1698                         } else if (q instanceof ForQuantifier) {
1699                             ForQuantifier fq=(ForQuantifier) q;
1700                             methodcall+=","+fq.getVar().getSafeSymbol();
1701                         }
1702                     }
1703                     methodcall+=");";
1704                     cr.outputline(methodcall);
1705                     cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1706                     cr.outputline("goto rebuild;");
1707                 }
1708             }
1709             cr.endblock();
1710         }
1711
1712         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1713         cr.startblock();
1714         cr.addDeclaration("int" , addeditem);
1715         cr.outputline(addeditem + "=0;");
1716
1717         String ifstring="if (!maybe";
1718         if (rd.getDomain().getType() instanceof StructureTypeDescriptor)  {
1719             ifstring+="&&"+leftvar;
1720         }
1721
1722         if (rd.getRange().getType() instanceof StructureTypeDescriptor)  {
1723             ifstring+="&&"+rightvar;
1724         }
1725
1726         ifstring+=")";
1727
1728         if (rd.testUsage(RelationDescriptor.IMAGE)) {
1729             cr.outputline(ifstring);
1730             cr.outputline(addeditem + " = SimpleHashadd("+rd.getSafeSymbol()+"_hash, (int)" + leftvar + ", (int)" + rightvar+ ");");
1731         }
1732
1733         if (rd.testUsage(RelationDescriptor.INVIMAGE)) {
1734             cr.outputline(ifstring);
1735             cr.outputline(addeditem + " = SimpleHashadd("+rd.getSafeSymbol()+"_hashinv, (int)" + rightvar + ", (int)" + leftvar + ");");
1736         }
1737
1738
1739         Vector dispatchrules = getrulelist(rd);
1740
1741         Set toremove=new HashSet();
1742         for(int i=0;i<dispatchrules.size();i++) {
1743             Rule r=(Rule)dispatchrules.get(i);
1744             if (!ruleset.contains(r))
1745                 toremove.add(r);
1746         }
1747         dispatchrules.removeAll(toremove);
1748         if (dispatchrules.size() == 0) {
1749             cr.outputline("/* nothing to dispatch */");
1750             cr.endblock();
1751             return;
1752         }
1753
1754         cr.outputline("if (" + addeditem + ")");
1755         cr.startblock();
1756
1757         for(int i = 0; i < dispatchrules.size(); i++) {
1758             Rule rule = (Rule) dispatchrules.elementAt(i);
1759             if (rule.getGuardExpr().getRequiredDescriptors().contains(rd)) {
1760                 /* Guard depends on this relation, so we recomput everything */
1761                 cr.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+",-1,0,0);");
1762             } else {
1763                 for (int j=0;j<rule.numQuantifiers();j++) {
1764                     Quantifier q=rule.getQuantifier(j);
1765                     if (q.getRequiredDescriptors().contains(rd)) {
1766                         /* Generate add */
1767                         cr.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+","+j+","+leftvar+","+rightvar+");");
1768                     }
1769                 }
1770             }
1771         }
1772         cr.endblock();
1773         cr.endblock();
1774     }
1775
1776
1777     public void generate_dispatch(CodeWriter cr, SetDescriptor sd, String setvar) {
1778         cr.outputline("/* SET DISPATCH */");
1779         if (Compiler.REPAIR) {
1780             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1781             cr.outputline("!SimpleHashcontainskey("+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash, "+setvar+"))");
1782             cr.startblock(); {
1783                 /* Adding new item */
1784                 /* See if there is an outstanding update in the repairtable */
1785                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1786                 cr.outputline("RepairHashcontainsset("+repairtable.getSafeSymbol()+","+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
1787                 cr.startblock(); {
1788                     /* Have update to call into */
1789                     VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1790                     String parttype="";
1791                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1792                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1793                             parttype=parttype+", int, int";
1794                         else
1795                             parttype=parttype+", int";
1796                     }
1797                     cr.addDeclaration("void (*"+funptr.getSafeSymbol()+") (struct "+name+"_state *,struct "+name+"*,struct RepairHash *"+parttype+");");
1798                     cr.outputline(funptr.getSafeSymbol()+"=");
1799                     cr.outputline("(void (*) (struct "+name+"_state *,struct "+name+"*,struct RepairHash *"+parttype+")) RepairHashgetset("+repairtable.getSafeSymbol()+","+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
1800                     String methodcall="("+funptr.getSafeSymbol()+") (thisvar,"+oldmodel.getSafeSymbol()+","+
1801                         repairtable.getSafeSymbol();
1802                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1803                         Quantifier q=currentrule.getQuantifier(i);
1804                         if (q instanceof SetQuantifier) {
1805                             SetQuantifier sq=(SetQuantifier) q;
1806                             methodcall+=","+sq.getVar().getSafeSymbol();
1807                         } else if (q instanceof RelationQuantifier) {
1808                             RelationQuantifier rq=(RelationQuantifier) q;
1809                             methodcall+=","+rq.x.getSafeSymbol();
1810                             methodcall+=","+rq.y.getSafeSymbol();
1811                         } else if (q instanceof ForQuantifier) {
1812                             ForQuantifier fq=(ForQuantifier) q;
1813                             methodcall+=","+fq.getVar().getSafeSymbol();
1814                         }
1815                     }
1816                     methodcall+=");";
1817                     cr.outputline(methodcall);
1818                     cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1819                     cr.outputline("goto rebuild;");
1820                 }
1821                 cr.endblock();
1822                 /* Build standard compensation actions */
1823                 Vector ruleset=new Vector();
1824                 ruleset.add(currentrule);
1825                 if (state.implicitruleinv.containsKey(currentrule))
1826                     ruleset.addAll((Set)state.implicitruleinv.get(currentrule));
1827                 for(int i=0;i<ruleset.size();i++) {
1828                     Rule itrule=(Rule)ruleset.get(i);
1829
1830                     if (need_compensation(itrule)) {
1831                         UpdateNode un=find_compensation(itrule);
1832                         String name=(String)updatenames.get(un);
1833                         usedupdates.add(un); /* Mark as used */
1834
1835                         String methodcall=name+"(thisvar,"+oldmodel.getSafeSymbol()+","+
1836                             repairtable.getSafeSymbol();
1837                         for(int j=0;j<currentrule.numQuantifiers();j++) {
1838                             Quantifier q=currentrule.getQuantifier(j);
1839                             if (q instanceof SetQuantifier) {
1840                                 SetQuantifier sq=(SetQuantifier) q;
1841                                 methodcall+=","+sq.getVar().getSafeSymbol();
1842                             } else if (q instanceof RelationQuantifier) {
1843                                 RelationQuantifier rq=(RelationQuantifier) q;
1844                                 methodcall+=","+rq.x.getSafeSymbol();
1845                                 methodcall+=","+rq.y.getSafeSymbol();
1846                             } else if (q instanceof ForQuantifier) {
1847                                 ForQuantifier fq=(ForQuantifier) q;
1848                                 methodcall+=","+fq.getVar().getSafeSymbol();
1849                             }
1850                         }
1851                         methodcall+=");";
1852                         if (currentrule!=itrule) {
1853                             SetDescriptor sdrule=((SetInclusion)itrule.getInclusion()).getSet();
1854                             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1855                             cr.outputline("!SimpleHashcontainskey("+ oldmodel.getSafeSymbol() +"->"+sdrule.getJustSafeSymbol() +"_hash,"+setvar+"))");
1856                             cr.startblock();
1857                         }
1858                         cr.outputline(methodcall);
1859                         cr.outputline("free"+name+"("+newmodel.getSafeSymbol()+");");
1860                         cr.outputline("goto rebuild;");
1861                         cr.endblock();
1862                     }
1863                     if (currentrule==itrule)
1864                         cr.endblock();
1865                 }
1866             }
1867         }
1868
1869         cr.startblock();
1870         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1871         cr.addDeclaration("int", addeditem);
1872         cr.outputline(addeditem + " = 0;");
1873         if (sd.getType() instanceof StructureTypeDescriptor)  {
1874             cr.outputline("if (!maybe&&"+setvar+")");
1875         } else
1876             cr.outputline("if (!maybe)");
1877         cr.outputline(addeditem + " = SimpleHashadd("+sd.getSafeSymbol()+"_hash, (int)" + setvar +  ", (int)" + setvar + ");");
1878         cr.startblock();
1879         Vector dispatchrules = getrulelist(sd);
1880
1881         Set toremove=new HashSet();
1882         for(int i=0;i<dispatchrules.size();i++) {
1883             Rule r=(Rule)dispatchrules.get(i);
1884             if (!ruleset.contains(r))
1885                 toremove.add(r);
1886         }
1887         dispatchrules.removeAll(toremove);
1888
1889         if (dispatchrules.size() == 0) {
1890             cr.outputline("/* nothing to dispatch */");
1891             cr.endblock();
1892             cr.endblock();
1893             return;
1894         }
1895         /* Add item to worklist if new */
1896         cr.outputline("if ("+addeditem+")");
1897         cr.startblock();
1898         for(int i = 0; i < dispatchrules.size(); i++) {
1899             Rule rule = (Rule) dispatchrules.elementAt(i);
1900             if (SetDescriptor.expand(rule.getGuardExpr().getRequiredDescriptors()).contains(sd)) {
1901                 /* Guard depends on this relation, so we recompute everything */
1902                 cr.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+",-1,0,0);");
1903             } else {
1904                 for (int j=0;j<rule.numQuantifiers();j++) {
1905                     Quantifier q=rule.getQuantifier(j);
1906                     if (SetDescriptor.expand(q.getRequiredDescriptors()).contains(sd)) {
1907                         /* Generate add */
1908                         cr.outputline("WorkListadd("+worklist.getSafeSymbol()+","+rule.getNum()+","+j+","+setvar+",0);");
1909                     }
1910                 }
1911             }
1912         }
1913         cr.endblock();
1914         cr.endblock();
1915         cr.endblock();
1916     }
1917 }