OSDN Git Service

2005-10-18 Paolo Bonzini <bonzini@gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / trans-types.c
1 /* Backend support for Fortran 95 basic types and derived types.
2    Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Paul Brook <paul@nowt.org>
4    and Steven Bosscher <s.bosscher@student.tudelft.nl>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
21 02110-1301, USA.  */
22
23 /* trans-types.c -- gfortran backend types */
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "tree.h"
29 #include "tm.h"
30 #include "target.h"
31 #include "ggc.h"
32 #include "toplev.h"
33 #include "gfortran.h"
34 #include "trans.h"
35 #include "trans-types.h"
36 #include "trans-const.h"
37 #include "real.h"
38 \f
39
40 #if (GFC_MAX_DIMENSIONS < 10)
41 #define GFC_RANK_DIGITS 1
42 #define GFC_RANK_PRINTF_FORMAT "%01d"
43 #elif (GFC_MAX_DIMENSIONS < 100)
44 #define GFC_RANK_DIGITS 2
45 #define GFC_RANK_PRINTF_FORMAT "%02d"
46 #else
47 #error If you really need >99 dimensions, continue the sequence above...
48 #endif
49
50 static tree gfc_get_derived_type (gfc_symbol * derived);
51
52 tree gfc_array_index_type;
53 tree gfc_array_range_type;
54 tree gfc_character1_type_node;
55 tree pvoid_type_node;
56 tree ppvoid_type_node;
57 tree pchar_type_node;
58
59 tree gfc_charlen_type_node;
60
61 static GTY(()) tree gfc_desc_dim_type;
62 static GTY(()) tree gfc_max_array_element_size;
63 static GTY(()) tree gfc_array_descriptor_base[GFC_MAX_DIMENSIONS];
64
65 /* Arrays for all integral and real kinds.  We'll fill this in at runtime
66    after the target has a chance to process command-line options.  */
67
68 #define MAX_INT_KINDS 5
69 gfc_integer_info gfc_integer_kinds[MAX_INT_KINDS + 1];
70 gfc_logical_info gfc_logical_kinds[MAX_INT_KINDS + 1];
71 static GTY(()) tree gfc_integer_types[MAX_INT_KINDS + 1];
72 static GTY(()) tree gfc_logical_types[MAX_INT_KINDS + 1];
73
74 #define MAX_REAL_KINDS 5
75 gfc_real_info gfc_real_kinds[MAX_REAL_KINDS + 1];
76 static GTY(()) tree gfc_real_types[MAX_REAL_KINDS + 1];
77 static GTY(()) tree gfc_complex_types[MAX_REAL_KINDS + 1];
78
79 /* The integer kind to use for array indices.  This will be set to the
80    proper value based on target information from the backend.  */
81
82 int gfc_index_integer_kind;
83
84 /* The default kinds of the various types.  */
85
86 int gfc_default_integer_kind;
87 int gfc_max_integer_kind;
88 int gfc_default_real_kind;
89 int gfc_default_double_kind;
90 int gfc_default_character_kind;
91 int gfc_default_logical_kind;
92 int gfc_default_complex_kind;
93 int gfc_c_int_kind;
94
95 /* Query the target to determine which machine modes are available for
96    computation.  Choose KIND numbers for them.  */
97
98 void
99 gfc_init_kinds (void)
100 {
101   enum machine_mode mode;
102   int i_index, r_index;
103   bool saw_i4 = false, saw_i8 = false;
104   bool saw_r4 = false, saw_r8 = false, saw_r16 = false;
105
106   for (i_index = 0, mode = MIN_MODE_INT; mode <= MAX_MODE_INT; mode++)
107     {
108       int kind, bitsize;
109
110       if (!targetm.scalar_mode_supported_p (mode))
111         continue;
112
113       /* The middle end doesn't support constants larger than 2*HWI.
114          Perhaps the target hook shouldn't have accepted these either,
115          but just to be safe...  */
116       bitsize = GET_MODE_BITSIZE (mode);
117       if (bitsize > 2*HOST_BITS_PER_WIDE_INT)
118         continue;
119
120       gcc_assert (i_index != MAX_INT_KINDS);
121
122       /* Let the kind equal the bit size divided by 8.  This insulates the
123          programmer from the underlying byte size.  */
124       kind = bitsize / 8;
125
126       if (kind == 4)
127         saw_i4 = true;
128       if (kind == 8)
129         saw_i8 = true;
130
131       gfc_integer_kinds[i_index].kind = kind;
132       gfc_integer_kinds[i_index].radix = 2;
133       gfc_integer_kinds[i_index].digits = bitsize - 1;
134       gfc_integer_kinds[i_index].bit_size = bitsize;
135
136       gfc_logical_kinds[i_index].kind = kind;
137       gfc_logical_kinds[i_index].bit_size = bitsize;
138
139       i_index += 1;
140     }
141
142   /* Set the maximum integer kind.  Used with at least BOZ constants.  */
143   gfc_max_integer_kind = gfc_integer_kinds[i_index - 1].kind;
144
145   for (r_index = 0, mode = MIN_MODE_FLOAT; mode <= MAX_MODE_FLOAT; mode++)
146     {
147       const struct real_format *fmt = REAL_MODE_FORMAT (mode);
148       int kind;
149
150       if (fmt == NULL)
151         continue;
152       if (!targetm.scalar_mode_supported_p (mode))
153         continue;
154
155       /* Only let float/double/long double go through because the fortran
156          library assumes these are the only floating point types.  */
157
158       if (mode != TYPE_MODE (float_type_node)
159           && (mode != TYPE_MODE (double_type_node))
160           && (mode != TYPE_MODE (long_double_type_node)))
161         continue;
162
163       /* Let the kind equal the precision divided by 8, rounding up.  Again,
164          this insulates the programmer from the underlying byte size.
165
166          Also, it effectively deals with IEEE extended formats.  There, the
167          total size of the type may equal 16, but it's got 6 bytes of padding
168          and the increased size can get in the way of a real IEEE quad format
169          which may also be supported by the target.
170
171          We round up so as to handle IA-64 __floatreg (RFmode), which is an
172          82 bit type.  Not to be confused with __float80 (XFmode), which is
173          an 80 bit type also supported by IA-64.  So XFmode should come out
174          to be kind=10, and RFmode should come out to be kind=11.  Egads.  */
175
176       kind = (GET_MODE_PRECISION (mode) + 7) / 8;
177
178       if (kind == 4)
179         saw_r4 = true;
180       if (kind == 8)
181         saw_r8 = true;
182       if (kind == 16)
183         saw_r16 = true;
184
185       /* Careful we don't stumble a wierd internal mode.  */
186       gcc_assert (r_index <= 0 || gfc_real_kinds[r_index-1].kind != kind);
187       /* Or have too many modes for the allocated space.  */
188       gcc_assert (r_index != MAX_REAL_KINDS);
189
190       gfc_real_kinds[r_index].kind = kind;
191       gfc_real_kinds[r_index].radix = fmt->b;
192       gfc_real_kinds[r_index].digits = fmt->p;
193       gfc_real_kinds[r_index].min_exponent = fmt->emin;
194       gfc_real_kinds[r_index].max_exponent = fmt->emax;
195       gfc_real_kinds[r_index].mode_precision = GET_MODE_PRECISION (mode);
196       r_index += 1;
197     }
198
199   /* Choose the default integer kind.  We choose 4 unless the user
200      directs us otherwise.  */
201   if (gfc_option.flag_default_integer)
202     {
203       if (!saw_i8)
204         fatal_error ("integer kind=8 not available for -fdefault-integer-8 option");
205       gfc_default_integer_kind = 8;
206     }
207   else if (saw_i4)
208     gfc_default_integer_kind = 4;
209   else
210     gfc_default_integer_kind = gfc_integer_kinds[i_index - 1].kind;
211
212   /* Choose the default real kind.  Again, we choose 4 when possible.  */
213   if (gfc_option.flag_default_real)
214     {
215       if (!saw_r8)
216         fatal_error ("real kind=8 not available for -fdefault-real-8 option");
217       gfc_default_real_kind = 8;
218     }
219   else if (saw_r4)
220     gfc_default_real_kind = 4;
221   else
222     gfc_default_real_kind = gfc_real_kinds[0].kind;
223
224   /* Choose the default double kind.  If -fdefault-real and -fdefault-double 
225      are specified, we use kind=8, if it's available.  If -fdefault-real is
226      specified without -fdefault-double, we use kind=16, if it's available.
227      Otherwise we do not change anything.  */
228   if (gfc_option.flag_default_double && !gfc_option.flag_default_real)
229     fatal_error ("Use of -fdefault-double-8 requires -fdefault-real-8");
230
231   if (gfc_option.flag_default_real && gfc_option.flag_default_double && saw_r8)
232     gfc_default_double_kind = 8;
233   else if (gfc_option.flag_default_real && saw_r16)
234     gfc_default_double_kind = 16;
235   else if (saw_r4 && saw_r8)
236     gfc_default_double_kind = 8;
237   else
238     {
239       /* F95 14.6.3.1: A nonpointer scalar object of type double precision
240          real ... occupies two contiguous numeric storage units.
241
242          Therefore we must be supplied a kind twice as large as we chose
243          for single precision.  There are loopholes, in that double
244          precision must *occupy* two storage units, though it doesn't have
245          to *use* two storage units.  Which means that you can make this
246          kind artificially wide by padding it.  But at present there are
247          no GCC targets for which a two-word type does not exist, so we
248          just let gfc_validate_kind abort and tell us if something breaks.  */
249
250       gfc_default_double_kind
251         = gfc_validate_kind (BT_REAL, gfc_default_real_kind * 2, false);
252     }
253
254   /* The default logical kind is constrained to be the same as the
255      default integer kind.  Similarly with complex and real.  */
256   gfc_default_logical_kind = gfc_default_integer_kind;
257   gfc_default_complex_kind = gfc_default_real_kind;
258
259   /* Choose the smallest integer kind for our default character.  */
260   gfc_default_character_kind = gfc_integer_kinds[0].kind;
261
262   /* Choose the integer kind the same size as "void*" for our index kind.  */
263   gfc_index_integer_kind = POINTER_SIZE / 8;
264   /* Pick a kind the same size as the C "int" type.  */
265   gfc_c_int_kind = INT_TYPE_SIZE / 8;
266 }
267
268 /* Make sure that a valid kind is present.  Returns an index into the
269    associated kinds array, -1 if the kind is not present.  */
270
271 static int
272 validate_integer (int kind)
273 {
274   int i;
275
276   for (i = 0; gfc_integer_kinds[i].kind != 0; i++)
277     if (gfc_integer_kinds[i].kind == kind)
278       return i;
279
280   return -1;
281 }
282
283 static int
284 validate_real (int kind)
285 {
286   int i;
287
288   for (i = 0; gfc_real_kinds[i].kind != 0; i++)
289     if (gfc_real_kinds[i].kind == kind)
290       return i;
291
292   return -1;
293 }
294
295 static int
296 validate_logical (int kind)
297 {
298   int i;
299
300   for (i = 0; gfc_logical_kinds[i].kind; i++)
301     if (gfc_logical_kinds[i].kind == kind)
302       return i;
303
304   return -1;
305 }
306
307 static int
308 validate_character (int kind)
309 {
310   return kind == gfc_default_character_kind ? 0 : -1;
311 }
312
313 /* Validate a kind given a basic type.  The return value is the same
314    for the child functions, with -1 indicating nonexistence of the
315    type.  If MAY_FAIL is false, then -1 is never returned, and we ICE.  */
316
317 int
318 gfc_validate_kind (bt type, int kind, bool may_fail)
319 {
320   int rc;
321
322   switch (type)
323     {
324     case BT_REAL:               /* Fall through */
325     case BT_COMPLEX:
326       rc = validate_real (kind);
327       break;
328     case BT_INTEGER:
329       rc = validate_integer (kind);
330       break;
331     case BT_LOGICAL:
332       rc = validate_logical (kind);
333       break;
334     case BT_CHARACTER:
335       rc = validate_character (kind);
336       break;
337
338     default:
339       gfc_internal_error ("gfc_validate_kind(): Got bad type");
340     }
341
342   if (rc < 0 && !may_fail)
343     gfc_internal_error ("gfc_validate_kind(): Got bad kind");
344
345   return rc;
346 }
347
348
349 /* Four subroutines of gfc_init_types.  Create type nodes for the given kind.
350    Reuse common type nodes where possible.  Recognize if the kind matches up
351    with a C type.  This will be used later in determining which routines may
352    be scarfed from libm.  */
353
354 static tree
355 gfc_build_int_type (gfc_integer_info *info)
356 {
357   int mode_precision = info->bit_size;
358
359   if (mode_precision == CHAR_TYPE_SIZE)
360     info->c_char = 1;
361   if (mode_precision == SHORT_TYPE_SIZE)
362     info->c_short = 1;
363   if (mode_precision == INT_TYPE_SIZE)
364     info->c_int = 1;
365   if (mode_precision == LONG_TYPE_SIZE)
366     info->c_long = 1;
367   if (mode_precision == LONG_LONG_TYPE_SIZE)
368     info->c_long_long = 1;
369
370   if (TYPE_PRECISION (intQI_type_node) == mode_precision)
371     return intQI_type_node;
372   if (TYPE_PRECISION (intHI_type_node) == mode_precision)
373     return intHI_type_node;
374   if (TYPE_PRECISION (intSI_type_node) == mode_precision)
375     return intSI_type_node;
376   if (TYPE_PRECISION (intDI_type_node) == mode_precision)
377     return intDI_type_node;
378   if (TYPE_PRECISION (intTI_type_node) == mode_precision)
379     return intTI_type_node;
380
381   return make_signed_type (mode_precision);
382 }
383
384 static tree
385 gfc_build_real_type (gfc_real_info *info)
386 {
387   int mode_precision = info->mode_precision;
388   tree new_type;
389
390   if (mode_precision == FLOAT_TYPE_SIZE)
391     info->c_float = 1;
392   if (mode_precision == DOUBLE_TYPE_SIZE)
393     info->c_double = 1;
394   if (mode_precision == LONG_DOUBLE_TYPE_SIZE)
395     info->c_long_double = 1;
396
397   if (TYPE_PRECISION (float_type_node) == mode_precision)
398     return float_type_node;
399   if (TYPE_PRECISION (double_type_node) == mode_precision)
400     return double_type_node;
401   if (TYPE_PRECISION (long_double_type_node) == mode_precision)
402     return long_double_type_node;
403
404   new_type = make_node (REAL_TYPE);
405   TYPE_PRECISION (new_type) = mode_precision;
406   layout_type (new_type);
407   return new_type;
408 }
409
410 static tree
411 gfc_build_complex_type (tree scalar_type)
412 {
413   tree new_type;
414
415   if (scalar_type == NULL)
416     return NULL;
417   if (scalar_type == float_type_node)
418     return complex_float_type_node;
419   if (scalar_type == double_type_node)
420     return complex_double_type_node;
421   if (scalar_type == long_double_type_node)
422     return complex_long_double_type_node;
423
424   new_type = make_node (COMPLEX_TYPE);
425   TREE_TYPE (new_type) = scalar_type;
426   layout_type (new_type);
427   return new_type;
428 }
429
430 static tree
431 gfc_build_logical_type (gfc_logical_info *info)
432 {
433   int bit_size = info->bit_size;
434   tree new_type;
435
436   if (bit_size == BOOL_TYPE_SIZE)
437     {
438       info->c_bool = 1;
439       return boolean_type_node;
440     }
441
442   new_type = make_unsigned_type (bit_size);
443   TREE_SET_CODE (new_type, BOOLEAN_TYPE);
444   TYPE_MAX_VALUE (new_type) = build_int_cst (new_type, 1);
445   TYPE_PRECISION (new_type) = 1;
446
447   return new_type;
448 }
449
450 #if 0
451 /* Return the bit size of the C "size_t".  */
452
453 static unsigned int
454 c_size_t_size (void)
455 {
456 #ifdef SIZE_TYPE  
457   if (strcmp (SIZE_TYPE, "unsigned int") == 0)
458     return INT_TYPE_SIZE;
459   if (strcmp (SIZE_TYPE, "long unsigned int") == 0)
460     return LONG_TYPE_SIZE;
461   if (strcmp (SIZE_TYPE, "short unsigned int") == 0)
462     return SHORT_TYPE_SIZE;
463   gcc_unreachable ();
464 #else
465   return LONG_TYPE_SIZE;
466 #endif
467 }
468 #endif
469
470 /* Create the backend type nodes. We map them to their
471    equivalent C type, at least for now.  We also give
472    names to the types here, and we push them in the
473    global binding level context.*/
474
475 void
476 gfc_init_types (void)
477 {
478   char name_buf[16];
479   int index;
480   tree type;
481   unsigned n;
482   unsigned HOST_WIDE_INT hi;
483   unsigned HOST_WIDE_INT lo;
484
485   /* Create and name the types.  */
486 #define PUSH_TYPE(name, node) \
487   pushdecl (build_decl (TYPE_DECL, get_identifier (name), node))
488
489   for (index = 0; gfc_integer_kinds[index].kind != 0; ++index)
490     {
491       type = gfc_build_int_type (&gfc_integer_kinds[index]);
492       gfc_integer_types[index] = type;
493       snprintf (name_buf, sizeof(name_buf), "int%d",
494                 gfc_integer_kinds[index].kind);
495       PUSH_TYPE (name_buf, type);
496     }
497
498   for (index = 0; gfc_logical_kinds[index].kind != 0; ++index)
499     {
500       type = gfc_build_logical_type (&gfc_logical_kinds[index]);
501       gfc_logical_types[index] = type;
502       snprintf (name_buf, sizeof(name_buf), "logical%d",
503                 gfc_logical_kinds[index].kind);
504       PUSH_TYPE (name_buf, type);
505     }
506
507   for (index = 0; gfc_real_kinds[index].kind != 0; index++)
508     {
509       type = gfc_build_real_type (&gfc_real_kinds[index]);
510       gfc_real_types[index] = type;
511       snprintf (name_buf, sizeof(name_buf), "real%d",
512                 gfc_real_kinds[index].kind);
513       PUSH_TYPE (name_buf, type);
514
515       type = gfc_build_complex_type (type);
516       gfc_complex_types[index] = type;
517       snprintf (name_buf, sizeof(name_buf), "complex%d",
518                 gfc_real_kinds[index].kind);
519       PUSH_TYPE (name_buf, type);
520     }
521
522   gfc_character1_type_node = build_type_variant (unsigned_char_type_node, 
523                                                  0, 0);
524   PUSH_TYPE ("char", gfc_character1_type_node);
525
526   PUSH_TYPE ("byte", unsigned_char_type_node);
527   PUSH_TYPE ("void", void_type_node);
528
529   /* DBX debugging output gets upset if these aren't set.  */
530   if (!TYPE_NAME (integer_type_node))
531     PUSH_TYPE ("c_integer", integer_type_node);
532   if (!TYPE_NAME (char_type_node))
533     PUSH_TYPE ("c_char", char_type_node);
534
535 #undef PUSH_TYPE
536
537   pvoid_type_node = build_pointer_type (void_type_node);
538   ppvoid_type_node = build_pointer_type (pvoid_type_node);
539   pchar_type_node = build_pointer_type (gfc_character1_type_node);
540
541   gfc_array_index_type = gfc_get_int_type (gfc_index_integer_kind);
542   /* We cannot use gfc_index_zero_node in definition of gfc_array_range_type,
543      since this function is called before gfc_init_constants.  */
544   gfc_array_range_type
545           = build_range_type (gfc_array_index_type,
546                               build_int_cst (gfc_array_index_type, 0),
547                               NULL_TREE);
548
549   /* The maximum array element size that can be handled is determined
550      by the number of bits available to store this field in the array
551      descriptor.  */
552
553   n = TYPE_PRECISION (gfc_array_index_type) - GFC_DTYPE_SIZE_SHIFT;
554   lo = ~ (unsigned HOST_WIDE_INT) 0;
555   if (n > HOST_BITS_PER_WIDE_INT)
556     hi = lo >> (2*HOST_BITS_PER_WIDE_INT - n);
557   else
558     hi = 0, lo >>= HOST_BITS_PER_WIDE_INT - n;
559   gfc_max_array_element_size
560     = build_int_cst_wide (long_unsigned_type_node, lo, hi);
561
562   size_type_node = gfc_array_index_type;
563
564   boolean_type_node = gfc_get_logical_type (gfc_default_logical_kind);
565   boolean_true_node = build_int_cst (boolean_type_node, 1);
566   boolean_false_node = build_int_cst (boolean_type_node, 0);
567
568   /* ??? Shouldn't this be based on gfc_index_integer_kind or so?  */
569   gfc_charlen_type_node = gfc_get_int_type (4);
570 }
571
572 /* Get the type node for the given type and kind.  */
573
574 tree
575 gfc_get_int_type (int kind)
576 {
577   int index = gfc_validate_kind (BT_INTEGER, kind, true);
578   return index < 0 ? 0 : gfc_integer_types[index];
579 }
580
581 tree
582 gfc_get_real_type (int kind)
583 {
584   int index = gfc_validate_kind (BT_REAL, kind, true);
585   return index < 0 ? 0 : gfc_real_types[index];
586 }
587
588 tree
589 gfc_get_complex_type (int kind)
590 {
591   int index = gfc_validate_kind (BT_COMPLEX, kind, true);
592   return index < 0 ? 0 : gfc_complex_types[index];
593 }
594
595 tree
596 gfc_get_logical_type (int kind)
597 {
598   int index = gfc_validate_kind (BT_LOGICAL, kind, true);
599   return index < 0 ? 0 : gfc_logical_types[index];
600 }
601 \f
602 /* Create a character type with the given kind and length.  */
603
604 tree
605 gfc_get_character_type_len (int kind, tree len)
606 {
607   tree bounds, type;
608
609   gfc_validate_kind (BT_CHARACTER, kind, false);
610
611   bounds = build_range_type (gfc_charlen_type_node, gfc_index_one_node, len);
612   type = build_array_type (gfc_character1_type_node, bounds);
613   TYPE_STRING_FLAG (type) = 1;
614
615   return type;
616 }
617
618
619 /* Get a type node for a character kind.  */
620
621 tree
622 gfc_get_character_type (int kind, gfc_charlen * cl)
623 {
624   tree len;
625
626   len = (cl == NULL) ? NULL_TREE : cl->backend_decl;
627
628   return gfc_get_character_type_len (kind, len);
629 }
630 \f
631 /* Covert a basic type.  This will be an array for character types.  */
632
633 tree
634 gfc_typenode_for_spec (gfc_typespec * spec)
635 {
636   tree basetype;
637
638   switch (spec->type)
639     {
640     case BT_UNKNOWN:
641       gcc_unreachable ();
642
643     case BT_INTEGER:
644       basetype = gfc_get_int_type (spec->kind);
645       break;
646
647     case BT_REAL:
648       basetype = gfc_get_real_type (spec->kind);
649       break;
650
651     case BT_COMPLEX:
652       basetype = gfc_get_complex_type (spec->kind);
653       break;
654
655     case BT_LOGICAL:
656       basetype = gfc_get_logical_type (spec->kind);
657       break;
658
659     case BT_CHARACTER:
660       basetype = gfc_get_character_type (spec->kind, spec->cl);
661       break;
662
663     case BT_DERIVED:
664       basetype = gfc_get_derived_type (spec->derived);
665       break;
666
667     default:
668       gcc_unreachable ();
669     }
670   return basetype;
671 }
672 \f
673 /* Build an INT_CST for constant expressions, otherwise return NULL_TREE.  */
674
675 static tree
676 gfc_conv_array_bound (gfc_expr * expr)
677 {
678   /* If expr is an integer constant, return that.  */
679   if (expr != NULL && expr->expr_type == EXPR_CONSTANT)
680     return gfc_conv_mpz_to_tree (expr->value.integer, gfc_index_integer_kind);
681
682   /* Otherwise return NULL.  */
683   return NULL_TREE;
684 }
685 \f
686 tree
687 gfc_get_element_type (tree type)
688 {
689   tree element;
690
691   if (GFC_ARRAY_TYPE_P (type))
692     {
693       if (TREE_CODE (type) == POINTER_TYPE)
694         type = TREE_TYPE (type);
695       gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
696       element = TREE_TYPE (type);
697     }
698   else
699     {
700       gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
701       element = GFC_TYPE_ARRAY_DATAPTR_TYPE (type);
702
703       gcc_assert (TREE_CODE (element) == POINTER_TYPE);
704       element = TREE_TYPE (element);
705
706       gcc_assert (TREE_CODE (element) == ARRAY_TYPE);
707       element = TREE_TYPE (element);
708     }
709
710   return element;
711 }
712 \f
713 /* Build an array. This function is called from gfc_sym_type().
714    Actually returns array descriptor type.
715
716    Format of array descriptors is as follows:
717
718     struct gfc_array_descriptor
719     {
720       array *data
721       index offset;
722       index dtype;
723       struct descriptor_dimension dimension[N_DIM];
724     }
725
726     struct descriptor_dimension
727     {
728       index stride;
729       index lbound;
730       index ubound;
731     }
732
733    Translation code should use gfc_conv_descriptor_* rather than accessing
734    the descriptor directly. Any changes to the array descriptor type will
735    require changes in gfc_conv_descriptor_* and gfc_build_array_initializer.
736
737    This is represented internally as a RECORD_TYPE. The index nodes are
738    gfc_array_index_type and the data node is a pointer to the data. See below
739    for the handling of character types.
740
741    The dtype member is formatted as follows:
742     rank = dtype & GFC_DTYPE_RANK_MASK // 3 bits
743     type = (dtype & GFC_DTYPE_TYPE_MASK) >> GFC_DTYPE_TYPE_SHIFT // 3 bits
744     size = dtype >> GFC_DTYPE_SIZE_SHIFT
745
746    I originally used nested ARRAY_TYPE nodes to represent arrays, but this
747    generated poor code for assumed/deferred size arrays.  These require
748    use of PLACEHOLDER_EXPR/WITH_RECORD_EXPR, which isn't part of the GENERIC
749    grammar.  Also, there is no way to explicitly set the array stride, so
750    all data must be packed(1).  I've tried to mark all the functions which
751    would require modification with a GCC ARRAYS comment.
752
753    The data component points to the first element in the array.
754    The offset field is the position of the origin of the array
755    (ie element (0, 0 ...)).  This may be outsite the bounds of the array.
756
757    An element is accessed by
758    data[offset + index0*stride0 + index1*stride1 + index2*stride2]
759    This gives good performance as the computation does not involve the
760    bounds of the array.  For packed arrays, this is optimized further by
761    substituting the known strides.
762
763    This system has one problem: all array bounds must be withing 2^31 elements
764    of the origin (2^63 on 64-bit machines).  For example
765    integer, dimension (80000:90000, 80000:90000, 2) :: array
766    may not work properly on 32-bit machines because 80000*80000 > 2^31, so
767    the calculation for stride02 would overflow.  This may still work, but
768    I haven't checked, and it relies on the overflow doing the right thing.
769
770    The way to fix this problem is to access elements as follows:
771    data[(index0-lbound0)*stride0 + (index1-lbound1)*stride1]
772    Obviously this is much slower.  I will make this a compile time option,
773    something like -fsmall-array-offsets.  Mixing code compiled with and without
774    this switch will work.
775
776    (1) This can be worked around by modifying the upper bound of the previous
777    dimension.  This requires extra fields in the descriptor (both real_ubound
778    and fake_ubound).  In tree.def there is mention of TYPE_SEP, which
779    may allow us to do this.  However I can't find mention of this anywhere
780    else.  */
781
782
783 /* Returns true if the array sym does not require a descriptor.  */
784
785 int
786 gfc_is_nodesc_array (gfc_symbol * sym)
787 {
788   gcc_assert (sym->attr.dimension);
789
790   /* We only want local arrays.  */
791   if (sym->attr.pointer || sym->attr.allocatable)
792     return 0;
793
794   if (sym->attr.dummy)
795     {
796       if (sym->as->type != AS_ASSUMED_SHAPE)
797         return 1;
798       else
799         return 0;
800     }
801
802   if (sym->attr.result || sym->attr.function)
803     return 0;
804
805   gcc_assert (sym->as->type == AS_EXPLICIT);
806
807   return 1;
808 }
809
810
811 /* Create an array descriptor type.  */
812
813 static tree
814 gfc_build_array_type (tree type, gfc_array_spec * as)
815 {
816   tree lbound[GFC_MAX_DIMENSIONS];
817   tree ubound[GFC_MAX_DIMENSIONS];
818   int n;
819
820   for (n = 0; n < as->rank; n++)
821     {
822       /* Create expressions for the known bounds of the array.  */
823       if (as->type == AS_ASSUMED_SHAPE && as->lower[n] == NULL)
824         lbound[n] = gfc_index_one_node;
825       else
826         lbound[n] = gfc_conv_array_bound (as->lower[n]);
827       ubound[n] = gfc_conv_array_bound (as->upper[n]);
828     }
829
830   return gfc_get_array_type_bounds (type, as->rank, lbound, ubound, 0);
831 }
832 \f
833 /* Returns the struct descriptor_dimension type.  */
834
835 static tree
836 gfc_get_desc_dim_type (void)
837 {
838   tree type;
839   tree decl;
840   tree fieldlist;
841
842   if (gfc_desc_dim_type)
843     return gfc_desc_dim_type;
844
845   /* Build the type node.  */
846   type = make_node (RECORD_TYPE);
847
848   TYPE_NAME (type) = get_identifier ("descriptor_dimension");
849   TYPE_PACKED (type) = 1;
850
851   /* Consists of the stride, lbound and ubound members.  */
852   decl = build_decl (FIELD_DECL,
853                      get_identifier ("stride"), gfc_array_index_type);
854   DECL_CONTEXT (decl) = type;
855   fieldlist = decl;
856
857   decl = build_decl (FIELD_DECL,
858                      get_identifier ("lbound"), gfc_array_index_type);
859   DECL_CONTEXT (decl) = type;
860   fieldlist = chainon (fieldlist, decl);
861
862   decl = build_decl (FIELD_DECL,
863                      get_identifier ("ubound"), gfc_array_index_type);
864   DECL_CONTEXT (decl) = type;
865   fieldlist = chainon (fieldlist, decl);
866
867   /* Finish off the type.  */
868   TYPE_FIELDS (type) = fieldlist;
869
870   gfc_finish_type (type);
871
872   gfc_desc_dim_type = type;
873   return type;
874 }
875
876
877 /* Return the DTYPE for an array.  This describes the type and type parameters
878    of the array.  */
879 /* TODO: Only call this when the value is actually used, and make all the
880    unknown cases abort.  */
881
882 tree
883 gfc_get_dtype (tree type)
884 {
885   tree size;
886   int n;
887   HOST_WIDE_INT i;
888   tree tmp;
889   tree dtype;
890   tree etype;
891   int rank;
892
893   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type) || GFC_ARRAY_TYPE_P (type));
894
895   if (GFC_TYPE_ARRAY_DTYPE (type))
896     return GFC_TYPE_ARRAY_DTYPE (type);
897
898   rank = GFC_TYPE_ARRAY_RANK (type);
899   etype = gfc_get_element_type (type);
900
901   switch (TREE_CODE (etype))
902     {
903     case INTEGER_TYPE:
904       n = GFC_DTYPE_INTEGER;
905       break;
906
907     case BOOLEAN_TYPE:
908       n = GFC_DTYPE_LOGICAL;
909       break;
910
911     case REAL_TYPE:
912       n = GFC_DTYPE_REAL;
913       break;
914
915     case COMPLEX_TYPE:
916       n = GFC_DTYPE_COMPLEX;
917       break;
918
919     /* We will never have arrays of arrays.  */
920     case RECORD_TYPE:
921       n = GFC_DTYPE_DERIVED;
922       break;
923
924     case ARRAY_TYPE:
925       n = GFC_DTYPE_CHARACTER;
926       break;
927
928     default:
929       /* TODO: Don't do dtype for temporary descriptorless arrays.  */
930       /* We can strange array types for temporary arrays.  */
931       return gfc_index_zero_node;
932     }
933
934   gcc_assert (rank <= GFC_DTYPE_RANK_MASK);
935   size = TYPE_SIZE_UNIT (etype);
936
937   i = rank | (n << GFC_DTYPE_TYPE_SHIFT);
938   if (size && INTEGER_CST_P (size))
939     {
940       if (tree_int_cst_lt (gfc_max_array_element_size, size))
941         internal_error ("Array element size too big");
942
943       i += TREE_INT_CST_LOW (size) << GFC_DTYPE_SIZE_SHIFT;
944     }
945   dtype = build_int_cst (gfc_array_index_type, i);
946
947   if (size && !INTEGER_CST_P (size))
948     {
949       tmp = build_int_cst (gfc_array_index_type, GFC_DTYPE_SIZE_SHIFT);
950       tmp  = fold_build2 (LSHIFT_EXPR, gfc_array_index_type, size, tmp);
951       dtype = fold_build2 (PLUS_EXPR, gfc_array_index_type, tmp, dtype);
952     }
953   /* If we don't know the size we leave it as zero.  This should never happen
954      for anything that is actually used.  */
955   /* TODO: Check this is actually true, particularly when repacking
956      assumed size parameters.  */
957
958   GFC_TYPE_ARRAY_DTYPE (type) = dtype;
959   return dtype;
960 }
961
962
963 /* Build an array type for use without a descriptor.  Valid values of packed
964    are 0=no, 1=partial, 2=full, 3=static.  */
965
966 tree
967 gfc_get_nodesc_array_type (tree etype, gfc_array_spec * as, int packed)
968 {
969   tree range;
970   tree type;
971   tree tmp;
972   int n;
973   int known_stride;
974   int known_offset;
975   mpz_t offset;
976   mpz_t stride;
977   mpz_t delta;
978   gfc_expr *expr;
979
980   mpz_init_set_ui (offset, 0);
981   mpz_init_set_ui (stride, 1);
982   mpz_init (delta);
983
984   /* We don't use build_array_type because this does not include include
985      lang-specific information (i.e. the bounds of the array) when checking
986      for duplicates.  */
987   type = make_node (ARRAY_TYPE);
988
989   GFC_ARRAY_TYPE_P (type) = 1;
990   TYPE_LANG_SPECIFIC (type) = (struct lang_type *)
991     ggc_alloc_cleared (sizeof (struct lang_type));
992
993   known_stride = (packed != 0);
994   known_offset = 1;
995   for (n = 0; n < as->rank; n++)
996     {
997       /* Fill in the stride and bound components of the type.  */
998       if (known_stride)
999         tmp =  gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1000       else
1001         tmp = NULL_TREE;
1002       GFC_TYPE_ARRAY_STRIDE (type, n) = tmp;
1003
1004       expr = as->lower[n];
1005       if (expr->expr_type == EXPR_CONSTANT)
1006         {
1007           tmp = gfc_conv_mpz_to_tree (expr->value.integer,
1008                                   gfc_index_integer_kind);
1009         }
1010       else
1011         {
1012           known_stride = 0;
1013           tmp = NULL_TREE;
1014         }
1015       GFC_TYPE_ARRAY_LBOUND (type, n) = tmp;
1016
1017       if (known_stride)
1018         {
1019           /* Calculate the offset.  */
1020           mpz_mul (delta, stride, as->lower[n]->value.integer);
1021           mpz_sub (offset, offset, delta);
1022         }
1023       else
1024         known_offset = 0;
1025
1026       expr = as->upper[n];
1027       if (expr && expr->expr_type == EXPR_CONSTANT)
1028         {
1029           tmp = gfc_conv_mpz_to_tree (expr->value.integer,
1030                                   gfc_index_integer_kind);
1031         }
1032       else
1033         {
1034           tmp = NULL_TREE;
1035           known_stride = 0;
1036         }
1037       GFC_TYPE_ARRAY_UBOUND (type, n) = tmp;
1038
1039       if (known_stride)
1040         {
1041           /* Calculate the stride.  */
1042           mpz_sub (delta, as->upper[n]->value.integer,
1043                    as->lower[n]->value.integer);
1044           mpz_add_ui (delta, delta, 1);
1045           mpz_mul (stride, stride, delta);
1046         }
1047
1048       /* Only the first stride is known for partial packed arrays.  */
1049       if (packed < 2)
1050         known_stride = 0;
1051     }
1052
1053   if (known_offset)
1054     {
1055       GFC_TYPE_ARRAY_OFFSET (type) =
1056         gfc_conv_mpz_to_tree (offset, gfc_index_integer_kind);
1057     }
1058   else
1059     GFC_TYPE_ARRAY_OFFSET (type) = NULL_TREE;
1060
1061   if (known_stride)
1062     {
1063       GFC_TYPE_ARRAY_SIZE (type) =
1064         gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1065     }
1066   else
1067     GFC_TYPE_ARRAY_SIZE (type) = NULL_TREE;
1068
1069   GFC_TYPE_ARRAY_RANK (type) = as->rank;
1070   GFC_TYPE_ARRAY_DTYPE (type) = NULL_TREE;
1071   range = build_range_type (gfc_array_index_type, gfc_index_zero_node,
1072                             NULL_TREE);
1073   /* TODO: use main type if it is unbounded.  */
1074   GFC_TYPE_ARRAY_DATAPTR_TYPE (type) =
1075     build_pointer_type (build_array_type (etype, range));
1076
1077   if (known_stride)
1078     {
1079       mpz_sub_ui (stride, stride, 1);
1080       range = gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1081     }
1082   else
1083     range = NULL_TREE;
1084
1085   range = build_range_type (gfc_array_index_type, gfc_index_zero_node, range);
1086   TYPE_DOMAIN (type) = range;
1087
1088   build_pointer_type (etype);
1089   TREE_TYPE (type) = etype;
1090
1091   layout_type (type);
1092
1093   mpz_clear (offset);
1094   mpz_clear (stride);
1095   mpz_clear (delta);
1096
1097   if (packed < 3 || !known_stride)
1098     {
1099       /* For dummy arrays and automatic (heap allocated) arrays we
1100          want a pointer to the array.  */
1101       type = build_pointer_type (type);
1102       GFC_ARRAY_TYPE_P (type) = 1;
1103       TYPE_LANG_SPECIFIC (type) = TYPE_LANG_SPECIFIC (TREE_TYPE (type));
1104     }
1105   return type;
1106 }
1107
1108 /* Return or create the base type for an array descriptor.  */
1109
1110 static tree
1111 gfc_get_array_descriptor_base (int dimen)
1112 {
1113   tree fat_type, fieldlist, decl, arraytype;
1114   char name[16 + GFC_RANK_DIGITS + 1];
1115
1116   gcc_assert (dimen >= 1 && dimen <= GFC_MAX_DIMENSIONS);
1117   if (gfc_array_descriptor_base[dimen - 1])
1118     return gfc_array_descriptor_base[dimen - 1];
1119
1120   /* Build the type node.  */
1121   fat_type = make_node (RECORD_TYPE);
1122
1123   sprintf (name, "array_descriptor" GFC_RANK_PRINTF_FORMAT, dimen);
1124   TYPE_NAME (fat_type) = get_identifier (name);
1125
1126   /* Add the data member as the first element of the descriptor.  */
1127   decl = build_decl (FIELD_DECL, get_identifier ("data"), ptr_type_node);
1128
1129   DECL_CONTEXT (decl) = fat_type;
1130   fieldlist = decl;
1131
1132   /* Add the base component.  */
1133   decl = build_decl (FIELD_DECL, get_identifier ("offset"),
1134                      gfc_array_index_type);
1135   DECL_CONTEXT (decl) = fat_type;
1136   fieldlist = chainon (fieldlist, decl);
1137
1138   /* Add the dtype component.  */
1139   decl = build_decl (FIELD_DECL, get_identifier ("dtype"),
1140                      gfc_array_index_type);
1141   DECL_CONTEXT (decl) = fat_type;
1142   fieldlist = chainon (fieldlist, decl);
1143
1144   /* Build the array type for the stride and bound components.  */
1145   arraytype =
1146     build_array_type (gfc_get_desc_dim_type (),
1147                       build_range_type (gfc_array_index_type,
1148                                         gfc_index_zero_node,
1149                                         gfc_rank_cst[dimen - 1]));
1150
1151   decl = build_decl (FIELD_DECL, get_identifier ("dim"), arraytype);
1152   DECL_CONTEXT (decl) = fat_type;
1153   fieldlist = chainon (fieldlist, decl);
1154
1155   /* Finish off the type.  */
1156   TYPE_FIELDS (fat_type) = fieldlist;
1157
1158   gfc_finish_type (fat_type);
1159
1160   gfc_array_descriptor_base[dimen - 1] = fat_type;
1161   return fat_type;
1162 }
1163
1164 /* Build an array (descriptor) type with given bounds.  */
1165
1166 tree
1167 gfc_get_array_type_bounds (tree etype, int dimen, tree * lbound,
1168                            tree * ubound, int packed)
1169 {
1170   char name[8 + GFC_RANK_DIGITS + GFC_MAX_SYMBOL_LEN];
1171   tree fat_type, base_type, arraytype, lower, upper, stride, tmp;
1172   const char *typename;
1173   int n;
1174
1175   base_type = gfc_get_array_descriptor_base (dimen);
1176   fat_type = build_variant_type_copy (base_type);
1177
1178   tmp = TYPE_NAME (etype);
1179   if (tmp && TREE_CODE (tmp) == TYPE_DECL)
1180     tmp = DECL_NAME (tmp);
1181   if (tmp)
1182     typename = IDENTIFIER_POINTER (tmp);
1183   else
1184     typename = "unknown";
1185   sprintf (name, "array" GFC_RANK_PRINTF_FORMAT "_%.*s", dimen,
1186            GFC_MAX_SYMBOL_LEN, typename);
1187   TYPE_NAME (fat_type) = get_identifier (name);
1188
1189   GFC_DESCRIPTOR_TYPE_P (fat_type) = 1;
1190   TYPE_LANG_SPECIFIC (fat_type) = (struct lang_type *)
1191     ggc_alloc_cleared (sizeof (struct lang_type));
1192
1193   GFC_TYPE_ARRAY_RANK (fat_type) = dimen;
1194   GFC_TYPE_ARRAY_DTYPE (fat_type) = NULL_TREE;
1195
1196   /* Build an array descriptor record type.  */
1197   if (packed != 0)
1198     stride = gfc_index_one_node;
1199   else
1200     stride = NULL_TREE;
1201   for (n = 0; n < dimen; n++)
1202     {
1203       GFC_TYPE_ARRAY_STRIDE (fat_type, n) = stride;
1204
1205       if (lbound)
1206         lower = lbound[n];
1207       else
1208         lower = NULL_TREE;
1209
1210       if (lower != NULL_TREE)
1211         {
1212           if (INTEGER_CST_P (lower))
1213             GFC_TYPE_ARRAY_LBOUND (fat_type, n) = lower;
1214           else
1215             lower = NULL_TREE;
1216         }
1217
1218       upper = ubound[n];
1219       if (upper != NULL_TREE)
1220         {
1221           if (INTEGER_CST_P (upper))
1222             GFC_TYPE_ARRAY_UBOUND (fat_type, n) = upper;
1223           else
1224             upper = NULL_TREE;
1225         }
1226
1227       if (upper != NULL_TREE && lower != NULL_TREE && stride != NULL_TREE)
1228         {
1229           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, upper, lower);
1230           tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type, tmp,
1231                              gfc_index_one_node);
1232           stride =
1233             fold_build2 (MULT_EXPR, gfc_array_index_type, tmp, stride);
1234           /* Check the folding worked.  */
1235           gcc_assert (INTEGER_CST_P (stride));
1236         }
1237       else
1238         stride = NULL_TREE;
1239     }
1240   GFC_TYPE_ARRAY_SIZE (fat_type) = stride;
1241
1242   /* TODO: known offsets for descriptors.  */
1243   GFC_TYPE_ARRAY_OFFSET (fat_type) = NULL_TREE;
1244
1245   /* We define data as an unknown size array. Much better than doing
1246      pointer arithmetic.  */
1247   arraytype =
1248     build_array_type (etype, gfc_array_range_type);
1249   arraytype = build_pointer_type (arraytype);
1250   GFC_TYPE_ARRAY_DATAPTR_TYPE (fat_type) = arraytype;
1251
1252   return fat_type;
1253 }
1254 \f
1255 /* Build a pointer type. This function is called from gfc_sym_type().  */
1256
1257 static tree
1258 gfc_build_pointer_type (gfc_symbol * sym, tree type)
1259 {
1260   /* Array pointer types aren't actually pointers.  */
1261   if (sym->attr.dimension)
1262     return type;
1263   else
1264     return build_pointer_type (type);
1265 }
1266 \f
1267 /* Return the type for a symbol.  Special handling is required for character
1268    types to get the correct level of indirection.
1269    For functions return the return type.
1270    For subroutines return void_type_node.
1271    Calling this multiple times for the same symbol should be avoided,
1272    especially for character and array types.  */
1273
1274 tree
1275 gfc_sym_type (gfc_symbol * sym)
1276 {
1277   tree type;
1278   int byref;
1279
1280   if (sym->attr.flavor == FL_PROCEDURE && !sym->attr.function)
1281     return void_type_node;
1282
1283   if (sym->backend_decl)
1284     {
1285       if (sym->attr.function)
1286         return TREE_TYPE (TREE_TYPE (sym->backend_decl));
1287       else
1288         return TREE_TYPE (sym->backend_decl);
1289     }
1290
1291   type = gfc_typenode_for_spec (&sym->ts);
1292   if (gfc_option.flag_f2c
1293       && sym->attr.function
1294       && sym->ts.type == BT_REAL
1295       && sym->ts.kind == gfc_default_real_kind
1296       && !sym->attr.always_explicit)
1297     {
1298       /* Special case: f2c calling conventions require that (scalar) 
1299          default REAL functions return the C type double instead.  */
1300       sym->ts.kind = gfc_default_double_kind;
1301       type = gfc_typenode_for_spec (&sym->ts);
1302       sym->ts.kind = gfc_default_real_kind;
1303     }
1304
1305   if (sym->attr.dummy && !sym->attr.function)
1306     byref = 1;
1307   else
1308     byref = 0;
1309
1310   if (sym->attr.dimension)
1311     {
1312       if (gfc_is_nodesc_array (sym))
1313         {
1314           /* If this is a character argument of unknown length, just use the
1315              base type.  */
1316           if (sym->ts.type != BT_CHARACTER
1317               || !(sym->attr.dummy || sym->attr.function)
1318               || sym->ts.cl->backend_decl)
1319             {
1320               type = gfc_get_nodesc_array_type (type, sym->as,
1321                                                 byref ? 2 : 3);
1322               byref = 0;
1323             }
1324         }
1325       else
1326         type = gfc_build_array_type (type, sym->as);
1327     }
1328   else
1329     {
1330       if (sym->attr.allocatable || sym->attr.pointer)
1331         type = gfc_build_pointer_type (sym, type);
1332     }
1333
1334   /* We currently pass all parameters by reference.
1335      See f95_get_function_decl.  For dummy function parameters return the
1336      function type.  */
1337   if (byref)
1338     {
1339       /* We must use pointer types for potentially absent variables.  The
1340          optimizers assume a reference type argument is never NULL.  */
1341       if (sym->attr.optional || sym->ns->proc_name->attr.entry_master)
1342         type = build_pointer_type (type);
1343       else
1344         type = build_reference_type (type);
1345     }
1346
1347   return (type);
1348 }
1349 \f
1350 /* Layout and output debug info for a record type.  */
1351
1352 void
1353 gfc_finish_type (tree type)
1354 {
1355   tree decl;
1356
1357   decl = build_decl (TYPE_DECL, NULL_TREE, type);
1358   TYPE_STUB_DECL (type) = decl;
1359   layout_type (type);
1360   rest_of_type_compilation (type, 1);
1361   rest_of_decl_compilation (decl, 1, 0);
1362 }
1363 \f
1364 /* Add a field of given NAME and TYPE to the context of a UNION_TYPE
1365    or RECORD_TYPE pointed to by STYPE.  The new field is chained
1366    to the fieldlist pointed to by FIELDLIST.
1367
1368    Returns a pointer to the new field.  */
1369
1370 tree
1371 gfc_add_field_to_struct (tree *fieldlist, tree context,
1372                          tree name, tree type)
1373 {
1374   tree decl;
1375
1376   decl = build_decl (FIELD_DECL, name, type);
1377
1378   DECL_CONTEXT (decl) = context;
1379   DECL_INITIAL (decl) = 0;
1380   DECL_ALIGN (decl) = 0;
1381   DECL_USER_ALIGN (decl) = 0;
1382   TREE_CHAIN (decl) = NULL_TREE;
1383   *fieldlist = chainon (*fieldlist, decl);
1384
1385   return decl;
1386 }
1387
1388
1389 /* Build a tree node for a derived type.  */
1390
1391 static tree
1392 gfc_get_derived_type (gfc_symbol * derived)
1393 {
1394   tree typenode, field, field_type, fieldlist;
1395   gfc_component *c;
1396
1397   gcc_assert (derived && derived->attr.flavor == FL_DERIVED);
1398
1399   /* derived->backend_decl != 0 means we saw it before, but its
1400      components' backend_decl may have not been built.  */
1401   if (derived->backend_decl)
1402     {
1403       /* Its components' backend_decl have been built.  */
1404       if (TYPE_FIELDS (derived->backend_decl))
1405         return derived->backend_decl;
1406       else
1407         typenode = derived->backend_decl;
1408     }
1409   else
1410     {
1411       /* We see this derived type first time, so build the type node.  */
1412       typenode = make_node (RECORD_TYPE);
1413       TYPE_NAME (typenode) = get_identifier (derived->name);
1414       TYPE_PACKED (typenode) = gfc_option.flag_pack_derived;
1415       derived->backend_decl = typenode;
1416     }
1417
1418   /* Go through the derived type components, building them as
1419      necessary. The reason for doing this now is that it is
1420      possible to recurse back to this derived type through a
1421      pointer component (PR24092). If this happens, the fields
1422      will be built and so we can return the type.  */
1423   for (c = derived->components; c; c = c->next)
1424     {
1425       if (c->ts.type != BT_DERIVED)
1426         continue;
1427
1428       if (!c->pointer || c->ts.derived->backend_decl == NULL)
1429         c->ts.derived->backend_decl = gfc_get_derived_type (c->ts.derived);
1430     }
1431
1432   if (TYPE_FIELDS (derived->backend_decl))
1433     return derived->backend_decl;
1434
1435   /* Build the type member list. Install the newly created RECORD_TYPE
1436      node as DECL_CONTEXT of each FIELD_DECL.  */
1437   fieldlist = NULL_TREE;
1438   for (c = derived->components; c; c = c->next)
1439     {
1440       if (c->ts.type == BT_DERIVED)
1441         field_type = c->ts.derived->backend_decl;
1442       else
1443         {
1444           if (c->ts.type == BT_CHARACTER)
1445             {
1446               /* Evaluate the string length.  */
1447               gfc_conv_const_charlen (c->ts.cl);
1448               gcc_assert (c->ts.cl->backend_decl);
1449             }
1450
1451           field_type = gfc_typenode_for_spec (&c->ts);
1452         }
1453
1454       /* This returns an array descriptor type.  Initialization may be
1455          required.  */
1456       if (c->dimension)
1457         {
1458           if (c->pointer)
1459             {
1460               /* Pointers to arrays aren't actually pointer types.  The
1461                  descriptors are separate, but the data is common.  */
1462               field_type = gfc_build_array_type (field_type, c->as);
1463             }
1464           else
1465             field_type = gfc_get_nodesc_array_type (field_type, c->as, 3);
1466         }
1467       else if (c->pointer)
1468         field_type = build_pointer_type (field_type);
1469
1470       field = gfc_add_field_to_struct (&fieldlist, typenode,
1471                                        get_identifier (c->name),
1472                                        field_type);
1473
1474       DECL_PACKED (field) |= TYPE_PACKED (typenode);
1475
1476       gcc_assert (field);
1477       if (!c->backend_decl)
1478         c->backend_decl = field;
1479     }
1480
1481   /* Now we have the final fieldlist.  Record it, then lay out the
1482      derived type, including the fields.  */
1483   TYPE_FIELDS (typenode) = fieldlist;
1484
1485   gfc_finish_type (typenode);
1486
1487   derived->backend_decl = typenode;
1488
1489   return typenode;
1490 }
1491 \f
1492 int
1493 gfc_return_by_reference (gfc_symbol * sym)
1494 {
1495   if (!sym->attr.function)
1496     return 0;
1497
1498   if (sym->attr.dimension)
1499     return 1;
1500
1501   if (sym->ts.type == BT_CHARACTER)
1502     return 1;
1503
1504   /* Possibly return complex numbers by reference for g77 compatibility.
1505      We don't do this for calls to intrinsics (as the library uses the
1506      -fno-f2c calling convention), nor for calls to functions which always
1507      require an explicit interface, as no compatibility problems can
1508      arise there.  */
1509   if (gfc_option.flag_f2c
1510       && sym->ts.type == BT_COMPLEX
1511       && !sym->attr.intrinsic && !sym->attr.always_explicit)
1512     return 1;
1513   
1514   return 0;
1515 }
1516 \f
1517 static tree
1518 gfc_get_mixed_entry_union (gfc_namespace *ns)
1519 {
1520   tree type;
1521   tree decl;
1522   tree fieldlist;
1523   char name[GFC_MAX_SYMBOL_LEN + 1];
1524   gfc_entry_list *el, *el2;
1525
1526   gcc_assert (ns->proc_name->attr.mixed_entry_master);
1527   gcc_assert (memcmp (ns->proc_name->name, "master.", 7) == 0);
1528
1529   snprintf (name, GFC_MAX_SYMBOL_LEN, "munion.%s", ns->proc_name->name + 7);
1530
1531   /* Build the type node.  */
1532   type = make_node (UNION_TYPE);
1533
1534   TYPE_NAME (type) = get_identifier (name);
1535   fieldlist = NULL;
1536
1537   for (el = ns->entries; el; el = el->next)
1538     {
1539       /* Search for duplicates.  */
1540       for (el2 = ns->entries; el2 != el; el2 = el2->next)
1541         if (el2->sym->result == el->sym->result)
1542           break;
1543
1544       if (el == el2)
1545         {
1546           decl = build_decl (FIELD_DECL,
1547                              get_identifier (el->sym->result->name),
1548                              gfc_sym_type (el->sym->result));
1549           DECL_CONTEXT (decl) = type;
1550           fieldlist = chainon (fieldlist, decl);
1551         }
1552     }
1553
1554   /* Finish off the type.  */
1555   TYPE_FIELDS (type) = fieldlist;
1556
1557   gfc_finish_type (type);
1558   return type;
1559 }
1560 \f
1561 tree
1562 gfc_get_function_type (gfc_symbol * sym)
1563 {
1564   tree type;
1565   tree typelist;
1566   gfc_formal_arglist *f;
1567   gfc_symbol *arg;
1568   int nstr;
1569   int alternate_return;
1570
1571   /* Make sure this symbol is a function or a subroutine.  */
1572   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1573
1574   if (sym->backend_decl)
1575     return TREE_TYPE (sym->backend_decl);
1576
1577   nstr = 0;
1578   alternate_return = 0;
1579   typelist = NULL_TREE;
1580
1581   if (sym->attr.entry_master)
1582     {
1583       /* Additional parameter for selecting an entry point.  */
1584       typelist = gfc_chainon_list (typelist, gfc_array_index_type);
1585     }
1586
1587   /* Some functions we use an extra parameter for the return value.  */
1588   if (gfc_return_by_reference (sym))
1589     {
1590       if (sym->result)
1591         arg = sym->result;
1592       else
1593         arg = sym;
1594
1595       if (arg->ts.type == BT_CHARACTER)
1596         gfc_conv_const_charlen (arg->ts.cl);
1597
1598       type = gfc_sym_type (arg);
1599       if (arg->ts.type == BT_COMPLEX
1600           || arg->attr.dimension
1601           || arg->ts.type == BT_CHARACTER)
1602         type = build_reference_type (type);
1603
1604       typelist = gfc_chainon_list (typelist, type);
1605       if (arg->ts.type == BT_CHARACTER)
1606         typelist = gfc_chainon_list (typelist, gfc_charlen_type_node);
1607     }
1608
1609   /* Build the argument types for the function.  */
1610   for (f = sym->formal; f; f = f->next)
1611     {
1612       arg = f->sym;
1613       if (arg)
1614         {
1615           /* Evaluate constant character lengths here so that they can be
1616              included in the type.  */
1617           if (arg->ts.type == BT_CHARACTER)
1618             gfc_conv_const_charlen (arg->ts.cl);
1619
1620           if (arg->attr.flavor == FL_PROCEDURE)
1621             {
1622               type = gfc_get_function_type (arg);
1623               type = build_pointer_type (type);
1624             }
1625           else
1626             type = gfc_sym_type (arg);
1627
1628           /* Parameter Passing Convention
1629
1630              We currently pass all parameters by reference.
1631              Parameters with INTENT(IN) could be passed by value.
1632              The problem arises if a function is called via an implicit
1633              prototype. In this situation the INTENT is not known.
1634              For this reason all parameters to global functions must be
1635              passed by reference.  Passing by value would potentially
1636              generate bad code.  Worse there would be no way of telling that
1637              this code was bad, except that it would give incorrect results.
1638
1639              Contained procedures could pass by value as these are never
1640              used without an explicit interface, and connot be passed as
1641              actual parameters for a dummy procedure.  */
1642           if (arg->ts.type == BT_CHARACTER)
1643             nstr++;
1644           typelist = gfc_chainon_list (typelist, type);
1645         }
1646       else
1647         {
1648           if (sym->attr.subroutine)
1649             alternate_return = 1;
1650         }
1651     }
1652
1653   /* Add hidden string length parameters.  */
1654   while (nstr--)
1655     typelist = gfc_chainon_list (typelist, gfc_charlen_type_node);
1656
1657   typelist = gfc_chainon_list (typelist, void_type_node);
1658
1659   if (alternate_return)
1660     type = integer_type_node;
1661   else if (!sym->attr.function || gfc_return_by_reference (sym))
1662     type = void_type_node;
1663   else if (sym->attr.mixed_entry_master)
1664     type = gfc_get_mixed_entry_union (sym->ns);
1665   else
1666     type = gfc_sym_type (sym);
1667
1668   type = build_function_type (type, typelist);
1669
1670   return type;
1671 }
1672 \f
1673 /* Language hooks for middle-end access to type nodes.  */
1674
1675 /* Return an integer type with BITS bits of precision,
1676    that is unsigned if UNSIGNEDP is nonzero, otherwise signed.  */
1677
1678 tree
1679 gfc_type_for_size (unsigned bits, int unsignedp)
1680 {
1681   if (!unsignedp)
1682     {
1683       int i;
1684       for (i = 0; i <= MAX_INT_KINDS; ++i)
1685         {
1686           tree type = gfc_integer_types[i];
1687           if (type && bits == TYPE_PRECISION (type))
1688             return type;
1689         }
1690     }
1691   else
1692     {
1693       if (bits == TYPE_PRECISION (unsigned_intQI_type_node))
1694         return unsigned_intQI_type_node;
1695       if (bits == TYPE_PRECISION (unsigned_intHI_type_node))
1696         return unsigned_intHI_type_node;
1697       if (bits == TYPE_PRECISION (unsigned_intSI_type_node))
1698         return unsigned_intSI_type_node;
1699       if (bits == TYPE_PRECISION (unsigned_intDI_type_node))
1700         return unsigned_intDI_type_node;
1701       if (bits == TYPE_PRECISION (unsigned_intTI_type_node))
1702         return unsigned_intTI_type_node;
1703     }
1704
1705   return NULL_TREE;
1706 }
1707
1708 /* Return a data type that has machine mode MODE.  If the mode is an
1709    integer, then UNSIGNEDP selects between signed and unsigned types.  */
1710
1711 tree
1712 gfc_type_for_mode (enum machine_mode mode, int unsignedp)
1713 {
1714   int i;
1715   tree *base;
1716
1717   if (GET_MODE_CLASS (mode) == MODE_FLOAT)
1718     base = gfc_real_types;
1719   else if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
1720     base = gfc_complex_types;
1721   else if (SCALAR_INT_MODE_P (mode))
1722     return gfc_type_for_size (GET_MODE_PRECISION (mode), unsignedp);
1723   else if (VECTOR_MODE_P (mode))
1724     {
1725       enum machine_mode inner_mode = GET_MODE_INNER (mode);
1726       tree inner_type = gfc_type_for_mode (inner_mode, unsignedp);
1727       if (inner_type != NULL_TREE)
1728         return build_vector_type_for_mode (inner_type, mode);
1729       return NULL_TREE;
1730     }
1731   else
1732     return NULL_TREE;
1733
1734   for (i = 0; i <= MAX_REAL_KINDS; ++i)
1735     {
1736       tree type = base[i];
1737       if (type && mode == TYPE_MODE (type))
1738         return type;
1739     }
1740
1741   return NULL_TREE;
1742 }
1743
1744 /* Return a type the same as TYPE except unsigned or
1745    signed according to UNSIGNEDP.  */
1746
1747 tree
1748 gfc_signed_or_unsigned_type (int unsignedp, tree type)
1749 {
1750   if (TREE_CODE (type) != INTEGER_TYPE || TYPE_UNSIGNED (type) == unsignedp)
1751     return type;
1752   else
1753     return gfc_type_for_size (TYPE_PRECISION (type), unsignedp);
1754 }
1755
1756 /* Return an unsigned type the same as TYPE in other respects.  */
1757
1758 tree
1759 gfc_unsigned_type (tree type)
1760 {
1761   return gfc_signed_or_unsigned_type (1, type);
1762 }
1763
1764 /* Return a signed type the same as TYPE in other respects.  */
1765
1766 tree
1767 gfc_signed_type (tree type)
1768 {
1769   return gfc_signed_or_unsigned_type (0, type);
1770 }
1771
1772 #include "gt-fortran-trans-types.h"