expr.c 115 KB
Newer Older
Anthony Green committed
1
/* Process expressions for the GNU compiler for the Java(TM) language.
2
   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3
   2005, 2006, 2007, 2008 Free Software Foundation, Inc.
Anthony Green committed
4

5
This file is part of GCC.
Anthony Green committed
6

7
GCC is free software; you can redistribute it and/or modify
Anthony Green committed
8
it under the terms of the GNU General Public License as published by
9
the Free Software Foundation; either version 3, or (at your option)
Anthony Green committed
10 11
any later version.

12
GCC is distributed in the hope that it will be useful,
Anthony Green committed
13 14 15 16 17
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
18 19
along with GCC; see the file COPYING3.  If not see
<http://www.gnu.org/licenses/>.  
Anthony Green committed
20 21 22 23 24 25 26 27

Java and all Java-based marks are trademarks or registered trademarks
of Sun Microsystems, Inc. in the United States and other countries.
The Free Software Foundation is independent of Sun Microsystems, Inc.  */

/* Hacked by Per Bothner <bothner@cygnus.com> February 1996. */

#include "config.h"
28
#include "system.h"
29 30
#include "coretypes.h"
#include "tm.h"
Anthony Green committed
31 32 33
#include "tree.h"
#include "real.h"
#include "rtl.h"
34
#include "flags.h"
Anthony Green committed
35 36 37 38 39 40 41
#include "expr.h"
#include "java-tree.h"
#include "javaop.h"
#include "java-opcodes.h"
#include "jcf.h"
#include "java-except.h"
#include "parse.h"
42
#include "toplev.h"
Kaveh R. Ghazi committed
43
#include "except.h"
44
#include "tm_p.h"
45
#include "ggc.h"
46 47
#include "tree-iterator.h"
#include "gimple.h"
48
#include "target.h"
Anthony Green committed
49

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
static void flush_quick_stack (void);
static void push_value (tree);
static tree pop_value (tree);
static void java_stack_swap (void);
static void java_stack_dup (int, int);
static void build_java_athrow (tree);
static void build_java_jsr (int, int);
static void build_java_ret (tree);
static void expand_java_multianewarray (tree, int);
static void expand_java_arraystore (tree);
static void expand_java_arrayload (tree);
static void expand_java_array_length (void);
static tree build_java_monitor (tree, tree);
static void expand_java_pushc (int, tree);
static void expand_java_return (tree);
static void expand_load_internal (int, tree, int);
static void expand_java_NEW (tree);
static void expand_java_INSTANCEOF (tree);
static void expand_java_CHECKCAST (tree);
static void expand_iinc (unsigned int, int, int);
static void expand_java_binop (tree, enum tree_code);
static void note_label (int, int);
static void expand_compare (enum tree_code, tree, tree, int);
static void expand_test (enum tree_code, tree, int);
static void expand_cond (enum tree_code, tree, int);
static void expand_java_goto (int);
76 77
static tree expand_java_switch (tree, int);
static void expand_java_add_case (tree, int, int);
78 79 80 81 82 83 84 85
static tree pop_arguments (tree); 
static void expand_invoke (int, int, int); 
static void expand_java_field_op (int, int, int); 
static void java_push_constant_from_pool (struct JCF *, int); 
static void java_stack_pop (int); 
static tree build_java_throw_out_of_bounds_exception (tree); 
static tree build_java_check_indexed_type (tree, tree); 
static unsigned char peek_opcode_at_pc (struct JCF *, int, int);
86
static void promote_arguments (void);
87
static void cache_cpool_data_ref (void);
88

89
static GTY(()) tree operand_type[59];
Anthony Green committed
90

91 92
static GTY(()) tree methods_ident;
static GTY(()) tree ncode_ident;
93 94
tree dtable_ident = NULL_TREE;

95
/* Set to nonzero value in order to emit class initialization code
96
   before static field references.  */
97
int always_initialize_class_p = 0;
98

Anthony Green committed
99 100 101 102 103 104 105 106 107 108 109 110
/* We store the stack state in two places:
   Within a basic block, we use the quick_stack, which is a
   pushdown list (TREE_LISTs) of expression nodes.
   This is the top part of the stack;  below that we use find_stack_slot.
   At the end of a basic block, the quick_stack must be flushed
   to the stack slot array (as handled by find_stack_slot).
   Using quick_stack generates better code (especially when
   compiled without optimization), because we do not have to
   explicitly store and load trees to temporary variables.

   If a variable is on the quick stack, it means the value of variable
   when the quick stack was last flushed.  Conceptually, flush_quick_stack
Ranjit Mathew committed
111
   saves all the quick_stack elements in parallel.  However, that is
Anthony Green committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125
   complicated, so it actually saves them (i.e. copies each stack value
   to is home virtual register) from low indexes.  This allows a quick_stack
   element at index i (counting from the bottom of stack the) to references
   slot virtuals for register that are >= i, but not those that are deeper.
   This convention makes most operations easier.  For example iadd works
   even when the stack contains (reg[0], reg[1]):  It results in the
   stack containing (reg[0]+reg[1]), which is OK.  However, some stack
   operations are more complicated.  For example dup given a stack
   containing (reg[0]) would yield (reg[0], reg[0]), which would violate
   the convention, since stack value 1 would refer to a register with
   lower index (reg[0]), which flush_quick_stack does not safely handle.
   So dup cannot just add an extra element to the quick_stack, but iadd can.
*/

126
static GTY(()) tree quick_stack;
Anthony Green committed
127

128
/* A free-list of unused permanent TREE_LIST nodes.  */
129
static GTY((deletable)) tree tree_list_free_list;
Anthony Green committed
130

131 132 133 134
/* The physical memory page size used in this computer.  See
   build_field_ref().  */
static GTY(()) tree page_size;

Anthony Green committed
135 136 137 138 139
/* The stack pointer of the Java virtual machine.
   This does include the size of the quick_stack. */

int stack_pointer;

Kaveh R. Ghazi committed
140
const unsigned char *linenumber_table;
Anthony Green committed
141 142
int linenumber_count;

143 144 145 146 147 148
/* Largest pc so far in this method that has been passed to lookup_label. */
int highest_label_pc_this_method = -1;

/* Base value for this method to add to pc to get generated label. */
int start_label_pc_this_method = 0;

149
void
150
init_expr_processing (void)
151 152 153 154 155 156 157 158
{
  operand_type[21] = operand_type[54] = int_type_node;
  operand_type[22] = operand_type[55] = long_type_node;
  operand_type[23] = operand_type[56] = float_type_node;
  operand_type[24] = operand_type[57] = double_type_node;
  operand_type[25] = operand_type[58] = ptr_type_node;
}

Anthony Green committed
159
tree
160
java_truthvalue_conversion (tree expr)
Anthony Green committed
161 162 163 164 165 166 167 168
{
  /* It is simpler and generates better code to have only TRUTH_*_EXPR
     or comparison expressions as truth values at this level.

     This function should normally be identity for Java.  */

  switch (TREE_CODE (expr))
    {
169 170 171 172
    case EQ_EXPR:   case NE_EXPR:   case UNEQ_EXPR: case LTGT_EXPR:
    case LE_EXPR:   case GE_EXPR:   case LT_EXPR:   case GT_EXPR:
    case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
    case ORDERED_EXPR: case UNORDERED_EXPR:
Anthony Green committed
173 174 175 176
    case TRUTH_ANDIF_EXPR:
    case TRUTH_ORIF_EXPR:
    case TRUTH_AND_EXPR:
    case TRUTH_OR_EXPR:
177 178
    case TRUTH_XOR_EXPR:
    case TRUTH_NOT_EXPR:
Anthony Green committed
179 180 181 182 183 184 185 186 187 188 189 190 191
    case ERROR_MARK:
      return expr;

    case INTEGER_CST:
      return integer_zerop (expr) ? boolean_false_node : boolean_true_node;

    case REAL_CST:
      return real_zerop (expr) ? boolean_false_node : boolean_true_node;

    /* are these legal? XXX JH */
    case NEGATE_EXPR:
    case ABS_EXPR:
    case FLOAT_EXPR:
192
      /* These don't change whether an object is nonzero or zero.  */
193
      return java_truthvalue_conversion (TREE_OPERAND (expr, 0));
Anthony Green committed
194 195 196

    case COND_EXPR:
      /* Distribute the conversion into the arms of a COND_EXPR.  */
197 198 199
      return fold_build3 (COND_EXPR, boolean_type_node, TREE_OPERAND (expr, 0),
			  java_truthvalue_conversion (TREE_OPERAND (expr, 1)),
			  java_truthvalue_conversion (TREE_OPERAND (expr, 2)));
Anthony Green committed
200 201 202 203 204

    case NOP_EXPR:
      /* If this is widening the argument, we can ignore it.  */
      if (TYPE_PRECISION (TREE_TYPE (expr))
          >= TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (expr, 0))))
205
        return java_truthvalue_conversion (TREE_OPERAND (expr, 0));
Anthony Green committed
206 207 208
      /* fall through to default */

    default:
209 210
      return fold_build2 (NE_EXPR, boolean_type_node,
			  expr, boolean_false_node);
Anthony Green committed
211 212 213 214 215 216 217 218 219 220
    }
}

/* Save any stack slots that happen to be in the quick_stack into their
   home virtual register slots.

   The copy order is from low stack index to high, to support the invariant
   that the expression for a slot may contain decls for stack slots with
   higher (or the same) index, but not lower. */

221
static void
222
flush_quick_stack (void)
Anthony Green committed
223 224
{
  int stack_index = stack_pointer;
225
  tree prev, cur, next;
Anthony Green committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

  /* First reverse the quick_stack, and count the number of slots it has. */
  for (cur = quick_stack, prev = NULL_TREE; cur != NULL_TREE; cur = next)
    {
      next = TREE_CHAIN (cur);
      TREE_CHAIN (cur) = prev;
      prev = cur;
      stack_index -= 1 + TYPE_IS_WIDE (TREE_TYPE (TREE_VALUE (cur)));
    }
  quick_stack = prev;

  while (quick_stack != NULL_TREE)
    {
      tree decl;
      tree node = quick_stack, type;
      quick_stack = TREE_CHAIN (node);
      TREE_CHAIN (node) = tree_list_free_list;
      tree_list_free_list = node;
      node = TREE_VALUE (node);
      type = TREE_TYPE (node);

      decl = find_stack_slot (stack_index, type);
      if (decl != node)
249
	java_add_stmt (build2 (MODIFY_EXPR, TREE_TYPE (node), decl, node));
Anthony Green committed
250 251 252 253
      stack_index += 1 + TYPE_IS_WIDE (type);
    }
}

254 255 256 257
/* Push TYPE on the type stack.
   Return true on success, 0 on overflow. */

int
258
push_type_0 (tree type)
Anthony Green committed
259 260 261 262 263
{
  int n_words;
  type = promote_type (type);
  n_words = 1 + TYPE_IS_WIDE (type);
  if (stack_pointer + n_words > DECL_MAX_STACK (current_function_decl))
264
    return 0;
265 266 267
  /* Allocate decl for this variable now, so we get a temporary that
     survives the whole method. */
  find_stack_slot (stack_pointer, type);
Anthony Green committed
268 269 270 271
  stack_type_map[stack_pointer++] = type;
  n_words--;
  while (--n_words >= 0)
    stack_type_map[stack_pointer++] = TYPE_SECOND;
272 273 274 275
  return 1;
}

void
276
push_type (tree type)
277
{
278 279
  int r = push_type_0 (type);
  gcc_assert (r);
Anthony Green committed
280 281
}

282
static void
283
push_value (tree value)
Anthony Green committed
284 285 286 287 288 289 290 291 292
{
  tree type = TREE_TYPE (value);
  if (TYPE_PRECISION (type) < 32 && INTEGRAL_TYPE_P (type))
    {
      type = promote_type (type);
      value = convert (type, value);
    }
  push_type (type);
  if (tree_list_free_list == NULL_TREE)
Mark Mitchell committed
293
    quick_stack = tree_cons (NULL_TREE, value, quick_stack);
Anthony Green committed
294 295 296 297 298 299 300 301
  else
    {
      tree node = tree_list_free_list;
      tree_list_free_list = TREE_CHAIN (tree_list_free_list);
      TREE_VALUE (node) = value;
      TREE_CHAIN (node) = quick_stack;
      quick_stack = node;
    }
302 303 304 305 306 307 308
  /* If the value has a side effect, then we need to evaluate it
     whether or not the result is used.  If the value ends up on the
     quick stack and is then popped, this won't happen -- so we flush
     the quick stack.  It is safest to simply always flush, though,
     since TREE_SIDE_EFFECTS doesn't capture COMPONENT_REF, and for
     the latter we may need to strip conversions.  */
  flush_quick_stack ();
Anthony Green committed
309 310
}

311 312
/* Pop a type from the type stack.
   TYPE is the expected type.   Return the actual type, which must be
313 314
   convertible to TYPE.
   On an error, *MESSAGEP is set to a freshly malloc'd error message. */
315

Anthony Green committed
316
tree
317
pop_type_0 (tree type, char **messagep)
Anthony Green committed
318 319 320
{
  int n_words;
  tree t;
321
  *messagep = NULL;
Anthony Green committed
322 323 324 325
  if (TREE_CODE (type) == RECORD_TYPE)
    type = promote_type (type);
  n_words = 1 + TYPE_IS_WIDE (type);
  if (stack_pointer < n_words)
326 327 328 329
    {
      *messagep = xstrdup ("stack underflow");
      return type;
    }
Anthony Green committed
330 331 332
  while (--n_words > 0)
    {
      if (stack_type_map[--stack_pointer] != void_type_node)
333 334 335 336
	{
	  *messagep = xstrdup ("Invalid multi-word value on type stack");
	  return type;
	}
Anthony Green committed
337 338 339 340
    }
  t = stack_type_map[--stack_pointer];
  if (type == NULL_TREE || t == type)
    return t;
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
  if (TREE_CODE (t) == TREE_LIST)
    {      
      do
	{
	  tree tt = TREE_PURPOSE (t);
	  if (! can_widen_reference_to (tt, type))
	    {
	      t = tt;
	      goto fail;
	    }
	  t = TREE_CHAIN (t);
	}
      while (t);
      return t;
    }
Anthony Green committed
356 357
  if (INTEGRAL_TYPE_P (type) && INTEGRAL_TYPE_P (t)
      && TYPE_PRECISION (type) <= 32 && TYPE_PRECISION (t) <= 32)
358
    return t;
Anthony Green committed
359 360
  if (TREE_CODE (type) == POINTER_TYPE && TREE_CODE (t) == POINTER_TYPE)
    {
361 362 363 364 365
      /* If the expected type we've been passed is object or ptr
	 (i.e. void*), the caller needs to know the real type.  */
      if (type == ptr_type_node || type == object_ptr_type_node)
        return t;

366 367 368 369 370 371
      /* Since the verifier has already run, we know that any
	 types we see will be compatible.  In BC mode, this fact
	 may be checked at runtime, but if that is so then we can
	 assume its truth here as well.  So, we always succeed
	 here, with the expected type.  */
      return type;
372 373 374 375 376 377
    }

  if (! flag_verify_invocations && flag_indirect_dispatch
      && t == object_ptr_type_node)
    {
      if (type != ptr_type_node)
378
	warning (0, "need to insert runtime check for %s", 
379 380
		 xstrdup (lang_printable_name (type, 0)));
      return type;
Anthony Green committed
381
    }
382

383 384
  /* lang_printable_name uses a static buffer, so we must save the result
     from calling it the first time.  */
385
 fail:
386 387
  {
    char *temp = xstrdup (lang_printable_name (type, 0));
Bryce McKinlay committed
388 389 390 391
    /* If the stack contains a multi-word type, keep popping the stack until 
       the real type is found.  */
    while (t == void_type_node)
      t = stack_type_map[--stack_pointer];
392 393 394 395 396
    *messagep = concat ("expected type '", temp,
			"' but stack contains '", lang_printable_name (t, 0),
			"'", NULL);
    free (temp);
  }
397
  return type;
398 399 400 401 402 403 404
}

/* Pop a type from the type stack.
   TYPE is the expected type.  Return the actual type, which must be
   convertible to TYPE, otherwise call error. */

tree
405
pop_type (tree type)
406
{
407 408 409 410
  char *message = NULL;
  type = pop_type_0 (type, &message);
  if (message != NULL)
    {
411
      error ("%s", message);
412 413
      free (message);
    }
414
  return type;
Anthony Green committed
415 416
}

417 418 419 420 421 422

/* Return true if two type assertions are equal.  */

static int
type_assertion_eq (const void * k1_p, const void * k2_p)
{
423 424
  const type_assertion k1 = *(const type_assertion *)k1_p;
  const type_assertion k2 = *(const type_assertion *)k2_p;
425 426 427 428 429 430 431 432 433 434
  return (k1.assertion_code == k2.assertion_code
          && k1.op1 == k2.op1
	  && k1.op2 == k2.op2);
}

/* Hash a type assertion.  */

static hashval_t
type_assertion_hash (const void *p)
{
435
  const type_assertion *k_p = (const type_assertion *) p;
436 437
  hashval_t hash = iterative_hash (&k_p->assertion_code, sizeof
				   k_p->assertion_code, 0);
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

  switch (k_p->assertion_code)
    {
    case JV_ASSERT_TYPES_COMPATIBLE:
      hash = iterative_hash (&TYPE_UID (k_p->op2), sizeof TYPE_UID (k_p->op2),
			     hash);
      /* Fall through.  */

    case JV_ASSERT_IS_INSTANTIABLE:
      hash = iterative_hash (&TYPE_UID (k_p->op1), sizeof TYPE_UID (k_p->op1),
			     hash);
      /* Fall through.  */

    case JV_ASSERT_END_OF_TABLE:
      break;

    default:
      gcc_unreachable ();
    }

  return hash;
459 460 461
}

/* Add an entry to the type assertion table for the given class.  
462
   KLASS is the class for which this assertion will be evaluated by the 
463 464 465 466 467 468
   runtime during loading/initialization.
   ASSERTION_CODE is the 'opcode' or type of this assertion: see java-tree.h.
   OP1 and OP2 are the operands. The tree type of these arguments may be
   specific to each assertion_code. */

void
469
add_type_assertion (tree klass, int assertion_code, tree op1, tree op2)
470 471 472 473 474
{
  htab_t assertions_htab;
  type_assertion as;
  void **as_pp;

475
  assertions_htab = TYPE_ASSERTIONS (klass);
476 477 478 479 480 481 482 483 484 485 486
  if (assertions_htab == NULL)
    {
      assertions_htab = htab_create_ggc (7, type_assertion_hash, 
					 type_assertion_eq, NULL);
      TYPE_ASSERTIONS (current_class) = assertions_htab;
    }

  as.assertion_code = assertion_code;
  as.op1 = op1;
  as.op2 = op2;

487
  as_pp = htab_find_slot (assertions_htab, &as, INSERT);
488 489 490 491 492 493 494 495 496 497

  /* Don't add the same assertion twice.  */
  if (*as_pp)
    return;

  *as_pp = ggc_alloc (sizeof (type_assertion));
  **(type_assertion **)as_pp = as;
}


498
/* Return 1 if SOURCE_TYPE can be safely widened to TARGET_TYPE.
Anthony Green committed
499 500 501
   Handles array types and interfaces.  */

