OSDN Git Service

2008-08-18 Manuel Lopez-Ibanez <manu@gcc.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, 2006, 2007, 2008
3    Free Software Foundation, Inc.
4    Contributed by Paul Brook <paul@nowt.org>
5    and Steven Bosscher <s.bosscher@student.tudelft.nl>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
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 "langhooks.h"
30 #include "tm.h"
31 #include "target.h"
32 #include "ggc.h"
33 #include "toplev.h"
34 #include "gfortran.h"
35 #include "trans.h"
36 #include "trans-types.h"
37 #include "trans-const.h"
38 #include "real.h"
39 #include "flags.h"
40 #include "dwarf2out.h"
41 \f
42
43 #if (GFC_MAX_DIMENSIONS < 10)
44 #define GFC_RANK_DIGITS 1
45 #define GFC_RANK_PRINTF_FORMAT "%01d"
46 #elif (GFC_MAX_DIMENSIONS < 100)
47 #define GFC_RANK_DIGITS 2
48 #define GFC_RANK_PRINTF_FORMAT "%02d"
49 #else
50 #error If you really need >99 dimensions, continue the sequence above...
51 #endif
52
53 /* array of structs so we don't have to worry about xmalloc or free */
54 CInteropKind_t c_interop_kinds_table[ISOCBINDING_NUMBER];
55
56 static tree gfc_get_derived_type (gfc_symbol * derived);
57
58 tree gfc_array_index_type;
59 tree gfc_array_range_type;
60 tree gfc_character1_type_node;
61 tree pvoid_type_node;
62 tree ppvoid_type_node;
63 tree pchar_type_node;
64 tree pfunc_type_node;
65
66 tree gfc_charlen_type_node;
67
68 static GTY(()) tree gfc_desc_dim_type;
69 static GTY(()) tree gfc_max_array_element_size;
70 static GTY(()) tree gfc_array_descriptor_base[GFC_MAX_DIMENSIONS];
71
72 /* Arrays for all integral and real kinds.  We'll fill this in at runtime
73    after the target has a chance to process command-line options.  */
74
75 #define MAX_INT_KINDS 5
76 gfc_integer_info gfc_integer_kinds[MAX_INT_KINDS + 1];
77 gfc_logical_info gfc_logical_kinds[MAX_INT_KINDS + 1];
78 static GTY(()) tree gfc_integer_types[MAX_INT_KINDS + 1];
79 static GTY(()) tree gfc_logical_types[MAX_INT_KINDS + 1];
80
81 #define MAX_REAL_KINDS 5
82 gfc_real_info gfc_real_kinds[MAX_REAL_KINDS + 1];
83 static GTY(()) tree gfc_real_types[MAX_REAL_KINDS + 1];
84 static GTY(()) tree gfc_complex_types[MAX_REAL_KINDS + 1];
85
86 #define MAX_CHARACTER_KINDS 2
87 gfc_character_info gfc_character_kinds[MAX_CHARACTER_KINDS + 1];
88 static GTY(()) tree gfc_character_types[MAX_CHARACTER_KINDS + 1];
89 static GTY(()) tree gfc_pcharacter_types[MAX_CHARACTER_KINDS + 1];
90
91
92 /* The integer kind to use for array indices.  This will be set to the
93    proper value based on target information from the backend.  */
94
95 int gfc_index_integer_kind;
96
97 /* The default kinds of the various types.  */
98
99 int gfc_default_integer_kind;
100 int gfc_max_integer_kind;
101 int gfc_default_real_kind;
102 int gfc_default_double_kind;
103 int gfc_default_character_kind;
104 int gfc_default_logical_kind;
105 int gfc_default_complex_kind;
106 int gfc_c_int_kind;
107
108 /* The kind size used for record offsets. If the target system supports
109    kind=8, this will be set to 8, otherwise it is set to 4.  */
110 int gfc_intio_kind; 
111
112 /* The integer kind used to store character lengths.  */
113 int gfc_charlen_int_kind;
114
115 /* The size of the numeric storage unit and character storage unit.  */
116 int gfc_numeric_storage_size;
117 int gfc_character_storage_size;
118
119
120 /* Validate that the f90_type of the given gfc_typespec is valid for
121    the type it represents.  The f90_type represents the Fortran types
122    this C kind can be used with.  For example, c_int has a f90_type of
123    BT_INTEGER and c_float has a f90_type of BT_REAL.  Returns FAILURE
124    if a mismatch occurs between ts->f90_type and ts->type; SUCCESS if
125    they match.  */
126
127 gfc_try
128 gfc_validate_c_kind (gfc_typespec *ts)
129 {
130    return ((ts->type == ts->f90_type) ? SUCCESS : FAILURE);
131 }
132
133
134 gfc_try
135 gfc_check_any_c_kind (gfc_typespec *ts)
136 {
137   int i;
138   
139   for (i = 0; i < ISOCBINDING_NUMBER; i++)
140     {
141       /* Check for any C interoperable kind for the given type/kind in ts.
142          This can be used after verify_c_interop to make sure that the
143          Fortran kind being used exists in at least some form for C.  */
144       if (c_interop_kinds_table[i].f90_type == ts->type &&
145           c_interop_kinds_table[i].value == ts->kind)
146         return SUCCESS;
147     }
148
149   return FAILURE;
150 }
151
152
153 static int
154 get_real_kind_from_node (tree type)
155 {
156   int i;
157
158   for (i = 0; gfc_real_kinds[i].kind != 0; i++)
159     if (gfc_real_kinds[i].mode_precision == TYPE_PRECISION (type))
160       return gfc_real_kinds[i].kind;
161
162   return -4;
163 }
164
165 static int
166 get_int_kind_from_node (tree type)
167 {
168   int i;
169
170   if (!type)
171     return -2;
172
173   for (i = 0; gfc_integer_kinds[i].kind != 0; i++)
174     if (gfc_integer_kinds[i].bit_size == TYPE_PRECISION (type))
175       return gfc_integer_kinds[i].kind;
176
177   return -1;
178 }
179
180 static int
181 get_int_kind_from_width (int size)
182 {
183   int i;
184
185   for (i = 0; gfc_integer_kinds[i].kind != 0; i++)
186     if (gfc_integer_kinds[i].bit_size == size)
187       return gfc_integer_kinds[i].kind;
188
189   return -2;
190 }
191
192 static int
193 get_int_kind_from_minimal_width (int size)
194 {
195   int i;
196
197   for (i = 0; gfc_integer_kinds[i].kind != 0; i++)
198     if (gfc_integer_kinds[i].bit_size >= size)
199       return gfc_integer_kinds[i].kind;
200
201   return -2;
202 }
203
204
205 /* Generate the CInteropKind_t objects for the C interoperable
206    kinds.  */
207
208 static
209 void init_c_interop_kinds (void)
210 {
211   int i;
212   tree intmax_type_node = INT_TYPE_SIZE == LONG_LONG_TYPE_SIZE ?
213                           integer_type_node :
214                           (LONG_TYPE_SIZE == LONG_LONG_TYPE_SIZE ?
215                            long_integer_type_node :
216                            long_long_integer_type_node);
217
218   /* init all pointers in the list to NULL */
219   for (i = 0; i < ISOCBINDING_NUMBER; i++)
220     {
221       /* Initialize the name and value fields.  */
222       c_interop_kinds_table[i].name[0] = '\0';
223       c_interop_kinds_table[i].value = -100;
224       c_interop_kinds_table[i].f90_type = BT_UNKNOWN;
225     }
226
227 #define NAMED_INTCST(a,b,c,d) \
228   strncpy (c_interop_kinds_table[a].name, b, strlen(b) + 1); \
229   c_interop_kinds_table[a].f90_type = BT_INTEGER; \
230   c_interop_kinds_table[a].value = c;
231 #define NAMED_REALCST(a,b,c) \
232   strncpy (c_interop_kinds_table[a].name, b, strlen(b) + 1); \
233   c_interop_kinds_table[a].f90_type = BT_REAL; \
234   c_interop_kinds_table[a].value = c;
235 #define NAMED_CMPXCST(a,b,c) \
236   strncpy (c_interop_kinds_table[a].name, b, strlen(b) + 1); \
237   c_interop_kinds_table[a].f90_type = BT_COMPLEX; \
238   c_interop_kinds_table[a].value = c;
239 #define NAMED_LOGCST(a,b,c) \
240   strncpy (c_interop_kinds_table[a].name, b, strlen(b) + 1); \
241   c_interop_kinds_table[a].f90_type = BT_LOGICAL; \
242   c_interop_kinds_table[a].value = c;
243 #define NAMED_CHARKNDCST(a,b,c) \
244   strncpy (c_interop_kinds_table[a].name, b, strlen(b) + 1); \
245   c_interop_kinds_table[a].f90_type = BT_CHARACTER; \
246   c_interop_kinds_table[a].value = c;
247 #define NAMED_CHARCST(a,b,c) \
248   strncpy (c_interop_kinds_table[a].name, b, strlen(b) + 1); \
249   c_interop_kinds_table[a].f90_type = BT_CHARACTER; \
250   c_interop_kinds_table[a].value = c;
251 #define DERIVED_TYPE(a,b,c) \
252   strncpy (c_interop_kinds_table[a].name, b, strlen(b) + 1); \
253   c_interop_kinds_table[a].f90_type = BT_DERIVED; \
254   c_interop_kinds_table[a].value = c;
255 #define PROCEDURE(a,b) \
256   strncpy (c_interop_kinds_table[a].name, b, strlen(b) + 1); \
257   c_interop_kinds_table[a].f90_type = BT_PROCEDURE; \
258   c_interop_kinds_table[a].value = 0;
259 #include "iso-c-binding.def"
260 }
261
262
263 /* Query the target to determine which machine modes are available for
264    computation.  Choose KIND numbers for them.  */
265
266 void
267 gfc_init_kinds (void)
268 {
269   enum machine_mode mode;
270   int i_index, r_index, kind;
271   bool saw_i4 = false, saw_i8 = false;
272   bool saw_r4 = false, saw_r8 = false, saw_r16 = false;
273
274   for (i_index = 0, mode = MIN_MODE_INT; mode <= MAX_MODE_INT; mode++)
275     {
276       int kind, bitsize;
277
278       if (!targetm.scalar_mode_supported_p (mode))
279         continue;
280
281       /* The middle end doesn't support constants larger than 2*HWI.
282          Perhaps the target hook shouldn't have accepted these either,
283          but just to be safe...  */
284       bitsize = GET_MODE_BITSIZE (mode);
285       if (bitsize > 2*HOST_BITS_PER_WIDE_INT)
286         continue;
287
288       gcc_assert (i_index != MAX_INT_KINDS);
289
290       /* Let the kind equal the bit size divided by 8.  This insulates the
291          programmer from the underlying byte size.  */
292       kind = bitsize / 8;
293
294       if (kind == 4)
295         saw_i4 = true;
296       if (kind == 8)
297         saw_i8 = true;
298
299       gfc_integer_kinds[i_index].kind = kind;
300       gfc_integer_kinds[i_index].radix = 2;
301       gfc_integer_kinds[i_index].digits = bitsize - 1;
302       gfc_integer_kinds[i_index].bit_size = bitsize;
303
304       gfc_logical_kinds[i_index].kind = kind;
305       gfc_logical_kinds[i_index].bit_size = bitsize;
306
307       i_index += 1;
308     }
309
310   /* Set the kind used to match GFC_INT_IO in libgfortran.  This is 
311      used for large file access.  */
312
313   if (saw_i8)
314     gfc_intio_kind = 8;
315   else
316     gfc_intio_kind = 4;
317
318   /* If we do not at least have kind = 4, everything is pointless.  */  
319   gcc_assert(saw_i4);  
320
321   /* Set the maximum integer kind.  Used with at least BOZ constants.  */
322   gfc_max_integer_kind = gfc_integer_kinds[i_index - 1].kind;
323
324   for (r_index = 0, mode = MIN_MODE_FLOAT; mode <= MAX_MODE_FLOAT; mode++)
325     {
326       const struct real_format *fmt = REAL_MODE_FORMAT (mode);
327       int kind;
328
329       if (fmt == NULL)
330         continue;
331       if (!targetm.scalar_mode_supported_p (mode))
332         continue;
333
334       /* Only let float/double/long double go through because the fortran
335          library assumes these are the only floating point types.  */
336
337       if (mode != TYPE_MODE (float_type_node)
338           && (mode != TYPE_MODE (double_type_node))
339           && (mode != TYPE_MODE (long_double_type_node)))
340         continue;
341
342       /* Let the kind equal the precision divided by 8, rounding up.  Again,
343          this insulates the programmer from the underlying byte size.
344
345          Also, it effectively deals with IEEE extended formats.  There, the
346          total size of the type may equal 16, but it's got 6 bytes of padding
347          and the increased size can get in the way of a real IEEE quad format
348          which may also be supported by the target.
349
350          We round up so as to handle IA-64 __floatreg (RFmode), which is an
351          82 bit type.  Not to be confused with __float80 (XFmode), which is
352          an 80 bit type also supported by IA-64.  So XFmode should come out
353          to be kind=10, and RFmode should come out to be kind=11.  Egads.  */
354
355       kind = (GET_MODE_PRECISION (mode) + 7) / 8;
356
357       if (kind == 4)
358         saw_r4 = true;
359       if (kind == 8)
360         saw_r8 = true;
361       if (kind == 16)
362         saw_r16 = true;
363
364       /* Careful we don't stumble a weird internal mode.  */
365       gcc_assert (r_index <= 0 || gfc_real_kinds[r_index-1].kind != kind);
366       /* Or have too many modes for the allocated space.  */
367       gcc_assert (r_index != MAX_REAL_KINDS);
368
369       gfc_real_kinds[r_index].kind = kind;
370       gfc_real_kinds[r_index].radix = fmt->b;
371       gfc_real_kinds[r_index].digits = fmt->p;
372       gfc_real_kinds[r_index].min_exponent = fmt->emin;
373       gfc_real_kinds[r_index].max_exponent = fmt->emax;
374       if (fmt->pnan < fmt->p)
375         /* This is an IBM extended double format (or the MIPS variant)
376            made up of two IEEE doubles.  The value of the long double is
377            the sum of the values of the two parts.  The most significant
378            part is required to be the value of the long double rounded
379            to the nearest double.  If we use emax of 1024 then we can't
380            represent huge(x) = (1 - b**(-p)) * b**(emax-1) * b, because
381            rounding will make the most significant part overflow.  */
382         gfc_real_kinds[r_index].max_exponent = fmt->emax - 1;
383       gfc_real_kinds[r_index].mode_precision = GET_MODE_PRECISION (mode);
384       r_index += 1;
385     }
386
387   /* Choose the default integer kind.  We choose 4 unless the user
388      directs us otherwise.  */
389   if (gfc_option.flag_default_integer)
390     {
391       if (!saw_i8)
392         fatal_error ("integer kind=8 not available for -fdefault-integer-8 option");
393       gfc_default_integer_kind = 8;
394
395       /* Even if the user specified that the default integer kind be 8,
396          the numeric storage size isn't 64.  In this case, a warning will
397          be issued when NUMERIC_STORAGE_SIZE is used.  */
398       gfc_numeric_storage_size = 4 * 8;
399     }
400   else if (saw_i4)
401     {
402       gfc_default_integer_kind = 4;
403       gfc_numeric_storage_size = 4 * 8;
404     }
405   else
406     {
407       gfc_default_integer_kind = gfc_integer_kinds[i_index - 1].kind;
408       gfc_numeric_storage_size = gfc_integer_kinds[i_index - 1].bit_size;
409     }
410
411   /* Choose the default real kind.  Again, we choose 4 when possible.  */
412   if (gfc_option.flag_default_real)
413     {
414       if (!saw_r8)
415         fatal_error ("real kind=8 not available for -fdefault-real-8 option");
416       gfc_default_real_kind = 8;
417     }
418   else if (saw_r4)
419     gfc_default_real_kind = 4;
420   else
421     gfc_default_real_kind = gfc_real_kinds[0].kind;
422
423   /* Choose the default double kind.  If -fdefault-real and -fdefault-double 
424      are specified, we use kind=8, if it's available.  If -fdefault-real is
425      specified without -fdefault-double, we use kind=16, if it's available.
426      Otherwise we do not change anything.  */
427   if (gfc_option.flag_default_double && !gfc_option.flag_default_real)
428     fatal_error ("Use of -fdefault-double-8 requires -fdefault-real-8");
429
430   if (gfc_option.flag_default_real && gfc_option.flag_default_double && saw_r8)
431     gfc_default_double_kind = 8;
432   else if (gfc_option.flag_default_real && saw_r16)
433     gfc_default_double_kind = 16;
434   else if (saw_r4 && saw_r8)
435     gfc_default_double_kind = 8;
436   else
437     {
438       /* F95 14.6.3.1: A nonpointer scalar object of type double precision
439          real ... occupies two contiguous numeric storage units.
440
441          Therefore we must be supplied a kind twice as large as we chose
442          for single precision.  There are loopholes, in that double
443          precision must *occupy* two storage units, though it doesn't have
444          to *use* two storage units.  Which means that you can make this
445          kind artificially wide by padding it.  But at present there are
446          no GCC targets for which a two-word type does not exist, so we
447          just let gfc_validate_kind abort and tell us if something breaks.  */
448
449       gfc_default_double_kind
450         = gfc_validate_kind (BT_REAL, gfc_default_real_kind * 2, false);
451     }
452
453   /* The default logical kind is constrained to be the same as the
454      default integer kind.  Similarly with complex and real.  */
455   gfc_default_logical_kind = gfc_default_integer_kind;
456   gfc_default_complex_kind = gfc_default_real_kind;
457
458   /* We only have two character kinds: ASCII and UCS-4.
459      ASCII corresponds to a 8-bit integer type, if one is available.
460      UCS-4 corresponds to a 32-bit integer type, if one is available. */
461   i_index = 0;
462   if ((kind = get_int_kind_from_width (8)) > 0)
463     {
464       gfc_character_kinds[i_index].kind = kind;
465       gfc_character_kinds[i_index].bit_size = 8;
466       gfc_character_kinds[i_index].name = "ascii";
467       i_index++;
468     }
469   if ((kind = get_int_kind_from_width (32)) > 0)
470     {
471       gfc_character_kinds[i_index].kind = kind;
472       gfc_character_kinds[i_index].bit_size = 32;
473       gfc_character_kinds[i_index].name = "iso_10646";
474       i_index++;
475     }
476
477   /* Choose the smallest integer kind for our default character.  */
478   gfc_default_character_kind = gfc_character_kinds[0].kind;
479   gfc_character_storage_size = gfc_default_character_kind * 8;
480
481   /* Choose the integer kind the same size as "void*" for our index kind.  */
482   gfc_index_integer_kind = POINTER_SIZE / 8;
483   /* Pick a kind the same size as the C "int" type.  */
484   gfc_c_int_kind = INT_TYPE_SIZE / 8;
485
486   /* initialize the C interoperable kinds  */
487   init_c_interop_kinds();
488 }
489
490 /* Make sure that a valid kind is present.  Returns an index into the
491    associated kinds array, -1 if the kind is not present.  */
492
493 static int
494 validate_integer (int kind)
495 {
496   int i;
497
498   for (i = 0; gfc_integer_kinds[i].kind != 0; i++)
499     if (gfc_integer_kinds[i].kind == kind)
500       return i;
501
502   return -1;
503 }
504
505 static int
506 validate_real (int kind)
507 {
508   int i;
509
510   for (i = 0; gfc_real_kinds[i].kind != 0; i++)
511     if (gfc_real_kinds[i].kind == kind)
512       return i;
513
514   return -1;
515 }
516
517 static int
518 validate_logical (int kind)
519 {
520   int i;
521
522   for (i = 0; gfc_logical_kinds[i].kind; i++)
523     if (gfc_logical_kinds[i].kind == kind)
524       return i;
525
526   return -1;
527 }
528
529 static int
530 validate_character (int kind)
531 {
532   int i;
533
534   for (i = 0; gfc_character_kinds[i].kind; i++)
535     if (gfc_character_kinds[i].kind == kind)
536       return i;
537
538   return -1;
539 }
540
541 /* Validate a kind given a basic type.  The return value is the same
542    for the child functions, with -1 indicating nonexistence of the
543    type.  If MAY_FAIL is false, then -1 is never returned, and we ICE.  */
544
545 int
546 gfc_validate_kind (bt type, int kind, bool may_fail)
547 {
548   int rc;
549
550   switch (type)
551     {
552     case BT_REAL:               /* Fall through */
553     case BT_COMPLEX:
554       rc = validate_real (kind);
555       break;
556     case BT_INTEGER:
557       rc = validate_integer (kind);
558       break;
559     case BT_LOGICAL:
560       rc = validate_logical (kind);
561       break;
562     case BT_CHARACTER:
563       rc = validate_character (kind);
564       break;
565
566     default:
567       gfc_internal_error ("gfc_validate_kind(): Got bad type");
568     }
569
570   if (rc < 0 && !may_fail)
571     gfc_internal_error ("gfc_validate_kind(): Got bad kind");
572
573   return rc;
574 }
575
576
577 /* Four subroutines of gfc_init_types.  Create type nodes for the given kind.
578    Reuse common type nodes where possible.  Recognize if the kind matches up
579    with a C type.  This will be used later in determining which routines may
580    be scarfed from libm.  */
581
582 static tree
583 gfc_build_int_type (gfc_integer_info *info)
584 {
585   int mode_precision = info->bit_size;
586
587   if (mode_precision == CHAR_TYPE_SIZE)
588     info->c_char = 1;
589   if (mode_precision == SHORT_TYPE_SIZE)
590     info->c_short = 1;
591   if (mode_precision == INT_TYPE_SIZE)
592     info->c_int = 1;
593   if (mode_precision == LONG_TYPE_SIZE)
594     info->c_long = 1;
595   if (mode_precision == LONG_LONG_TYPE_SIZE)
596     info->c_long_long = 1;
597
598   if (TYPE_PRECISION (intQI_type_node) == mode_precision)
599     return intQI_type_node;
600   if (TYPE_PRECISION (intHI_type_node) == mode_precision)
601     return intHI_type_node;
602   if (TYPE_PRECISION (intSI_type_node) == mode_precision)
603     return intSI_type_node;
604   if (TYPE_PRECISION (intDI_type_node) == mode_precision)
605     return intDI_type_node;
606   if (TYPE_PRECISION (intTI_type_node) == mode_precision)
607     return intTI_type_node;
608
609   return make_signed_type (mode_precision);
610 }
611
612 static tree
613 gfc_build_uint_type (int size)
614 {
615   if (size == CHAR_TYPE_SIZE)
616     return unsigned_char_type_node;
617   if (size == SHORT_TYPE_SIZE)
618     return short_unsigned_type_node;
619   if (size == INT_TYPE_SIZE)
620     return unsigned_type_node;
621   if (size == LONG_TYPE_SIZE)
622     return long_unsigned_type_node;
623   if (size == LONG_LONG_TYPE_SIZE)
624     return long_long_unsigned_type_node;
625
626   return make_unsigned_type (size);
627 }
628
629
630 static tree
631 gfc_build_real_type (gfc_real_info *info)
632 {
633   int mode_precision = info->mode_precision;
634   tree new_type;
635
636   if (mode_precision == FLOAT_TYPE_SIZE)
637     info->c_float = 1;
638   if (mode_precision == DOUBLE_TYPE_SIZE)
639     info->c_double = 1;
640   if (mode_precision == LONG_DOUBLE_TYPE_SIZE)
641     info->c_long_double = 1;
642
643   if (TYPE_PRECISION (float_type_node) == mode_precision)
644     return float_type_node;
645   if (TYPE_PRECISION (double_type_node) == mode_precision)
646     return double_type_node;
647   if (TYPE_PRECISION (long_double_type_node) == mode_precision)
648     return long_double_type_node;
649
650   new_type = make_node (REAL_TYPE);
651   TYPE_PRECISION (new_type) = mode_precision;
652   layout_type (new_type);
653   return new_type;
654 }
655
656 static tree
657 gfc_build_complex_type (tree scalar_type)
658 {
659   tree new_type;
660
661   if (scalar_type == NULL)
662     return NULL;
663   if (scalar_type == float_type_node)
664     return complex_float_type_node;
665   if (scalar_type == double_type_node)
666     return complex_double_type_node;
667   if (scalar_type == long_double_type_node)
668     return complex_long_double_type_node;
669
670   new_type = make_node (COMPLEX_TYPE);
671   TREE_TYPE (new_type) = scalar_type;
672   layout_type (new_type);
673   return new_type;
674 }
675
676 static tree
677 gfc_build_logical_type (gfc_logical_info *info)
678 {
679   int bit_size = info->bit_size;
680   tree new_type;
681
682   if (bit_size == BOOL_TYPE_SIZE)
683     {
684       info->c_bool = 1;
685       return boolean_type_node;
686     }
687
688   new_type = make_unsigned_type (bit_size);
689   TREE_SET_CODE (new_type, BOOLEAN_TYPE);
690   TYPE_MAX_VALUE (new_type) = build_int_cst (new_type, 1);
691   TYPE_PRECISION (new_type) = 1;
692
693   return new_type;
694 }
695
696 #if 0
697 /* Return the bit size of the C "size_t".  */
698
699 static unsigned int
700 c_size_t_size (void)
701 {
702 #ifdef SIZE_TYPE  
703   if (strcmp (SIZE_TYPE, "unsigned int") == 0)
704     return INT_TYPE_SIZE;
705   if (strcmp (SIZE_TYPE, "long unsigned int") == 0)
706     return LONG_TYPE_SIZE;
707   if (strcmp (SIZE_TYPE, "short unsigned int") == 0)
708     return SHORT_TYPE_SIZE;
709   gcc_unreachable ();
710 #else
711   return LONG_TYPE_SIZE;
712 #endif
713 }
714 #endif
715
716 /* Create the backend type nodes. We map them to their
717    equivalent C type, at least for now.  We also give
718    names to the types here, and we push them in the
719    global binding level context.*/
720
721 void
722 gfc_init_types (void)
723 {
724   char name_buf[18];
725   int index;
726   tree type;
727   unsigned n;
728   unsigned HOST_WIDE_INT hi;
729   unsigned HOST_WIDE_INT lo;
730
731   /* Create and name the types.  */
732 #define PUSH_TYPE(name, node) \
733   pushdecl (build_decl (TYPE_DECL, get_identifier (name), node))
734
735   for (index = 0; gfc_integer_kinds[index].kind != 0; ++index)
736     {
737       type = gfc_build_int_type (&gfc_integer_kinds[index]);
738       gfc_integer_types[index] = type;
739       snprintf (name_buf, sizeof(name_buf), "integer(kind=%d)",
740                 gfc_integer_kinds[index].kind);
741       PUSH_TYPE (name_buf, type);
742     }
743
744   for (index = 0; gfc_logical_kinds[index].kind != 0; ++index)
745     {
746       type = gfc_build_logical_type (&gfc_logical_kinds[index]);
747       gfc_logical_types[index] = type;
748       snprintf (name_buf, sizeof(name_buf), "logical(kind=%d)",
749                 gfc_logical_kinds[index].kind);
750       PUSH_TYPE (name_buf, type);
751     }
752
753   for (index = 0; gfc_real_kinds[index].kind != 0; index++)
754     {
755       type = gfc_build_real_type (&gfc_real_kinds[index]);
756       gfc_real_types[index] = type;
757       snprintf (name_buf, sizeof(name_buf), "real(kind=%d)",
758                 gfc_real_kinds[index].kind);
759       PUSH_TYPE (name_buf, type);
760
761       type = gfc_build_complex_type (type);
762       gfc_complex_types[index] = type;
763       snprintf (name_buf, sizeof(name_buf), "complex(kind=%d)",
764                 gfc_real_kinds[index].kind);
765       PUSH_TYPE (name_buf, type);
766     }
767
768   for (index = 0; gfc_character_kinds[index].kind != 0; ++index)
769     {
770       type = gfc_build_uint_type (gfc_character_kinds[index].bit_size);
771       type = build_qualified_type (type, TYPE_UNQUALIFIED);
772       snprintf (name_buf, sizeof(name_buf), "character(kind=%d)",
773                 gfc_character_kinds[index].kind);
774       PUSH_TYPE (name_buf, type);
775       gfc_character_types[index] = type;
776       gfc_pcharacter_types[index] = build_pointer_type (type);
777     }
778   gfc_character1_type_node = gfc_character_types[0];
779
780   PUSH_TYPE ("byte", unsigned_char_type_node);
781   PUSH_TYPE ("void", void_type_node);
782
783   /* DBX debugging output gets upset if these aren't set.  */
784   if (!TYPE_NAME (integer_type_node))
785     PUSH_TYPE ("c_integer", integer_type_node);
786   if (!TYPE_NAME (char_type_node))
787     PUSH_TYPE ("c_char", char_type_node);
788
789 #undef PUSH_TYPE
790
791   pvoid_type_node = build_pointer_type (void_type_node);
792   ppvoid_type_node = build_pointer_type (pvoid_type_node);
793   pchar_type_node = build_pointer_type (gfc_character1_type_node);
794   pfunc_type_node
795     = build_pointer_type (build_function_type (void_type_node, NULL_TREE));
796
797   gfc_array_index_type = gfc_get_int_type (gfc_index_integer_kind);
798   /* We cannot use gfc_index_zero_node in definition of gfc_array_range_type,
799      since this function is called before gfc_init_constants.  */
800   gfc_array_range_type
801           = build_range_type (gfc_array_index_type,
802                               build_int_cst (gfc_array_index_type, 0),
803                               NULL_TREE);
804
805   /* The maximum array element size that can be handled is determined
806      by the number of bits available to store this field in the array
807      descriptor.  */
808
809   n = TYPE_PRECISION (gfc_array_index_type) - GFC_DTYPE_SIZE_SHIFT;
810   lo = ~ (unsigned HOST_WIDE_INT) 0;
811   if (n > HOST_BITS_PER_WIDE_INT)
812     hi = lo >> (2*HOST_BITS_PER_WIDE_INT - n);
813   else
814     hi = 0, lo >>= HOST_BITS_PER_WIDE_INT - n;
815   gfc_max_array_element_size
816     = build_int_cst_wide (long_unsigned_type_node, lo, hi);
817
818   size_type_node = gfc_array_index_type;
819
820   boolean_type_node = gfc_get_logical_type (gfc_default_logical_kind);
821   boolean_true_node = build_int_cst (boolean_type_node, 1);
822   boolean_false_node = build_int_cst (boolean_type_node, 0);
823
824   /* ??? Shouldn't this be based on gfc_index_integer_kind or so?  */
825   gfc_charlen_int_kind = 4;
826   gfc_charlen_type_node = gfc_get_int_type (gfc_charlen_int_kind);
827 }
828
829 /* Get the type node for the given type and kind.  */
830
831 tree
832 gfc_get_int_type (int kind)
833 {
834   int index = gfc_validate_kind (BT_INTEGER, kind, true);
835   return index < 0 ? 0 : gfc_integer_types[index];
836 }
837
838 tree
839 gfc_get_real_type (int kind)
840 {
841   int index = gfc_validate_kind (BT_REAL, kind, true);
842   return index < 0 ? 0 : gfc_real_types[index];
843 }
844
845 tree
846 gfc_get_complex_type (int kind)
847 {
848   int index = gfc_validate_kind (BT_COMPLEX, kind, true);
849   return index < 0 ? 0 : gfc_complex_types[index];
850 }
851
852 tree
853 gfc_get_logical_type (int kind)
854 {
855   int index = gfc_validate_kind (BT_LOGICAL, kind, true);
856   return index < 0 ? 0 : gfc_logical_types[index];
857 }
858
859 tree
860 gfc_get_char_type (int kind)
861 {
862   int index = gfc_validate_kind (BT_CHARACTER, kind, true);
863   return index < 0 ? 0 : gfc_character_types[index];
864 }
865
866 tree
867 gfc_get_pchar_type (int kind)
868 {
869   int index = gfc_validate_kind (BT_CHARACTER, kind, true);
870   return index < 0 ? 0 : gfc_pcharacter_types[index];
871 }
872
873 \f
874 /* Create a character type with the given kind and length.  */
875
876 tree
877 gfc_get_character_type_len_for_eltype (tree eltype, tree len)
878 {
879   tree bounds, type;
880
881   bounds = build_range_type (gfc_charlen_type_node, gfc_index_one_node, len);
882   type = build_array_type (eltype, bounds);
883   TYPE_STRING_FLAG (type) = 1;
884
885   return type;
886 }
887
888 tree
889 gfc_get_character_type_len (int kind, tree len)
890 {
891   gfc_validate_kind (BT_CHARACTER, kind, false);
892   return gfc_get_character_type_len_for_eltype (gfc_get_char_type (kind), len);
893 }
894
895
896 /* Get a type node for a character kind.  */
897
898 tree
899 gfc_get_character_type (int kind, gfc_charlen * cl)
900 {
901   tree len;
902
903   len = (cl == NULL) ? NULL_TREE : cl->backend_decl;
904
905   return gfc_get_character_type_len (kind, len);
906 }
907 \f
908 /* Covert a basic type.  This will be an array for character types.  */
909
910 tree
911 gfc_typenode_for_spec (gfc_typespec * spec)
912 {
913   tree basetype;
914
915   switch (spec->type)
916     {
917     case BT_UNKNOWN:
918       gcc_unreachable ();
919
920     case BT_INTEGER:
921       /* We use INTEGER(c_intptr_t) for C_PTR and C_FUNPTR once the symbol
922          has been resolved.  This is done so we can convert C_PTR and
923          C_FUNPTR to simple variables that get translated to (void *).  */
924       if (spec->f90_type == BT_VOID)
925         {
926           if (spec->derived
927               && spec->derived->intmod_sym_id == ISOCBINDING_PTR)
928             basetype = ptr_type_node;
929           else
930             basetype = pfunc_type_node;
931         }
932       else
933         basetype = gfc_get_int_type (spec->kind);
934       break;
935
936     case BT_REAL:
937       basetype = gfc_get_real_type (spec->kind);
938       break;
939
940     case BT_COMPLEX:
941       basetype = gfc_get_complex_type (spec->kind);
942       break;
943
944     case BT_LOGICAL:
945       basetype = gfc_get_logical_type (spec->kind);
946       break;
947
948     case BT_CHARACTER:
949       basetype = gfc_get_character_type (spec->kind, spec->cl);
950       break;
951
952     case BT_DERIVED:
953       basetype = gfc_get_derived_type (spec->derived);
954
955       /* If we're dealing with either C_PTR or C_FUNPTR, we modified the
956          type and kind to fit a (void *) and the basetype returned was a
957          ptr_type_node.  We need to pass up this new information to the
958          symbol that was declared of type C_PTR or C_FUNPTR.  */
959       if (spec->derived->attr.is_iso_c)
960         {
961           spec->type = spec->derived->ts.type;
962           spec->kind = spec->derived->ts.kind;
963           spec->f90_type = spec->derived->ts.f90_type;
964         }
965       break;
966     case BT_VOID:
967       /* This is for the second arg to c_f_pointer and c_f_procpointer
968          of the iso_c_binding module, to accept any ptr type.  */
969       basetype = ptr_type_node;
970       if (spec->f90_type == BT_VOID)
971         {
972           if (spec->derived
973               && spec->derived->intmod_sym_id == ISOCBINDING_PTR)
974             basetype = ptr_type_node;
975           else
976             basetype = pfunc_type_node;
977         }
978        break;
979     default:
980       gcc_unreachable ();
981     }
982   return basetype;
983 }
984 \f
985 /* Build an INT_CST for constant expressions, otherwise return NULL_TREE.  */
986
987 static tree
988 gfc_conv_array_bound (gfc_expr * expr)
989 {
990   /* If expr is an integer constant, return that.  */
991   if (expr != NULL && expr->expr_type == EXPR_CONSTANT)
992     return gfc_conv_mpz_to_tree (expr->value.integer, gfc_index_integer_kind);
993
994   /* Otherwise return NULL.  */
995   return NULL_TREE;
996 }
997 \f
998 tree
999 gfc_get_element_type (tree type)
1000 {
1001   tree element;
1002
1003   if (GFC_ARRAY_TYPE_P (type))
1004     {
1005       if (TREE_CODE (type) == POINTER_TYPE)
1006         type = TREE_TYPE (type);
1007       gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
1008       element = TREE_TYPE (type);
1009     }
1010   else
1011     {
1012       gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
1013       element = GFC_TYPE_ARRAY_DATAPTR_TYPE (type);
1014
1015       gcc_assert (TREE_CODE (element) == POINTER_TYPE);
1016       element = TREE_TYPE (element);
1017
1018       gcc_assert (TREE_CODE (element) == ARRAY_TYPE);
1019       element = TREE_TYPE (element);
1020     }
1021
1022   return element;
1023 }
1024 \f
1025 /* Build an array.  This function is called from gfc_sym_type().
1026    Actually returns array descriptor type.
1027
1028    Format of array descriptors is as follows:
1029
1030     struct gfc_array_descriptor
1031     {
1032       array *data
1033       index offset;
1034       index dtype;
1035       struct descriptor_dimension dimension[N_DIM];
1036     }
1037
1038     struct descriptor_dimension
1039     {
1040       index stride;
1041       index lbound;
1042       index ubound;
1043     }
1044
1045    Translation code should use gfc_conv_descriptor_* rather than
1046    accessing the descriptor directly.  Any changes to the array
1047    descriptor type will require changes in gfc_conv_descriptor_* and
1048    gfc_build_array_initializer.
1049
1050    This is represented internally as a RECORD_TYPE. The index nodes
1051    are gfc_array_index_type and the data node is a pointer to the
1052    data.  See below for the handling of character types.
1053
1054    The dtype member is formatted as follows:
1055     rank = dtype & GFC_DTYPE_RANK_MASK // 3 bits
1056     type = (dtype & GFC_DTYPE_TYPE_MASK) >> GFC_DTYPE_TYPE_SHIFT // 3 bits
1057     size = dtype >> GFC_DTYPE_SIZE_SHIFT
1058
1059    I originally used nested ARRAY_TYPE nodes to represent arrays, but
1060    this generated poor code for assumed/deferred size arrays.  These
1061    require use of PLACEHOLDER_EXPR/WITH_RECORD_EXPR, which isn't part
1062    of the GENERIC grammar.  Also, there is no way to explicitly set
1063    the array stride, so all data must be packed(1).  I've tried to
1064    mark all the functions which would require modification with a GCC
1065    ARRAYS comment.
1066
1067    The data component points to the first element in the array.  The
1068    offset field is the position of the origin of the array (i.e. element
1069    (0, 0 ...)).  This may be outside the bounds of the array.
1070
1071    An element is accessed by
1072     data[offset + index0*stride0 + index1*stride1 + index2*stride2]
1073    This gives good performance as the computation does not involve the
1074    bounds of the array.  For packed arrays, this is optimized further
1075    by substituting the known strides.
1076
1077    This system has one problem: all array bounds must be within 2^31
1078    elements of the origin (2^63 on 64-bit machines).  For example
1079     integer, dimension (80000:90000, 80000:90000, 2) :: array
1080    may not work properly on 32-bit machines because 80000*80000 >
1081    2^31, so the calculation for stride2 would overflow.  This may
1082    still work, but I haven't checked, and it relies on the overflow
1083    doing the right thing.
1084
1085    The way to fix this problem is to access elements as follows:
1086     data[(index0-lbound0)*stride0 + (index1-lbound1)*stride1]
1087    Obviously this is much slower.  I will make this a compile time
1088    option, something like -fsmall-array-offsets.  Mixing code compiled
1089    with and without this switch will work.
1090
1091    (1) This can be worked around by modifying the upper bound of the
1092    previous dimension.  This requires extra fields in the descriptor
1093    (both real_ubound and fake_ubound).  */
1094
1095
1096 /* Returns true if the array sym does not require a descriptor.  */
1097
1098 int
1099 gfc_is_nodesc_array (gfc_symbol * sym)
1100 {
1101   gcc_assert (sym->attr.dimension);
1102
1103   /* We only want local arrays.  */
1104   if (sym->attr.pointer || sym->attr.allocatable)
1105     return 0;
1106
1107   if (sym->attr.dummy)
1108     {
1109       if (sym->as->type != AS_ASSUMED_SHAPE)
1110         return 1;
1111       else
1112         return 0;
1113     }
1114
1115   if (sym->attr.result || sym->attr.function)
1116     return 0;
1117
1118   gcc_assert (sym->as->type == AS_EXPLICIT);
1119
1120   return 1;
1121 }
1122
1123
1124 /* Create an array descriptor type.  */
1125
1126 static tree
1127 gfc_build_array_type (tree type, gfc_array_spec * as,
1128                       enum gfc_array_kind akind)
1129 {
1130   tree lbound[GFC_MAX_DIMENSIONS];
1131   tree ubound[GFC_MAX_DIMENSIONS];
1132   int n;
1133
1134   for (n = 0; n < as->rank; n++)
1135     {
1136       /* Create expressions for the known bounds of the array.  */
1137       if (as->type == AS_ASSUMED_SHAPE && as->lower[n] == NULL)
1138         lbound[n] = gfc_index_one_node;
1139       else
1140         lbound[n] = gfc_conv_array_bound (as->lower[n]);
1141       ubound[n] = gfc_conv_array_bound (as->upper[n]);
1142     }
1143
1144   if (as->type == AS_ASSUMED_SHAPE)
1145     akind = GFC_ARRAY_ASSUMED_SHAPE;
1146   return gfc_get_array_type_bounds (type, as->rank, lbound, ubound, 0, akind);
1147 }
1148 \f
1149 /* Returns the struct descriptor_dimension type.  */
1150
1151 static tree
1152 gfc_get_desc_dim_type (void)
1153 {
1154   tree type;
1155   tree decl;
1156   tree fieldlist;
1157
1158   if (gfc_desc_dim_type)
1159     return gfc_desc_dim_type;
1160
1161   /* Build the type node.  */
1162   type = make_node (RECORD_TYPE);
1163
1164   TYPE_NAME (type) = get_identifier ("descriptor_dimension");
1165   TYPE_PACKED (type) = 1;
1166
1167   /* Consists of the stride, lbound and ubound members.  */
1168   decl = build_decl (FIELD_DECL,
1169                      get_identifier ("stride"), gfc_array_index_type);
1170   DECL_CONTEXT (decl) = type;
1171   TREE_NO_WARNING (decl) = 1;
1172   fieldlist = decl;
1173
1174   decl = build_decl (FIELD_DECL,
1175                      get_identifier ("lbound"), gfc_array_index_type);
1176   DECL_CONTEXT (decl) = type;
1177   TREE_NO_WARNING (decl) = 1;
1178   fieldlist = chainon (fieldlist, decl);
1179
1180   decl = build_decl (FIELD_DECL,
1181                      get_identifier ("ubound"), gfc_array_index_type);
1182   DECL_CONTEXT (decl) = type;
1183   TREE_NO_WARNING (decl) = 1;
1184   fieldlist = chainon (fieldlist, decl);
1185
1186   /* Finish off the type.  */
1187   TYPE_FIELDS (type) = fieldlist;
1188
1189   gfc_finish_type (type);
1190   TYPE_DECL_SUPPRESS_DEBUG (TYPE_STUB_DECL (type)) = 1;
1191
1192   gfc_desc_dim_type = type;
1193   return type;
1194 }
1195
1196
1197 /* Return the DTYPE for an array.  This describes the type and type parameters
1198    of the array.  */
1199 /* TODO: Only call this when the value is actually used, and make all the
1200    unknown cases abort.  */
1201
1202 tree
1203 gfc_get_dtype (tree type)
1204 {
1205   tree size;
1206   int n;
1207   HOST_WIDE_INT i;
1208   tree tmp;
1209   tree dtype;
1210   tree etype;
1211   int rank;
1212
1213   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type) || GFC_ARRAY_TYPE_P (type));
1214
1215   if (GFC_TYPE_ARRAY_DTYPE (type))
1216     return GFC_TYPE_ARRAY_DTYPE (type);
1217
1218   rank = GFC_TYPE_ARRAY_RANK (type);
1219   etype = gfc_get_element_type (type);
1220
1221   switch (TREE_CODE (etype))
1222     {
1223     case INTEGER_TYPE:
1224       n = GFC_DTYPE_INTEGER;
1225       break;
1226
1227     case BOOLEAN_TYPE:
1228       n = GFC_DTYPE_LOGICAL;
1229       break;
1230
1231     case REAL_TYPE:
1232       n = GFC_DTYPE_REAL;
1233       break;
1234
1235     case COMPLEX_TYPE:
1236       n = GFC_DTYPE_COMPLEX;
1237       break;
1238
1239     /* We will never have arrays of arrays.  */
1240     case RECORD_TYPE:
1241       n = GFC_DTYPE_DERIVED;
1242       break;
1243
1244     case ARRAY_TYPE:
1245       n = GFC_DTYPE_CHARACTER;
1246       break;
1247
1248     default:
1249       /* TODO: Don't do dtype for temporary descriptorless arrays.  */
1250       /* We can strange array types for temporary arrays.  */
1251       return gfc_index_zero_node;
1252     }
1253
1254   gcc_assert (rank <= GFC_DTYPE_RANK_MASK);
1255   size = TYPE_SIZE_UNIT (etype);
1256
1257   i = rank | (n << GFC_DTYPE_TYPE_SHIFT);
1258   if (size && INTEGER_CST_P (size))
1259     {
1260       if (tree_int_cst_lt (gfc_max_array_element_size, size))
1261         internal_error ("Array element size too big");
1262
1263       i += TREE_INT_CST_LOW (size) << GFC_DTYPE_SIZE_SHIFT;
1264     }
1265   dtype = build_int_cst (gfc_array_index_type, i);
1266
1267   if (size && !INTEGER_CST_P (size))
1268     {
1269       tmp = build_int_cst (gfc_array_index_type, GFC_DTYPE_SIZE_SHIFT);
1270       tmp  = fold_build2 (LSHIFT_EXPR, gfc_array_index_type,
1271                           fold_convert (gfc_array_index_type, size), tmp);
1272       dtype = fold_build2 (PLUS_EXPR, gfc_array_index_type, tmp, dtype);
1273     }
1274   /* If we don't know the size we leave it as zero.  This should never happen
1275      for anything that is actually used.  */
1276   /* TODO: Check this is actually true, particularly when repacking
1277      assumed size parameters.  */
1278
1279   GFC_TYPE_ARRAY_DTYPE (type) = dtype;
1280   return dtype;
1281 }
1282
1283
1284 /* Build an array type for use without a descriptor, packed according
1285    to the value of PACKED.  */
1286
1287 tree
1288 gfc_get_nodesc_array_type (tree etype, gfc_array_spec * as, gfc_packed packed)
1289 {
1290   tree range;
1291   tree type;
1292   tree tmp;
1293   int n;
1294   int known_stride;
1295   int known_offset;
1296   mpz_t offset;
1297   mpz_t stride;
1298   mpz_t delta;
1299   gfc_expr *expr;
1300
1301   mpz_init_set_ui (offset, 0);
1302   mpz_init_set_ui (stride, 1);
1303   mpz_init (delta);
1304
1305   /* We don't use build_array_type because this does not include include
1306      lang-specific information (i.e. the bounds of the array) when checking
1307      for duplicates.  */
1308   type = make_node (ARRAY_TYPE);
1309
1310   GFC_ARRAY_TYPE_P (type) = 1;
1311   TYPE_LANG_SPECIFIC (type) = (struct lang_type *)
1312     ggc_alloc_cleared (sizeof (struct lang_type));
1313
1314   known_stride = (packed != PACKED_NO);
1315   known_offset = 1;
1316   for (n = 0; n < as->rank; n++)
1317     {
1318       /* Fill in the stride and bound components of the type.  */
1319       if (known_stride)
1320         tmp = gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1321       else
1322         tmp = NULL_TREE;
1323       GFC_TYPE_ARRAY_STRIDE (type, n) = tmp;
1324
1325       expr = as->lower[n];
1326       if (expr->expr_type == EXPR_CONSTANT)
1327         {
1328           tmp = gfc_conv_mpz_to_tree (expr->value.integer,
1329                                       gfc_index_integer_kind);
1330         }
1331       else
1332         {
1333           known_stride = 0;
1334           tmp = NULL_TREE;
1335         }
1336       GFC_TYPE_ARRAY_LBOUND (type, n) = tmp;
1337
1338       if (known_stride)
1339         {
1340           /* Calculate the offset.  */
1341           mpz_mul (delta, stride, as->lower[n]->value.integer);
1342           mpz_sub (offset, offset, delta);
1343         }
1344       else
1345         known_offset = 0;
1346
1347       expr = as->upper[n];
1348       if (expr && expr->expr_type == EXPR_CONSTANT)
1349         {
1350           tmp = gfc_conv_mpz_to_tree (expr->value.integer,
1351                                   gfc_index_integer_kind);
1352         }
1353       else
1354         {
1355           tmp = NULL_TREE;
1356           known_stride = 0;
1357         }
1358       GFC_TYPE_ARRAY_UBOUND (type, n) = tmp;
1359
1360       if (known_stride)
1361         {
1362           /* Calculate the stride.  */
1363           mpz_sub (delta, as->upper[n]->value.integer,
1364                    as->lower[n]->value.integer);
1365           mpz_add_ui (delta, delta, 1);
1366           mpz_mul (stride, stride, delta);
1367         }
1368
1369       /* Only the first stride is known for partial packed arrays.  */
1370       if (packed == PACKED_NO || packed == PACKED_PARTIAL)
1371         known_stride = 0;
1372     }
1373
1374   if (known_offset)
1375     {
1376       GFC_TYPE_ARRAY_OFFSET (type) =
1377         gfc_conv_mpz_to_tree (offset, gfc_index_integer_kind);
1378     }
1379   else
1380     GFC_TYPE_ARRAY_OFFSET (type) = NULL_TREE;
1381
1382   if (known_stride)
1383     {
1384       GFC_TYPE_ARRAY_SIZE (type) =
1385         gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1386     }
1387   else
1388     GFC_TYPE_ARRAY_SIZE (type) = NULL_TREE;
1389
1390   GFC_TYPE_ARRAY_RANK (type) = as->rank;
1391   GFC_TYPE_ARRAY_DTYPE (type) = NULL_TREE;
1392   range = build_range_type (gfc_array_index_type, gfc_index_zero_node,
1393                             NULL_TREE);
1394   /* TODO: use main type if it is unbounded.  */
1395   GFC_TYPE_ARRAY_DATAPTR_TYPE (type) =
1396     build_pointer_type (build_array_type (etype, range));
1397
1398   if (known_stride)
1399     {
1400       mpz_sub_ui (stride, stride, 1);
1401       range = gfc_conv_mpz_to_tree (stride, gfc_index_integer_kind);
1402     }
1403   else
1404     range = NULL_TREE;
1405
1406   range = build_range_type (gfc_array_index_type, gfc_index_zero_node, range);
1407   TYPE_DOMAIN (type) = range;
1408
1409   build_pointer_type (etype);
1410   TREE_TYPE (type) = etype;
1411
1412   layout_type (type);
1413
1414   mpz_clear (offset);
1415   mpz_clear (stride);
1416   mpz_clear (delta);
1417
1418   /* In debug info represent packed arrays as multi-dimensional
1419      if they have rank > 1 and with proper bounds, instead of flat
1420      arrays.  */
1421   if (known_offset && write_symbols != NO_DEBUG)
1422     {
1423       tree gtype = etype, rtype, type_decl;
1424
1425       for (n = as->rank - 1; n >= 0; n--)
1426         {
1427           rtype = build_range_type (gfc_array_index_type,
1428                                     GFC_TYPE_ARRAY_LBOUND (type, n),
1429                                     GFC_TYPE_ARRAY_UBOUND (type, n));
1430           gtype = build_array_type (gtype, rtype);
1431         }
1432       TYPE_NAME (type) = type_decl = build_decl (TYPE_DECL, NULL, gtype);
1433       DECL_ORIGINAL_TYPE (type_decl) = gtype;
1434     }
1435
1436   if (packed != PACKED_STATIC || !known_stride)
1437     {
1438       /* For dummy arrays and automatic (heap allocated) arrays we
1439          want a pointer to the array.  */
1440       type = build_pointer_type (type);
1441       GFC_ARRAY_TYPE_P (type) = 1;
1442       TYPE_LANG_SPECIFIC (type) = TYPE_LANG_SPECIFIC (TREE_TYPE (type));
1443     }
1444   return type;
1445 }
1446
1447 /* Return or create the base type for an array descriptor.  */
1448
1449 static tree
1450 gfc_get_array_descriptor_base (int dimen)
1451 {
1452   tree fat_type, fieldlist, decl, arraytype;
1453   char name[16 + GFC_RANK_DIGITS + 1];
1454
1455   gcc_assert (dimen >= 1 && dimen <= GFC_MAX_DIMENSIONS);
1456   if (gfc_array_descriptor_base[dimen - 1])
1457     return gfc_array_descriptor_base[dimen - 1];
1458
1459   /* Build the type node.  */
1460   fat_type = make_node (RECORD_TYPE);
1461
1462   sprintf (name, "array_descriptor" GFC_RANK_PRINTF_FORMAT, dimen);
1463   TYPE_NAME (fat_type) = get_identifier (name);
1464
1465   /* Add the data member as the first element of the descriptor.  */
1466   decl = build_decl (FIELD_DECL, get_identifier ("data"), ptr_type_node);
1467
1468   DECL_CONTEXT (decl) = fat_type;
1469   fieldlist = decl;
1470
1471   /* Add the base component.  */
1472   decl = build_decl (FIELD_DECL, get_identifier ("offset"),
1473                      gfc_array_index_type);
1474   DECL_CONTEXT (decl) = fat_type;
1475   TREE_NO_WARNING (decl) = 1;
1476   fieldlist = chainon (fieldlist, decl);
1477
1478   /* Add the dtype component.  */
1479   decl = build_decl (FIELD_DECL, get_identifier ("dtype"),
1480                      gfc_array_index_type);
1481   DECL_CONTEXT (decl) = fat_type;
1482   TREE_NO_WARNING (decl) = 1;
1483   fieldlist = chainon (fieldlist, decl);
1484
1485   /* Build the array type for the stride and bound components.  */
1486   arraytype =
1487     build_array_type (gfc_get_desc_dim_type (),
1488                       build_range_type (gfc_array_index_type,
1489                                         gfc_index_zero_node,
1490                                         gfc_rank_cst[dimen - 1]));
1491
1492   decl = build_decl (FIELD_DECL, get_identifier ("dim"), arraytype);
1493   DECL_CONTEXT (decl) = fat_type;
1494   TREE_NO_WARNING (decl) = 1;
1495   fieldlist = chainon (fieldlist, decl);
1496
1497   /* Finish off the type.  */
1498   TYPE_FIELDS (fat_type) = fieldlist;
1499
1500   gfc_finish_type (fat_type);
1501   TYPE_DECL_SUPPRESS_DEBUG (TYPE_STUB_DECL (fat_type)) = 1;
1502
1503   gfc_array_descriptor_base[dimen - 1] = fat_type;
1504   return fat_type;
1505 }
1506
1507 /* Build an array (descriptor) type with given bounds.  */
1508
1509 tree
1510 gfc_get_array_type_bounds (tree etype, int dimen, tree * lbound,
1511                            tree * ubound, int packed,
1512                            enum gfc_array_kind akind)
1513 {
1514   char name[8 + GFC_RANK_DIGITS + GFC_MAX_SYMBOL_LEN];
1515   tree fat_type, base_type, arraytype, lower, upper, stride, tmp, rtype;
1516   const char *type_name;
1517   int n;
1518
1519   base_type = gfc_get_array_descriptor_base (dimen);
1520   fat_type = build_variant_type_copy (base_type);
1521
1522   tmp = TYPE_NAME (etype);
1523   if (tmp && TREE_CODE (tmp) == TYPE_DECL)
1524     tmp = DECL_NAME (tmp);
1525   if (tmp)
1526     type_name = IDENTIFIER_POINTER (tmp);
1527   else
1528     type_name = "unknown";
1529   sprintf (name, "array" GFC_RANK_PRINTF_FORMAT "_%.*s", dimen,
1530            GFC_MAX_SYMBOL_LEN, type_name);
1531   TYPE_NAME (fat_type) = get_identifier (name);
1532
1533   GFC_DESCRIPTOR_TYPE_P (fat_type) = 1;
1534   TYPE_LANG_SPECIFIC (fat_type) = (struct lang_type *)
1535     ggc_alloc_cleared (sizeof (struct lang_type));
1536
1537   GFC_TYPE_ARRAY_RANK (fat_type) = dimen;
1538   GFC_TYPE_ARRAY_DTYPE (fat_type) = NULL_TREE;
1539   GFC_TYPE_ARRAY_AKIND (fat_type) = akind;
1540
1541   /* Build an array descriptor record type.  */
1542   if (packed != 0)
1543     stride = gfc_index_one_node;
1544   else
1545     stride = NULL_TREE;
1546   for (n = 0; n < dimen; n++)
1547     {
1548       GFC_TYPE_ARRAY_STRIDE (fat_type, n) = stride;
1549
1550       if (lbound)
1551         lower = lbound[n];
1552       else
1553         lower = NULL_TREE;
1554
1555       if (lower != NULL_TREE)
1556         {
1557           if (INTEGER_CST_P (lower))
1558             GFC_TYPE_ARRAY_LBOUND (fat_type, n) = lower;
1559           else
1560             lower = NULL_TREE;
1561         }
1562
1563       upper = ubound[n];
1564       if (upper != NULL_TREE)
1565         {
1566           if (INTEGER_CST_P (upper))
1567             GFC_TYPE_ARRAY_UBOUND (fat_type, n) = upper;
1568           else
1569             upper = NULL_TREE;
1570         }
1571
1572       if (upper != NULL_TREE && lower != NULL_TREE && stride != NULL_TREE)
1573         {
1574           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, upper, lower);
1575           tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type, tmp,
1576                              gfc_index_one_node);
1577           stride =
1578             fold_build2 (MULT_EXPR, gfc_array_index_type, tmp, stride);
1579           /* Check the folding worked.  */
1580           gcc_assert (INTEGER_CST_P (stride));
1581         }
1582       else
1583         stride = NULL_TREE;
1584     }
1585   GFC_TYPE_ARRAY_SIZE (fat_type) = stride;
1586
1587   /* TODO: known offsets for descriptors.  */
1588   GFC_TYPE_ARRAY_OFFSET (fat_type) = NULL_TREE;
1589
1590   /* We define data as an array with the correct size if possible.
1591      Much better than doing pointer arithmetic.  */
1592   if (stride)
1593     rtype = build_range_type (gfc_array_index_type, gfc_index_zero_node,
1594                               int_const_binop (MINUS_EXPR, stride,
1595                                                integer_one_node, 0));
1596   else
1597     rtype = gfc_array_range_type;
1598   arraytype = build_array_type (etype, rtype);
1599   arraytype = build_pointer_type (arraytype);
1600   GFC_TYPE_ARRAY_DATAPTR_TYPE (fat_type) = arraytype;
1601
1602   return fat_type;
1603 }
1604 \f
1605 /* Build a pointer type. This function is called from gfc_sym_type().  */
1606
1607 static tree
1608 gfc_build_pointer_type (gfc_symbol * sym, tree type)
1609 {
1610   /* Array pointer types aren't actually pointers.  */
1611   if (sym->attr.dimension)
1612     return type;
1613   else
1614     return build_pointer_type (type);
1615 }
1616 \f
1617 /* Return the type for a symbol.  Special handling is required for character
1618    types to get the correct level of indirection.
1619    For functions return the return type.
1620    For subroutines return void_type_node.
1621    Calling this multiple times for the same symbol should be avoided,
1622    especially for character and array types.  */
1623
1624 tree
1625 gfc_sym_type (gfc_symbol * sym)
1626 {
1627   tree type;
1628   int byref;
1629
1630   if (sym->attr.flavor == FL_PROCEDURE && !sym->attr.function)
1631     return void_type_node;
1632
1633   /* In the case of a function the fake result variable may have a
1634      type different from the function type, so don't return early in
1635      that case.  */
1636   if (sym->backend_decl && !sym->attr.function)
1637     return TREE_TYPE (sym->backend_decl);
1638
1639   if (sym->ts.type == BT_CHARACTER && sym->attr.is_bind_c
1640       && (sym->attr.function || sym->attr.result))
1641     type = gfc_character1_type_node;
1642   else
1643     type = gfc_typenode_for_spec (&sym->ts);
1644
1645   if (sym->attr.dummy && !sym->attr.function && !sym->attr.value)
1646     byref = 1;
1647   else
1648     byref = 0;
1649
1650   if (sym->attr.dimension)
1651     {
1652       if (gfc_is_nodesc_array (sym))
1653         {
1654           /* If this is a character argument of unknown length, just use the
1655              base type.  */
1656           if (sym->ts.type != BT_CHARACTER
1657               || !(sym->attr.dummy || sym->attr.function)
1658               || sym->ts.cl->backend_decl)
1659             {
1660               type = gfc_get_nodesc_array_type (type, sym->as,
1661                                                 byref ? PACKED_FULL
1662                                                       : PACKED_STATIC);
1663               byref = 0;
1664             }
1665         }
1666       else
1667         {
1668           enum gfc_array_kind akind = GFC_ARRAY_UNKNOWN;
1669           if (sym->attr.pointer)
1670             akind = GFC_ARRAY_POINTER;
1671           else if (sym->attr.allocatable)
1672             akind = GFC_ARRAY_ALLOCATABLE;
1673           type = gfc_build_array_type (type, sym->as, akind);
1674         }
1675     }
1676   else
1677     {
1678       if (sym->attr.allocatable || sym->attr.pointer)
1679         type = gfc_build_pointer_type (sym, type);
1680       if (sym->attr.pointer)
1681         GFC_POINTER_TYPE_P (type) = 1;
1682     }
1683
1684   /* We currently pass all parameters by reference.
1685      See f95_get_function_decl.  For dummy function parameters return the
1686      function type.  */
1687   if (byref)
1688     {
1689       /* We must use pointer types for potentially absent variables.  The
1690          optimizers assume a reference type argument is never NULL.  */
1691       if (sym->attr.optional || sym->ns->proc_name->attr.entry_master)
1692         type = build_pointer_type (type);
1693       else
1694         type = build_reference_type (type);
1695     }
1696
1697   return (type);
1698 }
1699 \f
1700 /* Layout and output debug info for a record type.  */
1701
1702 void
1703 gfc_finish_type (tree type)
1704 {
1705   tree decl;
1706
1707   decl = build_decl (TYPE_DECL, NULL_TREE, type);
1708   TYPE_STUB_DECL (type) = decl;
1709   layout_type (type);
1710   rest_of_type_compilation (type, 1);
1711   rest_of_decl_compilation (decl, 1, 0);
1712 }
1713 \f
1714 /* Add a field of given NAME and TYPE to the context of a UNION_TYPE
1715    or RECORD_TYPE pointed to by STYPE.  The new field is chained
1716    to the fieldlist pointed to by FIELDLIST.
1717
1718    Returns a pointer to the new field.  */
1719
1720 tree
1721 gfc_add_field_to_struct (tree *fieldlist, tree context,
1722                          tree name, tree type)
1723 {
1724   tree decl;
1725
1726   decl = build_decl (FIELD_DECL, name, type);
1727
1728   DECL_CONTEXT (decl) = context;
1729   DECL_INITIAL (decl) = 0;
1730   DECL_ALIGN (decl) = 0;
1731   DECL_USER_ALIGN (decl) = 0;
1732   TREE_CHAIN (decl) = NULL_TREE;
1733   *fieldlist = chainon (*fieldlist, decl);
1734
1735   return decl;
1736 }
1737
1738
1739 /* Copy the backend_decl and component backend_decls if
1740    the two derived type symbols are "equal", as described
1741    in 4.4.2 and resolved by gfc_compare_derived_types.  */
1742
1743 static int
1744 copy_dt_decls_ifequal (gfc_symbol *from, gfc_symbol *to)
1745 {
1746   gfc_component *to_cm;
1747   gfc_component *from_cm;
1748
1749   if (from->backend_decl == NULL
1750         || !gfc_compare_derived_types (from, to))
1751     return 0;
1752
1753   to->backend_decl = from->backend_decl;
1754
1755   to_cm = to->components;
1756   from_cm = from->components;
1757
1758   /* Copy the component declarations.  If a component is itself
1759      a derived type, we need a copy of its component declarations.
1760      This is done by recursing into gfc_get_derived_type and
1761      ensures that the component's component declarations have
1762      been built.  If it is a character, we need the character 
1763      length, as well.  */
1764   for (; to_cm; to_cm = to_cm->next, from_cm = from_cm->next)
1765     {
1766       to_cm->backend_decl = from_cm->backend_decl;
1767       if (!from_cm->pointer && from_cm->ts.type == BT_DERIVED)
1768         gfc_get_derived_type (to_cm->ts.derived);
1769
1770       else if (from_cm->ts.type == BT_CHARACTER)
1771         to_cm->ts.cl->backend_decl = from_cm->ts.cl->backend_decl;
1772     }
1773
1774   return 1;
1775 }
1776
1777
1778 /* Build a tree node for a derived type.  If there are equal
1779    derived types, with different local names, these are built
1780    at the same time.  If an equal derived type has been built
1781    in a parent namespace, this is used.  */
1782
1783 static tree
1784 gfc_get_derived_type (gfc_symbol * derived)
1785 {
1786   tree typenode = NULL, field = NULL, field_type = NULL, fieldlist = NULL;
1787   gfc_component *c;
1788   gfc_dt_list *dt;
1789
1790   gcc_assert (derived && derived->attr.flavor == FL_DERIVED);
1791
1792   /* See if it's one of the iso_c_binding derived types.  */
1793   if (derived->attr.is_iso_c == 1)
1794     {
1795       if (derived->backend_decl)
1796         return derived->backend_decl;
1797
1798       if (derived->intmod_sym_id == ISOCBINDING_PTR)
1799         derived->backend_decl = ptr_type_node;
1800       else
1801         derived->backend_decl = pfunc_type_node;
1802
1803       /* Create a backend_decl for the __c_ptr_c_address field.  */
1804       derived->components->backend_decl =
1805         gfc_add_field_to_struct (&(derived->backend_decl->type.values),
1806                                  derived->backend_decl,
1807                                  get_identifier (derived->components->name),
1808                                  gfc_typenode_for_spec (
1809                                    &(derived->components->ts)));
1810
1811       derived->ts.kind = gfc_index_integer_kind;
1812       derived->ts.type = BT_INTEGER;
1813       /* Set the f90_type to BT_VOID as a way to recognize something of type
1814          BT_INTEGER that needs to fit a void * for the purpose of the
1815          iso_c_binding derived types.  */
1816       derived->ts.f90_type = BT_VOID;
1817       
1818       return derived->backend_decl;
1819     }
1820   
1821   /* derived->backend_decl != 0 means we saw it before, but its
1822      components' backend_decl may have not been built.  */
1823   if (derived->backend_decl)
1824     {
1825       /* Its components' backend_decl have been built.  */
1826       if (TYPE_FIELDS (derived->backend_decl))
1827         return derived->backend_decl;
1828       else
1829         typenode = derived->backend_decl;
1830     }
1831   else
1832     {
1833
1834       /* We see this derived type first time, so build the type node.  */
1835       typenode = make_node (RECORD_TYPE);
1836       TYPE_NAME (typenode) = get_identifier (derived->name);
1837       TYPE_PACKED (typenode) = gfc_option.flag_pack_derived;
1838       derived->backend_decl = typenode;
1839     }
1840
1841   /* Go through the derived type components, building them as
1842      necessary. The reason for doing this now is that it is
1843      possible to recurse back to this derived type through a
1844      pointer component (PR24092). If this happens, the fields
1845      will be built and so we can return the type.  */
1846   for (c = derived->components; c; c = c->next)
1847     {
1848       if (c->ts.type != BT_DERIVED)
1849         continue;
1850
1851       if (!c->pointer || c->ts.derived->backend_decl == NULL)
1852         c->ts.derived->backend_decl = gfc_get_derived_type (c->ts.derived);
1853
1854       if (c->ts.derived && c->ts.derived->attr.is_iso_c)
1855         {
1856           /* Need to copy the modified ts from the derived type.  The
1857              typespec was modified because C_PTR/C_FUNPTR are translated
1858              into (void *) from derived types.  */
1859           c->ts.type = c->ts.derived->ts.type;
1860           c->ts.kind = c->ts.derived->ts.kind;
1861           c->ts.f90_type = c->ts.derived->ts.f90_type;
1862           if (c->initializer)
1863             {
1864               c->initializer->ts.type = c->ts.type;
1865               c->initializer->ts.kind = c->ts.kind;
1866               c->initializer->ts.f90_type = c->ts.f90_type;
1867               c->initializer->expr_type = EXPR_NULL;
1868             }
1869         }
1870     }
1871
1872   if (TYPE_FIELDS (derived->backend_decl))
1873     return derived->backend_decl;
1874
1875   /* Build the type member list. Install the newly created RECORD_TYPE
1876      node as DECL_CONTEXT of each FIELD_DECL.  */
1877   fieldlist = NULL_TREE;
1878   for (c = derived->components; c; c = c->next)
1879     {
1880       if (c->ts.type == BT_DERIVED)
1881         field_type = c->ts.derived->backend_decl;
1882       else
1883         {
1884           if (c->ts.type == BT_CHARACTER)
1885             {
1886               /* Evaluate the string length.  */
1887               gfc_conv_const_charlen (c->ts.cl);
1888               gcc_assert (c->ts.cl->backend_decl);
1889             }
1890
1891           field_type = gfc_typenode_for_spec (&c->ts);
1892         }
1893
1894       /* This returns an array descriptor type.  Initialization may be
1895          required.  */
1896       if (c->dimension)
1897         {
1898           if (c->pointer || c->allocatable)
1899             {
1900               enum gfc_array_kind akind;
1901               if (c->pointer)
1902                 akind = GFC_ARRAY_POINTER;
1903               else
1904                 akind = GFC_ARRAY_ALLOCATABLE;
1905               /* Pointers to arrays aren't actually pointer types.  The
1906                  descriptors are separate, but the data is common.  */
1907               field_type = gfc_build_array_type (field_type, c->as, akind);
1908             }
1909           else
1910             field_type = gfc_get_nodesc_array_type (field_type, c->as,
1911                                                     PACKED_STATIC);
1912         }
1913       else if (c->pointer)
1914         field_type = build_pointer_type (field_type);
1915
1916       field = gfc_add_field_to_struct (&fieldlist, typenode,
1917                                        get_identifier (c->name),
1918                                        field_type);
1919       if (c->loc.lb)
1920         gfc_set_decl_location (field, &c->loc);
1921       else if (derived->declared_at.lb)
1922         gfc_set_decl_location (field, &derived->declared_at);
1923
1924       DECL_PACKED (field) |= TYPE_PACKED (typenode);
1925
1926       gcc_assert (field);
1927       if (!c->backend_decl)
1928         c->backend_decl = field;
1929     }
1930
1931   /* Now we have the final fieldlist.  Record it, then lay out the
1932      derived type, including the fields.  */
1933   TYPE_FIELDS (typenode) = fieldlist;
1934
1935   gfc_finish_type (typenode);
1936   gfc_set_decl_location (TYPE_STUB_DECL (typenode), &derived->declared_at);
1937
1938   derived->backend_decl = typenode;
1939
1940     /* Add this backend_decl to all the other, equal derived types.  */
1941     for (dt = gfc_derived_types; dt; dt = dt->next)
1942       copy_dt_decls_ifequal (derived, dt->derived);
1943
1944   return derived->backend_decl;
1945 }
1946
1947
1948 int
1949 gfc_return_by_reference (gfc_symbol * sym)
1950 {
1951   if (!sym->attr.function)
1952     return 0;
1953
1954   if (sym->attr.dimension)
1955     return 1;
1956
1957   if (sym->ts.type == BT_CHARACTER && !sym->attr.is_bind_c)
1958     return 1;
1959
1960   /* Possibly return complex numbers by reference for g77 compatibility.
1961      We don't do this for calls to intrinsics (as the library uses the
1962      -fno-f2c calling convention), nor for calls to functions which always
1963      require an explicit interface, as no compatibility problems can
1964      arise there.  */
1965   if (gfc_option.flag_f2c
1966       && sym->ts.type == BT_COMPLEX
1967       && !sym->attr.intrinsic && !sym->attr.always_explicit)
1968     return 1;
1969
1970   return 0;
1971 }
1972 \f
1973 static tree
1974 gfc_get_mixed_entry_union (gfc_namespace *ns)
1975 {
1976   tree type;
1977   tree decl;
1978   tree fieldlist;
1979   char name[GFC_MAX_SYMBOL_LEN + 1];
1980   gfc_entry_list *el, *el2;
1981
1982   gcc_assert (ns->proc_name->attr.mixed_entry_master);
1983   gcc_assert (memcmp (ns->proc_name->name, "master.", 7) == 0);
1984
1985   snprintf (name, GFC_MAX_SYMBOL_LEN, "munion.%s", ns->proc_name->name + 7);
1986
1987   /* Build the type node.  */
1988   type = make_node (UNION_TYPE);
1989
1990   TYPE_NAME (type) = get_identifier (name);
1991   fieldlist = NULL;
1992
1993   for (el = ns->entries; el; el = el->next)
1994     {
1995       /* Search for duplicates.  */
1996       for (el2 = ns->entries; el2 != el; el2 = el2->next)
1997         if (el2->sym->result == el->sym->result)
1998           break;
1999
2000       if (el == el2)
2001         {
2002           decl = build_decl (FIELD_DECL,
2003                              get_identifier (el->sym->result->name),
2004                              gfc_sym_type (el->sym->result));
2005           DECL_CONTEXT (decl) = type;
2006           fieldlist = chainon (fieldlist, decl);
2007         }
2008     }
2009
2010   /* Finish off the type.  */
2011   TYPE_FIELDS (type) = fieldlist;
2012
2013   gfc_finish_type (type);
2014   TYPE_DECL_SUPPRESS_DEBUG (TYPE_STUB_DECL (type)) = 1;
2015   return type;
2016 }
2017 \f
2018 tree
2019 gfc_get_function_type (gfc_symbol * sym)
2020 {
2021   tree type;
2022   tree typelist;
2023   gfc_formal_arglist *f;
2024   gfc_symbol *arg;
2025   int nstr;
2026   int alternate_return;
2027
2028   /* Make sure this symbol is a function, a subroutine or the main
2029      program.  */
2030   gcc_assert (sym->attr.flavor == FL_PROCEDURE
2031               || sym->attr.flavor == FL_PROGRAM);
2032
2033   if (sym->backend_decl)
2034     return TREE_TYPE (sym->backend_decl);
2035
2036   nstr = 0;
2037   alternate_return = 0;
2038   typelist = NULL_TREE;
2039
2040   if (sym->attr.entry_master)
2041     {
2042       /* Additional parameter for selecting an entry point.  */
2043       typelist = gfc_chainon_list (typelist, gfc_array_index_type);
2044     }
2045
2046   if (sym->result)
2047     arg = sym->result;
2048   else
2049     arg = sym;
2050
2051   if (arg->ts.type == BT_CHARACTER)
2052     gfc_conv_const_charlen (arg->ts.cl);
2053
2054   /* Some functions we use an extra parameter for the return value.  */
2055   if (gfc_return_by_reference (sym))
2056     {
2057       type = gfc_sym_type (arg);
2058       if (arg->ts.type == BT_COMPLEX
2059           || arg->attr.dimension
2060           || arg->ts.type == BT_CHARACTER)
2061         type = build_reference_type (type);
2062
2063       typelist = gfc_chainon_list (typelist, type);
2064       if (arg->ts.type == BT_CHARACTER)
2065         typelist = gfc_chainon_list (typelist, gfc_charlen_type_node);
2066     }
2067
2068   /* Build the argument types for the function.  */
2069   for (f = sym->formal; f; f = f->next)
2070     {
2071       arg = f->sym;
2072       if (arg)
2073         {
2074           /* Evaluate constant character lengths here so that they can be
2075              included in the type.  */
2076           if (arg->ts.type == BT_CHARACTER)
2077             gfc_conv_const_charlen (arg->ts.cl);
2078
2079           if (arg->attr.flavor == FL_PROCEDURE)
2080             {
2081               type = gfc_get_function_type (arg);
2082               type = build_pointer_type (type);
2083             }
2084           else
2085             type = gfc_sym_type (arg);
2086
2087           /* Parameter Passing Convention
2088
2089              We currently pass all parameters by reference.
2090              Parameters with INTENT(IN) could be passed by value.
2091              The problem arises if a function is called via an implicit
2092              prototype. In this situation the INTENT is not known.
2093              For this reason all parameters to global functions must be
2094              passed by reference.  Passing by value would potentially
2095              generate bad code.  Worse there would be no way of telling that
2096              this code was bad, except that it would give incorrect results.
2097
2098              Contained procedures could pass by value as these are never
2099              used without an explicit interface, and cannot be passed as
2100              actual parameters for a dummy procedure.  */
2101           if (arg->ts.type == BT_CHARACTER)
2102             nstr++;
2103           typelist = gfc_chainon_list (typelist, type);
2104         }
2105       else
2106         {
2107           if (sym->attr.subroutine)
2108             alternate_return = 1;
2109         }
2110     }
2111
2112   /* Add hidden string length parameters.  */
2113   while (nstr--)
2114     typelist = gfc_chainon_list (typelist, gfc_charlen_type_node);
2115
2116   if (typelist)
2117     typelist = gfc_chainon_list (typelist, void_type_node);
2118
2119   if (alternate_return)
2120     type = integer_type_node;
2121   else if (!sym->attr.function || gfc_return_by_reference (sym))
2122     type = void_type_node;
2123   else if (sym->attr.mixed_entry_master)
2124     type = gfc_get_mixed_entry_union (sym->ns);
2125   else if (gfc_option.flag_f2c
2126            && sym->ts.type == BT_REAL
2127            && sym->ts.kind == gfc_default_real_kind
2128            && !sym->attr.always_explicit)
2129     {
2130       /* Special case: f2c calling conventions require that (scalar) 
2131          default REAL functions return the C type double instead.  f2c
2132          compatibility is only an issue with functions that don't
2133          require an explicit interface, as only these could be
2134          implemented in Fortran 77.  */
2135       sym->ts.kind = gfc_default_double_kind;
2136       type = gfc_typenode_for_spec (&sym->ts);
2137       sym->ts.kind = gfc_default_real_kind;
2138     }
2139   else
2140     type = gfc_sym_type (sym);
2141
2142   type = build_function_type (type, typelist);
2143
2144   return type;
2145 }
2146 \f
2147 /* Language hooks for middle-end access to type nodes.  */
2148
2149 /* Return an integer type with BITS bits of precision,
2150    that is unsigned if UNSIGNEDP is nonzero, otherwise signed.  */
2151
2152 tree
2153 gfc_type_for_size (unsigned bits, int unsignedp)
2154 {
2155   if (!unsignedp)
2156     {
2157       int i;
2158       for (i = 0; i <= MAX_INT_KINDS; ++i)
2159         {
2160           tree type = gfc_integer_types[i];
2161           if (type && bits == TYPE_PRECISION (type))
2162             return type;
2163         }
2164
2165       /* Handle TImode as a special case because it is used by some backends
2166          (e.g. ARM) even though it is not available for normal use.  */
2167 #if HOST_BITS_PER_WIDE_INT >= 64
2168       if (bits == TYPE_PRECISION (intTI_type_node))
2169         return intTI_type_node;
2170 #endif
2171     }
2172   else
2173     {
2174       if (bits == TYPE_PRECISION (unsigned_intQI_type_node))
2175         return unsigned_intQI_type_node;
2176       if (bits == TYPE_PRECISION (unsigned_intHI_type_node))
2177         return unsigned_intHI_type_node;
2178       if (bits == TYPE_PRECISION (unsigned_intSI_type_node))
2179         return unsigned_intSI_type_node;
2180       if (bits == TYPE_PRECISION (unsigned_intDI_type_node))
2181         return unsigned_intDI_type_node;
2182       if (bits == TYPE_PRECISION (unsigned_intTI_type_node))
2183         return unsigned_intTI_type_node;
2184     }
2185
2186   return NULL_TREE;
2187 }
2188
2189 /* Return a data type that has machine mode MODE.  If the mode is an
2190    integer, then UNSIGNEDP selects between signed and unsigned types.  */
2191
2192 tree
2193 gfc_type_for_mode (enum machine_mode mode, int unsignedp)
2194 {
2195   int i;
2196   tree *base;
2197
2198   if (GET_MODE_CLASS (mode) == MODE_FLOAT)
2199     base = gfc_real_types;
2200   else if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
2201     base = gfc_complex_types;
2202   else if (SCALAR_INT_MODE_P (mode))
2203     return gfc_type_for_size (GET_MODE_PRECISION (mode), unsignedp);
2204   else if (VECTOR_MODE_P (mode))
2205     {
2206       enum machine_mode inner_mode = GET_MODE_INNER (mode);
2207       tree inner_type = gfc_type_for_mode (inner_mode, unsignedp);
2208       if (inner_type != NULL_TREE)
2209         return build_vector_type_for_mode (inner_type, mode);
2210       return NULL_TREE;
2211     }
2212   else
2213     return NULL_TREE;
2214
2215   for (i = 0; i <= MAX_REAL_KINDS; ++i)
2216     {
2217       tree type = base[i];
2218       if (type && mode == TYPE_MODE (type))
2219         return type;
2220     }
2221
2222   return NULL_TREE;
2223 }
2224
2225 /* Return TRUE if TYPE is a type with a hidden descriptor, fill in INFO
2226    in that case.  */
2227
2228 bool
2229 gfc_get_array_descr_info (const_tree type, struct array_descr_info *info)
2230 {
2231   int rank, dim;
2232   bool indirect = false;
2233   tree etype, ptype, field, t, base_decl;
2234   tree data_off, offset_off, dim_off, dim_size, elem_size;
2235   tree lower_suboff, upper_suboff, stride_suboff;
2236
2237   if (! GFC_DESCRIPTOR_TYPE_P (type))
2238     {
2239       if (! POINTER_TYPE_P (type))
2240         return false;
2241       type = TREE_TYPE (type);
2242       if (! GFC_DESCRIPTOR_TYPE_P (type))
2243         return false;
2244       indirect = true;
2245     }
2246
2247   rank = GFC_TYPE_ARRAY_RANK (type);
2248   if (rank >= (int) (sizeof (info->dimen) / sizeof (info->dimen[0])))
2249     return false;
2250
2251   etype = GFC_TYPE_ARRAY_DATAPTR_TYPE (type);
2252   gcc_assert (POINTER_TYPE_P (etype));
2253   etype = TREE_TYPE (etype);
2254   gcc_assert (TREE_CODE (etype) == ARRAY_TYPE);
2255   etype = TREE_TYPE (etype);
2256   /* Can't handle variable sized elements yet.  */
2257   if (int_size_in_bytes (etype) <= 0)
2258     return false;
2259   /* Nor non-constant lower bounds in assumed shape arrays.  */
2260   if (GFC_TYPE_ARRAY_AKIND (type) == GFC_ARRAY_ASSUMED_SHAPE)
2261     {
2262       for (dim = 0; dim < rank; dim++)
2263         if (GFC_TYPE_ARRAY_LBOUND (type, dim) == NULL_TREE
2264             || TREE_CODE (GFC_TYPE_ARRAY_LBOUND (type, dim)) != INTEGER_CST)
2265           return false;
2266     }
2267
2268   memset (info, '\0', sizeof (*info));
2269   info->ndimensions = rank;
2270   info->element_type = etype;
2271   ptype = build_pointer_type (gfc_array_index_type);
2272   if (indirect)
2273     {
2274       info->base_decl = build_decl (VAR_DECL, NULL_TREE,
2275                                     build_pointer_type (ptype));
2276       base_decl = build1 (INDIRECT_REF, ptype, info->base_decl);
2277     }
2278   else
2279     info->base_decl = base_decl = build_decl (VAR_DECL, NULL_TREE, ptype);
2280
2281   elem_size = fold_convert (gfc_array_index_type, TYPE_SIZE_UNIT (etype));
2282   field = TYPE_FIELDS (TYPE_MAIN_VARIANT (type));
2283   data_off = byte_position (field);
2284   field = TREE_CHAIN (field);
2285   offset_off = byte_position (field);
2286   field = TREE_CHAIN (field);
2287   field = TREE_CHAIN (field);
2288   dim_off = byte_position (field);
2289   dim_size = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (field)));
2290   field = TYPE_FIELDS (TREE_TYPE (TREE_TYPE (field)));
2291   stride_suboff = byte_position (field);
2292   field = TREE_CHAIN (field);
2293   lower_suboff = byte_position (field);
2294   field = TREE_CHAIN (field);
2295   upper_suboff = byte_position (field);
2296
2297   t = base_decl;
2298   if (!integer_zerop (data_off))
2299     t = build2 (POINTER_PLUS_EXPR, ptype, t, data_off);
2300   t = build1 (NOP_EXPR, build_pointer_type (ptr_type_node), t);
2301   info->data_location = build1 (INDIRECT_REF, ptr_type_node, t);
2302   if (GFC_TYPE_ARRAY_AKIND (type) == GFC_ARRAY_ALLOCATABLE)
2303     info->allocated = build2 (NE_EXPR, boolean_type_node,
2304                               info->data_location, null_pointer_node);
2305   else if (GFC_TYPE_ARRAY_AKIND (type) == GFC_ARRAY_POINTER)
2306     info->associated = build2 (NE_EXPR, boolean_type_node,
2307                                info->data_location, null_pointer_node);
2308
2309   for (dim = 0; dim < rank; dim++)
2310     {
2311       t = build2 (POINTER_PLUS_EXPR, ptype, base_decl,
2312                   size_binop (PLUS_EXPR, dim_off, lower_suboff));
2313       t = build1 (INDIRECT_REF, gfc_array_index_type, t);
2314       info->dimen[dim].lower_bound = t;
2315       t = build2 (POINTER_PLUS_EXPR, ptype, base_decl,
2316                   size_binop (PLUS_EXPR, dim_off, upper_suboff));
2317       t = build1 (INDIRECT_REF, gfc_array_index_type, t);
2318       info->dimen[dim].upper_bound = t;
2319       if (GFC_TYPE_ARRAY_AKIND (type) == GFC_ARRAY_ASSUMED_SHAPE)
2320         {
2321           /* Assumed shape arrays have known lower bounds.  */
2322           info->dimen[dim].upper_bound
2323             = build2 (MINUS_EXPR, gfc_array_index_type,
2324                       info->dimen[dim].upper_bound,
2325                       info->dimen[dim].lower_bound);
2326           info->dimen[dim].lower_bound
2327             = fold_convert (gfc_array_index_type,
2328                             GFC_TYPE_ARRAY_LBOUND (type, dim));
2329           info->dimen[dim].upper_bound
2330             = build2 (PLUS_EXPR, gfc_array_index_type,
2331                       info->dimen[dim].lower_bound,
2332                       info->dimen[dim].upper_bound);
2333         }
2334       t = build2 (POINTER_PLUS_EXPR, ptype, base_decl,
2335                   size_binop (PLUS_EXPR, dim_off, stride_suboff));
2336       t = build1 (INDIRECT_REF, gfc_array_index_type, t);
2337       t = build2 (MULT_EXPR, gfc_array_index_type, t, elem_size);
2338       info->dimen[dim].stride = t;
2339       dim_off = size_binop (PLUS_EXPR, dim_off, dim_size);
2340     }
2341
2342   return true;
2343 }
2344
2345 #include "gt-fortran-trans-types.h"