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