int
502
can_widen_reference_to (tree source_type, tree target_type)
Anthony Green committed
503 504 505 506 507 508 509 510 511 512 513 514
{
  if (source_type == ptr_type_node || target_type == object_ptr_type_node)
    return 1;

  /* Get rid of pointers  */
  if (TREE_CODE (source_type) == POINTER_TYPE)
    source_type = TREE_TYPE (source_type);
  if (TREE_CODE (target_type) == POINTER_TYPE)
    target_type = TREE_TYPE (target_type);

  if (source_type == target_type)
    return 1;
515 516 517 518 519 520 521 522 523 524 525

  /* FIXME: This is very pessimistic, in that it checks everything,
     even if we already know that the types are compatible.  If we're
     to support full Java class loader semantics, we need this.
     However, we could do something more optimal.  */
  if (! flag_verify_invocations)
    {
      add_type_assertion (current_class, JV_ASSERT_TYPES_COMPATIBLE, 
			  source_type, target_type);

      if (!quiet_flag)
526
       warning (0, "assert: %s is assign compatible with %s", 
527 528 529 530 531 532 533 534 535 536
		xstrdup (lang_printable_name (target_type, 0)),
		xstrdup (lang_printable_name (source_type, 0)));
      /* Punt everything to runtime.  */
      return 1;
    }

  if (TYPE_DUMMY (source_type) || TYPE_DUMMY (target_type))
    {
      return 1;
    }
Anthony Green committed
537 538 539 540 541 542
  else
    {
      if (TYPE_ARRAY_P (source_type) || TYPE_ARRAY_P (target_type))
	{
	  HOST_WIDE_INT source_length, target_length;
	  if (TYPE_ARRAY_P (source_type) != TYPE_ARRAY_P (target_type))
543 544 545 546 547 548
	    {
	      /* An array implements Cloneable and Serializable.  */
	      tree name = DECL_NAME (TYPE_NAME (target_type));
	      return (name == java_lang_cloneable_identifier_node
		      || name == java_io_serializable_identifier_node);
	    }
Anthony Green committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
	  target_length = java_array_type_length (target_type);
	  if (target_length >= 0)
	    {
	      source_length = java_array_type_length (source_type);
	      if (source_length != target_length)
		return 0;
	    }
	  source_type = TYPE_ARRAY_ELEMENT (source_type);
	  target_type = TYPE_ARRAY_ELEMENT (target_type);
	  if (source_type == target_type)
	    return 1;
	  if (TREE_CODE (source_type) != POINTER_TYPE
	      || TREE_CODE (target_type) != POINTER_TYPE)
	    return 0;
	  return can_widen_reference_to (source_type, target_type);
	}
      else
	{
	  int source_depth = class_depth (source_type);
	  int target_depth = class_depth (target_type);

570 571 572
	  if (TYPE_DUMMY (source_type) || TYPE_DUMMY (target_type))
	    {
	      if (! quiet_flag)
573
		warning (0, "assert: %s is assign compatible with %s", 
574 575 576 577 578 579
			 xstrdup (lang_printable_name (target_type, 0)),
			 xstrdup (lang_printable_name (source_type, 0)));
	      return 1;
	    }

 	  /* class_depth can return a negative depth if an error occurred */
580 581 582
	  if (source_depth < 0 || target_depth < 0)
	    return 0;

Anthony Green committed
583 584 585 586
	  if (CLASS_INTERFACE (TYPE_NAME (target_type)))
	    {
	      /* target_type is OK if source_type or source_type ancestors
		 implement target_type. We handle multiple sub-interfaces  */
Nathan Sidwell committed
587 588
	      tree binfo, base_binfo;
	      int i;
Anthony Green committed
589

Nathan Sidwell committed
590 591 592 593
	      for (binfo = TYPE_BINFO (source_type), i = 0;
		   BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
	        if (can_widen_reference_to
		    (BINFO_TYPE (base_binfo), target_type))
Anthony Green committed
594
		  return 1;
Nathan Sidwell committed
595 596
	      
	      if (!i)
597
		return 0;
Anthony Green committed
598 599 600 601
	    }

	  for ( ; source_depth > target_depth;  source_depth--) 
	    {
602 603
	      source_type
		= BINFO_TYPE (BINFO_BASE_BINFO (TYPE_BINFO (source_type), 0));
Anthony Green committed
604 605 606 607 608 609
	    }
	  return source_type == target_type;
	}
    }
}

610
static tree
611
pop_value (tree type)
Anthony Green committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
{
  type = pop_type (type);
  if (quick_stack)
    {
      tree node = quick_stack;
      quick_stack = TREE_CHAIN (quick_stack);
      TREE_CHAIN (node) = tree_list_free_list;
      tree_list_free_list = node;
      node = TREE_VALUE (node);
      return node;
    }
  else
    return find_stack_slot (stack_pointer, promote_type (type));
}


Kazu Hirata committed
628
/* Pop and discard the top COUNT stack slots. */
Anthony Green committed
629

630
static void
631
java_stack_pop (int count)
Anthony Green committed
632 633 634 635
{
  while (count > 0)
    {
      tree type, val;
636

637
      gcc_assert (stack_pointer != 0);
638

Anthony Green committed
639 640 641 642
      type = stack_type_map[stack_pointer - 1];
      if (type == TYPE_SECOND)
	{
	  count--;
643
	  gcc_assert (stack_pointer != 1 && count > 0);
644

Anthony Green committed
645 646 647 648 649 650 651 652 653
	  type = stack_type_map[stack_pointer - 2];
	}
      val = pop_value (type);
      count--;
    }
}

/* Implement the 'swap' operator (to swap two top stack slots). */

654
static void
655
java_stack_swap (void)
Anthony Green committed
656 657
{
  tree type1, type2;
658
  tree temp;
Anthony Green committed
659 660
  tree decl1, decl2;

661
  if (stack_pointer < 2
662 663
      || (type1 = stack_type_map[stack_pointer - 1]) == TYPE_SECOND
      || (type2 = stack_type_map[stack_pointer - 2]) == TYPE_SECOND
664 665 666
      || TYPE_IS_WIDE (type1) || TYPE_IS_WIDE (type2))
    /* Bad stack swap.  */
    abort ();
667
  /* Bad stack swap.  */
Anthony Green committed
668 669 670 671

  flush_quick_stack ();
  decl1 = find_stack_slot (stack_pointer - 1, type1);
  decl2 = find_stack_slot (stack_pointer - 2, type2);
672
  temp = build_decl (input_location, VAR_DECL, NULL_TREE, type1);
673
  java_add_local_var (temp);
674 675 676 677 678 679 680
  java_add_stmt (build2 (MODIFY_EXPR, type1, temp, decl1));
  java_add_stmt (build2 (MODIFY_EXPR, type2, 
			 find_stack_slot (stack_pointer - 1, type2),
			 decl2));
  java_add_stmt (build2 (MODIFY_EXPR, type1, 
			 find_stack_slot (stack_pointer - 2, type1),
			 temp));
Anthony Green committed
681 682 683 684
  stack_type_map[stack_pointer - 1] = type2;
  stack_type_map[stack_pointer - 2] = type1;
}

685
static void
686
java_stack_dup (int size, int offset)
Anthony Green committed
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
{
  int low_index = stack_pointer - size - offset;
  int dst_index;
  if (low_index < 0)
    error ("stack underflow - dup* operation");

  flush_quick_stack ();

  stack_pointer += size;
  dst_index = stack_pointer;

  for (dst_index = stack_pointer;  --dst_index >= low_index; )
    {
      tree type;
      int src_index = dst_index - size;
      if (src_index < low_index)
	src_index = dst_index + size + offset;
      type = stack_type_map [src_index];
      if (type == TYPE_SECOND)
	{
707 708
	  /* Dup operation splits 64-bit number.  */
	  gcc_assert (src_index > low_index);
709

Anthony Green committed
710 711 712
	  stack_type_map[dst_index] = type;
	  src_index--;  dst_index--;
	  type = stack_type_map[src_index];
713
	  gcc_assert (TYPE_IS_WIDE (type));
Anthony Green committed
714
	}
715 716
      else
	gcc_assert (! TYPE_IS_WIDE (type));
717

Anthony Green committed
718 719 720 721
      if (src_index != dst_index)
	{
	  tree src_decl = find_stack_slot (src_index, type);
	  tree dst_decl = find_stack_slot (dst_index, type);
722 723

	  java_add_stmt 
724
	    (build2 (MODIFY_EXPR, TREE_TYPE (dst_decl), dst_decl, src_decl));
Anthony Green committed
725 726 727 728 729
	  stack_type_map[dst_index] = type;
	}
    }
}

730 731
/* Calls _Jv_Throw or _Jv_Sjlj_Throw.  Discard the contents of the
   value stack. */
Anthony Green committed
732

733
static void
734
build_java_athrow (tree node)
Anthony Green committed
735 736 737
{
  tree call;

738 739 740
  call = build_call_nary (void_type_node,
			  build_address_of (throw_node),
			  1, node);
Anthony Green committed
741
  TREE_SIDE_EFFECTS (call) = 1;
742
  java_add_stmt (call);
Anthony Green committed
743 744 745 746 747
  java_stack_pop (stack_pointer);
}

/* Implementation for jsr/ret */

748
static void
749
build_java_jsr (int target_pc, int return_pc)
Anthony Green committed
750
{
751 752
  tree where =  lookup_label (target_pc);
  tree ret = lookup_label (return_pc);
753
  tree ret_label = fold_build1 (ADDR_EXPR, return_address_type_node, ret);
Anthony Green committed
754 755
  push_value (ret_label);
  flush_quick_stack ();
756
  java_add_stmt (build1 (GOTO_EXPR, void_type_node, where));
757

758
  /* Do not need to emit the label here.  We noted the existence of the
759 760
     label as a jump target in note_instructions; we'll emit the label
     for real at the beginning of the expand_byte_code loop.  */
Anthony Green committed
761 762
}

763
static void
764
build_java_ret (tree location)
Anthony Green committed
765
{
766
  java_add_stmt (build1 (GOTO_EXPR, void_type_node, location));
Anthony Green committed
767 768 769 770 771
}
 
/* Implementation of operations on array: new, load, store, length */

tree
772
decode_newarray_type (int atype)
Anthony Green committed
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
{
  switch (atype)
    {
    case 4:  return boolean_type_node;
    case 5:  return char_type_node;
    case 6:  return float_type_node;
    case 7:  return double_type_node;
    case 8:  return byte_type_node;
    case 9:  return short_type_node;
    case 10: return int_type_node;
    case 11: return long_type_node;
    default: return NULL_TREE;
    }
}

788 789 790
/* Map primitive type to the code used by OPCODE_newarray. */

int
791
encode_newarray_type (tree type)
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
{
  if (type == boolean_type_node)
    return 4;
  else if (type == char_type_node)
    return 5;
  else if (type == float_type_node)
    return 6;
  else if (type == double_type_node)
    return 7;
  else if (type == byte_type_node)
    return 8;
  else if (type == short_type_node)
    return 9;
  else if (type == int_type_node)
    return 10;
  else if (type == long_type_node)
    return 11;
  else
810
    gcc_unreachable ();
811 812
}

Per Bothner committed
813 814
/* Build a call to _Jv_ThrowBadArrayIndex(), the
   ArrayIndexOfBoundsException exception handler.  */
Anthony Green committed
815 816

static tree
817
build_java_throw_out_of_bounds_exception (tree index)
Anthony Green committed
818
{
819 820 821 822 823 824 825
  tree node;

  /* We need to build a COMPOUND_EXPR because _Jv_ThrowBadArrayIndex()
     has void return type.  We cannot just set the type of the CALL_EXPR below
     to int_type_node because we would lose it during gimplification.  */
  gcc_assert (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (soft_badarrayindex_node))));
  node = build_call_nary (void_type_node,
826 827
			       build_address_of (soft_badarrayindex_node),
			       1, index);
828 829 830
  TREE_SIDE_EFFECTS (node) = 1;

  node = build2 (COMPOUND_EXPR, int_type_node, node, integer_zero_node);
Anthony Green committed
831
  TREE_SIDE_EFFECTS (node) = 1;	/* Allows expansion within ANDIF */
832

Anthony Green committed
833 834 835 836 837 838 839
  return (node);
}

/* Return the length of an array. Doesn't perform any checking on the nature
   or value of the array NODE. May be used to implement some bytecodes.  */

tree
840
build_java_array_length_access (tree node)
Anthony Green committed
841 842
{
  tree type = TREE_TYPE (node);
843
  tree array_type = TREE_TYPE (type);
Anthony Green committed
844
  HOST_WIDE_INT length;
845

Anthony Green committed
846
  if (!is_array_type_p (type))
847 848 849 850 851 852
    {
      /* With the new verifier, we will see an ordinary pointer type
	 here.  In this case, we just use an arbitrary array type.  */
      array_type = build_java_array_type (object_ptr_type_node, -1);
      type = promote_type (array_type);
    }
853

Anthony Green committed
854 855
  length = java_array_type_length (type);
  if (length >= 0)
856
    return build_int_cst (NULL_TREE, length);
857

858 859 860 861 862
  node = build3 (COMPONENT_REF, int_type_node,
		 build_java_indirect_ref (array_type, node,
					  flag_check_references),
		 lookup_field (&array_type, get_identifier ("length")),
		 NULL_TREE);
863
  IS_ARRAY_LENGTH_ACCESS (node) = 1;
864
  return node;
Anthony Green committed
865 866
}

867 868 869 870 871
/* Optionally checks a reference against the NULL pointer.  ARG1: the
   expr, ARG2: we should check the reference.  Don't generate extra
   checks if we're not generating code.  */

tree 
872
java_check_reference (tree expr, int check)
873 874 875 876
{
  if (!flag_syntax_only && check)
    {
      expr = save_expr (expr);
877 878 879
      expr = build3 (COND_EXPR, TREE_TYPE (expr),
		     build2 (EQ_EXPR, boolean_type_node,
			     expr, null_pointer_node),
880 881 882
		     build_call_nary (void_type_node, 
				      build_address_of (soft_nullpointer_node),
				      0),
883
		     expr);
884 885 886 887 888 889
    }

  return expr;
}

/* Reference an object: just like an INDIRECT_REF, but with checking.  */
Anthony Green committed
890 891

tree
892
build_java_indirect_ref (tree type, tree expr, int check)
Anthony Green committed
893
{
894 895 896 897
  tree t;
  t = java_check_reference (expr, check);
  t = convert (build_pointer_type (type), t);
  return build1 (INDIRECT_REF, type, t);
Anthony Green committed
898 899 900 901 902 903 904 905
}

/* Implement array indexing (either as l-value or r-value).
   Returns a tree for ARRAY[INDEX], assume TYPE is the element type.
   Optionally performs bounds checking and/or test to NULL.
   At this point, ARRAY should have been verified as an array.  */

tree
906
build_java_arrayaccess (tree array, tree type, tree index)
Anthony Green committed
907
{
908
  tree node, throw_expr = NULL_TREE;
909 910 911
  tree data_field;
  tree ref;
  tree array_type = TREE_TYPE (TREE_TYPE (array));
912
  tree size_exp = fold_convert (sizetype, size_in_bytes (type));
Anthony Green committed
913

914 915 916 917 918 919 920
  if (!is_array_type_p (TREE_TYPE (array)))
    {
      /* With the new verifier, we will see an ordinary pointer type
	 here.  In this case, we just use the correct array type.  */
      array_type = build_java_array_type (type, -1);
    }

Anthony Green committed
921 922 923 924 925 926 927 928
  if (flag_bounds_check)
    {
      /* Generate:
       * (unsigned jint) INDEX >= (unsigned jint) LEN
       *    && throw ArrayIndexOutOfBoundsException.
       * Note this is equivalent to and more efficient than:
       * INDEX < 0 || INDEX >= LEN && throw ... */
      tree test;
929 930
      tree len = convert (unsigned_int_type_node,
			  build_java_array_length_access (array));
931 932 933
      test = fold_build2 (GE_EXPR, boolean_type_node, 
			  convert (unsigned_int_type_node, index),
			  len);
Anthony Green committed
934 935
      if (! integer_zerop (test))
	{
936 937 938
	  throw_expr
	    = build2 (TRUTH_ANDIF_EXPR, int_type_node, test,
		      build_java_throw_out_of_bounds_exception (index));
Anthony Green committed
939
	  /* allows expansion within COMPOUND */
940
	  TREE_SIDE_EFFECTS( throw_expr ) = 1;
Anthony Green committed
941 942
	}
    }
943

944 945
  /* If checking bounds, wrap the index expr with a COMPOUND_EXPR in order
     to have the bounds check evaluated first. */
946 947
  if (throw_expr != NULL_TREE)
    index = build2 (COMPOUND_EXPR, int_type_node, throw_expr, index);
948

949 950
  data_field = lookup_field (&array_type, get_identifier ("data"));

951 952 953 954
  ref = build3 (COMPONENT_REF, TREE_TYPE (data_field),    
		build_java_indirect_ref (array_type, array, 
					 flag_check_references),
		data_field, NULL_TREE);
955 956 957 958 959 960 961

  /* Take the address of the data field and convert it to a pointer to
     the element type.  */
  node = build1 (NOP_EXPR, build_pointer_type (type), build_address_of (ref));

  /* Multiply the index by the size of an element to obtain a byte
     offset.  Convert the result to a pointer to the element type.  */
Andrew Pinski committed
962 963 964
  index = build2 (MULT_EXPR, sizetype, 
		  fold_convert (sizetype, index), 
		  size_exp);
965 966

  /* Sum the byte offset and the address of the data field.  */
Andrew Pinski committed
967
  node = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (node), node, index);
968 969 970 971 972 973 974

  /* Finally, return

    *((&array->data) + index*size_exp)

  */
  return build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (node)), node);
Anthony Green committed
975 976
}

977 978 979 980 981
/* Generate code to throw an ArrayStoreException if OBJECT is not assignable
   (at runtime) to an element of ARRAY.  A NOP_EXPR is returned if it can
   determine that no check is required. */

tree
982
build_java_arraystore_check (tree array, tree object)
983
{
984
  tree check, element_type, source;
985 986 987
  tree array_type_p = TREE_TYPE (array);
  tree object_type = TYPE_NAME (TREE_TYPE (TREE_TYPE (object)));

988 989 990 991 992 993 994 995
  if (! flag_verify_invocations)
    {
      /* With the new verifier, we don't track precise types.  FIXME:
	 performance regression here.  */
      element_type = TYPE_NAME (object_type_node);
    }
  else
    {
996
      gcc_assert (is_array_type_p (array_type_p));
997

998 999 1000 1001
      /* Get the TYPE_DECL for ARRAY's element type. */
      element_type
	= TYPE_NAME (TREE_TYPE (TREE_TYPE (TREE_TYPE (array_type_p))));
    }
1002

1003 1004
  gcc_assert (TREE_CODE (element_type) == TYPE_DECL
	      && TREE_CODE (object_type) == TYPE_DECL);
1005 1006

  if (!flag_store_check)
1007
    return build1 (NOP_EXPR, array_type_p, array);
1008

1009 1010 1011 1012 1013
  /* No check is needed if the element type is final.  Also check that
     element_type matches object_type, since in the bytecode
     compilation case element_type may be the actual element type of
     the array rather than its declared type.  However, if we're doing
     indirect dispatch, we can't do the `final' optimization.  */
1014
  if (element_type == object_type
1015 1016
      && ! flag_indirect_dispatch
      && CLASS_FINAL (element_type))
1017 1018
    return build1 (NOP_EXPR, array_type_p, array);
  
1019 1020 1021 1022 1023 1024
  /* OBJECT might be wrapped by a SAVE_EXPR. */
  if (TREE_CODE (object) == SAVE_EXPR)
    source = TREE_OPERAND (object, 0);
  else
    source = object;
  
1025
  /* Avoid the check if OBJECT was just loaded from the same array. */
1026
  if (TREE_CODE (source) == ARRAY_REF)
1027 1028
    {
      tree target;
1029
      source = TREE_OPERAND (source, 0); /* COMPONENT_REF. */
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
      source = TREE_OPERAND (source, 0); /* INDIRECT_REF. */
      source = TREE_OPERAND (source, 0); /* Source array's DECL or SAVE_EXPR. */
      if (TREE_CODE (source) == SAVE_EXPR)
	source = TREE_OPERAND (source, 0);
      
      target = array;
      if (TREE_CODE (target) == SAVE_EXPR)
	target = TREE_OPERAND (target, 0);
      
      if (source == target)
1040
        return build1 (NOP_EXPR, array_type_p, array);
1041 1042 1043
    }

  /* Build an invocation of _Jv_CheckArrayStore */
1044 1045 1046
  check = build_call_nary (void_type_node,
			   build_address_of (soft_checkarraystore_node),
			   2, array, object);
1047 1048 1049 1050 1051
  TREE_SIDE_EFFECTS (check) = 1;

  return check;
}

