compile fix
[cacao.git] / jit / typecheck.c
1 /* jit/typecheck.c - typechecking (part of bytecode verification)
2
3    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
4    R. Grafl, A. Krall, C. Kruegel, C. Oates, R. Obermaisser,
5    M. Probst, S. Ring, E. Steiner, C. Thalinger, D. Thuernbeck,
6    P. Tomsich, J. Wenninger
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23    02111-1307, USA.
24
25    Contact: cacao@complang.tuwien.ac.at
26
27    Authors: Edwin Steiner
28
29    $Id: typecheck.c 1415 2004-10-11 20:12:08Z jowenn $
30
31 */
32
33 #include "global.h" /* must be here because of CACAO_TYPECHECK */
34
35 #ifdef CACAO_TYPECHECK
36
37 #include <string.h>
38 #include "main.h"
39 #include "builtin.h"
40 #include "tables.h"
41 #include "loader.h"
42 #include "native.h"
43 #include "types.h"
44 #include "jit/jit.h"
45 #include "jit/stack.h"
46 #include "toolbox/logging.h"
47 #include "toolbox/memory.h"
48
49 /****************************************************************************/
50 /* DEBUG HELPERS                                                            */
51 /****************************************************************************/
52
53 #ifdef TYPECHECK_VERBOSE_OPT
54 bool typecheckverbose = false;
55 #define DOLOG(action)  do { if (typecheckverbose) {action;} } while(0)
56 #else
57 #define DOLOG(action)
58 #endif
59
60 #ifdef TYPECHECK_VERBOSE
61 #define TYPECHECK_VERBOSE_IMPORTANT
62 #define LOG(str)           DOLOG(log_text(str))
63 #define LOG1(str,a)        DOLOG(dolog(str,a))
64 #define LOG2(str,a,b)      DOLOG(dolog(str,a,b))
65 #define LOG3(str,a,b,c)    DOLOG(dolog(str,a,b,c))
66 #define LOGIF(cond,str)    DOLOG(do {if (cond) log_text(str);} while(0))
67 #define LOGINFO(info)      DOLOG(do {typeinfo_print_short(get_logfile(),(info));log_plain("\n");} while(0))
68 #define LOGFLUSH           DOLOG(fflush(get_logfile()))
69 #define LOGNL              DOLOG(log_plain("\n"))
70 #define LOGSTR(str)        DOLOG(log_plain(str))
71 #define LOGSTR1(str,a)     DOLOG(dolog_plain(str,a))
72 #define LOGSTR2(str,a,b)   DOLOG(dolog_plain(str,a,b))
73 #define LOGSTR3(str,a,b,c) DOLOG(dolog_plain(str,a,b,c))
74 #define LOGSTRu(utf)       DOLOG(log_plain_utf(utf))
75 #else
76 #define LOG(str)
77 #define LOG1(str,a)
78 #define LOG2(str,a,b)
79 #define LOG3(str,a,b,c)
80 #define LOGIF(cond,str)
81 #define LOGINFO(info)
82 #define LOGFLUSH
83 #define LOGNL
84 #define LOGSTR(str)
85 #define LOGSTR1(str,a)
86 #define LOGSTR2(str,a,b)
87 #define LOGSTR3(str,a,b,c)
88 #define LOGSTRu(utf)
89 #endif
90
91 #ifdef TYPECHECK_VERBOSE_IMPORTANT
92 #define LOGimp(str)     DOLOG(log_text(str))
93 #define LOGimpSTR(str)  DOLOG(log_plain(str))
94 #define LOGimpSTRu(utf) DOLOG(log_plain_utf(utf))
95 #else
96 #define LOGimp(str)
97 #define LOGimpSTR(str)
98 #define LOGimpSTRu(utf)
99 #endif
100
101 #if defined(TYPECHECK_VERBOSE) || defined(TYPECHECK_VERBOSE_IMPORTANT)
102
103 #include <stdio.h>
104
105 static
106 void
107 typestack_print(FILE *file,stackptr stack)
108 {
109     while (stack) {
110         typeinfo_print_stacktype(file,stack->type,&stack->typeinfo);
111         stack = stack->prev;
112         if (stack) fprintf(file," ");
113     }
114 }
115
116 static
117 void
118 typestate_print(FILE *file,stackptr instack,typevector *localset,int size)
119 {
120     fprintf(file,"Stack: ");
121     typestack_print(file,instack);
122     fprintf(file," Locals:");
123     typevectorset_print(file,localset,size);
124 }
125
126 #endif
127
128 /****************************************************************************/
129 /* STATISTICS                                                               */
130 /****************************************************************************/
131
132 #ifdef TYPECHECK_DEBUG
133 /*#define TYPECHECK_STATISTICS*/
134 #endif
135
136 #ifdef TYPECHECK_STATISTICS
137 #define STAT_ITERATIONS  10
138 #define STAT_BLOCKS      10
139 #define STAT_LOCALS      16
140
141 static int stat_typechecked = 0;
142 static int stat_typechecked_jsr = 0;
143 static int stat_iterations[STAT_ITERATIONS+1] = { 0 };
144 static int stat_reached = 0;
145 static int stat_copied = 0;
146 static int stat_merged = 0;
147 static int stat_merging_changed = 0;
148 static int stat_backwards = 0;
149 static int stat_blocks[STAT_BLOCKS+1] = { 0 };
150 static int stat_locals[STAT_LOCALS+1] = { 0 };
151 static int stat_ins = 0;
152 static int stat_ins_field = 0;
153 static int stat_ins_invoke = 0;
154 static int stat_ins_primload = 0;
155 static int stat_ins_aload = 0;
156 static int stat_ins_builtin = 0;
157 static int stat_ins_builtin_gen = 0;
158 static int stat_ins_branch = 0;
159 static int stat_ins_switch = 0;
160 static int stat_ins_unchecked = 0;
161 static int stat_handlers_reached = 0;
162 static int stat_savedstack = 0;
163
164 #define TYPECHECK_COUNT(cnt)  (cnt)++
165 #define TYPECHECK_COUNTIF(cond,cnt)  do{if(cond) (cnt)++;} while(0)
166 #define TYPECHECK_COUNT_FREQ(array,val,limit) \
167         do {                                                                      \
168                 if ((val) < (limit)) (array)[val]++;  \
169                 else (array)[limit]++;                            \
170         } while (0)
171
172 static void print_freq(FILE *file,int *array,int limit)
173 {
174         int i;
175         for (i=0; i<limit; ++i)
176                 fprintf(file,"      %3d: %8d\n",i,array[i]);
177         fprintf(file,"    =>%3d: %8d\n",limit,array[limit]);
178 }
179
180 void typecheck_print_statistics(FILE *file) {
181         fprintf(file,"typechecked methods: %8d\n",stat_typechecked);
182         fprintf(file,"methods with JSR   : %8d\n",stat_typechecked_jsr);
183         fprintf(file,"reached blocks     : %8d\n",stat_reached);
184         fprintf(file,"copied states      : %8d\n",stat_copied);
185         fprintf(file,"merged states      : %8d\n",stat_merged);
186         fprintf(file,"merging changed    : %8d\n",stat_merging_changed);
187         fprintf(file,"backwards branches : %8d\n",stat_backwards);
188         fprintf(file,"handlers reached   : %8d\n",stat_handlers_reached);
189         fprintf(file,"saved stack (times): %8d\n",stat_savedstack);
190         fprintf(file,"instructions       : %8d\n",stat_ins);
191         fprintf(file,"    field access   : %8d\n",stat_ins_field);
192         fprintf(file,"    invocations    : %8d\n",stat_ins_invoke);
193         fprintf(file,"    load primitive : %8d\n",stat_ins_primload);
194         fprintf(file,"    load address   : %8d\n",stat_ins_aload);
195         fprintf(file,"    builtins       : %8d\n",stat_ins_builtin);
196         fprintf(file,"        generic    : %8d\n",stat_ins_builtin_gen);
197         fprintf(file,"    unchecked      : %8d\n",stat_ins_unchecked);
198         fprintf(file,"    branches       : %8d\n",stat_ins_branch);
199         fprintf(file,"    switches       : %8d\n",stat_ins_switch);
200         fprintf(file,"iterations used:\n");
201         print_freq(file,stat_iterations,STAT_ITERATIONS);
202         fprintf(file,"basic blocks per method / 10:\n");
203         print_freq(file,stat_blocks,STAT_BLOCKS);
204         fprintf(file,"locals:\n");
205         print_freq(file,stat_locals,STAT_LOCALS);
206 }
207                                                    
208 #else
209                                                    
210 #define TYPECHECK_COUNT(cnt)
211 #define TYPECHECK_COUNTIF(cond,cnt)
212 #define TYPECHECK_COUNT_FREQ(array,val,limit)
213 #endif
214
215 /****************************************************************************/
216 /* TYPESTACK FUNCTIONS                                                      */
217 /****************************************************************************/
218
219 #define TYPESTACK_IS_RETURNADDRESS(sptr) \
220             TYPE_IS_RETURNADDRESS((sptr)->type,(sptr)->typeinfo)
221
222 #define TYPESTACK_IS_REFERENCE(sptr) \
223             TYPE_IS_REFERENCE((sptr)->type,(sptr)->typeinfo)
224
225 #define TYPESTACK_RETURNADDRESSSET(sptr) \
226             ((typeinfo_retaddr_set*)TYPEINFO_RETURNADDRESS((sptr)->typeinfo))
227
228 #define RETURNADDRESSSET_SEEK(set,pos) \
229             do {int i; for (i=pos;i--;) set=set->alt;} while(0)
230
231 #define TYPESTACK_COPY(sp,copy)                                                                 \
232                 do {for(; sp; sp=sp->prev, copy=copy->prev) {           \
233                                         copy->type = sp->type;                                          \
234                                         TYPEINFO_COPY(sp->typeinfo,copy->typeinfo);     \
235                                 }} while (0)                                                                    \
236
237 static void
238 typestack_copy(stackptr dst,stackptr y,typevector *selected)
239 {
240         typevector *sel;
241         typeinfo_retaddr_set *sety;
242         typeinfo_retaddr_set *new;
243         typeinfo_retaddr_set **next;
244         int k;
245         
246         for (;dst; dst=dst->prev, y=y->prev) {
247                 if (!y) panic("Stack depth mismatch 1");
248                 if (dst->type != y->type)
249                         panic("Stack type mismatch 1");
250                 LOG3("copy %p -> %p (type %d)",y,dst,dst->type);
251                 if (dst->type == TYPE_ADDRESS) {
252                         if (TYPEINFO_IS_PRIMITIVE(y->typeinfo)) {
253                                 /* We copy the returnAddresses from the selected
254                                  * states only. */
255
256                                 LOG("copying returnAddress");
257                                 sety = TYPESTACK_RETURNADDRESSSET(y);
258                                 next = &new;
259                                 for (k=0,sel=selected; sel; sel=sel->alt) {
260                                         LOG1("selected k=%d",sel->k);
261                                         while (k<sel->k) {
262                                                 sety = sety->alt;
263                                                 k++;
264                                         }
265                                         *next = DNEW(typeinfo_retaddr_set);
266                                         (*next)->addr = sety->addr;
267                                         next = &((*next)->alt);
268                                 }
269                                 *next = NULL;
270                                 TYPEINFO_INIT_RETURNADDRESS(dst->typeinfo,new);
271                         }
272                         else {
273                                 TYPEINFO_CLONE(y->typeinfo,dst->typeinfo);
274                         }
275                 }
276         }
277         if (y) panic("Stack depth mismatch 2");
278 }
279
280 static void
281 typestack_put_retaddr(stackptr dst,void *retaddr,typevector *loc)
282 {
283 #ifdef TYPECHECK_DEBUG
284         if (dst->type != TYPE_ADDRESS)
285                 panic("Internal error: Storing returnAddress in non-address slot");
286 #endif
287         
288         TYPEINFO_INIT_RETURNADDRESS(dst->typeinfo,NULL);
289         for (;loc; loc=loc->alt) {
290                 typeinfo_retaddr_set *set = DNEW(typeinfo_retaddr_set);
291                 set->addr = retaddr;
292                 set->alt = TYPESTACK_RETURNADDRESSSET(dst);
293                 TYPEINFO_INIT_RETURNADDRESS(dst->typeinfo,set);
294         }
295 }
296
297 static void
298 typestack_collapse(stackptr dst)
299 {
300         for (; dst; dst = dst->prev) {
301                 if (TYPESTACK_IS_RETURNADDRESS(dst))
302                         TYPESTACK_RETURNADDRESSSET(dst)->alt = NULL;
303         }
304 }
305
306 static bool
307 typestack_merge(stackptr dst,stackptr y)
308 {
309         bool changed = false;
310         for (; dst; dst = dst->prev, y=y->prev) {
311                 if (!y)
312                         panic("Stack depth mismatch 3");
313                 if (dst->type != y->type) panic("Stack type mismatch 2");
314                 if (dst->type == TYPE_ADDRESS) {
315                         if (TYPEINFO_IS_PRIMITIVE(dst->typeinfo)) {
316                                 /* dst has returnAddress type */
317                                 if (!TYPEINFO_IS_PRIMITIVE(y->typeinfo))
318                                         panic("Merging returnAddress with reference");
319                         }
320                         else {
321                                 /* dst has reference type */
322                                 if (TYPEINFO_IS_PRIMITIVE(y->typeinfo))
323                                         panic("Merging reference with returnAddress");
324                                 changed |= typeinfo_merge(&(dst->typeinfo),&(y->typeinfo));
325                         }
326                 }
327         }
328         if (y) panic("Stack depth mismatch 4");
329         return changed;
330 }
331
332 static void
333 typestack_add(stackptr dst,stackptr y,int ky)
334 {
335         typeinfo_retaddr_set *setd;
336         typeinfo_retaddr_set *sety;
337         
338         for (; dst; dst = dst->prev, y=y->prev) {
339                 if (TYPESTACK_IS_RETURNADDRESS(dst)) {
340                         setd = TYPESTACK_RETURNADDRESSSET(dst);
341                         sety = TYPESTACK_RETURNADDRESSSET(y);
342                         RETURNADDRESSSET_SEEK(sety,ky);
343                         while (setd->alt)
344                                 setd=setd->alt;
345                         setd->alt = DNEW(typeinfo_retaddr_set);
346                         setd->alt->addr = sety->addr;
347                         setd->alt->alt = NULL;
348                 }
349         }
350 }
351
352 /* 'a' and 'b' are assumed to have passed typestack_canmerge! */
353 static bool
354 typestack_separable_with(stackptr a,stackptr b,int kb)
355 {
356         typeinfo_retaddr_set *seta;
357         typeinfo_retaddr_set *setb;
358         
359         for (; a; a = a->prev, b = b->prev) {
360 #ifdef TYPECHECK_DEBUG
361                 if (!b) panic("Internal error: typestack_separable_from: different depth");
362 #endif
363                 if (TYPESTACK_IS_RETURNADDRESS(a)) {
364 #ifdef TYPECHECK_DEBUG
365                         if (!TYPESTACK_IS_RETURNADDRESS(b))
366                                 panic("Internal error: typestack_separable_from: unmergable stacks");
367 #endif
368                         seta = TYPESTACK_RETURNADDRESSSET(a);
369                         setb = TYPESTACK_RETURNADDRESSSET(b);
370                         RETURNADDRESSSET_SEEK(setb,kb);
371
372                         for (;seta;seta=seta->alt)
373                                 if (seta->addr != setb->addr) return true;
374                 }
375         }
376 #ifdef TYPECHECK_DEBUG
377         if (b) panic("Internal error: typestack_separable_from: different depth");
378 #endif
379         return false;
380 }
381
382 /* 'a' and 'b' are assumed to have passed typestack_canmerge! */
383 static bool
384 typestack_separable_from(stackptr a,int ka,stackptr b,int kb)
385 {
386         typeinfo_retaddr_set *seta;
387         typeinfo_retaddr_set *setb;
388
389         for (; a; a = a->prev, b = b->prev) {
390 #ifdef TYPECHECK_DEBUG
391                 if (!b) panic("Internal error: typestack_separable_from: different depth");
392 #endif
393                 if (TYPESTACK_IS_RETURNADDRESS(a)) {
394 #ifdef TYPECHECK_DEBUG
395                         if (!TYPESTACK_IS_RETURNADDRESS(b))
396                                 panic("Internal error: typestack_separable_from: unmergable stacks");
397 #endif
398                         seta = TYPESTACK_RETURNADDRESSSET(a);
399                         setb = TYPESTACK_RETURNADDRESSSET(b);
400                         RETURNADDRESSSET_SEEK(seta,ka);
401                         RETURNADDRESSSET_SEEK(setb,kb);
402
403                         if (seta->addr != setb->addr) return true;
404                 }
405         }
406 #ifdef TYPECHECK_DEBUG
407         if (b) panic("Internal error: typestack_separable_from: different depth");
408 #endif
409         return false;
410 }
411
412 /****************************************************************************/
413 /* TYPESTATE FUNCTIONS                                                      */
414 /****************************************************************************/
415
416 static bool
417 typestate_merge(stackptr deststack,typevector *destloc,
418                                 stackptr ystack,typevector *yloc,
419                                 int locsize,bool jsrencountered)
420 {
421         typevector *dvec,*yvec;
422         int kd,ky;
423         bool changed = false;
424         
425         LOG("merge:");
426         LOGSTR("dstack: "); DOLOG(typestack_print(get_logfile(),deststack)); LOGNL;
427         LOGSTR("ystack: "); DOLOG(typestack_print(get_logfile(),ystack)); LOGNL;
428         LOGSTR("dloc  : "); DOLOG(typevectorset_print(get_logfile(),destloc,locsize)); LOGNL;
429         LOGSTR("yloc  : "); DOLOG(typevectorset_print(get_logfile(),yloc,locsize)); LOGNL;
430         LOGFLUSH;
431
432         /* The stack is always merged. If there are returnAddresses on
433          * the stack they are ignored in this step. */
434
435         changed |= typestack_merge(deststack,ystack);
436
437         if (!jsrencountered)
438                 return typevector_merge(destloc,yloc,locsize);
439
440         for (yvec=yloc; yvec; yvec=yvec->alt) {
441                 ky = yvec->k;
442
443                 /* Check if the typestates (deststack,destloc) will be
444                  * separable when (ystack,yvec) is added. */
445
446                 if (!typestack_separable_with(deststack,ystack,ky)
447                         && !typevectorset_separable_with(destloc,yvec,locsize))
448                 {
449                         /* No, the resulting set won't be separable, thus we
450                          * may merge all states in (deststack,destloc) and
451                          * (ystack,yvec). */
452
453                         typestack_collapse(deststack);
454                         typevectorset_collapse(destloc,locsize);
455                         typevector_merge(destloc,yvec,locsize);
456                 }
457                 else {
458                         /* Yes, the resulting set will be separable. Thus we check
459                          * if we may merge (ystack,yvec) with a single state in
460                          * (deststack,destloc). */
461                 
462                         for (dvec=destloc,kd=0; dvec; dvec=dvec->alt, kd++) {
463                                 if (!typestack_separable_from(ystack,ky,deststack,kd)
464                                         && !typevector_separable_from(yvec,dvec,locsize))
465                                 {
466                                         /* The typestate (ystack,yvec) is not separable from
467                                          * (deststack,dvec) by any returnAddress. Thus we may
468                                          * merge the states. */
469                                         
470                                         changed |= typevector_merge(dvec,yvec,locsize);
471                                         
472                                         goto merged;
473                                 }
474                         }
475
476                         /* The typestate (ystack,yvec) is separable from all typestates
477                          * (deststack,destloc). Thus we must add this state to the
478                          * result set. */
479
480                         typestack_add(deststack,ystack,ky);
481                         typevectorset_add(destloc,yvec,locsize);
482                         changed = true;
483                 }
484                    
485         merged:
486                 ;
487         }
488         
489         LOG("result:");
490         LOGSTR("dstack: "); DOLOG(typestack_print(get_logfile(),deststack)); LOGNL;
491         LOGSTR("dloc  : "); DOLOG(typevectorset_print(get_logfile(),destloc,locsize)); LOGNL;
492         LOGFLUSH;
493         
494         return changed;
495 }
496
497
498 static bool
499 typestate_reach(methodinfo *m, void *localbuf,
500                                 basicblock *current,
501                                 basicblock *destblock,
502                                 stackptr ystack,typevector *yloc,
503                                 int locsize,bool jsrencountered)
504 {
505         typevector *destloc;
506         int destidx;
507         bool changed = false;
508
509         LOG1("reaching block L%03d",destblock->debug_nr);
510         TYPECHECK_COUNT(stat_reached);
511         
512         destidx = destblock - m->basicblocks;
513         destloc = MGET_TYPEVECTOR(localbuf,destidx,locsize);
514
515         /* When branching backwards we have to check for uninitialized objects */
516         
517         if (destblock <= current) {
518                 stackptr sp;
519                 int i;
520                 
521                 TYPECHECK_COUNT(stat_backwards);
522         LOG("BACKWARDS!");
523         for (sp = ystack; sp; sp=sp->prev)
524             if (sp->type == TYPE_ADR &&
525                 TYPEINFO_IS_NEWOBJECT(sp->typeinfo))
526                 panic("Branching backwards with uninitialized object on stack");
527
528         for (i=0; i<locsize; ++i)
529             if (yloc->td[i].type == TYPE_ADR &&
530                 TYPEINFO_IS_NEWOBJECT(yloc->td[i].info))
531                 panic("Branching backwards with uninitialized object in local variable");
532     }
533         
534         if (destblock->flags == BBTYPECHECK_UNDEF) {
535                 /* The destblock has never been reached before */
536
537                 TYPECHECK_COUNT(stat_copied);
538                 LOG1("block (index %04d) reached first time",destidx);
539                 
540                 typestack_copy(destblock->instack,ystack,yloc);
541                 COPY_TYPEVECTORSET(yloc,destloc,locsize);
542                 changed = true;
543         }
544         else {
545                 /* The destblock has already been reached before */
546                 
547                 TYPECHECK_COUNT(stat_merged);
548                 LOG1("block (index %04d) reached before",destidx);
549                 
550                 changed = typestate_merge(destblock->instack,destloc,
551                                                                   ystack,yloc,locsize,
552                                                                   jsrencountered);
553                 TYPECHECK_COUNTIF(changed,stat_merging_changed);
554         }
555
556         if (changed) {
557                 LOG("changed!");
558                 destblock->flags = BBTYPECHECK_REACHED;
559                 if (destblock <= current) {LOG("REPEAT!"); return true;}
560         }
561         return false;
562 }
563
564
565 static bool
566 typestate_ret(methodinfo *m, void *localbuf,
567                           basicblock *current,
568                           stackptr ystack,typevector *yloc,
569                           int retindex,int locsize)
570 {
571         typevector *yvec;
572         typevector *selected;
573         basicblock *destblock;
574         bool repeat = false;
575
576         for (yvec=yloc; yvec; ) {
577                 if (!TYPEDESC_IS_RETURNADDRESS(yvec->td[retindex]))
578                         panic("Illegal instruction: RET on non-returnAddress");
579
580                 destblock = (basicblock*) TYPEINFO_RETURNADDRESS(yvec->td[retindex].info);
581
582                 selected = typevectorset_select(&yvec,retindex,destblock);
583                 
584                 repeat |= typestate_reach(m, localbuf,current,destblock,
585                                                                   ystack,selected,locsize,true);
586         }
587         return repeat;
588 }
589
590 /****************************************************************************/
591 /* HELPER FUNCTIONS                                                         */
592 /****************************************************************************/
593
594 /* If a field is checked, definingclass == implementingclass */
595 static bool
596 is_accessible(int flags,classinfo *definingclass,classinfo *implementingclass, classinfo *methodclass,
597                           typeinfo *instance)
598 {
599         /* check access rights */
600         if (methodclass != definingclass) {
601                 switch (flags & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED)) {
602                   case ACC_PUBLIC:
603                           break;
604                           
605                           /* In the cases below, definingclass cannot be an interface */
606                           
607                   case 0:
608                           if (definingclass->packagename != methodclass->packagename)
609                                   return false;
610                           break;
611                   case ACC_PROTECTED:
612                           if (definingclass->packagename != methodclass->packagename) {
613                                   if (!builtin_isanysubclass(methodclass,implementingclass))
614                                           return false;
615                                   
616                                   /* For protected access of super class members in another
617                                    * package the instance must be a subclass of or the same
618                                    * as the current class. */
619                                   LOG("protected access into other package");
620                                   implementingclass = methodclass;
621                           }
622                           break;
623                   case ACC_PRIVATE:
624                           if (definingclass != methodclass) {
625                                   LOG("private access");
626                                   return false;
627                           }
628                           break;
629                   default:
630                           panic("Invalid access flags");
631                 }
632         }
633
634         if (instance) {
635                 if ((flags & ACC_STATIC) != 0) {
636                         LOG("accessing STATIC member with instance");
637                         return false;
638                 }
639                 
640                 if (implementingclass
641                         && !TYPEINFO_IS_NULLTYPE(*instance)
642                         && !TYPEINFO_IS_NEWOBJECT(*instance))
643                 {
644                         if (!typeinfo_is_assignable_to_classinfo(instance,
645                                                                                                          implementingclass))
646                         {
647                                 LOG("instance not assignable");
648                                 LOGINFO(instance);
649                                 LOGSTRu(implementingclass->name); LOGNL; LOGFLUSH;
650                                 return false;
651                         }
652                 }
653         }
654         else {
655                 if ((flags & ACC_STATIC) == 0) {
656                         LOG("accessing non-STATIC member without instance");
657                         return false;
658                 }
659         }
660         
661         return true;
662 }
663
664 /****************************************************************************/
665 /* MACROS FOR LOCAL VARIABLE CHECKING                                       */
666 /****************************************************************************/
667
668 #define INDEX_ONEWORD(num)                                                                              \
669         do { if((num)<0 || (num)>=validlocals)                                          \
670                         panic("Invalid local variable index"); } while (0)
671 #define INDEX_TWOWORD(num)                                                                              \
672         do { if((num)<0 || ((num)+1)>=validlocals)                                      \
673                         panic("Invalid local variable index"); } while (0)
674
675 #define STORE_ONEWORD(num,type)                                                                 \
676         do {typevectorset_store(localset,num,type,NULL);} while(0)
677
678 #define STORE_TWOWORD(num,type)                                                                         \
679         do {typevectorset_store_twoword(localset,num,type);} while(0)
680
681 #define CHECK_ONEWORD(num,tp)                                                                                   \
682         do {TYPECHECK_COUNT(stat_ins_primload);                                                         \
683                 if (jsrencountered) {                                                                                   \
684                         if (!typevectorset_checktype(localset,num,tp))                          \
685                                 panic("Variable type mismatch");                                                \
686                 }                                                                                                                               \
687                 else {                                                                                                                  \
688                         if (localset->td[num].type != tp)                                                       \
689                                 panic("Variable type mismatch");                                                \
690                 }                                                                                                                               \
691                 } while(0)
692
693 #define CHECK_TWOWORD(num,type)                                                                                 \
694         do {TYPECHECK_COUNT(stat_ins_primload);                                                         \
695                 if (!typevectorset_checktype(localset,num,type))                \
696             panic("Variable type mismatch");                            \
697                 } while(0)
698
699 /****************************************************************************/
700 /* MACROS FOR STACK TYPE CHECKING                                           */
701 /****************************************************************************/
702
703 /* These macros are for basic typechecks which were not done in stack.c */
704
705 #define TYPECHECK_STACK(sp,tp)                                                          \
706         do { if ((sp)->type != (tp))                                                    \
707                         panic("Wrong data type on stack"); } while(0)
708
709 #define TYPECHECK_ADR(sp)  TYPECHECK_STACK(sp,TYPE_ADR)
710 #define TYPECHECK_INT(sp)  TYPECHECK_STACK(sp,TYPE_INT)
711 #define TYPECHECK_LNG(sp)  TYPECHECK_STACK(sp,TYPE_LNG)
712 #define TYPECHECK_FLT(sp)  TYPECHECK_STACK(sp,TYPE_FLT)
713 #define TYPECHECK_DBL(sp)  TYPECHECK_STACK(sp,TYPE_DBL)
714
715 #define TYPECHECK_ARGS1(t1)                                                                 \
716         do {TYPECHECK_STACK(curstack,t1);} while (0)
717 #define TYPECHECK_ARGS2(t1,t2)                                                      \
718         do {TYPECHECK_ARGS1(t1);                                                                        \
719                 TYPECHECK_STACK(curstack->prev,t2);} while (0)
720 #define TYPECHECK_ARGS3(t1,t2,t3)                                                               \
721         do {TYPECHECK_ARGS2(t1,t2);                                                                     \
722                 TYPECHECK_STACK(curstack->prev->prev,t3);} while (0)
723
724 /****************************************************************************/
725 /* MISC MACROS                                                              */
726 /****************************************************************************/
727
728 #define COPYTYPE(source,dest)   \
729         {if ((source)->type == TYPE_ADR)                                                                \
730                         TYPEINFO_COPY((source)->typeinfo,(dest)->typeinfo);}
731
732 #define ISBUILTIN(v)   (iptr->val.a == (functionptr)(v))
733
734 /* TYPECHECK_REACH: executed, when the target block (tbptr) can be reached
735  *     from the current block (bptr). The types of local variables and
736  *     stack slots are propagated to the target block.
737  * Input:
738  *     bptr.......current block
739  *     tbptr......target block
740  *     dst........current output stack pointer
741  *     numlocals..number of local variables
742  *     localset...current local variable vectorset
743  *     localbuf...local variable vectorset buffer
744  *     jsrencountered...true if a JSR has been seen
745  * Output:
746  *     repeat.....changed to true if a block before the current
747  *                block has changed
748  */
749 #define TYPECHECK_REACH                                                 \
750     do {                                                                \
751     repeat |= typestate_reach(m, localbuf,bptr,tbptr,dst,               \
752                                                           localset,numlocals,jsrencountered);       \
753     LOG("done.");                                                       \
754     } while (0)
755
756 /* TYPECHECK_LEAVE: executed when the method is exited non-abruptly
757  * Input:
758  *     class........class of the current method
759  *     numlocals....number of local variables
760  *     localset.....current local variable vectorset
761  *     initmethod...true if this is an <init> method
762  */
763 #define TYPECHECK_LEAVE                                                 \
764     do {                                                                \
765         if (initmethod && m->class != class_java_lang_Object) {         \
766             /* check the marker variable */                             \
767             LOG("Checking <init> marker");                              \
768             if (!typevectorset_checktype(localset,numlocals-1,TYPE_INT))\
769                 panic("<init> method does not initialize 'this'");      \
770         }                                                               \
771     } while (0)
772
773 /****************************************************************************/
774 /* typecheck()                                                              */
775 /****************************************************************************/
776
777 #define MAXPARAMS 255
778
779 /* typecheck is called directly after analyse_stack */
780
781 methodinfo *typecheck(codegendata *codegendata)
782 {
783     int b_count, b_index;
784     stackptr curstack;      /* input stack top for current instruction */
785     stackptr srcstack;         /* source stack for copying and merging */
786     int opcode;                                      /* current opcode */
787     int i;                                        /* temporary counter */
788     int len;                        /* for counting instructions, etc. */
789     bool superblockend;        /* true if no fallthrough to next block */
790     bool repeat;            /* if true, blocks are iterated over again */
791     instruction *iptr;               /* pointer to current instruction */
792     basicblock *bptr;                /* pointer to current basic block */
793     basicblock *tbptr;                   /* temporary for target block */
794         
795     int numlocals;                        /* number of local variables */
796         int validlocals;         /* number of valid local variable indices */
797         void *localbuf;       /* local variable types for each block start */
798         typevector *localset;        /* typevector set for local variables */
799         typevector *lset;                             /* temporary pointer */
800         typedescriptor *td;                           /* temporary pointer */
801
802         stackptr savedstackbuf = NULL;      /* buffer for saving the stack */
803         stackptr savedstack = NULL;      /* saved instack of current block */
804
805         stackelement excstack;           /* instack for exception handlers */
806                                                                                                           
807         typedescriptor returntype;        /* return type of current method */
808     u1 *ptype;                     /* parameter types of called method */
809     typeinfo *pinfo;           /* parameter typeinfos of called method */
810     int rtype;                         /* return type of called method */
811     typeinfo rinfo;       /* typeinfo for return type of called method */
812         
813     stackptr dst;               /* output stack of current instruction */
814     basicblock **tptr;    /* pointer into target list of switch instr. */
815     exceptiontable **handlers;            /* active exception handlers */
816     classinfo *cls;                                       /* temporary */
817     bool maythrow;               /* true if this instruction may throw */
818     static utf *name_init;                                 /* "<init>" */
819     bool initmethod;             /* true if this is an "<init>" method */
820         builtin_descriptor *builtindesc;    /* temp. descriptor of builtin */
821         bool jsrencountered = false;         /* true if we there was a JSR */
822
823     classinfo *myclass;
824     methodinfo *m=codegendata->method;
825
826 #ifdef TYPECHECK_STATISTICS
827         int count_iterations = 0;
828         TYPECHECK_COUNT(stat_typechecked);
829         TYPECHECK_COUNT_FREQ(stat_locals,m->maxlocals,STAT_LOCALS);
830         TYPECHECK_COUNT_FREQ(stat_blocks,m->basicblockcount/10,STAT_BLOCKS);
831 #endif
832
833     LOGSTR("\n==============================================================================\n");
834     DOLOG(show_icmd_method());
835     LOGSTR("\n==============================================================================\n");
836     LOGimpSTR("Entering typecheck: ");
837     LOGimpSTRu(method->name);
838     LOGimpSTR("    ");
839     LOGimpSTRu(method->descriptor);
840     LOGimpSTR("    (class ");
841     LOGimpSTRu(method->class->name);
842     LOGimpSTR(")\n");
843         LOGFLUSH;
844
845         if (!name_init)
846                 name_init = utf_new_char("<init>");
847     initmethod = (m->name == name_init);
848
849         /* Allocate buffer for method arguments */
850         
851     ptype = DMNEW(u1,MAXPARAMS);
852     pinfo = DMNEW(typeinfo,MAXPARAMS);
853     
854     LOG("Buffer allocated.\n");
855
856     /* reset all BBFINISHED blocks to BBTYPECHECK_UNDEF. */
857     b_count = m->basicblockcount;
858     bptr = m->basicblocks;
859     while (--b_count >= 0) {
860 #ifdef TYPECHECK_DEBUG
861         if (bptr->flags != BBFINISHED && bptr->flags != BBDELETED
862             && bptr->flags != BBUNDEF)
863         {
864             show_icmd_method();
865             LOGSTR1("block flags: %d\n",bptr->flags); LOGFLUSH;
866             panic("Internal error: Unexpected block flags in typecheck()");
867         }
868 #endif
869         if (bptr->flags >= BBFINISHED) {
870             bptr->flags = BBTYPECHECK_UNDEF;
871         }
872         bptr++;
873     }
874
875     /* The first block is always reached */
876     if (m->basicblockcount && m->basicblocks[0].flags == BBTYPECHECK_UNDEF)
877         m->basicblocks[0].flags = BBTYPECHECK_REACHED;
878
879     LOG("Blocks reset.\n");
880
881     /* number of local variables */
882     
883     /* In <init> methods we use an extra local variable to signal if
884      * the 'this' reference has been initialized. */
885     numlocals = m->maxlocals;
886         validlocals = numlocals;
887     if (initmethod) numlocals++;
888
889     /* allocate the buffers for local variables */
890         localbuf = DMNEW_TYPEVECTOR(m->basicblockcount+1, numlocals);
891         localset = MGET_TYPEVECTOR(localbuf,m->basicblockcount,numlocals);
892
893     LOG("Variable buffer allocated.\n");
894
895     /* allocate the buffer of active exception handlers */
896     handlers = DMNEW(exceptiontable*, codegendata->exceptiontablelength + 1);
897
898     /* initialize the variable types of the first block */
899     /* to the types of the arguments */
900         lset = MGET_TYPEVECTOR(localbuf,0,numlocals);
901         lset->k = 0;
902         lset->alt = NULL;
903         td = lset->td;
904         i = validlocals;
905
906     /* if this is an instance method initialize the "this" ref type */
907     if (!(m->flags & ACC_STATIC)) {
908                 if (!i)
909                         panic("Not enough local variables for method arguments");
910         td->type = TYPE_ADDRESS;
911         if (initmethod)
912             TYPEINFO_INIT_NEWOBJECT(td->info,NULL);
913         else
914             TYPEINFO_INIT_CLASSINFO(td->info, m->class);
915         td++;
916                 i--;
917     }
918
919     LOG("'this' argument set.\n");
920
921     /* the rest of the arguments and the return type */
922     i = typedescriptors_init_from_method_args(td, m->descriptor,
923                                                                                           i,
924                                                                                           true, /* two word types use two slots */
925                                                                                           &returntype);
926         td += i;
927         i = numlocals - (td - lset->td);
928         while (i--) {
929                 td->type = TYPE_VOID;
930                 td++;
931         }
932
933     LOG("Arguments set.\n");
934
935     /* initialize the input stack of exception handlers */
936         excstack.prev = NULL;
937         excstack.type = TYPE_ADR;
938         TYPEINFO_INIT_CLASSINFO(excstack.typeinfo,
939                                                         class_java_lang_Throwable); /* changed later */
940
941     LOG("Exception handler stacks set.\n");
942
943     /* loop while there are still blocks to be checked */
944     do {
945                 TYPECHECK_COUNT(count_iterations);
946
947         repeat = false;
948         
949         b_count = m->basicblockcount;
950         bptr = m->basicblocks;
951
952         while (--b_count >= 0) {
953             LOGSTR1("---- BLOCK %04d, ",bptr-block);
954             LOGSTR1("blockflags: %d\n",bptr->flags);
955             LOGFLUSH;
956                 
957             if (bptr->flags == BBTYPECHECK_REACHED) {
958                 LOGSTR1("\n---- BLOCK %04d ------------------------------------------------\n",bptr-block);
959                 LOGFLUSH;
960                 
961                 superblockend = false;
962                 bptr->flags = BBFINISHED;
963                 b_index = bptr - m->basicblocks;
964
965                 /* init stack at the start of this block */
966                 curstack = bptr->instack;
967                                         
968                 /* determine the active exception handlers for this block */
969                 /* XXX could use a faster algorithm with sorted lists or
970                  * something? */
971                 len = 0;
972                 for (i = 0; i < codegendata->exceptiontablelength; ++i) {
973                     if ((codegendata->exceptiontable[i].start <= bptr) && (codegendata->exceptiontable[i].end > bptr)) {
974                         LOG1("active handler L%03d", codegendata->exceptiontable[i].handler->debug_nr);
975                         handlers[len++] = codegendata->exceptiontable + i;
976                     }
977                 }
978                 handlers[len] = NULL;
979                                         
980                 /* init variable types at the start of this block */
981                                 COPY_TYPEVECTORSET(MGET_TYPEVECTOR(localbuf,b_index,numlocals),
982                                                                    localset,numlocals);
983                                 if (handlers[0])
984                                         for (i=0; i<numlocals; ++i)
985                                                 if (localset->td[i].type == TYPE_ADR
986                                                         && TYPEINFO_IS_NEWOBJECT(localset->td[i].info))
987                                                         panic("Uninitialized object in local variable inside try block");
988
989                                 DOLOG(typestate_print(get_logfile(),curstack,localset,numlocals));
990                                 LOGNL; LOGFLUSH;
991
992                 /* loop over the instructions */
993                 len = bptr->icount;
994                 iptr = bptr->iinstr;
995                 while (--len >= 0)  {
996                                         TYPECHECK_COUNT(stat_ins);
997                     DOLOG(show_icmd(iptr,false)); LOGNL; LOGFLUSH;
998                         
999                     opcode = iptr->opc;
1000                     myclass = iptr->method->class;
1001                     dst = iptr->dst;
1002                     maythrow = false;
1003                                                 
1004                     switch (opcode) {
1005
1006                         /****************************************/
1007                         /* STACK MANIPULATIONS                  */
1008
1009                         /* We just need to copy the typeinfo */
1010                         /* for slots containing addresses.   */
1011
1012                         /* XXX We assume that the destination stack
1013                          * slots were continuously allocated in
1014                          * memory.  (The current implementation in
1015                          * stack.c)
1016                          */
1017
1018                       case ICMD_DUP:
1019                           COPYTYPE(curstack,dst);
1020                           break;
1021                                                           
1022                       case ICMD_DUP_X1:
1023                           COPYTYPE(curstack,dst);
1024                           COPYTYPE(curstack,dst-2);
1025                           COPYTYPE(curstack->prev,dst-1);
1026                           break;
1027                                                           
1028                       case ICMD_DUP_X2:
1029                           COPYTYPE(curstack,dst);
1030                           COPYTYPE(curstack,dst-3);
1031                           COPYTYPE(curstack->prev,dst-1);
1032                           COPYTYPE(curstack->prev->prev,dst-2);
1033                           break;
1034                                                           
1035                       case ICMD_DUP2:
1036                           COPYTYPE(curstack,dst);
1037                           COPYTYPE(curstack->prev,dst-1);
1038                           break;
1039
1040                       case ICMD_DUP2_X1:
1041                           COPYTYPE(curstack,dst);
1042                           COPYTYPE(curstack->prev,dst-1);
1043                           COPYTYPE(curstack,dst-3);
1044                           COPYTYPE(curstack->prev,dst-4);
1045                           COPYTYPE(curstack->prev->prev,dst-2);
1046                           break;
1047                                                           
1048                       case ICMD_DUP2_X2:
1049                           COPYTYPE(curstack,dst);
1050                           COPYTYPE(curstack->prev,dst-1);
1051                           COPYTYPE(curstack,dst-4);
1052                           COPYTYPE(curstack->prev,dst-5);
1053                           COPYTYPE(curstack->prev->prev,dst-2);
1054                           COPYTYPE(curstack->prev->prev->prev,dst-3);
1055                           break;
1056                                                           
1057                       case ICMD_SWAP:
1058                           COPYTYPE(curstack,dst-1);
1059                           COPYTYPE(curstack->prev,dst);
1060                           break;
1061
1062                           /****************************************/
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072                           /* PRIMITIVE VARIABLE ACCESS            */
1073
1074                       case ICMD_ILOAD: CHECK_ONEWORD(iptr->op1,TYPE_INT); break;
1075                       case ICMD_FLOAD: CHECK_ONEWORD(iptr->op1,TYPE_FLOAT); break;
1076                       case ICMD_IINC:  CHECK_ONEWORD(iptr->op1,TYPE_INT); break;
1077                       case ICMD_LLOAD: CHECK_TWOWORD(iptr->op1,TYPE_LONG); break;
1078                       case ICMD_DLOAD: CHECK_TWOWORD(iptr->op1,TYPE_DOUBLE); break;
1079                           
1080                       case ICMD_FSTORE: STORE_ONEWORD(iptr->op1,TYPE_FLOAT); break;
1081                       case ICMD_ISTORE: STORE_ONEWORD(iptr->op1,TYPE_INT); break;
1082                       case ICMD_LSTORE: STORE_TWOWORD(iptr->op1,TYPE_LONG); break;
1083                       case ICMD_DSTORE: STORE_TWOWORD(iptr->op1,TYPE_DOUBLE); break;
1084                           
1085                           /****************************************/
1086                           /* LOADING ADDRESS FROM VARIABLE        */
1087
1088                       case ICMD_ALOAD:
1089                                                   TYPECHECK_COUNT(stat_ins_aload);
1090                           
1091                           /* loading a returnAddress is not allowed */
1092                                                   if (jsrencountered) {
1093                                                           if (!typevectorset_checkreference(localset,iptr->op1))
1094                                                                   panic("illegal instruction: ALOAD loading non-reference");
1095
1096                                                           typevectorset_copymergedtype(localset,iptr->op1,&(dst->typeinfo));
1097                                                   }
1098                                                   else {
1099                                                           if (!TYPEDESC_IS_REFERENCE(localset->td[iptr->op1]))
1100                                                                   panic("illegal instruction: ALOAD loading non-reference");
1101                                                           TYPEINFO_COPY(localset->td[iptr->op1].info,dst->typeinfo);
1102                                                   }
1103                           break;
1104                                                         
1105                           /****************************************/
1106                           /* STORING ADDRESS TO VARIABLE          */
1107
1108                       case ICMD_ASTORE:
1109                           if (handlers[0] &&
1110                               TYPEINFO_IS_NEWOBJECT(curstack->typeinfo))
1111                               panic("Storing uninitialized object in local variable inside try block");
1112
1113                                                   if (TYPESTACK_IS_RETURNADDRESS(curstack))
1114                                                           typevectorset_store_retaddr(localset,iptr->op1,&(curstack->typeinfo));
1115                                                   else
1116                                                           typevectorset_store(localset,iptr->op1,TYPE_ADDRESS,
1117                                                                                                   &(curstack->typeinfo));
1118                           break;
1119                           
1120                           /****************************************/
1121                           /* LOADING ADDRESS FROM ARRAY           */
1122
1123                       case ICMD_AALOAD:
1124                           if (!TYPEINFO_MAYBE_ARRAY_OF_REFS(curstack->prev->typeinfo))
1125                               panic("illegal instruction: AALOAD on non-reference array");
1126
1127                           typeinfo_init_component(&curstack->prev->typeinfo,&dst->typeinfo);
1128                           maythrow = true;
1129                           break;
1130                                                           
1131                           /****************************************/
1132                           /* FIELD ACCESS                         */
1133
1134                       case ICMD_PUTFIELD:
1135                                                   TYPECHECK_COUNT(stat_ins_field);
1136                           if (!TYPEINFO_IS_REFERENCE(curstack->prev->typeinfo))
1137                               panic("illegal instruction: PUTFIELD on non-reference");
1138                           if (TYPEINFO_IS_ARRAY(curstack->prev->typeinfo))
1139                               panic("illegal instruction: PUTFIELD on array");
1140
1141                           /* check if the value is assignable to the field */
1142                                                   {
1143                                                           fieldinfo *fi = (fieldinfo*) iptr[0].val.a;
1144
1145                                                           if (TYPEINFO_IS_NEWOBJECT(curstack->prev->typeinfo)) {
1146                                                                   if (initmethod
1147                                                                           && !TYPEINFO_NEWOBJECT_INSTRUCTION(curstack->prev->typeinfo))
1148                                                                   {
1149                                                                           /* uninitialized "this" instance */
1150                                                                           if (fi->class != m->class || (fi->flags & ACC_STATIC) != 0)
1151                                                                                   panic("Setting unaccessible field in uninitialized object");
1152                                                                   }
1153                                                                   else {
1154                                                                           panic("PUTFIELD on uninitialized object");
1155                                                                   }
1156                                                           }
1157                                                           else {
1158                                                                   if (!is_accessible(fi->flags,fi->class,fi->class, myclass,
1159                                                                                                          &(curstack->prev->typeinfo)))
1160                                                                           panic("PUTFIELD: field is not accessible");
1161                                                           }
1162
1163                                                           if (curstack->type != fi->type)
1164                                                                   panic("PUTFIELD type mismatch");
1165                                                           if (fi->type == TYPE_ADR) {
1166                                                                   TYPEINFO_INIT_FROM_FIELDINFO(rinfo,fi);
1167                                                                   if (!typeinfo_is_assignable(&(curstack->typeinfo),
1168                                                                                                                           &rinfo))
1169                                                                           panic("PUTFIELD reference type not assignable");
1170                                                           }
1171                                                   }
1172                           maythrow = true;
1173                           break;
1174
1175                       case ICMD_PUTSTATIC:
1176                                                   TYPECHECK_COUNT(stat_ins_field);
1177                           /* check if the value is assignable to the field */
1178                                                   {
1179                                                           fieldinfo *fi = (fieldinfo*) iptr[0].val.a;
1180
1181                                                           if (!is_accessible(fi->flags,fi->class,fi->class,myclass,NULL))
1182                                                                   panic("PUTSTATIC: field is not accessible");
1183
1184                                                           if (curstack->type != fi->type)
1185                                                                   panic("PUTSTATIC type mismatch");
1186                                                           if (fi->type == TYPE_ADR) {
1187                                                                   TYPEINFO_INIT_FROM_FIELDINFO(rinfo,fi);
1188                                                                   if (!typeinfo_is_assignable(&(curstack->typeinfo),
1189                                                                                                                           &rinfo))
1190                                                                           panic("PUTSTATIC reference type not assignable");
1191                                                           }
1192                                                   }
1193                           maythrow = true;
1194                           break;
1195
1196                       case ICMD_GETFIELD:
1197                                                   TYPECHECK_COUNT(stat_ins_field);
1198                           if (!TYPEINFO_IS_REFERENCE(curstack->typeinfo))
1199                               panic("illegal instruction: GETFIELD on non-reference");
1200                           if (TYPEINFO_IS_ARRAY(curstack->typeinfo))
1201                               panic("illegal instruction: GETFIELD on array");
1202                           
1203                           {
1204                               fieldinfo *fi = (fieldinfo *)(iptr->val.a);
1205
1206                                                           if (!is_accessible(fi->flags,fi->class,fi->class,myclass,
1207                                                                                                  &(curstack->typeinfo)))
1208                                                                   panic("GETFIELD: field is not accessible");
1209                                                           
1210                               if (dst->type == TYPE_ADR) {
1211                                   TYPEINFO_INIT_FROM_FIELDINFO(dst->typeinfo,fi);
1212                               }
1213                           }
1214                           maythrow = true;
1215                           break;
1216
1217                       case ICMD_GETSTATIC:
1218                                                   TYPECHECK_COUNT(stat_ins_field);
1219                           {
1220                               fieldinfo *fi = (fieldinfo *)(iptr->val.a);
1221                                                           
1222                                                           if (!is_accessible(fi->flags,fi->class,fi->class,myclass,NULL)) {
1223                                                                 printf("---------\n");
1224                                                                   utf_display(fi->class->name);
1225                                                                 printf("\n");
1226                                                                   utf_display(myclass->name);
1227                                                                 printf("\n");
1228
1229
1230                                                                   panic("GETSTATIC: field is not accessible");
1231                                                         }
1232
1233                               if (dst->type == TYPE_ADR) {
1234                                   TYPEINFO_INIT_FROM_FIELDINFO(dst->typeinfo,fi);
1235                               }
1236                           }
1237                           maythrow = true;
1238                           break;
1239
1240                           /****************************************/
1241                           /* PRIMITIVE ARRAY ACCESS               */
1242
1243                       case ICMD_ARRAYLENGTH:
1244                           if (!TYPEINFO_MAYBE_ARRAY(curstack->typeinfo)
1245                                                           && curstack->typeinfo.typeclass != pseudo_class_Arraystub)
1246                               panic("illegal instruction: ARRAYLENGTH on non-array");
1247                           maythrow = true;
1248                           break;
1249
1250                       case ICMD_BALOAD:
1251                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo,ARRAYTYPE_BOOLEAN)
1252                               && !TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo,ARRAYTYPE_BYTE))
1253                               panic("Array type mismatch");
1254                           maythrow = true;
1255                           break;
1256                       case ICMD_CALOAD:
1257                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo,ARRAYTYPE_CHAR))
1258                               panic("Array type mismatch");
1259                           maythrow = true;
1260                           break;
1261                       case ICMD_DALOAD:
1262                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo,ARRAYTYPE_DOUBLE))
1263                               panic("Array type mismatch");
1264                           maythrow = true;
1265                           break;
1266                       case ICMD_FALOAD:
1267                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo,ARRAYTYPE_FLOAT))
1268                               panic("Array type mismatch");
1269                           maythrow = true;
1270                           break;
1271                       case ICMD_IALOAD:
1272                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo,ARRAYTYPE_INT))
1273                               panic("Array type mismatch");
1274                           maythrow = true;
1275                           break;
1276                       case ICMD_SALOAD:
1277                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo,ARRAYTYPE_SHORT))
1278                               panic("Array type mismatch");
1279                           maythrow = true;
1280                           break;
1281                       case ICMD_LALOAD:
1282                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo,ARRAYTYPE_LONG))
1283                               panic("Array type mismatch");
1284                           maythrow = true;
1285                           break;
1286
1287                       case ICMD_BASTORE:
1288                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->prev->typeinfo,ARRAYTYPE_BOOLEAN)
1289                               && !TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->prev->typeinfo,ARRAYTYPE_BYTE))
1290                               panic("Array type mismatch");
1291                           maythrow = true;
1292                           break;
1293                       case ICMD_CASTORE:
1294                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->prev->typeinfo,ARRAYTYPE_CHAR))
1295                               panic("Array type mismatch");
1296                           maythrow = true;
1297                           break;
1298                       case ICMD_DASTORE:
1299                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->prev->typeinfo,ARRAYTYPE_DOUBLE))
1300                               panic("Array type mismatch");
1301                           maythrow = true;
1302                           break;
1303                       case ICMD_FASTORE:
1304                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->prev->typeinfo,ARRAYTYPE_FLOAT))
1305                               panic("Array type mismatch");
1306                           maythrow = true;
1307                           break;
1308                       case ICMD_IASTORE:
1309                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->prev->typeinfo,ARRAYTYPE_INT))
1310                               panic("Array type mismatch");
1311                           maythrow = true;
1312                           break;
1313                       case ICMD_SASTORE:
1314                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->prev->typeinfo,ARRAYTYPE_SHORT))
1315                               panic("Array type mismatch");
1316                           maythrow = true;
1317                           break;
1318                       case ICMD_LASTORE:
1319                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->prev->typeinfo,ARRAYTYPE_LONG))
1320                               panic("Array type mismatch");
1321                           maythrow = true;
1322                           break;
1323
1324                       case ICMD_IASTORECONST:
1325                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo, ARRAYTYPE_INT))
1326                               panic("Array type mismatch");
1327                           maythrow = true;
1328                           break;
1329
1330                       case ICMD_LASTORECONST:
1331                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo, ARRAYTYPE_LONG))
1332                               panic("Array type mismatch");
1333                           maythrow = true;
1334                           break;
1335
1336                       case ICMD_BASTORECONST:
1337                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo, ARRAYTYPE_BOOLEAN)
1338                               && !TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo, ARRAYTYPE_BYTE))
1339                               panic("Array type mismatch");
1340                           maythrow = true;
1341                           break;
1342
1343                       case ICMD_CASTORECONST:
1344                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo, ARRAYTYPE_CHAR))
1345                               panic("Array type mismatch");
1346                           maythrow = true;
1347                           break;
1348
1349                       case ICMD_SASTORECONST:
1350                           if (!TYPEINFO_MAYBE_PRIMITIVE_ARRAY(curstack->prev->typeinfo, ARRAYTYPE_SHORT))
1351                               panic("Array type mismatch");
1352                           maythrow = true;
1353                           break;
1354
1355
1356                           /****************************************/
1357                           /* ADDRESS CONSTANTS                    */
1358
1359                       case ICMD_ACONST:
1360                           if (iptr->val.a == NULL)
1361                               TYPEINFO_INIT_NULLTYPE(dst->typeinfo);
1362                           else
1363                               /* string constants (or constant for builtin function) */
1364                               TYPEINFO_INIT_CLASSINFO(dst->typeinfo,class_java_lang_String);
1365                           break;
1366
1367                           /****************************************/
1368                           /* CHECKCAST AND INSTANCEOF             */
1369
1370                       case ICMD_CHECKCAST:
1371                                                   TYPECHECK_ADR(curstack);
1372                           /* returnAddress is not allowed */
1373                           if (!TYPEINFO_IS_REFERENCE(curstack->typeinfo))
1374                               panic("Illegal instruction: CHECKCAST on non-reference");
1375
1376                           TYPEINFO_INIT_CLASSINFO(dst->typeinfo,(classinfo *)iptr[0].val.a);
1377                           maythrow = true;
1378                           break;
1379
1380                       case ICMD_INSTANCEOF:
1381                                                   TYPECHECK_ADR(curstack);
1382                           /* returnAddress is not allowed */
1383                           if (!TYPEINFO_IS_REFERENCE(curstack->typeinfo))
1384                               panic("Illegal instruction: INSTANCEOF on non-reference");
1385                           break;
1386                           
1387                           /****************************************/
1388                           /* BRANCH INSTRUCTIONS                  */
1389
1390                       case ICMD_GOTO:
1391                           superblockend = true;
1392                           /* FALLTHROUGH! */
1393                       case ICMD_IFNULL:
1394                       case ICMD_IFNONNULL:
1395                       case ICMD_IFEQ:
1396                       case ICMD_IFNE:
1397                       case ICMD_IFLT:
1398                       case ICMD_IFGE:
1399                       case ICMD_IFGT:
1400                       case ICMD_IFLE:
1401                       case ICMD_IF_ICMPEQ:
1402                       case ICMD_IF_ICMPNE:
1403                       case ICMD_IF_ICMPLT:
1404                       case ICMD_IF_ICMPGE:
1405                       case ICMD_IF_ICMPGT:
1406                       case ICMD_IF_ICMPLE:
1407                       case ICMD_IF_ACMPEQ:
1408                       case ICMD_IF_ACMPNE:
1409                       case ICMD_IF_LEQ:
1410                       case ICMD_IF_LNE:
1411                       case ICMD_IF_LLT:
1412                       case ICMD_IF_LGE:
1413                       case ICMD_IF_LGT:
1414                       case ICMD_IF_LLE:
1415                       case ICMD_IF_LCMPEQ:
1416                       case ICMD_IF_LCMPNE:
1417                       case ICMD_IF_LCMPLT:
1418                       case ICMD_IF_LCMPGE:
1419                       case ICMD_IF_LCMPGT:
1420                       case ICMD_IF_LCMPLE:
1421                                                   TYPECHECK_COUNT(stat_ins_branch);
1422                           tbptr = (basicblock *) iptr->target;
1423
1424                           /* propagate stack and variables to the target block */
1425                           TYPECHECK_REACH;
1426                           break;
1427
1428                           /****************************************/
1429                           /* SWITCHES                             */
1430                           
1431                       case ICMD_TABLESWITCH:
1432                                                   TYPECHECK_COUNT(stat_ins_switch);
1433                           {
1434                               s4 *s4ptr = iptr->val.a;
1435                               s4ptr++;              /* skip default */
1436                               i = *s4ptr++;         /* low */
1437                               i = *s4ptr++ - i + 2; /* +1 for default target */
1438                           }
1439                           goto switch_instruction_tail;
1440                           
1441                       case ICMD_LOOKUPSWITCH:
1442                                                   TYPECHECK_COUNT(stat_ins_switch);
1443                           {
1444                               s4 *s4ptr = iptr->val.a;
1445                               s4ptr++;              /* skip default */
1446                               i = *s4ptr++ + 1;     /* count +1 for default */
1447                           }
1448                     switch_instruction_tail:
1449                           tptr = (basicblock **)iptr->target;
1450                           
1451                           while (--i >= 0) {
1452                               tbptr = *tptr++;
1453                               LOG2("target %d is block %04d",(tptr-(basicblock **)iptr->target)-1,tbptr-block);
1454                               TYPECHECK_REACH;
1455                           }
1456                           LOG("switch done");
1457                           superblockend = true;
1458                           break;
1459
1460                           /****************************************/
1461                           /* RETURNS AND THROW                    */
1462
1463                       case ICMD_ATHROW:
1464                           if (!typeinfo_is_assignable_to_classinfo(
1465                                    &curstack->typeinfo,class_java_lang_Throwable))
1466                               panic("illegal instruction: ATHROW on non-Throwable");
1467                           superblockend = true;
1468                           maythrow = true;
1469                           break;
1470
1471                       case ICMD_ARETURN:
1472                           if (!TYPEINFO_IS_REFERENCE(curstack->typeinfo))
1473                               panic("illegal instruction: ARETURN on non-reference");
1474
1475                           if (returntype.type != TYPE_ADDRESS
1476                               || !typeinfo_is_assignable(&curstack->typeinfo,&(returntype.info)))
1477                               panic("Return type mismatch");
1478                                                   goto return_tail;
1479                                                   
1480                       case ICMD_IRETURN:
1481                           if (returntype.type != TYPE_INT) panic("Return type mismatch");
1482                                                   goto return_tail;
1483                                                   
1484                       case ICMD_LRETURN:
1485                           if (returntype.type != TYPE_LONG) panic("Return type mismatch");
1486                                                   goto return_tail;
1487                                                   
1488                       case ICMD_FRETURN:
1489                           if (returntype.type != TYPE_FLOAT) panic("Return type mismatch");
1490                                                   goto return_tail;
1491                                                   
1492                       case ICMD_DRETURN:
1493                           if (returntype.type != TYPE_DOUBLE) panic("Return type mismatch");
1494                                                   goto return_tail;
1495                                                   
1496                       case ICMD_RETURN:
1497                           if (returntype.type != TYPE_VOID) panic("Return type mismatch");
1498                                           return_tail:
1499                           TYPECHECK_LEAVE;
1500                           superblockend = true;
1501                           maythrow = true;
1502                           break;
1503                                                     
1504                           /****************************************/
1505                           /* SUBROUTINE INSTRUCTIONS              */
1506
1507                       case ICMD_JSR:
1508                           LOG("jsr");
1509                                                   jsrencountered = true;
1510
1511                           /* This is a dirty hack. It is needed
1512                            * because of the special handling of
1513                            * ICMD_JSR in stack.c
1514                            */
1515                           dst = (stackptr) iptr->val.a;
1516                           
1517                           tbptr = (basicblock *) iptr->target;
1518                                                   if (bptr + 1 == (m->basicblocks + m->basicblockcount + 1))
1519                                                           panic("Illegal instruction: JSR at end of bytecode");
1520                                                   typestack_put_retaddr(dst,bptr+1,localset);
1521                                                   repeat |= typestate_reach(m, localbuf,bptr,tbptr,dst,
1522                                                                                                         localset,numlocals,true);
1523
1524                                                   superblockend = true;
1525                           break;
1526                           
1527                       case ICMD_RET:
1528                           /* check returnAddress variable */
1529                                                   if (!typevectorset_checkretaddr(localset,iptr->op1))
1530                               panic("illegal instruction: RET using non-returnAddress variable");
1531
1532                                                   repeat |= typestate_ret(m, localbuf,bptr,curstack,
1533                                                                                                   localset,iptr->op1,numlocals);
1534
1535                           superblockend = true;
1536                           break;
1537                                                           
1538                           /****************************************/
1539                           /* INVOKATIONS                          */
1540
1541                       case ICMD_INVOKEVIRTUAL:
1542                       case ICMD_INVOKESPECIAL:
1543                       case ICMD_INVOKESTATIC:
1544                       case ICMD_INVOKEINTERFACE:
1545                                                   TYPECHECK_COUNT(stat_ins_invoke);
1546                           {
1547                               methodinfo *mi = (methodinfo*) iptr->val.a;
1548                                                           bool specialmethod = (mi->name->text[0] == '<');
1549                               bool callinginit = (opcode == ICMD_INVOKESPECIAL && mi->name == name_init);
1550                               instruction *ins;
1551                               classinfo *initclass;
1552
1553                                                           if (specialmethod && !callinginit)
1554                                                                   panic("Invalid invocation of special method");
1555
1556                                                           if (opcode == ICMD_INVOKESPECIAL) {
1557                                                                   /* XXX for INVOKESPECIAL: check if the invokation is done at all */
1558                                                                   
1559                                                                   /* (If callinginit the class is checked later.) */
1560                                                                   if (!callinginit) { 
1561                                                                           if (!builtin_isanysubclass(myclass,mi->class)) 
1562                                                                                   panic("Illegal instruction: INVOKESPECIAL calling non-superclass method"); 
1563                                                                   } 
1564                                                           }
1565
1566                               /* fetch parameter types and return type */
1567                               i = 0;
1568                               if (opcode != ICMD_INVOKESTATIC) {
1569                                   ptype[0] = TYPE_ADR;
1570                                   TYPEINFO_INIT_CLASSINFO(pinfo[0],mi->class);
1571                                   i++;
1572                               }
1573                               typeinfo_init_from_method_args(mi->descriptor,ptype+i,pinfo+i,
1574                                                              MAXPARAMS-i,false,
1575                                                              &rtype,&rinfo);
1576
1577                               /* check parameter types */
1578                               srcstack = curstack;
1579                               i = mi->paramcount; /* number of parameters including 'this'*/
1580                               while (--i >= 0) {
1581                                   LOG1("param %d",i);
1582                                   if (srcstack->type != ptype[i])
1583                                       panic("Parameter type mismatch in method invocation");
1584                                   if (srcstack->type == TYPE_ADR) {
1585                                       LOGINFO(&(srcstack->typeinfo));
1586                                       LOGINFO(pinfo + i);
1587                                       if (i==0 && callinginit)
1588                                       {
1589                                           /* first argument to <init> method */
1590                                           if (!TYPEINFO_IS_NEWOBJECT(srcstack->typeinfo))
1591                                               panic("Calling <init> on initialized object");
1592                                           
1593                                           /* get the address of the NEW instruction */
1594                                           LOGINFO(&(srcstack->typeinfo));
1595                                           ins = (instruction*)TYPEINFO_NEWOBJECT_INSTRUCTION(srcstack->typeinfo);
1596                                           initclass = (ins) ? (classinfo*)ins[-1].val.a : m->class;
1597                                           LOGSTR("class: "); LOGSTRu(initclass->name); LOGNL;
1598
1599                                                                                   /* check type */
1600                                                                                   /* (This is checked below.) */
1601 /*                                                                                TYPEINFO_INIT_CLASSINFO(tempinfo,initclass); */
1602 /*                                           if (!typeinfo_is_assignable(&tempinfo,pinfo+0)) */
1603 /*                                               panic("Parameter reference type mismatch in <init> invocation"); */
1604                                       }
1605                                       else {
1606                                           if (!typeinfo_is_assignable(&(srcstack->typeinfo),pinfo+i))
1607                                               panic("Parameter reference type mismatch in method invocation");
1608                                       }
1609                                   }
1610                                   LOG("ok");
1611
1612                                   if (i) srcstack = srcstack->prev;
1613                               }
1614
1615                                                           /* XXX We should resolve the method and pass its
1616                                                            * class as implementingclass to is_accessible. */
1617                                                           if (!is_accessible(mi->flags,mi->class,NULL, myclass,
1618                                                                                                  (opcode == ICMD_INVOKESTATIC) ? NULL
1619                                                                                                  : &(srcstack->typeinfo)))
1620                                                                   panic("Invoking unaccessible method");
1621
1622                                                           LOG("checking return type");
1623                               if (rtype != TYPE_VOID) {
1624                                   if (rtype != dst->type)
1625                                       panic("Return type mismatch in method invocation");
1626                                   TYPEINFO_COPY(rinfo,dst->typeinfo);
1627                               }
1628
1629                               if (callinginit) {
1630                                                                   LOG("replacing uninitialized object");
1631                                   /* replace uninitialized object type on stack */
1632                                   srcstack = dst;
1633                                   while (srcstack) {
1634                                       if (srcstack->type == TYPE_ADR
1635                                           && TYPEINFO_IS_NEWOBJECT(srcstack->typeinfo)
1636                                           && TYPEINFO_NEWOBJECT_INSTRUCTION(srcstack->typeinfo) == ins)
1637                                       {
1638                                           LOG("replacing uninitialized type on stack");
1639
1640                                                                                   /* If this stackslot is in the instack of
1641                                                                                    * this basic block we must save the type(s)
1642                                                                                    * we are going to replace.
1643                                                                                    */
1644                                                                                   if (srcstack <= bptr->instack && !savedstack)
1645                                                                                   {
1646                                                                                           stackptr sp;
1647                                                                                           stackptr copy;
1648                                                                                           LOG("saving input stack types");
1649                                                                                           if (!savedstackbuf) {
1650                                                                                                   LOG("allocating savedstack buffer");
1651                                                                                                   savedstackbuf = DMNEW(stackelement,m->maxstack);
1652                                                                                                   savedstackbuf->prev = NULL;
1653                                                                                                   for (i=1; i<m->maxstack; ++i)
1654                                                                                                           savedstackbuf[i].prev = savedstackbuf+(i-1);
1655                                                                                           }
1656                                                                                           sp = savedstack = bptr->instack;
1657                                                                                           copy = bptr->instack = savedstackbuf + (bptr->indepth-1);
1658                                                                                           TYPESTACK_COPY(sp,copy);
1659                                                                                   }
1660                                                                                   
1661                                           TYPEINFO_INIT_CLASSINFO(srcstack->typeinfo,initclass);
1662                                       }
1663                                       srcstack = srcstack->prev;
1664                                   }
1665                                   /* replace uninitialized object type in locals */
1666                                                                   typevectorset_init_object(localset,ins,initclass,numlocals);
1667
1668                                   /* initializing the 'this' reference? */
1669                                   if (!ins) {
1670 #ifdef TYPECHECK_DEBUG
1671                                                                           if (!initmethod)
1672                                                                                   panic("Internal error: calling <init> on this in non-<init> method.");
1673 #endif
1674                                                                           /* must be <init> of current class or direct superclass */
1675                                                                           if (mi->class != m->class && mi->class != m->class->super)
1676                                                                                   panic("<init> calling <init> of the wrong class");
1677                                                                           
1678                                       /* set our marker variable to type int */
1679                                       LOG("setting <init> marker");
1680                                                                           typevectorset_store(localset,numlocals-1,TYPE_INT,NULL);
1681                                   }
1682                                                                   else {
1683                                                                           /* initializing an instance created with NEW */
1684                                                                           /* XXX is this strictness ok? */
1685                                                                           if (mi->class != initclass)
1686                                                                                   panic("Calling <init> method of the wrong class");
1687                                                                   }
1688                               }
1689                           }
1690                           maythrow = true;
1691                           break;
1692                           
1693                       case ICMD_MULTIANEWARRAY:
1694                                                   {
1695                                                           vftbl_t *arrayvftbl;
1696                                                           arraydescriptor *desc;
1697                                                           
1698                                                           /* check the array lengths on the stack */
1699                                                           i = iptr[0].op1;
1700                                                           if (i<1) panic("MULTIANEWARRAY with dimensions < 1");
1701                                                           srcstack = curstack;
1702                                                           while (i--) {
1703                                                                   if (!srcstack)
1704                                                                           panic("MULTIANEWARRAY missing array length");
1705                                                                   if (srcstack->type != TYPE_INT)
1706                                                                           panic("MULTIANEWARRAY using non-int as array length");
1707                                                                   srcstack = srcstack->prev;
1708                                                           }
1709                                                           
1710                                                           /* check array descriptor */
1711                                                           arrayvftbl = (vftbl_t*) iptr[0].val.a;
1712                                                           if (!arrayvftbl)
1713                                                                   panic("MULTIANEWARRAY with unlinked class");
1714                                                           if ((desc = arrayvftbl->arraydesc) == NULL)
1715                                                                   panic("MULTIANEWARRAY with non-array class");
1716                                                           if (desc->dimension < iptr[0].op1)
1717                                                                   panic("MULTIANEWARRAY dimension to high");
1718                                                           
1719                                                           /* set the array type of the result */
1720                                                           TYPEINFO_INIT_CLASSINFO(dst->typeinfo,arrayvftbl->class);
1721                                                   }
1722                           maythrow = true;
1723                           break;
1724                           
1725                       case ICMD_BUILTIN3:
1726                                                   TYPECHECK_COUNT(stat_ins_builtin);
1727                           if (ISBUILTIN(BUILTIN_aastore)) {
1728                                                           TYPECHECK_ADR(curstack);
1729                                                           TYPECHECK_INT(curstack->prev);
1730                                                           TYPECHECK_ADR(curstack->prev->prev);
1731                               if (!TYPEINFO_MAYBE_ARRAY_OF_REFS(curstack->prev->prev->typeinfo))
1732                                   panic("illegal instruction: AASTORE to non-reference array");
1733                           }
1734                                                   else {
1735                                                           /* XXX put these checks in a function */
1736                                                           TYPECHECK_COUNT(stat_ins_builtin_gen);
1737                                                           builtindesc = builtin_desc;
1738                                                           while (builtindesc->opcode && builtindesc->builtin
1739                                                                          != (functionptr) iptr->val.a) builtindesc++;
1740                                                           if (!builtindesc->opcode) {
1741                                                                   dolog("Builtin not in table: %s",icmd_builtin_name((functionptr) iptr->val.a));
1742                                                                   panic("Internal error: builtin not found in table");
1743                                                           }
1744                                                           TYPECHECK_ARGS3(builtindesc->type_s3,builtindesc->type_s2,builtindesc->type_s1);
1745                                                   }
1746                           maythrow = true;
1747                           break;
1748                           
1749                       case ICMD_BUILTIN2:
1750                                                   TYPECHECK_COUNT(stat_ins_builtin);
1751                           if (ISBUILTIN(BUILTIN_newarray))
1752                           {
1753                                                           vftbl_t *vft;
1754                                                           TYPECHECK_INT(curstack->prev);
1755                               if (iptr[-1].opc != ICMD_ACONST)
1756                                   panic("illegal instruction: builtin_newarray without classinfo");
1757                                                           vft = (vftbl_t *)iptr[-1].val.a;
1758                                                           if (!vft)
1759                                                                   panic("ANEWARRAY with unlinked class");
1760                                                           if (!vft->arraydesc)
1761                                                                   panic("ANEWARRAY with non-array class");
1762                               TYPEINFO_INIT_CLASSINFO(dst->typeinfo,vft->class);
1763                           }
1764                           else if (ISBUILTIN(BUILTIN_arrayinstanceof))
1765                           {
1766                                                           vftbl_t *vft;
1767                                                           TYPECHECK_ADR(curstack->prev);
1768                               if (iptr[-1].opc != ICMD_ACONST)
1769                                   panic("illegal instruction: builtin_arrayinstanceof without classinfo");
1770                                                           vft = (vftbl_t *)iptr[-1].val.a;
1771                                                           if (!vft)
1772                                                                   panic("INSTANCEOF with unlinked class");
1773                                                           if (!vft->arraydesc)
1774                                                                   panic("internal error: builtin_arrayinstanceof with non-array class");
1775                                                   }
1776                           else if (ISBUILTIN(BUILTIN_checkarraycast)) {
1777                                                           vftbl_t *vft;
1778                                                           TYPECHECK_ADR(curstack->prev);
1779                               if (iptr[-1].opc != ICMD_ACONST)
1780                                   panic("illegal instruction: BUILTIN_checkarraycast without classinfo");
1781                                                           vft = (vftbl_t *)iptr[-1].val.a;
1782                                                           if (!vft)
1783                                                                   panic("CHECKCAST with unlinked class");
1784                                                           if (!vft->arraydesc)
1785                                                                   panic("internal error: builtin_checkarraycast with non-array class");
1786                               TYPEINFO_INIT_CLASSINFO(dst->typeinfo,vft->class);
1787                           }
1788                                                   else {
1789                                                           TYPECHECK_COUNT(stat_ins_builtin_gen);
1790                                                           builtindesc = builtin_desc;
1791                                                           while (builtindesc->opcode && builtindesc->builtin
1792                                                                          != (functionptr) iptr->val.a) builtindesc++;
1793                                                           if (!builtindesc->opcode) {
1794                                                                   dolog("Builtin not in table: %s",icmd_builtin_name((functionptr) iptr->val.a));
1795                                                                   panic("Internal error: builtin not found in table");
1796                                                           }
1797                                                           TYPECHECK_ARGS2(builtindesc->type_s2,builtindesc->type_s1);
1798                                                   }
1799                           maythrow = true;
1800                           break;
1801                           
1802                       case ICMD_BUILTIN1:
1803                                                   TYPECHECK_COUNT(stat_ins_builtin);
1804                           if (ISBUILTIN(BUILTIN_new)) {
1805                                                           
1806                               if (iptr[-1].opc != ICMD_ACONST)
1807                                   panic("illegal instruction: builtin_new without classinfo");
1808                                                           cls = (classinfo *) iptr[-1].val.a;
1809                                                           if (!cls->linked)
1810                                                                   panic("Internal error: NEW with unlinked class");
1811                                                           /* The following check also forbids array classes and interfaces: */
1812                                                           if ((cls->flags & ACC_ABSTRACT) != 0)
1813                                                                   panic("Invalid instruction: NEW creating instance of abstract class");
1814                               TYPEINFO_INIT_NEWOBJECT(dst->typeinfo,iptr);
1815                           }
1816                           else if (ISBUILTIN(BUILTIN_newarray_boolean)) {
1817                                                           TYPECHECK_INT(curstack);
1818                               TYPEINFO_INIT_PRIMITIVE_ARRAY(dst->typeinfo,ARRAYTYPE_BOOLEAN);
1819                           }
1820                           else if (ISBUILTIN(BUILTIN_newarray_char)) {
1821                                                           TYPECHECK_INT(curstack);
1822                               TYPEINFO_INIT_PRIMITIVE_ARRAY(dst->typeinfo,ARRAYTYPE_CHAR);
1823                           }
1824                           else if (ISBUILTIN(BUILTIN_newarray_float)) {
1825                                                           TYPECHECK_INT(curstack);
1826                               TYPEINFO_INIT_PRIMITIVE_ARRAY(dst->typeinfo,ARRAYTYPE_FLOAT);
1827                           }
1828                           else if (ISBUILTIN(BUILTIN_newarray_double)) {
1829                                                           TYPECHECK_INT(curstack);
1830                               TYPEINFO_INIT_PRIMITIVE_ARRAY(dst->typeinfo,ARRAYTYPE_DOUBLE);
1831                           }
1832                           else if (ISBUILTIN(BUILTIN_newarray_byte)) {
1833                                                           TYPECHECK_INT(curstack);
1834                               TYPEINFO_INIT_PRIMITIVE_ARRAY(dst->typeinfo,ARRAYTYPE_BYTE);
1835                           }
1836                           else if (ISBUILTIN(BUILTIN_newarray_short)) {
1837                                                           TYPECHECK_INT(curstack);
1838                               TYPEINFO_INIT_PRIMITIVE_ARRAY(dst->typeinfo,ARRAYTYPE_SHORT);
1839                           }
1840                           else if (ISBUILTIN(BUILTIN_newarray_int)) {
1841                                                           TYPECHECK_INT(curstack);
1842                               TYPEINFO_INIT_PRIMITIVE_ARRAY(dst->typeinfo,ARRAYTYPE_INT);
1843                           }
1844                           else if (ISBUILTIN(BUILTIN_newarray_long)) {
1845                                                           TYPECHECK_INT(curstack);
1846                               TYPEINFO_INIT_PRIMITIVE_ARRAY(dst->typeinfo,ARRAYTYPE_LONG);
1847                           }
1848                                                   else {
1849                                                           TYPECHECK_COUNT(stat_ins_builtin_gen);
1850                                                           builtindesc = builtin_desc;
1851                                                           while (builtindesc->opcode && builtindesc->builtin
1852                                                                          != (functionptr) iptr->val.a) builtindesc++;
1853                                                           if (!builtindesc->opcode) {
1854                                                                   dolog("Builtin not in table: %s",icmd_builtin_name((functionptr) iptr->val.a));
1855                                                                   panic("Internal error: builtin not found in table");
1856                                                           }
1857                                                           TYPECHECK_ARGS1(builtindesc->type_s1);
1858                                                   }
1859                           maythrow = true;
1860                           break;
1861                                                      
1862                           /****************************************/
1863                           /* SIMPLE EXCEPTION THROWING TESTS      */
1864
1865                       case ICMD_CHECKASIZE:
1866                                                   /* The argument to CHECKASIZE is typechecked by
1867                                                    * typechecking the array creation instructions. */
1868
1869                                                   /* FALLTHROUGH! */
1870                       case ICMD_NULLCHECKPOP:
1871                                                   /* NULLCHECKPOP just requires that the stack top
1872                                                    * is an address. This is checked in stack.c */
1873                                                   
1874                           maythrow = true;
1875                           break;
1876
1877                           /****************************************/
1878                           /* INSTRUCTIONS WHICH SHOULD HAVE BEEN  */
1879                           /* REPLACED BY OTHER OPCODES            */
1880
1881 #ifdef TYPECHECK_DEBUG
1882                       case ICMD_NEW:
1883                       case ICMD_NEWARRAY:
1884                       case ICMD_ANEWARRAY:
1885                       case ICMD_MONITORENTER:
1886                       case ICMD_MONITOREXIT:
1887                       case ICMD_AASTORE:
1888                           LOG2("ICMD %d at %d\n", iptr->opc, (int)(iptr-instr));
1889                                                   LOG("Should have been converted to builtin function call.");
1890                           panic("Internal error: unexpected instruction encountered");
1891                           break;
1892                                                      
1893                       case ICMD_READONLY_ARG:
1894                       case ICMD_CLEAR_ARGREN:
1895                           LOG2("ICMD %d at %d\n", iptr->opc, (int)(iptr-instr));
1896                                                   LOG("Should have been replaced in stack.c.");
1897                           panic("Internal error: unexpected pseudo instruction encountered");
1898                           break;
1899 #endif
1900                                                   
1901                           /****************************************/
1902                           /* UNCHECKED OPERATIONS                 */
1903
1904                                                   /*********************************************
1905                                                    * Instructions below...
1906                                                    *     *) don't operate on local variables,
1907                                                    *     *) don't operate on references,
1908                                                    *     *) don't operate on returnAddresses.
1909                                                    *
1910                                                    * (These instructions are typechecked in
1911                                                    *  analyse_stack.)
1912                                                    ********************************************/
1913
1914                           /* Instructions which may throw a runtime exception: */
1915                           
1916                       case ICMD_IDIV:
1917                       case ICMD_IREM:
1918                       case ICMD_LDIV:
1919                       case ICMD_LREM:
1920                           
1921                           maythrow = true;
1922                           break;
1923                           
1924                           /* Instructions which never throw a runtime exception: */
1925 #if defined(TYPECHECK_DEBUG) || defined(TYPECHECK_STATISTICS)
1926                       case ICMD_NOP:
1927                       case ICMD_POP:
1928                       case ICMD_POP2:
1929
1930                       case ICMD_ICONST:
1931                       case ICMD_LCONST:
1932                       case ICMD_FCONST:
1933                       case ICMD_DCONST:
1934
1935                       case ICMD_IFEQ_ICONST:
1936                       case ICMD_IFNE_ICONST:
1937                       case ICMD_IFLT_ICONST:
1938                       case ICMD_IFGE_ICONST:
1939                       case ICMD_IFGT_ICONST:
1940                       case ICMD_IFLE_ICONST:
1941                       case ICMD_ELSE_ICONST:
1942
1943                       case ICMD_IADD:
1944                       case ICMD_ISUB:
1945                       case ICMD_IMUL:
1946                       case ICMD_INEG:
1947                       case ICMD_IAND:
1948                       case ICMD_IOR:
1949                       case ICMD_IXOR:
1950                       case ICMD_ISHL:
1951                       case ICMD_ISHR:
1952                       case ICMD_IUSHR:
1953                       case ICMD_LADD:
1954                       case ICMD_LSUB:
1955                       case ICMD_LMUL:
1956                       case ICMD_LNEG:
1957                       case ICMD_LAND:
1958                       case ICMD_LOR:
1959                       case ICMD_LXOR:
1960                       case ICMD_LSHL:
1961                       case ICMD_LSHR:
1962                       case ICMD_LUSHR:
1963                       case ICMD_IREM0X10001:
1964                       case ICMD_LREM0X10001:
1965                       case ICMD_IDIVPOW2:
1966                       case ICMD_LDIVPOW2:
1967                       case ICMD_IADDCONST:
1968                       case ICMD_ISUBCONST:
1969                       case ICMD_IMULCONST:
1970                       case ICMD_IANDCONST:
1971                       case ICMD_IORCONST:
1972                       case ICMD_IXORCONST:
1973                       case ICMD_ISHLCONST:
1974                       case ICMD_ISHRCONST:
1975                       case ICMD_IUSHRCONST:
1976                       case ICMD_IREMPOW2:
1977                       case ICMD_LADDCONST:
1978                       case ICMD_LSUBCONST:
1979                       case ICMD_LMULCONST:
1980                       case ICMD_LANDCONST:
1981                       case ICMD_LORCONST:
1982                       case ICMD_LXORCONST:
1983                       case ICMD_LSHLCONST:
1984                       case ICMD_LSHRCONST:
1985                       case ICMD_LUSHRCONST:
1986                       case ICMD_LREMPOW2:
1987                           
1988                       case ICMD_I2L:
1989                       case ICMD_I2F:
1990                       case ICMD_I2D:
1991                       case ICMD_L2I:
1992                       case ICMD_L2F:
1993                       case ICMD_L2D:
1994                       case ICMD_F2I:
1995                       case ICMD_F2L:
1996                       case ICMD_F2D:
1997                       case ICMD_D2I:
1998                       case ICMD_D2L:
1999                       case ICMD_D2F:
2000                       case ICMD_INT2BYTE:
2001                       case ICMD_INT2CHAR:
2002                       case ICMD_INT2SHORT:
2003
2004                       case ICMD_LCMP:
2005                       case ICMD_LCMPCONST:
2006                       case ICMD_FCMPL:
2007                       case ICMD_FCMPG:
2008                       case ICMD_DCMPL:
2009                       case ICMD_DCMPG:
2010                           
2011                       case ICMD_FADD:
2012                       case ICMD_DADD:
2013                       case ICMD_FSUB:
2014                       case ICMD_DSUB:
2015                       case ICMD_FMUL:
2016                       case ICMD_DMUL:
2017                       case ICMD_FDIV:
2018                       case ICMD_DDIV:
2019                       case ICMD_FREM:
2020                       case ICMD_DREM:
2021                       case ICMD_FNEG:
2022                       case ICMD_DNEG:
2023
2024                                                   TYPECHECK_COUNT(stat_ins_unchecked);
2025                           break;
2026                           
2027                           /****************************************/
2028
2029                       default:
2030                           LOG2("ICMD %d at %d\n", iptr->opc, (int)(iptr-instr));
2031                           panic("Missing ICMD code during typecheck");
2032 #endif
2033                                         }
2034
2035                     /* the output of this instruction becomes the current stack */
2036                     curstack = dst;
2037                     
2038                     /* reach exception handlers for this instruction */
2039                     if (maythrow) {
2040                         LOG("reaching exception handlers");
2041                         i = 0;
2042                         while (handlers[i]) {
2043                                                         TYPECHECK_COUNT(stat_handlers_reached);
2044                                                         cls = handlers[i]->catchtype;
2045                                                         excstack.typeinfo.typeclass = (cls) ? cls
2046                                                                 : class_java_lang_Throwable;
2047                                                         repeat |= typestate_reach(m, localbuf,bptr,
2048                                                                                                           handlers[i]->handler,
2049                                                                                                           &excstack,localset,
2050                                                                                                           numlocals,
2051                                                                                                           jsrencountered);
2052                             i++;
2053                         }
2054                     }
2055
2056                     iptr++;
2057                 } /* while instructions */
2058
2059                 LOG("instructions done");
2060                 LOGSTR("RESULT=> ");
2061                 DOLOG(typestate_print(get_logfile(),curstack,localset,numlocals));
2062                 LOGNL; LOGFLUSH;
2063                 
2064                 /* propagate stack and variables to the following block */
2065                 if (!superblockend) {
2066                     LOG("reaching following block");
2067                     tbptr = bptr + 1;
2068                     while (tbptr->flags == BBDELETED) {
2069                         tbptr++;
2070 #ifdef TYPECHECK_DEBUG
2071                         if ((tbptr-block) >= m->basicblockcount)
2072                             panic("Control flow falls off the last block");
2073 #endif
2074                     }
2075                     TYPECHECK_REACH;
2076                 }
2077
2078                                 /* We may have to restore the types of the instack slots. They
2079                                  * have been saved if an <init> call inside the block has
2080                                  * modified the instack types. (see INVOKESPECIAL) */
2081                                 
2082                                 if (savedstack) {
2083                                         stackptr sp = bptr->instack;
2084                                         stackptr copy = savedstack;
2085                                         TYPECHECK_COUNT(stat_savedstack);
2086                                         LOG("restoring saved instack");
2087                                         TYPESTACK_COPY(sp,copy);
2088                                         bptr->instack = savedstack;
2089                                         savedstack = NULL;
2090                                 }
2091                 
2092             } /* if block has to be checked */
2093             bptr++;
2094         } /* while blocks */
2095
2096         LOGIF(repeat,"repeat=true");
2097     } while (repeat);
2098
2099 #ifdef TYPECHECK_STATISTICS
2100         dolog("Typechecker did %4d iterations",count_iterations);
2101         TYPECHECK_COUNT_FREQ(stat_iterations,count_iterations,STAT_ITERATIONS);
2102         TYPECHECK_COUNTIF(jsrencountered,stat_typechecked_jsr);
2103 #endif
2104
2105 #ifdef TYPECHECK_DEBUG
2106         for (i=0; i<m->basicblockcount; ++i) {
2107                 if (m->basicblocks[i].flags != BBDELETED
2108                         && m->basicblocks[i].flags != BBUNDEF
2109                         && m->basicblocks[i].flags != BBFINISHED
2110                         && m->basicblocks[i].flags != BBTYPECHECK_UNDEF) /* typecheck may never reach
2111                                                                                                          * some exception handlers,
2112                                                                                                          * that's ok. */
2113                 {
2114                         LOG2("block L%03d has invalid flags after typecheck: %d",
2115                                  m->basicblocks[i].debug_nr,m->basicblocks[i].flags);
2116                         panic("Invalid block flags after typecheck");
2117                 }
2118         }
2119 #endif
2120         
2121         /* Reset blocks we never reached */
2122         for (i=0; i<m->basicblockcount; ++i) {
2123                 if (m->basicblocks[i].flags == BBTYPECHECK_UNDEF)
2124                         m->basicblocks[i].flags = BBFINISHED;
2125         }
2126                 
2127     LOGimp("exiting typecheck");
2128
2129         /* just return methodinfo* to signal everything was ok */
2130
2131         return m;
2132 }
2133
2134 #undef COPYTYPE
2135
2136 #endif /* CACAO_TYPECHECK */
2137
2138 /*
2139  * These are local overrides for various environment variables in Emacs.
2140  * Please do not remove this and leave it at the end of the file, where
2141  * Emacs will automagically detect them.
2142  * ---------------------------------------------------------------------
2143  * Local variables:
2144  * mode: c
2145  * indent-tabs-mode: t
2146  * c-basic-offset: 4
2147  * tab-width: 4
2148  * End:
2149  */