Anthony Green committed
1052 1053 1054 1055
/* Makes sure that INDEXED_TYPE is appropriate. If not, make it from
   ARRAY_NODE. This function is used to retrieve something less vague than
   a pointer type when indexing the first dimension of something like [[<t>.
   May return a corrected type, if necessary, otherwise INDEXED_TYPE is
1056
   return unchanged.  */
Anthony Green committed
1057 1058

static tree
1059 1060
build_java_check_indexed_type (tree array_node ATTRIBUTE_UNUSED,
			       tree indexed_type)
Anthony Green committed
1061
{
1062 1063 1064 1065
  /* We used to check to see if ARRAY_NODE really had array type.
     However, with the new verifier, this is not necessary, as we know
     that the object will be an array of the appropriate type.  */

1066
  return indexed_type;
Anthony Green committed
1067 1068
}

1069 1070 1071
/* newarray triggers a call to _Jv_NewPrimArray. This function should be 
   called with an integer code (the type of array to create), and the length
   of the array to create.  */
Anthony Green committed
1072 1073

tree
1074
build_newarray (int atype_value, tree length)
Anthony Green committed
1075
{
1076 1077 1078
  tree type_arg;

  tree prim_type = decode_newarray_type (atype_value);
1079
  tree type
1080
    = build_java_array_type (prim_type,
1081 1082
			     host_integerp (length, 0) == INTEGER_CST
			     ? tree_low_cst (length, 0) : -1);
1083

1084 1085 1086
  /* Pass a reference to the primitive type class and save the runtime
     some work.  */
  type_arg = build_class_ref (prim_type);
1087

1088 1089 1090
  return build_call_nary (promote_type (type),
			  build_address_of (soft_newarray_node),
			  2, type_arg, length);
Anthony Green committed
1091 1092 1093 1094
}

/* Generates anewarray from a given CLASS_TYPE. Gets from the stack the size
   of the dimension. */
1095

Anthony Green committed
1096
tree
1097
build_anewarray (tree class_type, tree length)
Anthony Green committed
1098
{
1099 1100
  tree type
    = build_java_array_type (class_type,
1101 1102
			     host_integerp (length, 0)
			     ? tree_low_cst (length, 0) : -1);
1103

1104 1105 1106 1107 1108 1109
  return build_call_nary (promote_type (type),
			  build_address_of (soft_anewarray_node),
			  3,
			  length,
			  build_class_ref (class_type),
			  null_pointer_node);
Anthony Green committed
1110 1111
}

1112 1113 1114
/* Return a node the evaluates 'new TYPE[LENGTH]'. */

tree
1115
build_new_array (tree type, tree length)
1116 1117 1118 1119 1120 1121 1122
{
  if (JPRIMITIVE_TYPE_P (type))
    return build_newarray (encode_newarray_type (type), length);
  else
    return build_anewarray (TREE_TYPE (type), length);
}

Per Bothner committed
1123 1124 1125
/* Generates a call to _Jv_NewMultiArray. multianewarray expects a
   class pointer, a number of dimensions and the matching number of
   dimensions. The argument list is NULL terminated.  */
Anthony Green committed
1126

1127
static void
1128
expand_java_multianewarray (tree class_type, int ndim)
Anthony Green committed
1129 1130 1131 1132 1133 1134 1135
{
  int i;
  tree args = build_tree_list( NULL_TREE, null_pointer_node );

  for( i = 0; i < ndim; i++ )
    args = tree_cons (NULL_TREE, pop_value (int_type_node), args);

1136 1137 1138 1139 1140 1141 1142 1143 1144
  args = tree_cons (NULL_TREE,
		    build_class_ref (class_type),
		    tree_cons (NULL_TREE, 
			       build_int_cst (NULL_TREE, ndim),
			       args));

  push_value (build_call_list (promote_type (class_type),
			       build_address_of (soft_multianewarray_node),
			       args));
Anthony Green committed
1145 1146 1147 1148 1149 1150
}

/*  ARRAY[INDEX] <- RHS. build_java_check_indexed_type makes sure that
    ARRAY is an array type. May expand some bound checking and NULL
    pointer checking. RHS_TYPE_NODE we are going to store. In the case
    of the CHAR/BYTE/BOOLEAN SHORT, the type popped of the stack is an
1151
    INT. In those cases, we make the conversion.
Anthony Green committed
1152 1153 1154 1155 1156

    if ARRAy is a reference type, the assignment is checked at run-time
    to make sure that the RHS can be assigned to the array element
    type. It is not necessary to generate this code if ARRAY is final.  */

1157
static void
1158
expand_java_arraystore (tree rhs_type_node)
Anthony Green committed
1159 1160 1161 1162 1163
{
  tree rhs_node    = pop_value ((INTEGRAL_TYPE_P (rhs_type_node) 
				 && TYPE_PRECISION (rhs_type_node) <= 32) ? 
				 int_type_node : rhs_type_node);
  tree index = pop_value (int_type_node);
1164
  tree array_type, array, temp, access;
1165

1166 1167 1168
  /* If we're processing an `aaload' we might as well just pick
     `Object'.  */
  if (TREE_CODE (rhs_type_node) == POINTER_TYPE)
1169
    {
1170 1171
      array_type = build_java_array_type (object_ptr_type_node, -1);
      rhs_type_node = object_ptr_type_node;
1172 1173
    }
  else
1174 1175
    array_type = build_java_array_type (rhs_type_node, -1);

1176
  array = pop_value (array_type);
1177
  array = build1 (NOP_EXPR, promote_type (array_type), array);
Anthony Green committed
1178 1179 1180 1181 1182 1183 1184 1185

  rhs_type_node    = build_java_check_indexed_type (array, rhs_type_node);

  flush_quick_stack ();

  index = save_expr (index);
  array = save_expr (array);

1186 1187 1188 1189 1190 1191 1192 1193 1194
  /* We want to perform the bounds check (done by
     build_java_arrayaccess) before the type check (done by
     build_java_arraystore_check).  So, we call build_java_arrayaccess
     -- which returns an ARRAY_REF lvalue -- and we then generate code
     to stash the address of that lvalue in a temp.  Then we call
     build_java_arraystore_check, and finally we generate a
     MODIFY_EXPR to set the array element.  */

  access = build_java_arrayaccess (array, rhs_type_node, index);
1195
  temp = build_decl (input_location, VAR_DECL, NULL_TREE, 
1196 1197 1198 1199 1200 1201
		     build_pointer_type (TREE_TYPE (access)));
  java_add_local_var (temp);
  java_add_stmt (build2 (MODIFY_EXPR, TREE_TYPE (temp),
			 temp, 
			 build_fold_addr_expr (access)));

1202
  if (TREE_CODE (rhs_type_node) == POINTER_TYPE)
Anthony Green committed
1203
    {
1204
      tree check = build_java_arraystore_check (array, rhs_node);
1205
      java_add_stmt (check);
Anthony Green committed
1206 1207
    }
  
1208 1209 1210
  java_add_stmt (build2 (MODIFY_EXPR, TREE_TYPE (access), 
			 build1 (INDIRECT_REF, TREE_TYPE (access), temp),
			 rhs_node));  
Anthony Green committed
1211 1212 1213 1214 1215 1216 1217 1218 1219
}

/* Expand the evaluation of ARRAY[INDEX]. build_java_check_indexed_type makes 
   sure that LHS is an array type. May expand some bound checking and NULL
   pointer checking.  
   LHS_TYPE_NODE is the type of ARRAY[INDEX]. But in the case of CHAR/BYTE/
   BOOLEAN/SHORT, we push a promoted type back to the stack.
*/

1220
static void
1221
expand_java_arrayload (tree lhs_type_node)
Anthony Green committed
1222 1223 1224
{
  tree load_node;
  tree index_node = pop_value (int_type_node);
1225 1226 1227
  tree array_type;
  tree array_node;

1228 1229 1230
  /* If we're processing an `aaload' we might as well just pick
     `Object'.  */
  if (TREE_CODE (lhs_type_node) == POINTER_TYPE)
1231
    {
1232 1233
      array_type = build_java_array_type (object_ptr_type_node, -1);
      lhs_type_node = object_ptr_type_node;
1234 1235
    }
  else
1236
    array_type = build_java_array_type (lhs_type_node, -1);
1237
  array_node = pop_value (array_type);
1238
  array_node = build1 (NOP_EXPR, promote_type (array_type), array_node);
Anthony Green committed
1239 1240 1241

  index_node = save_expr (index_node);
  array_node = save_expr (array_node);
1242

1243 1244 1245 1246 1247
  lhs_type_node = build_java_check_indexed_type (array_node,
						 lhs_type_node);
  load_node = build_java_arrayaccess (array_node,
				      lhs_type_node,
				      index_node);
Anthony Green committed
1248
  if (INTEGRAL_TYPE_P (lhs_type_node) && TYPE_PRECISION (lhs_type_node) <= 32)
1249
    load_node = fold_build1 (NOP_EXPR, int_type_node, load_node);
Anthony Green committed
1250 1251 1252 1253 1254 1255
  push_value (load_node);
}

/* Expands .length. Makes sure that we deal with and array and may expand
   a NULL check on the array object.  */

1256
static void
1257
expand_java_array_length (void)
Anthony Green committed
1258 1259 1260 1261
{
  tree array  = pop_value (ptr_type_node);
  tree length = build_java_array_length_access (array);

1262
  push_value (length);
Anthony Green committed
1263 1264
}

Per Bothner committed
1265 1266
/* Emit code for the call to _Jv_Monitor{Enter,Exit}. CALL can be
   either soft_monitorenter_node or soft_monitorexit_node.  */
Anthony Green committed
1267

1268
static tree
1269
build_java_monitor (tree call, tree object)
Anthony Green committed
1270
{
1271 1272 1273
  return build_call_nary (void_type_node,
			  build_address_of (call),
			  1, object);
Anthony Green committed
1274 1275 1276 1277
}

/* Emit code for one of the PUSHC instructions. */

1278
static void
1279
expand_java_pushc (int ival, tree type)
Anthony Green committed
1280 1281 1282 1283 1284
{
  tree value;
  if (type == ptr_type_node && ival == 0)
    value = null_pointer_node;
  else if (type == int_type_node || type == long_type_node)
1285
    value = build_int_cst (type, ival);
Anthony Green committed
1286 1287 1288 1289 1290 1291 1292
  else if (type == float_type_node || type == double_type_node)
    {
      REAL_VALUE_TYPE x;
      REAL_VALUE_FROM_INT (x, ival, 0, TYPE_MODE (type));
      value = build_real (type, x);
    }
  else
1293
    gcc_unreachable ();
1294

Anthony Green committed
1295 1296 1297
  push_value (value);
}

1298
static void
1299
expand_java_return (tree type)
Anthony Green committed
1300 1301
{
  if (type == void_type_node)
1302
    java_add_stmt (build1 (RETURN_EXPR, void_type_node, NULL));   
Anthony Green committed
1303 1304 1305 1306
  else
    {
      tree retval = pop_value (type);
      tree res = DECL_RESULT (current_function_decl);
1307
      retval = build2 (MODIFY_EXPR, TREE_TYPE (res), res, retval);
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317

      /* Handle the situation where the native integer type is smaller
	 than the JVM integer. It can happen for many cross compilers.
	 The whole if expression just goes away if INT_TYPE_SIZE < 32
	 is false. */
      if (INT_TYPE_SIZE < 32
	  && (GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (res)))
	      < GET_MODE_SIZE (TYPE_MODE (type))))
	retval = build1(NOP_EXPR, TREE_TYPE(res), retval);
      
Anthony Green committed
1318
      TREE_SIDE_EFFECTS (retval) = 1;
1319
      java_add_stmt (build1 (RETURN_EXPR, void_type_node, retval));
Anthony Green committed
1320 1321 1322
    }
}

1323
static void
1324
expand_load_internal (int index, tree type, int pc)
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
{
  tree copy;
  tree var = find_local_variable (index, type, pc);

  /* Now VAR is the VAR_DECL (or PARM_DECL) that we are going to push
     on the stack.  If there is an assignment to this VAR_DECL between
     the stack push and the use, then the wrong code could be
     generated.  To avoid this we create a new local and copy our
     value into it.  Then we push this new local on the stack.
     Hopefully this all gets optimized out.  */
1335
  copy = build_decl (input_location, VAR_DECL, NULL_TREE, type);
1336
  if ((INTEGRAL_TYPE_P (type) || POINTER_TYPE_P (type))
1337 1338
      && TREE_TYPE (copy) != TREE_TYPE (var))
    var = convert (type, var);
1339
  java_add_local_var (copy);
1340
  java_add_stmt (build2 (MODIFY_EXPR, TREE_TYPE (var), copy, var));
1341
  
1342 1343 1344
  push_value (copy);
}

Anthony Green committed
1345
tree
1346
build_address_of (tree value)
Anthony Green committed
1347 1348 1349 1350
{
  return build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (value)), value);
}

Ranjit Mathew committed
1351 1352
bool
class_has_finalize_method (tree type)
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
{
  tree super = CLASSTYPE_SUPER (type);

  if (super == NULL_TREE)
    return false;	/* Every class with a real finalizer inherits	*/
   			/* from java.lang.Object.			*/
  else
    return HAS_FINALIZER_P (type) || class_has_finalize_method (super);
}

1363 1364 1365 1366 1367 1368 1369
tree
java_create_object (tree type)
{
  tree alloc_node = (class_has_finalize_method (type) 
		     ? alloc_object_node
		     : alloc_no_finalizer_node);
  
1370 1371 1372
  return build_call_nary (promote_type (type),
			  build_address_of (alloc_node),
			  1, build_class_ref (type));
1373 1374
}

1375
static void
1376
expand_java_NEW (tree type)
Anthony Green committed
1377
{
1378 1379 1380 1381
  tree alloc_node;

  alloc_node = (class_has_finalize_method (type) ? alloc_object_node
		  				 : alloc_no_finalizer_node);
Anthony Green committed
1382 1383
  if (! CLASS_LOADED_P (type))
    load_class (type, 1);
1384
  safe_layout_class (type);
1385 1386 1387
  push_value (build_call_nary (promote_type (type),
			       build_address_of (alloc_node),
			       1, build_class_ref (type)));
Anthony Green committed
1388 1389
}

1390 1391 1392 1393
/* This returns an expression which will extract the class of an
   object.  */

tree
1394
build_get_class (tree value)
1395 1396 1397 1398
{
  tree class_field = lookup_field (&dtable_type, get_identifier ("class"));
  tree vtable_field = lookup_field (&object_type_node,
				    get_identifier ("vtable"));
1399 1400 1401 1402 1403 1404 1405
  tree tmp = build3 (COMPONENT_REF, dtable_ptr_type,
		     build_java_indirect_ref (object_type_node, value,
					      flag_check_references),
		     vtable_field, NULL_TREE);
  return build3 (COMPONENT_REF, class_ptr_type,
		 build1 (INDIRECT_REF, dtable_type, tmp),
		 class_field, NULL_TREE);
1406 1407 1408 1409 1410 1411 1412
}

/* This builds the tree representation of the `instanceof' operator.
   It tries various tricks to optimize this in cases where types are
   known.  */

tree
1413
build_instanceof (tree value, tree type)
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
{
  tree expr;
  tree itype = TREE_TYPE (TREE_TYPE (soft_instanceof_node));
  tree valtype = TREE_TYPE (TREE_TYPE (value));
  tree valclass = TYPE_NAME (valtype);
  tree klass;

  /* When compiling from bytecode, we need to ensure that TYPE has
     been loaded.  */
  if (CLASS_P (type) && ! CLASS_LOADED_P (type))
    {
      load_class (type, 1);
1426
      safe_layout_class (type);
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
      if (! TYPE_SIZE (type) || TREE_CODE (TYPE_SIZE (type)) == ERROR_MARK)
	return error_mark_node;
    }
  klass = TYPE_NAME (type);

  if (type == object_type_node || inherits_from_p (valtype, type))
    {
      /* Anything except `null' is an instance of Object.  Likewise,
	 if the object is known to be an instance of the class, then
	 we only need to check for `null'.  */
1437
      expr = build2 (NE_EXPR, itype, value, null_pointer_node);
1438
    }
1439 1440
  else if (flag_verify_invocations
	   && ! TYPE_ARRAY_P (type)
1441 1442
	   && ! TYPE_ARRAY_P (valtype)
	   && DECL_P (klass) && DECL_P (valclass)
1443
	   && ! CLASS_INTERFACE (valclass)
1444 1445 1446 1447 1448 1449 1450 1451 1452
	   && ! CLASS_INTERFACE (klass)
	   && ! inherits_from_p (type, valtype)
	   && (CLASS_FINAL (klass)
	       || ! inherits_from_p (valtype, type)))
    {
      /* The classes are from different branches of the derivation
	 tree, so we immediately know the answer.  */
      expr = boolean_false_node;
    }
1453
  else if (DECL_P (klass) && CLASS_FINAL (klass))
1454 1455
    {
      tree save = save_expr (value);
1456 1457 1458 1459 1460 1461 1462
      expr = build3 (COND_EXPR, itype,
		     build2 (NE_EXPR, boolean_type_node,
			     save, null_pointer_node),
		     build2 (EQ_EXPR, itype,
			     build_get_class (save),
			     build_class_ref (type)),
		     boolean_false_node);
1463 1464 1465
    }
  else
    {
1466 1467 1468
      expr = build_call_nary (itype,
			      build_address_of (soft_instanceof_node),
			      2, value, build_class_ref (type));
1469 1470 1471 1472 1473
    }
  TREE_SIDE_EFFECTS (expr) = TREE_SIDE_EFFECTS (value);
  return expr;
}

1474
static void
1475
expand_java_INSTANCEOF (tree type)
Anthony Green committed
1476 1477
{
  tree value = pop_value (object_ptr_type_node);
1478
  value = build_instanceof (value, type);
Anthony Green committed
1479 1480 1481
  push_value (value);
}

1482
static void
1483
expand_java_CHECKCAST (tree type)
Anthony Green committed
1484 1485
{
  tree value = pop_value (ptr_type_node);
1486 1487 1488
  value = build_call_nary (promote_type (type),
			   build_address_of (soft_checkcast_node),
			   2, build_class_ref (type), value);
Anthony Green committed
1489 1490 1491
  push_value (value);
}

1492
static void
1493
expand_iinc (unsigned int local_var_index, int ival, int pc)
Anthony Green committed
1494
{
1495 1496
  tree local_var, res;
  tree constant_value;
Anthony Green committed
1497

1498 1499
  flush_quick_stack ();
  local_var = find_local_variable (local_var_index, int_type_node, pc);
1500
  constant_value = build_int_cst (NULL_TREE, ival);
1501
  res = fold_build2 (PLUS_EXPR, int_type_node, local_var, constant_value);
1502
  java_add_stmt (build2 (MODIFY_EXPR, TREE_TYPE (local_var), local_var, res));
Anthony Green committed
1503 1504
}

1505

1506
tree
1507
build_java_soft_divmod (enum tree_code op, tree type, tree op1, tree op2)
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
{
  tree call = NULL;
  tree arg1 = convert (type, op1);
  tree arg2 = convert (type, op2);

  if (type == int_type_node)
    {	  
      switch (op)
	{
	case TRUNC_DIV_EXPR:
	  call = soft_idiv_node;
	  break;
	case TRUNC_MOD_EXPR:
	  call = soft_irem_node;
	  break;
Kaveh R. Ghazi committed
1523 1524
	default:
	  break;
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
	}
    }
  else if (type == long_type_node)
    {	  
      switch (op)
	{
	case TRUNC_DIV_EXPR:
	  call = soft_ldiv_node;
	  break;
	case TRUNC_MOD_EXPR:
	  call = soft_lrem_node;
	  break;
Kaveh R. Ghazi committed
1537 1538
	default:
	  break;
1539 1540 1541
	}
    }

1542
  gcc_assert (call);
1543
  call = build_call_nary (type, build_address_of (call), 2, arg1, arg2);
1544 1545 1546
  return call;
}

Anthony Green committed
1547
tree
1548
build_java_binop (enum tree_code op, tree type, tree arg1, tree arg2)
Anthony Green committed
1549 1550 1551 1552 1553 1554
{
  tree mask;
  switch (op)
    {
    case URSHIFT_EXPR:
      {
1555
	tree u_type = unsigned_type_for (type);
Anthony Green committed
1556 1557 1558 1559 1560 1561
	arg1 = convert (u_type, arg1);
	arg1 = build_java_binop (RSHIFT_EXPR, u_type, arg1, arg2);
	return convert (type, arg1);
      }
    case LSHIFT_EXPR:
    case RSHIFT_EXPR:
1562
      mask = build_int_cst (NULL_TREE,
1563
			    TYPE_PRECISION (TREE_TYPE (arg1)) - 1);
1564
      arg2 = fold_build2 (BIT_AND_EXPR, int_type_node, arg2, mask);
Anthony Green committed
1565 1566 1567 1568 1569 1570
      break;

    case COMPARE_L_EXPR:  /* arg1 > arg2 ?  1 : arg1 == arg2 ? 0 : -1 */
    case COMPARE_G_EXPR:  /* arg1 < arg2 ? -1 : arg1 == arg2 ? 0 :  1 */
      arg1 = save_expr (arg1);  arg2 = save_expr (arg2);
      {
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
	tree ifexp1 = fold_build2 (op == COMPARE_L_EXPR ? GT_EXPR : LT_EXPR,
				   boolean_type_node, arg1, arg2);
	tree ifexp2 = fold_build2 (EQ_EXPR, boolean_type_node, arg1, arg2);
	tree second_compare = fold_build3 (COND_EXPR, int_type_node,
					   ifexp2, integer_zero_node,
					   op == COMPARE_L_EXPR
					   ? integer_minus_one_node
					   : integer_one_node);
	return fold_build3 (COND_EXPR, int_type_node, ifexp1,
			    op == COMPARE_L_EXPR ? integer_one_node
			    : integer_minus_one_node,
			    second_compare);
Anthony Green committed
1583 1584 1585 1586
      }
    case COMPARE_EXPR:
      arg1 = save_expr (arg1);  arg2 = save_expr (arg2);
      {
1587 1588 1589 1590 1591 1592 1593
	tree ifexp1 = fold_build2 (LT_EXPR, boolean_type_node, arg1, arg2);
	tree ifexp2 = fold_build2 (GT_EXPR, boolean_type_node, arg1, arg2);
	tree second_compare = fold_build3 (COND_EXPR, int_type_node,
					   ifexp2, integer_one_node,
					   integer_zero_node);
	return fold_build3 (COND_EXPR, int_type_node,
			    ifexp1, integer_minus_one_node, second_compare);
1594 1595
      }      
    case TRUNC_DIV_EXPR:
Anthony Green committed
1596
    case TRUNC_MOD_EXPR:
1597 1598
      if (TREE_CODE (type) == REAL_TYPE
	  && op == TRUNC_MOD_EXPR)
Anthony Green committed
1599 1600 1601 1602 1603 1604 1605
	{
	  tree call;
	  if (type != double_type_node)
	    {
	      arg1 = convert (double_type_node, arg1);
	      arg2 = convert (double_type_node, arg2);
	    }
1606 1607 1608
	  call = build_call_nary (double_type_node,
				  build_address_of (soft_fmod_node),
				  2, arg1, arg2);
Anthony Green committed
1609 1610 1611 1612
	  if (type != double_type_node)
	    call = convert (type, call);
	  return call;
	}
1613 1614 1615 1616 1617 1618
      
      if (TREE_CODE (type) == INTEGER_TYPE
	  && flag_use_divide_subroutine
	  && ! flag_syntax_only)
	return build_java_soft_divmod (op, type, arg1, arg2);
      
Anthony Green committed
1619
      break;
1620
    default:  ;
Anthony Green committed
1621
    }
1622
  return fold_build2 (op, type, arg1, arg2);
Anthony Green committed
1623 1624
}

1625
static void
1626
expand_java_binop (tree type, enum tree_code op)
Anthony Green committed
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
{
  tree larg, rarg;
  tree ltype = type;
  tree rtype = type;
  switch (op)
    {
    case LSHIFT_EXPR:
    case RSHIFT_EXPR:
    case URSHIFT_EXPR:
      rtype = int_type_node;
      rarg = pop_value (rtype);
      break;
    default:
      rarg = pop_value (rtype);
    }
  larg = pop_value (ltype);
  push_value (build_java_binop (op, type, larg, rarg));
}

/* Lookup the field named NAME in *TYPEP or its super classes.
   If not found, return NULL_TREE.
1648 1649
   (If the *TYPEP is not found, or if the field reference is
   ambiguous, return error_mark_node.)
Anthony Green committed
1650 1651 1652 1653
   If found, return the FIELD_DECL, and set *TYPEP to the
   class containing the field. */

tree
1654
lookup_field (tree *typep, tree name)
Anthony Green committed
1655 1656 1657 1658
{
  if (CLASS_P (*typep) && !CLASS_LOADED_P (*typep))
    {
      load_class (*typep, 1);
1659
      safe_layout_class (*typep);
1660
      if (!TYPE_SIZE (*typep) || TREE_CODE (TYPE_SIZE (*typep)) == ERROR_MARK)
Anthony Green committed
1661 1662 1663 1664
	return error_mark_node;
    }
  do
    {
Nathan Sidwell committed
1665
      tree field, binfo, base_binfo;
1666
      tree save_field;
Nathan Sidwell committed
1667
      int i;
1668 1669 1670 1671 1672 1673

      for (field = TYPE_FIELDS (*typep); field; field = TREE_CHAIN (field))
	if (DECL_NAME (field) == name)
	  return field;

      /* Process implemented interfaces. */
1674
      save_field = NULL_TREE;
Nathan Sidwell committed
1675 1676
      for (binfo = TYPE_BINFO (*typep), i = 0;
	   BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
Anthony Green committed
1677
	{
Nathan Sidwell committed
1678
	  tree t = BINFO_TYPE (base_binfo);
1679
	  if ((field = lookup_field (&t, name)))
1680
	    {
1681 1682
	      if (save_field == field)
		continue;
1683 1684 1685 1686 1687 1688
	      if (save_field == NULL_TREE)
		save_field = field;
	      else
		{
		  tree i1 = DECL_CONTEXT (save_field);
		  tree i2 = DECL_CONTEXT (field);
1689
		  error ("reference %qs is ambiguous: appears in interface %qs and interface %qs",
1690 1691 1692 1693 1694 1695
			 IDENTIFIER_POINTER (name),
			 IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (i1))),
			 IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (i2))));
		  return error_mark_node;
		}
	    }
Anthony Green committed
1696
	}
1697 1698 1699 1700

      if (save_field != NULL_TREE)
	return save_field;

Anthony Green committed
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
      *typep = CLASSTYPE_SUPER (*typep);
    } while (*typep);
  return NULL_TREE;
}

/* Look up the field named NAME in object SELF_VALUE,
   which has class SELF_CLASS (a non-handle RECORD_TYPE).
   SELF_VALUE is NULL_TREE if looking for a static field. */

tree
1711
build_field_ref (tree self_value, tree self_class, tree name)
Anthony Green committed
1712 1713 1714 1715 1716
{
  tree base_class = self_class;
  tree field_decl = lookup_field (&base_class, name);
  if (field_decl == NULL_TREE)
    {
1717
      error ("field %qs not found", IDENTIFIER_POINTER (name));
Anthony Green committed
1718 1719 1720 1721 1722 1723 1724 1725
      return error_mark_node;
    }
  if (self_value == NULL_TREE)
    {
      return build_static_field_ref (field_decl);
    }
  else
    {
1726
      tree base_type = promote_type (base_class);
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737

      /* CHECK is true if self_value is not the this pointer.  */
      int check = (! (DECL_P (self_value)
		      && DECL_NAME (self_value) == this_identifier_node));

      /* Determine whether a field offset from NULL will lie within
	 Page 0: this is necessary on those GNU/Linux/BSD systems that
	 trap SEGV to generate NullPointerExceptions.  

	 We assume that Page 0 will be mapped with NOPERM, and that
	 memory may be allocated from any other page, so only field
1738
	 offsets < pagesize are guaranteed to trap.  We also assume
1739
	 the smallest page size we'll encounter is 4k bytes.  */
1740 1741
      if (! flag_syntax_only && check && ! flag_check_references 
	  && ! flag_indirect_dispatch)
1742 1743 1744 1745 1746 1747 1748
	{
	  tree field_offset = byte_position (field_decl);
	  if (! page_size)
	    page_size = size_int (4096); 	      
	  check = ! INT_CST_LT_UNSIGNED (field_offset, page_size);
	}

1749
      if (base_type != TREE_TYPE (self_value))
1750
	self_value = fold_build1 (NOP_EXPR, base_type, self_value);
1751
      if (! flag_syntax_only && flag_indirect_dispatch)
1752
	{
1753
	  tree otable_index
1754
	    = build_int_cst (NULL_TREE, get_symbol_table_index 
1755 1756
			     (field_decl, NULL_TREE, 
			      &TYPE_OTABLE_METHODS (output_class)));
1757
	  tree field_offset
1758 1759 1760
	    = build4 (ARRAY_REF, integer_type_node,
		      TYPE_OTABLE_DECL (output_class), otable_index,
		      NULL_TREE, NULL_TREE);
1761
	  tree address;
1762

1763 1764 1765 1766 1767
	  if (DECL_CONTEXT (field_decl) != output_class)
	    field_offset
	      = build3 (COND_EXPR, TREE_TYPE (field_offset),
			build2 (EQ_EXPR, boolean_type_node,
				field_offset, integer_zero_node),
1768 1769 1770
			build_call_nary (void_type_node, 
					 build_address_of (soft_nosuchfield_node),
					 1, otable_index),
1771 1772
			field_offset);
	  
1773
	  field_offset = fold (convert (sizetype, field_offset));
1774
	  self_value = java_check_reference (self_value, check);
1775
	  address 
Andrew Pinski committed
1776
	    = fold_build2 (POINTER_PLUS_EXPR, 
1777
			   TREE_TYPE (self_value),
1778
			   self_value, field_offset);
1779 1780
	  address = fold_convert (build_pointer_type (TREE_TYPE (field_decl)),
				  address);
1781
	  return fold_build1 (INDIRECT_REF, TREE_TYPE (field_decl), address);
1782 1783
	}

1784
      self_value = build_java_indirect_ref (TREE_TYPE (TREE_TYPE (self_value)),
1785
					    self_value, check);
1786 1787
      return fold_build3 (COMPONENT_REF, TREE_TYPE (field_decl),
			  self_value, field_decl, NULL_TREE);
Anthony Green committed
1788 1789 1790 1791
    }
}

tree
1792
lookup_label (int pc)
Anthony Green committed
1793 1794
{
  tree name;
1795
  char buf[32];
1796 1797 1798
  if (pc > highest_label_pc_this_method)
    highest_label_pc_this_method = pc;
  ASM_GENERATE_INTERNAL_LABEL(buf, "LJpc=", start_label_pc_this_method + pc);
Anthony Green committed
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
  name = get_identifier (buf);
  if (IDENTIFIER_LOCAL_VALUE (name))
    return IDENTIFIER_LOCAL_VALUE (name);
  else
    {
      /* The type of the address of a label is return_address_type_node. */
      tree decl = create_label_decl (name);
      return pushdecl (decl);
    }
}

Per Bothner committed
1810 1811 1812 1813
/* Generate a unique name for the purpose of loops and switches
   labels, and try-catch-finally blocks label or temporary variables.  */

tree
1814
generate_name (void)
Per Bothner committed
1815 1816
{
  static int l_number = 0;
1817 1818 1819
  char buff [32];
  ASM_GENERATE_INTERNAL_LABEL(buff, "LJv", l_number);
  l_number++;
Per Bothner committed
1820 1821 1822
  return get_identifier (buff);
}

Anthony Green committed
1823
tree
1824
create_label_decl (tree name)
Anthony Green committed
1825 1826
{
  tree decl;
1827
  decl = build_decl (input_location, LABEL_DECL, name, 
Anthony Green committed
1828 1829 1830 1831 1832 1833
		     TREE_TYPE (return_address_type_node));
  DECL_CONTEXT (decl) = current_function_decl;
  DECL_IGNORED_P (decl) = 1;
  return decl;
}

1834
/* This maps a bytecode offset (PC) to various flags.  */
Anthony Green committed
1835 1836
char *instruction_bits;

1837 1838 1839 1840 1841 1842
/* This is a vector of type states for the current method.  It is
   indexed by PC.  Each element is a tree vector holding the type
   state at that PC.  We only note type states at basic block
   boundaries.  */
VEC(tree, gc) *type_states;

1843
static void
1844
note_label (int current_pc ATTRIBUTE_UNUSED, int target_pc)
Anthony Green committed
1845 1846 1847 1848 1849 1850 1851 1852
{
  lookup_label (target_pc);
  instruction_bits [target_pc] |= BCODE_JUMP_TARGET;
}

/* Emit code to jump to TARGET_PC if VALUE1 CONDITION VALUE2,
   where CONDITION is one of one the compare operators. */

1853
static void
1854 1855
expand_compare (enum tree_code condition, tree value1, tree value2,
		int target_pc)
Anthony Green committed
1856 1857
{
  tree target = lookup_label (target_pc);
1858
  tree cond = fold_build2 (condition, boolean_type_node, value1, value2);
1859
  java_add_stmt 
1860 1861 1862
    (build3 (COND_EXPR, void_type_node, java_truthvalue_conversion (cond),
	     build1 (GOTO_EXPR, void_type_node, target), 
	     build_java_empty_stmt ()));
Anthony Green committed
1863 1864 1865 1866
}

/* Emit code for a TEST-type opcode. */

1867
static void
1868
expand_test (enum tree_code condition, tree type, int target_pc)
Anthony Green committed
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
{
  tree value1, value2;
  flush_quick_stack ();
  value1 = pop_value (type);
  value2 = (type == ptr_type_node) ? null_pointer_node : integer_zero_node;
  expand_compare (condition, value1, value2, target_pc);
}

/* Emit code for a COND-type opcode. */

1879
static void
1880
expand_cond (enum tree_code condition, tree type, int target_pc)
Anthony Green committed
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
{
  tree value1, value2;
  flush_quick_stack ();
  /* note: pop values in opposite order */
  value2 = pop_value (type);
  value1 = pop_value (type);
  /* Maybe should check value1 and value2 for type compatibility ??? */
  expand_compare (condition, value1, value2, target_pc);
}

1891
static void
1892
expand_java_goto (int target_pc)
Anthony Green committed
1893 1894 1895
{
  tree target_label = lookup_label (target_pc);
  flush_quick_stack ();
1896
  java_add_stmt (build1 (GOTO_EXPR, void_type_node, target_label));
1897 1898 1899 1900 1901 1902 1903 1904
}

static tree
expand_java_switch (tree selector, int default_pc)
{
  tree switch_expr, x;

  flush_quick_stack ();
1905 1906
  switch_expr = build3 (SWITCH_EXPR, TREE_TYPE (selector), selector,
			NULL_TREE, NULL_TREE);
1907 1908
  java_add_stmt (switch_expr);

1909
  x = build3 (CASE_LABEL_EXPR, void_type_node, NULL_TREE, NULL_TREE,
1910
	      create_artificial_label (input_location));
1911 1912
  append_to_statement_list (x, &SWITCH_BODY (switch_expr));

1913
  x = build1 (GOTO_EXPR, void_type_node, lookup_label (default_pc));
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
  append_to_statement_list (x, &SWITCH_BODY (switch_expr));

  return switch_expr;
}

static void
expand_java_add_case (tree switch_expr, int match, int target_pc)
{
  tree value, x;

1924
  value = build_int_cst (TREE_TYPE (switch_expr), match);
1925
  
1926
  x = build3 (CASE_LABEL_EXPR, void_type_node, value, NULL_TREE,
1927
	      create_artificial_label (input_location));
1928 1929
  append_to_statement_list (x, &SWITCH_BODY (switch_expr));

1930
  x = build1 (GOTO_EXPR, void_type_node, lookup_label (target_pc));
1931
  append_to_statement_list (x, &SWITCH_BODY (switch_expr));
Anthony Green committed
1932 1933
}

1934
static tree
1935
pop_arguments (tree arg_types)
Anthony Green committed
1936
{
1937
  if (arg_types == end_params_node)
Anthony Green committed
1938 1939 1940 1941
    return NULL_TREE;
  if (TREE_CODE (arg_types) == TREE_LIST)
    {
      tree tail = pop_arguments (TREE_CHAIN (arg_types));
Per Bothner committed
1942 1943
      tree type = TREE_VALUE (arg_types);
      tree arg = pop_value (type);
1944

1945 1946 1947 1948 1949
      /* We simply cast each argument to its proper type.  This is
	 needed since we lose type information coming out of the
	 verifier.  We also have to do this when we pop an integer
	 type that must be promoted for the function call.  */
      if (TREE_CODE (type) == POINTER_TYPE)
1950 1951 1952 1953
	arg = build1 (NOP_EXPR, type, arg);
      else if (targetm.calls.promote_prototypes (type)
	       && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node)
	       && INTEGRAL_TYPE_P (type))
Per Bothner committed
1954 1955
	arg = convert (integer_type_node, arg);
      return tree_cons (NULL_TREE, arg, tail);
Anthony Green committed
1956
    }
1957
  gcc_unreachable ();
Anthony Green committed
1958 1959
}

1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
/* Attach to PTR (a block) the declaration found in ENTRY. */

int
attach_init_test_initialization_flags (void **entry, void *ptr)
{
  tree block = (tree)ptr;
  struct treetreehash_entry *ite = (struct treetreehash_entry *) *entry;

  if (block != error_mark_node)
    {
      if (TREE_CODE (block) == BIND_EXPR)
        {
	  tree body = BIND_EXPR_BODY (block);
	  TREE_CHAIN (ite->value) = BIND_EXPR_VARS (block);
	  BIND_EXPR_VARS (block) = ite->value;
	  body = build2 (COMPOUND_EXPR, void_type_node,
			 build1 (DECL_EXPR, void_type_node, ite->value), body);
	  BIND_EXPR_BODY (block) = body;
	}
      else
	{
	  tree body = BLOCK_SUBBLOCKS (block);
	  TREE_CHAIN (ite->value) = BLOCK_EXPR_DECLS (block);
	  BLOCK_EXPR_DECLS (block) = ite->value;
	  body = build2 (COMPOUND_EXPR, void_type_node,
			 build1 (DECL_EXPR, void_type_node, ite->value), body);
	  BLOCK_SUBBLOCKS (block) = body;
        }
      
    }
  return true;
}

Anthony Green committed
1993 1994 1995 1996 1997
/* Build an expression to initialize the class CLAS.
   if EXPR is non-NULL, returns an expression to first call the initializer
   (if it is needed) and then calls EXPR. */

tree
1998
build_class_init (tree clas, tree expr)
Anthony Green committed
1999
{
2000
  tree init;
2001 2002 2003 2004 2005 2006 2007 2008

  /* An optimization: if CLAS is a superclass of the class we're
     compiling, we don't need to initialize it.  However, if CLAS is
     an interface, it won't necessarily be initialized, even if we
     implement it.  */
  if ((! CLASS_INTERFACE (TYPE_NAME (clas))
       && inherits_from_p (current_class, clas))
      || current_class == clas)
Anthony Green committed
2009
    return expr;
2010 2011 2012

  if (always_initialize_class_p)
    {
2013 2014 2015
      init = build_call_nary (void_type_node,
			      build_address_of (soft_initclass_node),
			      1, build_class_ref (clas));
2016 2017 2018 2019
      TREE_SIDE_EFFECTS (init) = 1;
    }
  else
    {
2020
      tree *init_test_decl;
2021
      tree decl;
2022 2023 2024 2025
      init_test_decl = java_treetreehash_new
	(DECL_FUNCTION_INIT_TEST_TABLE (current_function_decl), clas);

      if (*init_test_decl == NULL)
2026 2027 2028
	{
	  /* Build a declaration and mark it as a flag used to track
	     static class initializations. */
2029
	  decl = build_decl (input_location, VAR_DECL, NULL_TREE,
2030 2031 2032 2033
			     boolean_type_node);
	  MAYBE_CREATE_VAR_LANG_DECL_SPECIFIC (decl);
	  DECL_CONTEXT (decl) = current_function_decl;
	  DECL_INITIAL (decl) = boolean_false_node;
2034
	  /* Don't emit any symbolic debugging info for this decl.  */
2035 2036
	  DECL_IGNORED_P (decl) = 1;	  
	  *init_test_decl = decl;
2037
	}
2038

2039 2040 2041
      init = build_call_nary (void_type_node,
			      build_address_of (soft_initclass_node),
			      1, build_class_ref (clas));
2042
      TREE_SIDE_EFFECTS (init) = 1;
2043 2044 2045 2046
      init = build3 (COND_EXPR, void_type_node,
		     build2 (EQ_EXPR, boolean_type_node, 
			     *init_test_decl, boolean_false_node),
		     init, integer_zero_node);
2047
      TREE_SIDE_EFFECTS (init) = 1;
2048 2049 2050
      init = build2 (COMPOUND_EXPR, TREE_TYPE (expr), init, 
		     build2 (MODIFY_EXPR, boolean_type_node,
			     *init_test_decl, boolean_true_node));
2051 2052 2053
      TREE_SIDE_EFFECTS (init) = 1;
    }

Anthony Green committed
2054 2055
  if (expr != NULL_TREE)
    {
2056
      expr = build2 (COMPOUND_EXPR, TREE_TYPE (expr), init, expr);
Anthony Green committed
2057 2058 2059 2060 2061 2062
      TREE_SIDE_EFFECTS (expr) = 1;
      return expr;
    }
  return init;
}

Andrew Haley committed
2063 2064 2065


/* Rewrite expensive calls that require stack unwinding at runtime to
2066
   cheaper alternatives.  The logic here performs these
Andrew Haley committed
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
   transformations:

   java.lang.Class.forName("foo") -> java.lang.Class.forName("foo", class$)
   java.lang.Class.getClassLoader() -> java.lang.Class.getClassLoader(class$)

*/

typedef struct
{
  const char *classname;
  const char *method;
  const char *signature;
2079
  const char *new_classname;
Andrew Haley committed
2080 2081 2082 2083 2084
  const char *new_signature;
  int flags;
  tree (*rewrite_arglist) (tree arglist);
} rewrite_rule;

2085 2086 2087 2088 2089 2090 2091
/* Add __builtin_return_address(0) to the end of an arglist.  */


static tree 
rewrite_arglist_getcaller (tree arglist)
{
  tree retaddr 
2092 2093
    = build_call_expr (built_in_decls[BUILT_IN_RETURN_ADDRESS],
		       1, integer_zero_node);
2094

2095 2096
  DECL_UNINLINABLE (current_function_decl) = 1;
  
2097 2098 2099 2100 2101
  return chainon (arglist, 
		  tree_cons (NULL_TREE, retaddr, 
			     NULL_TREE));
}

Andrew Haley committed
2102 2103 2104 2105 2106 2107
/* Add this.class to the end of an arglist.  */

static tree 
rewrite_arglist_getclass (tree arglist)
{
  return chainon (arglist, 
2108 2109
		  tree_cons (NULL_TREE, build_class_ref (output_class),
			     NULL_TREE));
Andrew Haley committed
2110 2111 2112 2113
}

static rewrite_rule rules[] =
  {{"java.lang.Class", "getClassLoader", "()Ljava/lang/ClassLoader;", 
2114
    "java.lang.Class", "(Ljava/lang/Class;)Ljava/lang/ClassLoader;", 
Andrew Haley committed
2115
    ACC_FINAL|ACC_PRIVATE, rewrite_arglist_getclass},
2116

Andrew Haley committed
2117
   {"java.lang.Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;",
2118
    "java.lang.Class", "(Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Class;",
Andrew Haley committed
2119
    ACC_FINAL|ACC_PRIVATE|ACC_STATIC, rewrite_arglist_getclass},
2120

2121
   {"gnu.classpath.VMStackWalker", "getCallingClass", "()Ljava/lang/Class;",
2122
    "gnu.classpath.VMStackWalker", "(Lgnu/gcj/RawData;)Ljava/lang/Class;",
2123
    ACC_FINAL|ACC_PRIVATE|ACC_STATIC, rewrite_arglist_getcaller},
2124

2125 2126
   {"gnu.classpath.VMStackWalker", "getCallingClassLoader", 
    "()Ljava/lang/ClassLoader;",
2127
    "gnu.classpath.VMStackWalker", "(Lgnu/gcj/RawData;)Ljava/lang/ClassLoader;",
2128 2129
    ACC_FINAL|ACC_PRIVATE|ACC_STATIC, rewrite_arglist_getcaller},

2130 2131 2132 2133 2134
   {"gnu.java.lang.VMCPStringBuilder", "toString", "([CII)Ljava/lang/String;", 
    "java.lang.String", "([CII)Ljava/lang/String;",
    ACC_FINAL|ACC_PRIVATE|ACC_STATIC, NULL},

   {NULL, NULL, NULL, NULL, NULL, 0, NULL}};
Andrew Haley committed
2135

2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
/* True if this method is special, i.e. it's a private method that
   should be exported from a DSO.  */

bool
special_method_p (tree candidate_method)
{
  tree context = DECL_NAME (TYPE_NAME (DECL_CONTEXT (candidate_method)));
  tree method = DECL_NAME (candidate_method);
  rewrite_rule *p;

  for (p = rules; p->classname; p++)
    {
      if (get_identifier (p->classname) == context
	  && get_identifier (p->method) == method)
	return true;
    }
  return false;
}

Andrew Haley committed
2155
/* Scan the rules list for replacements for *METHOD_P and replace the
2156 2157
   args accordingly.  If the rewrite results in an access to a private
   method, update SPECIAL.*/
Andrew Haley committed
2158 2159 2160

void
maybe_rewrite_invocation (tree *method_p, tree *arg_list_p, 
2161
			  tree *method_signature_p, tree *special)
Andrew Haley committed
2162 2163 2164
{
  tree context = DECL_NAME (TYPE_NAME (DECL_CONTEXT (*method_p)));
  rewrite_rule *p;
2165 2166
  *special = NULL_TREE;

Andrew Haley committed
2167 2168 2169 2170 2171 2172 2173 2174
  for (p = rules; p->classname; p++)
    {
      if (get_identifier (p->classname) == context)
	{
	  tree method = DECL_NAME (*method_p);
	  if (get_identifier (p->method) == method
	      && get_identifier (p->signature) == *method_signature_p)
	    {
2175 2176 2177 2178 2179 2180
	      tree maybe_method;
	      tree destination_class 
		= lookup_class (get_identifier (p->new_classname));
	      gcc_assert (destination_class);
	      maybe_method
		= lookup_java_method (destination_class,
Andrew Haley committed
2181 2182 2183 2184 2185
				      method,
				      get_identifier (p->new_signature));
	      if (! maybe_method && ! flag_verify_invocations)
		{
		  maybe_method
2186
		    = add_method (destination_class, p->flags, 
Andrew Haley committed
2187 2188 2189 2190 2191
				  method, get_identifier (p->new_signature));
		  DECL_EXTERNAL (maybe_method) = 1;
		}
	      *method_p = maybe_method;
	      gcc_assert (*method_p);
2192 2193
	      if (p->rewrite_arglist)
		*arg_list_p = p->rewrite_arglist (*arg_list_p);
Andrew Haley committed
2194
	      *method_signature_p = get_identifier (p->new_signature);
2195
	      *special = integer_one_node;
Andrew Haley committed
2196 2197 2198 2199 2200 2201 2202 2203 2204

	      break;
	    }
	}
    }
}



Anthony Green committed
2205
tree
2206 2207
build_known_method_ref (tree method, tree method_type ATTRIBUTE_UNUSED,
			tree self_type, tree method_signature ATTRIBUTE_UNUSED,
2208
			tree arg_list ATTRIBUTE_UNUSED, tree special)
Anthony Green committed
2209 2210
{
  tree func;
Per Bothner committed
2211
  if (is_compiled_class (self_type))
Anthony Green committed
2212
    {
2213
      /* With indirect dispatch we have to use indirect calls for all
2214
	 publicly visible methods or gcc will use PLT indirections
2215 2216 2217 2218
	 to reach them.  We also have to use indirect dispatch for all
	 external methods.  */
      if (! flag_indirect_dispatch 
	  || (! DECL_EXTERNAL (method) && ! TREE_PUBLIC (method)))
2219
	{
2220 2221
	  func = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (method)),
			 method);
2222 2223 2224
	}
      else
	{
2225
	  tree table_index
2226 2227 2228 2229
	    = build_int_cst (NULL_TREE, 
			     (get_symbol_table_index 
			      (method, special,
			       &TYPE_ATABLE_METHODS (output_class))));
2230 2231 2232 2233 2234
	  func 
	    = build4 (ARRAY_REF,  
		      TREE_TYPE (TREE_TYPE (TYPE_ATABLE_DECL (output_class))),
		      TYPE_ATABLE_DECL (output_class), table_index,
		      NULL_TREE, NULL_TREE);
2235
	}
2236
      func = convert (method_ptr_type_node, func);
Anthony Green committed
2237 2238 2239 2240 2241
    }
  else
    {
      /* We don't know whether the method has been (statically) compiled.
	 Compile this code to get a reference to the method's code:
2242

Anthony Green committed
2243
	 SELF_TYPE->methods[METHOD_INDEX].ncode
2244

2245
      */
2246

Anthony Green committed
2247
      int method_index = 0;
2248 2249 2250 2251 2252 2253 2254
      tree meth, ref;

      /* The method might actually be declared in some superclass, so
	 we have to use its class context, not the caller's notion of
	 where the method is.  */
      self_type = DECL_CONTEXT (method);
      ref = build_class_ref (self_type);
Anthony Green committed
2255 2256 2257 2258 2259
      ref = build1 (INDIRECT_REF, class_type_node, ref);
      if (ncode_ident == NULL_TREE)
	ncode_ident = get_identifier ("ncode");
      if (methods_ident == NULL_TREE)
	methods_ident = get_identifier ("methods");
2260 2261 2262
      ref = build3 (COMPONENT_REF, method_ptr_type_node, ref,
		    lookup_field (&class_type_node, methods_ident),
		    NULL_TREE);
2263
      for (meth = TYPE_METHODS (self_type);
Anthony Green committed
2264 2265 2266 2267 2268
	   ; meth = TREE_CHAIN (meth))
	{
	  if (method == meth)
	    break;
	  if (meth == NULL_TREE)
2269 2270
	    fatal_error ("method '%s' not found in class",
			 IDENTIFIER_POINTER (DECL_NAME (method)));
Anthony Green committed
2271 2272 2273
	  method_index++;
	}
      method_index *= int_size_in_bytes (method_type_node);
Andrew Pinski committed
2274 2275
      ref = fold_build2 (POINTER_PLUS_EXPR, method_ptr_type_node,
			 ref, size_int (method_index));
Anthony Green committed
2276
      ref = build1 (INDIRECT_REF, method_type_node, ref);
2277 2278 2279
      func = build3 (COMPONENT_REF, nativecode_ptr_type_node,
		     ref, lookup_field (&method_type_node, ncode_ident),
		     NULL_TREE);
Anthony Green committed
2280 2281 2282 2283 2284
    }
  return func;
}

tree
2285
invoke_build_dtable (int is_invoke_interface, tree arg_list)
Anthony Green committed
2286 2287 2288 2289 2290 2291 2292 2293 2294
{
  tree dtable, objectref;

  TREE_VALUE (arg_list) = save_expr (TREE_VALUE (arg_list));

  /* If we're dealing with interfaces and if the objectref
     argument is an array then get the dispatch table of the class
     Object rather than the one from the objectref.  */
  objectref = (is_invoke_interface 
2295 2296 2297
	       && is_array_type_p (TREE_TYPE (TREE_VALUE (arg_list)))
	       ? build_class_ref (object_type_node) : TREE_VALUE (arg_list));

Anthony Green committed
2298
  if (dtable_ident == NULL_TREE)
2299
    dtable_ident = get_identifier ("vtable");
2300 2301
  dtable = build_java_indirect_ref (object_type_node, objectref, 
				    flag_check_references);
2302 2303
  dtable = build3 (COMPONENT_REF, dtable_ptr_type, dtable,
		   lookup_field (&object_type_node, dtable_ident), NULL_TREE);
Anthony Green committed
2304 2305 2306 2307

  return dtable;
}

2308 2309
/* Determine the index in SYMBOL_TABLE for a reference to the decl
   T. If this decl has not been seen before, it will be added to the
2310 2311
   [oa]table_methods. If it has, the existing table slot will be
   reused.  */
2312

2313
int
2314
get_symbol_table_index (tree t, tree special, tree *symbol_table)
2315 2316 2317
{
  int i = 1;
  tree method_list;
2318 2319

  if (*symbol_table == NULL_TREE)
2320
    {
2321
      *symbol_table = build_tree_list (special, t);
2322 2323 2324
      return 1;
    }
  
2325
  method_list = *symbol_table;
2326 2327 2328
  
  while (1)
    {
2329
      tree value = TREE_VALUE (method_list);
2330 2331
      tree purpose = TREE_PURPOSE (method_list);
      if (value == t && purpose == special)
2332
	return i;
2333 2334 2335 2336 2337 2338 2339
      i++;
      if (TREE_CHAIN (method_list) == NULL_TREE)
        break;
      else
        method_list = TREE_CHAIN (method_list);
    }

2340
  TREE_CHAIN (method_list) = build_tree_list (special, t);
2341 2342 2343
  return i;
}

Anthony Green committed
2344
tree 
2345
build_invokevirtual (tree dtable, tree method, tree special)
Anthony Green committed
2346 2347 2348 2349
{
  tree func;
  tree nativecode_ptr_ptr_type_node
    = build_pointer_type (nativecode_ptr_type_node);
2350 2351
  tree method_index;
  tree otable_index;
2352

2353 2354
  if (flag_indirect_dispatch)
    {
2355
      gcc_assert (! CLASS_INTERFACE (TYPE_NAME (DECL_CONTEXT (method))));
2356

2357
      otable_index 
2358
	= build_int_cst (NULL_TREE, get_symbol_table_index 
2359 2360
			 (method, special,
			  &TYPE_OTABLE_METHODS (output_class)));
2361 2362 2363
      method_index = build4 (ARRAY_REF, integer_type_node, 
			     TYPE_OTABLE_DECL (output_class), 
			     otable_index, NULL_TREE, NULL_TREE);
2364
    }
2365
  else
2366
    {
2367 2368 2369 2370 2371
      /* We fetch the DECL_VINDEX field directly here, rather than
	 using get_method_index().  DECL_VINDEX is the true offset
	 from the vtable base to a method, regrdless of any extra
	 words inserted at the start of the vtable.  */
      method_index = DECL_VINDEX (method);
2372 2373 2374 2375 2376 2377
      method_index = size_binop (MULT_EXPR, method_index,
				 TYPE_SIZE_UNIT (nativecode_ptr_ptr_type_node));
      if (TARGET_VTABLE_USES_DESCRIPTORS)
	method_index = size_binop (MULT_EXPR, method_index,
				   size_int (TARGET_VTABLE_USES_DESCRIPTORS));
    }
2378

2379
  func = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (dtable), dtable,
Andrew Pinski committed
2380
		      convert (sizetype, method_index));
2381 2382 2383 2384

  if (TARGET_VTABLE_USES_DESCRIPTORS)
    func = build1 (NOP_EXPR, nativecode_ptr_type_node, func);
  else
2385 2386 2387 2388
    {
      func = fold_convert (nativecode_ptr_ptr_type_node, func);
      func = build1 (INDIRECT_REF, nativecode_ptr_type_node, func);
    }
Anthony Green committed
2389 2390 2391 2392

  return func;
}

2393
static GTY(()) tree class_ident;
2394
tree
2395
build_invokeinterface (tree dtable, tree method)
2396
{
2397 2398
  tree interface;
  tree idx;
2399

2400
  /* We expand invokeinterface here.  */
2401 2402
	    
  if (class_ident == NULL_TREE)
2403
    class_ident = get_identifier ("class");
2404

2405 2406
  dtable = build_java_indirect_ref (dtable_type, dtable,
				    flag_check_references);
2407 2408
  dtable = build3 (COMPONENT_REF, class_ptr_type, dtable,
		   lookup_field (&dtable_type, class_ident), NULL_TREE);
2409 2410

  interface = DECL_CONTEXT (method);
2411
  gcc_assert (CLASS_INTERFACE (TYPE_NAME (interface)));
2412
  layout_class_methods (interface);
2413
  
2414
  if (flag_indirect_dispatch)
2415
    {
2416 2417
      int itable_index 
	= 2 * (get_symbol_table_index 
2418
	       (method, NULL_TREE, &TYPE_ITABLE_METHODS (output_class)));
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
      interface 
	= build4 (ARRAY_REF, 
		 TREE_TYPE (TREE_TYPE (TYPE_ITABLE_DECL (output_class))),
		 TYPE_ITABLE_DECL (output_class), 
		  build_int_cst (NULL_TREE, itable_index-1),
		  NULL_TREE, NULL_TREE);
      idx 
	= build4 (ARRAY_REF, 
		 TREE_TYPE (TREE_TYPE (TYPE_ITABLE_DECL (output_class))),
		 TYPE_ITABLE_DECL (output_class), 
		  build_int_cst (NULL_TREE, itable_index),
		  NULL_TREE, NULL_TREE);
      interface = convert (class_ptr_type, interface);
      idx = convert (integer_type_node, idx);
2433 2434
    }
  else
2435 2436 2437 2438 2439
    {
      idx = build_int_cst (NULL_TREE, 
			   get_interface_method_index (method, interface));
      interface = build_class_ref (interface);
    }
2440
				     			  
2441 2442 2443
  return build_call_nary (ptr_type_node, 
			  build_address_of (soft_lookupinterfacemethod_node),
			  3, dtable, interface, idx);
2444 2445
}
  
Anthony Green committed
2446
/* Expand one of the invoke_* opcodes.
2447
   OPCODE is the specific opcode.
Anthony Green committed
2448 2449 2450
   METHOD_REF_INDEX is an index into the constant pool.
   NARGS is the number of arguments, or -1 if not specified. */

2451
static void
2452
expand_invoke (int opcode, int method_ref_index, int nargs ATTRIBUTE_UNUSED)
Anthony Green committed
2453
{
Ranjit Mathew committed
2454 2455
  tree method_signature
    = COMPONENT_REF_SIGNATURE(&current_jcf->cpool, method_ref_index);
2456 2457
  tree method_name = COMPONENT_REF_NAME (&current_jcf->cpool,
					 method_ref_index);
Ranjit Mathew committed
2458 2459 2460 2461
  tree self_type
    = get_class_constant (current_jcf,
                          COMPONENT_REF_CLASS_INDEX(&current_jcf->cpool,
                          method_ref_index));
2462
  const char *const self_name
2463
    = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (self_type)));
Anthony Green committed
2464
  tree call, func, method, arg_list, method_type;
2465
  tree check = NULL_TREE;
Anthony Green committed
2466

2467 2468
  tree special = NULL_TREE;

Anthony Green committed
2469 2470 2471
  if (! CLASS_LOADED_P (self_type))
    {
      load_class (self_type, 1);
2472
      safe_layout_class (self_type);
Anthony Green committed
2473
      if (TREE_CODE (TYPE_SIZE (self_type)) == ERROR_MARK)
2474
	fatal_error ("failed to find class '%s'", self_name);
Anthony Green committed
2475
    }
2476
  layout_class_methods (self_type);
Anthony Green committed
2477

2478
  if (ID_INIT_P (method_name))
2479
    method = lookup_java_constructor (self_type, method_signature);
Anthony Green committed
2480
  else
2481
    method = lookup_java_method (self_type, method_name, method_signature);
2482

2483 2484 2485 2486 2487 2488 2489 2490
  /* We've found a method in a class other than the one in which it
     was wanted.  This can happen if, for instance, we're trying to
     compile invokespecial super.equals().  
     FIXME: This is a kludge.  Rather than nullifying the result, we
     should change lookup_java_method() so that it doesn't search the
     superclass chain when we're BC-compiling.  */
  if (! flag_verify_invocations
      && method
2491
      && ! TYPE_ARRAY_P (self_type)
2492 2493 2494
      && self_type != DECL_CONTEXT (method))
    method = NULL_TREE;

2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
  /* We've found a method in an interface, but this isn't an interface
     call.  */
  if (opcode != OPCODE_invokeinterface
      && method
      && (CLASS_INTERFACE (TYPE_NAME (DECL_CONTEXT (method)))))
    method = NULL_TREE;

  /* We've found a non-interface method but we are making an
     interface call.  This can happen if the interface overrides a
     method in Object.  */
  if (! flag_verify_invocations
      && opcode == OPCODE_invokeinterface
      && method
      && ! CLASS_INTERFACE (TYPE_NAME (DECL_CONTEXT (method))))
    method = NULL_TREE;

Anthony Green committed
2511 2512
  if (method == NULL_TREE)
    {
2513
      if (flag_verify_invocations || ! flag_indirect_dispatch)
Anthony Green committed
2514
	{
2515 2516 2517 2518
	  error ("class '%s' has no method named '%s' matching signature '%s'",
		 self_name,
		 IDENTIFIER_POINTER (method_name),
		 IDENTIFIER_POINTER (method_signature));
Anthony Green committed
2519
	}
2520
      else
Anthony Green committed
2521
	{
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
	  int flags = ACC_PUBLIC;
	  if (opcode == OPCODE_invokestatic)
	    flags |= ACC_STATIC;
	  if (opcode == OPCODE_invokeinterface)
	    {
	      flags |= ACC_INTERFACE | ACC_ABSTRACT;
	      CLASS_INTERFACE (TYPE_NAME (self_type)) = 1;
	    }
	  method = add_method (self_type, flags, method_name,
			       method_signature);
	  DECL_ARTIFICIAL (method) = 1;
	  METHOD_DUMMY (method) = 1;
	  layout_class_method (self_type, NULL,
			       method, NULL);
Anthony Green committed
2536 2537
	}
    }
2538 2539 2540

  /* Invoke static can't invoke static/abstract method */
  if (method != NULL_TREE)
Anthony Green committed
2541
    {
2542
      if (opcode == OPCODE_invokestatic)
Anthony Green committed
2543
	{
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
	  if (!METHOD_STATIC (method))
	    {
	      error ("invokestatic on non static method");
	      method = NULL_TREE;
	    }
	  else if (METHOD_ABSTRACT (method))
	    {
	      error ("invokestatic on abstract method");
	      method = NULL_TREE;
	    }
	}
      else
	{
	  if (METHOD_STATIC (method))
	    {
	      error ("invoke[non-static] on static method");
	      method = NULL_TREE;
	    }
Anthony Green committed
2562 2563 2564 2565 2566
	}
    }

  if (method == NULL_TREE)
    {
2567 2568 2569
      /* If we got here, we emitted an error message above.  So we
	 just pop the arguments, push a properly-typed zero, and
	 continue.  */
Anthony Green committed
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
      method_type = get_type_from_signature (method_signature);
      pop_arguments (TYPE_ARG_TYPES (method_type));
      if (opcode != OPCODE_invokestatic) 
	pop_type (self_type);
      method_type = promote_type (TREE_TYPE (method_type));
      push_value (convert (method_type, integer_zero_node));
      return;
    }

  method_type = TREE_TYPE (method);
  arg_list = pop_arguments (TYPE_ARG_TYPES (method_type));
  flush_quick_stack ();

2583 2584
  maybe_rewrite_invocation (&method, &arg_list, &method_signature,
			    &special);
Andrew Haley committed
2585

Anthony Green committed
2586
  func = NULL_TREE;
2587
  if (opcode == OPCODE_invokestatic)
Anthony Green committed
2588
    func = build_known_method_ref (method, method_type, self_type,
2589
				   method_signature, arg_list, special);
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
  else if (opcode == OPCODE_invokespecial
	   || (opcode == OPCODE_invokevirtual
	       && (METHOD_PRIVATE (method)
		   || METHOD_FINAL (method) 
		   || CLASS_FINAL (TYPE_NAME (self_type)))))
    {
      /* If the object for the method call is null, we throw an
	 exception.  We don't do this if the object is the current
	 method's `this'.  In other cases we just rely on an
	 optimization pass to eliminate redundant checks.  FIXME:
	 Unfortunately there doesn't seem to be a way to determine
2601 2602
	 what the current method is right now.
	 We do omit the check if we're calling <init>.  */
2603 2604 2605 2606
      /* We use a SAVE_EXPR here to make sure we only evaluate
	 the new `self' expression once.  */
      tree save_arg = save_expr (TREE_VALUE (arg_list));
      TREE_VALUE (arg_list) = save_arg;
2607
      check = java_check_reference (save_arg, ! DECL_INIT_P (method));
2608
      func = build_known_method_ref (method, method_type, self_type,
2609
				     method_signature, arg_list, special);
2610
    }
Anthony Green committed
2611 2612 2613 2614 2615
  else
    {
      tree dtable = invoke_build_dtable (opcode == OPCODE_invokeinterface, 
					 arg_list);
      if (opcode == OPCODE_invokevirtual)
2616
	func = build_invokevirtual (dtable, method, special);
Anthony Green committed
2617
      else
2618
	func = build_invokeinterface (dtable, method);
Anthony Green committed
2619
    }
2620 2621 2622 2623 2624
      
  if (TREE_CODE (func) == ADDR_EXPR)
    TREE_TYPE (func) = build_pointer_type (method_type);
  else
    func = build1 (NOP_EXPR, build_pointer_type (method_type), func);
2625

2626
  call = build_call_list (TREE_TYPE (method_type), func, arg_list);
2627 2628
  TREE_SIDE_EFFECTS (call) = 1;
  call = check_for_builtin (method, call);
Anthony Green committed
2629

2630
  if (check != NULL_TREE)
2631
    {
2632
      call = build2 (COMPOUND_EXPR, TREE_TYPE (call), check, call);
2633 2634 2635
      TREE_SIDE_EFFECTS (call) = 1;
    }

Anthony Green committed
2636
  if (TREE_CODE (TREE_TYPE (method_type)) == VOID_TYPE)
2637
    java_add_stmt (call);
Anthony Green committed
2638 2639 2640 2641 2642 2643 2644
  else
    {
      push_value (call);
      flush_quick_stack ();
    }
}

2645 2646 2647 2648
/* Create a stub which will be put into the vtable but which will call
   a JNI function.  */

tree
2649
build_jni_stub (tree method)
2650
{
2651 2652
  tree jnifunc, call, args, body, method_sig, arg_types;
  tree jniarg0, jniarg1, jniarg2, jniarg3;
2653 2654 2655
  tree jni_func_type, tem;
  tree env_var, res_var = NULL_TREE, block;
  tree method_args, res_type;
2656
  tree meth_var;
2657
  tree bind;
2658

2659 2660
  int args_size = 0;

2661 2662 2663
  tree klass = DECL_CONTEXT (method);
  klass = build_class_ref (klass);

2664
  gcc_assert (METHOD_NATIVE (method) && flag_jni);
2665 2666 2667 2668

  DECL_ARTIFICIAL (method) = 1;
  DECL_EXTERNAL (method) = 0;

2669 2670
  env_var = build_decl (input_location,
			VAR_DECL, get_identifier ("env"), ptr_type_node);
2671 2672
  DECL_CONTEXT (env_var) = method;

2673 2674
  if (TREE_TYPE (TREE_TYPE (method)) != void_type_node)
    {
2675
      res_var = build_decl (input_location, VAR_DECL, get_identifier ("res"),
2676
			    TREE_TYPE (TREE_TYPE (method)));
2677
      DECL_CONTEXT (res_var) = method;
2678 2679 2680
      TREE_CHAIN (env_var) = res_var;
    }

2681
  method_args = DECL_ARGUMENTS (method);
2682
  block = build_block (env_var, NULL_TREE, method_args, NULL_TREE);
2683
  TREE_SIDE_EFFECTS (block) = 1;
2684
  TREE_TYPE (block) = TREE_TYPE (TREE_TYPE (method));
2685 2686

  /* Compute the local `env' by calling _Jv_GetJNIEnvNewFrame.  */
2687
  body = build2 (MODIFY_EXPR, ptr_type_node, env_var,
2688 2689 2690
		 build_call_nary (ptr_type_node,
				  build_address_of (soft_getjnienvnewframe_node),
				  1, klass));
2691 2692 2693 2694 2695 2696

  /* All the arguments to this method become arguments to the
     underlying JNI function.  If we had to wrap object arguments in a
     special way, we would do that here.  */
  args = NULL_TREE;
  for (tem = method_args; tem != NULL_TREE; tem = TREE_CHAIN (tem))
2697
    {
2698
      int arg_bits = TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (tem)));
2699 2700 2701 2702 2703 2704 2705 2706
#ifdef PARM_BOUNDARY
      arg_bits = (((arg_bits + PARM_BOUNDARY - 1) / PARM_BOUNDARY)
                  * PARM_BOUNDARY);
#endif
      args_size += (arg_bits / BITS_PER_UNIT);

      args = tree_cons (NULL_TREE, tem, args);
    }
2707 2708 2709 2710 2711 2712 2713 2714
  args = nreverse (args);
  arg_types = TYPE_ARG_TYPES (TREE_TYPE (method));

  /* For a static method the second argument is the class.  For a
     non-static method the second argument is `this'; that is already
     available in the argument list.  */
  if (METHOD_STATIC (method))
    {
2715
      args_size += int_size_in_bytes (TREE_TYPE (klass));
2716 2717 2718 2719 2720
      args = tree_cons (NULL_TREE, klass, args);
      arg_types = tree_cons (NULL_TREE, object_ptr_type_node, arg_types);
    }

  /* The JNIEnv structure is the first argument to the JNI function.  */
2721
  args_size += int_size_in_bytes (TREE_TYPE (env_var));
2722 2723 2724 2725 2726 2727 2728
  args = tree_cons (NULL_TREE, env_var, args);
  arg_types = tree_cons (NULL_TREE, ptr_type_node, arg_types);

  /* We call _Jv_LookupJNIMethod to find the actual underlying
     function pointer.  _Jv_LookupJNIMethod will throw the appropriate
     exception if this function is not found at runtime.  */
  method_sig = build_java_signature (TREE_TYPE (method));
2729 2730 2731 2732 2733 2734 2735
  jniarg0 = klass;
  jniarg1 = build_utf8_ref (DECL_NAME (method));
  jniarg2 = build_utf8_ref (unmangle_classname
			    (IDENTIFIER_POINTER (method_sig),
			     IDENTIFIER_LENGTH (method_sig)));
  jniarg3 = build_int_cst (NULL_TREE, args_size);

2736 2737 2738 2739 2740
  tem = build_function_type (TREE_TYPE (TREE_TYPE (method)), arg_types);

#ifdef MODIFY_JNI_METHOD_CALL
  tem = MODIFY_JNI_METHOD_CALL (tem);
#endif
2741

2742
  jni_func_type = build_pointer_type (tem);
2743

2744 2745 2746 2747 2748
  /* Use the actual function type, rather than a generic pointer type,
     such that this decl keeps the actual pointer type from being
     garbage-collected.  If it is, we end up using canonical types
     with different uids for equivalent function types, and this in
     turn causes utf8 identifiers and output order to vary.  */
2749 2750
  meth_var = build_decl (input_location,
			 VAR_DECL, get_identifier ("meth"), jni_func_type);
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
  TREE_STATIC (meth_var) = 1;
  TREE_PUBLIC (meth_var) = 0;
  DECL_EXTERNAL (meth_var) = 0;
  DECL_CONTEXT (meth_var) = method;
  DECL_ARTIFICIAL (meth_var) = 1;
  DECL_INITIAL (meth_var) = null_pointer_node;
  TREE_USED (meth_var) = 1;
  chainon (env_var, meth_var);
  build_result_decl (method);

  jnifunc = build3 (COND_EXPR, jni_func_type,
2762 2763 2764
		    build2 (NE_EXPR, boolean_type_node,
			    meth_var, build_int_cst (TREE_TYPE (meth_var), 0)),
		    meth_var,
2765 2766 2767 2768 2769 2770 2771 2772 2773
		    build2 (MODIFY_EXPR, jni_func_type, meth_var,
			    build1
			    (NOP_EXPR, jni_func_type,
			     build_call_nary (ptr_type_node,
					      build_address_of
					      (soft_lookupjnimethod_node),
					      4,
					      jniarg0, jniarg1,
					      jniarg2, jniarg3))));
2774 2775 2776

  /* Now we make the actual JNI call via the resulting function
     pointer.    */
2777
  call = build_call_list (TREE_TYPE (TREE_TYPE (method)),
2778
			  jnifunc, args);
2779 2780 2781 2782

  /* If the JNI call returned a result, capture it here.  If we had to
     unwrap JNI object results, we would do that here.  */
  if (res_var != NULL_TREE)
2783 2784 2785 2786
    {
      /* If the call returns an object, it may return a JNI weak
	 reference, in which case we must unwrap it.  */
      if (! JPRIMITIVE_TYPE_P (TREE_TYPE (TREE_TYPE (method))))
2787 2788 2789
	call = build_call_nary (TREE_TYPE (TREE_TYPE (method)),
				build_address_of (soft_unwrapjni_node),
				1, call);
2790 2791 2792
      call = build2 (MODIFY_EXPR, TREE_TYPE (TREE_TYPE (method)),
		     res_var, call);
    }
2793 2794 2795

  TREE_SIDE_EFFECTS (call) = 1;

2796
  body = build2 (COMPOUND_EXPR, void_type_node, body, call);
2797 2798 2799
  TREE_SIDE_EFFECTS (body) = 1;

  /* Now free the environment we allocated.  */
2800 2801 2802
  call = build_call_nary (ptr_type_node,
			  build_address_of (soft_jnipopsystemframe_node),
			  1, env_var);
2803
  TREE_SIDE_EFFECTS (call) = 1;
2804
  body = build2 (COMPOUND_EXPR, void_type_node, body, call);
2805 2806
  TREE_SIDE_EFFECTS (body) = 1;

2807 2808 2809
  /* Finally, do the return.  */
  res_type = void_type_node;
  if (res_var != NULL_TREE)
2810
    {
2811
      tree drt;
2812
      gcc_assert (DECL_RESULT (method));
2813 2814 2815 2816 2817 2818 2819
      /* Make sure we copy the result variable to the actual
	 result.  We use the type of the DECL_RESULT because it
	 might be different from the return type of the function:
	 it might be promoted.  */
      drt = TREE_TYPE (DECL_RESULT (method));
      if (drt != TREE_TYPE (res_var))
	res_var = build1 (CONVERT_EXPR, drt, res_var);
2820
      res_var = build2 (MODIFY_EXPR, drt, DECL_RESULT (method), res_var);
2821
      TREE_SIDE_EFFECTS (res_var) = 1;
2822
    }
2823

2824
  body = build2 (COMPOUND_EXPR, void_type_node, body,
2825
		 build1 (RETURN_EXPR, void_type_node, res_var));
2826
  TREE_SIDE_EFFECTS (body) = 1;
2827
  
2828 2829 2830 2831 2832 2833
  /* Prepend class initialization for static methods reachable from
     other classes.  */
  if (METHOD_STATIC (method)
      && (! METHOD_PRIVATE (method)
          || INNER_CLASS_P (DECL_CONTEXT (method))))
    {
2834 2835
      tree init = build_call_expr (soft_initclass_node, 1, 
				   klass);
2836 2837 2838 2839
      body = build2 (COMPOUND_EXPR, void_type_node, init, body);
      TREE_SIDE_EFFECTS (body) = 1;
    }

2840 2841
  bind = build3 (BIND_EXPR, void_type_node, BLOCK_VARS (block), 
		 body, block);
2842
  return bind;
2843 2844
}

2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863

/* Given lvalue EXP, return a volatile expression that references the
   same object.  */

tree
java_modify_addr_for_volatile (tree exp)
{
  tree exp_type = TREE_TYPE (exp);
  tree v_type 
    = build_qualified_type (exp_type,
			    TYPE_QUALS (exp_type) | TYPE_QUAL_VOLATILE);
  tree addr = build_fold_addr_expr (exp);
  v_type = build_pointer_type (v_type);
  addr = fold_convert (v_type, addr);
  exp = build_fold_indirect_ref (addr);
  return exp;
}


Anthony Green committed
2864 2865 2866 2867 2868
/* Expand an operation to extract from or store into a field.
   IS_STATIC is 1 iff the field is static.
   IS_PUTTING is 1 for putting into a field;  0 for getting from the field.
   FIELD_REF_INDEX is an index into the constant pool.  */

2869
static void
2870
expand_java_field_op (int is_static, int is_putting, int field_ref_index)
Anthony Green committed
2871
{
Ranjit Mathew committed
2872 2873 2874 2875 2876 2877
  tree self_type
    = get_class_constant (current_jcf,
                          COMPONENT_REF_CLASS_INDEX (&current_jcf->cpool,
                          field_ref_index));
  const char *self_name
    = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (self_type)));
Anthony Green committed
2878
  tree field_name = COMPONENT_REF_NAME (&current_jcf->cpool, field_ref_index);
2879 2880
  tree field_signature = COMPONENT_REF_SIGNATURE (&current_jcf->cpool, 
						  field_ref_index);
Anthony Green committed
2881 2882 2883 2884
  tree field_type = get_type_from_signature (field_signature);
  tree new_value = is_putting ? pop_value (field_type) : NULL_TREE;
  tree field_ref;
  int is_error = 0;
2885
  tree original_self_type = self_type;
2886
  tree field_decl;
2887
  tree modify_expr;
2888 2889 2890 2891
  
  if (! CLASS_LOADED_P (self_type))
    load_class (self_type, 1);  
  field_decl = lookup_field (&self_type, field_name);
Anthony Green committed
2892 2893 2894 2895 2896 2897
  if (field_decl == error_mark_node)
    {
      is_error = 1;
    }
  else if (field_decl == NULL_TREE)
    {
2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
      if (! flag_verify_invocations)
	{
	  int flags = ACC_PUBLIC;
	  if (is_static)
	    flags |= ACC_STATIC;
	  self_type = original_self_type;
	  field_decl = add_field (original_self_type, field_name,
				  field_type, flags); 
	  DECL_ARTIFICIAL (field_decl) = 1;
	  DECL_IGNORED_P (field_decl) = 1;
2908 2909 2910 2911 2912 2913 2914
#if 0
	  /* FIXME: We should be pessimistic about volatility.  We
	     don't know one way or another, but this is safe.
	     However, doing this has bad effects on code quality.  We
	     need to look at better ways to do this.  */
	  TREE_THIS_VOLATILE (field_decl) = 1;
#endif
2915 2916 2917 2918 2919 2920 2921
	}
      else
	{      
	  error ("missing field '%s' in '%s'",
		 IDENTIFIER_POINTER (field_name), self_name);
	  is_error = 1;
      }
Anthony Green committed
2922 2923 2924
    }
  else if (build_java_signature (TREE_TYPE (field_decl)) != field_signature)
    {
2925
      error ("mismatching signature for field '%s' in '%s'",
Anthony Green committed
2926 2927 2928 2929 2930 2931 2932
	     IDENTIFIER_POINTER (field_name), self_name);
      is_error = 1;
    }
  field_ref = is_static ? NULL_TREE : pop_value (self_type);
  if (is_error)
    {
      if (! is_putting)
Per Bothner committed
2933
	push_value (convert (field_type, integer_zero_node));
Anthony Green committed
2934 2935 2936 2937 2938
      flush_quick_stack ();
      return;
    }

  field_ref = build_field_ref (field_ref, self_type, field_name);
2939 2940
  if (is_static
      && ! flag_indirect_dispatch)
2941 2942 2943 2944
    {
      tree context = DECL_CONTEXT (field_ref);
      if (context != self_type && CLASS_INTERFACE (TYPE_NAME (context)))
	field_ref = build_class_init (context, field_ref);
2945 2946
      else
	field_ref = build_class_init (self_type, field_ref);
2947
    }
Anthony Green committed
2948 2949 2950 2951 2952 2953
  if (is_putting)
    {
      flush_quick_stack ();
      if (FIELD_FINAL (field_decl))
	{
	  if (DECL_CONTEXT (field_decl) != current_class)
2954 2955
            error ("assignment to final field %q+D not in field's class",
                   field_decl);
2956 2957 2958 2959
	  /* We used to check for assignments to final fields not
	     occurring in the class initializer or in a constructor
	     here.  However, this constraint doesn't seem to be
	     enforced by the JVM.  */
2960 2961 2962 2963 2964 2965 2966 2967 2968
	}      

      if (TREE_THIS_VOLATILE (field_decl))
	field_ref = java_modify_addr_for_volatile (field_ref);

      modify_expr = build2 (MODIFY_EXPR, TREE_TYPE (field_ref),
			    field_ref, new_value);

      if (TREE_THIS_VOLATILE (field_decl))
2969 2970
	java_add_stmt
	  (build_call_expr (built_in_decls[BUILT_IN_SYNCHRONIZE], 0));
2971 2972
      	  
      java_add_stmt (modify_expr);
Anthony Green committed
2973 2974
    }
  else
2975
    {
2976 2977
      tree temp = build_decl (input_location,
			      VAR_DECL, NULL_TREE, TREE_TYPE (field_ref));
2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
      java_add_local_var (temp);

      if (TREE_THIS_VOLATILE (field_decl))
	field_ref = java_modify_addr_for_volatile (field_ref);

      modify_expr 
	= build2 (MODIFY_EXPR, TREE_TYPE (field_ref), temp, field_ref);
      java_add_stmt (modify_expr);

      if (TREE_THIS_VOLATILE (field_decl))
	java_add_stmt 
2989
	  (build_call_expr (built_in_decls[BUILT_IN_SYNCHRONIZE], 0));
2990 2991 2992 2993

      push_value (temp);
    }      
  TREE_THIS_VOLATILE (field_ref) = TREE_THIS_VOLATILE (field_decl);
Anthony Green committed
2994 2995
}

2996 2997
static void
load_type_state (int pc)
Anthony Green committed
2998 2999
{
  int i;
3000
  tree vec = VEC_index (tree, type_states, pc);
Anthony Green committed
3001 3002 3003 3004 3005 3006
  int cur_length = TREE_VEC_LENGTH (vec);
  stack_pointer = cur_length - DECL_MAX_LOCALS(current_function_decl);
  for (i = 0; i < cur_length; i++)
    type_map [i] = TREE_VEC_ELT (vec, i);
}

3007 3008 3009
/* Go over METHOD's bytecode and note instruction starts in
   instruction_bits[].  */

Anthony Green committed
3010
void
3011
note_instructions (JCF *jcf, tree method)
Anthony Green committed
3012
{
3013 3014 3015 3016
  int PC; 
  unsigned char* byte_ops;
  long length = DECL_CODE_LENGTH (method);

Anthony Green committed
3017
  int saw_index;
3018
  jint INT_temp;
Anthony Green committed
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036

#undef RET /* Defined by config/i386/i386.h */
#undef PTR
#define BCODE byte_ops
#define BYTE_type_node byte_type_node
#define SHORT_type_node short_type_node
#define INT_type_node int_type_node
#define LONG_type_node long_type_node
#define CHAR_type_node char_type_node
#define PTR_type_node ptr_type_node
#define FLOAT_type_node float_type_node
#define DOUBLE_type_node double_type_node
#define VOID_type_node void_type_node
#define CONST_INDEX_1 (saw_index = 1, IMMEDIATE_u1)
#define CONST_INDEX_2 (saw_index = 1, IMMEDIATE_u2)
#define VAR_INDEX_1 (saw_index = 1, IMMEDIATE_u1)
#define VAR_INDEX_2 (saw_index = 1, IMMEDIATE_u2)

3037
#define CHECK_PC_IN_RANGE(PC) ((void)1) /* Already handled by verifier. */
Anthony Green committed
3038

3039 3040
  JCF_SEEK (jcf, DECL_CODE_OFFSET (method));
  byte_ops = jcf->read_ptr;
3041
  instruction_bits = XRESIZEVAR (char, instruction_bits, length + 1);
3042
  memset (instruction_bits, 0, length + 1);
3043 3044
  type_states = VEC_alloc (tree, gc, length + 1);
  VEC_safe_grow_cleared (tree, gc, type_states, length + 1);
Anthony Green committed
3045

3046
  /* This pass figures out which PC can be the targets of jumps. */
Anthony Green committed
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
  for (PC = 0; PC < length;)
    {
      int oldpc = PC; /* PC at instruction start. */
      instruction_bits [PC] |=  BCODE_INSTRUCTION_START;
      switch (byte_ops[PC++])
	{
#define JAVAOP(OPNAME, OPCODE, OPKIND, OPERAND_TYPE, OPERAND_VALUE) \
        case OPCODE: \
	  PRE_##OPKIND(OPERAND_TYPE, OPERAND_VALUE); \
	  break;

#define NOTE_LABEL(PC) note_label(oldpc, PC)

#define PRE_PUSHC(OPERAND_TYPE, OPERAND_VALUE) (void)(OPERAND_VALUE);
#define PRE_LOAD(OPERAND_TYPE, OPERAND_VALUE) (void)(OPERAND_VALUE);
#define PRE_STORE(OPERAND_TYPE, OPERAND_VALUE) (void)(OPERAND_VALUE);
#define PRE_STACK(OPERAND_TYPE, OPERAND_VALUE) /* nothing */
#define PRE_UNOP(OPERAND_TYPE, OPERAND_VALUE) /* nothing */
#define PRE_BINOP(OPERAND_TYPE, OPERAND_VALUE) /* nothing */
#define PRE_CONVERT(OPERAND_TYPE, OPERAND_VALUE) /* nothing */
#define PRE_CONVERT2(OPERAND_TYPE, OPERAND_VALUE) /* nothing */

#define PRE_SPECIAL(OPERAND_TYPE, INSTRUCTION) \
  PRE_SPECIAL_##INSTRUCTION(OPERAND_TYPE)
#define PRE_SPECIAL_IINC(OPERAND_TYPE) \
  ((void) IMMEDIATE_u1, (void) IMMEDIATE_s1)
#define PRE_SPECIAL_ENTER(IGNORE) /* nothing */
#define PRE_SPECIAL_EXIT(IGNORE) /* nothing */
#define PRE_SPECIAL_THROW(IGNORE) /* nothing */
#define PRE_SPECIAL_BREAK(IGNORE) /* nothing */

/* two forms of wide instructions */
#define PRE_SPECIAL_WIDE(IGNORE) \
  { \
    int modified_opcode = IMMEDIATE_u1; \
    if (modified_opcode == OPCODE_iinc)	\
      { \
	(void) IMMEDIATE_u2;	/* indexbyte1 and indexbyte2 */ \
	(void) IMMEDIATE_s2;	/* constbyte1 and constbyte2 */ \
      } \
    else \
      { \
	(void) IMMEDIATE_u2;	/* indexbyte1 and indexbyte2 */ \
      } \
  }

#define PRE_IMPL(IGNORE1, IGNORE2) /* nothing */

#define PRE_MONITOR(OPERAND_TYPE, OPERAND_VALUE) /* nothing */

#define PRE_RETURN(OPERAND_TYPE, OPERAND_VALUE) /* nothing */
#define PRE_ARRAY(OPERAND_TYPE, SUBOP) \
	  PRE_ARRAY_##SUBOP(OPERAND_TYPE)
#define PRE_ARRAY_LOAD(TYPE) /* nothing */
#define PRE_ARRAY_STORE(TYPE) /* nothing */
#define PRE_ARRAY_LENGTH(TYPE) /* nothing */
#define PRE_ARRAY_NEW(TYPE) PRE_ARRAY_NEW_##TYPE
#define PRE_ARRAY_NEW_NUM ((void) IMMEDIATE_u1)
#define PRE_ARRAY_NEW_PTR ((void) IMMEDIATE_u2)
#define PRE_ARRAY_NEW_MULTI ((void) IMMEDIATE_u2, (void) IMMEDIATE_u1)

#define PRE_TEST(OPERAND_TYPE, OPERAND_VALUE) NOTE_LABEL (oldpc+IMMEDIATE_s2)
#define PRE_COND(OPERAND_TYPE, OPERAND_VALUE) NOTE_LABEL (oldpc+IMMEDIATE_s2)
#define PRE_BRANCH(OPERAND_TYPE, OPERAND_VALUE) \
  saw_index = 0;  INT_temp = (OPERAND_VALUE); \
  if (!saw_index)  NOTE_LABEL(oldpc + INT_temp);
#define PRE_JSR(OPERAND_TYPE, OPERAND_VALUE) \
  saw_index = 0;  INT_temp = (OPERAND_VALUE); \
3115
  NOTE_LABEL (PC); \
Anthony Green committed
3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
  if (!saw_index)  NOTE_LABEL(oldpc + INT_temp);

#define PRE_RET(OPERAND_TYPE, OPERAND_VALUE)  (void)(OPERAND_VALUE)

#define PRE_SWITCH(OPERAND_TYPE, TABLE_OR_LOOKUP) \
  PC = (PC + 3) / 4 * 4; PRE_##TABLE_OR_LOOKUP##_SWITCH

#define PRE_LOOKUP_SWITCH						\
  { jint default_offset = IMMEDIATE_s4;  jint npairs = IMMEDIATE_s4;	\
    NOTE_LABEL (default_offset+oldpc);					\
    if (npairs >= 0)							\
      while (--npairs >= 0) {						\
3128 3129
       jint match ATTRIBUTE_UNUSED = IMMEDIATE_s4;			\
       jint offset = IMMEDIATE_s4;					\
Anthony Green committed
3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
       NOTE_LABEL (offset+oldpc); }					\
  }

#define PRE_TABLE_SWITCH				\
  { jint default_offset = IMMEDIATE_s4;			\
    jint low = IMMEDIATE_s4; jint high = IMMEDIATE_s4;	\
    NOTE_LABEL (default_offset+oldpc);			\
    if (low <= high)					\
     while (low++ <= high) {				\
       jint offset = IMMEDIATE_s4;			\
       NOTE_LABEL (offset+oldpc); }			\
  }

#define PRE_FIELD(MAYBE_STATIC, PUT_OR_GET) (void)(IMMEDIATE_u2);
#define PRE_OBJECT(MAYBE_STATIC, PUT_OR_GET) (void)(IMMEDIATE_u2);
#define PRE_INVOKE(MAYBE_STATIC, IS_INTERFACE) \
  (void)(IMMEDIATE_u2); \
  PC += 2 * IS_INTERFACE /* for invokeinterface */;

#include "javaop.def"
#undef JAVAOP
	}
    } /* for */
3153 3154 3155
}

void
3156
expand_byte_code (JCF *jcf, tree method)
3157 3158 3159 3160 3161 3162 3163
{
  int PC;
  int i;
  const unsigned char *linenumber_pointer;
  int dead_code_index = -1;
  unsigned char* byte_ops;
  long length = DECL_CODE_LENGTH (method);
3164
  location_t max_location = input_location;
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177

  stack_pointer = 0;
  JCF_SEEK (jcf, DECL_CODE_OFFSET (method));
  byte_ops = jcf->read_ptr;

  /* We make an initial pass of the line number table, to note
     which instructions have associated line number entries. */
  linenumber_pointer = linenumber_table;
  for (i = 0; i < linenumber_count; i++)
    {
      int pc = GET_u2 (linenumber_pointer);
      linenumber_pointer += 4;
      if (pc >= length)
3178
	warning (0, "invalid PC in line number table");
3179 3180 3181 3182 3183 3184 3185
      else
	{
	  if ((instruction_bits[pc] & BCODE_HAS_LINENUMBER) != 0)
	    instruction_bits[pc] |= BCODE_HAS_MULTI_LINENUMBERS;
	  instruction_bits[pc] |= BCODE_HAS_LINENUMBER;
	}
    }  
Anthony Green committed
3186

3187 3188
  if (! verify_jvm_instructions_new (jcf, byte_ops, length))
    return;
Anthony Green committed
3189

3190
  promote_arguments ();
3191 3192
  cache_this_class_ref (method);
  cache_cpool_data_ref ();
3193

3194
  /* Translate bytecodes.  */
Anthony Green committed
3195 3196 3197 3198 3199 3200 3201 3202
  linenumber_pointer = linenumber_table;
  for (PC = 0; PC < length;)
    {
      if ((instruction_bits [PC] & BCODE_TARGET) != 0 || PC == 0)
	{
	  tree label = lookup_label (PC);
          flush_quick_stack ();
	  if ((instruction_bits [PC] & BCODE_TARGET) != 0)
3203
	    java_add_stmt (build1 (LABEL_EXPR, void_type_node, label));
3204 3205
	  if ((instruction_bits[PC] & BCODE_VERIFIED) != 0)
	    load_type_state (PC);
Anthony Green committed
3206 3207 3208 3209
	}

      if (! (instruction_bits [PC] & BCODE_VERIFIED))
	{
Anthony Green committed
3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
	  if (dead_code_index == -1)
	    {
	      /* This is the start of a region of unreachable bytecodes.
                 They still need to be processed in order for EH ranges
                 to get handled correctly.  However, we can simply
                 replace these bytecodes with nops.  */
	      dead_code_index = PC;
            }
          
          /* Turn this bytecode into a nop.  */
          byte_ops[PC] = 0x0;
        }
       else
        {
	  if (dead_code_index != -1)
	    {
              /* We've just reached the end of a region of dead code.  */
3227
	      if (extra_warnings)
3228
		warning (0, "unreachable bytecode from %d to before %d",
3229
			 dead_code_index, PC);
Anthony Green committed
3230 3231
              dead_code_index = -1;
            }
Anthony Green committed
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
	}

      /* Handle possible line number entry for this PC.

	 This code handles out-of-order and multiple linenumbers per PC,
	 but is optimized for the case of line numbers increasing
	 monotonically with PC. */
      if ((instruction_bits[PC] & BCODE_HAS_LINENUMBER) != 0)
	{
	  if ((instruction_bits[PC] & BCODE_HAS_MULTI_LINENUMBERS) != 0
	      || GET_u2 (linenumber_pointer) != PC)
	    linenumber_pointer = linenumber_table;
	  while (linenumber_pointer < linenumber_table + linenumber_count * 4)
	    {
	      int pc = GET_u2 (linenumber_pointer);
	      linenumber_pointer += 4;
	      if (pc == PC)
		{
3250
		  int line = GET_u2 (linenumber_pointer - 2);
3251
		  input_location = linemap_line_start (line_table, line, 1);
3252 3253
		  if (input_location > max_location)
		    max_location = input_location;
Anthony Green committed
3254 3255 3256 3257 3258 3259 3260 3261 3262
		  if (!(instruction_bits[PC] & BCODE_HAS_MULTI_LINENUMBERS))
		    break;
		}
	    }
	}
      maybe_pushlevels (PC);
      PC = process_jvm_instruction (PC, byte_ops, length);
      maybe_poplevels (PC);
    } /* for */
3263

3264 3265
  uncache_this_class_ref (method);

Anthony Green committed
3266 3267 3268
  if (dead_code_index != -1)
    {
      /* We've just reached the end of a region of dead code.  */
3269
      if (extra_warnings)
3270
	warning (0, "unreachable bytecode from %d to the end of the method", 
3271
		 dead_code_index);
Anthony Green committed
3272
    }
3273 3274

  DECL_FUNCTION_LAST_LINE (method) = max_location;
Anthony Green committed
3275 3276
}

3277
static void
3278
java_push_constant_from_pool (JCF *jcf, int index)
Anthony Green committed
3279 3280 3281 3282 3283 3284 3285 3286
{
  tree c;
  if (JPOOL_TAG (jcf, index) == CONSTANT_String)
    {
      tree name;
      name = get_name_constant (jcf, JPOOL_USHORT1 (jcf, index));
      index = alloc_name_constant (CONSTANT_String, name);
      c = build_ref_from_constant_pool (index);
3287
      c = convert (promote_type (string_type_node), c);
Anthony Green committed
3288
    }
3289 3290 3291 3292 3293 3294
  else if (JPOOL_TAG (jcf, index) == CONSTANT_Class
	   || JPOOL_TAG (jcf, index) == CONSTANT_ResolvedClass)
    {
      tree record = get_class_constant (jcf, index);
      c = build_class_ref (record);
    }
Anthony Green committed
3295 3296 3297 3298 3299 3300
  else
    c = get_constant (jcf, index);
  push_value (c);
} 

int
3301 3302
process_jvm_instruction (int PC, const unsigned char* byte_ops,
			 long length ATTRIBUTE_UNUSED)
Anthony Green committed
3303
{ 
Kaveh R. Ghazi committed
3304
  const char *opname; /* Temporary ??? */
Anthony Green committed
3305
  int oldpc = PC; /* PC at instruction start. */
Per Bothner committed
3306

3307 3308
  /* If the instruction is at the beginning of an exception handler,
     replace the top of the stack with the thrown object reference.  */
Per Bothner committed
3309 3310
  if (instruction_bits [PC] & BCODE_EXCEPTION_TARGET)
    {
3311 3312 3313 3314
      /* Note that the verifier will not emit a type map at all for
	 dead exception handlers.  In this case we just ignore the
	 situation.  */
      if ((instruction_bits[PC] & BCODE_VERIFIED) != 0)
3315 3316 3317 3318
	{
	  tree type = pop_type (promote_type (throwable_type_node));
	  push_value (build_exception_object_ref (type));
	}
Per Bothner committed
3319 3320
    }

Anthony Green committed
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
  switch (byte_ops[PC++])
    {
#define JAVAOP(OPNAME, OPCODE, OPKIND, OPERAND_TYPE, OPERAND_VALUE) \
    case OPCODE: \
      opname = #OPNAME; \
      OPKIND(OPERAND_TYPE, OPERAND_VALUE); \
      break;

#define RET(OPERAND_TYPE, OPERAND_VALUE) 				\
  {									\
    int saw_index = 0;							\
    int index     = OPERAND_VALUE;					\
3333 3334
    build_java_ret							\
      (find_local_variable (index, return_address_type_node, oldpc));	\
Anthony Green committed
3335 3336
  }

3337
#define JSR(OPERAND_TYPE, OPERAND_VALUE) \
3338 3339 3340 3341 3342
  {						    \
    /* OPERAND_VALUE may have side-effects on PC */ \
    int opvalue = OPERAND_VALUE;		    \
    build_java_jsr (oldpc + opvalue, PC);	    \
  }
Anthony Green committed
3343 3344 3345 3346 3347 3348 3349 3350 3351

/* Push a constant onto the stack. */
#define PUSHC(OPERAND_TYPE, OPERAND_VALUE) \
  { int saw_index = 0;  int ival = (OPERAND_VALUE); \
    if (saw_index) java_push_constant_from_pool (current_jcf, ival); \
    else expand_java_pushc (ival, OPERAND_TYPE##_type_node); }

/* internal macro added for use by the WIDE case */
#define LOAD_INTERNAL(OPTYPE, OPVALUE) \
3352
  expand_load_internal (OPVALUE, type_map[OPVALUE], oldpc);
Anthony Green committed
3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420

/* Push local variable onto the opcode stack. */
#define LOAD(OPERAND_TYPE, OPERAND_VALUE) \
  { \
    /* have to do this since OPERAND_VALUE may have side-effects */ \
    int opvalue = OPERAND_VALUE; \
    LOAD_INTERNAL(OPERAND_TYPE##_type_node, opvalue); \
  }

#define RETURN(OPERAND_TYPE, OPERAND_VALUE) \
  expand_java_return (OPERAND_TYPE##_type_node)

#define REM_EXPR TRUNC_MOD_EXPR
#define BINOP(OPERAND_TYPE, OPERAND_VALUE) \
  expand_java_binop (OPERAND_TYPE##_type_node, OPERAND_VALUE##_EXPR)

#define FIELD(IS_STATIC, IS_PUT) \
  expand_java_field_op (IS_STATIC, IS_PUT, IMMEDIATE_u2)

#define TEST(OPERAND_TYPE, CONDITION) \
  expand_test (CONDITION##_EXPR, OPERAND_TYPE##_type_node, oldpc+IMMEDIATE_s2)

#define COND(OPERAND_TYPE, CONDITION) \
  expand_cond (CONDITION##_EXPR, OPERAND_TYPE##_type_node, oldpc+IMMEDIATE_s2)

#define BRANCH(OPERAND_TYPE, OPERAND_VALUE) \
  BRANCH_##OPERAND_TYPE (OPERAND_VALUE)

#define BRANCH_GOTO(OPERAND_VALUE) \
  expand_java_goto (oldpc + OPERAND_VALUE)

#define BRANCH_CALL(OPERAND_VALUE) \
  expand_java_call (oldpc + OPERAND_VALUE, oldpc)

#if 0
#define BRANCH_RETURN(OPERAND_VALUE) \
  { \
    tree type = OPERAND_TYPE##_type_node; \
    tree value = find_local_variable (OPERAND_VALUE, type, oldpc); \
    expand_java_ret (value); \
  }
#endif

#define NOT_IMPL(OPERAND_TYPE, OPERAND_VALUE) \
	  fprintf (stderr, "%3d: %s ", oldpc, opname); \
	  fprintf (stderr, "(not implemented)\n")
#define NOT_IMPL1(OPERAND_VALUE) \
	  fprintf (stderr, "%3d: %s ", oldpc, opname); \
	  fprintf (stderr, "(not implemented)\n")

#define BRANCH_RETURN(OPERAND_VALUE) NOT_IMPL1(OPERAND_VALUE)

#define STACK(SUBOP, COUNT) STACK_##SUBOP (COUNT)

#define STACK_POP(COUNT) java_stack_pop (COUNT)

#define STACK_SWAP(COUNT) java_stack_swap()

#define STACK_DUP(COUNT) java_stack_dup (COUNT, 0)
#define STACK_DUPx1(COUNT) java_stack_dup (COUNT, 1)
#define STACK_DUPx2(COUNT) java_stack_dup (COUNT, 2)

#define SWITCH(OPERAND_TYPE, TABLE_OR_LOOKUP) \
  PC = (PC + 3) / 4 * 4; TABLE_OR_LOOKUP##_SWITCH

#define LOOKUP_SWITCH \
  { jint default_offset = IMMEDIATE_s4;  jint npairs = IMMEDIATE_s4; \
    tree selector = pop_value (INT_type_node); \
3421
    tree switch_expr = expand_java_switch (selector, oldpc + default_offset); \
Anthony Green committed
3422 3423 3424
    while (--npairs >= 0) \
      { \
	jint match = IMMEDIATE_s4; jint offset = IMMEDIATE_s4; \
3425
	expand_java_add_case (switch_expr, match, oldpc + offset); \
Anthony Green committed
3426 3427 3428 3429 3430 3431 3432
      } \
  }

#define TABLE_SWITCH \
  { jint default_offset = IMMEDIATE_s4; \
    jint low = IMMEDIATE_s4; jint high = IMMEDIATE_s4; \
    tree selector = pop_value (INT_type_node); \
3433
    tree switch_expr = expand_java_switch (selector, oldpc + default_offset); \
Anthony Green committed
3434 3435 3436
    for (; low <= high; low++) \
      { \
        jint offset = IMMEDIATE_s4; \
3437
	expand_java_add_case (switch_expr, low, oldpc + offset); \
Anthony Green committed
3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
      } \
  }

#define INVOKE(MAYBE_STATIC, IS_INTERFACE) \
  { int opcode = byte_ops[PC-1]; \
    int method_ref_index = IMMEDIATE_u2; \
    int nargs; \
    if (IS_INTERFACE) { nargs = IMMEDIATE_u1;  (void) IMMEDIATE_u1; } \
    else nargs = -1; \
    expand_invoke (opcode, method_ref_index, nargs); \
  }

/* Handle new, checkcast, instanceof */
#define OBJECT(TYPE, OP) \
  expand_java_##OP (get_class_constant (current_jcf, IMMEDIATE_u2))

#define ARRAY(OPERAND_TYPE, SUBOP) ARRAY_##SUBOP(OPERAND_TYPE)

#define ARRAY_LOAD(OPERAND_TYPE) 			\
  {							\
    expand_java_arrayload( OPERAND_TYPE##_type_node );	\
  }

#define ARRAY_STORE(OPERAND_TYPE)			\
  {							\
    expand_java_arraystore( OPERAND_TYPE##_type_node );	\
  }

#define ARRAY_LENGTH(OPERAND_TYPE) expand_java_array_length();
#define ARRAY_NEW(OPERAND_TYPE) ARRAY_NEW_##OPERAND_TYPE()
#define ARRAY_NEW_PTR()							\
    push_value (build_anewarray (get_class_constant (current_jcf,	\
						     IMMEDIATE_u2),	\
				 pop_value (int_type_node)));
#define ARRAY_NEW_NUM()				\
  {						\
    int atype = IMMEDIATE_u1;			\
    push_value (build_newarray (atype, pop_value (int_type_node)));\
  }
#define ARRAY_NEW_MULTI()					\
  {								\
3479
    tree klass = get_class_constant (current_jcf, IMMEDIATE_u2 );	\
Anthony Green committed
3480
    int  ndims = IMMEDIATE_u1;					\
3481
    expand_java_multianewarray( klass, ndims );			\
Anthony Green committed
3482 3483 3484
  }

#define UNOP(OPERAND_TYPE, OPERAND_VALUE) \
3485 3486
  push_value (fold_build1 (NEGATE_EXPR, OPERAND_TYPE##_type_node, \
			   pop_value (OPERAND_TYPE##_type_node)));
Anthony Green committed
3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502

#define CONVERT2(FROM_TYPE, TO_TYPE)					 \
  {									 \
    push_value (build1 (NOP_EXPR, int_type_node,			 \
			(convert (TO_TYPE##_type_node,			 \
				  pop_value (FROM_TYPE##_type_node))))); \
  }

#define CONVERT(FROM_TYPE, TO_TYPE)				\
  {								\
    push_value (convert (TO_TYPE##_type_node,	                \
			 pop_value (FROM_TYPE##_type_node)));	\
  }

/* internal macro added for use by the WIDE case 
   Added TREE_TYPE (decl) assignment, apbianco  */
3503 3504 3505 3506 3507 3508 3509 3510 3511
#define STORE_INTERNAL(OPTYPE, OPVALUE)				\
  {								\
    tree decl, value;						\
    int index = OPVALUE;					\
    tree type = OPTYPE;						\
    value = pop_value (type);					\
    type = TREE_TYPE (value);					\
    decl = find_local_variable (index, type, oldpc);		\
    set_local_type (index, type);				\
3512
    java_add_stmt (build2 (MODIFY_EXPR, type, decl, value));	\
Anthony Green committed
3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534
  }

#define STORE(OPERAND_TYPE, OPERAND_VALUE) \
  { \
    /* have to do this since OPERAND_VALUE may have side-effects */ \
    int opvalue = OPERAND_VALUE; \
    STORE_INTERNAL(OPERAND_TYPE##_type_node, opvalue); \
  }

#define SPECIAL(OPERAND_TYPE, INSTRUCTION) \
  SPECIAL_##INSTRUCTION(OPERAND_TYPE)

#define SPECIAL_ENTER(IGNORED) MONITOR_OPERATION (soft_monitorenter_node)
#define SPECIAL_EXIT(IGNORED)  MONITOR_OPERATION (soft_monitorexit_node)

#define MONITOR_OPERATION(call)			\
  {						\
    tree o = pop_value (ptr_type_node);		\
    tree c;					\
    flush_quick_stack ();			\
    c = build_java_monitor (call, o);		\
    TREE_SIDE_EFFECTS (c) = 1;			\
3535
    java_add_stmt (c);				\
Anthony Green committed
3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
  }

#define SPECIAL_IINC(IGNORED) \
  { \
    unsigned int local_var_index = IMMEDIATE_u1; \
    int ival = IMMEDIATE_s1; \
    expand_iinc(local_var_index, ival, oldpc); \
  }

#define SPECIAL_WIDE(IGNORED) \
  { \
    int modified_opcode = IMMEDIATE_u1; \
    unsigned int local_var_index = IMMEDIATE_u2; \
    switch (modified_opcode) \
      { \
      case OPCODE_iinc: \
	{ \
	  int ival = IMMEDIATE_s2; \
	  expand_iinc (local_var_index, ival, oldpc); \
	  break; \
	} \
      case OPCODE_iload: \
      case OPCODE_lload: \
      case OPCODE_fload: \
      case OPCODE_dload: \
      case OPCODE_aload: \
	{ \
	  /* duplicate code from LOAD macro */ \
	  LOAD_INTERNAL(operand_type[modified_opcode], local_var_index); \
	  break; \
	} \
      case OPCODE_istore: \
      case OPCODE_lstore: \
      case OPCODE_fstore: \
      case OPCODE_dstore: \
      case OPCODE_astore: \
	{ \
	  STORE_INTERNAL(operand_type[modified_opcode], local_var_index); \
	  break; \
	} \
      default: \
        error ("unrecogized wide sub-instruction"); \
      } \
  }

#define SPECIAL_THROW(IGNORED) \
  build_java_athrow (pop_value (throwable_type_node))

#define SPECIAL_BREAK NOT_IMPL1
#define IMPL          NOT_IMPL

#include "javaop.def"
#undef JAVAOP
   default:
    fprintf (stderr, "%3d: unknown(%3d)\n", oldpc, byte_ops[PC]);
  }
  return PC;
}
3594

3595 3596 3597 3598
/* Return the opcode at PC in the code section pointed to by
   CODE_OFFSET.  */

static unsigned char
3599
peek_opcode_at_pc (JCF *jcf, int code_offset, int pc)
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
{
  unsigned char opcode;
  long absolute_offset = (long)JCF_TELL (jcf);

  JCF_SEEK (jcf, code_offset);
  opcode = jcf->read_ptr [pc];
  JCF_SEEK (jcf, absolute_offset);
  return opcode;
}

/* Some bytecode compilers are emitting accurate LocalVariableTable
   attributes. Here's an example:
   
     PC   <t>store_<n>
     PC+1 ...
     
     Attribute "LocalVariableTable"
     slot #<n>: ... (PC: PC+1 length: L)
   
   This is accurate because the local in slot <n> really exists after
   the opcode at PC is executed, hence from PC+1 to PC+1+L.

   This procedure recognizes this situation and extends the live range
   of the local in SLOT to START_PC-1 or START_PC-2 (depending on the
   length of the store instruction.)

   This function is used by `give_name_to_locals' so that a local's
   DECL features a DECL_LOCAL_START_PC such that the first related
3628
   store operation will use DECL as a destination, not an unrelated
3629 3630 3631 3632 3633 3634
   temporary created for the occasion.

   This function uses a global (instruction_bits) `note_instructions' should
   have allocated and filled properly.  */

int
3635 3636
maybe_adjust_start_pc (struct JCF *jcf, int code_offset,
		       int start_pc, int slot)
3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719
{
  int first, index, opcode;
  int pc, insn_pc;
  int wide_found = 0;

  if (!start_pc)
    return start_pc;

  first = index = -1;

  /* Find last previous instruction and remember it */
  for (pc = start_pc-1; pc; pc--) 
    if (instruction_bits [pc] & BCODE_INSTRUCTION_START)
      break;
  insn_pc = pc;

  /* Retrieve the instruction, handle `wide'. */  
  opcode = (int) peek_opcode_at_pc (jcf, code_offset, pc++);
  if (opcode == OPCODE_wide)
    {
      wide_found = 1;
      opcode = (int) peek_opcode_at_pc (jcf, code_offset, pc++);
    }

  switch (opcode)
    {
    case OPCODE_astore_0:
    case OPCODE_astore_1:
    case OPCODE_astore_2:
    case OPCODE_astore_3:
      first = OPCODE_astore_0;
      break;

    case OPCODE_istore_0:
    case OPCODE_istore_1:
    case OPCODE_istore_2:
    case OPCODE_istore_3:
      first = OPCODE_istore_0;
      break;
      
    case OPCODE_lstore_0:
    case OPCODE_lstore_1:
    case OPCODE_lstore_2:
    case OPCODE_lstore_3:
      first = OPCODE_lstore_0;
      break;

    case OPCODE_fstore_0:
    case OPCODE_fstore_1:
    case OPCODE_fstore_2:
    case OPCODE_fstore_3:
      first = OPCODE_fstore_0;
      break;

    case OPCODE_dstore_0:
    case OPCODE_dstore_1:
    case OPCODE_dstore_2:
    case OPCODE_dstore_3:
      first = OPCODE_dstore_0;
      break;

    case OPCODE_astore:
    case OPCODE_istore:
    case OPCODE_lstore:
    case OPCODE_fstore:
    case OPCODE_dstore:
      index = peek_opcode_at_pc (jcf, code_offset, pc);
      if (wide_found)
	{
	  int other = peek_opcode_at_pc (jcf, code_offset, ++pc);
	  index = (other << 8) + index;
	}
      break;
    }

  /* Now we decide: first >0 means we have a <t>store_<n>, index >0
     means we have a <t>store. */
  if ((first > 0 && opcode - first == slot) || (index > 0 && index == slot))
    start_pc = insn_pc;

  return start_pc;
}

3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731
/* Force the (direct) sub-operands of NODE to be evaluated in left-to-right
   order, as specified by Java Language Specification.

   The problem is that while expand_expr will evaluate its sub-operands in
   left-to-right order, for variables it will just return an rtx (i.e.
   an lvalue) for the variable (rather than an rvalue).  So it is possible
   that a later sub-operand will change the register, and when the
   actual operation is done, it will use the new value, when it should
   have used the original value.

   We fix this by using save_expr.  This forces the sub-operand to be
   copied into a fresh virtual register,
3732 3733 3734 3735

   For method invocation, we modify the arguments so that a
   left-to-right order evaluation is performed. Saved expressions
   will, in CALL_EXPR order, be reused when the call will be expanded.
3736 3737

   We also promote outgoing args if needed.  */
3738 3739

tree
3740
force_evaluation_order (tree node)
3741 3742 3743
{
  if (flag_syntax_only)
    return node;
3744 3745 3746 3747
  if (TREE_CODE (node) == CALL_EXPR
      || (TREE_CODE (node) == COMPOUND_EXPR
	  && TREE_CODE (TREE_OPERAND (node, 0)) == CALL_EXPR
	  && TREE_CODE (TREE_OPERAND (node, 1)) == SAVE_EXPR)) 
3748
    {
3749 3750
      tree call, cmp;
      int i, nargs;
3751

3752
      /* Account for wrapped around ctors.  */
3753
      if (TREE_CODE (node) == COMPOUND_EXPR)
3754 3755 3756
        call = TREE_OPERAND (node, 0);
      else
	call = node;
3757

3758
      nargs = call_expr_nargs (call);
3759

3760
      /* This reverses the evaluation order. This is a desired effect. */
3761
      for (i = 0, cmp = NULL_TREE; i < nargs; i++)
3762
	{
3763
	  tree arg = CALL_EXPR_ARG (call, i);
3764 3765
	  /* Promote types smaller than integer.  This is required by
	     some ABIs.  */
3766
	  tree type = TREE_TYPE (arg);
3767
	  tree saved;
3768 3769 3770 3771
	  if (targetm.calls.promote_prototypes (type)
	      && INTEGRAL_TYPE_P (type)
	      && INT_CST_LT_UNSIGNED (TYPE_SIZE (type),
				      TYPE_SIZE (integer_type_node)))
3772
	    arg = fold_convert (integer_type_node, arg);
3773

3774
	  saved = save_expr (force_evaluation_order (arg));
3775
	  cmp = (cmp == NULL_TREE ? saved :
3776
		 build2 (COMPOUND_EXPR, void_type_node, cmp, saved));
3777 3778

	  CALL_EXPR_ARG (call, i) = saved;
3779
	}
3780 3781 3782 3783 3784
      
      if (cmp && TREE_CODE (cmp) == COMPOUND_EXPR)
	TREE_SIDE_EFFECTS (cmp) = 1;

      if (cmp)
3785
	{
3786
	  cmp = build2 (COMPOUND_EXPR, TREE_TYPE (node), cmp, node);
3787 3788
	  if (TREE_TYPE (cmp) != void_type_node)
	    cmp = save_expr (cmp);
3789 3790
	  TREE_SIDE_EFFECTS (cmp) = 1;
	  node = cmp;
3791 3792 3793 3794
	}
    }
  return node;
}
3795

3796 3797 3798 3799 3800
/* Build a node to represent empty statements and blocks. */

tree
build_java_empty_stmt (void)
{
3801
  tree t = build_empty_stmt (input_location);
3802 3803 3804
  return t;
}

3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828
/* Promote all args of integral type before generating any code.  */

static void
promote_arguments (void)
{
  int i;
  tree arg;
  for (arg = DECL_ARGUMENTS (current_function_decl), i = 0;
       arg != NULL_TREE;  arg = TREE_CHAIN (arg), i++)
    {
      tree arg_type = TREE_TYPE (arg);
      if (INTEGRAL_TYPE_P (arg_type)
	  && TYPE_PRECISION (arg_type) < 32)
	{
	  tree copy = find_local_variable (i, integer_type_node, -1);
	  java_add_stmt (build2 (MODIFY_EXPR, integer_type_node,
				 copy,
				 fold_convert (integer_type_node, arg)));
	}
      if (TYPE_IS_WIDE (arg_type))
	i++;
    }
}

3829 3830 3831 3832 3833 3834 3835 3836 3837
/* Create a local variable that points to the constant pool.  */

static void
cache_cpool_data_ref (void)
{
  if (optimize)
    {
      tree cpool;
      tree d = build_constant_data_ref (flag_indirect_classes);
3838
      tree cpool_ptr = build_decl (input_location, VAR_DECL, NULL_TREE, 
3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
				   build_pointer_type (TREE_TYPE (d)));
      java_add_local_var (cpool_ptr);
      TREE_CONSTANT (cpool_ptr) = 1;

      java_add_stmt (build2 (MODIFY_EXPR, TREE_TYPE (cpool_ptr), 
			     cpool_ptr, build_address_of (d)));
      cpool = build1 (INDIRECT_REF, TREE_TYPE (d), cpool_ptr);
      TREE_THIS_NOTRAP (cpool) = 1;
      TYPE_CPOOL_DATA_REF (output_class) = cpool;
    }
}

3851
#include "gt-java-expr.h"