re PR fortran/38536 (ICE with C_LOC in resolve.c due to not properly going through...
[platform/upstream/gcc.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various structures.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
3    2010, 2011
4    Free Software Foundation, Inc.
5    Contributed by Andy Vaught
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 #include "config.h"
24 #include "system.h"
25 #include "flags.h"
26 #include "gfortran.h"
27 #include "obstack.h"
28 #include "bitmap.h"
29 #include "arith.h"  /* For gfc_compare_expr().  */
30 #include "dependency.h"
31 #include "data.h"
32 #include "target-memory.h" /* for gfc_simplify_transfer */
33 #include "constructor.h"
34
35 /* Types used in equivalence statements.  */
36
37 typedef enum seq_type
38 {
39   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
40 }
41 seq_type;
42
43 /* Stack to keep track of the nesting of blocks as we move through the
44    code.  See resolve_branch() and resolve_code().  */
45
46 typedef struct code_stack
47 {
48   struct gfc_code *head, *current;
49   struct code_stack *prev;
50
51   /* This bitmap keeps track of the targets valid for a branch from
52      inside this block except for END {IF|SELECT}s of enclosing
53      blocks.  */
54   bitmap reachable_labels;
55 }
56 code_stack;
57
58 static code_stack *cs_base = NULL;
59
60
61 /* Nonzero if we're inside a FORALL block.  */
62
63 static int forall_flag;
64
65 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
66
67 static int omp_workshare_flag;
68
69 /* Nonzero if we are processing a formal arglist. The corresponding function
70    resets the flag each time that it is read.  */
71 static int formal_arg_flag = 0;
72
73 /* True if we are resolving a specification expression.  */
74 static int specification_expr = 0;
75
76 /* The id of the last entry seen.  */
77 static int current_entry_id;
78
79 /* We use bitmaps to determine if a branch target is valid.  */
80 static bitmap_obstack labels_obstack;
81
82 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
83 static bool inquiry_argument = false;
84
85 int
86 gfc_is_formal_arg (void)
87 {
88   return formal_arg_flag;
89 }
90
91 /* Is the symbol host associated?  */
92 static bool
93 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
94 {
95   for (ns = ns->parent; ns; ns = ns->parent)
96     {      
97       if (sym->ns == ns)
98         return true;
99     }
100
101   return false;
102 }
103
104 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
105    an ABSTRACT derived-type.  If where is not NULL, an error message with that
106    locus is printed, optionally using name.  */
107
108 static gfc_try
109 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
110 {
111   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
112     {
113       if (where)
114         {
115           if (name)
116             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
117                        name, where, ts->u.derived->name);
118           else
119             gfc_error ("ABSTRACT type '%s' used at %L",
120                        ts->u.derived->name, where);
121         }
122
123       return FAILURE;
124     }
125
126   return SUCCESS;
127 }
128
129
130 static void resolve_symbol (gfc_symbol *sym);
131 static gfc_try resolve_intrinsic (gfc_symbol *sym, locus *loc);
132
133
134 /* Resolve the interface for a PROCEDURE declaration or procedure pointer.  */
135
136 static gfc_try
137 resolve_procedure_interface (gfc_symbol *sym)
138 {
139   if (sym->ts.interface == sym)
140     {
141       gfc_error ("PROCEDURE '%s' at %L may not be used as its own interface",
142                  sym->name, &sym->declared_at);
143       return FAILURE;
144     }
145   if (sym->ts.interface->attr.procedure)
146     {
147       gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared "
148                  "in a later PROCEDURE statement", sym->ts.interface->name,
149                  sym->name, &sym->declared_at);
150       return FAILURE;
151     }
152
153   /* Get the attributes from the interface (now resolved).  */
154   if (sym->ts.interface->attr.if_source || sym->ts.interface->attr.intrinsic)
155     {
156       gfc_symbol *ifc = sym->ts.interface;
157       resolve_symbol (ifc);
158
159       if (ifc->attr.intrinsic)
160         resolve_intrinsic (ifc, &ifc->declared_at);
161
162       if (ifc->result)
163         sym->ts = ifc->result->ts;
164       else   
165         sym->ts = ifc->ts;
166       sym->ts.interface = ifc;
167       sym->attr.function = ifc->attr.function;
168       sym->attr.subroutine = ifc->attr.subroutine;
169       gfc_copy_formal_args (sym, ifc);
170
171       sym->attr.allocatable = ifc->attr.allocatable;
172       sym->attr.pointer = ifc->attr.pointer;
173       sym->attr.pure = ifc->attr.pure;
174       sym->attr.elemental = ifc->attr.elemental;
175       sym->attr.dimension = ifc->attr.dimension;
176       sym->attr.contiguous = ifc->attr.contiguous;
177       sym->attr.recursive = ifc->attr.recursive;
178       sym->attr.always_explicit = ifc->attr.always_explicit;
179       sym->attr.ext_attr |= ifc->attr.ext_attr;
180       sym->attr.is_bind_c = ifc->attr.is_bind_c;
181       /* Copy array spec.  */
182       sym->as = gfc_copy_array_spec (ifc->as);
183       if (sym->as)
184         {
185           int i;
186           for (i = 0; i < sym->as->rank; i++)
187             {
188               gfc_expr_replace_symbols (sym->as->lower[i], sym);
189               gfc_expr_replace_symbols (sym->as->upper[i], sym);
190             }
191         }
192       /* Copy char length.  */
193       if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
194         {
195           sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
196           gfc_expr_replace_symbols (sym->ts.u.cl->length, sym);
197           if (sym->ts.u.cl->length && !sym->ts.u.cl->resolved
198               && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
199             return FAILURE;
200         }
201     }
202   else if (sym->ts.interface->name[0] != '\0')
203     {
204       gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
205                  sym->ts.interface->name, sym->name, &sym->declared_at);
206       return FAILURE;
207     }
208
209   return SUCCESS;
210 }
211
212
213 /* Resolve types of formal argument lists.  These have to be done early so that
214    the formal argument lists of module procedures can be copied to the
215    containing module before the individual procedures are resolved
216    individually.  We also resolve argument lists of procedures in interface
217    blocks because they are self-contained scoping units.
218
219    Since a dummy argument cannot be a non-dummy procedure, the only
220    resort left for untyped names are the IMPLICIT types.  */
221
222 static void
223 resolve_formal_arglist (gfc_symbol *proc)
224 {
225   gfc_formal_arglist *f;
226   gfc_symbol *sym;
227   int i;
228
229   if (proc->result != NULL)
230     sym = proc->result;
231   else
232     sym = proc;
233
234   if (gfc_elemental (proc)
235       || sym->attr.pointer || sym->attr.allocatable
236       || (sym->as && sym->as->rank > 0))
237     {
238       proc->attr.always_explicit = 1;
239       sym->attr.always_explicit = 1;
240     }
241
242   formal_arg_flag = 1;
243
244   for (f = proc->formal; f; f = f->next)
245     {
246       sym = f->sym;
247
248       if (sym == NULL)
249         {
250           /* Alternate return placeholder.  */
251           if (gfc_elemental (proc))
252             gfc_error ("Alternate return specifier in elemental subroutine "
253                        "'%s' at %L is not allowed", proc->name,
254                        &proc->declared_at);
255           if (proc->attr.function)
256             gfc_error ("Alternate return specifier in function "
257                        "'%s' at %L is not allowed", proc->name,
258                        &proc->declared_at);
259           continue;
260         }
261       else if (sym->attr.procedure && sym->ts.interface
262                && sym->attr.if_source != IFSRC_DECL)
263         resolve_procedure_interface (sym);
264
265       if (sym->attr.if_source != IFSRC_UNKNOWN)
266         resolve_formal_arglist (sym);
267
268       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
269         {
270           if (gfc_pure (proc) && !gfc_pure (sym))
271             {
272               gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
273                          "also be PURE", sym->name, &sym->declared_at);
274               continue;
275             }
276
277           if (proc->attr.implicit_pure && !gfc_pure(sym))
278             proc->attr.implicit_pure = 0;
279
280           if (gfc_elemental (proc))
281             {
282               gfc_error ("Dummy procedure at %L not allowed in ELEMENTAL "
283                          "procedure", &sym->declared_at);
284               continue;
285             }
286
287           if (sym->attr.function
288                 && sym->ts.type == BT_UNKNOWN
289                 && sym->attr.intrinsic)
290             {
291               gfc_intrinsic_sym *isym;
292               isym = gfc_find_function (sym->name);
293               if (isym == NULL || !isym->specific)
294                 {
295                   gfc_error ("Unable to find a specific INTRINSIC procedure "
296                              "for the reference '%s' at %L", sym->name,
297                              &sym->declared_at);
298                 }
299               sym->ts = isym->ts;
300             }
301
302           continue;
303         }
304
305       if (sym->ts.type == BT_UNKNOWN && !proc->attr.intrinsic
306           && (!sym->attr.function || sym->result == sym))
307         gfc_set_default_type (sym, 1, sym->ns);
308
309       gfc_resolve_array_spec (sym->as, 0);
310
311       /* We can't tell if an array with dimension (:) is assumed or deferred
312          shape until we know if it has the pointer or allocatable attributes.
313       */
314       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
315           && !(sym->attr.pointer || sym->attr.allocatable))
316         {
317           sym->as->type = AS_ASSUMED_SHAPE;
318           for (i = 0; i < sym->as->rank; i++)
319             sym->as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind,
320                                                   NULL, 1);
321         }
322
323       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
324           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
325           || sym->attr.optional)
326         {
327           proc->attr.always_explicit = 1;
328           if (proc->result)
329             proc->result->attr.always_explicit = 1;
330         }
331
332       /* If the flavor is unknown at this point, it has to be a variable.
333          A procedure specification would have already set the type.  */
334
335       if (sym->attr.flavor == FL_UNKNOWN)
336         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
337
338       if (gfc_pure (proc) && !sym->attr.pointer
339           && sym->attr.flavor != FL_PROCEDURE)
340         {
341           if (proc->attr.function && sym->attr.intent != INTENT_IN)
342             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
343                        "INTENT(IN)", sym->name, proc->name,
344                        &sym->declared_at);
345
346           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
347             gfc_error ("Argument '%s' of pure subroutine '%s' at %L must "
348                        "have its INTENT specified", sym->name, proc->name,
349                        &sym->declared_at);
350         }
351
352       if (proc->attr.implicit_pure && !sym->attr.pointer
353           && sym->attr.flavor != FL_PROCEDURE)
354         {
355           if (proc->attr.function && sym->attr.intent != INTENT_IN)
356             proc->attr.implicit_pure = 0;
357
358           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
359             proc->attr.implicit_pure = 0;
360         }
361
362       if (gfc_elemental (proc))
363         {
364           /* F2008, C1289.  */
365           if (sym->attr.codimension)
366             {
367               gfc_error ("Coarray dummy argument '%s' at %L to elemental "
368                          "procedure", sym->name, &sym->declared_at);
369               continue;
370             }
371
372           if (sym->as != NULL)
373             {
374               gfc_error ("Argument '%s' of elemental procedure at %L must "
375                          "be scalar", sym->name, &sym->declared_at);
376               continue;
377             }
378
379           if (sym->attr.allocatable)
380             {
381               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
382                          "have the ALLOCATABLE attribute", sym->name,
383                          &sym->declared_at);
384               continue;
385             }
386
387           if (sym->attr.pointer)
388             {
389               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
390                          "have the POINTER attribute", sym->name,
391                          &sym->declared_at);
392               continue;
393             }
394
395           if (sym->attr.flavor == FL_PROCEDURE)
396             {
397               gfc_error ("Dummy procedure '%s' not allowed in elemental "
398                          "procedure '%s' at %L", sym->name, proc->name,
399                          &sym->declared_at);
400               continue;
401             }
402
403           if (sym->attr.intent == INTENT_UNKNOWN)
404             {
405               gfc_error ("Argument '%s' of elemental procedure '%s' at %L must "
406                          "have its INTENT specified", sym->name, proc->name,
407                          &sym->declared_at);
408               continue;
409             }
410         }
411
412       /* Each dummy shall be specified to be scalar.  */
413       if (proc->attr.proc == PROC_ST_FUNCTION)
414         {
415           if (sym->as != NULL)
416             {
417               gfc_error ("Argument '%s' of statement function at %L must "
418                          "be scalar", sym->name, &sym->declared_at);
419               continue;
420             }
421
422           if (sym->ts.type == BT_CHARACTER)
423             {
424               gfc_charlen *cl = sym->ts.u.cl;
425               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
426                 {
427                   gfc_error ("Character-valued argument '%s' of statement "
428                              "function at %L must have constant length",
429                              sym->name, &sym->declared_at);
430                   continue;
431                 }
432             }
433         }
434     }
435   formal_arg_flag = 0;
436 }
437
438
439 /* Work function called when searching for symbols that have argument lists
440    associated with them.  */
441
442 static void
443 find_arglists (gfc_symbol *sym)
444 {
445   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
446     return;
447
448   resolve_formal_arglist (sym);
449 }
450
451
452 /* Given a namespace, resolve all formal argument lists within the namespace.
453  */
454
455 static void
456 resolve_formal_arglists (gfc_namespace *ns)
457 {
458   if (ns == NULL)
459     return;
460
461   gfc_traverse_ns (ns, find_arglists);
462 }
463
464
465 static void
466 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
467 {
468   gfc_try t;
469
470   /* If this namespace is not a function or an entry master function,
471      ignore it.  */
472   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
473       || sym->attr.entry_master)
474     return;
475
476   /* Try to find out of what the return type is.  */
477   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
478     {
479       t = gfc_set_default_type (sym->result, 0, ns);
480
481       if (t == FAILURE && !sym->result->attr.untyped)
482         {
483           if (sym->result == sym)
484             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
485                        sym->name, &sym->declared_at);
486           else if (!sym->result->attr.proc_pointer)
487             gfc_error ("Result '%s' of contained function '%s' at %L has "
488                        "no IMPLICIT type", sym->result->name, sym->name,
489                        &sym->result->declared_at);
490           sym->result->attr.untyped = 1;
491         }
492     }
493
494   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character 
495      type, lists the only ways a character length value of * can be used:
496      dummy arguments of procedures, named constants, and function results
497      in external functions.  Internal function results and results of module
498      procedures are not on this list, ergo, not permitted.  */
499
500   if (sym->result->ts.type == BT_CHARACTER)
501     {
502       gfc_charlen *cl = sym->result->ts.u.cl;
503       if (!cl || !cl->length)
504         {
505           /* See if this is a module-procedure and adapt error message
506              accordingly.  */
507           bool module_proc;
508           gcc_assert (ns->parent && ns->parent->proc_name);
509           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
510
511           gfc_error ("Character-valued %s '%s' at %L must not be"
512                      " assumed length",
513                      module_proc ? _("module procedure")
514                                  : _("internal function"),
515                      sym->name, &sym->declared_at);
516         }
517     }
518 }
519
520
521 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
522    introduce duplicates.  */
523
524 static void
525 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
526 {
527   gfc_formal_arglist *f, *new_arglist;
528   gfc_symbol *new_sym;
529
530   for (; new_args != NULL; new_args = new_args->next)
531     {
532       new_sym = new_args->sym;
533       /* See if this arg is already in the formal argument list.  */
534       for (f = proc->formal; f; f = f->next)
535         {
536           if (new_sym == f->sym)
537             break;
538         }
539
540       if (f)
541         continue;
542
543       /* Add a new argument.  Argument order is not important.  */
544       new_arglist = gfc_get_formal_arglist ();
545       new_arglist->sym = new_sym;
546       new_arglist->next = proc->formal;
547       proc->formal  = new_arglist;
548     }
549 }
550
551
552 /* Flag the arguments that are not present in all entries.  */
553
554 static void
555 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
556 {
557   gfc_formal_arglist *f, *head;
558   head = new_args;
559
560   for (f = proc->formal; f; f = f->next)
561     {
562       if (f->sym == NULL)
563         continue;
564
565       for (new_args = head; new_args; new_args = new_args->next)
566         {
567           if (new_args->sym == f->sym)
568             break;
569         }
570
571       if (new_args)
572         continue;
573
574       f->sym->attr.not_always_present = 1;
575     }
576 }
577
578
579 /* Resolve alternate entry points.  If a symbol has multiple entry points we
580    create a new master symbol for the main routine, and turn the existing
581    symbol into an entry point.  */
582
583 static void
584 resolve_entries (gfc_namespace *ns)
585 {
586   gfc_namespace *old_ns;
587   gfc_code *c;
588   gfc_symbol *proc;
589   gfc_entry_list *el;
590   char name[GFC_MAX_SYMBOL_LEN + 1];
591   static int master_count = 0;
592
593   if (ns->proc_name == NULL)
594     return;
595
596   /* No need to do anything if this procedure doesn't have alternate entry
597      points.  */
598   if (!ns->entries)
599     return;
600
601   /* We may already have resolved alternate entry points.  */
602   if (ns->proc_name->attr.entry_master)
603     return;
604
605   /* If this isn't a procedure something has gone horribly wrong.  */
606   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
607
608   /* Remember the current namespace.  */
609   old_ns = gfc_current_ns;
610
611   gfc_current_ns = ns;
612
613   /* Add the main entry point to the list of entry points.  */
614   el = gfc_get_entry_list ();
615   el->sym = ns->proc_name;
616   el->id = 0;
617   el->next = ns->entries;
618   ns->entries = el;
619   ns->proc_name->attr.entry = 1;
620
621   /* If it is a module function, it needs to be in the right namespace
622      so that gfc_get_fake_result_decl can gather up the results. The
623      need for this arose in get_proc_name, where these beasts were
624      left in their own namespace, to keep prior references linked to
625      the entry declaration.*/
626   if (ns->proc_name->attr.function
627       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
628     el->sym->ns = ns;
629
630   /* Do the same for entries where the master is not a module
631      procedure.  These are retained in the module namespace because
632      of the module procedure declaration.  */
633   for (el = el->next; el; el = el->next)
634     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
635           && el->sym->attr.mod_proc)
636       el->sym->ns = ns;
637   el = ns->entries;
638
639   /* Add an entry statement for it.  */
640   c = gfc_get_code ();
641   c->op = EXEC_ENTRY;
642   c->ext.entry = el;
643   c->next = ns->code;
644   ns->code = c;
645
646   /* Create a new symbol for the master function.  */
647   /* Give the internal function a unique name (within this file).
648      Also include the function name so the user has some hope of figuring
649      out what is going on.  */
650   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
651             master_count++, ns->proc_name->name);
652   gfc_get_ha_symbol (name, &proc);
653   gcc_assert (proc != NULL);
654
655   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
656   if (ns->proc_name->attr.subroutine)
657     gfc_add_subroutine (&proc->attr, proc->name, NULL);
658   else
659     {
660       gfc_symbol *sym;
661       gfc_typespec *ts, *fts;
662       gfc_array_spec *as, *fas;
663       gfc_add_function (&proc->attr, proc->name, NULL);
664       proc->result = proc;
665       fas = ns->entries->sym->as;
666       fas = fas ? fas : ns->entries->sym->result->as;
667       fts = &ns->entries->sym->result->ts;
668       if (fts->type == BT_UNKNOWN)
669         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
670       for (el = ns->entries->next; el; el = el->next)
671         {
672           ts = &el->sym->result->ts;
673           as = el->sym->as;
674           as = as ? as : el->sym->result->as;
675           if (ts->type == BT_UNKNOWN)
676             ts = gfc_get_default_type (el->sym->result->name, NULL);
677
678           if (! gfc_compare_types (ts, fts)
679               || (el->sym->result->attr.dimension
680                   != ns->entries->sym->result->attr.dimension)
681               || (el->sym->result->attr.pointer
682                   != ns->entries->sym->result->attr.pointer))
683             break;
684           else if (as && fas && ns->entries->sym->result != el->sym->result
685                       && gfc_compare_array_spec (as, fas) == 0)
686             gfc_error ("Function %s at %L has entries with mismatched "
687                        "array specifications", ns->entries->sym->name,
688                        &ns->entries->sym->declared_at);
689           /* The characteristics need to match and thus both need to have
690              the same string length, i.e. both len=*, or both len=4.
691              Having both len=<variable> is also possible, but difficult to
692              check at compile time.  */
693           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
694                    && (((ts->u.cl->length && !fts->u.cl->length)
695                         ||(!ts->u.cl->length && fts->u.cl->length))
696                        || (ts->u.cl->length
697                            && ts->u.cl->length->expr_type
698                               != fts->u.cl->length->expr_type)
699                        || (ts->u.cl->length
700                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
701                            && mpz_cmp (ts->u.cl->length->value.integer,
702                                        fts->u.cl->length->value.integer) != 0)))
703             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
704                             "entries returning variables of different "
705                             "string lengths", ns->entries->sym->name,
706                             &ns->entries->sym->declared_at);
707         }
708
709       if (el == NULL)
710         {
711           sym = ns->entries->sym->result;
712           /* All result types the same.  */
713           proc->ts = *fts;
714           if (sym->attr.dimension)
715             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
716           if (sym->attr.pointer)
717             gfc_add_pointer (&proc->attr, NULL);
718         }
719       else
720         {
721           /* Otherwise the result will be passed through a union by
722              reference.  */
723           proc->attr.mixed_entry_master = 1;
724           for (el = ns->entries; el; el = el->next)
725             {
726               sym = el->sym->result;
727               if (sym->attr.dimension)
728                 {
729                   if (el == ns->entries)
730                     gfc_error ("FUNCTION result %s can't be an array in "
731                                "FUNCTION %s at %L", sym->name,
732                                ns->entries->sym->name, &sym->declared_at);
733                   else
734                     gfc_error ("ENTRY result %s can't be an array in "
735                                "FUNCTION %s at %L", sym->name,
736                                ns->entries->sym->name, &sym->declared_at);
737                 }
738               else if (sym->attr.pointer)
739                 {
740                   if (el == ns->entries)
741                     gfc_error ("FUNCTION result %s can't be a POINTER in "
742                                "FUNCTION %s at %L", sym->name,
743                                ns->entries->sym->name, &sym->declared_at);
744                   else
745                     gfc_error ("ENTRY result %s can't be a POINTER in "
746                                "FUNCTION %s at %L", sym->name,
747                                ns->entries->sym->name, &sym->declared_at);
748                 }
749               else
750                 {
751                   ts = &sym->ts;
752                   if (ts->type == BT_UNKNOWN)
753                     ts = gfc_get_default_type (sym->name, NULL);
754                   switch (ts->type)
755                     {
756                     case BT_INTEGER:
757                       if (ts->kind == gfc_default_integer_kind)
758                         sym = NULL;
759                       break;
760                     case BT_REAL:
761                       if (ts->kind == gfc_default_real_kind
762                           || ts->kind == gfc_default_double_kind)
763                         sym = NULL;
764                       break;
765                     case BT_COMPLEX:
766                       if (ts->kind == gfc_default_complex_kind)
767                         sym = NULL;
768                       break;
769                     case BT_LOGICAL:
770                       if (ts->kind == gfc_default_logical_kind)
771                         sym = NULL;
772                       break;
773                     case BT_UNKNOWN:
774                       /* We will issue error elsewhere.  */
775                       sym = NULL;
776                       break;
777                     default:
778                       break;
779                     }
780                   if (sym)
781                     {
782                       if (el == ns->entries)
783                         gfc_error ("FUNCTION result %s can't be of type %s "
784                                    "in FUNCTION %s at %L", sym->name,
785                                    gfc_typename (ts), ns->entries->sym->name,
786                                    &sym->declared_at);
787                       else
788                         gfc_error ("ENTRY result %s can't be of type %s "
789                                    "in FUNCTION %s at %L", sym->name,
790                                    gfc_typename (ts), ns->entries->sym->name,
791                                    &sym->declared_at);
792                     }
793                 }
794             }
795         }
796     }
797   proc->attr.access = ACCESS_PRIVATE;
798   proc->attr.entry_master = 1;
799
800   /* Merge all the entry point arguments.  */
801   for (el = ns->entries; el; el = el->next)
802     merge_argument_lists (proc, el->sym->formal);
803
804   /* Check the master formal arguments for any that are not
805      present in all entry points.  */
806   for (el = ns->entries; el; el = el->next)
807     check_argument_lists (proc, el->sym->formal);
808
809   /* Use the master function for the function body.  */
810   ns->proc_name = proc;
811
812   /* Finalize the new symbols.  */
813   gfc_commit_symbols ();
814
815   /* Restore the original namespace.  */
816   gfc_current_ns = old_ns;
817 }
818
819
820 /* Resolve common variables.  */
821 static void
822 resolve_common_vars (gfc_symbol *sym, bool named_common)
823 {
824   gfc_symbol *csym = sym;
825
826   for (; csym; csym = csym->common_next)
827     {
828       if (csym->value || csym->attr.data)
829         {
830           if (!csym->ns->is_block_data)
831             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
832                             "but only in BLOCK DATA initialization is "
833                             "allowed", csym->name, &csym->declared_at);
834           else if (!named_common)
835             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
836                             "in a blank COMMON but initialization is only "
837                             "allowed in named common blocks", csym->name,
838                             &csym->declared_at);
839         }
840
841       if (csym->ts.type != BT_DERIVED)
842         continue;
843
844       if (!(csym->ts.u.derived->attr.sequence
845             || csym->ts.u.derived->attr.is_bind_c))
846         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
847                        "has neither the SEQUENCE nor the BIND(C) "
848                        "attribute", csym->name, &csym->declared_at);
849       if (csym->ts.u.derived->attr.alloc_comp)
850         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
851                        "has an ultimate component that is "
852                        "allocatable", csym->name, &csym->declared_at);
853       if (gfc_has_default_initializer (csym->ts.u.derived))
854         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
855                        "may not have default initializer", csym->name,
856                        &csym->declared_at);
857
858       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
859         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
860     }
861 }
862
863 /* Resolve common blocks.  */
864 static void
865 resolve_common_blocks (gfc_symtree *common_root)
866 {
867   gfc_symbol *sym;
868
869   if (common_root == NULL)
870     return;
871
872   if (common_root->left)
873     resolve_common_blocks (common_root->left);
874   if (common_root->right)
875     resolve_common_blocks (common_root->right);
876
877   resolve_common_vars (common_root->n.common->head, true);
878
879   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
880   if (sym == NULL)
881     return;
882
883   if (sym->attr.flavor == FL_PARAMETER)
884     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
885                sym->name, &common_root->n.common->where, &sym->declared_at);
886
887   if (sym->attr.intrinsic)
888     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
889                sym->name, &common_root->n.common->where);
890   else if (sym->attr.result
891            || gfc_is_function_return_value (sym, gfc_current_ns))
892     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
893                     "that is also a function result", sym->name,
894                     &common_root->n.common->where);
895   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
896            && sym->attr.proc != PROC_ST_FUNCTION)
897     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
898                     "that is also a global procedure", sym->name,
899                     &common_root->n.common->where);
900 }
901
902
903 /* Resolve contained function types.  Because contained functions can call one
904    another, they have to be worked out before any of the contained procedures
905    can be resolved.
906
907    The good news is that if a function doesn't already have a type, the only
908    way it can get one is through an IMPLICIT type or a RESULT variable, because
909    by definition contained functions are contained namespace they're contained
910    in, not in a sibling or parent namespace.  */
911
912 static void
913 resolve_contained_functions (gfc_namespace *ns)
914 {
915   gfc_namespace *child;
916   gfc_entry_list *el;
917
918   resolve_formal_arglists (ns);
919
920   for (child = ns->contained; child; child = child->sibling)
921     {
922       /* Resolve alternate entry points first.  */
923       resolve_entries (child);
924
925       /* Then check function return types.  */
926       resolve_contained_fntype (child->proc_name, child);
927       for (el = child->entries; el; el = el->next)
928         resolve_contained_fntype (el->sym, child);
929     }
930 }
931
932
933 /* Resolve all of the elements of a structure constructor and make sure that
934    the types are correct. The 'init' flag indicates that the given
935    constructor is an initializer.  */
936
937 static gfc_try
938 resolve_structure_cons (gfc_expr *expr, int init)
939 {
940   gfc_constructor *cons;
941   gfc_component *comp;
942   gfc_try t;
943   symbol_attribute a;
944
945   t = SUCCESS;
946
947   if (expr->ts.type == BT_DERIVED)
948     resolve_symbol (expr->ts.u.derived);
949
950   cons = gfc_constructor_first (expr->value.constructor);
951   /* A constructor may have references if it is the result of substituting a
952      parameter variable.  In this case we just pull out the component we
953      want.  */
954   if (expr->ref)
955     comp = expr->ref->u.c.sym->components;
956   else
957     comp = expr->ts.u.derived->components;
958
959   /* See if the user is trying to invoke a structure constructor for one of
960      the iso_c_binding derived types.  */
961   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
962       && expr->ts.u.derived->ts.is_iso_c && cons
963       && (cons->expr == NULL || cons->expr->expr_type != EXPR_NULL))
964     {
965       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
966                  expr->ts.u.derived->name, &(expr->where));
967       return FAILURE;
968     }
969
970   /* Return if structure constructor is c_null_(fun)prt.  */
971   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
972       && expr->ts.u.derived->ts.is_iso_c && cons
973       && cons->expr && cons->expr->expr_type == EXPR_NULL)
974     return SUCCESS;
975
976   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
977     {
978       int rank;
979
980       if (!cons->expr)
981         continue;
982
983       if (gfc_resolve_expr (cons->expr) == FAILURE)
984         {
985           t = FAILURE;
986           continue;
987         }
988
989       rank = comp->as ? comp->as->rank : 0;
990       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
991           && (comp->attr.allocatable || cons->expr->rank))
992         {
993           gfc_error ("The rank of the element in the derived type "
994                      "constructor at %L does not match that of the "
995                      "component (%d/%d)", &cons->expr->where,
996                      cons->expr->rank, rank);
997           t = FAILURE;
998         }
999
1000       /* If we don't have the right type, try to convert it.  */
1001
1002       if (!comp->attr.proc_pointer &&
1003           !gfc_compare_types (&cons->expr->ts, &comp->ts))
1004         {
1005           t = FAILURE;
1006           if (strcmp (comp->name, "_extends") == 0)
1007             {
1008               /* Can afford to be brutal with the _extends initializer.
1009                  The derived type can get lost because it is PRIVATE
1010                  but it is not usage constrained by the standard.  */
1011               cons->expr->ts = comp->ts;
1012               t = SUCCESS;
1013             }
1014           else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
1015             gfc_error ("The element in the derived type constructor at %L, "
1016                        "for pointer component '%s', is %s but should be %s",
1017                        &cons->expr->where, comp->name,
1018                        gfc_basic_typename (cons->expr->ts.type),
1019                        gfc_basic_typename (comp->ts.type));
1020           else
1021             t = gfc_convert_type (cons->expr, &comp->ts, 1);
1022         }
1023
1024       /* For strings, the length of the constructor should be the same as
1025          the one of the structure, ensure this if the lengths are known at
1026          compile time and when we are dealing with PARAMETER or structure
1027          constructors.  */
1028       if (cons->expr->ts.type == BT_CHARACTER && comp->ts.u.cl
1029           && comp->ts.u.cl->length
1030           && comp->ts.u.cl->length->expr_type == EXPR_CONSTANT
1031           && cons->expr->ts.u.cl && cons->expr->ts.u.cl->length
1032           && cons->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
1033           && mpz_cmp (cons->expr->ts.u.cl->length->value.integer,
1034                       comp->ts.u.cl->length->value.integer) != 0)
1035         {
1036           if (cons->expr->expr_type == EXPR_VARIABLE
1037               && cons->expr->symtree->n.sym->attr.flavor == FL_PARAMETER)
1038             {
1039               /* Wrap the parameter in an array constructor (EXPR_ARRAY)
1040                  to make use of the gfc_resolve_character_array_constructor
1041                  machinery.  The expression is later simplified away to
1042                  an array of string literals.  */
1043               gfc_expr *para = cons->expr;
1044               cons->expr = gfc_get_expr ();
1045               cons->expr->ts = para->ts;
1046               cons->expr->where = para->where;
1047               cons->expr->expr_type = EXPR_ARRAY;
1048               cons->expr->rank = para->rank;
1049               cons->expr->shape = gfc_copy_shape (para->shape, para->rank);
1050               gfc_constructor_append_expr (&cons->expr->value.constructor,
1051                                            para, &cons->expr->where);
1052             }
1053           if (cons->expr->expr_type == EXPR_ARRAY)
1054             {
1055               gfc_constructor *p;
1056               p = gfc_constructor_first (cons->expr->value.constructor);
1057               if (cons->expr->ts.u.cl != p->expr->ts.u.cl)
1058                 {
1059                   gfc_charlen *cl, *cl2;
1060
1061                   cl2 = NULL;
1062                   for (cl = gfc_current_ns->cl_list; cl; cl = cl->next)
1063                     {
1064                       if (cl == cons->expr->ts.u.cl)
1065                         break;
1066                       cl2 = cl;
1067                     }
1068
1069                   gcc_assert (cl);
1070
1071                   if (cl2)
1072                     cl2->next = cl->next;
1073
1074                   gfc_free_expr (cl->length);
1075                   gfc_free (cl);
1076                 }
1077
1078               cons->expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1079               cons->expr->ts.u.cl->length_from_typespec = true;
1080               cons->expr->ts.u.cl->length = gfc_copy_expr (comp->ts.u.cl->length);
1081               gfc_resolve_character_array_constructor (cons->expr);
1082             }
1083         }
1084
1085       if (cons->expr->expr_type == EXPR_NULL
1086           && !(comp->attr.pointer || comp->attr.allocatable
1087                || comp->attr.proc_pointer
1088                || (comp->ts.type == BT_CLASS
1089                    && (CLASS_DATA (comp)->attr.class_pointer
1090                        || CLASS_DATA (comp)->attr.allocatable))))
1091         {
1092           t = FAILURE;
1093           gfc_error ("The NULL in the derived type constructor at %L is "
1094                      "being applied to component '%s', which is neither "
1095                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
1096                      comp->name);
1097         }
1098
1099       if (!comp->attr.pointer || comp->attr.proc_pointer
1100           || cons->expr->expr_type == EXPR_NULL)
1101         continue;
1102
1103       a = gfc_expr_attr (cons->expr);
1104
1105       if (!a.pointer && !a.target)
1106         {
1107           t = FAILURE;
1108           gfc_error ("The element in the derived type constructor at %L, "
1109                      "for pointer component '%s' should be a POINTER or "
1110                      "a TARGET", &cons->expr->where, comp->name);
1111         }
1112
1113       if (init)
1114         {
1115           /* F08:C461. Additional checks for pointer initialization.  */
1116           if (a.allocatable)
1117             {
1118               t = FAILURE;
1119               gfc_error ("Pointer initialization target at %L "
1120                          "must not be ALLOCATABLE ", &cons->expr->where);
1121             }
1122           if (!a.save)
1123             {
1124               t = FAILURE;
1125               gfc_error ("Pointer initialization target at %L "
1126                          "must have the SAVE attribute", &cons->expr->where);
1127             }
1128         }
1129
1130       /* F2003, C1272 (3).  */
1131       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
1132           && (gfc_impure_variable (cons->expr->symtree->n.sym)
1133               || gfc_is_coindexed (cons->expr)))
1134         {
1135           t = FAILURE;
1136           gfc_error ("Invalid expression in the derived type constructor for "
1137                      "pointer component '%s' at %L in PURE procedure",
1138                      comp->name, &cons->expr->where);
1139         }
1140
1141       if (gfc_implicit_pure (NULL)
1142             && cons->expr->expr_type == EXPR_VARIABLE
1143             && (gfc_impure_variable (cons->expr->symtree->n.sym)
1144                 || gfc_is_coindexed (cons->expr)))
1145         gfc_current_ns->proc_name->attr.implicit_pure = 0;
1146
1147     }
1148
1149   return t;
1150 }
1151
1152
1153 /****************** Expression name resolution ******************/
1154
1155 /* Returns 0 if a symbol was not declared with a type or
1156    attribute declaration statement, nonzero otherwise.  */
1157
1158 static int
1159 was_declared (gfc_symbol *sym)
1160 {
1161   symbol_attribute a;
1162
1163   a = sym->attr;
1164
1165   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
1166     return 1;
1167
1168   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
1169       || a.optional || a.pointer || a.save || a.target || a.volatile_
1170       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
1171       || a.asynchronous || a.codimension)
1172     return 1;
1173
1174   return 0;
1175 }
1176
1177
1178 /* Determine if a symbol is generic or not.  */
1179
1180 static int
1181 generic_sym (gfc_symbol *sym)
1182 {
1183   gfc_symbol *s;
1184
1185   if (sym->attr.generic ||
1186       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
1187     return 1;
1188
1189   if (was_declared (sym) || sym->ns->parent == NULL)
1190     return 0;
1191
1192   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1193   
1194   if (s != NULL)
1195     {
1196       if (s == sym)
1197         return 0;
1198       else
1199         return generic_sym (s);
1200     }
1201
1202   return 0;
1203 }
1204
1205
1206 /* Determine if a symbol is specific or not.  */
1207
1208 static int
1209 specific_sym (gfc_symbol *sym)
1210 {
1211   gfc_symbol *s;
1212
1213   if (sym->attr.if_source == IFSRC_IFBODY
1214       || sym->attr.proc == PROC_MODULE
1215       || sym->attr.proc == PROC_INTERNAL
1216       || sym->attr.proc == PROC_ST_FUNCTION
1217       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1218       || sym->attr.external)
1219     return 1;
1220
1221   if (was_declared (sym) || sym->ns->parent == NULL)
1222     return 0;
1223
1224   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1225
1226   return (s == NULL) ? 0 : specific_sym (s);
1227 }
1228
1229
1230 /* Figure out if the procedure is specific, generic or unknown.  */
1231
1232 typedef enum
1233 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1234 proc_type;
1235
1236 static proc_type
1237 procedure_kind (gfc_symbol *sym)
1238 {
1239   if (generic_sym (sym))
1240     return PTYPE_GENERIC;
1241
1242   if (specific_sym (sym))
1243     return PTYPE_SPECIFIC;
1244
1245   return PTYPE_UNKNOWN;
1246 }
1247
1248 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1249    is nonzero when matching actual arguments.  */
1250
1251 static int need_full_assumed_size = 0;
1252
1253 static bool
1254 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1255 {
1256   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1257       return false;
1258
1259   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1260      What should it be?  */
1261   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1262           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1263                && (e->ref->u.ar.type == AR_FULL))
1264     {
1265       gfc_error ("The upper bound in the last dimension must "
1266                  "appear in the reference to the assumed size "
1267                  "array '%s' at %L", sym->name, &e->where);
1268       return true;
1269     }
1270   return false;
1271 }
1272
1273
1274 /* Look for bad assumed size array references in argument expressions
1275   of elemental and array valued intrinsic procedures.  Since this is
1276   called from procedure resolution functions, it only recurses at
1277   operators.  */
1278
1279 static bool
1280 resolve_assumed_size_actual (gfc_expr *e)
1281 {
1282   if (e == NULL)
1283    return false;
1284
1285   switch (e->expr_type)
1286     {
1287     case EXPR_VARIABLE:
1288       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1289         return true;
1290       break;
1291
1292     case EXPR_OP:
1293       if (resolve_assumed_size_actual (e->value.op.op1)
1294           || resolve_assumed_size_actual (e->value.op.op2))
1295         return true;
1296       break;
1297
1298     default:
1299       break;
1300     }
1301   return false;
1302 }
1303
1304
1305 /* Check a generic procedure, passed as an actual argument, to see if
1306    there is a matching specific name.  If none, it is an error, and if
1307    more than one, the reference is ambiguous.  */
1308 static int
1309 count_specific_procs (gfc_expr *e)
1310 {
1311   int n;
1312   gfc_interface *p;
1313   gfc_symbol *sym;
1314         
1315   n = 0;
1316   sym = e->symtree->n.sym;
1317
1318   for (p = sym->generic; p; p = p->next)
1319     if (strcmp (sym->name, p->sym->name) == 0)
1320       {
1321         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1322                                        sym->name);
1323         n++;
1324       }
1325
1326   if (n > 1)
1327     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1328                &e->where);
1329
1330   if (n == 0)
1331     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1332                "argument at %L", sym->name, &e->where);
1333
1334   return n;
1335 }
1336
1337
1338 /* See if a call to sym could possibly be a not allowed RECURSION because of
1339    a missing RECURIVE declaration.  This means that either sym is the current
1340    context itself, or sym is the parent of a contained procedure calling its
1341    non-RECURSIVE containing procedure.
1342    This also works if sym is an ENTRY.  */
1343
1344 static bool
1345 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1346 {
1347   gfc_symbol* proc_sym;
1348   gfc_symbol* context_proc;
1349   gfc_namespace* real_context;
1350
1351   if (sym->attr.flavor == FL_PROGRAM)
1352     return false;
1353
1354   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1355
1356   /* If we've got an ENTRY, find real procedure.  */
1357   if (sym->attr.entry && sym->ns->entries)
1358     proc_sym = sym->ns->entries->sym;
1359   else
1360     proc_sym = sym;
1361
1362   /* If sym is RECURSIVE, all is well of course.  */
1363   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1364     return false;
1365
1366   /* Find the context procedure's "real" symbol if it has entries.
1367      We look for a procedure symbol, so recurse on the parents if we don't
1368      find one (like in case of a BLOCK construct).  */
1369   for (real_context = context; ; real_context = real_context->parent)
1370     {
1371       /* We should find something, eventually!  */
1372       gcc_assert (real_context);
1373
1374       context_proc = (real_context->entries ? real_context->entries->sym
1375                                             : real_context->proc_name);
1376
1377       /* In some special cases, there may not be a proc_name, like for this
1378          invalid code:
1379          real(bad_kind()) function foo () ...
1380          when checking the call to bad_kind ().
1381          In these cases, we simply return here and assume that the
1382          call is ok.  */
1383       if (!context_proc)
1384         return false;
1385
1386       if (context_proc->attr.flavor != FL_LABEL)
1387         break;
1388     }
1389
1390   /* A call from sym's body to itself is recursion, of course.  */
1391   if (context_proc == proc_sym)
1392     return true;
1393
1394   /* The same is true if context is a contained procedure and sym the
1395      containing one.  */
1396   if (context_proc->attr.contained)
1397     {
1398       gfc_symbol* parent_proc;
1399
1400       gcc_assert (context->parent);
1401       parent_proc = (context->parent->entries ? context->parent->entries->sym
1402                                               : context->parent->proc_name);
1403
1404       if (parent_proc == proc_sym)
1405         return true;
1406     }
1407
1408   return false;
1409 }
1410
1411
1412 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1413    its typespec and formal argument list.  */
1414
1415 static gfc_try
1416 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1417 {
1418   gfc_intrinsic_sym* isym = NULL;
1419   const char* symstd;
1420
1421   if (sym->formal)
1422     return SUCCESS;
1423
1424   /* We already know this one is an intrinsic, so we don't call
1425      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1426      gfc_find_subroutine directly to check whether it is a function or
1427      subroutine.  */
1428
1429   if (sym->intmod_sym_id)
1430     isym = gfc_intrinsic_function_by_id ((gfc_isym_id) sym->intmod_sym_id);
1431   else
1432     isym = gfc_find_function (sym->name);
1433
1434   if (isym)
1435     {
1436       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1437           && !sym->attr.implicit_type)
1438         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1439                       " ignored", sym->name, &sym->declared_at);
1440
1441       if (!sym->attr.function &&
1442           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1443         return FAILURE;
1444
1445       sym->ts = isym->ts;
1446     }
1447   else if ((isym = gfc_find_subroutine (sym->name)))
1448     {
1449       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1450         {
1451           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1452                       " specifier", sym->name, &sym->declared_at);
1453           return FAILURE;
1454         }
1455
1456       if (!sym->attr.subroutine &&
1457           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1458         return FAILURE;
1459     }
1460   else
1461     {
1462       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1463                  &sym->declared_at);
1464       return FAILURE;
1465     }
1466
1467   gfc_copy_formal_args_intr (sym, isym);
1468
1469   /* Check it is actually available in the standard settings.  */
1470   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1471       == FAILURE)
1472     {
1473       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1474                  " available in the current standard settings but %s.  Use"
1475                  " an appropriate -std=* option or enable -fall-intrinsics"
1476                  " in order to use it.",
1477                  sym->name, &sym->declared_at, symstd);
1478       return FAILURE;
1479     }
1480
1481   return SUCCESS;
1482 }
1483
1484
1485 /* Resolve a procedure expression, like passing it to a called procedure or as
1486    RHS for a procedure pointer assignment.  */
1487
1488 static gfc_try
1489 resolve_procedure_expression (gfc_expr* expr)
1490 {
1491   gfc_symbol* sym;
1492
1493   if (expr->expr_type != EXPR_VARIABLE)
1494     return SUCCESS;
1495   gcc_assert (expr->symtree);
1496
1497   sym = expr->symtree->n.sym;
1498
1499   if (sym->attr.intrinsic)
1500     resolve_intrinsic (sym, &expr->where);
1501
1502   if (sym->attr.flavor != FL_PROCEDURE
1503       || (sym->attr.function && sym->result == sym))
1504     return SUCCESS;
1505
1506   /* A non-RECURSIVE procedure that is used as procedure expression within its
1507      own body is in danger of being called recursively.  */
1508   if (is_illegal_recursion (sym, gfc_current_ns))
1509     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1510                  " itself recursively.  Declare it RECURSIVE or use"
1511                  " -frecursive", sym->name, &expr->where);
1512   
1513   return SUCCESS;
1514 }
1515
1516
1517 /* Resolve an actual argument list.  Most of the time, this is just
1518    resolving the expressions in the list.
1519    The exception is that we sometimes have to decide whether arguments
1520    that look like procedure arguments are really simple variable
1521    references.  */
1522
1523 static gfc_try
1524 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1525                         bool no_formal_args)
1526 {
1527   gfc_symbol *sym;
1528   gfc_symtree *parent_st;
1529   gfc_expr *e;
1530   int save_need_full_assumed_size;
1531
1532   for (; arg; arg = arg->next)
1533     {
1534       e = arg->expr;
1535       if (e == NULL)
1536         {
1537           /* Check the label is a valid branching target.  */
1538           if (arg->label)
1539             {
1540               if (arg->label->defined == ST_LABEL_UNKNOWN)
1541                 {
1542                   gfc_error ("Label %d referenced at %L is never defined",
1543                              arg->label->value, &arg->label->where);
1544                   return FAILURE;
1545                 }
1546             }
1547           continue;
1548         }
1549
1550       if (e->expr_type == EXPR_VARIABLE
1551             && e->symtree->n.sym->attr.generic
1552             && no_formal_args
1553             && count_specific_procs (e) != 1)
1554         return FAILURE;
1555
1556       if (e->ts.type != BT_PROCEDURE)
1557         {
1558           save_need_full_assumed_size = need_full_assumed_size;
1559           if (e->expr_type != EXPR_VARIABLE)
1560             need_full_assumed_size = 0;
1561           if (gfc_resolve_expr (e) != SUCCESS)
1562             return FAILURE;
1563           need_full_assumed_size = save_need_full_assumed_size;
1564           goto argument_list;
1565         }
1566
1567       /* See if the expression node should really be a variable reference.  */
1568
1569       sym = e->symtree->n.sym;
1570
1571       if (sym->attr.flavor == FL_PROCEDURE
1572           || sym->attr.intrinsic
1573           || sym->attr.external)
1574         {
1575           int actual_ok;
1576
1577           /* If a procedure is not already determined to be something else
1578              check if it is intrinsic.  */
1579           if (!sym->attr.intrinsic
1580               && !(sym->attr.external || sym->attr.use_assoc
1581                    || sym->attr.if_source == IFSRC_IFBODY)
1582               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1583             sym->attr.intrinsic = 1;
1584
1585           if (sym->attr.proc == PROC_ST_FUNCTION)
1586             {
1587               gfc_error ("Statement function '%s' at %L is not allowed as an "
1588                          "actual argument", sym->name, &e->where);
1589             }
1590
1591           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1592                                                sym->attr.subroutine);
1593           if (sym->attr.intrinsic && actual_ok == 0)
1594             {
1595               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1596                          "actual argument", sym->name, &e->where);
1597             }
1598
1599           if (sym->attr.contained && !sym->attr.use_assoc
1600               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1601             {
1602               if (gfc_notify_std (GFC_STD_F2008,
1603                                   "Fortran 2008: Internal procedure '%s' is"
1604                                   " used as actual argument at %L",
1605                                   sym->name, &e->where) == FAILURE)
1606                 return FAILURE;
1607             }
1608
1609           if (sym->attr.elemental && !sym->attr.intrinsic)
1610             {
1611               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1612                          "allowed as an actual argument at %L", sym->name,
1613                          &e->where);
1614             }
1615
1616           /* Check if a generic interface has a specific procedure
1617             with the same name before emitting an error.  */
1618           if (sym->attr.generic && count_specific_procs (e) != 1)
1619             return FAILURE;
1620           
1621           /* Just in case a specific was found for the expression.  */
1622           sym = e->symtree->n.sym;
1623
1624           /* If the symbol is the function that names the current (or
1625              parent) scope, then we really have a variable reference.  */
1626
1627           if (gfc_is_function_return_value (sym, sym->ns))
1628             goto got_variable;
1629
1630           /* If all else fails, see if we have a specific intrinsic.  */
1631           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1632             {
1633               gfc_intrinsic_sym *isym;
1634
1635               isym = gfc_find_function (sym->name);
1636               if (isym == NULL || !isym->specific)
1637                 {
1638                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1639                              "for the reference '%s' at %L", sym->name,
1640                              &e->where);
1641                   return FAILURE;
1642                 }
1643               sym->ts = isym->ts;
1644               sym->attr.intrinsic = 1;
1645               sym->attr.function = 1;
1646             }
1647
1648           if (gfc_resolve_expr (e) == FAILURE)
1649             return FAILURE;
1650           goto argument_list;
1651         }
1652
1653       /* See if the name is a module procedure in a parent unit.  */
1654
1655       if (was_declared (sym) || sym->ns->parent == NULL)
1656         goto got_variable;
1657
1658       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1659         {
1660           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1661           return FAILURE;
1662         }
1663
1664       if (parent_st == NULL)
1665         goto got_variable;
1666
1667       sym = parent_st->n.sym;
1668       e->symtree = parent_st;           /* Point to the right thing.  */
1669
1670       if (sym->attr.flavor == FL_PROCEDURE
1671           || sym->attr.intrinsic
1672           || sym->attr.external)
1673         {
1674           if (gfc_resolve_expr (e) == FAILURE)
1675             return FAILURE;
1676           goto argument_list;
1677         }
1678
1679     got_variable:
1680       e->expr_type = EXPR_VARIABLE;
1681       e->ts = sym->ts;
1682       if (sym->as != NULL)
1683         {
1684           e->rank = sym->as->rank;
1685           e->ref = gfc_get_ref ();
1686           e->ref->type = REF_ARRAY;
1687           e->ref->u.ar.type = AR_FULL;
1688           e->ref->u.ar.as = sym->as;
1689         }
1690
1691       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1692          primary.c (match_actual_arg). If above code determines that it
1693          is a  variable instead, it needs to be resolved as it was not
1694          done at the beginning of this function.  */
1695       save_need_full_assumed_size = need_full_assumed_size;
1696       if (e->expr_type != EXPR_VARIABLE)
1697         need_full_assumed_size = 0;
1698       if (gfc_resolve_expr (e) != SUCCESS)
1699         return FAILURE;
1700       need_full_assumed_size = save_need_full_assumed_size;
1701
1702     argument_list:
1703       /* Check argument list functions %VAL, %LOC and %REF.  There is
1704          nothing to do for %REF.  */
1705       if (arg->name && arg->name[0] == '%')
1706         {
1707           if (strncmp ("%VAL", arg->name, 4) == 0)
1708             {
1709               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1710                 {
1711                   gfc_error ("By-value argument at %L is not of numeric "
1712                              "type", &e->where);
1713                   return FAILURE;
1714                 }
1715
1716               if (e->rank)
1717                 {
1718                   gfc_error ("By-value argument at %L cannot be an array or "
1719                              "an array section", &e->where);
1720                 return FAILURE;
1721                 }
1722
1723               /* Intrinsics are still PROC_UNKNOWN here.  However,
1724                  since same file external procedures are not resolvable
1725                  in gfortran, it is a good deal easier to leave them to
1726                  intrinsic.c.  */
1727               if (ptype != PROC_UNKNOWN
1728                   && ptype != PROC_DUMMY
1729                   && ptype != PROC_EXTERNAL
1730                   && ptype != PROC_MODULE)
1731                 {
1732                   gfc_error ("By-value argument at %L is not allowed "
1733                              "in this context", &e->where);
1734                   return FAILURE;
1735                 }
1736             }
1737
1738           /* Statement functions have already been excluded above.  */
1739           else if (strncmp ("%LOC", arg->name, 4) == 0
1740                    && e->ts.type == BT_PROCEDURE)
1741             {
1742               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1743                 {
1744                   gfc_error ("Passing internal procedure at %L by location "
1745                              "not allowed", &e->where);
1746                   return FAILURE;
1747                 }
1748             }
1749         }
1750
1751       /* Fortran 2008, C1237.  */
1752       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1753           && gfc_has_ultimate_pointer (e))
1754         {
1755           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1756                      "component", &e->where);
1757           return FAILURE;
1758         }
1759     }
1760
1761   return SUCCESS;
1762 }
1763
1764
1765 /* Do the checks of the actual argument list that are specific to elemental
1766    procedures.  If called with c == NULL, we have a function, otherwise if
1767    expr == NULL, we have a subroutine.  */
1768
1769 static gfc_try
1770 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1771 {
1772   gfc_actual_arglist *arg0;
1773   gfc_actual_arglist *arg;
1774   gfc_symbol *esym = NULL;
1775   gfc_intrinsic_sym *isym = NULL;
1776   gfc_expr *e = NULL;
1777   gfc_intrinsic_arg *iformal = NULL;
1778   gfc_formal_arglist *eformal = NULL;
1779   bool formal_optional = false;
1780   bool set_by_optional = false;
1781   int i;
1782   int rank = 0;
1783
1784   /* Is this an elemental procedure?  */
1785   if (expr && expr->value.function.actual != NULL)
1786     {
1787       if (expr->value.function.esym != NULL
1788           && expr->value.function.esym->attr.elemental)
1789         {
1790           arg0 = expr->value.function.actual;
1791           esym = expr->value.function.esym;
1792         }
1793       else if (expr->value.function.isym != NULL
1794                && expr->value.function.isym->elemental)
1795         {
1796           arg0 = expr->value.function.actual;
1797           isym = expr->value.function.isym;
1798         }
1799       else
1800         return SUCCESS;
1801     }
1802   else if (c && c->ext.actual != NULL)
1803     {
1804       arg0 = c->ext.actual;
1805       
1806       if (c->resolved_sym)
1807         esym = c->resolved_sym;
1808       else
1809         esym = c->symtree->n.sym;
1810       gcc_assert (esym);
1811
1812       if (!esym->attr.elemental)
1813         return SUCCESS;
1814     }
1815   else
1816     return SUCCESS;
1817
1818   /* The rank of an elemental is the rank of its array argument(s).  */
1819   for (arg = arg0; arg; arg = arg->next)
1820     {
1821       if (arg->expr != NULL && arg->expr->rank > 0)
1822         {
1823           rank = arg->expr->rank;
1824           if (arg->expr->expr_type == EXPR_VARIABLE
1825               && arg->expr->symtree->n.sym->attr.optional)
1826             set_by_optional = true;
1827
1828           /* Function specific; set the result rank and shape.  */
1829           if (expr)
1830             {
1831               expr->rank = rank;
1832               if (!expr->shape && arg->expr->shape)
1833                 {
1834                   expr->shape = gfc_get_shape (rank);
1835                   for (i = 0; i < rank; i++)
1836                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1837                 }
1838             }
1839           break;
1840         }
1841     }
1842
1843   /* If it is an array, it shall not be supplied as an actual argument
1844      to an elemental procedure unless an array of the same rank is supplied
1845      as an actual argument corresponding to a nonoptional dummy argument of
1846      that elemental procedure(12.4.1.5).  */
1847   formal_optional = false;
1848   if (isym)
1849     iformal = isym->formal;
1850   else
1851     eformal = esym->formal;
1852
1853   for (arg = arg0; arg; arg = arg->next)
1854     {
1855       if (eformal)
1856         {
1857           if (eformal->sym && eformal->sym->attr.optional)
1858             formal_optional = true;
1859           eformal = eformal->next;
1860         }
1861       else if (isym && iformal)
1862         {
1863           if (iformal->optional)
1864             formal_optional = true;
1865           iformal = iformal->next;
1866         }
1867       else if (isym)
1868         formal_optional = true;
1869
1870       if (pedantic && arg->expr != NULL
1871           && arg->expr->expr_type == EXPR_VARIABLE
1872           && arg->expr->symtree->n.sym->attr.optional
1873           && formal_optional
1874           && arg->expr->rank
1875           && (set_by_optional || arg->expr->rank != rank)
1876           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1877         {
1878           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1879                        "MISSING, it cannot be the actual argument of an "
1880                        "ELEMENTAL procedure unless there is a non-optional "
1881                        "argument with the same rank (12.4.1.5)",
1882                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1883           return FAILURE;
1884         }
1885     }
1886
1887   for (arg = arg0; arg; arg = arg->next)
1888     {
1889       if (arg->expr == NULL || arg->expr->rank == 0)
1890         continue;
1891
1892       /* Being elemental, the last upper bound of an assumed size array
1893          argument must be present.  */
1894       if (resolve_assumed_size_actual (arg->expr))
1895         return FAILURE;
1896
1897       /* Elemental procedure's array actual arguments must conform.  */
1898       if (e != NULL)
1899         {
1900           if (gfc_check_conformance (arg->expr, e,
1901                                      "elemental procedure") == FAILURE)
1902             return FAILURE;
1903         }
1904       else
1905         e = arg->expr;
1906     }
1907
1908   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1909      is an array, the intent inout/out variable needs to be also an array.  */
1910   if (rank > 0 && esym && expr == NULL)
1911     for (eformal = esym->formal, arg = arg0; arg && eformal;
1912          arg = arg->next, eformal = eformal->next)
1913       if ((eformal->sym->attr.intent == INTENT_OUT
1914            || eformal->sym->attr.intent == INTENT_INOUT)
1915           && arg->expr && arg->expr->rank == 0)
1916         {
1917           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1918                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1919                      "actual argument is an array", &arg->expr->where,
1920                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1921                      : "INOUT", eformal->sym->name, esym->name);
1922           return FAILURE;
1923         }
1924   return SUCCESS;
1925 }
1926
1927
1928 /* This function does the checking of references to global procedures
1929    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1930    77 and 95 standards.  It checks for a gsymbol for the name, making
1931    one if it does not already exist.  If it already exists, then the
1932    reference being resolved must correspond to the type of gsymbol.
1933    Otherwise, the new symbol is equipped with the attributes of the
1934    reference.  The corresponding code that is called in creating
1935    global entities is parse.c.
1936
1937    In addition, for all but -std=legacy, the gsymbols are used to
1938    check the interfaces of external procedures from the same file.
1939    The namespace of the gsymbol is resolved and then, once this is
1940    done the interface is checked.  */
1941
1942
1943 static bool
1944 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
1945 {
1946   if (!gsym_ns->proc_name->attr.recursive)
1947     return true;
1948
1949   if (sym->ns == gsym_ns)
1950     return false;
1951
1952   if (sym->ns->parent && sym->ns->parent == gsym_ns)
1953     return false;
1954
1955   return true;
1956 }
1957
1958 static bool
1959 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
1960 {
1961   if (gsym_ns->entries)
1962     {
1963       gfc_entry_list *entry = gsym_ns->entries;
1964
1965       for (; entry; entry = entry->next)
1966         {
1967           if (strcmp (sym->name, entry->sym->name) == 0)
1968             {
1969               if (strcmp (gsym_ns->proc_name->name,
1970                           sym->ns->proc_name->name) == 0)
1971                 return false;
1972
1973               if (sym->ns->parent
1974                   && strcmp (gsym_ns->proc_name->name,
1975                              sym->ns->parent->proc_name->name) == 0)
1976                 return false;
1977             }
1978         }
1979     }
1980   return true;
1981 }
1982
1983 static void
1984 resolve_global_procedure (gfc_symbol *sym, locus *where,
1985                           gfc_actual_arglist **actual, int sub)
1986 {
1987   gfc_gsymbol * gsym;
1988   gfc_namespace *ns;
1989   enum gfc_symbol_type type;
1990
1991   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
1992
1993   gsym = gfc_get_gsymbol (sym->name);
1994
1995   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
1996     gfc_global_used (gsym, where);
1997
1998   if (gfc_option.flag_whole_file
1999         && (sym->attr.if_source == IFSRC_UNKNOWN
2000             || sym->attr.if_source == IFSRC_IFBODY)
2001         && gsym->type != GSYM_UNKNOWN
2002         && gsym->ns
2003         && gsym->ns->resolved != -1
2004         && gsym->ns->proc_name
2005         && not_in_recursive (sym, gsym->ns)
2006         && not_entry_self_reference (sym, gsym->ns))
2007     {
2008       gfc_symbol *def_sym;
2009
2010       /* Resolve the gsymbol namespace if needed.  */
2011       if (!gsym->ns->resolved)
2012         {
2013           gfc_dt_list *old_dt_list;
2014           struct gfc_omp_saved_state old_omp_state;
2015
2016           /* Stash away derived types so that the backend_decls do not
2017              get mixed up.  */
2018           old_dt_list = gfc_derived_types;
2019           gfc_derived_types = NULL;
2020           /* And stash away openmp state.  */
2021           gfc_omp_save_and_clear_state (&old_omp_state);
2022
2023           gfc_resolve (gsym->ns);
2024
2025           /* Store the new derived types with the global namespace.  */
2026           if (gfc_derived_types)
2027             gsym->ns->derived_types = gfc_derived_types;
2028
2029           /* Restore the derived types of this namespace.  */
2030           gfc_derived_types = old_dt_list;
2031           /* And openmp state.  */
2032           gfc_omp_restore_state (&old_omp_state);
2033         }
2034
2035       /* Make sure that translation for the gsymbol occurs before
2036          the procedure currently being resolved.  */
2037       ns = gfc_global_ns_list;
2038       for (; ns && ns != gsym->ns; ns = ns->sibling)
2039         {
2040           if (ns->sibling == gsym->ns)
2041             {
2042               ns->sibling = gsym->ns->sibling;
2043               gsym->ns->sibling = gfc_global_ns_list;
2044               gfc_global_ns_list = gsym->ns;
2045               break;
2046             }
2047         }
2048
2049       def_sym = gsym->ns->proc_name;
2050       if (def_sym->attr.entry_master)
2051         {
2052           gfc_entry_list *entry;
2053           for (entry = gsym->ns->entries; entry; entry = entry->next)
2054             if (strcmp (entry->sym->name, sym->name) == 0)
2055               {
2056                 def_sym = entry->sym;
2057                 break;
2058               }
2059         }
2060
2061       /* Differences in constant character lengths.  */
2062       if (sym->attr.function && sym->ts.type == BT_CHARACTER)
2063         {
2064           long int l1 = 0, l2 = 0;
2065           gfc_charlen *cl1 = sym->ts.u.cl;
2066           gfc_charlen *cl2 = def_sym->ts.u.cl;
2067
2068           if (cl1 != NULL
2069               && cl1->length != NULL
2070               && cl1->length->expr_type == EXPR_CONSTANT)
2071             l1 = mpz_get_si (cl1->length->value.integer);
2072
2073           if (cl2 != NULL
2074               && cl2->length != NULL
2075               && cl2->length->expr_type == EXPR_CONSTANT)
2076             l2 = mpz_get_si (cl2->length->value.integer);
2077
2078           if (l1 && l2 && l1 != l2)
2079             gfc_error ("Character length mismatch in return type of "
2080                        "function '%s' at %L (%ld/%ld)", sym->name,
2081                        &sym->declared_at, l1, l2);
2082         }
2083
2084      /* Type mismatch of function return type and expected type.  */
2085      if (sym->attr.function
2086          && !gfc_compare_types (&sym->ts, &def_sym->ts))
2087         gfc_error ("Return type mismatch of function '%s' at %L (%s/%s)",
2088                    sym->name, &sym->declared_at, gfc_typename (&sym->ts),
2089                    gfc_typename (&def_sym->ts));
2090
2091       if (def_sym->formal && sym->attr.if_source != IFSRC_IFBODY)
2092         {
2093           gfc_formal_arglist *arg = def_sym->formal;
2094           for ( ; arg; arg = arg->next)
2095             if (!arg->sym)
2096               continue;
2097             /* F2003, 12.3.1.1 (2a); F2008, 12.4.2.2 (2a)  */
2098             else if (arg->sym->attr.allocatable
2099                      || arg->sym->attr.asynchronous
2100                      || arg->sym->attr.optional
2101                      || arg->sym->attr.pointer
2102                      || arg->sym->attr.target
2103                      || arg->sym->attr.value
2104                      || arg->sym->attr.volatile_)
2105               {
2106                 gfc_error ("Dummy argument '%s' of procedure '%s' at %L "
2107                            "has an attribute that requires an explicit "
2108                            "interface for this procedure", arg->sym->name,
2109                            sym->name, &sym->declared_at);
2110                 break;
2111               }
2112             /* F2003, 12.3.1.1 (2b); F2008, 12.4.2.2 (2b)  */
2113             else if (arg->sym && arg->sym->as
2114                      && arg->sym->as->type == AS_ASSUMED_SHAPE)
2115               {
2116                 gfc_error ("Procedure '%s' at %L with assumed-shape dummy "
2117                            "argument '%s' must have an explicit interface",
2118                            sym->name, &sym->declared_at, arg->sym->name);
2119                 break;
2120               }
2121             /* F2008, 12.4.2.2 (2c)  */
2122             else if (arg->sym->attr.codimension)
2123               {
2124                 gfc_error ("Procedure '%s' at %L with coarray dummy argument "
2125                            "'%s' must have an explicit interface",
2126                            sym->name, &sym->declared_at, arg->sym->name);
2127                 break;
2128               }
2129             /* F2003, 12.3.1.1 (2c); F2008, 12.4.2.2 (2d)   */
2130             else if (false) /* TODO: is a parametrized derived type  */
2131               {
2132                 gfc_error ("Procedure '%s' at %L with parametrized derived "
2133                            "type argument '%s' must have an explicit "
2134                            "interface", sym->name, &sym->declared_at,
2135                            arg->sym->name);
2136                 break;
2137               }
2138             /* F2003, 12.3.1.1 (2d); F2008, 12.4.2.2 (2e)   */
2139             else if (arg->sym->ts.type == BT_CLASS)
2140               {
2141                 gfc_error ("Procedure '%s' at %L with polymorphic dummy "
2142                            "argument '%s' must have an explicit interface",
2143                            sym->name, &sym->declared_at, arg->sym->name);
2144                 break;
2145               }
2146         }
2147
2148       if (def_sym->attr.function)
2149         {
2150           /* F2003, 12.3.1.1 (3a); F2008, 12.4.2.2 (3a) */
2151           if (def_sym->as && def_sym->as->rank
2152               && (!sym->as || sym->as->rank != def_sym->as->rank))
2153             gfc_error ("The reference to function '%s' at %L either needs an "
2154                        "explicit INTERFACE or the rank is incorrect", sym->name,
2155                        where);
2156
2157           /* F2003, 12.3.1.1 (3b); F2008, 12.4.2.2 (3b) */
2158           if ((def_sym->result->attr.pointer
2159                || def_sym->result->attr.allocatable)
2160                && (sym->attr.if_source != IFSRC_IFBODY
2161                    || def_sym->result->attr.pointer
2162                         != sym->result->attr.pointer
2163                    || def_sym->result->attr.allocatable
2164                         != sym->result->attr.allocatable))
2165             gfc_error ("Function '%s' at %L with a POINTER or ALLOCATABLE "
2166                        "result must have an explicit interface", sym->name,
2167                        where);
2168
2169           /* F2003, 12.3.1.1 (3c); F2008, 12.4.2.2 (3c)  */
2170           if (sym->ts.type == BT_CHARACTER && sym->attr.if_source != IFSRC_IFBODY
2171               && def_sym->ts.u.cl->length != NULL)
2172             {
2173               gfc_charlen *cl = sym->ts.u.cl;
2174
2175               if (!sym->attr.entry_master && sym->attr.if_source == IFSRC_UNKNOWN
2176                   && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
2177                 {
2178                   gfc_error ("Nonconstant character-length function '%s' at %L "
2179                              "must have an explicit interface", sym->name,
2180                              &sym->declared_at);
2181                 }
2182             }
2183         }
2184
2185       /* F2003, 12.3.1.1 (4); F2008, 12.4.2.2 (4) */
2186       if (def_sym->attr.elemental && !sym->attr.elemental)
2187         {
2188           gfc_error ("ELEMENTAL procedure '%s' at %L must have an explicit "
2189                      "interface", sym->name, &sym->declared_at);
2190         }
2191
2192       /* F2003, 12.3.1.1 (5); F2008, 12.4.2.2 (5) */
2193       if (def_sym->attr.is_bind_c && !sym->attr.is_bind_c)
2194         {
2195           gfc_error ("Procedure '%s' at %L with BIND(C) attribute must have "
2196                      "an explicit interface", sym->name, &sym->declared_at);
2197         }
2198
2199       if (gfc_option.flag_whole_file == 1
2200           || ((gfc_option.warn_std & GFC_STD_LEGACY)
2201               && !(gfc_option.warn_std & GFC_STD_GNU)))
2202         gfc_errors_to_warnings (1);
2203
2204       if (sym->attr.if_source != IFSRC_IFBODY)  
2205         gfc_procedure_use (def_sym, actual, where);
2206
2207       gfc_errors_to_warnings (0);
2208     }
2209
2210   if (gsym->type == GSYM_UNKNOWN)
2211     {
2212       gsym->type = type;
2213       gsym->where = *where;
2214     }
2215
2216   gsym->used = 1;
2217 }
2218
2219
2220 /************* Function resolution *************/
2221
2222 /* Resolve a function call known to be generic.
2223    Section 14.1.2.4.1.  */
2224
2225 static match
2226 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
2227 {
2228   gfc_symbol *s;
2229
2230   if (sym->attr.generic)
2231     {
2232       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
2233       if (s != NULL)
2234         {
2235           expr->value.function.name = s->name;
2236           expr->value.function.esym = s;
2237
2238           if (s->ts.type != BT_UNKNOWN)
2239             expr->ts = s->ts;
2240           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
2241             expr->ts = s->result->ts;
2242
2243           if (s->as != NULL)
2244             expr->rank = s->as->rank;
2245           else if (s->result != NULL && s->result->as != NULL)
2246             expr->rank = s->result->as->rank;
2247
2248           gfc_set_sym_referenced (expr->value.function.esym);
2249
2250           return MATCH_YES;
2251         }
2252
2253       /* TODO: Need to search for elemental references in generic
2254          interface.  */
2255     }
2256
2257   if (sym->attr.intrinsic)
2258     return gfc_intrinsic_func_interface (expr, 0);
2259
2260   return MATCH_NO;
2261 }
2262
2263
2264 static gfc_try
2265 resolve_generic_f (gfc_expr *expr)
2266 {
2267   gfc_symbol *sym;
2268   match m;
2269
2270   sym = expr->symtree->n.sym;
2271
2272   for (;;)
2273     {
2274       m = resolve_generic_f0 (expr, sym);
2275       if (m == MATCH_YES)
2276         return SUCCESS;
2277       else if (m == MATCH_ERROR)
2278         return FAILURE;
2279
2280 generic:
2281       if (sym->ns->parent == NULL)
2282         break;
2283       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2284
2285       if (sym == NULL)
2286         break;
2287       if (!generic_sym (sym))
2288         goto generic;
2289     }
2290
2291   /* Last ditch attempt.  See if the reference is to an intrinsic
2292      that possesses a matching interface.  14.1.2.4  */
2293   if (sym && !gfc_is_intrinsic (sym, 0, expr->where))
2294     {
2295       gfc_error ("There is no specific function for the generic '%s' at %L",
2296                  expr->symtree->n.sym->name, &expr->where);
2297       return FAILURE;
2298     }
2299
2300   m = gfc_intrinsic_func_interface (expr, 0);
2301   if (m == MATCH_YES)
2302     return SUCCESS;
2303   if (m == MATCH_NO)
2304     gfc_error ("Generic function '%s' at %L is not consistent with a "
2305                "specific intrinsic interface", expr->symtree->n.sym->name,
2306                &expr->where);
2307
2308   return FAILURE;
2309 }
2310
2311
2312 /* Resolve a function call known to be specific.  */
2313
2314 static match
2315 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2316 {
2317   match m;
2318
2319   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2320     {
2321       if (sym->attr.dummy)
2322         {
2323           sym->attr.proc = PROC_DUMMY;
2324           goto found;
2325         }
2326
2327       sym->attr.proc = PROC_EXTERNAL;
2328       goto found;
2329     }
2330
2331   if (sym->attr.proc == PROC_MODULE
2332       || sym->attr.proc == PROC_ST_FUNCTION
2333       || sym->attr.proc == PROC_INTERNAL)
2334     goto found;
2335
2336   if (sym->attr.intrinsic)
2337     {
2338       m = gfc_intrinsic_func_interface (expr, 1);
2339       if (m == MATCH_YES)
2340         return MATCH_YES;
2341       if (m == MATCH_NO)
2342         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2343                    "with an intrinsic", sym->name, &expr->where);
2344
2345       return MATCH_ERROR;
2346     }
2347
2348   return MATCH_NO;
2349
2350 found:
2351   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2352
2353   if (sym->result)
2354     expr->ts = sym->result->ts;
2355   else
2356     expr->ts = sym->ts;
2357   expr->value.function.name = sym->name;
2358   expr->value.function.esym = sym;
2359   if (sym->as != NULL)
2360     expr->rank = sym->as->rank;
2361
2362   return MATCH_YES;
2363 }
2364
2365
2366 static gfc_try
2367 resolve_specific_f (gfc_expr *expr)
2368 {
2369   gfc_symbol *sym;
2370   match m;
2371
2372   sym = expr->symtree->n.sym;
2373
2374   for (;;)
2375     {
2376       m = resolve_specific_f0 (sym, expr);
2377       if (m == MATCH_YES)
2378         return SUCCESS;
2379       if (m == MATCH_ERROR)
2380         return FAILURE;
2381
2382       if (sym->ns->parent == NULL)
2383         break;
2384
2385       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2386
2387       if (sym == NULL)
2388         break;
2389     }
2390
2391   gfc_error ("Unable to resolve the specific function '%s' at %L",
2392              expr->symtree->n.sym->name, &expr->where);
2393
2394   return SUCCESS;
2395 }
2396
2397
2398 /* Resolve a procedure call not known to be generic nor specific.  */
2399
2400 static gfc_try
2401 resolve_unknown_f (gfc_expr *expr)
2402 {
2403   gfc_symbol *sym;
2404   gfc_typespec *ts;
2405
2406   sym = expr->symtree->n.sym;
2407
2408   if (sym->attr.dummy)
2409     {
2410       sym->attr.proc = PROC_DUMMY;
2411       expr->value.function.name = sym->name;
2412       goto set_type;
2413     }
2414
2415   /* See if we have an intrinsic function reference.  */
2416
2417   if (gfc_is_intrinsic (sym, 0, expr->where))
2418     {
2419       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2420         return SUCCESS;
2421       return FAILURE;
2422     }
2423
2424   /* The reference is to an external name.  */
2425
2426   sym->attr.proc = PROC_EXTERNAL;
2427   expr->value.function.name = sym->name;
2428   expr->value.function.esym = expr->symtree->n.sym;
2429
2430   if (sym->as != NULL)
2431     expr->rank = sym->as->rank;
2432
2433   /* Type of the expression is either the type of the symbol or the
2434      default type of the symbol.  */
2435
2436 set_type:
2437   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2438
2439   if (sym->ts.type != BT_UNKNOWN)
2440     expr->ts = sym->ts;
2441   else
2442     {
2443       ts = gfc_get_default_type (sym->name, sym->ns);
2444
2445       if (ts->type == BT_UNKNOWN)
2446         {
2447           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2448                      sym->name, &expr->where);
2449           return FAILURE;
2450         }
2451       else
2452         expr->ts = *ts;
2453     }
2454
2455   return SUCCESS;
2456 }
2457
2458
2459 /* Return true, if the symbol is an external procedure.  */
2460 static bool
2461 is_external_proc (gfc_symbol *sym)
2462 {
2463   if (!sym->attr.dummy && !sym->attr.contained
2464         && !(sym->attr.intrinsic
2465               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2466         && sym->attr.proc != PROC_ST_FUNCTION
2467         && !sym->attr.proc_pointer
2468         && !sym->attr.use_assoc
2469         && sym->name)
2470     return true;
2471
2472   return false;
2473 }
2474
2475
2476 /* Figure out if a function reference is pure or not.  Also set the name
2477    of the function for a potential error message.  Return nonzero if the
2478    function is PURE, zero if not.  */
2479 static int
2480 pure_stmt_function (gfc_expr *, gfc_symbol *);
2481
2482 static int
2483 pure_function (gfc_expr *e, const char **name)
2484 {
2485   int pure;
2486
2487   *name = NULL;
2488
2489   if (e->symtree != NULL
2490         && e->symtree->n.sym != NULL
2491         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2492     return pure_stmt_function (e, e->symtree->n.sym);
2493
2494   if (e->value.function.esym)
2495     {
2496       pure = gfc_pure (e->value.function.esym);
2497       *name = e->value.function.esym->name;
2498     }
2499   else if (e->value.function.isym)
2500     {
2501       pure = e->value.function.isym->pure
2502              || e->value.function.isym->elemental;
2503       *name = e->value.function.isym->name;
2504     }
2505   else
2506     {
2507       /* Implicit functions are not pure.  */
2508       pure = 0;
2509       *name = e->value.function.name;
2510     }
2511
2512   return pure;
2513 }
2514
2515
2516 static bool
2517 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2518                  int *f ATTRIBUTE_UNUSED)
2519 {
2520   const char *name;
2521
2522   /* Don't bother recursing into other statement functions
2523      since they will be checked individually for purity.  */
2524   if (e->expr_type != EXPR_FUNCTION
2525         || !e->symtree
2526         || e->symtree->n.sym == sym
2527         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2528     return false;
2529
2530   return pure_function (e, &name) ? false : true;
2531 }
2532
2533
2534 static int
2535 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2536 {
2537   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2538 }
2539
2540
2541 static gfc_try
2542 is_scalar_expr_ptr (gfc_expr *expr)
2543 {
2544   gfc_try retval = SUCCESS;
2545   gfc_ref *ref;
2546   int start;
2547   int end;
2548
2549   /* See if we have a gfc_ref, which means we have a substring, array
2550      reference, or a component.  */
2551   if (expr->ref != NULL)
2552     {
2553       ref = expr->ref;
2554       while (ref->next != NULL)
2555         ref = ref->next;
2556
2557       switch (ref->type)
2558         {
2559         case REF_SUBSTRING:
2560           if (ref->u.ss.start == NULL || ref->u.ss.end == NULL
2561               || gfc_dep_compare_expr (ref->u.ss.start, ref->u.ss.end) != 0)
2562             retval = FAILURE;
2563           break;
2564
2565         case REF_ARRAY:
2566           if (ref->u.ar.type == AR_ELEMENT)
2567             retval = SUCCESS;
2568           else if (ref->u.ar.type == AR_FULL)
2569             {
2570               /* The user can give a full array if the array is of size 1.  */
2571               if (ref->u.ar.as != NULL
2572                   && ref->u.ar.as->rank == 1
2573                   && ref->u.ar.as->type == AS_EXPLICIT
2574                   && ref->u.ar.as->lower[0] != NULL
2575                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2576                   && ref->u.ar.as->upper[0] != NULL
2577                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2578                 {
2579                   /* If we have a character string, we need to check if
2580                      its length is one.  */
2581                   if (expr->ts.type == BT_CHARACTER)
2582                     {
2583                       if (expr->ts.u.cl == NULL
2584                           || expr->ts.u.cl->length == NULL
2585                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2586                           != 0)
2587                         retval = FAILURE;
2588                     }
2589                   else
2590                     {
2591                       /* We have constant lower and upper bounds.  If the
2592                          difference between is 1, it can be considered a
2593                          scalar.  
2594                          FIXME: Use gfc_dep_compare_expr instead.  */
2595                       start = (int) mpz_get_si
2596                                 (ref->u.ar.as->lower[0]->value.integer);
2597                       end = (int) mpz_get_si
2598                                 (ref->u.ar.as->upper[0]->value.integer);
2599                       if (end - start + 1 != 1)
2600                         retval = FAILURE;
2601                    }
2602                 }
2603               else
2604                 retval = FAILURE;
2605             }
2606           else
2607             retval = FAILURE;
2608           break;
2609         default:
2610           retval = SUCCESS;
2611           break;
2612         }
2613     }
2614   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2615     {
2616       /* Character string.  Make sure it's of length 1.  */
2617       if (expr->ts.u.cl == NULL
2618           || expr->ts.u.cl->length == NULL
2619           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2620         retval = FAILURE;
2621     }
2622   else if (expr->rank != 0)
2623     retval = FAILURE;
2624
2625   return retval;
2626 }
2627
2628
2629 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2630    and, in the case of c_associated, set the binding label based on
2631    the arguments.  */
2632
2633 static gfc_try
2634 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2635                           gfc_symbol **new_sym)
2636 {
2637   char name[GFC_MAX_SYMBOL_LEN + 1];
2638   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2639   int optional_arg = 0;
2640   gfc_try retval = SUCCESS;
2641   gfc_symbol *args_sym;
2642   gfc_typespec *arg_ts;
2643   symbol_attribute arg_attr;
2644
2645   if (args->expr->expr_type == EXPR_CONSTANT
2646       || args->expr->expr_type == EXPR_OP
2647       || args->expr->expr_type == EXPR_NULL)
2648     {
2649       gfc_error ("Argument to '%s' at %L is not a variable",
2650                  sym->name, &(args->expr->where));
2651       return FAILURE;
2652     }
2653
2654   args_sym = args->expr->symtree->n.sym;
2655
2656   /* The typespec for the actual arg should be that stored in the expr
2657      and not necessarily that of the expr symbol (args_sym), because
2658      the actual expression could be a part-ref of the expr symbol.  */
2659   arg_ts = &(args->expr->ts);
2660   arg_attr = gfc_expr_attr (args->expr);
2661     
2662   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2663     {
2664       /* If the user gave two args then they are providing something for
2665          the optional arg (the second cptr).  Therefore, set the name and
2666          binding label to the c_associated for two cptrs.  Otherwise,
2667          set c_associated to expect one cptr.  */
2668       if (args->next)
2669         {
2670           /* two args.  */
2671           sprintf (name, "%s_2", sym->name);
2672           sprintf (binding_label, "%s_2", sym->binding_label);
2673           optional_arg = 1;
2674         }
2675       else
2676         {
2677           /* one arg.  */
2678           sprintf (name, "%s_1", sym->name);
2679           sprintf (binding_label, "%s_1", sym->binding_label);
2680           optional_arg = 0;
2681         }
2682
2683       /* Get a new symbol for the version of c_associated that
2684          will get called.  */
2685       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2686     }
2687   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2688            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2689     {
2690       sprintf (name, "%s", sym->name);
2691       sprintf (binding_label, "%s", sym->binding_label);
2692
2693       /* Error check the call.  */
2694       if (args->next != NULL)
2695         {
2696           gfc_error_now ("More actual than formal arguments in '%s' "
2697                          "call at %L", name, &(args->expr->where));
2698           retval = FAILURE;
2699         }
2700       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2701         {
2702           gfc_ref *ref;
2703           bool seen_section;
2704
2705           /* Make sure we have either the target or pointer attribute.  */
2706           if (!arg_attr.target && !arg_attr.pointer)
2707             {
2708               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2709                              "a TARGET or an associated pointer",
2710                              args_sym->name,
2711                              sym->name, &(args->expr->where));
2712               retval = FAILURE;
2713             }
2714
2715           if (gfc_is_coindexed (args->expr))
2716             {
2717               gfc_error_now ("Coindexed argument not permitted"
2718                              " in '%s' call at %L", name,
2719                              &(args->expr->where));
2720               retval = FAILURE;
2721             }
2722
2723           /* Follow references to make sure there are no array
2724              sections.  */
2725           seen_section = false;
2726
2727           for (ref=args->expr->ref; ref; ref = ref->next)
2728             {
2729               if (ref->type == REF_ARRAY)
2730                 {
2731                   if (ref->u.ar.type == AR_SECTION)
2732                     seen_section = true;
2733
2734                   if (ref->u.ar.type != AR_ELEMENT)
2735                     {
2736                       gfc_ref *r;
2737                       for (r = ref->next; r; r=r->next)
2738                         if (r->type == REF_COMPONENT)
2739                           {
2740                             gfc_error_now ("Array section not permitted"
2741                                            " in '%s' call at %L", name,
2742                                            &(args->expr->where));
2743                             retval = FAILURE;
2744                             break;
2745                           }
2746                     }
2747                 }
2748             }
2749
2750           if (seen_section && retval == SUCCESS)
2751             gfc_warning ("Array section in '%s' call at %L", name,
2752                          &(args->expr->where));
2753                          
2754           /* See if we have interoperable type and type param.  */
2755           if (verify_c_interop (arg_ts) == SUCCESS
2756               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2757             {
2758               if (args_sym->attr.target == 1)
2759                 {
2760                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2761                      has the target attribute and is interoperable.  */
2762                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2763                      allocatable variable that has the TARGET attribute and
2764                      is not an array of zero size.  */
2765                   if (args_sym->attr.allocatable == 1)
2766                     {
2767                       if (args_sym->attr.dimension != 0 
2768                           && (args_sym->as && args_sym->as->rank == 0))
2769                         {
2770                           gfc_error_now ("Allocatable variable '%s' used as a "
2771                                          "parameter to '%s' at %L must not be "
2772                                          "an array of zero size",
2773                                          args_sym->name, sym->name,
2774                                          &(args->expr->where));
2775                           retval = FAILURE;
2776                         }
2777                     }
2778                   else
2779                     {
2780                       /* A non-allocatable target variable with C
2781                          interoperable type and type parameters must be
2782                          interoperable.  */
2783                       if (args_sym && args_sym->attr.dimension)
2784                         {
2785                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2786                             {
2787                               gfc_error ("Assumed-shape array '%s' at %L "
2788                                          "cannot be an argument to the "
2789                                          "procedure '%s' because "
2790                                          "it is not C interoperable",
2791                                          args_sym->name,
2792                                          &(args->expr->where), sym->name);
2793                               retval = FAILURE;
2794                             }
2795                           else if (args_sym->as->type == AS_DEFERRED)
2796                             {
2797                               gfc_error ("Deferred-shape array '%s' at %L "
2798                                          "cannot be an argument to the "
2799                                          "procedure '%s' because "
2800                                          "it is not C interoperable",
2801                                          args_sym->name,
2802                                          &(args->expr->where), sym->name);
2803                               retval = FAILURE;
2804                             }
2805                         }
2806                               
2807                       /* Make sure it's not a character string.  Arrays of
2808                          any type should be ok if the variable is of a C
2809                          interoperable type.  */
2810                       if (arg_ts->type == BT_CHARACTER)
2811                         if (arg_ts->u.cl != NULL
2812                             && (arg_ts->u.cl->length == NULL
2813                                 || arg_ts->u.cl->length->expr_type
2814                                    != EXPR_CONSTANT
2815                                 || mpz_cmp_si
2816                                     (arg_ts->u.cl->length->value.integer, 1)
2817                                    != 0)
2818                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2819                           {
2820                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2821                                            "at %L must have a length of 1",
2822                                            args_sym->name, sym->name,
2823                                            &(args->expr->where));
2824                             retval = FAILURE;
2825                           }
2826                     }
2827                 }
2828               else if (arg_attr.pointer
2829                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2830                 {
2831                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2832                      scalar pointer.  */
2833                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2834                                  "associated scalar POINTER", args_sym->name,
2835                                  sym->name, &(args->expr->where));
2836                   retval = FAILURE;
2837                 }
2838             }
2839           else
2840             {
2841               /* The parameter is not required to be C interoperable.  If it
2842                  is not C interoperable, it must be a nonpolymorphic scalar
2843                  with no length type parameters.  It still must have either
2844                  the pointer or target attribute, and it can be
2845                  allocatable (but must be allocated when c_loc is called).  */
2846               if (args->expr->rank != 0 
2847                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2848                 {
2849                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2850                                  "scalar", args_sym->name, sym->name,
2851                                  &(args->expr->where));
2852                   retval = FAILURE;
2853                 }
2854               else if (arg_ts->type == BT_CHARACTER 
2855                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2856                 {
2857                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2858                                  "%L must have a length of 1",
2859                                  args_sym->name, sym->name,
2860                                  &(args->expr->where));
2861                   retval = FAILURE;
2862                 }
2863               else if (arg_ts->type == BT_CLASS)
2864                 {
2865                   gfc_error_now ("Parameter '%s' to '%s' at %L must not be "
2866                                  "polymorphic", args_sym->name, sym->name,
2867                                  &(args->expr->where));
2868                   retval = FAILURE;
2869                 }
2870             }
2871         }
2872       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2873         {
2874           if (args_sym->attr.flavor != FL_PROCEDURE)
2875             {
2876               /* TODO: Update this error message to allow for procedure
2877                  pointers once they are implemented.  */
2878               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2879                              "procedure",
2880                              args_sym->name, sym->name,
2881                              &(args->expr->where));
2882               retval = FAILURE;
2883             }
2884           else if (args_sym->attr.is_bind_c != 1)
2885             {
2886               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2887                              "BIND(C)",
2888                              args_sym->name, sym->name,
2889                              &(args->expr->where));
2890               retval = FAILURE;
2891             }
2892         }
2893       
2894       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2895       *new_sym = sym;
2896     }
2897   else
2898     {
2899       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2900                           "iso_c_binding function: '%s'!\n", sym->name);
2901     }
2902
2903   return retval;
2904 }
2905
2906
2907 /* Resolve a function call, which means resolving the arguments, then figuring
2908    out which entity the name refers to.  */
2909
2910 static gfc_try
2911 resolve_function (gfc_expr *expr)
2912 {
2913   gfc_actual_arglist *arg;
2914   gfc_symbol *sym;
2915   const char *name;
2916   gfc_try t;
2917   int temp;
2918   procedure_type p = PROC_INTRINSIC;
2919   bool no_formal_args;
2920
2921   sym = NULL;
2922   if (expr->symtree)
2923     sym = expr->symtree->n.sym;
2924
2925   /* If this is a procedure pointer component, it has already been resolved.  */
2926   if (gfc_is_proc_ptr_comp (expr, NULL))
2927     return SUCCESS;
2928   
2929   if (sym && sym->attr.intrinsic
2930       && resolve_intrinsic (sym, &expr->where) == FAILURE)
2931     return FAILURE;
2932
2933   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2934     {
2935       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2936       return FAILURE;
2937     }
2938
2939   /* If this ia a deferred TBP with an abstract interface (which may
2940      of course be referenced), expr->value.function.esym will be set.  */
2941   if (sym && sym->attr.abstract && !expr->value.function.esym)
2942     {
2943       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2944                  sym->name, &expr->where);
2945       return FAILURE;
2946     }
2947
2948   /* Switch off assumed size checking and do this again for certain kinds
2949      of procedure, once the procedure itself is resolved.  */
2950   need_full_assumed_size++;
2951
2952   if (expr->symtree && expr->symtree->n.sym)
2953     p = expr->symtree->n.sym->attr.proc;
2954
2955   if (expr->value.function.isym && expr->value.function.isym->inquiry)
2956     inquiry_argument = true;
2957   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
2958
2959   if (resolve_actual_arglist (expr->value.function.actual,
2960                               p, no_formal_args) == FAILURE)
2961     {
2962       inquiry_argument = false;
2963       return FAILURE;
2964     }
2965
2966   inquiry_argument = false;
2967  
2968   /* Need to setup the call to the correct c_associated, depending on
2969      the number of cptrs to user gives to compare.  */
2970   if (sym && sym->attr.is_iso_c == 1)
2971     {
2972       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
2973           == FAILURE)
2974         return FAILURE;
2975       
2976       /* Get the symtree for the new symbol (resolved func).
2977          the old one will be freed later, when it's no longer used.  */
2978       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
2979     }
2980   
2981   /* Resume assumed_size checking.  */
2982   need_full_assumed_size--;
2983
2984   /* If the procedure is external, check for usage.  */
2985   if (sym && is_external_proc (sym))
2986     resolve_global_procedure (sym, &expr->where,
2987                               &expr->value.function.actual, 0);
2988
2989   if (sym && sym->ts.type == BT_CHARACTER
2990       && sym->ts.u.cl
2991       && sym->ts.u.cl->length == NULL
2992       && !sym->attr.dummy
2993       && expr->value.function.esym == NULL
2994       && !sym->attr.contained)
2995     {
2996       /* Internal procedures are taken care of in resolve_contained_fntype.  */
2997       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
2998                  "be used at %L since it is not a dummy argument",
2999                  sym->name, &expr->where);
3000       return FAILURE;
3001     }
3002
3003   /* See if function is already resolved.  */
3004
3005   if (expr->value.function.name != NULL)
3006     {
3007       if (expr->ts.type == BT_UNKNOWN)
3008         expr->ts = sym->ts;
3009       t = SUCCESS;
3010     }
3011   else
3012     {
3013       /* Apply the rules of section 14.1.2.  */
3014
3015       switch (procedure_kind (sym))
3016         {
3017         case PTYPE_GENERIC:
3018           t = resolve_generic_f (expr);
3019           break;
3020
3021         case PTYPE_SPECIFIC:
3022           t = resolve_specific_f (expr);
3023           break;
3024
3025         case PTYPE_UNKNOWN:
3026           t = resolve_unknown_f (expr);
3027           break;
3028
3029         default:
3030           gfc_internal_error ("resolve_function(): bad function type");
3031         }
3032     }
3033
3034   /* If the expression is still a function (it might have simplified),
3035      then we check to see if we are calling an elemental function.  */
3036
3037   if (expr->expr_type != EXPR_FUNCTION)
3038     return t;
3039
3040   temp = need_full_assumed_size;
3041   need_full_assumed_size = 0;
3042
3043   if (resolve_elemental_actual (expr, NULL) == FAILURE)
3044     return FAILURE;
3045
3046   if (omp_workshare_flag
3047       && expr->value.function.esym
3048       && ! gfc_elemental (expr->value.function.esym))
3049     {
3050       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
3051                  "in WORKSHARE construct", expr->value.function.esym->name,
3052                  &expr->where);
3053       t = FAILURE;
3054     }
3055
3056 #define GENERIC_ID expr->value.function.isym->id
3057   else if (expr->value.function.actual != NULL
3058            && expr->value.function.isym != NULL
3059            && GENERIC_ID != GFC_ISYM_LBOUND
3060            && GENERIC_ID != GFC_ISYM_LEN
3061            && GENERIC_ID != GFC_ISYM_LOC
3062            && GENERIC_ID != GFC_ISYM_PRESENT)
3063     {
3064       /* Array intrinsics must also have the last upper bound of an
3065          assumed size array argument.  UBOUND and SIZE have to be
3066          excluded from the check if the second argument is anything
3067          than a constant.  */
3068
3069       for (arg = expr->value.function.actual; arg; arg = arg->next)
3070         {
3071           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
3072               && arg->next != NULL && arg->next->expr)
3073             {
3074               if (arg->next->expr->expr_type != EXPR_CONSTANT)
3075                 break;
3076
3077               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
3078                 break;
3079
3080               if ((int)mpz_get_si (arg->next->expr->value.integer)
3081                         < arg->expr->rank)
3082                 break;
3083             }
3084
3085           if (arg->expr != NULL
3086               && arg->expr->rank > 0
3087               && resolve_assumed_size_actual (arg->expr))
3088             return FAILURE;
3089         }
3090     }
3091 #undef GENERIC_ID
3092
3093   need_full_assumed_size = temp;
3094   name = NULL;
3095
3096   if (!pure_function (expr, &name) && name)
3097     {
3098       if (forall_flag)
3099         {
3100           gfc_error ("reference to non-PURE function '%s' at %L inside a "
3101                      "FORALL %s", name, &expr->where,
3102                      forall_flag == 2 ? "mask" : "block");
3103           t = FAILURE;
3104         }
3105       else if (gfc_pure (NULL))
3106         {
3107           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
3108                      "procedure within a PURE procedure", name, &expr->where);
3109           t = FAILURE;
3110         }
3111     }
3112
3113   if (!pure_function (expr, &name) && name && gfc_implicit_pure (NULL))
3114     gfc_current_ns->proc_name->attr.implicit_pure = 0;
3115
3116   /* Functions without the RECURSIVE attribution are not allowed to
3117    * call themselves.  */
3118   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
3119     {
3120       gfc_symbol *esym;
3121       esym = expr->value.function.esym;
3122
3123       if (is_illegal_recursion (esym, gfc_current_ns))
3124       {
3125         if (esym->attr.entry && esym->ns->entries)
3126           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3127                      " function '%s' is not RECURSIVE",
3128                      esym->name, &expr->where, esym->ns->entries->sym->name);
3129         else
3130           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
3131                      " is not RECURSIVE", esym->name, &expr->where);
3132
3133         t = FAILURE;
3134       }
3135     }
3136
3137   /* Character lengths of use associated functions may contains references to
3138      symbols not referenced from the current program unit otherwise.  Make sure
3139      those symbols are marked as referenced.  */
3140
3141   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
3142       && expr->value.function.esym->attr.use_assoc)
3143     {
3144       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
3145     }
3146
3147   /* Make sure that the expression has a typespec that works.  */
3148   if (expr->ts.type == BT_UNKNOWN)
3149     {
3150       if (expr->symtree->n.sym->result
3151             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
3152             && !expr->symtree->n.sym->result->attr.proc_pointer)
3153         expr->ts = expr->symtree->n.sym->result->ts;
3154     }
3155
3156   return t;
3157 }
3158
3159
3160 /************* Subroutine resolution *************/
3161
3162 static void
3163 pure_subroutine (gfc_code *c, gfc_symbol *sym)
3164 {
3165   if (gfc_pure (sym))
3166     return;
3167
3168   if (forall_flag)
3169     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
3170                sym->name, &c->loc);
3171   else if (gfc_pure (NULL))
3172     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
3173                &c->loc);
3174 }
3175
3176
3177 static match
3178 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
3179 {
3180   gfc_symbol *s;
3181
3182   if (sym->attr.generic)
3183     {
3184       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
3185       if (s != NULL)
3186         {
3187           c->resolved_sym = s;
3188           pure_subroutine (c, s);
3189           return MATCH_YES;
3190         }
3191
3192       /* TODO: Need to search for elemental references in generic interface.  */
3193     }
3194
3195   if (sym->attr.intrinsic)
3196     return gfc_intrinsic_sub_interface (c, 0);
3197
3198   return MATCH_NO;
3199 }
3200
3201
3202 static gfc_try
3203 resolve_generic_s (gfc_code *c)
3204 {
3205   gfc_symbol *sym;
3206   match m;
3207
3208   sym = c->symtree->n.sym;
3209
3210   for (;;)
3211     {
3212       m = resolve_generic_s0 (c, sym);
3213       if (m == MATCH_YES)
3214         return SUCCESS;
3215       else if (m == MATCH_ERROR)
3216         return FAILURE;
3217
3218 generic:
3219       if (sym->ns->parent == NULL)
3220         break;
3221       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3222
3223       if (sym == NULL)
3224         break;
3225       if (!generic_sym (sym))
3226         goto generic;
3227     }
3228
3229   /* Last ditch attempt.  See if the reference is to an intrinsic
3230      that possesses a matching interface.  14.1.2.4  */
3231   sym = c->symtree->n.sym;
3232
3233   if (!gfc_is_intrinsic (sym, 1, c->loc))
3234     {
3235       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
3236                  sym->name, &c->loc);
3237       return FAILURE;
3238     }
3239
3240   m = gfc_intrinsic_sub_interface (c, 0);
3241   if (m == MATCH_YES)
3242     return SUCCESS;
3243   if (m == MATCH_NO)
3244     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
3245                "intrinsic subroutine interface", sym->name, &c->loc);
3246
3247   return FAILURE;
3248 }
3249
3250
3251 /* Set the name and binding label of the subroutine symbol in the call
3252    expression represented by 'c' to include the type and kind of the
3253    second parameter.  This function is for resolving the appropriate
3254    version of c_f_pointer() and c_f_procpointer().  For example, a
3255    call to c_f_pointer() for a default integer pointer could have a
3256    name of c_f_pointer_i4.  If no second arg exists, which is an error
3257    for these two functions, it defaults to the generic symbol's name
3258    and binding label.  */
3259
3260 static void
3261 set_name_and_label (gfc_code *c, gfc_symbol *sym,
3262                     char *name, char *binding_label)
3263 {
3264   gfc_expr *arg = NULL;
3265   char type;
3266   int kind;
3267
3268   /* The second arg of c_f_pointer and c_f_procpointer determines
3269      the type and kind for the procedure name.  */
3270   arg = c->ext.actual->next->expr;
3271
3272   if (arg != NULL)
3273     {
3274       /* Set up the name to have the given symbol's name,
3275          plus the type and kind.  */
3276       /* a derived type is marked with the type letter 'u' */
3277       if (arg->ts.type == BT_DERIVED)
3278         {
3279           type = 'd';
3280           kind = 0; /* set the kind as 0 for now */
3281         }
3282       else
3283         {
3284           type = gfc_type_letter (arg->ts.type);
3285           kind = arg->ts.kind;
3286         }
3287
3288       if (arg->ts.type == BT_CHARACTER)
3289         /* Kind info for character strings not needed.  */
3290         kind = 0;
3291
3292       sprintf (name, "%s_%c%d", sym->name, type, kind);
3293       /* Set up the binding label as the given symbol's label plus
3294          the type and kind.  */
3295       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
3296     }
3297   else
3298     {
3299       /* If the second arg is missing, set the name and label as
3300          was, cause it should at least be found, and the missing
3301          arg error will be caught by compare_parameters().  */
3302       sprintf (name, "%s", sym->name);
3303       sprintf (binding_label, "%s", sym->binding_label);
3304     }
3305    
3306   return;
3307 }
3308
3309
3310 /* Resolve a generic version of the iso_c_binding procedure given
3311    (sym) to the specific one based on the type and kind of the
3312    argument(s).  Currently, this function resolves c_f_pointer() and
3313    c_f_procpointer based on the type and kind of the second argument
3314    (FPTR).  Other iso_c_binding procedures aren't specially handled.
3315    Upon successfully exiting, c->resolved_sym will hold the resolved
3316    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
3317    otherwise.  */
3318
3319 match
3320 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
3321 {
3322   gfc_symbol *new_sym;
3323   /* this is fine, since we know the names won't use the max */
3324   char name[GFC_MAX_SYMBOL_LEN + 1];
3325   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
3326   /* default to success; will override if find error */
3327   match m = MATCH_YES;
3328
3329   /* Make sure the actual arguments are in the necessary order (based on the 
3330      formal args) before resolving.  */
3331   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
3332
3333   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
3334       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
3335     {
3336       set_name_and_label (c, sym, name, binding_label);
3337       
3338       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
3339         {
3340           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
3341             {
3342               /* Make sure we got a third arg if the second arg has non-zero
3343                  rank.  We must also check that the type and rank are
3344                  correct since we short-circuit this check in
3345                  gfc_procedure_use() (called above to sort actual args).  */
3346               if (c->ext.actual->next->expr->rank != 0)
3347                 {
3348                   if(c->ext.actual->next->next == NULL 
3349                      || c->ext.actual->next->next->expr == NULL)
3350                     {
3351                       m = MATCH_ERROR;
3352                       gfc_error ("Missing SHAPE parameter for call to %s "
3353                                  "at %L", sym->name, &(c->loc));
3354                     }
3355                   else if (c->ext.actual->next->next->expr->ts.type
3356                            != BT_INTEGER
3357                            || c->ext.actual->next->next->expr->rank != 1)
3358                     {
3359                       m = MATCH_ERROR;
3360                       gfc_error ("SHAPE parameter for call to %s at %L must "
3361                                  "be a rank 1 INTEGER array", sym->name,
3362                                  &(c->loc));
3363                     }
3364                 }
3365             }
3366         }
3367       
3368       if (m != MATCH_ERROR)
3369         {
3370           /* the 1 means to add the optional arg to formal list */
3371           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
3372          
3373           /* for error reporting, say it's declared where the original was */
3374           new_sym->declared_at = sym->declared_at;
3375         }
3376     }
3377   else
3378     {
3379       /* no differences for c_loc or c_funloc */
3380       new_sym = sym;
3381     }
3382
3383   /* set the resolved symbol */
3384   if (m != MATCH_ERROR)
3385     c->resolved_sym = new_sym;
3386   else
3387     c->resolved_sym = sym;
3388   
3389   return m;
3390 }
3391
3392
3393 /* Resolve a subroutine call known to be specific.  */
3394
3395 static match
3396 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3397 {
3398   match m;
3399
3400   if(sym->attr.is_iso_c)
3401     {
3402       m = gfc_iso_c_sub_interface (c,sym);
3403       return m;
3404     }
3405   
3406   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3407     {
3408       if (sym->attr.dummy)
3409         {
3410           sym->attr.proc = PROC_DUMMY;
3411           goto found;
3412         }
3413
3414       sym->attr.proc = PROC_EXTERNAL;
3415       goto found;
3416     }
3417
3418   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3419     goto found;
3420
3421   if (sym->attr.intrinsic)
3422     {
3423       m = gfc_intrinsic_sub_interface (c, 1);
3424       if (m == MATCH_YES)
3425         return MATCH_YES;
3426       if (m == MATCH_NO)
3427         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3428                    "with an intrinsic", sym->name, &c->loc);
3429
3430       return MATCH_ERROR;
3431     }
3432
3433   return MATCH_NO;
3434
3435 found:
3436   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3437
3438   c->resolved_sym = sym;
3439   pure_subroutine (c, sym);
3440
3441   return MATCH_YES;
3442 }
3443
3444
3445 static gfc_try
3446 resolve_specific_s (gfc_code *c)
3447 {
3448   gfc_symbol *sym;
3449   match m;
3450
3451   sym = c->symtree->n.sym;
3452
3453   for (;;)
3454     {
3455       m = resolve_specific_s0 (c, sym);
3456       if (m == MATCH_YES)
3457         return SUCCESS;
3458       if (m == MATCH_ERROR)
3459         return FAILURE;
3460
3461       if (sym->ns->parent == NULL)
3462         break;
3463
3464       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3465
3466       if (sym == NULL)
3467         break;
3468     }
3469
3470   sym = c->symtree->n.sym;
3471   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3472              sym->name, &c->loc);
3473
3474   return FAILURE;
3475 }
3476
3477
3478 /* Resolve a subroutine call not known to be generic nor specific.  */
3479
3480 static gfc_try
3481 resolve_unknown_s (gfc_code *c)
3482 {
3483   gfc_symbol *sym;
3484
3485   sym = c->symtree->n.sym;
3486
3487   if (sym->attr.dummy)
3488     {
3489       sym->attr.proc = PROC_DUMMY;
3490       goto found;
3491     }
3492
3493   /* See if we have an intrinsic function reference.  */
3494
3495   if (gfc_is_intrinsic (sym, 1, c->loc))
3496     {
3497       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3498         return SUCCESS;
3499       return FAILURE;
3500     }
3501
3502   /* The reference is to an external name.  */
3503
3504 found:
3505   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3506
3507   c->resolved_sym = sym;
3508
3509   pure_subroutine (c, sym);
3510
3511   return SUCCESS;
3512 }
3513
3514
3515 /* Resolve a subroutine call.  Although it was tempting to use the same code
3516    for functions, subroutines and functions are stored differently and this
3517    makes things awkward.  */
3518
3519 static gfc_try
3520 resolve_call (gfc_code *c)
3521 {
3522   gfc_try t;
3523   procedure_type ptype = PROC_INTRINSIC;
3524   gfc_symbol *csym, *sym;
3525   bool no_formal_args;
3526
3527   csym = c->symtree ? c->symtree->n.sym : NULL;
3528
3529   if (csym && csym->ts.type != BT_UNKNOWN)
3530     {
3531       gfc_error ("'%s' at %L has a type, which is not consistent with "
3532                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3533       return FAILURE;
3534     }
3535
3536   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3537     {
3538       gfc_symtree *st;
3539       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
3540       sym = st ? st->n.sym : NULL;
3541       if (sym && csym != sym
3542               && sym->ns == gfc_current_ns
3543               && sym->attr.flavor == FL_PROCEDURE
3544               && sym->attr.contained)
3545         {
3546           sym->refs++;
3547           if (csym->attr.generic)
3548             c->symtree->n.sym = sym;
3549           else
3550             c->symtree = st;
3551           csym = c->symtree->n.sym;
3552         }
3553     }
3554
3555   /* If this ia a deferred TBP with an abstract interface
3556      (which may of course be referenced), c->expr1 will be set.  */
3557   if (csym && csym->attr.abstract && !c->expr1)
3558     {
3559       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3560                  csym->name, &c->loc);
3561       return FAILURE;
3562     }
3563
3564   /* Subroutines without the RECURSIVE attribution are not allowed to
3565    * call themselves.  */
3566   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3567     {
3568       if (csym->attr.entry && csym->ns->entries)
3569         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3570                    " subroutine '%s' is not RECURSIVE",
3571                    csym->name, &c->loc, csym->ns->entries->sym->name);
3572       else
3573         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3574                    " is not RECURSIVE", csym->name, &c->loc);
3575
3576       t = FAILURE;
3577     }
3578
3579   /* Switch off assumed size checking and do this again for certain kinds
3580      of procedure, once the procedure itself is resolved.  */
3581   need_full_assumed_size++;
3582
3583   if (csym)
3584     ptype = csym->attr.proc;
3585
3586   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3587   if (resolve_actual_arglist (c->ext.actual, ptype,
3588                               no_formal_args) == FAILURE)
3589     return FAILURE;
3590
3591   /* Resume assumed_size checking.  */
3592   need_full_assumed_size--;
3593
3594   /* If external, check for usage.  */
3595   if (csym && is_external_proc (csym))
3596     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3597
3598   t = SUCCESS;
3599   if (c->resolved_sym == NULL)
3600     {
3601       c->resolved_isym = NULL;
3602       switch (procedure_kind (csym))
3603         {
3604         case PTYPE_GENERIC:
3605           t = resolve_generic_s (c);
3606           break;
3607
3608         case PTYPE_SPECIFIC:
3609           t = resolve_specific_s (c);
3610           break;
3611
3612         case PTYPE_UNKNOWN:
3613           t = resolve_unknown_s (c);
3614           break;
3615
3616         default:
3617           gfc_internal_error ("resolve_subroutine(): bad function type");
3618         }
3619     }
3620
3621   /* Some checks of elemental subroutine actual arguments.  */
3622   if (resolve_elemental_actual (NULL, c) == FAILURE)
3623     return FAILURE;
3624
3625   return t;
3626 }
3627
3628
3629 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3630    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3631    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3632    if their shapes do not match.  If either op1->shape or op2->shape is
3633    NULL, return SUCCESS.  */
3634
3635 static gfc_try
3636 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3637 {
3638   gfc_try t;
3639   int i;
3640
3641   t = SUCCESS;
3642
3643   if (op1->shape != NULL && op2->shape != NULL)
3644     {
3645       for (i = 0; i < op1->rank; i++)
3646         {
3647           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3648            {
3649              gfc_error ("Shapes for operands at %L and %L are not conformable",
3650                          &op1->where, &op2->where);
3651              t = FAILURE;
3652              break;
3653            }
3654         }
3655     }
3656
3657   return t;
3658 }
3659
3660
3661 /* Resolve an operator expression node.  This can involve replacing the
3662    operation with a user defined function call.  */
3663
3664 static gfc_try
3665 resolve_operator (gfc_expr *e)
3666 {
3667   gfc_expr *op1, *op2;
3668   char msg[200];
3669   bool dual_locus_error;
3670   gfc_try t;
3671
3672   /* Resolve all subnodes-- give them types.  */
3673
3674   switch (e->value.op.op)
3675     {
3676     default:
3677       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3678         return FAILURE;
3679
3680     /* Fall through...  */
3681
3682     case INTRINSIC_NOT:
3683     case INTRINSIC_UPLUS:
3684     case INTRINSIC_UMINUS:
3685     case INTRINSIC_PARENTHESES:
3686       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3687         return FAILURE;
3688       break;
3689     }
3690
3691   /* Typecheck the new node.  */
3692
3693   op1 = e->value.op.op1;
3694   op2 = e->value.op.op2;
3695   dual_locus_error = false;
3696
3697   if ((op1 && op1->expr_type == EXPR_NULL)
3698       || (op2 && op2->expr_type == EXPR_NULL))
3699     {
3700       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3701       goto bad_op;
3702     }
3703
3704   switch (e->value.op.op)
3705     {
3706     case INTRINSIC_UPLUS:
3707     case INTRINSIC_UMINUS:
3708       if (op1->ts.type == BT_INTEGER
3709           || op1->ts.type == BT_REAL
3710           || op1->ts.type == BT_COMPLEX)
3711         {
3712           e->ts = op1->ts;
3713           break;
3714         }
3715
3716       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3717                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3718       goto bad_op;
3719
3720     case INTRINSIC_PLUS:
3721     case INTRINSIC_MINUS:
3722     case INTRINSIC_TIMES:
3723     case INTRINSIC_DIVIDE:
3724     case INTRINSIC_POWER:
3725       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3726         {
3727           gfc_type_convert_binary (e, 1);
3728           break;
3729         }
3730
3731       sprintf (msg,
3732                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3733                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3734                gfc_typename (&op2->ts));
3735       goto bad_op;
3736
3737     case INTRINSIC_CONCAT:
3738       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3739           && op1->ts.kind == op2->ts.kind)
3740         {
3741           e->ts.type = BT_CHARACTER;
3742           e->ts.kind = op1->ts.kind;
3743           break;
3744         }
3745
3746       sprintf (msg,
3747                _("Operands of string concatenation operator at %%L are %s/%s"),
3748                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3749       goto bad_op;
3750
3751     case INTRINSIC_AND:
3752     case INTRINSIC_OR:
3753     case INTRINSIC_EQV:
3754     case INTRINSIC_NEQV:
3755       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3756         {
3757           e->ts.type = BT_LOGICAL;
3758           e->ts.kind = gfc_kind_max (op1, op2);
3759           if (op1->ts.kind < e->ts.kind)
3760             gfc_convert_type (op1, &e->ts, 2);
3761           else if (op2->ts.kind < e->ts.kind)
3762             gfc_convert_type (op2, &e->ts, 2);
3763           break;
3764         }
3765
3766       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3767                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3768                gfc_typename (&op2->ts));
3769
3770       goto bad_op;
3771
3772     case INTRINSIC_NOT:
3773       if (op1->ts.type == BT_LOGICAL)
3774         {
3775           e->ts.type = BT_LOGICAL;
3776           e->ts.kind = op1->ts.kind;
3777           break;
3778         }
3779
3780       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3781                gfc_typename (&op1->ts));
3782       goto bad_op;
3783
3784     case INTRINSIC_GT:
3785     case INTRINSIC_GT_OS:
3786     case INTRINSIC_GE:
3787     case INTRINSIC_GE_OS:
3788     case INTRINSIC_LT:
3789     case INTRINSIC_LT_OS:
3790     case INTRINSIC_LE:
3791     case INTRINSIC_LE_OS:
3792       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3793         {
3794           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3795           goto bad_op;
3796         }
3797
3798       /* Fall through...  */
3799
3800     case INTRINSIC_EQ:
3801     case INTRINSIC_EQ_OS:
3802     case INTRINSIC_NE:
3803     case INTRINSIC_NE_OS:
3804       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3805           && op1->ts.kind == op2->ts.kind)
3806         {
3807           e->ts.type = BT_LOGICAL;
3808           e->ts.kind = gfc_default_logical_kind;
3809           break;
3810         }
3811
3812       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3813         {
3814           gfc_type_convert_binary (e, 1);
3815
3816           e->ts.type = BT_LOGICAL;
3817           e->ts.kind = gfc_default_logical_kind;
3818           break;
3819         }
3820
3821       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3822         sprintf (msg,
3823                  _("Logicals at %%L must be compared with %s instead of %s"),
3824                  (e->value.op.op == INTRINSIC_EQ 
3825                   || e->value.op.op == INTRINSIC_EQ_OS)
3826                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3827       else
3828         sprintf (msg,
3829                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3830                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3831                  gfc_typename (&op2->ts));
3832
3833       goto bad_op;
3834
3835     case INTRINSIC_USER:
3836       if (e->value.op.uop->op == NULL)
3837         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3838       else if (op2 == NULL)
3839         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3840                  e->value.op.uop->name, gfc_typename (&op1->ts));
3841       else
3842         {
3843           sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3844                    e->value.op.uop->name, gfc_typename (&op1->ts),
3845                    gfc_typename (&op2->ts));
3846           e->value.op.uop->op->sym->attr.referenced = 1;
3847         }
3848
3849       goto bad_op;
3850
3851     case INTRINSIC_PARENTHESES:
3852       e->ts = op1->ts;
3853       if (e->ts.type == BT_CHARACTER)
3854         e->ts.u.cl = op1->ts.u.cl;
3855       break;
3856
3857     default:
3858       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3859     }
3860
3861   /* Deal with arrayness of an operand through an operator.  */
3862
3863   t = SUCCESS;
3864
3865   switch (e->value.op.op)
3866     {
3867     case INTRINSIC_PLUS:
3868     case INTRINSIC_MINUS:
3869     case INTRINSIC_TIMES:
3870     case INTRINSIC_DIVIDE:
3871     case INTRINSIC_POWER:
3872     case INTRINSIC_CONCAT:
3873     case INTRINSIC_AND:
3874     case INTRINSIC_OR:
3875     case INTRINSIC_EQV:
3876     case INTRINSIC_NEQV:
3877     case INTRINSIC_EQ:
3878     case INTRINSIC_EQ_OS:
3879     case INTRINSIC_NE:
3880     case INTRINSIC_NE_OS:
3881     case INTRINSIC_GT:
3882     case INTRINSIC_GT_OS:
3883     case INTRINSIC_GE:
3884     case INTRINSIC_GE_OS:
3885     case INTRINSIC_LT:
3886     case INTRINSIC_LT_OS:
3887     case INTRINSIC_LE:
3888     case INTRINSIC_LE_OS:
3889
3890       if (op1->rank == 0 && op2->rank == 0)
3891         e->rank = 0;
3892
3893       if (op1->rank == 0 && op2->rank != 0)
3894         {
3895           e->rank = op2->rank;
3896
3897           if (e->shape == NULL)
3898             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3899         }
3900
3901       if (op1->rank != 0 && op2->rank == 0)
3902         {
3903           e->rank = op1->rank;
3904
3905           if (e->shape == NULL)
3906             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3907         }
3908
3909       if (op1->rank != 0 && op2->rank != 0)
3910         {
3911           if (op1->rank == op2->rank)
3912             {
3913               e->rank = op1->rank;
3914               if (e->shape == NULL)
3915                 {
3916                   t = compare_shapes (op1, op2);
3917                   if (t == FAILURE)
3918                     e->shape = NULL;
3919                   else
3920                     e->shape = gfc_copy_shape (op1->shape, op1->rank);
3921                 }
3922             }
3923           else
3924             {
3925               /* Allow higher level expressions to work.  */
3926               e->rank = 0;
3927
3928               /* Try user-defined operators, and otherwise throw an error.  */
3929               dual_locus_error = true;
3930               sprintf (msg,
3931                        _("Inconsistent ranks for operator at %%L and %%L"));
3932               goto bad_op;
3933             }
3934         }
3935
3936       break;
3937
3938     case INTRINSIC_PARENTHESES:
3939     case INTRINSIC_NOT:
3940     case INTRINSIC_UPLUS:
3941     case INTRINSIC_UMINUS:
3942       /* Simply copy arrayness attribute */
3943       e->rank = op1->rank;
3944
3945       if (e->shape == NULL)
3946         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3947
3948       break;
3949
3950     default:
3951       break;
3952     }
3953
3954   /* Attempt to simplify the expression.  */
3955   if (t == SUCCESS)
3956     {
3957       t = gfc_simplify_expr (e, 0);
3958       /* Some calls do not succeed in simplification and return FAILURE
3959          even though there is no error; e.g. variable references to
3960          PARAMETER arrays.  */
3961       if (!gfc_is_constant_expr (e))
3962         t = SUCCESS;
3963     }
3964   return t;
3965
3966 bad_op:
3967
3968   {
3969     bool real_error;
3970     if (gfc_extend_expr (e, &real_error) == SUCCESS)
3971       return SUCCESS;
3972
3973     if (real_error)
3974       return FAILURE;
3975   }
3976
3977   if (dual_locus_error)
3978     gfc_error (msg, &op1->where, &op2->where);
3979   else
3980     gfc_error (msg, &e->where);
3981
3982   return FAILURE;
3983 }
3984
3985
3986 /************** Array resolution subroutines **************/
3987
3988 typedef enum
3989 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
3990 comparison;
3991
3992 /* Compare two integer expressions.  */
3993
3994 static comparison
3995 compare_bound (gfc_expr *a, gfc_expr *b)
3996 {
3997   int i;
3998
3999   if (a == NULL || a->expr_type != EXPR_CONSTANT
4000       || b == NULL || b->expr_type != EXPR_CONSTANT)
4001     return CMP_UNKNOWN;
4002
4003   /* If either of the types isn't INTEGER, we must have
4004      raised an error earlier.  */
4005
4006   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
4007     return CMP_UNKNOWN;
4008
4009   i = mpz_cmp (a->value.integer, b->value.integer);
4010
4011   if (i < 0)
4012     return CMP_LT;
4013   if (i > 0)
4014     return CMP_GT;
4015   return CMP_EQ;
4016 }
4017
4018
4019 /* Compare an integer expression with an integer.  */
4020
4021 static comparison
4022 compare_bound_int (gfc_expr *a, int b)
4023 {
4024   int i;
4025
4026   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4027     return CMP_UNKNOWN;
4028
4029   if (a->ts.type != BT_INTEGER)
4030     gfc_internal_error ("compare_bound_int(): Bad expression");
4031
4032   i = mpz_cmp_si (a->value.integer, b);
4033
4034   if (i < 0)
4035     return CMP_LT;
4036   if (i > 0)
4037     return CMP_GT;
4038   return CMP_EQ;
4039 }
4040
4041
4042 /* Compare an integer expression with a mpz_t.  */
4043
4044 static comparison
4045 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
4046 {
4047   int i;
4048
4049   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4050     return CMP_UNKNOWN;
4051
4052   if (a->ts.type != BT_INTEGER)
4053     gfc_internal_error ("compare_bound_int(): Bad expression");
4054
4055   i = mpz_cmp (a->value.integer, b);
4056
4057   if (i < 0)
4058     return CMP_LT;
4059   if (i > 0)
4060     return CMP_GT;
4061   return CMP_EQ;
4062 }
4063
4064
4065 /* Compute the last value of a sequence given by a triplet.  
4066    Return 0 if it wasn't able to compute the last value, or if the
4067    sequence if empty, and 1 otherwise.  */
4068
4069 static int
4070 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
4071                                 gfc_expr *stride, mpz_t last)
4072 {
4073   mpz_t rem;
4074
4075   if (start == NULL || start->expr_type != EXPR_CONSTANT
4076       || end == NULL || end->expr_type != EXPR_CONSTANT
4077       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
4078     return 0;
4079
4080   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
4081       || (stride != NULL && stride->ts.type != BT_INTEGER))
4082     return 0;
4083
4084   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
4085     {
4086       if (compare_bound (start, end) == CMP_GT)
4087         return 0;
4088       mpz_set (last, end->value.integer);
4089       return 1;
4090     }
4091
4092   if (compare_bound_int (stride, 0) == CMP_GT)
4093     {
4094       /* Stride is positive */
4095       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
4096         return 0;
4097     }
4098   else
4099     {
4100       /* Stride is negative */
4101       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
4102         return 0;
4103     }
4104
4105   mpz_init (rem);
4106   mpz_sub (rem, end->value.integer, start->value.integer);
4107   mpz_tdiv_r (rem, rem, stride->value.integer);
4108   mpz_sub (last, end->value.integer, rem);
4109   mpz_clear (rem);
4110
4111   return 1;
4112 }
4113
4114
4115 /* Compare a single dimension of an array reference to the array
4116    specification.  */
4117
4118 static gfc_try
4119 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
4120 {
4121   mpz_t last_value;
4122
4123   if (ar->dimen_type[i] == DIMEN_STAR)
4124     {
4125       gcc_assert (ar->stride[i] == NULL);
4126       /* This implies [*] as [*:] and [*:3] are not possible.  */
4127       if (ar->start[i] == NULL)
4128         {
4129           gcc_assert (ar->end[i] == NULL);
4130           return SUCCESS;
4131         }
4132     }
4133
4134 /* Given start, end and stride values, calculate the minimum and
4135    maximum referenced indexes.  */
4136
4137   switch (ar->dimen_type[i])
4138     {
4139     case DIMEN_VECTOR:
4140       break;
4141
4142     case DIMEN_STAR:
4143     case DIMEN_ELEMENT:
4144       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
4145         {
4146           if (i < as->rank)
4147             gfc_warning ("Array reference at %L is out of bounds "
4148                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
4149                          mpz_get_si (ar->start[i]->value.integer),
4150                          mpz_get_si (as->lower[i]->value.integer), i+1);
4151           else
4152             gfc_warning ("Array reference at %L is out of bounds "
4153                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
4154                          mpz_get_si (ar->start[i]->value.integer),
4155                          mpz_get_si (as->lower[i]->value.integer),
4156                          i + 1 - as->rank);
4157           return SUCCESS;
4158         }
4159       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
4160         {
4161           if (i < as->rank)
4162             gfc_warning ("Array reference at %L is out of bounds "
4163                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
4164                          mpz_get_si (ar->start[i]->value.integer),
4165                          mpz_get_si (as->upper[i]->value.integer), i+1);
4166           else
4167             gfc_warning ("Array reference at %L is out of bounds "
4168                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
4169                          mpz_get_si (ar->start[i]->value.integer),
4170                          mpz_get_si (as->upper[i]->value.integer),
4171                          i + 1 - as->rank);
4172           return SUCCESS;
4173         }
4174
4175       break;
4176
4177     case DIMEN_RANGE:
4178       {
4179 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
4180 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
4181
4182         comparison comp_start_end = compare_bound (AR_START, AR_END);
4183
4184         /* Check for zero stride, which is not allowed.  */
4185         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
4186           {
4187             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
4188             return FAILURE;
4189           }
4190
4191         /* if start == len || (stride > 0 && start < len)
4192                            || (stride < 0 && start > len),
4193            then the array section contains at least one element.  In this
4194            case, there is an out-of-bounds access if
4195            (start < lower || start > upper).  */
4196         if (compare_bound (AR_START, AR_END) == CMP_EQ
4197             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
4198                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
4199             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
4200                 && comp_start_end == CMP_GT))
4201           {
4202             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
4203               {
4204                 gfc_warning ("Lower array reference at %L is out of bounds "
4205                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4206                        mpz_get_si (AR_START->value.integer),
4207                        mpz_get_si (as->lower[i]->value.integer), i+1);
4208                 return SUCCESS;
4209               }
4210             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
4211               {
4212                 gfc_warning ("Lower array reference at %L is out of bounds "
4213                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4214                        mpz_get_si (AR_START->value.integer),
4215                        mpz_get_si (as->upper[i]->value.integer), i+1);
4216                 return SUCCESS;
4217               }
4218           }
4219
4220         /* If we can compute the highest index of the array section,
4221            then it also has to be between lower and upper.  */
4222         mpz_init (last_value);
4223         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
4224                                             last_value))
4225           {
4226             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
4227               {
4228                 gfc_warning ("Upper array reference at %L is out of bounds "
4229                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4230                        mpz_get_si (last_value),
4231                        mpz_get_si (as->lower[i]->value.integer), i+1);
4232                 mpz_clear (last_value);
4233                 return SUCCESS;
4234               }
4235             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
4236               {
4237                 gfc_warning ("Upper array reference at %L is out of bounds "
4238                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4239                        mpz_get_si (last_value),
4240                        mpz_get_si (as->upper[i]->value.integer), i+1);
4241                 mpz_clear (last_value);
4242                 return SUCCESS;
4243               }
4244           }
4245         mpz_clear (last_value);
4246
4247 #undef AR_START
4248 #undef AR_END
4249       }
4250       break;
4251
4252     default:
4253       gfc_internal_error ("check_dimension(): Bad array reference");
4254     }
4255
4256   return SUCCESS;
4257 }
4258
4259
4260 /* Compare an array reference with an array specification.  */
4261
4262 static gfc_try
4263 compare_spec_to_ref (gfc_array_ref *ar)
4264 {
4265   gfc_array_spec *as;
4266   int i;
4267
4268   as = ar->as;
4269   i = as->rank - 1;
4270   /* TODO: Full array sections are only allowed as actual parameters.  */
4271   if (as->type == AS_ASSUMED_SIZE
4272       && (/*ar->type == AR_FULL
4273           ||*/ (ar->type == AR_SECTION
4274               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
4275     {
4276       gfc_error ("Rightmost upper bound of assumed size array section "
4277                  "not specified at %L", &ar->where);
4278       return FAILURE;
4279     }
4280
4281   if (ar->type == AR_FULL)
4282     return SUCCESS;
4283
4284   if (as->rank != ar->dimen)
4285     {
4286       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
4287                  &ar->where, ar->dimen, as->rank);
4288       return FAILURE;
4289     }
4290
4291   /* ar->codimen == 0 is a local array.  */
4292   if (as->corank != ar->codimen && ar->codimen != 0)
4293     {
4294       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
4295                  &ar->where, ar->codimen, as->corank);
4296       return FAILURE;
4297     }
4298
4299   for (i = 0; i < as->rank; i++)
4300     if (check_dimension (i, ar, as) == FAILURE)
4301       return FAILURE;
4302
4303   /* Local access has no coarray spec.  */
4304   if (ar->codimen != 0)
4305     for (i = as->rank; i < as->rank + as->corank; i++)
4306       {
4307         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate)
4308           {
4309             gfc_error ("Coindex of codimension %d must be a scalar at %L",
4310                        i + 1 - as->rank, &ar->where);
4311             return FAILURE;
4312           }
4313         if (check_dimension (i, ar, as) == FAILURE)
4314           return FAILURE;
4315       }
4316
4317   return SUCCESS;
4318 }
4319
4320
4321 /* Resolve one part of an array index.  */
4322
4323 static gfc_try
4324 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
4325                      int force_index_integer_kind)
4326 {
4327   gfc_typespec ts;
4328
4329   if (index == NULL)
4330     return SUCCESS;
4331
4332   if (gfc_resolve_expr (index) == FAILURE)
4333     return FAILURE;
4334
4335   if (check_scalar && index->rank != 0)
4336     {
4337       gfc_error ("Array index at %L must be scalar", &index->where);
4338       return FAILURE;
4339     }
4340
4341   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4342     {
4343       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4344                  &index->where, gfc_basic_typename (index->ts.type));
4345       return FAILURE;
4346     }
4347
4348   if (index->ts.type == BT_REAL)
4349     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
4350                         &index->where) == FAILURE)
4351       return FAILURE;
4352
4353   if ((index->ts.kind != gfc_index_integer_kind
4354        && force_index_integer_kind)
4355       || index->ts.type != BT_INTEGER)
4356     {
4357       gfc_clear_ts (&ts);
4358       ts.type = BT_INTEGER;
4359       ts.kind = gfc_index_integer_kind;
4360
4361       gfc_convert_type_warn (index, &ts, 2, 0);
4362     }
4363
4364   return SUCCESS;
4365 }
4366
4367 /* Resolve one part of an array index.  */
4368
4369 gfc_try
4370 gfc_resolve_index (gfc_expr *index, int check_scalar)
4371 {
4372   return gfc_resolve_index_1 (index, check_scalar, 1);
4373 }
4374
4375 /* Resolve a dim argument to an intrinsic function.  */
4376
4377 gfc_try
4378 gfc_resolve_dim_arg (gfc_expr *dim)
4379 {
4380   if (dim == NULL)
4381     return SUCCESS;
4382
4383   if (gfc_resolve_expr (dim) == FAILURE)
4384     return FAILURE;
4385
4386   if (dim->rank != 0)
4387     {
4388       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4389       return FAILURE;
4390
4391     }
4392
4393   if (dim->ts.type != BT_INTEGER)
4394     {
4395       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4396       return FAILURE;
4397     }
4398
4399   if (dim->ts.kind != gfc_index_integer_kind)
4400     {
4401       gfc_typespec ts;
4402
4403       gfc_clear_ts (&ts);
4404       ts.type = BT_INTEGER;
4405       ts.kind = gfc_index_integer_kind;
4406
4407       gfc_convert_type_warn (dim, &ts, 2, 0);
4408     }
4409
4410   return SUCCESS;
4411 }
4412
4413 /* Given an expression that contains array references, update those array
4414    references to point to the right array specifications.  While this is
4415    filled in during matching, this information is difficult to save and load
4416    in a module, so we take care of it here.
4417
4418    The idea here is that the original array reference comes from the
4419    base symbol.  We traverse the list of reference structures, setting
4420    the stored reference to references.  Component references can
4421    provide an additional array specification.  */
4422
4423 static void
4424 find_array_spec (gfc_expr *e)
4425 {
4426   gfc_array_spec *as;
4427   gfc_component *c;
4428   gfc_symbol *derived;
4429   gfc_ref *ref;
4430
4431   if (e->symtree->n.sym->ts.type == BT_CLASS)
4432     as = CLASS_DATA (e->symtree->n.sym)->as;
4433   else
4434     as = e->symtree->n.sym->as;
4435   derived = NULL;
4436
4437   for (ref = e->ref; ref; ref = ref->next)
4438     switch (ref->type)
4439       {
4440       case REF_ARRAY:
4441         if (as == NULL)
4442           gfc_internal_error ("find_array_spec(): Missing spec");
4443
4444         ref->u.ar.as = as;
4445         as = NULL;
4446         break;
4447
4448       case REF_COMPONENT:
4449         if (derived == NULL)
4450           derived = e->symtree->n.sym->ts.u.derived;
4451
4452         if (derived->attr.is_class)
4453           derived = derived->components->ts.u.derived;
4454
4455         c = derived->components;
4456
4457         for (; c; c = c->next)
4458           if (c == ref->u.c.component)
4459             {
4460               /* Track the sequence of component references.  */
4461               if (c->ts.type == BT_DERIVED)
4462                 derived = c->ts.u.derived;
4463               break;
4464             }
4465
4466         if (c == NULL)
4467           gfc_internal_error ("find_array_spec(): Component not found");
4468
4469         if (c->attr.dimension)
4470           {
4471             if (as != NULL)
4472               gfc_internal_error ("find_array_spec(): unused as(1)");
4473             as = c->as;
4474           }
4475
4476         break;
4477
4478       case REF_SUBSTRING:
4479         break;
4480       }
4481
4482   if (as != NULL)
4483     gfc_internal_error ("find_array_spec(): unused as(2)");
4484 }
4485
4486
4487 /* Resolve an array reference.  */
4488
4489 static gfc_try
4490 resolve_array_ref (gfc_array_ref *ar)
4491 {
4492   int i, check_scalar;
4493   gfc_expr *e;
4494
4495   for (i = 0; i < ar->dimen + ar->codimen; i++)
4496     {
4497       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4498
4499       /* Do not force gfc_index_integer_kind for the start.  We can
4500          do fine with any integer kind.  This avoids temporary arrays
4501          created for indexing with a vector.  */
4502       if (gfc_resolve_index_1 (ar->start[i], check_scalar, 0) == FAILURE)
4503         return FAILURE;
4504       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4505         return FAILURE;
4506       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4507         return FAILURE;
4508
4509       e = ar->start[i];
4510
4511       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4512         switch (e->rank)
4513           {
4514           case 0:
4515             ar->dimen_type[i] = DIMEN_ELEMENT;
4516             break;
4517
4518           case 1:
4519             ar->dimen_type[i] = DIMEN_VECTOR;
4520             if (e->expr_type == EXPR_VARIABLE
4521                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4522               ar->start[i] = gfc_get_parentheses (e);
4523             break;
4524
4525           default:
4526             gfc_error ("Array index at %L is an array of rank %d",
4527                        &ar->c_where[i], e->rank);
4528             return FAILURE;
4529           }
4530
4531       /* Fill in the upper bound, which may be lower than the
4532          specified one for something like a(2:10:5), which is
4533          identical to a(2:7:5).  Only relevant for strides not equal
4534          to one.  */
4535       if (ar->dimen_type[i] == DIMEN_RANGE
4536           && ar->stride[i] != NULL && ar->stride[i]->expr_type == EXPR_CONSTANT
4537           && mpz_cmp_si (ar->stride[i]->value.integer, 1L) != 0)
4538         {
4539           mpz_t size, end;
4540
4541           if (gfc_ref_dimen_size (ar, i, &size, &end) == SUCCESS)
4542             {
4543               if (ar->end[i] == NULL)
4544                 {
4545                   ar->end[i] =
4546                     gfc_get_constant_expr (BT_INTEGER, gfc_index_integer_kind,
4547                                            &ar->where);
4548                   mpz_set (ar->end[i]->value.integer, end);
4549                 }
4550               else if (ar->end[i]->ts.type == BT_INTEGER
4551                        && ar->end[i]->expr_type == EXPR_CONSTANT)
4552                 {
4553                   mpz_set (ar->end[i]->value.integer, end);
4554                 }
4555               else
4556                 gcc_unreachable ();
4557
4558               mpz_clear (size);
4559               mpz_clear (end);
4560             }
4561         }
4562     }
4563
4564   if (ar->type == AR_FULL && ar->as->rank == 0)
4565     ar->type = AR_ELEMENT;
4566
4567   /* If the reference type is unknown, figure out what kind it is.  */
4568
4569   if (ar->type == AR_UNKNOWN)
4570     {
4571       ar->type = AR_ELEMENT;
4572       for (i = 0; i < ar->dimen; i++)
4573         if (ar->dimen_type[i] == DIMEN_RANGE
4574             || ar->dimen_type[i] == DIMEN_VECTOR)
4575           {
4576             ar->type = AR_SECTION;
4577             break;
4578           }
4579     }
4580
4581   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4582     return FAILURE;
4583
4584   return SUCCESS;
4585 }
4586
4587
4588 static gfc_try
4589 resolve_substring (gfc_ref *ref)
4590 {
4591   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4592
4593   if (ref->u.ss.start != NULL)
4594     {
4595       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4596         return FAILURE;
4597
4598       if (ref->u.ss.start->ts.type != BT_INTEGER)
4599         {
4600           gfc_error ("Substring start index at %L must be of type INTEGER",
4601                      &ref->u.ss.start->where);
4602           return FAILURE;
4603         }
4604
4605       if (ref->u.ss.start->rank != 0)
4606         {
4607           gfc_error ("Substring start index at %L must be scalar",
4608                      &ref->u.ss.start->where);
4609           return FAILURE;
4610         }
4611
4612       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4613           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4614               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4615         {
4616           gfc_error ("Substring start index at %L is less than one",
4617                      &ref->u.ss.start->where);
4618           return FAILURE;
4619         }
4620     }
4621
4622   if (ref->u.ss.end != NULL)
4623     {
4624       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4625         return FAILURE;
4626
4627       if (ref->u.ss.end->ts.type != BT_INTEGER)
4628         {
4629           gfc_error ("Substring end index at %L must be of type INTEGER",
4630                      &ref->u.ss.end->where);
4631           return FAILURE;
4632         }
4633
4634       if (ref->u.ss.end->rank != 0)
4635         {
4636           gfc_error ("Substring end index at %L must be scalar",
4637                      &ref->u.ss.end->where);
4638           return FAILURE;
4639         }
4640
4641       if (ref->u.ss.length != NULL
4642           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4643           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4644               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4645         {
4646           gfc_error ("Substring end index at %L exceeds the string length",
4647                      &ref->u.ss.start->where);
4648           return FAILURE;
4649         }
4650
4651       if (compare_bound_mpz_t (ref->u.ss.end,
4652                                gfc_integer_kinds[k].huge) == CMP_GT
4653           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4654               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4655         {
4656           gfc_error ("Substring end index at %L is too large",
4657                      &ref->u.ss.end->where);
4658           return FAILURE;
4659         }
4660     }
4661
4662   return SUCCESS;
4663 }
4664
4665
4666 /* This function supplies missing substring charlens.  */
4667
4668 void
4669 gfc_resolve_substring_charlen (gfc_expr *e)
4670 {
4671   gfc_ref *char_ref;
4672   gfc_expr *start, *end;
4673
4674   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4675     if (char_ref->type == REF_SUBSTRING)
4676       break;
4677
4678   if (!char_ref)
4679     return;
4680
4681   gcc_assert (char_ref->next == NULL);
4682
4683   if (e->ts.u.cl)
4684     {
4685       if (e->ts.u.cl->length)
4686         gfc_free_expr (e->ts.u.cl->length);
4687       else if (e->expr_type == EXPR_VARIABLE
4688                  && e->symtree->n.sym->attr.dummy)
4689         return;
4690     }
4691
4692   e->ts.type = BT_CHARACTER;
4693   e->ts.kind = gfc_default_character_kind;
4694
4695   if (!e->ts.u.cl)
4696     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4697
4698   if (char_ref->u.ss.start)
4699     start = gfc_copy_expr (char_ref->u.ss.start);
4700   else
4701     start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
4702
4703   if (char_ref->u.ss.end)
4704     end = gfc_copy_expr (char_ref->u.ss.end);
4705   else if (e->expr_type == EXPR_VARIABLE)
4706     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4707   else
4708     end = NULL;
4709
4710   if (!start || !end)
4711     return;
4712
4713   /* Length = (end - start +1).  */
4714   e->ts.u.cl->length = gfc_subtract (end, start);
4715   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
4716                                 gfc_get_int_expr (gfc_default_integer_kind,
4717                                                   NULL, 1));
4718
4719   e->ts.u.cl->length->ts.type = BT_INTEGER;
4720   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4721
4722   /* Make sure that the length is simplified.  */
4723   gfc_simplify_expr (e->ts.u.cl->length, 1);
4724   gfc_resolve_expr (e->ts.u.cl->length);
4725 }
4726
4727
4728 /* Resolve subtype references.  */
4729
4730 static gfc_try
4731 resolve_ref (gfc_expr *expr)
4732 {
4733   int current_part_dimension, n_components, seen_part_dimension;
4734   gfc_ref *ref;
4735
4736   for (ref = expr->ref; ref; ref = ref->next)
4737     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4738       {
4739         find_array_spec (expr);
4740         break;
4741       }
4742
4743   for (ref = expr->ref; ref; ref = ref->next)
4744     switch (ref->type)
4745       {
4746       case REF_ARRAY:
4747         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4748           return FAILURE;
4749         break;
4750
4751       case REF_COMPONENT:
4752         break;
4753
4754       case REF_SUBSTRING:
4755         resolve_substring (ref);
4756         break;
4757       }
4758
4759   /* Check constraints on part references.  */
4760
4761   current_part_dimension = 0;
4762   seen_part_dimension = 0;
4763   n_components = 0;
4764
4765   for (ref = expr->ref; ref; ref = ref->next)
4766     {
4767       switch (ref->type)
4768         {
4769         case REF_ARRAY:
4770           switch (ref->u.ar.type)
4771             {
4772             case AR_FULL:
4773               /* Coarray scalar.  */
4774               if (ref->u.ar.as->rank == 0)
4775                 {
4776                   current_part_dimension = 0;
4777                   break;
4778                 }
4779               /* Fall through.  */
4780             case AR_SECTION:
4781               current_part_dimension = 1;
4782               break;
4783
4784             case AR_ELEMENT:
4785               current_part_dimension = 0;
4786               break;
4787
4788             case AR_UNKNOWN:
4789               gfc_internal_error ("resolve_ref(): Bad array reference");
4790             }
4791
4792           break;
4793
4794         case REF_COMPONENT:
4795           if (current_part_dimension || seen_part_dimension)
4796             {
4797               /* F03:C614.  */
4798               if (ref->u.c.component->attr.pointer
4799                   || ref->u.c.component->attr.proc_pointer)
4800                 {
4801                   gfc_error ("Component to the right of a part reference "
4802                              "with nonzero rank must not have the POINTER "
4803                              "attribute at %L", &expr->where);
4804                   return FAILURE;
4805                 }
4806               else if (ref->u.c.component->attr.allocatable)
4807                 {
4808                   gfc_error ("Component to the right of a part reference "
4809                              "with nonzero rank must not have the ALLOCATABLE "
4810                              "attribute at %L", &expr->where);
4811                   return FAILURE;
4812                 }
4813             }
4814
4815           n_components++;
4816           break;
4817
4818         case REF_SUBSTRING:
4819           break;
4820         }
4821
4822       if (((ref->type == REF_COMPONENT && n_components > 1)
4823            || ref->next == NULL)
4824           && current_part_dimension
4825           && seen_part_dimension)
4826         {
4827           gfc_error ("Two or more part references with nonzero rank must "
4828                      "not be specified at %L", &expr->where);
4829           return FAILURE;
4830         }
4831
4832       if (ref->type == REF_COMPONENT)
4833         {
4834           if (current_part_dimension)
4835             seen_part_dimension = 1;
4836
4837           /* reset to make sure */
4838           current_part_dimension = 0;
4839         }
4840     }
4841
4842   return SUCCESS;
4843 }
4844
4845
4846 /* Given an expression, determine its shape.  This is easier than it sounds.
4847    Leaves the shape array NULL if it is not possible to determine the shape.  */
4848
4849 static void
4850 expression_shape (gfc_expr *e)
4851 {
4852   mpz_t array[GFC_MAX_DIMENSIONS];
4853   int i;
4854
4855   if (e->rank == 0 || e->shape != NULL)
4856     return;
4857
4858   for (i = 0; i < e->rank; i++)
4859     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4860       goto fail;
4861
4862   e->shape = gfc_get_shape (e->rank);
4863
4864   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4865
4866   return;
4867
4868 fail:
4869   for (i--; i >= 0; i--)
4870     mpz_clear (array[i]);
4871 }
4872
4873
4874 /* Given a variable expression node, compute the rank of the expression by
4875    examining the base symbol and any reference structures it may have.  */
4876
4877 static void
4878 expression_rank (gfc_expr *e)
4879 {
4880   gfc_ref *ref;
4881   int i, rank;
4882
4883   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4884      could lead to serious confusion...  */
4885   gcc_assert (e->expr_type != EXPR_COMPCALL);
4886
4887   if (e->ref == NULL)
4888     {
4889       if (e->expr_type == EXPR_ARRAY)
4890         goto done;
4891       /* Constructors can have a rank different from one via RESHAPE().  */
4892
4893       if (e->symtree == NULL)
4894         {
4895           e->rank = 0;
4896           goto done;
4897         }
4898
4899       e->rank = (e->symtree->n.sym->as == NULL)
4900                 ? 0 : e->symtree->n.sym->as->rank;
4901       goto done;
4902     }
4903
4904   rank = 0;
4905
4906   for (ref = e->ref; ref; ref = ref->next)
4907     {
4908       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.proc_pointer
4909           && ref->u.c.component->attr.function && !ref->next)
4910         rank = ref->u.c.component->as ? ref->u.c.component->as->rank : 0;
4911
4912       if (ref->type != REF_ARRAY)
4913         continue;
4914
4915       if (ref->u.ar.type == AR_FULL)
4916         {
4917           rank = ref->u.ar.as->rank;
4918           break;
4919         }
4920
4921       if (ref->u.ar.type == AR_SECTION)
4922         {
4923           /* Figure out the rank of the section.  */
4924           if (rank != 0)
4925             gfc_internal_error ("expression_rank(): Two array specs");
4926
4927           for (i = 0; i < ref->u.ar.dimen; i++)
4928             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4929                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4930               rank++;
4931
4932           break;
4933         }
4934     }
4935
4936   e->rank = rank;
4937
4938 done:
4939   expression_shape (e);
4940 }
4941
4942
4943 /* Resolve a variable expression.  */
4944
4945 static gfc_try
4946 resolve_variable (gfc_expr *e)
4947 {
4948   gfc_symbol *sym;
4949   gfc_try t;
4950
4951   t = SUCCESS;
4952
4953   if (e->symtree == NULL)
4954     return FAILURE;
4955   sym = e->symtree->n.sym;
4956
4957   /* If this is an associate-name, it may be parsed with an array reference
4958      in error even though the target is scalar.  Fail directly in this case.  */
4959   if (sym->assoc && !sym->attr.dimension && e->ref && e->ref->type == REF_ARRAY)
4960     return FAILURE;
4961
4962   /* On the other hand, the parser may not have known this is an array;
4963      in this case, we have to add a FULL reference.  */
4964   if (sym->assoc && sym->attr.dimension && !e->ref)
4965     {
4966       e->ref = gfc_get_ref ();
4967       e->ref->type = REF_ARRAY;
4968       e->ref->u.ar.type = AR_FULL;
4969       e->ref->u.ar.dimen = 0;
4970     }
4971
4972   if (e->ref && resolve_ref (e) == FAILURE)
4973     return FAILURE;
4974
4975   if (sym->attr.flavor == FL_PROCEDURE
4976       && (!sym->attr.function
4977           || (sym->attr.function && sym->result
4978               && sym->result->attr.proc_pointer
4979               && !sym->result->attr.function)))
4980     {
4981       e->ts.type = BT_PROCEDURE;
4982       goto resolve_procedure;
4983     }
4984
4985   if (sym->ts.type != BT_UNKNOWN)
4986     gfc_variable_attr (e, &e->ts);
4987   else
4988     {
4989       /* Must be a simple variable reference.  */
4990       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
4991         return FAILURE;
4992       e->ts = sym->ts;
4993     }
4994
4995   if (check_assumed_size_reference (sym, e))
4996     return FAILURE;
4997
4998   /* Deal with forward references to entries during resolve_code, to
4999      satisfy, at least partially, 12.5.2.5.  */
5000   if (gfc_current_ns->entries
5001       && current_entry_id == sym->entry_id
5002       && cs_base
5003       && cs_base->current
5004       && cs_base->current->op != EXEC_ENTRY)
5005     {
5006       gfc_entry_list *entry;
5007       gfc_formal_arglist *formal;
5008       int n;
5009       bool seen;
5010
5011       /* If the symbol is a dummy...  */
5012       if (sym->attr.dummy && sym->ns == gfc_current_ns)
5013         {
5014           entry = gfc_current_ns->entries;
5015           seen = false;
5016
5017           /* ...test if the symbol is a parameter of previous entries.  */
5018           for (; entry && entry->id <= current_entry_id; entry = entry->next)
5019             for (formal = entry->sym->formal; formal; formal = formal->next)
5020               {
5021                 if (formal->sym && sym->name == formal->sym->name)
5022                   seen = true;
5023               }
5024
5025           /*  If it has not been seen as a dummy, this is an error.  */
5026           if (!seen)
5027             {
5028               if (specification_expr)
5029                 gfc_error ("Variable '%s', used in a specification expression"
5030                            ", is referenced at %L before the ENTRY statement "
5031                            "in which it is a parameter",
5032                            sym->name, &cs_base->current->loc);
5033               else
5034                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
5035                            "statement in which it is a parameter",
5036                            sym->name, &cs_base->current->loc);
5037               t = FAILURE;
5038             }
5039         }
5040
5041       /* Now do the same check on the specification expressions.  */
5042       specification_expr = 1;
5043       if (sym->ts.type == BT_CHARACTER
5044           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
5045         t = FAILURE;
5046
5047       if (sym->as)
5048         for (n = 0; n < sym->as->rank; n++)
5049           {
5050              specification_expr = 1;
5051              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
5052                t = FAILURE;
5053              specification_expr = 1;
5054              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
5055                t = FAILURE;
5056           }
5057       specification_expr = 0;
5058
5059       if (t == SUCCESS)
5060         /* Update the symbol's entry level.  */
5061         sym->entry_id = current_entry_id + 1;
5062     }
5063
5064   /* If a symbol has been host_associated mark it.  This is used latter,
5065      to identify if aliasing is possible via host association.  */
5066   if (sym->attr.flavor == FL_VARIABLE
5067         && gfc_current_ns->parent
5068         && (gfc_current_ns->parent == sym->ns
5069               || (gfc_current_ns->parent->parent
5070                     && gfc_current_ns->parent->parent == sym->ns)))
5071     sym->attr.host_assoc = 1;
5072
5073 resolve_procedure:
5074   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
5075     t = FAILURE;
5076
5077   /* F2008, C617 and C1229.  */
5078   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
5079       && gfc_is_coindexed (e))
5080     {
5081       gfc_ref *ref, *ref2 = NULL;
5082
5083       for (ref = e->ref; ref; ref = ref->next)
5084         {
5085           if (ref->type == REF_COMPONENT)
5086             ref2 = ref;
5087           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5088             break;
5089         }
5090
5091       for ( ; ref; ref = ref->next)
5092         if (ref->type == REF_COMPONENT)
5093           break;
5094
5095       /* Expression itself is not coindexed object.  */
5096       if (ref && e->ts.type == BT_CLASS)
5097         {
5098           gfc_error ("Polymorphic subobject of coindexed object at %L",
5099                      &e->where);
5100           t = FAILURE;
5101         }
5102
5103       /* Expression itself is coindexed object.  */
5104       if (ref == NULL)
5105         {
5106           gfc_component *c;
5107           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
5108           for ( ; c; c = c->next)
5109             if (c->attr.allocatable && c->ts.type == BT_CLASS)
5110               {
5111                 gfc_error ("Coindexed object with polymorphic allocatable "
5112                          "subcomponent at %L", &e->where);
5113                 t = FAILURE;
5114                 break;
5115               }
5116         }
5117     }
5118
5119   return t;
5120 }
5121
5122
5123 /* Checks to see that the correct symbol has been host associated.
5124    The only situation where this arises is that in which a twice
5125    contained function is parsed after the host association is made.
5126    Therefore, on detecting this, change the symbol in the expression
5127    and convert the array reference into an actual arglist if the old
5128    symbol is a variable.  */
5129 static bool
5130 check_host_association (gfc_expr *e)
5131 {
5132   gfc_symbol *sym, *old_sym;
5133   gfc_symtree *st;
5134   int n;
5135   gfc_ref *ref;
5136   gfc_actual_arglist *arg, *tail = NULL;
5137   bool retval = e->expr_type == EXPR_FUNCTION;
5138
5139   /*  If the expression is the result of substitution in
5140       interface.c(gfc_extend_expr) because there is no way in
5141       which the host association can be wrong.  */
5142   if (e->symtree == NULL
5143         || e->symtree->n.sym == NULL
5144         || e->user_operator)
5145     return retval;
5146
5147   old_sym = e->symtree->n.sym;
5148
5149   if (gfc_current_ns->parent
5150         && old_sym->ns != gfc_current_ns)
5151     {
5152       /* Use the 'USE' name so that renamed module symbols are
5153          correctly handled.  */
5154       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
5155
5156       if (sym && old_sym != sym
5157               && sym->ts.type == old_sym->ts.type
5158               && sym->attr.flavor == FL_PROCEDURE
5159               && sym->attr.contained)
5160         {
5161           /* Clear the shape, since it might not be valid.  */
5162           if (e->shape != NULL)
5163             {
5164               for (n = 0; n < e->rank; n++)
5165                 mpz_clear (e->shape[n]);
5166
5167               gfc_free (e->shape);
5168             }
5169
5170           /* Give the expression the right symtree!  */
5171           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
5172           gcc_assert (st != NULL);
5173
5174           if (old_sym->attr.flavor == FL_PROCEDURE
5175                 || e->expr_type == EXPR_FUNCTION)
5176             {
5177               /* Original was function so point to the new symbol, since
5178                  the actual argument list is already attached to the
5179                  expression. */
5180               e->value.function.esym = NULL;
5181               e->symtree = st;
5182             }
5183           else
5184             {
5185               /* Original was variable so convert array references into
5186                  an actual arglist. This does not need any checking now
5187                  since gfc_resolve_function will take care of it.  */
5188               e->value.function.actual = NULL;
5189               e->expr_type = EXPR_FUNCTION;
5190               e->symtree = st;
5191
5192               /* Ambiguity will not arise if the array reference is not
5193                  the last reference.  */
5194               for (ref = e->ref; ref; ref = ref->next)
5195                 if (ref->type == REF_ARRAY && ref->next == NULL)
5196                   break;
5197
5198               gcc_assert (ref->type == REF_ARRAY);
5199
5200               /* Grab the start expressions from the array ref and
5201                  copy them into actual arguments.  */
5202               for (n = 0; n < ref->u.ar.dimen; n++)
5203                 {
5204                   arg = gfc_get_actual_arglist ();
5205                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
5206                   if (e->value.function.actual == NULL)
5207                     tail = e->value.function.actual = arg;
5208                   else
5209                     {
5210                       tail->next = arg;
5211                       tail = arg;
5212                     }
5213                 }
5214
5215               /* Dump the reference list and set the rank.  */
5216               gfc_free_ref_list (e->ref);
5217               e->ref = NULL;
5218               e->rank = sym->as ? sym->as->rank : 0;
5219             }
5220
5221           gfc_resolve_expr (e);
5222           sym->refs++;
5223         }
5224     }
5225   /* This might have changed!  */
5226   return e->expr_type == EXPR_FUNCTION;
5227 }
5228
5229
5230 static void
5231 gfc_resolve_character_operator (gfc_expr *e)
5232 {
5233   gfc_expr *op1 = e->value.op.op1;
5234   gfc_expr *op2 = e->value.op.op2;
5235   gfc_expr *e1 = NULL;
5236   gfc_expr *e2 = NULL;
5237
5238   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
5239
5240   if (op1->ts.u.cl && op1->ts.u.cl->length)
5241     e1 = gfc_copy_expr (op1->ts.u.cl->length);
5242   else if (op1->expr_type == EXPR_CONSTANT)
5243     e1 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5244                            op1->value.character.length);
5245
5246   if (op2->ts.u.cl && op2->ts.u.cl->length)
5247     e2 = gfc_copy_expr (op2->ts.u.cl->length);
5248   else if (op2->expr_type == EXPR_CONSTANT)
5249     e2 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5250                            op2->value.character.length);
5251
5252   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5253
5254   if (!e1 || !e2)
5255     return;
5256
5257   e->ts.u.cl->length = gfc_add (e1, e2);
5258   e->ts.u.cl->length->ts.type = BT_INTEGER;
5259   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5260   gfc_simplify_expr (e->ts.u.cl->length, 0);
5261   gfc_resolve_expr (e->ts.u.cl->length);
5262
5263   return;
5264 }
5265
5266
5267 /*  Ensure that an character expression has a charlen and, if possible, a
5268     length expression.  */
5269
5270 static void
5271 fixup_charlen (gfc_expr *e)
5272 {
5273   /* The cases fall through so that changes in expression type and the need
5274      for multiple fixes are picked up.  In all circumstances, a charlen should
5275      be available for the middle end to hang a backend_decl on.  */
5276   switch (e->expr_type)
5277     {
5278     case EXPR_OP:
5279       gfc_resolve_character_operator (e);
5280
5281     case EXPR_ARRAY:
5282       if (e->expr_type == EXPR_ARRAY)
5283         gfc_resolve_character_array_constructor (e);
5284
5285     case EXPR_SUBSTRING:
5286       if (!e->ts.u.cl && e->ref)
5287         gfc_resolve_substring_charlen (e);
5288
5289     default:
5290       if (!e->ts.u.cl)
5291         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5292
5293       break;
5294     }
5295 }
5296
5297
5298 /* Update an actual argument to include the passed-object for type-bound
5299    procedures at the right position.  */
5300
5301 static gfc_actual_arglist*
5302 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
5303                      const char *name)
5304 {
5305   gcc_assert (argpos > 0);
5306
5307   if (argpos == 1)
5308     {
5309       gfc_actual_arglist* result;
5310
5311       result = gfc_get_actual_arglist ();
5312       result->expr = po;
5313       result->next = lst;
5314       if (name)
5315         result->name = name;
5316
5317       return result;
5318     }
5319
5320   if (lst)
5321     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
5322   else
5323     lst = update_arglist_pass (NULL, po, argpos - 1, name);
5324   return lst;
5325 }
5326
5327
5328 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
5329
5330 static gfc_expr*
5331 extract_compcall_passed_object (gfc_expr* e)
5332 {
5333   gfc_expr* po;
5334
5335   gcc_assert (e->expr_type == EXPR_COMPCALL);
5336
5337   if (e->value.compcall.base_object)
5338     po = gfc_copy_expr (e->value.compcall.base_object);
5339   else
5340     {
5341       po = gfc_get_expr ();
5342       po->expr_type = EXPR_VARIABLE;
5343       po->symtree = e->symtree;
5344       po->ref = gfc_copy_ref (e->ref);
5345       po->where = e->where;
5346     }
5347
5348   if (gfc_resolve_expr (po) == FAILURE)
5349     return NULL;
5350
5351   return po;
5352 }
5353
5354
5355 /* Update the arglist of an EXPR_COMPCALL expression to include the
5356    passed-object.  */
5357
5358 static gfc_try
5359 update_compcall_arglist (gfc_expr* e)
5360 {
5361   gfc_expr* po;
5362   gfc_typebound_proc* tbp;
5363
5364   tbp = e->value.compcall.tbp;
5365
5366   if (tbp->error)
5367     return FAILURE;
5368
5369   po = extract_compcall_passed_object (e);
5370   if (!po)
5371     return FAILURE;
5372
5373   if (tbp->nopass || e->value.compcall.ignore_pass)
5374     {
5375       gfc_free_expr (po);
5376       return SUCCESS;
5377     }
5378
5379   gcc_assert (tbp->pass_arg_num > 0);
5380   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5381                                                   tbp->pass_arg_num,
5382                                                   tbp->pass_arg);
5383
5384   return SUCCESS;
5385 }
5386
5387
5388 /* Extract the passed object from a PPC call (a copy of it).  */
5389
5390 static gfc_expr*
5391 extract_ppc_passed_object (gfc_expr *e)
5392 {
5393   gfc_expr *po;
5394   gfc_ref **ref;
5395
5396   po = gfc_get_expr ();
5397   po->expr_type = EXPR_VARIABLE;
5398   po->symtree = e->symtree;
5399   po->ref = gfc_copy_ref (e->ref);
5400   po->where = e->where;
5401
5402   /* Remove PPC reference.  */
5403   ref = &po->ref;
5404   while ((*ref)->next)
5405     ref = &(*ref)->next;
5406   gfc_free_ref_list (*ref);
5407   *ref = NULL;
5408
5409   if (gfc_resolve_expr (po) == FAILURE)
5410     return NULL;
5411
5412   return po;
5413 }
5414
5415
5416 /* Update the actual arglist of a procedure pointer component to include the
5417    passed-object.  */
5418
5419 static gfc_try
5420 update_ppc_arglist (gfc_expr* e)
5421 {
5422   gfc_expr* po;
5423   gfc_component *ppc;
5424   gfc_typebound_proc* tb;
5425
5426   if (!gfc_is_proc_ptr_comp (e, &ppc))
5427     return FAILURE;
5428
5429   tb = ppc->tb;
5430
5431   if (tb->error)
5432     return FAILURE;
5433   else if (tb->nopass)
5434     return SUCCESS;
5435
5436   po = extract_ppc_passed_object (e);
5437   if (!po)
5438     return FAILURE;
5439
5440   /* F08:R739.  */
5441   if (po->rank > 0)
5442     {
5443       gfc_error ("Passed-object at %L must be scalar", &e->where);
5444       return FAILURE;
5445     }
5446
5447   /* F08:C611.  */
5448   if (po->ts.type == BT_DERIVED && po->ts.u.derived->attr.abstract)
5449     {
5450       gfc_error ("Base object for procedure-pointer component call at %L is of"
5451                  " ABSTRACT type '%s'", &e->where, po->ts.u.derived->name);
5452       return FAILURE;
5453     }
5454
5455   gcc_assert (tb->pass_arg_num > 0);
5456   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5457                                                   tb->pass_arg_num,
5458                                                   tb->pass_arg);
5459
5460   return SUCCESS;
5461 }
5462
5463
5464 /* Check that the object a TBP is called on is valid, i.e. it must not be
5465    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5466
5467 static gfc_try
5468 check_typebound_baseobject (gfc_expr* e)
5469 {
5470   gfc_expr* base;
5471   gfc_try return_value = FAILURE;
5472
5473   base = extract_compcall_passed_object (e);
5474   if (!base)
5475     return FAILURE;
5476
5477   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5478
5479   /* F08:C611.  */
5480   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5481     {
5482       gfc_error ("Base object for type-bound procedure call at %L is of"
5483                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5484       goto cleanup;
5485     }
5486
5487   /* F08:C1230. If the procedure called is NOPASS,
5488      the base object must be scalar.  */
5489   if (e->value.compcall.tbp->nopass && base->rank > 0)
5490     {
5491       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5492                  " be scalar", &e->where);
5493       goto cleanup;
5494     }
5495
5496   /* FIXME: Remove once PR 43214 is fixed (TBP with non-scalar PASS).  */
5497   if (base->rank > 0)
5498     {
5499       gfc_error ("Non-scalar base object at %L currently not implemented",
5500                  &e->where);
5501       goto cleanup;
5502     }
5503
5504   return_value = SUCCESS;
5505
5506 cleanup:
5507   gfc_free_expr (base);
5508   return return_value;
5509 }
5510
5511
5512 /* Resolve a call to a type-bound procedure, either function or subroutine,
5513    statically from the data in an EXPR_COMPCALL expression.  The adapted
5514    arglist and the target-procedure symtree are returned.  */
5515
5516 static gfc_try
5517 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5518                           gfc_actual_arglist** actual)
5519 {
5520   gcc_assert (e->expr_type == EXPR_COMPCALL);
5521   gcc_assert (!e->value.compcall.tbp->is_generic);
5522
5523   /* Update the actual arglist for PASS.  */
5524   if (update_compcall_arglist (e) == FAILURE)
5525     return FAILURE;
5526
5527   *actual = e->value.compcall.actual;
5528   *target = e->value.compcall.tbp->u.specific;
5529
5530   gfc_free_ref_list (e->ref);
5531   e->ref = NULL;
5532   e->value.compcall.actual = NULL;
5533
5534   return SUCCESS;
5535 }
5536
5537
5538 /* Get the ultimate declared type from an expression.  In addition,
5539    return the last class/derived type reference and the copy of the
5540    reference list.  */
5541 static gfc_symbol*
5542 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5543                         gfc_expr *e)
5544 {
5545   gfc_symbol *declared;
5546   gfc_ref *ref;
5547
5548   declared = NULL;
5549   if (class_ref)
5550     *class_ref = NULL;
5551   if (new_ref)
5552     *new_ref = gfc_copy_ref (e->ref);
5553
5554   for (ref = e->ref; ref; ref = ref->next)
5555     {
5556       if (ref->type != REF_COMPONENT)
5557         continue;
5558
5559       if (ref->u.c.component->ts.type == BT_CLASS
5560             || ref->u.c.component->ts.type == BT_DERIVED)
5561         {
5562           declared = ref->u.c.component->ts.u.derived;
5563           if (class_ref)
5564             *class_ref = ref;
5565         }
5566     }
5567
5568   if (declared == NULL)
5569     declared = e->symtree->n.sym->ts.u.derived;
5570
5571   return declared;
5572 }
5573
5574
5575 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5576    which of the specific bindings (if any) matches the arglist and transform
5577    the expression into a call of that binding.  */
5578
5579 static gfc_try
5580 resolve_typebound_generic_call (gfc_expr* e, const char **name)
5581 {
5582   gfc_typebound_proc* genproc;
5583   const char* genname;
5584   gfc_symtree *st;
5585   gfc_symbol *derived;
5586
5587   gcc_assert (e->expr_type == EXPR_COMPCALL);
5588   genname = e->value.compcall.name;
5589   genproc = e->value.compcall.tbp;
5590
5591   if (!genproc->is_generic)
5592     return SUCCESS;
5593
5594   /* Try the bindings on this type and in the inheritance hierarchy.  */
5595   for (; genproc; genproc = genproc->overridden)
5596     {
5597       gfc_tbp_generic* g;
5598
5599       gcc_assert (genproc->is_generic);
5600       for (g = genproc->u.generic; g; g = g->next)
5601         {
5602           gfc_symbol* target;
5603           gfc_actual_arglist* args;
5604           bool matches;
5605
5606           gcc_assert (g->specific);
5607
5608           if (g->specific->error)
5609             continue;
5610
5611           target = g->specific->u.specific->n.sym;
5612
5613           /* Get the right arglist by handling PASS/NOPASS.  */
5614           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5615           if (!g->specific->nopass)
5616             {
5617               gfc_expr* po;
5618               po = extract_compcall_passed_object (e);
5619               if (!po)
5620                 return FAILURE;
5621
5622               gcc_assert (g->specific->pass_arg_num > 0);
5623               gcc_assert (!g->specific->error);
5624               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5625                                           g->specific->pass_arg);
5626             }
5627           resolve_actual_arglist (args, target->attr.proc,
5628                                   is_external_proc (target) && !target->formal);
5629
5630           /* Check if this arglist matches the formal.  */
5631           matches = gfc_arglist_matches_symbol (&args, target);
5632
5633           /* Clean up and break out of the loop if we've found it.  */
5634           gfc_free_actual_arglist (args);
5635           if (matches)
5636             {
5637               e->value.compcall.tbp = g->specific;
5638               genname = g->specific_st->name;
5639               /* Pass along the name for CLASS methods, where the vtab
5640                  procedure pointer component has to be referenced.  */
5641               if (name)
5642                 *name = genname;
5643               goto success;
5644             }
5645         }
5646     }
5647
5648   /* Nothing matching found!  */
5649   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5650              " '%s' at %L", genname, &e->where);
5651   return FAILURE;
5652
5653 success:
5654   /* Make sure that we have the right specific instance for the name.  */
5655   derived = get_declared_from_expr (NULL, NULL, e);
5656
5657   st = gfc_find_typebound_proc (derived, NULL, genname, false, &e->where);
5658   if (st)
5659     e->value.compcall.tbp = st->n.tb;
5660
5661   return SUCCESS;
5662 }
5663
5664
5665 /* Resolve a call to a type-bound subroutine.  */
5666
5667 static gfc_try
5668 resolve_typebound_call (gfc_code* c, const char **name)
5669 {
5670   gfc_actual_arglist* newactual;
5671   gfc_symtree* target;
5672
5673   /* Check that's really a SUBROUTINE.  */
5674   if (!c->expr1->value.compcall.tbp->subroutine)
5675     {
5676       gfc_error ("'%s' at %L should be a SUBROUTINE",
5677                  c->expr1->value.compcall.name, &c->loc);
5678       return FAILURE;
5679     }
5680
5681   if (check_typebound_baseobject (c->expr1) == FAILURE)
5682     return FAILURE;
5683
5684   /* Pass along the name for CLASS methods, where the vtab
5685      procedure pointer component has to be referenced.  */
5686   if (name)
5687     *name = c->expr1->value.compcall.name;
5688
5689   if (resolve_typebound_generic_call (c->expr1, name) == FAILURE)
5690     return FAILURE;
5691
5692   /* Transform into an ordinary EXEC_CALL for now.  */
5693
5694   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5695     return FAILURE;
5696
5697   c->ext.actual = newactual;
5698   c->symtree = target;
5699   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5700
5701   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5702
5703   gfc_free_expr (c->expr1);
5704   c->expr1 = gfc_get_expr ();
5705   c->expr1->expr_type = EXPR_FUNCTION;
5706   c->expr1->symtree = target;
5707   c->expr1->where = c->loc;
5708
5709   return resolve_call (c);
5710 }
5711
5712
5713 /* Resolve a component-call expression.  */
5714 static gfc_try
5715 resolve_compcall (gfc_expr* e, const char **name)
5716 {
5717   gfc_actual_arglist* newactual;
5718   gfc_symtree* target;
5719
5720   /* Check that's really a FUNCTION.  */
5721   if (!e->value.compcall.tbp->function)
5722     {
5723       gfc_error ("'%s' at %L should be a FUNCTION",
5724                  e->value.compcall.name, &e->where);
5725       return FAILURE;
5726     }
5727
5728   /* These must not be assign-calls!  */
5729   gcc_assert (!e->value.compcall.assign);
5730
5731   if (check_typebound_baseobject (e) == FAILURE)
5732     return FAILURE;
5733
5734   /* Pass along the name for CLASS methods, where the vtab
5735      procedure pointer component has to be referenced.  */
5736   if (name)
5737     *name = e->value.compcall.name;
5738
5739   if (resolve_typebound_generic_call (e, name) == FAILURE)
5740     return FAILURE;
5741   gcc_assert (!e->value.compcall.tbp->is_generic);
5742
5743   /* Take the rank from the function's symbol.  */
5744   if (e->value.compcall.tbp->u.specific->n.sym->as)
5745     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5746
5747   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5748      arglist to the TBP's binding target.  */
5749
5750   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5751     return FAILURE;
5752
5753   e->value.function.actual = newactual;
5754   e->value.function.name = NULL;
5755   e->value.function.esym = target->n.sym;
5756   e->value.function.isym = NULL;
5757   e->symtree = target;
5758   e->ts = target->n.sym->ts;
5759   e->expr_type = EXPR_FUNCTION;
5760
5761   /* Resolution is not necessary if this is a class subroutine; this
5762      function only has to identify the specific proc. Resolution of
5763      the call will be done next in resolve_typebound_call.  */
5764   return gfc_resolve_expr (e);
5765 }
5766
5767
5768
5769 /* Resolve a typebound function, or 'method'. First separate all
5770    the non-CLASS references by calling resolve_compcall directly.  */
5771
5772 static gfc_try
5773 resolve_typebound_function (gfc_expr* e)
5774 {
5775   gfc_symbol *declared;
5776   gfc_component *c;
5777   gfc_ref *new_ref;
5778   gfc_ref *class_ref;
5779   gfc_symtree *st;
5780   const char *name;
5781   gfc_typespec ts;
5782   gfc_expr *expr;
5783
5784   st = e->symtree;
5785
5786   /* Deal with typebound operators for CLASS objects.  */
5787   expr = e->value.compcall.base_object;
5788   if (expr && expr->ts.type == BT_CLASS && e->value.compcall.name)
5789     {
5790       /* Since the typebound operators are generic, we have to ensure
5791          that any delays in resolution are corrected and that the vtab
5792          is present.  */
5793       ts = expr->ts;
5794       declared = ts.u.derived;
5795       c = gfc_find_component (declared, "_vptr", true, true);
5796       if (c->ts.u.derived == NULL)
5797         c->ts.u.derived = gfc_find_derived_vtab (declared);
5798
5799       if (resolve_compcall (e, &name) == FAILURE)
5800         return FAILURE;
5801
5802       /* Use the generic name if it is there.  */
5803       name = name ? name : e->value.function.esym->name;
5804       e->symtree = expr->symtree;
5805       e->ref = gfc_copy_ref (expr->ref);
5806       gfc_add_vptr_component (e);
5807       gfc_add_component_ref (e, name);
5808       e->value.function.esym = NULL;
5809       return SUCCESS;
5810     }
5811
5812   if (st == NULL)
5813     return resolve_compcall (e, NULL);
5814
5815   if (resolve_ref (e) == FAILURE)
5816     return FAILURE;
5817
5818   /* Get the CLASS declared type.  */
5819   declared = get_declared_from_expr (&class_ref, &new_ref, e);
5820
5821   /* Weed out cases of the ultimate component being a derived type.  */
5822   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5823          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5824     {
5825       gfc_free_ref_list (new_ref);
5826       return resolve_compcall (e, NULL);
5827     }
5828
5829   c = gfc_find_component (declared, "_data", true, true);
5830   declared = c->ts.u.derived;
5831
5832   /* Treat the call as if it is a typebound procedure, in order to roll
5833      out the correct name for the specific function.  */
5834   if (resolve_compcall (e, &name) == FAILURE)
5835     return FAILURE;
5836   ts = e->ts;
5837
5838   /* Then convert the expression to a procedure pointer component call.  */
5839   e->value.function.esym = NULL;
5840   e->symtree = st;
5841
5842   if (new_ref)  
5843     e->ref = new_ref;
5844
5845   /* '_vptr' points to the vtab, which contains the procedure pointers.  */
5846   gfc_add_vptr_component (e);
5847   gfc_add_component_ref (e, name);
5848
5849   /* Recover the typespec for the expression.  This is really only
5850      necessary for generic procedures, where the additional call
5851      to gfc_add_component_ref seems to throw the collection of the
5852      correct typespec.  */
5853   e->ts = ts;
5854   return SUCCESS;
5855 }
5856
5857 /* Resolve a typebound subroutine, or 'method'. First separate all
5858    the non-CLASS references by calling resolve_typebound_call
5859    directly.  */
5860
5861 static gfc_try
5862 resolve_typebound_subroutine (gfc_code *code)
5863 {
5864   gfc_symbol *declared;
5865   gfc_component *c;
5866   gfc_ref *new_ref;
5867   gfc_ref *class_ref;
5868   gfc_symtree *st;
5869   const char *name;
5870   gfc_typespec ts;
5871   gfc_expr *expr;
5872
5873   st = code->expr1->symtree;
5874
5875   /* Deal with typebound operators for CLASS objects.  */
5876   expr = code->expr1->value.compcall.base_object;
5877   if (expr && expr->symtree->n.sym->ts.type == BT_CLASS
5878         && code->expr1->value.compcall.name)
5879     {
5880       /* Since the typebound operators are generic, we have to ensure
5881          that any delays in resolution are corrected and that the vtab
5882          is present.  */
5883       ts = expr->symtree->n.sym->ts;
5884       declared = ts.u.derived;
5885       c = gfc_find_component (declared, "_vptr", true, true);
5886       if (c->ts.u.derived == NULL)
5887         c->ts.u.derived = gfc_find_derived_vtab (declared);
5888
5889       if (resolve_typebound_call (code, &name) == FAILURE)
5890         return FAILURE;
5891
5892       /* Use the generic name if it is there.  */
5893       name = name ? name : code->expr1->value.function.esym->name;
5894       code->expr1->symtree = expr->symtree;
5895       expr->symtree->n.sym->ts.u.derived = declared;
5896       gfc_add_vptr_component (code->expr1);
5897       gfc_add_component_ref (code->expr1, name);
5898       code->expr1->value.function.esym = NULL;
5899       return SUCCESS;
5900     }
5901
5902   if (st == NULL)
5903     return resolve_typebound_call (code, NULL);
5904
5905   if (resolve_ref (code->expr1) == FAILURE)
5906     return FAILURE;
5907
5908   /* Get the CLASS declared type.  */
5909   get_declared_from_expr (&class_ref, &new_ref, code->expr1);
5910
5911   /* Weed out cases of the ultimate component being a derived type.  */
5912   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5913          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5914     {
5915       gfc_free_ref_list (new_ref);
5916       return resolve_typebound_call (code, NULL);
5917     }
5918
5919   if (resolve_typebound_call (code, &name) == FAILURE)
5920     return FAILURE;
5921   ts = code->expr1->ts;
5922
5923   /* Then convert the expression to a procedure pointer component call.  */
5924   code->expr1->value.function.esym = NULL;
5925   code->expr1->symtree = st;
5926
5927   if (new_ref)
5928     code->expr1->ref = new_ref;
5929
5930   /* '_vptr' points to the vtab, which contains the procedure pointers.  */
5931   gfc_add_vptr_component (code->expr1);
5932   gfc_add_component_ref (code->expr1, name);
5933
5934   /* Recover the typespec for the expression.  This is really only
5935      necessary for generic procedures, where the additional call
5936      to gfc_add_component_ref seems to throw the collection of the
5937      correct typespec.  */
5938   code->expr1->ts = ts;
5939   return SUCCESS;
5940 }
5941
5942
5943 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
5944
5945 static gfc_try
5946 resolve_ppc_call (gfc_code* c)
5947 {
5948   gfc_component *comp;
5949   bool b;
5950
5951   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
5952   gcc_assert (b);
5953
5954   c->resolved_sym = c->expr1->symtree->n.sym;
5955   c->expr1->expr_type = EXPR_VARIABLE;
5956
5957   if (!comp->attr.subroutine)
5958     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
5959
5960   if (resolve_ref (c->expr1) == FAILURE)
5961     return FAILURE;
5962
5963   if (update_ppc_arglist (c->expr1) == FAILURE)
5964     return FAILURE;
5965
5966   c->ext.actual = c->expr1->value.compcall.actual;
5967
5968   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
5969                               comp->formal == NULL) == FAILURE)
5970     return FAILURE;
5971
5972   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
5973
5974   return SUCCESS;
5975 }
5976
5977
5978 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
5979
5980 static gfc_try
5981 resolve_expr_ppc (gfc_expr* e)
5982 {
5983   gfc_component *comp;
5984   bool b;
5985
5986   b = gfc_is_proc_ptr_comp (e, &comp);
5987   gcc_assert (b);
5988
5989   /* Convert to EXPR_FUNCTION.  */
5990   e->expr_type = EXPR_FUNCTION;
5991   e->value.function.isym = NULL;
5992   e->value.function.actual = e->value.compcall.actual;
5993   e->ts = comp->ts;
5994   if (comp->as != NULL)
5995     e->rank = comp->as->rank;
5996
5997   if (!comp->attr.function)
5998     gfc_add_function (&comp->attr, comp->name, &e->where);
5999
6000   if (resolve_ref (e) == FAILURE)
6001     return FAILURE;
6002
6003   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
6004                               comp->formal == NULL) == FAILURE)
6005     return FAILURE;
6006
6007   if (update_ppc_arglist (e) == FAILURE)
6008     return FAILURE;
6009
6010   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
6011
6012   return SUCCESS;
6013 }
6014
6015
6016 static bool
6017 gfc_is_expandable_expr (gfc_expr *e)
6018 {
6019   gfc_constructor *con;
6020
6021   if (e->expr_type == EXPR_ARRAY)
6022     {
6023       /* Traverse the constructor looking for variables that are flavor
6024          parameter.  Parameters must be expanded since they are fully used at
6025          compile time.  */
6026       con = gfc_constructor_first (e->value.constructor);
6027       for (; con; con = gfc_constructor_next (con))
6028         {
6029           if (con->expr->expr_type == EXPR_VARIABLE
6030               && con->expr->symtree
6031               && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
6032               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
6033             return true;
6034           if (con->expr->expr_type == EXPR_ARRAY
6035               && gfc_is_expandable_expr (con->expr))
6036             return true;
6037         }
6038     }
6039
6040   return false;
6041 }
6042
6043 /* Resolve an expression.  That is, make sure that types of operands agree
6044    with their operators, intrinsic operators are converted to function calls
6045    for overloaded types and unresolved function references are resolved.  */
6046
6047 gfc_try
6048 gfc_resolve_expr (gfc_expr *e)
6049 {
6050   gfc_try t;
6051   bool inquiry_save;
6052
6053   if (e == NULL)
6054     return SUCCESS;
6055
6056   /* inquiry_argument only applies to variables.  */
6057   inquiry_save = inquiry_argument;
6058   if (e->expr_type != EXPR_VARIABLE)
6059     inquiry_argument = false;
6060
6061   switch (e->expr_type)
6062     {
6063     case EXPR_OP:
6064       t = resolve_operator (e);
6065       break;
6066
6067     case EXPR_FUNCTION:
6068     case EXPR_VARIABLE:
6069
6070       if (check_host_association (e))
6071         t = resolve_function (e);
6072       else
6073         {
6074           t = resolve_variable (e);
6075           if (t == SUCCESS)
6076             expression_rank (e);
6077         }
6078
6079       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
6080           && e->ref->type != REF_SUBSTRING)
6081         gfc_resolve_substring_charlen (e);
6082
6083       break;
6084
6085     case EXPR_COMPCALL:
6086       t = resolve_typebound_function (e);
6087       break;
6088
6089     case EXPR_SUBSTRING:
6090       t = resolve_ref (e);
6091       break;
6092
6093     case EXPR_CONSTANT:
6094     case EXPR_NULL:
6095       t = SUCCESS;
6096       break;
6097
6098     case EXPR_PPC:
6099       t = resolve_expr_ppc (e);
6100       break;
6101
6102     case EXPR_ARRAY:
6103       t = FAILURE;
6104       if (resolve_ref (e) == FAILURE)
6105         break;
6106
6107       t = gfc_resolve_array_constructor (e);
6108       /* Also try to expand a constructor.  */
6109       if (t == SUCCESS)
6110         {
6111           expression_rank (e);
6112           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
6113             gfc_expand_constructor (e, false);
6114         }
6115
6116       /* This provides the opportunity for the length of constructors with
6117          character valued function elements to propagate the string length
6118          to the expression.  */
6119       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
6120         {
6121           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
6122              here rather then add a duplicate test for it above.  */ 
6123           gfc_expand_constructor (e, false);
6124           t = gfc_resolve_character_array_constructor (e);
6125         }
6126
6127       break;
6128
6129     case EXPR_STRUCTURE:
6130       t = resolve_ref (e);
6131       if (t == FAILURE)
6132         break;
6133
6134       t = resolve_structure_cons (e, 0);
6135       if (t == FAILURE)
6136         break;
6137
6138       t = gfc_simplify_expr (e, 0);
6139       break;
6140
6141     default:
6142       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
6143     }
6144
6145   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
6146     fixup_charlen (e);
6147
6148   inquiry_argument = inquiry_save;
6149
6150   return t;
6151 }
6152
6153
6154 /* Resolve an expression from an iterator.  They must be scalar and have
6155    INTEGER or (optionally) REAL type.  */
6156
6157 static gfc_try
6158 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
6159                            const char *name_msgid)
6160 {
6161   if (gfc_resolve_expr (expr) == FAILURE)
6162     return FAILURE;
6163
6164   if (expr->rank != 0)
6165     {
6166       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
6167       return FAILURE;
6168     }
6169
6170   if (expr->ts.type != BT_INTEGER)
6171     {
6172       if (expr->ts.type == BT_REAL)
6173         {
6174           if (real_ok)
6175             return gfc_notify_std (GFC_STD_F95_DEL,
6176                                    "Deleted feature: %s at %L must be integer",
6177                                    _(name_msgid), &expr->where);
6178           else
6179             {
6180               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
6181                          &expr->where);
6182               return FAILURE;
6183             }
6184         }
6185       else
6186         {
6187           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
6188           return FAILURE;
6189         }
6190     }
6191   return SUCCESS;
6192 }
6193
6194
6195 /* Resolve the expressions in an iterator structure.  If REAL_OK is
6196    false allow only INTEGER type iterators, otherwise allow REAL types.  */
6197
6198 gfc_try
6199 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
6200 {
6201   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
6202       == FAILURE)
6203     return FAILURE;
6204
6205   if (gfc_check_vardef_context (iter->var, false, _("iterator variable"))
6206       == FAILURE)
6207     return FAILURE;
6208
6209   if (gfc_resolve_iterator_expr (iter->start, real_ok,
6210                                  "Start expression in DO loop") == FAILURE)
6211     return FAILURE;
6212
6213   if (gfc_resolve_iterator_expr (iter->end, real_ok,
6214                                  "End expression in DO loop") == FAILURE)
6215     return FAILURE;
6216
6217   if (gfc_resolve_iterator_expr (iter->step, real_ok,
6218                                  "Step expression in DO loop") == FAILURE)
6219     return FAILURE;
6220
6221   if (iter->step->expr_type == EXPR_CONSTANT)
6222     {
6223       if ((iter->step->ts.type == BT_INTEGER
6224            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
6225           || (iter->step->ts.type == BT_REAL
6226               && mpfr_sgn (iter->step->value.real) == 0))
6227         {
6228           gfc_error ("Step expression in DO loop at %L cannot be zero",
6229                      &iter->step->where);
6230           return FAILURE;
6231         }
6232     }
6233
6234   /* Convert start, end, and step to the same type as var.  */
6235   if (iter->start->ts.kind != iter->var->ts.kind
6236       || iter->start->ts.type != iter->var->ts.type)
6237     gfc_convert_type (iter->start, &iter->var->ts, 2);
6238
6239   if (iter->end->ts.kind != iter->var->ts.kind
6240       || iter->end->ts.type != iter->var->ts.type)
6241     gfc_convert_type (iter->end, &iter->var->ts, 2);
6242
6243   if (iter->step->ts.kind != iter->var->ts.kind
6244       || iter->step->ts.type != iter->var->ts.type)
6245     gfc_convert_type (iter->step, &iter->var->ts, 2);
6246
6247   if (iter->start->expr_type == EXPR_CONSTANT
6248       && iter->end->expr_type == EXPR_CONSTANT
6249       && iter->step->expr_type == EXPR_CONSTANT)
6250     {
6251       int sgn, cmp;
6252       if (iter->start->ts.type == BT_INTEGER)
6253         {
6254           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
6255           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
6256         }
6257       else
6258         {
6259           sgn = mpfr_sgn (iter->step->value.real);
6260           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
6261         }
6262       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
6263         gfc_warning ("DO loop at %L will be executed zero times",
6264                      &iter->step->where);
6265     }
6266
6267   return SUCCESS;
6268 }
6269
6270
6271 /* Traversal function for find_forall_index.  f == 2 signals that
6272    that variable itself is not to be checked - only the references.  */
6273
6274 static bool
6275 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
6276 {
6277   if (expr->expr_type != EXPR_VARIABLE)
6278     return false;
6279   
6280   /* A scalar assignment  */
6281   if (!expr->ref || *f == 1)
6282     {
6283       if (expr->symtree->n.sym == sym)
6284         return true;
6285       else
6286         return false;
6287     }
6288
6289   if (*f == 2)
6290     *f = 1;
6291   return false;
6292 }
6293
6294
6295 /* Check whether the FORALL index appears in the expression or not.
6296    Returns SUCCESS if SYM is found in EXPR.  */
6297
6298 gfc_try
6299 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
6300 {
6301   if (gfc_traverse_expr (expr, sym, forall_index, f))
6302     return SUCCESS;
6303   else
6304     return FAILURE;
6305 }
6306
6307
6308 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
6309    to be a scalar INTEGER variable.  The subscripts and stride are scalar
6310    INTEGERs, and if stride is a constant it must be nonzero.
6311    Furthermore "A subscript or stride in a forall-triplet-spec shall
6312    not contain a reference to any index-name in the
6313    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
6314
6315 static void
6316 resolve_forall_iterators (gfc_forall_iterator *it)
6317 {
6318   gfc_forall_iterator *iter, *iter2;
6319
6320   for (iter = it; iter; iter = iter->next)
6321     {
6322       if (gfc_resolve_expr (iter->var) == SUCCESS
6323           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
6324         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
6325                    &iter->var->where);
6326
6327       if (gfc_resolve_expr (iter->start) == SUCCESS
6328           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
6329         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
6330                    &iter->start->where);
6331       if (iter->var->ts.kind != iter->start->ts.kind)
6332         gfc_convert_type (iter->start, &iter->var->ts, 2);
6333
6334       if (gfc_resolve_expr (iter->end) == SUCCESS
6335           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
6336         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
6337                    &iter->end->where);
6338       if (iter->var->ts.kind != iter->end->ts.kind)
6339         gfc_convert_type (iter->end, &iter->var->ts, 2);
6340
6341       if (gfc_resolve_expr (iter->stride) == SUCCESS)
6342         {
6343           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
6344             gfc_error ("FORALL stride expression at %L must be a scalar %s",
6345                        &iter->stride->where, "INTEGER");
6346
6347           if (iter->stride->expr_type == EXPR_CONSTANT
6348               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
6349             gfc_error ("FORALL stride expression at %L cannot be zero",
6350                        &iter->stride->where);
6351         }
6352       if (iter->var->ts.kind != iter->stride->ts.kind)
6353         gfc_convert_type (iter->stride, &iter->var->ts, 2);
6354     }
6355
6356   for (iter = it; iter; iter = iter->next)
6357     for (iter2 = iter; iter2; iter2 = iter2->next)
6358       {
6359         if (find_forall_index (iter2->start,
6360                                iter->var->symtree->n.sym, 0) == SUCCESS
6361             || find_forall_index (iter2->end,
6362                                   iter->var->symtree->n.sym, 0) == SUCCESS
6363             || find_forall_index (iter2->stride,
6364                                   iter->var->symtree->n.sym, 0) == SUCCESS)
6365           gfc_error ("FORALL index '%s' may not appear in triplet "
6366                      "specification at %L", iter->var->symtree->name,
6367                      &iter2->start->where);
6368       }
6369 }
6370
6371
6372 /* Given a pointer to a symbol that is a derived type, see if it's
6373    inaccessible, i.e. if it's defined in another module and the components are
6374    PRIVATE.  The search is recursive if necessary.  Returns zero if no
6375    inaccessible components are found, nonzero otherwise.  */
6376
6377 static int
6378 derived_inaccessible (gfc_symbol *sym)
6379 {
6380   gfc_component *c;
6381
6382   if (sym->attr.use_assoc && sym->attr.private_comp)
6383     return 1;
6384
6385   for (c = sym->components; c; c = c->next)
6386     {
6387         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
6388           return 1;
6389     }
6390
6391   return 0;
6392 }
6393
6394
6395 /* Resolve the argument of a deallocate expression.  The expression must be
6396    a pointer or a full array.  */
6397
6398 static gfc_try
6399 resolve_deallocate_expr (gfc_expr *e)
6400 {
6401   symbol_attribute attr;
6402   int allocatable, pointer;
6403   gfc_ref *ref;
6404   gfc_symbol *sym;
6405   gfc_component *c;
6406
6407   if (gfc_resolve_expr (e) == FAILURE)
6408     return FAILURE;
6409
6410   if (e->expr_type != EXPR_VARIABLE)
6411     goto bad;
6412
6413   sym = e->symtree->n.sym;
6414
6415   if (sym->ts.type == BT_CLASS)
6416     {
6417       allocatable = CLASS_DATA (sym)->attr.allocatable;
6418       pointer = CLASS_DATA (sym)->attr.class_pointer;
6419     }
6420   else
6421     {
6422       allocatable = sym->attr.allocatable;
6423       pointer = sym->attr.pointer;
6424     }
6425   for (ref = e->ref; ref; ref = ref->next)
6426     {
6427       switch (ref->type)
6428         {
6429         case REF_ARRAY:
6430           if (ref->u.ar.type != AR_FULL)
6431             allocatable = 0;
6432           break;
6433
6434         case REF_COMPONENT:
6435           c = ref->u.c.component;
6436           if (c->ts.type == BT_CLASS)
6437             {
6438               allocatable = CLASS_DATA (c)->attr.allocatable;
6439               pointer = CLASS_DATA (c)->attr.class_pointer;
6440             }
6441           else
6442             {
6443               allocatable = c->attr.allocatable;
6444               pointer = c->attr.pointer;
6445             }
6446           break;
6447
6448         case REF_SUBSTRING:
6449           allocatable = 0;
6450           break;
6451         }
6452     }
6453
6454   attr = gfc_expr_attr (e);
6455
6456   if (allocatable == 0 && attr.pointer == 0)
6457     {
6458     bad:
6459       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6460                  &e->where);
6461       return FAILURE;
6462     }
6463
6464   if (pointer
6465       && gfc_check_vardef_context (e, true, _("DEALLOCATE object")) == FAILURE)
6466     return FAILURE;
6467   if (gfc_check_vardef_context (e, false, _("DEALLOCATE object")) == FAILURE)
6468     return FAILURE;
6469
6470   return SUCCESS;
6471 }
6472
6473
6474 /* Returns true if the expression e contains a reference to the symbol sym.  */
6475 static bool
6476 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6477 {
6478   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6479     return true;
6480
6481   return false;
6482 }
6483
6484 bool
6485 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6486 {
6487   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6488 }
6489
6490
6491 /* Given the expression node e for an allocatable/pointer of derived type to be
6492    allocated, get the expression node to be initialized afterwards (needed for
6493    derived types with default initializers, and derived types with allocatable
6494    components that need nullification.)  */
6495
6496 gfc_expr *
6497 gfc_expr_to_initialize (gfc_expr *e)
6498 {
6499   gfc_expr *result;
6500   gfc_ref *ref;
6501   int i;
6502
6503   result = gfc_copy_expr (e);
6504
6505   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6506   for (ref = result->ref; ref; ref = ref->next)
6507     if (ref->type == REF_ARRAY && ref->next == NULL)
6508       {
6509         ref->u.ar.type = AR_FULL;
6510
6511         for (i = 0; i < ref->u.ar.dimen; i++)
6512           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6513
6514         result->rank = ref->u.ar.dimen;
6515         break;
6516       }
6517
6518   return result;
6519 }
6520
6521
6522 /* If the last ref of an expression is an array ref, return a copy of the
6523    expression with that one removed.  Otherwise, a copy of the original
6524    expression.  This is used for allocate-expressions and pointer assignment
6525    LHS, where there may be an array specification that needs to be stripped
6526    off when using gfc_check_vardef_context.  */
6527
6528 static gfc_expr*
6529 remove_last_array_ref (gfc_expr* e)
6530 {
6531   gfc_expr* e2;
6532   gfc_ref** r;
6533
6534   e2 = gfc_copy_expr (e);
6535   for (r = &e2->ref; *r; r = &(*r)->next)
6536     if ((*r)->type == REF_ARRAY && !(*r)->next)
6537       {
6538         gfc_free_ref_list (*r);
6539         *r = NULL;
6540         break;
6541       }
6542
6543   return e2;
6544 }
6545
6546
6547 /* Used in resolve_allocate_expr to check that a allocation-object and
6548    a source-expr are conformable.  This does not catch all possible 
6549    cases; in particular a runtime checking is needed.  */
6550
6551 static gfc_try
6552 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6553 {
6554   gfc_ref *tail;
6555   for (tail = e2->ref; tail && tail->next; tail = tail->next);
6556   
6557   /* First compare rank.  */
6558   if (tail && e1->rank != tail->u.ar.as->rank)
6559     {
6560       gfc_error ("Source-expr at %L must be scalar or have the "
6561                  "same rank as the allocate-object at %L",
6562                  &e1->where, &e2->where);
6563       return FAILURE;
6564     }
6565
6566   if (e1->shape)
6567     {
6568       int i;
6569       mpz_t s;
6570
6571       mpz_init (s);
6572
6573       for (i = 0; i < e1->rank; i++)
6574         {
6575           if (tail->u.ar.end[i])
6576             {
6577               mpz_set (s, tail->u.ar.end[i]->value.integer);
6578               mpz_sub (s, s, tail->u.ar.start[i]->value.integer);
6579               mpz_add_ui (s, s, 1);
6580             }
6581           else
6582             {
6583               mpz_set (s, tail->u.ar.start[i]->value.integer);
6584             }
6585
6586           if (mpz_cmp (e1->shape[i], s) != 0)
6587             {
6588               gfc_error ("Source-expr at %L and allocate-object at %L must "
6589                          "have the same shape", &e1->where, &e2->where);
6590               mpz_clear (s);
6591               return FAILURE;
6592             }
6593         }
6594
6595       mpz_clear (s);
6596     }
6597
6598   return SUCCESS;
6599 }
6600
6601
6602 /* Resolve the expression in an ALLOCATE statement, doing the additional
6603    checks to see whether the expression is OK or not.  The expression must
6604    have a trailing array reference that gives the size of the array.  */
6605
6606 static gfc_try
6607 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6608 {
6609   int i, pointer, allocatable, dimension, is_abstract;
6610   int codimension;
6611   symbol_attribute attr;
6612   gfc_ref *ref, *ref2;
6613   gfc_expr *e2;
6614   gfc_array_ref *ar;
6615   gfc_symbol *sym = NULL;
6616   gfc_alloc *a;
6617   gfc_component *c;
6618   gfc_try t;
6619
6620   /* Mark the ultimost array component as being in allocate to allow DIMEN_STAR
6621      checking of coarrays.  */
6622   for (ref = e->ref; ref; ref = ref->next)
6623     if (ref->next == NULL)
6624       break;
6625
6626   if (ref && ref->type == REF_ARRAY)
6627     ref->u.ar.in_allocate = true;
6628
6629   if (gfc_resolve_expr (e) == FAILURE)
6630     goto failure;
6631
6632   /* Make sure the expression is allocatable or a pointer.  If it is
6633      pointer, the next-to-last reference must be a pointer.  */
6634
6635   ref2 = NULL;
6636   if (e->symtree)
6637     sym = e->symtree->n.sym;
6638
6639   /* Check whether ultimate component is abstract and CLASS.  */
6640   is_abstract = 0;
6641
6642   if (e->expr_type != EXPR_VARIABLE)
6643     {
6644       allocatable = 0;
6645       attr = gfc_expr_attr (e);
6646       pointer = attr.pointer;
6647       dimension = attr.dimension;
6648       codimension = attr.codimension;
6649     }
6650   else
6651     {
6652       if (sym->ts.type == BT_CLASS)
6653         {
6654           allocatable = CLASS_DATA (sym)->attr.allocatable;
6655           pointer = CLASS_DATA (sym)->attr.class_pointer;
6656           dimension = CLASS_DATA (sym)->attr.dimension;
6657           codimension = CLASS_DATA (sym)->attr.codimension;
6658           is_abstract = CLASS_DATA (sym)->attr.abstract;
6659         }
6660       else
6661         {
6662           allocatable = sym->attr.allocatable;
6663           pointer = sym->attr.pointer;
6664           dimension = sym->attr.dimension;
6665           codimension = sym->attr.codimension;
6666         }
6667
6668       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6669         {
6670           switch (ref->type)
6671             {
6672               case REF_ARRAY:
6673                 if (ref->next != NULL)
6674                   pointer = 0;
6675                 break;
6676
6677               case REF_COMPONENT:
6678                 /* F2008, C644.  */
6679                 if (gfc_is_coindexed (e))
6680                   {
6681                     gfc_error ("Coindexed allocatable object at %L",
6682                                &e->where);
6683                     goto failure;
6684                   }
6685
6686                 c = ref->u.c.component;
6687                 if (c->ts.type == BT_CLASS)
6688                   {
6689                     allocatable = CLASS_DATA (c)->attr.allocatable;
6690                     pointer = CLASS_DATA (c)->attr.class_pointer;
6691                     dimension = CLASS_DATA (c)->attr.dimension;
6692                     codimension = CLASS_DATA (c)->attr.codimension;
6693                     is_abstract = CLASS_DATA (c)->attr.abstract;
6694                   }
6695                 else
6696                   {
6697                     allocatable = c->attr.allocatable;
6698                     pointer = c->attr.pointer;
6699                     dimension = c->attr.dimension;
6700                     codimension = c->attr.codimension;
6701                     is_abstract = c->attr.abstract;
6702                   }
6703                 break;
6704
6705               case REF_SUBSTRING:
6706                 allocatable = 0;
6707                 pointer = 0;
6708                 break;
6709             }
6710         }
6711     }
6712
6713   if (allocatable == 0 && pointer == 0)
6714     {
6715       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6716                  &e->where);
6717       goto failure;
6718     }
6719
6720   /* Some checks for the SOURCE tag.  */
6721   if (code->expr3)
6722     {
6723       /* Check F03:C631.  */
6724       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6725         {
6726           gfc_error ("Type of entity at %L is type incompatible with "
6727                       "source-expr at %L", &e->where, &code->expr3->where);
6728           goto failure;
6729         }
6730
6731       /* Check F03:C632 and restriction following Note 6.18.  */
6732       if (code->expr3->rank > 0
6733           && conformable_arrays (code->expr3, e) == FAILURE)
6734         goto failure;
6735
6736       /* Check F03:C633.  */
6737       if (code->expr3->ts.kind != e->ts.kind)
6738         {
6739           gfc_error ("The allocate-object at %L and the source-expr at %L "
6740                       "shall have the same kind type parameter",
6741                       &e->where, &code->expr3->where);
6742           goto failure;
6743         }
6744     }
6745
6746   /* Check F08:C629.  */
6747   if (is_abstract && code->ext.alloc.ts.type == BT_UNKNOWN
6748       && !code->expr3)
6749     {
6750       gcc_assert (e->ts.type == BT_CLASS);
6751       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6752                  "type-spec or source-expr", sym->name, &e->where);
6753       goto failure;
6754     }
6755
6756   /* In the variable definition context checks, gfc_expr_attr is used
6757      on the expression.  This is fooled by the array specification
6758      present in e, thus we have to eliminate that one temporarily.  */
6759   e2 = remove_last_array_ref (e);
6760   t = SUCCESS;
6761   if (t == SUCCESS && pointer)
6762     t = gfc_check_vardef_context (e2, true, _("ALLOCATE object"));
6763   if (t == SUCCESS)
6764     t = gfc_check_vardef_context (e2, false, _("ALLOCATE object"));
6765   gfc_free_expr (e2);
6766   if (t == FAILURE)
6767     goto failure;
6768
6769   if (!code->expr3)
6770     {
6771       /* Set up default initializer if needed.  */
6772       gfc_typespec ts;
6773       gfc_expr *init_e;
6774
6775       if (code->ext.alloc.ts.type == BT_DERIVED)
6776         ts = code->ext.alloc.ts;
6777       else
6778         ts = e->ts;
6779
6780       if (ts.type == BT_CLASS)
6781         ts = ts.u.derived->components->ts;
6782
6783       if (ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&ts)))
6784         {
6785           gfc_code *init_st = gfc_get_code ();
6786           init_st->loc = code->loc;
6787           init_st->op = EXEC_INIT_ASSIGN;
6788           init_st->expr1 = gfc_expr_to_initialize (e);
6789           init_st->expr2 = init_e;
6790           init_st->next = code->next;
6791           code->next = init_st;
6792         }
6793     }
6794   else if (code->expr3->mold && code->expr3->ts.type == BT_DERIVED)
6795     {
6796       /* Default initialization via MOLD (non-polymorphic).  */
6797       gfc_expr *rhs = gfc_default_initializer (&code->expr3->ts);
6798       gfc_resolve_expr (rhs);
6799       gfc_free_expr (code->expr3);
6800       code->expr3 = rhs;
6801     }
6802
6803   if (e->ts.type == BT_CLASS)
6804     {
6805       /* Make sure the vtab symbol is present when
6806          the module variables are generated.  */
6807       gfc_typespec ts = e->ts;
6808       if (code->expr3)
6809         ts = code->expr3->ts;
6810       else if (code->ext.alloc.ts.type == BT_DERIVED)
6811         ts = code->ext.alloc.ts;
6812       gfc_find_derived_vtab (ts.u.derived);
6813     }
6814
6815   if (pointer || (dimension == 0 && codimension == 0))
6816     goto success;
6817
6818   /* Make sure the last reference node is an array specifiction.  */
6819
6820   if (!ref2 || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
6821       || (dimension && ref2->u.ar.dimen == 0))
6822     {
6823       gfc_error ("Array specification required in ALLOCATE statement "
6824                  "at %L", &e->where);
6825       goto failure;
6826     }
6827
6828   /* Make sure that the array section reference makes sense in the
6829     context of an ALLOCATE specification.  */
6830
6831   ar = &ref2->u.ar;
6832
6833   if (codimension && ar->codimen == 0)
6834     {
6835       gfc_error ("Coarray specification required in ALLOCATE statement "
6836                  "at %L", &e->where);
6837       goto failure;
6838     }
6839
6840   for (i = 0; i < ar->dimen; i++)
6841     {
6842       if (ref2->u.ar.type == AR_ELEMENT)
6843         goto check_symbols;
6844
6845       switch (ar->dimen_type[i])
6846         {
6847         case DIMEN_ELEMENT:
6848           break;
6849
6850         case DIMEN_RANGE:
6851           if (ar->start[i] != NULL
6852               && ar->end[i] != NULL
6853               && ar->stride[i] == NULL)
6854             break;
6855
6856           /* Fall Through...  */
6857
6858         case DIMEN_UNKNOWN:
6859         case DIMEN_VECTOR:
6860         case DIMEN_STAR:
6861           gfc_error ("Bad array specification in ALLOCATE statement at %L",
6862                      &e->where);
6863           goto failure;
6864         }
6865
6866 check_symbols:
6867       for (a = code->ext.alloc.list; a; a = a->next)
6868         {
6869           sym = a->expr->symtree->n.sym;
6870
6871           /* TODO - check derived type components.  */
6872           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
6873             continue;
6874
6875           if ((ar->start[i] != NULL
6876                && gfc_find_sym_in_expr (sym, ar->start[i]))
6877               || (ar->end[i] != NULL
6878                   && gfc_find_sym_in_expr (sym, ar->end[i])))
6879             {
6880               gfc_error ("'%s' must not appear in the array specification at "
6881                          "%L in the same ALLOCATE statement where it is "
6882                          "itself allocated", sym->name, &ar->where);
6883               goto failure;
6884             }
6885         }
6886     }
6887
6888   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
6889     {
6890       if (ar->dimen_type[i] == DIMEN_ELEMENT
6891           || ar->dimen_type[i] == DIMEN_RANGE)
6892         {
6893           if (i == (ar->dimen + ar->codimen - 1))
6894             {
6895               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
6896                          "statement at %L", &e->where);
6897               goto failure;
6898             }
6899           break;
6900         }
6901
6902       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
6903           && ar->stride[i] == NULL)
6904         break;
6905
6906       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
6907                  &e->where);
6908       goto failure;
6909     }
6910
6911   if (codimension && ar->as->rank == 0)
6912     {
6913       gfc_error ("Sorry, allocatable scalar coarrays are not yet supported "
6914                  "at %L", &e->where);
6915       goto failure;
6916     }
6917
6918 success:
6919   if (e->ts.deferred)
6920     {
6921       gfc_error ("Support for entity at %L with deferred type parameter "
6922                  "not yet implemented", &e->where);
6923       return FAILURE;
6924     }
6925   return SUCCESS;
6926
6927 failure:
6928   return FAILURE;
6929 }
6930
6931 static void
6932 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
6933 {
6934   gfc_expr *stat, *errmsg, *pe, *qe;
6935   gfc_alloc *a, *p, *q;
6936
6937   stat = code->expr1;
6938   errmsg = code->expr2;
6939
6940   /* Check the stat variable.  */
6941   if (stat)
6942     {
6943       gfc_check_vardef_context (stat, false, _("STAT variable"));
6944
6945       if ((stat->ts.type != BT_INTEGER
6946            && !(stat->ref && (stat->ref->type == REF_ARRAY
6947                               || stat->ref->type == REF_COMPONENT)))
6948           || stat->rank > 0)
6949         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
6950                    "variable", &stat->where);
6951
6952       for (p = code->ext.alloc.list; p; p = p->next)
6953         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
6954           {
6955             gfc_ref *ref1, *ref2;
6956             bool found = true;
6957
6958             for (ref1 = p->expr->ref, ref2 = stat->ref; ref1 && ref2;
6959                  ref1 = ref1->next, ref2 = ref2->next)
6960               {
6961                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
6962                   continue;
6963                 if (ref1->u.c.component->name != ref2->u.c.component->name)
6964                   {
6965                     found = false;
6966                     break;
6967                   }
6968               }
6969
6970             if (found)
6971               {
6972                 gfc_error ("Stat-variable at %L shall not be %sd within "
6973                            "the same %s statement", &stat->where, fcn, fcn);
6974                 break;
6975               }
6976           }
6977     }
6978
6979   /* Check the errmsg variable.  */
6980   if (errmsg)
6981     {
6982       if (!stat)
6983         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
6984                      &errmsg->where);
6985
6986       gfc_check_vardef_context (errmsg, false, _("ERRMSG variable"));
6987
6988       if ((errmsg->ts.type != BT_CHARACTER
6989            && !(errmsg->ref
6990                 && (errmsg->ref->type == REF_ARRAY
6991                     || errmsg->ref->type == REF_COMPONENT)))
6992           || errmsg->rank > 0 )
6993         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
6994                    "variable", &errmsg->where);
6995
6996       for (p = code->ext.alloc.list; p; p = p->next)
6997         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
6998           {
6999             gfc_ref *ref1, *ref2;
7000             bool found = true;
7001
7002             for (ref1 = p->expr->ref, ref2 = errmsg->ref; ref1 && ref2;
7003                  ref1 = ref1->next, ref2 = ref2->next)
7004               {
7005                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7006                   continue;
7007                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7008                   {
7009                     found = false;
7010                     break;
7011                   }
7012               }
7013
7014             if (found)
7015               {
7016                 gfc_error ("Errmsg-variable at %L shall not be %sd within "
7017                            "the same %s statement", &errmsg->where, fcn, fcn);
7018                 break;
7019               }
7020           }
7021     }
7022
7023   /* Check that an allocate-object appears only once in the statement.  
7024      FIXME: Checking derived types is disabled.  */
7025   for (p = code->ext.alloc.list; p; p = p->next)
7026     {
7027       pe = p->expr;
7028       for (q = p->next; q; q = q->next)
7029         {
7030           qe = q->expr;
7031           if (pe->symtree->n.sym->name == qe->symtree->n.sym->name)
7032             {
7033               /* This is a potential collision.  */
7034               gfc_ref *pr = pe->ref;
7035               gfc_ref *qr = qe->ref;
7036               
7037               /* Follow the references  until
7038                  a) They start to differ, in which case there is no error;
7039                  you can deallocate a%b and a%c in a single statement
7040                  b) Both of them stop, which is an error
7041                  c) One of them stops, which is also an error.  */
7042               while (1)
7043                 {
7044                   if (pr == NULL && qr == NULL)
7045                     {
7046                       gfc_error ("Allocate-object at %L also appears at %L",
7047                                  &pe->where, &qe->where);
7048                       break;
7049                     }
7050                   else if (pr != NULL && qr == NULL)
7051                     {
7052                       gfc_error ("Allocate-object at %L is subobject of"
7053                                  " object at %L", &pe->where, &qe->where);
7054                       break;
7055                     }
7056                   else if (pr == NULL && qr != NULL)
7057                     {
7058                       gfc_error ("Allocate-object at %L is subobject of"
7059                                  " object at %L", &qe->where, &pe->where);
7060                       break;
7061                     }
7062                   /* Here, pr != NULL && qr != NULL  */
7063                   gcc_assert(pr->type == qr->type);
7064                   if (pr->type == REF_ARRAY)
7065                     {
7066                       /* Handle cases like allocate(v(3)%x(3), v(2)%x(3)),
7067                          which are legal.  */
7068                       gcc_assert (qr->type == REF_ARRAY);
7069
7070                       if (pr->next && qr->next)
7071                         {
7072                           gfc_array_ref *par = &(pr->u.ar);
7073                           gfc_array_ref *qar = &(qr->u.ar);
7074                           if (gfc_dep_compare_expr (par->start[0],
7075                                                     qar->start[0]) != 0)
7076                               break;
7077                         }
7078                     }
7079                   else
7080                     {
7081                       if (pr->u.c.component->name != qr->u.c.component->name)
7082                         break;
7083                     }
7084                   
7085                   pr = pr->next;
7086                   qr = qr->next;
7087                 }
7088             }
7089         }
7090     }
7091
7092   if (strcmp (fcn, "ALLOCATE") == 0)
7093     {
7094       for (a = code->ext.alloc.list; a; a = a->next)
7095         resolve_allocate_expr (a->expr, code);
7096     }
7097   else
7098     {
7099       for (a = code->ext.alloc.list; a; a = a->next)
7100         resolve_deallocate_expr (a->expr);
7101     }
7102 }
7103
7104
7105 /************ SELECT CASE resolution subroutines ************/
7106
7107 /* Callback function for our mergesort variant.  Determines interval
7108    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
7109    op1 > op2.  Assumes we're not dealing with the default case.  
7110    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
7111    There are nine situations to check.  */
7112
7113 static int
7114 compare_cases (const gfc_case *op1, const gfc_case *op2)
7115 {
7116   int retval;
7117
7118   if (op1->low == NULL) /* op1 = (:L)  */
7119     {
7120       /* op2 = (:N), so overlap.  */
7121       retval = 0;
7122       /* op2 = (M:) or (M:N),  L < M  */
7123       if (op2->low != NULL
7124           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7125         retval = -1;
7126     }
7127   else if (op1->high == NULL) /* op1 = (K:)  */
7128     {
7129       /* op2 = (M:), so overlap.  */
7130       retval = 0;
7131       /* op2 = (:N) or (M:N), K > N  */
7132       if (op2->high != NULL
7133           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7134         retval = 1;
7135     }
7136   else /* op1 = (K:L)  */
7137     {
7138       if (op2->low == NULL)       /* op2 = (:N), K > N  */
7139         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7140                  ? 1 : 0;
7141       else if (op2->high == NULL) /* op2 = (M:), L < M  */
7142         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7143                  ? -1 : 0;
7144       else                      /* op2 = (M:N)  */
7145         {
7146           retval =  0;
7147           /* L < M  */
7148           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7149             retval =  -1;
7150           /* K > N  */
7151           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7152             retval =  1;
7153         }
7154     }
7155
7156   return retval;
7157 }
7158
7159
7160 /* Merge-sort a double linked case list, detecting overlap in the
7161    process.  LIST is the head of the double linked case list before it
7162    is sorted.  Returns the head of the sorted list if we don't see any
7163    overlap, or NULL otherwise.  */
7164
7165 static gfc_case *
7166 check_case_overlap (gfc_case *list)
7167 {
7168   gfc_case *p, *q, *e, *tail;
7169   int insize, nmerges, psize, qsize, cmp, overlap_seen;
7170
7171   /* If the passed list was empty, return immediately.  */
7172   if (!list)
7173     return NULL;
7174
7175   overlap_seen = 0;
7176   insize = 1;
7177
7178   /* Loop unconditionally.  The only exit from this loop is a return
7179      statement, when we've finished sorting the case list.  */
7180   for (;;)
7181     {
7182       p = list;
7183       list = NULL;
7184       tail = NULL;
7185
7186       /* Count the number of merges we do in this pass.  */
7187       nmerges = 0;
7188
7189       /* Loop while there exists a merge to be done.  */
7190       while (p)
7191         {
7192           int i;
7193
7194           /* Count this merge.  */
7195           nmerges++;
7196
7197           /* Cut the list in two pieces by stepping INSIZE places
7198              forward in the list, starting from P.  */
7199           psize = 0;
7200           q = p;
7201           for (i = 0; i < insize; i++)
7202             {
7203               psize++;
7204               q = q->right;
7205               if (!q)
7206                 break;
7207             }
7208           qsize = insize;
7209
7210           /* Now we have two lists.  Merge them!  */
7211           while (psize > 0 || (qsize > 0 && q != NULL))
7212             {
7213               /* See from which the next case to merge comes from.  */
7214               if (psize == 0)
7215                 {
7216                   /* P is empty so the next case must come from Q.  */
7217                   e = q;
7218                   q = q->right;
7219                   qsize--;
7220                 }
7221               else if (qsize == 0 || q == NULL)
7222                 {
7223                   /* Q is empty.  */
7224                   e = p;
7225                   p = p->right;
7226                   psize--;
7227                 }
7228               else
7229                 {
7230                   cmp = compare_cases (p, q);
7231                   if (cmp < 0)
7232                     {
7233                       /* The whole case range for P is less than the
7234                          one for Q.  */
7235                       e = p;
7236                       p = p->right;
7237                       psize--;
7238                     }
7239                   else if (cmp > 0)
7240                     {
7241                       /* The whole case range for Q is greater than
7242                          the case range for P.  */
7243                       e = q;
7244                       q = q->right;
7245                       qsize--;
7246                     }
7247                   else
7248                     {
7249                       /* The cases overlap, or they are the same
7250                          element in the list.  Either way, we must
7251                          issue an error and get the next case from P.  */
7252                       /* FIXME: Sort P and Q by line number.  */
7253                       gfc_error ("CASE label at %L overlaps with CASE "
7254                                  "label at %L", &p->where, &q->where);
7255                       overlap_seen = 1;
7256                       e = p;
7257                       p = p->right;
7258                       psize--;
7259                     }
7260                 }
7261
7262                 /* Add the next element to the merged list.  */
7263               if (tail)
7264                 tail->right = e;
7265               else
7266                 list = e;
7267               e->left = tail;
7268               tail = e;
7269             }
7270
7271           /* P has now stepped INSIZE places along, and so has Q.  So
7272              they're the same.  */
7273           p = q;
7274         }
7275       tail->right = NULL;
7276
7277       /* If we have done only one merge or none at all, we've
7278          finished sorting the cases.  */
7279       if (nmerges <= 1)
7280         {
7281           if (!overlap_seen)
7282             return list;
7283           else
7284             return NULL;
7285         }
7286
7287       /* Otherwise repeat, merging lists twice the size.  */
7288       insize *= 2;
7289     }
7290 }
7291
7292
7293 /* Check to see if an expression is suitable for use in a CASE statement.
7294    Makes sure that all case expressions are scalar constants of the same
7295    type.  Return FAILURE if anything is wrong.  */
7296
7297 static gfc_try
7298 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
7299 {
7300   if (e == NULL) return SUCCESS;
7301
7302   if (e->ts.type != case_expr->ts.type)
7303     {
7304       gfc_error ("Expression in CASE statement at %L must be of type %s",
7305                  &e->where, gfc_basic_typename (case_expr->ts.type));
7306       return FAILURE;
7307     }
7308
7309   /* C805 (R808) For a given case-construct, each case-value shall be of
7310      the same type as case-expr.  For character type, length differences
7311      are allowed, but the kind type parameters shall be the same.  */
7312
7313   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
7314     {
7315       gfc_error ("Expression in CASE statement at %L must be of kind %d",
7316                  &e->where, case_expr->ts.kind);
7317       return FAILURE;
7318     }
7319
7320   /* Convert the case value kind to that of case expression kind,
7321      if needed */
7322
7323   if (e->ts.kind != case_expr->ts.kind)
7324     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
7325
7326   if (e->rank != 0)
7327     {
7328       gfc_error ("Expression in CASE statement at %L must be scalar",
7329                  &e->where);
7330       return FAILURE;
7331     }
7332
7333   return SUCCESS;
7334 }
7335
7336
7337 /* Given a completely parsed select statement, we:
7338
7339      - Validate all expressions and code within the SELECT.
7340      - Make sure that the selection expression is not of the wrong type.
7341      - Make sure that no case ranges overlap.
7342      - Eliminate unreachable cases and unreachable code resulting from
7343        removing case labels.
7344
7345    The standard does allow unreachable cases, e.g. CASE (5:3).  But
7346    they are a hassle for code generation, and to prevent that, we just
7347    cut them out here.  This is not necessary for overlapping cases
7348    because they are illegal and we never even try to generate code.
7349
7350    We have the additional caveat that a SELECT construct could have
7351    been a computed GOTO in the source code. Fortunately we can fairly
7352    easily work around that here: The case_expr for a "real" SELECT CASE
7353    is in code->expr1, but for a computed GOTO it is in code->expr2. All
7354    we have to do is make sure that the case_expr is a scalar integer
7355    expression.  */
7356
7357 static void
7358 resolve_select (gfc_code *code)
7359 {
7360   gfc_code *body;
7361   gfc_expr *case_expr;
7362   gfc_case *cp, *default_case, *tail, *head;
7363   int seen_unreachable;
7364   int seen_logical;
7365   int ncases;
7366   bt type;
7367   gfc_try t;
7368
7369   if (code->expr1 == NULL)
7370     {
7371       /* This was actually a computed GOTO statement.  */
7372       case_expr = code->expr2;
7373       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
7374         gfc_error ("Selection expression in computed GOTO statement "
7375                    "at %L must be a scalar integer expression",
7376                    &case_expr->where);
7377
7378       /* Further checking is not necessary because this SELECT was built
7379          by the compiler, so it should always be OK.  Just move the
7380          case_expr from expr2 to expr so that we can handle computed
7381          GOTOs as normal SELECTs from here on.  */
7382       code->expr1 = code->expr2;
7383       code->expr2 = NULL;
7384       return;
7385     }
7386
7387   case_expr = code->expr1;
7388
7389   type = case_expr->ts.type;
7390   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
7391     {
7392       gfc_error ("Argument of SELECT statement at %L cannot be %s",
7393                  &case_expr->where, gfc_typename (&case_expr->ts));
7394
7395       /* Punt. Going on here just produce more garbage error messages.  */
7396       return;
7397     }
7398
7399   if (case_expr->rank != 0)
7400     {
7401       gfc_error ("Argument of SELECT statement at %L must be a scalar "
7402                  "expression", &case_expr->where);
7403
7404       /* Punt.  */
7405       return;
7406     }
7407
7408
7409   /* Raise a warning if an INTEGER case value exceeds the range of
7410      the case-expr. Later, all expressions will be promoted to the
7411      largest kind of all case-labels.  */
7412
7413   if (type == BT_INTEGER)
7414     for (body = code->block; body; body = body->block)
7415       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7416         {
7417           if (cp->low
7418               && gfc_check_integer_range (cp->low->value.integer,
7419                                           case_expr->ts.kind) != ARITH_OK)
7420             gfc_warning ("Expression in CASE statement at %L is "
7421                          "not in the range of %s", &cp->low->where,
7422                          gfc_typename (&case_expr->ts));
7423
7424           if (cp->high
7425               && cp->low != cp->high
7426               && gfc_check_integer_range (cp->high->value.integer,
7427                                           case_expr->ts.kind) != ARITH_OK)
7428             gfc_warning ("Expression in CASE statement at %L is "
7429                          "not in the range of %s", &cp->high->where,
7430                          gfc_typename (&case_expr->ts));
7431         }
7432
7433   /* PR 19168 has a long discussion concerning a mismatch of the kinds
7434      of the SELECT CASE expression and its CASE values.  Walk the lists
7435      of case values, and if we find a mismatch, promote case_expr to
7436      the appropriate kind.  */
7437
7438   if (type == BT_LOGICAL || type == BT_INTEGER)
7439     {
7440       for (body = code->block; body; body = body->block)
7441         {
7442           /* Walk the case label list.  */
7443           for (cp = body->ext.block.case_list; cp; cp = cp->next)
7444             {
7445               /* Intercept the DEFAULT case.  It does not have a kind.  */
7446               if (cp->low == NULL && cp->high == NULL)
7447                 continue;
7448
7449               /* Unreachable case ranges are discarded, so ignore.  */
7450               if (cp->low != NULL && cp->high != NULL
7451                   && cp->low != cp->high
7452                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7453                 continue;
7454
7455               if (cp->low != NULL
7456                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
7457                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
7458
7459               if (cp->high != NULL
7460                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
7461                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
7462             }
7463          }
7464     }
7465
7466   /* Assume there is no DEFAULT case.  */
7467   default_case = NULL;
7468   head = tail = NULL;
7469   ncases = 0;
7470   seen_logical = 0;
7471
7472   for (body = code->block; body; body = body->block)
7473     {
7474       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
7475       t = SUCCESS;
7476       seen_unreachable = 0;
7477
7478       /* Walk the case label list, making sure that all case labels
7479          are legal.  */
7480       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7481         {
7482           /* Count the number of cases in the whole construct.  */
7483           ncases++;
7484
7485           /* Intercept the DEFAULT case.  */
7486           if (cp->low == NULL && cp->high == NULL)
7487             {
7488               if (default_case != NULL)
7489                 {
7490                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
7491                              "by a second DEFAULT CASE at %L",
7492                              &default_case->where, &cp->where);
7493                   t = FAILURE;
7494                   break;
7495                 }
7496               else
7497                 {
7498                   default_case = cp;
7499                   continue;
7500                 }
7501             }
7502
7503           /* Deal with single value cases and case ranges.  Errors are
7504              issued from the validation function.  */
7505           if (validate_case_label_expr (cp->low, case_expr) != SUCCESS
7506               || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
7507             {
7508               t = FAILURE;
7509               break;
7510             }
7511
7512           if (type == BT_LOGICAL
7513               && ((cp->low == NULL || cp->high == NULL)
7514                   || cp->low != cp->high))
7515             {
7516               gfc_error ("Logical range in CASE statement at %L is not "
7517                          "allowed", &cp->low->where);
7518               t = FAILURE;
7519               break;
7520             }
7521
7522           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
7523             {
7524               int value;
7525               value = cp->low->value.logical == 0 ? 2 : 1;
7526               if (value & seen_logical)
7527                 {
7528                   gfc_error ("Constant logical value in CASE statement "
7529                              "is repeated at %L",
7530                              &cp->low->where);
7531                   t = FAILURE;
7532                   break;
7533                 }
7534               seen_logical |= value;
7535             }
7536
7537           if (cp->low != NULL && cp->high != NULL
7538               && cp->low != cp->high
7539               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7540             {
7541               if (gfc_option.warn_surprising)
7542                 gfc_warning ("Range specification at %L can never "
7543                              "be matched", &cp->where);
7544
7545               cp->unreachable = 1;
7546               seen_unreachable = 1;
7547             }
7548           else
7549             {
7550               /* If the case range can be matched, it can also overlap with
7551                  other cases.  To make sure it does not, we put it in a
7552                  double linked list here.  We sort that with a merge sort
7553                  later on to detect any overlapping cases.  */
7554               if (!head)
7555                 {
7556                   head = tail = cp;
7557                   head->right = head->left = NULL;
7558                 }
7559               else
7560                 {
7561                   tail->right = cp;
7562                   tail->right->left = tail;
7563                   tail = tail->right;
7564                   tail->right = NULL;
7565                 }
7566             }
7567         }
7568
7569       /* It there was a failure in the previous case label, give up
7570          for this case label list.  Continue with the next block.  */
7571       if (t == FAILURE)
7572         continue;
7573
7574       /* See if any case labels that are unreachable have been seen.
7575          If so, we eliminate them.  This is a bit of a kludge because
7576          the case lists for a single case statement (label) is a
7577          single forward linked lists.  */
7578       if (seen_unreachable)
7579       {
7580         /* Advance until the first case in the list is reachable.  */
7581         while (body->ext.block.case_list != NULL
7582                && body->ext.block.case_list->unreachable)
7583           {
7584             gfc_case *n = body->ext.block.case_list;
7585             body->ext.block.case_list = body->ext.block.case_list->next;
7586             n->next = NULL;
7587             gfc_free_case_list (n);
7588           }
7589
7590         /* Strip all other unreachable cases.  */
7591         if (body->ext.block.case_list)
7592           {
7593             for (cp = body->ext.block.case_list; cp->next; cp = cp->next)
7594               {
7595                 if (cp->next->unreachable)
7596                   {
7597                     gfc_case *n = cp->next;
7598                     cp->next = cp->next->next;
7599                     n->next = NULL;
7600                     gfc_free_case_list (n);
7601                   }
7602               }
7603           }
7604       }
7605     }
7606
7607   /* See if there were overlapping cases.  If the check returns NULL,
7608      there was overlap.  In that case we don't do anything.  If head
7609      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7610      then used during code generation for SELECT CASE constructs with
7611      a case expression of a CHARACTER type.  */
7612   if (head)
7613     {
7614       head = check_case_overlap (head);
7615
7616       /* Prepend the default_case if it is there.  */
7617       if (head != NULL && default_case)
7618         {
7619           default_case->left = NULL;
7620           default_case->right = head;
7621           head->left = default_case;
7622         }
7623     }
7624
7625   /* Eliminate dead blocks that may be the result if we've seen
7626      unreachable case labels for a block.  */
7627   for (body = code; body && body->block; body = body->block)
7628     {
7629       if (body->block->ext.block.case_list == NULL)
7630         {
7631           /* Cut the unreachable block from the code chain.  */
7632           gfc_code *c = body->block;
7633           body->block = c->block;
7634
7635           /* Kill the dead block, but not the blocks below it.  */
7636           c->block = NULL;
7637           gfc_free_statements (c);
7638         }
7639     }
7640
7641   /* More than two cases is legal but insane for logical selects.
7642      Issue a warning for it.  */
7643   if (gfc_option.warn_surprising && type == BT_LOGICAL
7644       && ncases > 2)
7645     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7646                  &code->loc);
7647 }
7648
7649
7650 /* Check if a derived type is extensible.  */
7651
7652 bool
7653 gfc_type_is_extensible (gfc_symbol *sym)
7654 {
7655   return !(sym->attr.is_bind_c || sym->attr.sequence);
7656 }
7657
7658
7659 /* Resolve an associate name:  Resolve target and ensure the type-spec is
7660    correct as well as possibly the array-spec.  */
7661
7662 static void
7663 resolve_assoc_var (gfc_symbol* sym, bool resolve_target)
7664 {
7665   gfc_expr* target;
7666
7667   gcc_assert (sym->assoc);
7668   gcc_assert (sym->attr.flavor == FL_VARIABLE);
7669
7670   /* If this is for SELECT TYPE, the target may not yet be set.  In that
7671      case, return.  Resolution will be called later manually again when
7672      this is done.  */
7673   target = sym->assoc->target;
7674   if (!target)
7675     return;
7676   gcc_assert (!sym->assoc->dangling);
7677
7678   if (resolve_target && gfc_resolve_expr (target) != SUCCESS)
7679     return;
7680
7681   /* For variable targets, we get some attributes from the target.  */
7682   if (target->expr_type == EXPR_VARIABLE)
7683     {
7684       gfc_symbol* tsym;
7685
7686       gcc_assert (target->symtree);
7687       tsym = target->symtree->n.sym;
7688
7689       sym->attr.asynchronous = tsym->attr.asynchronous;
7690       sym->attr.volatile_ = tsym->attr.volatile_;
7691
7692       sym->attr.target = (tsym->attr.target || tsym->attr.pointer);
7693     }
7694
7695   /* Get type if this was not already set.  Note that it can be
7696      some other type than the target in case this is a SELECT TYPE
7697      selector!  So we must not update when the type is already there.  */
7698   if (sym->ts.type == BT_UNKNOWN)
7699     sym->ts = target->ts;
7700   gcc_assert (sym->ts.type != BT_UNKNOWN);
7701
7702   /* See if this is a valid association-to-variable.  */
7703   sym->assoc->variable = (target->expr_type == EXPR_VARIABLE
7704                           && !gfc_has_vector_subscript (target));
7705
7706   /* Finally resolve if this is an array or not.  */
7707   if (sym->attr.dimension && target->rank == 0)
7708     {
7709       gfc_error ("Associate-name '%s' at %L is used as array",
7710                  sym->name, &sym->declared_at);
7711       sym->attr.dimension = 0;
7712       return;
7713     }
7714   if (target->rank > 0)
7715     sym->attr.dimension = 1;
7716
7717   if (sym->attr.dimension)
7718     {
7719       sym->as = gfc_get_array_spec ();
7720       sym->as->rank = target->rank;
7721       sym->as->type = AS_DEFERRED;
7722
7723       /* Target must not be coindexed, thus the associate-variable
7724          has no corank.  */
7725       sym->as->corank = 0;
7726     }
7727 }
7728
7729
7730 /* Resolve a SELECT TYPE statement.  */
7731
7732 static void
7733 resolve_select_type (gfc_code *code, gfc_namespace *old_ns)
7734 {
7735   gfc_symbol *selector_type;
7736   gfc_code *body, *new_st, *if_st, *tail;
7737   gfc_code *class_is = NULL, *default_case = NULL;
7738   gfc_case *c;
7739   gfc_symtree *st;
7740   char name[GFC_MAX_SYMBOL_LEN];
7741   gfc_namespace *ns;
7742   int error = 0;
7743
7744   ns = code->ext.block.ns;
7745   gfc_resolve (ns);
7746
7747   /* Check for F03:C813.  */
7748   if (code->expr1->ts.type != BT_CLASS
7749       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
7750     {
7751       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
7752                  "at %L", &code->loc);
7753       return;
7754     }
7755
7756   if (code->expr2)
7757     {
7758       if (code->expr1->symtree->n.sym->attr.untyped)
7759         code->expr1->symtree->n.sym->ts = code->expr2->ts;
7760       selector_type = CLASS_DATA (code->expr2)->ts.u.derived;
7761     }
7762   else
7763     selector_type = CLASS_DATA (code->expr1)->ts.u.derived;
7764
7765   /* Loop over TYPE IS / CLASS IS cases.  */
7766   for (body = code->block; body; body = body->block)
7767     {
7768       c = body->ext.block.case_list;
7769
7770       /* Check F03:C815.  */
7771       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7772           && !gfc_type_is_extensible (c->ts.u.derived))
7773         {
7774           gfc_error ("Derived type '%s' at %L must be extensible",
7775                      c->ts.u.derived->name, &c->where);
7776           error++;
7777           continue;
7778         }
7779
7780       /* Check F03:C816.  */
7781       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7782           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
7783         {
7784           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
7785                      c->ts.u.derived->name, &c->where, selector_type->name);
7786           error++;
7787           continue;
7788         }
7789
7790       /* Intercept the DEFAULT case.  */
7791       if (c->ts.type == BT_UNKNOWN)
7792         {
7793           /* Check F03:C818.  */
7794           if (default_case)
7795             {
7796               gfc_error ("The DEFAULT CASE at %L cannot be followed "
7797                          "by a second DEFAULT CASE at %L",
7798                          &default_case->ext.block.case_list->where, &c->where);
7799               error++;
7800               continue;
7801             }
7802
7803           default_case = body;
7804         }
7805     }
7806     
7807   if (error > 0)
7808     return;
7809
7810   /* Transform SELECT TYPE statement to BLOCK and associate selector to
7811      target if present.  If there are any EXIT statements referring to the
7812      SELECT TYPE construct, this is no problem because the gfc_code
7813      reference stays the same and EXIT is equally possible from the BLOCK
7814      it is changed to.  */
7815   code->op = EXEC_BLOCK;
7816   if (code->expr2)
7817     {
7818       gfc_association_list* assoc;
7819
7820       assoc = gfc_get_association_list ();
7821       assoc->st = code->expr1->symtree;
7822       assoc->target = gfc_copy_expr (code->expr2);
7823       /* assoc->variable will be set by resolve_assoc_var.  */
7824       
7825       code->ext.block.assoc = assoc;
7826       code->expr1->symtree->n.sym->assoc = assoc;
7827
7828       resolve_assoc_var (code->expr1->symtree->n.sym, false);
7829     }
7830   else
7831     code->ext.block.assoc = NULL;
7832
7833   /* Add EXEC_SELECT to switch on type.  */
7834   new_st = gfc_get_code ();
7835   new_st->op = code->op;
7836   new_st->expr1 = code->expr1;
7837   new_st->expr2 = code->expr2;
7838   new_st->block = code->block;
7839   code->expr1 = code->expr2 =  NULL;
7840   code->block = NULL;
7841   if (!ns->code)
7842     ns->code = new_st;
7843   else
7844     ns->code->next = new_st;
7845   code = new_st;
7846   code->op = EXEC_SELECT;
7847   gfc_add_vptr_component (code->expr1);
7848   gfc_add_hash_component (code->expr1);
7849
7850   /* Loop over TYPE IS / CLASS IS cases.  */
7851   for (body = code->block; body; body = body->block)
7852     {
7853       c = body->ext.block.case_list;
7854
7855       if (c->ts.type == BT_DERIVED)
7856         c->low = c->high = gfc_get_int_expr (gfc_default_integer_kind, NULL,
7857                                              c->ts.u.derived->hash_value);
7858
7859       else if (c->ts.type == BT_UNKNOWN)
7860         continue;
7861
7862       /* Associate temporary to selector.  This should only be done
7863          when this case is actually true, so build a new ASSOCIATE
7864          that does precisely this here (instead of using the
7865          'global' one).  */
7866
7867       if (c->ts.type == BT_CLASS)
7868         sprintf (name, "__tmp_class_%s", c->ts.u.derived->name);
7869       else
7870         sprintf (name, "__tmp_type_%s", c->ts.u.derived->name);
7871       st = gfc_find_symtree (ns->sym_root, name);
7872       gcc_assert (st->n.sym->assoc);
7873       st->n.sym->assoc->target = gfc_get_variable_expr (code->expr1->symtree);
7874       if (c->ts.type == BT_DERIVED)
7875         gfc_add_data_component (st->n.sym->assoc->target);
7876
7877       new_st = gfc_get_code ();
7878       new_st->op = EXEC_BLOCK;
7879       new_st->ext.block.ns = gfc_build_block_ns (ns);
7880       new_st->ext.block.ns->code = body->next;
7881       body->next = new_st;
7882
7883       /* Chain in the new list only if it is marked as dangling.  Otherwise
7884          there is a CASE label overlap and this is already used.  Just ignore,
7885          the error is diagonsed elsewhere.  */
7886       if (st->n.sym->assoc->dangling)
7887         {
7888           new_st->ext.block.assoc = st->n.sym->assoc;
7889           st->n.sym->assoc->dangling = 0;
7890         }
7891
7892       resolve_assoc_var (st->n.sym, false);
7893     }
7894     
7895   /* Take out CLASS IS cases for separate treatment.  */
7896   body = code;
7897   while (body && body->block)
7898     {
7899       if (body->block->ext.block.case_list->ts.type == BT_CLASS)
7900         {
7901           /* Add to class_is list.  */
7902           if (class_is == NULL)
7903             { 
7904               class_is = body->block;
7905               tail = class_is;
7906             }
7907           else
7908             {
7909               for (tail = class_is; tail->block; tail = tail->block) ;
7910               tail->block = body->block;
7911               tail = tail->block;
7912             }
7913           /* Remove from EXEC_SELECT list.  */
7914           body->block = body->block->block;
7915           tail->block = NULL;
7916         }
7917       else
7918         body = body->block;
7919     }
7920
7921   if (class_is)
7922     {
7923       gfc_symbol *vtab;
7924       
7925       if (!default_case)
7926         {
7927           /* Add a default case to hold the CLASS IS cases.  */
7928           for (tail = code; tail->block; tail = tail->block) ;
7929           tail->block = gfc_get_code ();
7930           tail = tail->block;
7931           tail->op = EXEC_SELECT_TYPE;
7932           tail->ext.block.case_list = gfc_get_case ();
7933           tail->ext.block.case_list->ts.type = BT_UNKNOWN;
7934           tail->next = NULL;
7935           default_case = tail;
7936         }
7937
7938       /* More than one CLASS IS block?  */
7939       if (class_is->block)
7940         {
7941           gfc_code **c1,*c2;
7942           bool swapped;
7943           /* Sort CLASS IS blocks by extension level.  */
7944           do
7945             {
7946               swapped = false;
7947               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
7948                 {
7949                   c2 = (*c1)->block;
7950                   /* F03:C817 (check for doubles).  */
7951                   if ((*c1)->ext.block.case_list->ts.u.derived->hash_value
7952                       == c2->ext.block.case_list->ts.u.derived->hash_value)
7953                     {
7954                       gfc_error ("Double CLASS IS block in SELECT TYPE "
7955                                  "statement at %L",
7956                                  &c2->ext.block.case_list->where);
7957                       return;
7958                     }
7959                   if ((*c1)->ext.block.case_list->ts.u.derived->attr.extension
7960                       < c2->ext.block.case_list->ts.u.derived->attr.extension)
7961                     {
7962                       /* Swap.  */
7963                       (*c1)->block = c2->block;
7964                       c2->block = *c1;
7965                       *c1 = c2;
7966                       swapped = true;
7967                     }
7968                 }
7969             }
7970           while (swapped);
7971         }
7972         
7973       /* Generate IF chain.  */
7974       if_st = gfc_get_code ();
7975       if_st->op = EXEC_IF;
7976       new_st = if_st;
7977       for (body = class_is; body; body = body->block)
7978         {
7979           new_st->block = gfc_get_code ();
7980           new_st = new_st->block;
7981           new_st->op = EXEC_IF;
7982           /* Set up IF condition: Call _gfortran_is_extension_of.  */
7983           new_st->expr1 = gfc_get_expr ();
7984           new_st->expr1->expr_type = EXPR_FUNCTION;
7985           new_st->expr1->ts.type = BT_LOGICAL;
7986           new_st->expr1->ts.kind = 4;
7987           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
7988           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
7989           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
7990           /* Set up arguments.  */
7991           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
7992           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
7993           new_st->expr1->value.function.actual->expr->where = code->loc;
7994           gfc_add_vptr_component (new_st->expr1->value.function.actual->expr);
7995           vtab = gfc_find_derived_vtab (body->ext.block.case_list->ts.u.derived);
7996           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
7997           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
7998           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
7999           new_st->next = body->next;
8000         }
8001         if (default_case->next)
8002           {
8003             new_st->block = gfc_get_code ();
8004             new_st = new_st->block;
8005             new_st->op = EXEC_IF;
8006             new_st->next = default_case->next;
8007           }
8008           
8009         /* Replace CLASS DEFAULT code by the IF chain.  */
8010         default_case->next = if_st;
8011     }
8012
8013   /* Resolve the internal code.  This can not be done earlier because
8014      it requires that the sym->assoc of selectors is set already.  */
8015   gfc_current_ns = ns;
8016   gfc_resolve_blocks (code->block, gfc_current_ns);
8017   gfc_current_ns = old_ns;
8018
8019   resolve_select (code);
8020 }
8021
8022
8023 /* Resolve a transfer statement. This is making sure that:
8024    -- a derived type being transferred has only non-pointer components
8025    -- a derived type being transferred doesn't have private components, unless 
8026       it's being transferred from the module where the type was defined
8027    -- we're not trying to transfer a whole assumed size array.  */
8028
8029 static void
8030 resolve_transfer (gfc_code *code)
8031 {
8032   gfc_typespec *ts;
8033   gfc_symbol *sym;
8034   gfc_ref *ref;
8035   gfc_expr *exp;
8036
8037   exp = code->expr1;
8038
8039   while (exp != NULL && exp->expr_type == EXPR_OP
8040          && exp->value.op.op == INTRINSIC_PARENTHESES)
8041     exp = exp->value.op.op1;
8042
8043   if (exp == NULL || (exp->expr_type != EXPR_VARIABLE
8044                       && exp->expr_type != EXPR_FUNCTION))
8045     return;
8046
8047   /* If we are reading, the variable will be changed.  Note that
8048      code->ext.dt may be NULL if the TRANSFER is related to
8049      an INQUIRE statement -- but in this case, we are not reading, either.  */
8050   if (code->ext.dt && code->ext.dt->dt_io_kind->value.iokind == M_READ
8051       && gfc_check_vardef_context (exp, false, _("item in READ")) == FAILURE)
8052     return;
8053
8054   sym = exp->symtree->n.sym;
8055   ts = &sym->ts;
8056
8057   /* Go to actual component transferred.  */
8058   for (ref = exp->ref; ref; ref = ref->next)
8059     if (ref->type == REF_COMPONENT)
8060       ts = &ref->u.c.component->ts;
8061
8062   if (ts->type == BT_CLASS)
8063     {
8064       /* FIXME: Test for defined input/output.  */
8065       gfc_error ("Data transfer element at %L cannot be polymorphic unless "
8066                 "it is processed by a defined input/output procedure",
8067                 &code->loc);
8068       return;
8069     }
8070
8071   if (ts->type == BT_DERIVED)
8072     {
8073       /* Check that transferred derived type doesn't contain POINTER
8074          components.  */
8075       if (ts->u.derived->attr.pointer_comp)
8076         {
8077           gfc_error ("Data transfer element at %L cannot have "
8078                      "POINTER components", &code->loc);
8079           return;
8080         }
8081
8082       if (ts->u.derived->attr.alloc_comp)
8083         {
8084           gfc_error ("Data transfer element at %L cannot have "
8085                      "ALLOCATABLE components", &code->loc);
8086           return;
8087         }
8088
8089       if (derived_inaccessible (ts->u.derived))
8090         {
8091           gfc_error ("Data transfer element at %L cannot have "
8092                      "PRIVATE components",&code->loc);
8093           return;
8094         }
8095     }
8096
8097   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
8098       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
8099     {
8100       gfc_error ("Data transfer element at %L cannot be a full reference to "
8101                  "an assumed-size array", &code->loc);
8102       return;
8103     }
8104 }
8105
8106
8107 /*********** Toplevel code resolution subroutines ***********/
8108
8109 /* Find the set of labels that are reachable from this block.  We also
8110    record the last statement in each block.  */
8111      
8112 static void
8113 find_reachable_labels (gfc_code *block)
8114 {
8115   gfc_code *c;
8116
8117   if (!block)
8118     return;
8119
8120   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
8121
8122   /* Collect labels in this block.  We don't keep those corresponding
8123      to END {IF|SELECT}, these are checked in resolve_branch by going
8124      up through the code_stack.  */
8125   for (c = block; c; c = c->next)
8126     {
8127       if (c->here && c->op != EXEC_END_BLOCK)
8128         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
8129     }
8130
8131   /* Merge with labels from parent block.  */
8132   if (cs_base->prev)
8133     {
8134       gcc_assert (cs_base->prev->reachable_labels);
8135       bitmap_ior_into (cs_base->reachable_labels,
8136                        cs_base->prev->reachable_labels);
8137     }
8138 }
8139
8140
8141 static void
8142 resolve_sync (gfc_code *code)
8143 {
8144   /* Check imageset. The * case matches expr1 == NULL.  */
8145   if (code->expr1)
8146     {
8147       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
8148         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
8149                    "INTEGER expression", &code->expr1->where);
8150       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
8151           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
8152         gfc_error ("Imageset argument at %L must between 1 and num_images()",
8153                    &code->expr1->where);
8154       else if (code->expr1->expr_type == EXPR_ARRAY
8155                && gfc_simplify_expr (code->expr1, 0) == SUCCESS)
8156         {
8157            gfc_constructor *cons;
8158            cons = gfc_constructor_first (code->expr1->value.constructor);
8159            for (; cons; cons = gfc_constructor_next (cons))
8160              if (cons->expr->expr_type == EXPR_CONSTANT
8161                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
8162                gfc_error ("Imageset argument at %L must between 1 and "
8163                           "num_images()", &cons->expr->where);
8164         }
8165     }
8166
8167   /* Check STAT.  */
8168   if (code->expr2
8169       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8170           || code->expr2->expr_type != EXPR_VARIABLE))
8171     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8172                &code->expr2->where);
8173
8174   /* Check ERRMSG.  */
8175   if (code->expr3
8176       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8177           || code->expr3->expr_type != EXPR_VARIABLE))
8178     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8179                &code->expr3->where);
8180 }
8181
8182
8183 /* Given a branch to a label, see if the branch is conforming.
8184    The code node describes where the branch is located.  */
8185
8186 static void
8187 resolve_branch (gfc_st_label *label, gfc_code *code)
8188 {
8189   code_stack *stack;
8190
8191   if (label == NULL)
8192     return;
8193
8194   /* Step one: is this a valid branching target?  */
8195
8196   if (label->defined == ST_LABEL_UNKNOWN)
8197     {
8198       gfc_error ("Label %d referenced at %L is never defined", label->value,
8199                  &label->where);
8200       return;
8201     }
8202
8203   if (label->defined != ST_LABEL_TARGET)
8204     {
8205       gfc_error ("Statement at %L is not a valid branch target statement "
8206                  "for the branch statement at %L", &label->where, &code->loc);
8207       return;
8208     }
8209
8210   /* Step two: make sure this branch is not a branch to itself ;-)  */
8211
8212   if (code->here == label)
8213     {
8214       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
8215       return;
8216     }
8217
8218   /* Step three:  See if the label is in the same block as the
8219      branching statement.  The hard work has been done by setting up
8220      the bitmap reachable_labels.  */
8221
8222   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
8223     {
8224       /* Check now whether there is a CRITICAL construct; if so, check
8225          whether the label is still visible outside of the CRITICAL block,
8226          which is invalid.  */
8227       for (stack = cs_base; stack; stack = stack->prev)
8228         if (stack->current->op == EXEC_CRITICAL
8229             && bitmap_bit_p (stack->reachable_labels, label->value))
8230           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8231                       " at %L", &code->loc, &label->where);
8232
8233       return;
8234     }
8235
8236   /* Step four:  If we haven't found the label in the bitmap, it may
8237     still be the label of the END of the enclosing block, in which
8238     case we find it by going up the code_stack.  */
8239
8240   for (stack = cs_base; stack; stack = stack->prev)
8241     {
8242       if (stack->current->next && stack->current->next->here == label)
8243         break;
8244       if (stack->current->op == EXEC_CRITICAL)
8245         {
8246           /* Note: A label at END CRITICAL does not leave the CRITICAL
8247              construct as END CRITICAL is still part of it.  */
8248           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8249                       " at %L", &code->loc, &label->where);
8250           return;
8251         }
8252     }
8253
8254   if (stack)
8255     {
8256       gcc_assert (stack->current->next->op == EXEC_END_BLOCK);
8257       return;
8258     }
8259
8260   /* The label is not in an enclosing block, so illegal.  This was
8261      allowed in Fortran 66, so we allow it as extension.  No
8262      further checks are necessary in this case.  */
8263   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
8264                   "as the GOTO statement at %L", &label->where,
8265                   &code->loc);
8266   return;
8267 }
8268
8269
8270 /* Check whether EXPR1 has the same shape as EXPR2.  */
8271
8272 static gfc_try
8273 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
8274 {
8275   mpz_t shape[GFC_MAX_DIMENSIONS];
8276   mpz_t shape2[GFC_MAX_DIMENSIONS];
8277   gfc_try result = FAILURE;
8278   int i;
8279
8280   /* Compare the rank.  */
8281   if (expr1->rank != expr2->rank)
8282     return result;
8283
8284   /* Compare the size of each dimension.  */
8285   for (i=0; i<expr1->rank; i++)
8286     {
8287       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
8288         goto ignore;
8289
8290       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
8291         goto ignore;
8292
8293       if (mpz_cmp (shape[i], shape2[i]))
8294         goto over;
8295     }
8296
8297   /* When either of the two expression is an assumed size array, we
8298      ignore the comparison of dimension sizes.  */
8299 ignore:
8300   result = SUCCESS;
8301
8302 over:
8303   for (i--; i >= 0; i--)
8304     {
8305       mpz_clear (shape[i]);
8306       mpz_clear (shape2[i]);
8307     }
8308   return result;
8309 }
8310
8311
8312 /* Check whether a WHERE assignment target or a WHERE mask expression
8313    has the same shape as the outmost WHERE mask expression.  */
8314
8315 static void
8316 resolve_where (gfc_code *code, gfc_expr *mask)
8317 {
8318   gfc_code *cblock;
8319   gfc_code *cnext;
8320   gfc_expr *e = NULL;
8321
8322   cblock = code->block;
8323
8324   /* Store the first WHERE mask-expr of the WHERE statement or construct.
8325      In case of nested WHERE, only the outmost one is stored.  */
8326   if (mask == NULL) /* outmost WHERE */
8327     e = cblock->expr1;
8328   else /* inner WHERE */
8329     e = mask;
8330
8331   while (cblock)
8332     {
8333       if (cblock->expr1)
8334         {
8335           /* Check if the mask-expr has a consistent shape with the
8336              outmost WHERE mask-expr.  */
8337           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
8338             gfc_error ("WHERE mask at %L has inconsistent shape",
8339                        &cblock->expr1->where);
8340          }
8341
8342       /* the assignment statement of a WHERE statement, or the first
8343          statement in where-body-construct of a WHERE construct */
8344       cnext = cblock->next;
8345       while (cnext)
8346         {
8347           switch (cnext->op)
8348             {
8349             /* WHERE assignment statement */
8350             case EXEC_ASSIGN:
8351
8352               /* Check shape consistent for WHERE assignment target.  */
8353               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
8354                gfc_error ("WHERE assignment target at %L has "
8355                           "inconsistent shape", &cnext->expr1->where);
8356               break;
8357
8358   
8359             case EXEC_ASSIGN_CALL:
8360               resolve_call (cnext);
8361               if (!cnext->resolved_sym->attr.elemental)
8362                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8363                           &cnext->ext.actual->expr->where);
8364               break;
8365
8366             /* WHERE or WHERE construct is part of a where-body-construct */
8367             case EXEC_WHERE:
8368               resolve_where (cnext, e);
8369               break;
8370
8371             default:
8372               gfc_error ("Unsupported statement inside WHERE at %L",
8373                          &cnext->loc);
8374             }
8375          /* the next statement within the same where-body-construct */
8376          cnext = cnext->next;
8377        }
8378     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8379     cblock = cblock->block;
8380   }
8381 }
8382
8383
8384 /* Resolve assignment in FORALL construct.
8385    NVAR is the number of FORALL index variables, and VAR_EXPR records the
8386    FORALL index variables.  */
8387
8388 static void
8389 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
8390 {
8391   int n;
8392
8393   for (n = 0; n < nvar; n++)
8394     {
8395       gfc_symbol *forall_index;
8396
8397       forall_index = var_expr[n]->symtree->n.sym;
8398
8399       /* Check whether the assignment target is one of the FORALL index
8400          variable.  */
8401       if ((code->expr1->expr_type == EXPR_VARIABLE)
8402           && (code->expr1->symtree->n.sym == forall_index))
8403         gfc_error ("Assignment to a FORALL index variable at %L",
8404                    &code->expr1->where);
8405       else
8406         {
8407           /* If one of the FORALL index variables doesn't appear in the
8408              assignment variable, then there could be a many-to-one
8409              assignment.  Emit a warning rather than an error because the
8410              mask could be resolving this problem.  */
8411           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
8412             gfc_warning ("The FORALL with index '%s' is not used on the "
8413                          "left side of the assignment at %L and so might "
8414                          "cause multiple assignment to this object",
8415                          var_expr[n]->symtree->name, &code->expr1->where);
8416         }
8417     }
8418 }
8419
8420
8421 /* Resolve WHERE statement in FORALL construct.  */
8422
8423 static void
8424 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
8425                                   gfc_expr **var_expr)
8426 {
8427   gfc_code *cblock;
8428   gfc_code *cnext;
8429
8430   cblock = code->block;
8431   while (cblock)
8432     {
8433       /* the assignment statement of a WHERE statement, or the first
8434          statement in where-body-construct of a WHERE construct */
8435       cnext = cblock->next;
8436       while (cnext)
8437         {
8438           switch (cnext->op)
8439             {
8440             /* WHERE assignment statement */
8441             case EXEC_ASSIGN:
8442               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
8443               break;
8444   
8445             /* WHERE operator assignment statement */
8446             case EXEC_ASSIGN_CALL:
8447               resolve_call (cnext);
8448               if (!cnext->resolved_sym->attr.elemental)
8449                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8450                           &cnext->ext.actual->expr->where);
8451               break;
8452
8453             /* WHERE or WHERE construct is part of a where-body-construct */
8454             case EXEC_WHERE:
8455               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
8456               break;
8457
8458             default:
8459               gfc_error ("Unsupported statement inside WHERE at %L",
8460                          &cnext->loc);
8461             }
8462           /* the next statement within the same where-body-construct */
8463           cnext = cnext->next;
8464         }
8465       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8466       cblock = cblock->block;
8467     }
8468 }
8469
8470
8471 /* Traverse the FORALL body to check whether the following errors exist:
8472    1. For assignment, check if a many-to-one assignment happens.
8473    2. For WHERE statement, check the WHERE body to see if there is any
8474       many-to-one assignment.  */
8475
8476 static void
8477 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
8478 {
8479   gfc_code *c;
8480
8481   c = code->block->next;
8482   while (c)
8483     {
8484       switch (c->op)
8485         {
8486         case EXEC_ASSIGN:
8487         case EXEC_POINTER_ASSIGN:
8488           gfc_resolve_assign_in_forall (c, nvar, var_expr);
8489           break;
8490
8491         case EXEC_ASSIGN_CALL:
8492           resolve_call (c);
8493           break;
8494
8495         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
8496            there is no need to handle it here.  */
8497         case EXEC_FORALL:
8498           break;
8499         case EXEC_WHERE:
8500           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
8501           break;
8502         default:
8503           break;
8504         }
8505       /* The next statement in the FORALL body.  */
8506       c = c->next;
8507     }
8508 }
8509
8510
8511 /* Counts the number of iterators needed inside a forall construct, including
8512    nested forall constructs. This is used to allocate the needed memory 
8513    in gfc_resolve_forall.  */
8514
8515 static int 
8516 gfc_count_forall_iterators (gfc_code *code)
8517 {
8518   int max_iters, sub_iters, current_iters;
8519   gfc_forall_iterator *fa;
8520
8521   gcc_assert(code->op == EXEC_FORALL);
8522   max_iters = 0;
8523   current_iters = 0;
8524
8525   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8526     current_iters ++;
8527   
8528   code = code->block->next;
8529
8530   while (code)
8531     {          
8532       if (code->op == EXEC_FORALL)
8533         {
8534           sub_iters = gfc_count_forall_iterators (code);
8535           if (sub_iters > max_iters)
8536             max_iters = sub_iters;
8537         }
8538       code = code->next;
8539     }
8540
8541   return current_iters + max_iters;
8542 }
8543
8544
8545 /* Given a FORALL construct, first resolve the FORALL iterator, then call
8546    gfc_resolve_forall_body to resolve the FORALL body.  */
8547
8548 static void
8549 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
8550 {
8551   static gfc_expr **var_expr;
8552   static int total_var = 0;
8553   static int nvar = 0;
8554   int old_nvar, tmp;
8555   gfc_forall_iterator *fa;
8556   int i;
8557
8558   old_nvar = nvar;
8559
8560   /* Start to resolve a FORALL construct   */
8561   if (forall_save == 0)
8562     {
8563       /* Count the total number of FORALL index in the nested FORALL
8564          construct in order to allocate the VAR_EXPR with proper size.  */
8565       total_var = gfc_count_forall_iterators (code);
8566
8567       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
8568       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
8569     }
8570
8571   /* The information about FORALL iterator, including FORALL index start, end
8572      and stride. The FORALL index can not appear in start, end or stride.  */
8573   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8574     {
8575       /* Check if any outer FORALL index name is the same as the current
8576          one.  */
8577       for (i = 0; i < nvar; i++)
8578         {
8579           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
8580             {
8581               gfc_error ("An outer FORALL construct already has an index "
8582                          "with this name %L", &fa->var->where);
8583             }
8584         }
8585
8586       /* Record the current FORALL index.  */
8587       var_expr[nvar] = gfc_copy_expr (fa->var);
8588
8589       nvar++;
8590
8591       /* No memory leak.  */
8592       gcc_assert (nvar <= total_var);
8593     }
8594
8595   /* Resolve the FORALL body.  */
8596   gfc_resolve_forall_body (code, nvar, var_expr);
8597
8598   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
8599   gfc_resolve_blocks (code->block, ns);
8600
8601   tmp = nvar;
8602   nvar = old_nvar;
8603   /* Free only the VAR_EXPRs allocated in this frame.  */
8604   for (i = nvar; i < tmp; i++)
8605      gfc_free_expr (var_expr[i]);
8606
8607   if (nvar == 0)
8608     {
8609       /* We are in the outermost FORALL construct.  */
8610       gcc_assert (forall_save == 0);
8611
8612       /* VAR_EXPR is not needed any more.  */
8613       gfc_free (var_expr);
8614       total_var = 0;
8615     }
8616 }
8617
8618
8619 /* Resolve a BLOCK construct statement.  */
8620
8621 static void
8622 resolve_block_construct (gfc_code* code)
8623 {
8624   /* Resolve the BLOCK's namespace.  */
8625   gfc_resolve (code->ext.block.ns);
8626
8627   /* For an ASSOCIATE block, the associations (and their targets) are already
8628      resolved during resolve_symbol.  */
8629 }
8630
8631
8632 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
8633    DO code nodes.  */
8634
8635 static void resolve_code (gfc_code *, gfc_namespace *);
8636
8637 void
8638 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
8639 {
8640   gfc_try t;
8641
8642   for (; b; b = b->block)
8643     {
8644       t = gfc_resolve_expr (b->expr1);
8645       if (gfc_resolve_expr (b->expr2) == FAILURE)
8646         t = FAILURE;
8647
8648       switch (b->op)
8649         {
8650         case EXEC_IF:
8651           if (t == SUCCESS && b->expr1 != NULL
8652               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
8653             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8654                        &b->expr1->where);
8655           break;
8656
8657         case EXEC_WHERE:
8658           if (t == SUCCESS
8659               && b->expr1 != NULL
8660               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
8661             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
8662                        &b->expr1->where);
8663           break;
8664
8665         case EXEC_GOTO:
8666           resolve_branch (b->label1, b);
8667           break;
8668
8669         case EXEC_BLOCK:
8670           resolve_block_construct (b);
8671           break;
8672
8673         case EXEC_SELECT:
8674         case EXEC_SELECT_TYPE:
8675         case EXEC_FORALL:
8676         case EXEC_DO:
8677         case EXEC_DO_WHILE:
8678         case EXEC_CRITICAL:
8679         case EXEC_READ:
8680         case EXEC_WRITE:
8681         case EXEC_IOLENGTH:
8682         case EXEC_WAIT:
8683           break;
8684
8685         case EXEC_OMP_ATOMIC:
8686         case EXEC_OMP_CRITICAL:
8687         case EXEC_OMP_DO:
8688         case EXEC_OMP_MASTER:
8689         case EXEC_OMP_ORDERED:
8690         case EXEC_OMP_PARALLEL:
8691         case EXEC_OMP_PARALLEL_DO:
8692         case EXEC_OMP_PARALLEL_SECTIONS:
8693         case EXEC_OMP_PARALLEL_WORKSHARE:
8694         case EXEC_OMP_SECTIONS:
8695         case EXEC_OMP_SINGLE:
8696         case EXEC_OMP_TASK:
8697         case EXEC_OMP_TASKWAIT:
8698         case EXEC_OMP_WORKSHARE:
8699           break;
8700
8701         default:
8702           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
8703         }
8704
8705       resolve_code (b->next, ns);
8706     }
8707 }
8708
8709
8710 /* Does everything to resolve an ordinary assignment.  Returns true
8711    if this is an interface assignment.  */
8712 static bool
8713 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
8714 {
8715   bool rval = false;
8716   gfc_expr *lhs;
8717   gfc_expr *rhs;
8718   int llen = 0;
8719   int rlen = 0;
8720   int n;
8721   gfc_ref *ref;
8722
8723   if (gfc_extend_assign (code, ns) == SUCCESS)
8724     {
8725       gfc_expr** rhsptr;
8726
8727       if (code->op == EXEC_ASSIGN_CALL)
8728         {
8729           lhs = code->ext.actual->expr;
8730           rhsptr = &code->ext.actual->next->expr;
8731         }
8732       else
8733         {
8734           gfc_actual_arglist* args;
8735           gfc_typebound_proc* tbp;
8736
8737           gcc_assert (code->op == EXEC_COMPCALL);
8738
8739           args = code->expr1->value.compcall.actual;
8740           lhs = args->expr;
8741           rhsptr = &args->next->expr;
8742
8743           tbp = code->expr1->value.compcall.tbp;
8744           gcc_assert (!tbp->is_generic);
8745         }
8746
8747       /* Make a temporary rhs when there is a default initializer
8748          and rhs is the same symbol as the lhs.  */
8749       if ((*rhsptr)->expr_type == EXPR_VARIABLE
8750             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
8751             && gfc_has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
8752             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
8753         *rhsptr = gfc_get_parentheses (*rhsptr);
8754
8755       return true;
8756     }
8757
8758   lhs = code->expr1;
8759   rhs = code->expr2;
8760
8761   if (rhs->is_boz
8762       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
8763                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
8764                          &code->loc) == FAILURE)
8765     return false;
8766
8767   /* Handle the case of a BOZ literal on the RHS.  */
8768   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
8769     {
8770       int rc;
8771       if (gfc_option.warn_surprising)
8772         gfc_warning ("BOZ literal at %L is bitwise transferred "
8773                      "non-integer symbol '%s'", &code->loc,
8774                      lhs->symtree->n.sym->name);
8775
8776       if (!gfc_convert_boz (rhs, &lhs->ts))
8777         return false;
8778       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
8779         {
8780           if (rc == ARITH_UNDERFLOW)
8781             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
8782                        ". This check can be disabled with the option "
8783                        "-fno-range-check", &rhs->where);
8784           else if (rc == ARITH_OVERFLOW)
8785             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
8786                        ". This check can be disabled with the option "
8787                        "-fno-range-check", &rhs->where);
8788           else if (rc == ARITH_NAN)
8789             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
8790                        ". This check can be disabled with the option "
8791                        "-fno-range-check", &rhs->where);
8792           return false;
8793         }
8794     }
8795
8796   if (lhs->ts.type == BT_CHARACTER
8797         && gfc_option.warn_character_truncation)
8798     {
8799       if (lhs->ts.u.cl != NULL
8800             && lhs->ts.u.cl->length != NULL
8801             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8802         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
8803
8804       if (rhs->expr_type == EXPR_CONSTANT)
8805         rlen = rhs->value.character.length;
8806
8807       else if (rhs->ts.u.cl != NULL
8808                  && rhs->ts.u.cl->length != NULL
8809                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8810         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
8811
8812       if (rlen && llen && rlen > llen)
8813         gfc_warning_now ("CHARACTER expression will be truncated "
8814                          "in assignment (%d/%d) at %L",
8815                          llen, rlen, &code->loc);
8816     }
8817
8818   /* Ensure that a vector index expression for the lvalue is evaluated
8819      to a temporary if the lvalue symbol is referenced in it.  */
8820   if (lhs->rank)
8821     {
8822       for (ref = lhs->ref; ref; ref= ref->next)
8823         if (ref->type == REF_ARRAY)
8824           {
8825             for (n = 0; n < ref->u.ar.dimen; n++)
8826               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
8827                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
8828                                            ref->u.ar.start[n]))
8829                 ref->u.ar.start[n]
8830                         = gfc_get_parentheses (ref->u.ar.start[n]);
8831           }
8832     }
8833
8834   if (gfc_pure (NULL))
8835     {
8836       if (lhs->ts.type == BT_DERIVED
8837             && lhs->expr_type == EXPR_VARIABLE
8838             && lhs->ts.u.derived->attr.pointer_comp
8839             && rhs->expr_type == EXPR_VARIABLE
8840             && (gfc_impure_variable (rhs->symtree->n.sym)
8841                 || gfc_is_coindexed (rhs)))
8842         {
8843           /* F2008, C1283.  */
8844           if (gfc_is_coindexed (rhs))
8845             gfc_error ("Coindexed expression at %L is assigned to "
8846                         "a derived type variable with a POINTER "
8847                         "component in a PURE procedure",
8848                         &rhs->where);
8849           else
8850             gfc_error ("The impure variable at %L is assigned to "
8851                         "a derived type variable with a POINTER "
8852                         "component in a PURE procedure (12.6)",
8853                         &rhs->where);
8854           return rval;
8855         }
8856
8857       /* Fortran 2008, C1283.  */
8858       if (gfc_is_coindexed (lhs))
8859         {
8860           gfc_error ("Assignment to coindexed variable at %L in a PURE "
8861                      "procedure", &rhs->where);
8862           return rval;
8863         }
8864     }
8865
8866   if (gfc_implicit_pure (NULL))
8867     {
8868       if (lhs->expr_type == EXPR_VARIABLE
8869             && lhs->symtree->n.sym != gfc_current_ns->proc_name
8870             && lhs->symtree->n.sym->ns != gfc_current_ns)
8871         gfc_current_ns->proc_name->attr.implicit_pure = 0;
8872
8873       if (lhs->ts.type == BT_DERIVED
8874             && lhs->expr_type == EXPR_VARIABLE
8875             && lhs->ts.u.derived->attr.pointer_comp
8876             && rhs->expr_type == EXPR_VARIABLE
8877             && (gfc_impure_variable (rhs->symtree->n.sym)
8878                 || gfc_is_coindexed (rhs)))
8879         gfc_current_ns->proc_name->attr.implicit_pure = 0;
8880
8881       /* Fortran 2008, C1283.  */
8882       if (gfc_is_coindexed (lhs))
8883         gfc_current_ns->proc_name->attr.implicit_pure = 0;
8884     }
8885
8886   /* F03:7.4.1.2.  */
8887   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
8888      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
8889   if (lhs->ts.type == BT_CLASS)
8890     {
8891       gfc_error ("Variable must not be polymorphic in assignment at %L",
8892                  &lhs->where);
8893       return false;
8894     }
8895
8896   /* F2008, Section 7.2.1.2.  */
8897   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
8898     {
8899       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
8900                  "component in assignment at %L", &lhs->where);
8901       return false;
8902     }
8903
8904   gfc_check_assign (lhs, rhs, 1);
8905   return false;
8906 }
8907
8908
8909 /* Given a block of code, recursively resolve everything pointed to by this
8910    code block.  */
8911
8912 static void
8913 resolve_code (gfc_code *code, gfc_namespace *ns)
8914 {
8915   int omp_workshare_save;
8916   int forall_save;
8917   code_stack frame;
8918   gfc_try t;
8919
8920   frame.prev = cs_base;
8921   frame.head = code;
8922   cs_base = &frame;
8923
8924   find_reachable_labels (code);
8925
8926   for (; code; code = code->next)
8927     {
8928       frame.current = code;
8929       forall_save = forall_flag;
8930
8931       if (code->op == EXEC_FORALL)
8932         {
8933           forall_flag = 1;
8934           gfc_resolve_forall (code, ns, forall_save);
8935           forall_flag = 2;
8936         }
8937       else if (code->block)
8938         {
8939           omp_workshare_save = -1;
8940           switch (code->op)
8941             {
8942             case EXEC_OMP_PARALLEL_WORKSHARE:
8943               omp_workshare_save = omp_workshare_flag;
8944               omp_workshare_flag = 1;
8945               gfc_resolve_omp_parallel_blocks (code, ns);
8946               break;
8947             case EXEC_OMP_PARALLEL:
8948             case EXEC_OMP_PARALLEL_DO:
8949             case EXEC_OMP_PARALLEL_SECTIONS:
8950             case EXEC_OMP_TASK:
8951               omp_workshare_save = omp_workshare_flag;
8952               omp_workshare_flag = 0;
8953               gfc_resolve_omp_parallel_blocks (code, ns);
8954               break;
8955             case EXEC_OMP_DO:
8956               gfc_resolve_omp_do_blocks (code, ns);
8957               break;
8958             case EXEC_SELECT_TYPE:
8959               /* Blocks are handled in resolve_select_type because we have
8960                  to transform the SELECT TYPE into ASSOCIATE first.  */
8961               break;
8962             case EXEC_OMP_WORKSHARE:
8963               omp_workshare_save = omp_workshare_flag;
8964               omp_workshare_flag = 1;
8965               /* FALLTHROUGH */
8966             default:
8967               gfc_resolve_blocks (code->block, ns);
8968               break;
8969             }
8970
8971           if (omp_workshare_save != -1)
8972             omp_workshare_flag = omp_workshare_save;
8973         }
8974
8975       t = SUCCESS;
8976       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
8977         t = gfc_resolve_expr (code->expr1);
8978       forall_flag = forall_save;
8979
8980       if (gfc_resolve_expr (code->expr2) == FAILURE)
8981         t = FAILURE;
8982
8983       if (code->op == EXEC_ALLOCATE
8984           && gfc_resolve_expr (code->expr3) == FAILURE)
8985         t = FAILURE;
8986
8987       switch (code->op)
8988         {
8989         case EXEC_NOP:
8990         case EXEC_END_BLOCK:
8991         case EXEC_CYCLE:
8992         case EXEC_PAUSE:
8993         case EXEC_STOP:
8994         case EXEC_ERROR_STOP:
8995         case EXEC_EXIT:
8996         case EXEC_CONTINUE:
8997         case EXEC_DT_END:
8998         case EXEC_ASSIGN_CALL:
8999         case EXEC_CRITICAL:
9000           break;
9001
9002         case EXEC_SYNC_ALL:
9003         case EXEC_SYNC_IMAGES:
9004         case EXEC_SYNC_MEMORY:
9005           resolve_sync (code);
9006           break;
9007
9008         case EXEC_ENTRY:
9009           /* Keep track of which entry we are up to.  */
9010           current_entry_id = code->ext.entry->id;
9011           break;
9012
9013         case EXEC_WHERE:
9014           resolve_where (code, NULL);
9015           break;
9016
9017         case EXEC_GOTO:
9018           if (code->expr1 != NULL)
9019             {
9020               if (code->expr1->ts.type != BT_INTEGER)
9021                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
9022                            "INTEGER variable", &code->expr1->where);
9023               else if (code->expr1->symtree->n.sym->attr.assign != 1)
9024                 gfc_error ("Variable '%s' has not been assigned a target "
9025                            "label at %L", code->expr1->symtree->n.sym->name,
9026                            &code->expr1->where);
9027             }
9028           else
9029             resolve_branch (code->label1, code);
9030           break;
9031
9032         case EXEC_RETURN:
9033           if (code->expr1 != NULL
9034                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
9035             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
9036                        "INTEGER return specifier", &code->expr1->where);
9037           break;
9038
9039         case EXEC_INIT_ASSIGN:
9040         case EXEC_END_PROCEDURE:
9041           break;
9042
9043         case EXEC_ASSIGN:
9044           if (t == FAILURE)
9045             break;
9046
9047           if (gfc_check_vardef_context (code->expr1, false, _("assignment"))
9048                 == FAILURE)
9049             break;
9050
9051           if (resolve_ordinary_assign (code, ns))
9052             {
9053               if (code->op == EXEC_COMPCALL)
9054                 goto compcall;
9055               else
9056                 goto call;
9057             }
9058           break;
9059
9060         case EXEC_LABEL_ASSIGN:
9061           if (code->label1->defined == ST_LABEL_UNKNOWN)
9062             gfc_error ("Label %d referenced at %L is never defined",
9063                        code->label1->value, &code->label1->where);
9064           if (t == SUCCESS
9065               && (code->expr1->expr_type != EXPR_VARIABLE
9066                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
9067                   || code->expr1->symtree->n.sym->ts.kind
9068                      != gfc_default_integer_kind
9069                   || code->expr1->symtree->n.sym->as != NULL))
9070             gfc_error ("ASSIGN statement at %L requires a scalar "
9071                        "default INTEGER variable", &code->expr1->where);
9072           break;
9073
9074         case EXEC_POINTER_ASSIGN:
9075           {
9076             gfc_expr* e;
9077
9078             if (t == FAILURE)
9079               break;
9080
9081             /* This is both a variable definition and pointer assignment
9082                context, so check both of them.  For rank remapping, a final
9083                array ref may be present on the LHS and fool gfc_expr_attr
9084                used in gfc_check_vardef_context.  Remove it.  */
9085             e = remove_last_array_ref (code->expr1);
9086             t = gfc_check_vardef_context (e, true, _("pointer assignment"));
9087             if (t == SUCCESS)
9088               t = gfc_check_vardef_context (e, false, _("pointer assignment"));
9089             gfc_free_expr (e);
9090             if (t == FAILURE)
9091               break;
9092
9093             gfc_check_pointer_assign (code->expr1, code->expr2);
9094             break;
9095           }
9096
9097         case EXEC_ARITHMETIC_IF:
9098           if (t == SUCCESS
9099               && code->expr1->ts.type != BT_INTEGER
9100               && code->expr1->ts.type != BT_REAL)
9101             gfc_error ("Arithmetic IF statement at %L requires a numeric "
9102                        "expression", &code->expr1->where);
9103
9104           resolve_branch (code->label1, code);
9105           resolve_branch (code->label2, code);
9106           resolve_branch (code->label3, code);
9107           break;
9108
9109         case EXEC_IF:
9110           if (t == SUCCESS && code->expr1 != NULL
9111               && (code->expr1->ts.type != BT_LOGICAL
9112                   || code->expr1->rank != 0))
9113             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
9114                        &code->expr1->where);
9115           break;
9116
9117         case EXEC_CALL:
9118         call:
9119           resolve_call (code);
9120           break;
9121
9122         case EXEC_COMPCALL:
9123         compcall:
9124           resolve_typebound_subroutine (code);
9125           break;
9126
9127         case EXEC_CALL_PPC:
9128           resolve_ppc_call (code);
9129           break;
9130
9131         case EXEC_SELECT:
9132           /* Select is complicated. Also, a SELECT construct could be
9133              a transformed computed GOTO.  */
9134           resolve_select (code);
9135           break;
9136
9137         case EXEC_SELECT_TYPE:
9138           resolve_select_type (code, ns);
9139           break;
9140
9141         case EXEC_BLOCK:
9142           resolve_block_construct (code);
9143           break;
9144
9145         case EXEC_DO:
9146           if (code->ext.iterator != NULL)
9147             {
9148               gfc_iterator *iter = code->ext.iterator;
9149               if (gfc_resolve_iterator (iter, true) != FAILURE)
9150                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
9151             }
9152           break;
9153
9154         case EXEC_DO_WHILE:
9155           if (code->expr1 == NULL)
9156             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
9157           if (t == SUCCESS
9158               && (code->expr1->rank != 0
9159                   || code->expr1->ts.type != BT_LOGICAL))
9160             gfc_error ("Exit condition of DO WHILE loop at %L must be "
9161                        "a scalar LOGICAL expression", &code->expr1->where);
9162           break;
9163
9164         case EXEC_ALLOCATE:
9165           if (t == SUCCESS)
9166             resolve_allocate_deallocate (code, "ALLOCATE");
9167
9168           break;
9169
9170         case EXEC_DEALLOCATE:
9171           if (t == SUCCESS)
9172             resolve_allocate_deallocate (code, "DEALLOCATE");
9173
9174           break;
9175
9176         case EXEC_OPEN:
9177           if (gfc_resolve_open (code->ext.open) == FAILURE)
9178             break;
9179
9180           resolve_branch (code->ext.open->err, code);
9181           break;
9182
9183         case EXEC_CLOSE:
9184           if (gfc_resolve_close (code->ext.close) == FAILURE)
9185             break;
9186
9187           resolve_branch (code->ext.close->err, code);
9188           break;
9189
9190         case EXEC_BACKSPACE:
9191         case EXEC_ENDFILE:
9192         case EXEC_REWIND:
9193         case EXEC_FLUSH:
9194           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
9195             break;
9196
9197           resolve_branch (code->ext.filepos->err, code);
9198           break;
9199
9200         case EXEC_INQUIRE:
9201           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9202               break;
9203
9204           resolve_branch (code->ext.inquire->err, code);
9205           break;
9206
9207         case EXEC_IOLENGTH:
9208           gcc_assert (code->ext.inquire != NULL);
9209           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9210             break;
9211
9212           resolve_branch (code->ext.inquire->err, code);
9213           break;
9214
9215         case EXEC_WAIT:
9216           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
9217             break;
9218
9219           resolve_branch (code->ext.wait->err, code);
9220           resolve_branch (code->ext.wait->end, code);
9221           resolve_branch (code->ext.wait->eor, code);
9222           break;
9223
9224         case EXEC_READ:
9225         case EXEC_WRITE:
9226           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
9227             break;
9228
9229           resolve_branch (code->ext.dt->err, code);
9230           resolve_branch (code->ext.dt->end, code);
9231           resolve_branch (code->ext.dt->eor, code);
9232           break;
9233
9234         case EXEC_TRANSFER:
9235           resolve_transfer (code);
9236           break;
9237
9238         case EXEC_FORALL:
9239           resolve_forall_iterators (code->ext.forall_iterator);
9240
9241           if (code->expr1 != NULL
9242               && (code->expr1->ts.type != BT_LOGICAL || code->expr1->rank))
9243             gfc_error ("FORALL mask clause at %L requires a scalar LOGICAL "
9244                        "expression", &code->expr1->where);
9245           break;
9246
9247         case EXEC_OMP_ATOMIC:
9248         case EXEC_OMP_BARRIER:
9249         case EXEC_OMP_CRITICAL:
9250         case EXEC_OMP_FLUSH:
9251         case EXEC_OMP_DO:
9252         case EXEC_OMP_MASTER:
9253         case EXEC_OMP_ORDERED:
9254         case EXEC_OMP_SECTIONS:
9255         case EXEC_OMP_SINGLE:
9256         case EXEC_OMP_TASKWAIT:
9257         case EXEC_OMP_WORKSHARE:
9258           gfc_resolve_omp_directive (code, ns);
9259           break;
9260
9261         case EXEC_OMP_PARALLEL:
9262         case EXEC_OMP_PARALLEL_DO:
9263         case EXEC_OMP_PARALLEL_SECTIONS:
9264         case EXEC_OMP_PARALLEL_WORKSHARE:
9265         case EXEC_OMP_TASK:
9266           omp_workshare_save = omp_workshare_flag;
9267           omp_workshare_flag = 0;
9268           gfc_resolve_omp_directive (code, ns);
9269           omp_workshare_flag = omp_workshare_save;
9270           break;
9271
9272         default:
9273           gfc_internal_error ("resolve_code(): Bad statement code");
9274         }
9275     }
9276
9277   cs_base = frame.prev;
9278 }
9279
9280
9281 /* Resolve initial values and make sure they are compatible with
9282    the variable.  */
9283
9284 static void
9285 resolve_values (gfc_symbol *sym)
9286 {
9287   gfc_try t;
9288
9289   if (sym->value == NULL)
9290     return;
9291
9292   if (sym->value->expr_type == EXPR_STRUCTURE)
9293     t= resolve_structure_cons (sym->value, 1);
9294   else 
9295     t = gfc_resolve_expr (sym->value);
9296
9297   if (t == FAILURE)
9298     return;
9299
9300   gfc_check_assign_symbol (sym, sym->value);
9301 }
9302
9303
9304 /* Verify the binding labels for common blocks that are BIND(C).  The label
9305    for a BIND(C) common block must be identical in all scoping units in which
9306    the common block is declared.  Further, the binding label can not collide
9307    with any other global entity in the program.  */
9308
9309 static void
9310 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
9311 {
9312   if (comm_block_tree->n.common->is_bind_c == 1)
9313     {
9314       gfc_gsymbol *binding_label_gsym;
9315       gfc_gsymbol *comm_name_gsym;
9316
9317       /* See if a global symbol exists by the common block's name.  It may
9318          be NULL if the common block is use-associated.  */
9319       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
9320                                          comm_block_tree->n.common->name);
9321       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
9322         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
9323                    "with the global entity '%s' at %L",
9324                    comm_block_tree->n.common->binding_label,
9325                    comm_block_tree->n.common->name,
9326                    &(comm_block_tree->n.common->where),
9327                    comm_name_gsym->name, &(comm_name_gsym->where));
9328       else if (comm_name_gsym != NULL
9329                && strcmp (comm_name_gsym->name,
9330                           comm_block_tree->n.common->name) == 0)
9331         {
9332           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
9333              as expected.  */
9334           if (comm_name_gsym->binding_label == NULL)
9335             /* No binding label for common block stored yet; save this one.  */
9336             comm_name_gsym->binding_label =
9337               comm_block_tree->n.common->binding_label;
9338           else
9339             if (strcmp (comm_name_gsym->binding_label,
9340                         comm_block_tree->n.common->binding_label) != 0)
9341               {
9342                 /* Common block names match but binding labels do not.  */
9343                 gfc_error ("Binding label '%s' for common block '%s' at %L "
9344                            "does not match the binding label '%s' for common "
9345                            "block '%s' at %L",
9346                            comm_block_tree->n.common->binding_label,
9347                            comm_block_tree->n.common->name,
9348                            &(comm_block_tree->n.common->where),
9349                            comm_name_gsym->binding_label,
9350                            comm_name_gsym->name,
9351                            &(comm_name_gsym->where));
9352                 return;
9353               }
9354         }
9355
9356       /* There is no binding label (NAME="") so we have nothing further to
9357          check and nothing to add as a global symbol for the label.  */
9358       if (comm_block_tree->n.common->binding_label[0] == '\0' )
9359         return;
9360       
9361       binding_label_gsym =
9362         gfc_find_gsymbol (gfc_gsym_root,
9363                           comm_block_tree->n.common->binding_label);
9364       if (binding_label_gsym == NULL)
9365         {
9366           /* Need to make a global symbol for the binding label to prevent
9367              it from colliding with another.  */
9368           binding_label_gsym =
9369             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
9370           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
9371           binding_label_gsym->type = GSYM_COMMON;
9372         }
9373       else
9374         {
9375           /* If comm_name_gsym is NULL, the name common block is use
9376              associated and the name could be colliding.  */
9377           if (binding_label_gsym->type != GSYM_COMMON)
9378             gfc_error ("Binding label '%s' for common block '%s' at %L "
9379                        "collides with the global entity '%s' at %L",
9380                        comm_block_tree->n.common->binding_label,
9381                        comm_block_tree->n.common->name,
9382                        &(comm_block_tree->n.common->where),
9383                        binding_label_gsym->name,
9384                        &(binding_label_gsym->where));
9385           else if (comm_name_gsym != NULL
9386                    && (strcmp (binding_label_gsym->name,
9387                                comm_name_gsym->binding_label) != 0)
9388                    && (strcmp (binding_label_gsym->sym_name,
9389                                comm_name_gsym->name) != 0))
9390             gfc_error ("Binding label '%s' for common block '%s' at %L "
9391                        "collides with global entity '%s' at %L",
9392                        binding_label_gsym->name, binding_label_gsym->sym_name,
9393                        &(comm_block_tree->n.common->where),
9394                        comm_name_gsym->name, &(comm_name_gsym->where));
9395         }
9396     }
9397   
9398   return;
9399 }
9400
9401
9402 /* Verify any BIND(C) derived types in the namespace so we can report errors
9403    for them once, rather than for each variable declared of that type.  */
9404
9405 static void
9406 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
9407 {
9408   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
9409       && derived_sym->attr.is_bind_c == 1)
9410     verify_bind_c_derived_type (derived_sym);
9411   
9412   return;
9413 }
9414
9415
9416 /* Verify that any binding labels used in a given namespace do not collide 
9417    with the names or binding labels of any global symbols.  */
9418
9419 static void
9420 gfc_verify_binding_labels (gfc_symbol *sym)
9421 {
9422   int has_error = 0;
9423   
9424   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
9425       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
9426     {
9427       gfc_gsymbol *bind_c_sym;
9428
9429       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
9430       if (bind_c_sym != NULL 
9431           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
9432         {
9433           if (sym->attr.if_source == IFSRC_DECL 
9434               && (bind_c_sym->type != GSYM_SUBROUTINE 
9435                   && bind_c_sym->type != GSYM_FUNCTION) 
9436               && ((sym->attr.contained == 1 
9437                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
9438                   || (sym->attr.use_assoc == 1 
9439                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
9440             {
9441               /* Make sure global procedures don't collide with anything.  */
9442               gfc_error ("Binding label '%s' at %L collides with the global "
9443                          "entity '%s' at %L", sym->binding_label,
9444                          &(sym->declared_at), bind_c_sym->name,
9445                          &(bind_c_sym->where));
9446               has_error = 1;
9447             }
9448           else if (sym->attr.contained == 0 
9449                    && (sym->attr.if_source == IFSRC_IFBODY 
9450                        && sym->attr.flavor == FL_PROCEDURE) 
9451                    && (bind_c_sym->sym_name != NULL 
9452                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
9453             {
9454               /* Make sure procedures in interface bodies don't collide.  */
9455               gfc_error ("Binding label '%s' in interface body at %L collides "
9456                          "with the global entity '%s' at %L",
9457                          sym->binding_label,
9458                          &(sym->declared_at), bind_c_sym->name,
9459                          &(bind_c_sym->where));
9460               has_error = 1;
9461             }
9462           else if (sym->attr.contained == 0 
9463                    && sym->attr.if_source == IFSRC_UNKNOWN)
9464             if ((sym->attr.use_assoc && bind_c_sym->mod_name
9465                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
9466                 || sym->attr.use_assoc == 0)
9467               {
9468                 gfc_error ("Binding label '%s' at %L collides with global "
9469                            "entity '%s' at %L", sym->binding_label,
9470                            &(sym->declared_at), bind_c_sym->name,
9471                            &(bind_c_sym->where));
9472                 has_error = 1;
9473               }
9474
9475           if (has_error != 0)
9476             /* Clear the binding label to prevent checking multiple times.  */
9477             sym->binding_label[0] = '\0';
9478         }
9479       else if (bind_c_sym == NULL)
9480         {
9481           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
9482           bind_c_sym->where = sym->declared_at;
9483           bind_c_sym->sym_name = sym->name;
9484
9485           if (sym->attr.use_assoc == 1)
9486             bind_c_sym->mod_name = sym->module;
9487           else
9488             if (sym->ns->proc_name != NULL)
9489               bind_c_sym->mod_name = sym->ns->proc_name->name;
9490
9491           if (sym->attr.contained == 0)
9492             {
9493               if (sym->attr.subroutine)
9494                 bind_c_sym->type = GSYM_SUBROUTINE;
9495               else if (sym->attr.function)
9496                 bind_c_sym->type = GSYM_FUNCTION;
9497             }
9498         }
9499     }
9500   return;
9501 }
9502
9503
9504 /* Resolve an index expression.  */
9505
9506 static gfc_try
9507 resolve_index_expr (gfc_expr *e)
9508 {
9509   if (gfc_resolve_expr (e) == FAILURE)
9510     return FAILURE;
9511
9512   if (gfc_simplify_expr (e, 0) == FAILURE)
9513     return FAILURE;
9514
9515   if (gfc_specification_expr (e) == FAILURE)
9516     return FAILURE;
9517
9518   return SUCCESS;
9519 }
9520
9521
9522 /* Resolve a charlen structure.  */
9523
9524 static gfc_try
9525 resolve_charlen (gfc_charlen *cl)
9526 {
9527   int i, k;
9528
9529   if (cl->resolved)
9530     return SUCCESS;
9531
9532   cl->resolved = 1;
9533
9534   specification_expr = 1;
9535
9536   if (resolve_index_expr (cl->length) == FAILURE)
9537     {
9538       specification_expr = 0;
9539       return FAILURE;
9540     }
9541
9542   /* "If the character length parameter value evaluates to a negative
9543      value, the length of character entities declared is zero."  */
9544   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
9545     {
9546       if (gfc_option.warn_surprising)
9547         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
9548                          " the length has been set to zero",
9549                          &cl->length->where, i);
9550       gfc_replace_expr (cl->length,
9551                         gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
9552     }
9553
9554   /* Check that the character length is not too large.  */
9555   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
9556   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
9557       && cl->length->ts.type == BT_INTEGER
9558       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
9559     {
9560       gfc_error ("String length at %L is too large", &cl->length->where);
9561       return FAILURE;
9562     }
9563
9564   return SUCCESS;
9565 }
9566
9567
9568 /* Test for non-constant shape arrays.  */
9569
9570 static bool
9571 is_non_constant_shape_array (gfc_symbol *sym)
9572 {
9573   gfc_expr *e;
9574   int i;
9575   bool not_constant;
9576
9577   not_constant = false;
9578   if (sym->as != NULL)
9579     {
9580       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
9581          has not been simplified; parameter array references.  Do the
9582          simplification now.  */
9583       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
9584         {
9585           e = sym->as->lower[i];
9586           if (e && (resolve_index_expr (e) == FAILURE
9587                     || !gfc_is_constant_expr (e)))
9588             not_constant = true;
9589           e = sym->as->upper[i];
9590           if (e && (resolve_index_expr (e) == FAILURE
9591                     || !gfc_is_constant_expr (e)))
9592             not_constant = true;
9593         }
9594     }
9595   return not_constant;
9596 }
9597
9598 /* Given a symbol and an initialization expression, add code to initialize
9599    the symbol to the function entry.  */
9600 static void
9601 build_init_assign (gfc_symbol *sym, gfc_expr *init)
9602 {
9603   gfc_expr *lval;
9604   gfc_code *init_st;
9605   gfc_namespace *ns = sym->ns;
9606
9607   /* Search for the function namespace if this is a contained
9608      function without an explicit result.  */
9609   if (sym->attr.function && sym == sym->result
9610       && sym->name != sym->ns->proc_name->name)
9611     {
9612       ns = ns->contained;
9613       for (;ns; ns = ns->sibling)
9614         if (strcmp (ns->proc_name->name, sym->name) == 0)
9615           break;
9616     }
9617
9618   if (ns == NULL)
9619     {
9620       gfc_free_expr (init);
9621       return;
9622     }
9623
9624   /* Build an l-value expression for the result.  */
9625   lval = gfc_lval_expr_from_sym (sym);
9626
9627   /* Add the code at scope entry.  */
9628   init_st = gfc_get_code ();
9629   init_st->next = ns->code;
9630   ns->code = init_st;
9631
9632   /* Assign the default initializer to the l-value.  */
9633   init_st->loc = sym->declared_at;
9634   init_st->op = EXEC_INIT_ASSIGN;
9635   init_st->expr1 = lval;
9636   init_st->expr2 = init;
9637 }
9638
9639 /* Assign the default initializer to a derived type variable or result.  */
9640
9641 static void
9642 apply_default_init (gfc_symbol *sym)
9643 {
9644   gfc_expr *init = NULL;
9645
9646   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9647     return;
9648
9649   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
9650     init = gfc_default_initializer (&sym->ts);
9651
9652   if (init == NULL && sym->ts.type != BT_CLASS)
9653     return;
9654
9655   build_init_assign (sym, init);
9656   sym->attr.referenced = 1;
9657 }
9658
9659 /* Build an initializer for a local integer, real, complex, logical, or
9660    character variable, based on the command line flags finit-local-zero,
9661    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
9662    null if the symbol should not have a default initialization.  */
9663 static gfc_expr *
9664 build_default_init_expr (gfc_symbol *sym)
9665 {
9666   int char_len;
9667   gfc_expr *init_expr;
9668   int i;
9669
9670   /* These symbols should never have a default initialization.  */
9671   if ((sym->attr.dimension && !gfc_is_compile_time_shape (sym->as))
9672       || sym->attr.external
9673       || sym->attr.dummy
9674       || sym->attr.pointer
9675       || sym->attr.in_equivalence
9676       || sym->attr.in_common
9677       || sym->attr.data
9678       || sym->module
9679       || sym->attr.cray_pointee
9680       || sym->attr.cray_pointer)
9681     return NULL;
9682
9683   /* Now we'll try to build an initializer expression.  */
9684   init_expr = gfc_get_constant_expr (sym->ts.type, sym->ts.kind,
9685                                      &sym->declared_at);
9686
9687   /* We will only initialize integers, reals, complex, logicals, and
9688      characters, and only if the corresponding command-line flags
9689      were set.  Otherwise, we free init_expr and return null.  */
9690   switch (sym->ts.type)
9691     {    
9692     case BT_INTEGER:
9693       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
9694         mpz_set_si (init_expr->value.integer, 
9695                          gfc_option.flag_init_integer_value);
9696       else
9697         {
9698           gfc_free_expr (init_expr);
9699           init_expr = NULL;
9700         }
9701       break;
9702
9703     case BT_REAL:
9704       switch (gfc_option.flag_init_real)
9705         {
9706         case GFC_INIT_REAL_SNAN:
9707           init_expr->is_snan = 1;
9708           /* Fall through.  */
9709         case GFC_INIT_REAL_NAN:
9710           mpfr_set_nan (init_expr->value.real);
9711           break;
9712
9713         case GFC_INIT_REAL_INF:
9714           mpfr_set_inf (init_expr->value.real, 1);
9715           break;
9716
9717         case GFC_INIT_REAL_NEG_INF:
9718           mpfr_set_inf (init_expr->value.real, -1);
9719           break;
9720
9721         case GFC_INIT_REAL_ZERO:
9722           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
9723           break;
9724
9725         default:
9726           gfc_free_expr (init_expr);
9727           init_expr = NULL;
9728           break;
9729         }
9730       break;
9731           
9732     case BT_COMPLEX:
9733       switch (gfc_option.flag_init_real)
9734         {
9735         case GFC_INIT_REAL_SNAN:
9736           init_expr->is_snan = 1;
9737           /* Fall through.  */
9738         case GFC_INIT_REAL_NAN:
9739           mpfr_set_nan (mpc_realref (init_expr->value.complex));
9740           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
9741           break;
9742
9743         case GFC_INIT_REAL_INF:
9744           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
9745           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
9746           break;
9747
9748         case GFC_INIT_REAL_NEG_INF:
9749           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
9750           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
9751           break;
9752
9753         case GFC_INIT_REAL_ZERO:
9754           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
9755           break;
9756
9757         default:
9758           gfc_free_expr (init_expr);
9759           init_expr = NULL;
9760           break;
9761         }
9762       break;
9763           
9764     case BT_LOGICAL:
9765       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
9766         init_expr->value.logical = 0;
9767       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
9768         init_expr->value.logical = 1;
9769       else
9770         {
9771           gfc_free_expr (init_expr);
9772           init_expr = NULL;
9773         }
9774       break;
9775           
9776     case BT_CHARACTER:
9777       /* For characters, the length must be constant in order to 
9778          create a default initializer.  */
9779       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
9780           && sym->ts.u.cl->length
9781           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9782         {
9783           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
9784           init_expr->value.character.length = char_len;
9785           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
9786           for (i = 0; i < char_len; i++)
9787             init_expr->value.character.string[i]
9788               = (unsigned char) gfc_option.flag_init_character_value;
9789         }
9790       else
9791         {
9792           gfc_free_expr (init_expr);
9793           init_expr = NULL;
9794         }
9795       break;
9796           
9797     default:
9798      gfc_free_expr (init_expr);
9799      init_expr = NULL;
9800     }
9801   return init_expr;
9802 }
9803
9804 /* Add an initialization expression to a local variable.  */
9805 static void
9806 apply_default_init_local (gfc_symbol *sym)
9807 {
9808   gfc_expr *init = NULL;
9809
9810   /* The symbol should be a variable or a function return value.  */
9811   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9812       || (sym->attr.function && sym->result != sym))
9813     return;
9814
9815   /* Try to build the initializer expression.  If we can't initialize
9816      this symbol, then init will be NULL.  */
9817   init = build_default_init_expr (sym);
9818   if (init == NULL)
9819     return;
9820
9821   /* For saved variables, we don't want to add an initializer at 
9822      function entry, so we just add a static initializer.  */
9823   if (sym->attr.save || sym->ns->save_all 
9824       || gfc_option.flag_max_stack_var_size == 0)
9825     {
9826       /* Don't clobber an existing initializer!  */
9827       gcc_assert (sym->value == NULL);
9828       sym->value = init;
9829       return;
9830     }
9831
9832   build_init_assign (sym, init);
9833 }
9834
9835
9836 /* Resolution of common features of flavors variable and procedure.  */
9837
9838 static gfc_try
9839 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
9840 {
9841   /* Constraints on deferred shape variable.  */
9842   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
9843     {
9844       if (sym->attr.allocatable)
9845         {
9846           if (sym->attr.dimension)
9847             {
9848               gfc_error ("Allocatable array '%s' at %L must have "
9849                          "a deferred shape", sym->name, &sym->declared_at);
9850               return FAILURE;
9851             }
9852           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
9853                                    "may not be ALLOCATABLE", sym->name,
9854                                    &sym->declared_at) == FAILURE)
9855             return FAILURE;
9856         }
9857
9858       if (sym->attr.pointer && sym->attr.dimension)
9859         {
9860           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
9861                      sym->name, &sym->declared_at);
9862           return FAILURE;
9863         }
9864     }
9865   else
9866     {
9867       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
9868           && !sym->attr.dummy && sym->ts.type != BT_CLASS && !sym->assoc)
9869         {
9870           gfc_error ("Array '%s' at %L cannot have a deferred shape",
9871                      sym->name, &sym->declared_at);
9872           return FAILURE;
9873          }
9874     }
9875
9876   /* Constraints on polymorphic variables.  */
9877   if (sym->ts.type == BT_CLASS && !(sym->result && sym->result != sym))
9878     {
9879       /* F03:C502.  */
9880       if (sym->attr.class_ok
9881           && !gfc_type_is_extensible (CLASS_DATA (sym)->ts.u.derived))
9882         {
9883           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
9884                      CLASS_DATA (sym)->ts.u.derived->name, sym->name,
9885                      &sym->declared_at);
9886           return FAILURE;
9887         }
9888
9889       /* F03:C509.  */
9890       /* Assume that use associated symbols were checked in the module ns.
9891          Class-variables that are associate-names are also something special
9892          and excepted from the test.  */
9893       if (!sym->attr.class_ok && !sym->attr.use_assoc && !sym->assoc)
9894         {
9895           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
9896                      "or pointer", sym->name, &sym->declared_at);
9897           return FAILURE;
9898         }
9899     }
9900     
9901   return SUCCESS;
9902 }
9903
9904
9905 /* Additional checks for symbols with flavor variable and derived
9906    type.  To be called from resolve_fl_variable.  */
9907
9908 static gfc_try
9909 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
9910 {
9911   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
9912
9913   /* Check to see if a derived type is blocked from being host
9914      associated by the presence of another class I symbol in the same
9915      namespace.  14.6.1.3 of the standard and the discussion on
9916      comp.lang.fortran.  */
9917   if (sym->ns != sym->ts.u.derived->ns
9918       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
9919     {
9920       gfc_symbol *s;
9921       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
9922       if (s && s->attr.flavor != FL_DERIVED)
9923         {
9924           gfc_error ("The type '%s' cannot be host associated at %L "
9925                      "because it is blocked by an incompatible object "
9926                      "of the same name declared at %L",
9927                      sym->ts.u.derived->name, &sym->declared_at,
9928                      &s->declared_at);
9929           return FAILURE;
9930         }
9931     }
9932
9933   /* 4th constraint in section 11.3: "If an object of a type for which
9934      component-initialization is specified (R429) appears in the
9935      specification-part of a module and does not have the ALLOCATABLE
9936      or POINTER attribute, the object shall have the SAVE attribute."
9937
9938      The check for initializers is performed with
9939      gfc_has_default_initializer because gfc_default_initializer generates
9940      a hidden default for allocatable components.  */
9941   if (!(sym->value || no_init_flag) && sym->ns->proc_name
9942       && sym->ns->proc_name->attr.flavor == FL_MODULE
9943       && !sym->ns->save_all && !sym->attr.save
9944       && !sym->attr.pointer && !sym->attr.allocatable
9945       && gfc_has_default_initializer (sym->ts.u.derived)
9946       && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Implied SAVE for "
9947                          "module variable '%s' at %L, needed due to "
9948                          "the default initialization", sym->name,
9949                          &sym->declared_at) == FAILURE)
9950     return FAILURE;
9951
9952   /* Assign default initializer.  */
9953   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
9954       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
9955     {
9956       sym->value = gfc_default_initializer (&sym->ts);
9957     }
9958
9959   return SUCCESS;
9960 }
9961
9962
9963 /* Resolve symbols with flavor variable.  */
9964
9965 static gfc_try
9966 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
9967 {
9968   int no_init_flag, automatic_flag;
9969   gfc_expr *e;
9970   const char *auto_save_msg;
9971
9972   auto_save_msg = "Automatic object '%s' at %L cannot have the "
9973                   "SAVE attribute";
9974
9975   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9976     return FAILURE;
9977
9978   /* Set this flag to check that variables are parameters of all entries.
9979      This check is effected by the call to gfc_resolve_expr through
9980      is_non_constant_shape_array.  */
9981   specification_expr = 1;
9982
9983   if (sym->ns->proc_name
9984       && (sym->ns->proc_name->attr.flavor == FL_MODULE
9985           || sym->ns->proc_name->attr.is_main_program)
9986       && !sym->attr.use_assoc
9987       && !sym->attr.allocatable
9988       && !sym->attr.pointer
9989       && is_non_constant_shape_array (sym))
9990     {
9991       /* The shape of a main program or module array needs to be
9992          constant.  */
9993       gfc_error ("The module or main program array '%s' at %L must "
9994                  "have constant shape", sym->name, &sym->declared_at);
9995       specification_expr = 0;
9996       return FAILURE;
9997     }
9998
9999   /* Constraints on deferred type parameter.  */
10000   if (sym->ts.deferred && !(sym->attr.pointer || sym->attr.allocatable))
10001     {
10002       gfc_error ("Entity '%s' at %L has a deferred type parameter and "
10003                  "requires either the pointer or allocatable attribute",
10004                      sym->name, &sym->declared_at);
10005       return FAILURE;
10006     }
10007
10008   if (sym->ts.type == BT_CHARACTER)
10009     {
10010       /* Make sure that character string variables with assumed length are
10011          dummy arguments.  */
10012       e = sym->ts.u.cl->length;
10013       if (e == NULL && !sym->attr.dummy && !sym->attr.result
10014           && !sym->ts.deferred)
10015         {
10016           gfc_error ("Entity with assumed character length at %L must be a "
10017                      "dummy argument or a PARAMETER", &sym->declared_at);
10018           return FAILURE;
10019         }
10020
10021       if (e && sym->attr.save == SAVE_EXPLICIT && !gfc_is_constant_expr (e))
10022         {
10023           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10024           return FAILURE;
10025         }
10026
10027       if (!gfc_is_constant_expr (e)
10028           && !(e->expr_type == EXPR_VARIABLE
10029                && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
10030           && sym->ns->proc_name
10031           && (sym->ns->proc_name->attr.flavor == FL_MODULE
10032               || sym->ns->proc_name->attr.is_main_program)
10033           && !sym->attr.use_assoc)
10034         {
10035           gfc_error ("'%s' at %L must have constant character length "
10036                      "in this context", sym->name, &sym->declared_at);
10037           return FAILURE;
10038         }
10039     }
10040
10041   if (sym->value == NULL && sym->attr.referenced)
10042     apply_default_init_local (sym); /* Try to apply a default initialization.  */
10043
10044   /* Determine if the symbol may not have an initializer.  */
10045   no_init_flag = automatic_flag = 0;
10046   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
10047       || sym->attr.intrinsic || sym->attr.result)
10048     no_init_flag = 1;
10049   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
10050            && is_non_constant_shape_array (sym))
10051     {
10052       no_init_flag = automatic_flag = 1;
10053
10054       /* Also, they must not have the SAVE attribute.
10055          SAVE_IMPLICIT is checked below.  */
10056       if (sym->attr.save == SAVE_EXPLICIT)
10057         {
10058           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10059           return FAILURE;
10060         }
10061     }
10062
10063   /* Ensure that any initializer is simplified.  */
10064   if (sym->value)
10065     gfc_simplify_expr (sym->value, 1);
10066
10067   /* Reject illegal initializers.  */
10068   if (!sym->mark && sym->value)
10069     {
10070       if (sym->attr.allocatable)
10071         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
10072                    sym->name, &sym->declared_at);
10073       else if (sym->attr.external)
10074         gfc_error ("External '%s' at %L cannot have an initializer",
10075                    sym->name, &sym->declared_at);
10076       else if (sym->attr.dummy
10077         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
10078         gfc_error ("Dummy '%s' at %L cannot have an initializer",
10079                    sym->name, &sym->declared_at);
10080       else if (sym->attr.intrinsic)
10081         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
10082                    sym->name, &sym->declared_at);
10083       else if (sym->attr.result)
10084         gfc_error ("Function result '%s' at %L cannot have an initializer",
10085                    sym->name, &sym->declared_at);
10086       else if (automatic_flag)
10087         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
10088                    sym->name, &sym->declared_at);
10089       else
10090         goto no_init_error;
10091       return FAILURE;
10092     }
10093
10094 no_init_error:
10095   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
10096     return resolve_fl_variable_derived (sym, no_init_flag);
10097
10098   return SUCCESS;
10099 }
10100
10101
10102 /* Resolve a procedure.  */
10103
10104 static gfc_try
10105 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
10106 {
10107   gfc_formal_arglist *arg;
10108
10109   if (sym->attr.function
10110       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
10111     return FAILURE;
10112
10113   if (sym->ts.type == BT_CHARACTER)
10114     {
10115       gfc_charlen *cl = sym->ts.u.cl;
10116
10117       if (cl && cl->length && gfc_is_constant_expr (cl->length)
10118              && resolve_charlen (cl) == FAILURE)
10119         return FAILURE;
10120
10121       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
10122           && sym->attr.proc == PROC_ST_FUNCTION)
10123         {
10124           gfc_error ("Character-valued statement function '%s' at %L must "
10125                      "have constant length", sym->name, &sym->declared_at);
10126           return FAILURE;
10127         }
10128     }
10129
10130   /* Ensure that derived type for are not of a private type.  Internal
10131      module procedures are excluded by 2.2.3.3 - i.e., they are not
10132      externally accessible and can access all the objects accessible in
10133      the host.  */
10134   if (!(sym->ns->parent
10135         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
10136       && gfc_check_access(sym->attr.access, sym->ns->default_access))
10137     {
10138       gfc_interface *iface;
10139
10140       for (arg = sym->formal; arg; arg = arg->next)
10141         {
10142           if (arg->sym
10143               && arg->sym->ts.type == BT_DERIVED
10144               && !arg->sym->ts.u.derived->attr.use_assoc
10145               && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
10146                                     arg->sym->ts.u.derived->ns->default_access)
10147               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
10148                                  "PRIVATE type and cannot be a dummy argument"
10149                                  " of '%s', which is PUBLIC at %L",
10150                                  arg->sym->name, sym->name, &sym->declared_at)
10151                  == FAILURE)
10152             {
10153               /* Stop this message from recurring.  */
10154               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10155               return FAILURE;
10156             }
10157         }
10158
10159       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10160          PRIVATE to the containing module.  */
10161       for (iface = sym->generic; iface; iface = iface->next)
10162         {
10163           for (arg = iface->sym->formal; arg; arg = arg->next)
10164             {
10165               if (arg->sym
10166                   && arg->sym->ts.type == BT_DERIVED
10167                   && !arg->sym->ts.u.derived->attr.use_assoc
10168                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
10169                                         arg->sym->ts.u.derived->ns->default_access)
10170                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10171                                      "'%s' in PUBLIC interface '%s' at %L "
10172                                      "takes dummy arguments of '%s' which is "
10173                                      "PRIVATE", iface->sym->name, sym->name,
10174                                      &iface->sym->declared_at,
10175                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10176                 {
10177                   /* Stop this message from recurring.  */
10178                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10179                   return FAILURE;
10180                 }
10181              }
10182         }
10183
10184       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10185          PRIVATE to the containing module.  */
10186       for (iface = sym->generic; iface; iface = iface->next)
10187         {
10188           for (arg = iface->sym->formal; arg; arg = arg->next)
10189             {
10190               if (arg->sym
10191                   && arg->sym->ts.type == BT_DERIVED
10192                   && !arg->sym->ts.u.derived->attr.use_assoc
10193                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
10194                                         arg->sym->ts.u.derived->ns->default_access)
10195                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10196                                      "'%s' in PUBLIC interface '%s' at %L "
10197                                      "takes dummy arguments of '%s' which is "
10198                                      "PRIVATE", iface->sym->name, sym->name,
10199                                      &iface->sym->declared_at,
10200                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10201                 {
10202                   /* Stop this message from recurring.  */
10203                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10204                   return FAILURE;
10205                 }
10206              }
10207         }
10208     }
10209
10210   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
10211       && !sym->attr.proc_pointer)
10212     {
10213       gfc_error ("Function '%s' at %L cannot have an initializer",
10214                  sym->name, &sym->declared_at);
10215       return FAILURE;
10216     }
10217
10218   /* An external symbol may not have an initializer because it is taken to be
10219      a procedure. Exception: Procedure Pointers.  */
10220   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
10221     {
10222       gfc_error ("External object '%s' at %L may not have an initializer",
10223                  sym->name, &sym->declared_at);
10224       return FAILURE;
10225     }
10226
10227   /* An elemental function is required to return a scalar 12.7.1  */
10228   if (sym->attr.elemental && sym->attr.function && sym->as)
10229     {
10230       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
10231                  "result", sym->name, &sym->declared_at);
10232       /* Reset so that the error only occurs once.  */
10233       sym->attr.elemental = 0;
10234       return FAILURE;
10235     }
10236
10237   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
10238      char-len-param shall not be array-valued, pointer-valued, recursive
10239      or pure.  ....snip... A character value of * may only be used in the
10240      following ways: (i) Dummy arg of procedure - dummy associates with
10241      actual length; (ii) To declare a named constant; or (iii) External
10242      function - but length must be declared in calling scoping unit.  */
10243   if (sym->attr.function
10244       && sym->ts.type == BT_CHARACTER
10245       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
10246     {
10247       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
10248           || (sym->attr.recursive) || (sym->attr.pure))
10249         {
10250           if (sym->as && sym->as->rank)
10251             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10252                        "array-valued", sym->name, &sym->declared_at);
10253
10254           if (sym->attr.pointer)
10255             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10256                        "pointer-valued", sym->name, &sym->declared_at);
10257
10258           if (sym->attr.pure)
10259             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10260                        "pure", sym->name, &sym->declared_at);
10261
10262           if (sym->attr.recursive)
10263             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10264                        "recursive", sym->name, &sym->declared_at);
10265
10266           return FAILURE;
10267         }
10268
10269       /* Appendix B.2 of the standard.  Contained functions give an
10270          error anyway.  Fixed-form is likely to be F77/legacy.  */
10271       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
10272         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
10273                         "CHARACTER(*) function '%s' at %L",
10274                         sym->name, &sym->declared_at);
10275     }
10276
10277   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
10278     {
10279       gfc_formal_arglist *curr_arg;
10280       int has_non_interop_arg = 0;
10281
10282       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
10283                              sym->common_block) == FAILURE)
10284         {
10285           /* Clear these to prevent looking at them again if there was an
10286              error.  */
10287           sym->attr.is_bind_c = 0;
10288           sym->attr.is_c_interop = 0;
10289           sym->ts.is_c_interop = 0;
10290         }
10291       else
10292         {
10293           /* So far, no errors have been found.  */
10294           sym->attr.is_c_interop = 1;
10295           sym->ts.is_c_interop = 1;
10296         }
10297       
10298       curr_arg = sym->formal;
10299       while (curr_arg != NULL)
10300         {
10301           /* Skip implicitly typed dummy args here.  */
10302           if (curr_arg->sym->attr.implicit_type == 0)
10303             if (verify_c_interop_param (curr_arg->sym) == FAILURE)
10304               /* If something is found to fail, record the fact so we
10305                  can mark the symbol for the procedure as not being
10306                  BIND(C) to try and prevent multiple errors being
10307                  reported.  */
10308               has_non_interop_arg = 1;
10309           
10310           curr_arg = curr_arg->next;
10311         }
10312
10313       /* See if any of the arguments were not interoperable and if so, clear
10314          the procedure symbol to prevent duplicate error messages.  */
10315       if (has_non_interop_arg != 0)
10316         {
10317           sym->attr.is_c_interop = 0;
10318           sym->ts.is_c_interop = 0;
10319           sym->attr.is_bind_c = 0;
10320         }
10321     }
10322   
10323   if (!sym->attr.proc_pointer)
10324     {
10325       if (sym->attr.save == SAVE_EXPLICIT)
10326         {
10327           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
10328                      "in '%s' at %L", sym->name, &sym->declared_at);
10329           return FAILURE;
10330         }
10331       if (sym->attr.intent)
10332         {
10333           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
10334                      "in '%s' at %L", sym->name, &sym->declared_at);
10335           return FAILURE;
10336         }
10337       if (sym->attr.subroutine && sym->attr.result)
10338         {
10339           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
10340                      "in '%s' at %L", sym->name, &sym->declared_at);
10341           return FAILURE;
10342         }
10343       if (sym->attr.external && sym->attr.function
10344           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
10345               || sym->attr.contained))
10346         {
10347           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
10348                      "in '%s' at %L", sym->name, &sym->declared_at);
10349           return FAILURE;
10350         }
10351       if (strcmp ("ppr@", sym->name) == 0)
10352         {
10353           gfc_error ("Procedure pointer result '%s' at %L "
10354                      "is missing the pointer attribute",
10355                      sym->ns->proc_name->name, &sym->declared_at);
10356           return FAILURE;
10357         }
10358     }
10359
10360   return SUCCESS;
10361 }
10362
10363
10364 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
10365    been defined and we now know their defined arguments, check that they fulfill
10366    the requirements of the standard for procedures used as finalizers.  */
10367
10368 static gfc_try
10369 gfc_resolve_finalizers (gfc_symbol* derived)
10370 {
10371   gfc_finalizer* list;
10372   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
10373   gfc_try result = SUCCESS;
10374   bool seen_scalar = false;
10375
10376   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
10377     return SUCCESS;
10378
10379   /* Walk over the list of finalizer-procedures, check them, and if any one
10380      does not fit in with the standard's definition, print an error and remove
10381      it from the list.  */
10382   prev_link = &derived->f2k_derived->finalizers;
10383   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
10384     {
10385       gfc_symbol* arg;
10386       gfc_finalizer* i;
10387       int my_rank;
10388
10389       /* Skip this finalizer if we already resolved it.  */
10390       if (list->proc_tree)
10391         {
10392           prev_link = &(list->next);
10393           continue;
10394         }
10395
10396       /* Check this exists and is a SUBROUTINE.  */
10397       if (!list->proc_sym->attr.subroutine)
10398         {
10399           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
10400                      list->proc_sym->name, &list->where);
10401           goto error;
10402         }
10403
10404       /* We should have exactly one argument.  */
10405       if (!list->proc_sym->formal || list->proc_sym->formal->next)
10406         {
10407           gfc_error ("FINAL procedure at %L must have exactly one argument",
10408                      &list->where);
10409           goto error;
10410         }
10411       arg = list->proc_sym->formal->sym;
10412
10413       /* This argument must be of our type.  */
10414       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
10415         {
10416           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
10417                      &arg->declared_at, derived->name);
10418           goto error;
10419         }
10420
10421       /* It must neither be a pointer nor allocatable nor optional.  */
10422       if (arg->attr.pointer)
10423         {
10424           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
10425                      &arg->declared_at);
10426           goto error;
10427         }
10428       if (arg->attr.allocatable)
10429         {
10430           gfc_error ("Argument of FINAL procedure at %L must not be"
10431                      " ALLOCATABLE", &arg->declared_at);
10432           goto error;
10433         }
10434       if (arg->attr.optional)
10435         {
10436           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
10437                      &arg->declared_at);
10438           goto error;
10439         }
10440
10441       /* It must not be INTENT(OUT).  */
10442       if (arg->attr.intent == INTENT_OUT)
10443         {
10444           gfc_error ("Argument of FINAL procedure at %L must not be"
10445                      " INTENT(OUT)", &arg->declared_at);
10446           goto error;
10447         }
10448
10449       /* Warn if the procedure is non-scalar and not assumed shape.  */
10450       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
10451           && arg->as->type != AS_ASSUMED_SHAPE)
10452         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
10453                      " shape argument", &arg->declared_at);
10454
10455       /* Check that it does not match in kind and rank with a FINAL procedure
10456          defined earlier.  To really loop over the *earlier* declarations,
10457          we need to walk the tail of the list as new ones were pushed at the
10458          front.  */
10459       /* TODO: Handle kind parameters once they are implemented.  */
10460       my_rank = (arg->as ? arg->as->rank : 0);
10461       for (i = list->next; i; i = i->next)
10462         {
10463           /* Argument list might be empty; that is an error signalled earlier,
10464              but we nevertheless continued resolving.  */
10465           if (i->proc_sym->formal)
10466             {
10467               gfc_symbol* i_arg = i->proc_sym->formal->sym;
10468               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
10469               if (i_rank == my_rank)
10470                 {
10471                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
10472                              " rank (%d) as '%s'",
10473                              list->proc_sym->name, &list->where, my_rank, 
10474                              i->proc_sym->name);
10475                   goto error;
10476                 }
10477             }
10478         }
10479
10480         /* Is this the/a scalar finalizer procedure?  */
10481         if (!arg->as || arg->as->rank == 0)
10482           seen_scalar = true;
10483
10484         /* Find the symtree for this procedure.  */
10485         gcc_assert (!list->proc_tree);
10486         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
10487
10488         prev_link = &list->next;
10489         continue;
10490
10491         /* Remove wrong nodes immediately from the list so we don't risk any
10492            troubles in the future when they might fail later expectations.  */
10493 error:
10494         result = FAILURE;
10495         i = list;
10496         *prev_link = list->next;
10497         gfc_free_finalizer (i);
10498     }
10499
10500   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
10501      were nodes in the list, must have been for arrays.  It is surely a good
10502      idea to have a scalar version there if there's something to finalize.  */
10503   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
10504     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
10505                  " defined at %L, suggest also scalar one",
10506                  derived->name, &derived->declared_at);
10507
10508   /* TODO:  Remove this error when finalization is finished.  */
10509   gfc_error ("Finalization at %L is not yet implemented",
10510              &derived->declared_at);
10511
10512   return result;
10513 }
10514
10515
10516 /* Check that it is ok for the typebound procedure proc to override the
10517    procedure old.  */
10518
10519 static gfc_try
10520 check_typebound_override (gfc_symtree* proc, gfc_symtree* old)
10521 {
10522   locus where;
10523   const gfc_symbol* proc_target;
10524   const gfc_symbol* old_target;
10525   unsigned proc_pass_arg, old_pass_arg, argpos;
10526   gfc_formal_arglist* proc_formal;
10527   gfc_formal_arglist* old_formal;
10528
10529   /* This procedure should only be called for non-GENERIC proc.  */
10530   gcc_assert (!proc->n.tb->is_generic);
10531
10532   /* If the overwritten procedure is GENERIC, this is an error.  */
10533   if (old->n.tb->is_generic)
10534     {
10535       gfc_error ("Can't overwrite GENERIC '%s' at %L",
10536                  old->name, &proc->n.tb->where);
10537       return FAILURE;
10538     }
10539
10540   where = proc->n.tb->where;
10541   proc_target = proc->n.tb->u.specific->n.sym;
10542   old_target = old->n.tb->u.specific->n.sym;
10543
10544   /* Check that overridden binding is not NON_OVERRIDABLE.  */
10545   if (old->n.tb->non_overridable)
10546     {
10547       gfc_error ("'%s' at %L overrides a procedure binding declared"
10548                  " NON_OVERRIDABLE", proc->name, &where);
10549       return FAILURE;
10550     }
10551
10552   /* It's an error to override a non-DEFERRED procedure with a DEFERRED one.  */
10553   if (!old->n.tb->deferred && proc->n.tb->deferred)
10554     {
10555       gfc_error ("'%s' at %L must not be DEFERRED as it overrides a"
10556                  " non-DEFERRED binding", proc->name, &where);
10557       return FAILURE;
10558     }
10559
10560   /* If the overridden binding is PURE, the overriding must be, too.  */
10561   if (old_target->attr.pure && !proc_target->attr.pure)
10562     {
10563       gfc_error ("'%s' at %L overrides a PURE procedure and must also be PURE",
10564                  proc->name, &where);
10565       return FAILURE;
10566     }
10567
10568   /* If the overridden binding is ELEMENTAL, the overriding must be, too.  If it
10569      is not, the overriding must not be either.  */
10570   if (old_target->attr.elemental && !proc_target->attr.elemental)
10571     {
10572       gfc_error ("'%s' at %L overrides an ELEMENTAL procedure and must also be"
10573                  " ELEMENTAL", proc->name, &where);
10574       return FAILURE;
10575     }
10576   if (!old_target->attr.elemental && proc_target->attr.elemental)
10577     {
10578       gfc_error ("'%s' at %L overrides a non-ELEMENTAL procedure and must not"
10579                  " be ELEMENTAL, either", proc->name, &where);
10580       return FAILURE;
10581     }
10582
10583   /* If the overridden binding is a SUBROUTINE, the overriding must also be a
10584      SUBROUTINE.  */
10585   if (old_target->attr.subroutine && !proc_target->attr.subroutine)
10586     {
10587       gfc_error ("'%s' at %L overrides a SUBROUTINE and must also be a"
10588                  " SUBROUTINE", proc->name, &where);
10589       return FAILURE;
10590     }
10591
10592   /* If the overridden binding is a FUNCTION, the overriding must also be a
10593      FUNCTION and have the same characteristics.  */
10594   if (old_target->attr.function)
10595     {
10596       if (!proc_target->attr.function)
10597         {
10598           gfc_error ("'%s' at %L overrides a FUNCTION and must also be a"
10599                      " FUNCTION", proc->name, &where);
10600           return FAILURE;
10601         }
10602
10603       /* FIXME:  Do more comprehensive checking (including, for instance, the
10604          rank and array-shape).  */
10605       gcc_assert (proc_target->result && old_target->result);
10606       if (!gfc_compare_types (&proc_target->result->ts,
10607                               &old_target->result->ts))
10608         {
10609           gfc_error ("'%s' at %L and the overridden FUNCTION should have"
10610                      " matching result types", proc->name, &where);
10611           return FAILURE;
10612         }
10613     }
10614
10615   /* If the overridden binding is PUBLIC, the overriding one must not be
10616      PRIVATE.  */
10617   if (old->n.tb->access == ACCESS_PUBLIC
10618       && proc->n.tb->access == ACCESS_PRIVATE)
10619     {
10620       gfc_error ("'%s' at %L overrides a PUBLIC procedure and must not be"
10621                  " PRIVATE", proc->name, &where);
10622       return FAILURE;
10623     }
10624
10625   /* Compare the formal argument lists of both procedures.  This is also abused
10626      to find the position of the passed-object dummy arguments of both
10627      bindings as at least the overridden one might not yet be resolved and we
10628      need those positions in the check below.  */
10629   proc_pass_arg = old_pass_arg = 0;
10630   if (!proc->n.tb->nopass && !proc->n.tb->pass_arg)
10631     proc_pass_arg = 1;
10632   if (!old->n.tb->nopass && !old->n.tb->pass_arg)
10633     old_pass_arg = 1;
10634   argpos = 1;
10635   for (proc_formal = proc_target->formal, old_formal = old_target->formal;
10636        proc_formal && old_formal;
10637        proc_formal = proc_formal->next, old_formal = old_formal->next)
10638     {
10639       if (proc->n.tb->pass_arg
10640           && !strcmp (proc->n.tb->pass_arg, proc_formal->sym->name))
10641         proc_pass_arg = argpos;
10642       if (old->n.tb->pass_arg
10643           && !strcmp (old->n.tb->pass_arg, old_formal->sym->name))
10644         old_pass_arg = argpos;
10645
10646       /* Check that the names correspond.  */
10647       if (strcmp (proc_formal->sym->name, old_formal->sym->name))
10648         {
10649           gfc_error ("Dummy argument '%s' of '%s' at %L should be named '%s' as"
10650                      " to match the corresponding argument of the overridden"
10651                      " procedure", proc_formal->sym->name, proc->name, &where,
10652                      old_formal->sym->name);
10653           return FAILURE;
10654         }
10655
10656       /* Check that the types correspond if neither is the passed-object
10657          argument.  */
10658       /* FIXME:  Do more comprehensive testing here.  */
10659       if (proc_pass_arg != argpos && old_pass_arg != argpos
10660           && !gfc_compare_types (&proc_formal->sym->ts, &old_formal->sym->ts))
10661         {
10662           gfc_error ("Types mismatch for dummy argument '%s' of '%s' %L "
10663                      "in respect to the overridden procedure",
10664                      proc_formal->sym->name, proc->name, &where);
10665           return FAILURE;
10666         }
10667
10668       ++argpos;
10669     }
10670   if (proc_formal || old_formal)
10671     {
10672       gfc_error ("'%s' at %L must have the same number of formal arguments as"
10673                  " the overridden procedure", proc->name, &where);
10674       return FAILURE;
10675     }
10676
10677   /* If the overridden binding is NOPASS, the overriding one must also be
10678      NOPASS.  */
10679   if (old->n.tb->nopass && !proc->n.tb->nopass)
10680     {
10681       gfc_error ("'%s' at %L overrides a NOPASS binding and must also be"
10682                  " NOPASS", proc->name, &where);
10683       return FAILURE;
10684     }
10685
10686   /* If the overridden binding is PASS(x), the overriding one must also be
10687      PASS and the passed-object dummy arguments must correspond.  */
10688   if (!old->n.tb->nopass)
10689     {
10690       if (proc->n.tb->nopass)
10691         {
10692           gfc_error ("'%s' at %L overrides a binding with PASS and must also be"
10693                      " PASS", proc->name, &where);
10694           return FAILURE;
10695         }
10696
10697       if (proc_pass_arg != old_pass_arg)
10698         {
10699           gfc_error ("Passed-object dummy argument of '%s' at %L must be at"
10700                      " the same position as the passed-object dummy argument of"
10701                      " the overridden procedure", proc->name, &where);
10702           return FAILURE;
10703         }
10704     }
10705
10706   return SUCCESS;
10707 }
10708
10709
10710 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
10711
10712 static gfc_try
10713 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
10714                              const char* generic_name, locus where)
10715 {
10716   gfc_symbol* sym1;
10717   gfc_symbol* sym2;
10718
10719   gcc_assert (t1->specific && t2->specific);
10720   gcc_assert (!t1->specific->is_generic);
10721   gcc_assert (!t2->specific->is_generic);
10722
10723   sym1 = t1->specific->u.specific->n.sym;
10724   sym2 = t2->specific->u.specific->n.sym;
10725
10726   if (sym1 == sym2)
10727     return SUCCESS;
10728
10729   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
10730   if (sym1->attr.subroutine != sym2->attr.subroutine
10731       || sym1->attr.function != sym2->attr.function)
10732     {
10733       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
10734                  " GENERIC '%s' at %L",
10735                  sym1->name, sym2->name, generic_name, &where);
10736       return FAILURE;
10737     }
10738
10739   /* Compare the interfaces.  */
10740   if (gfc_compare_interfaces (sym1, sym2, sym2->name, 1, 0, NULL, 0))
10741     {
10742       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
10743                  sym1->name, sym2->name, generic_name, &where);
10744       return FAILURE;
10745     }
10746
10747   return SUCCESS;
10748 }
10749
10750
10751 /* Worker function for resolving a generic procedure binding; this is used to
10752    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
10753
10754    The difference between those cases is finding possible inherited bindings
10755    that are overridden, as one has to look for them in tb_sym_root,
10756    tb_uop_root or tb_op, respectively.  Thus the caller must already find
10757    the super-type and set p->overridden correctly.  */
10758
10759 static gfc_try
10760 resolve_tb_generic_targets (gfc_symbol* super_type,
10761                             gfc_typebound_proc* p, const char* name)
10762 {
10763   gfc_tbp_generic* target;
10764   gfc_symtree* first_target;
10765   gfc_symtree* inherited;
10766
10767   gcc_assert (p && p->is_generic);
10768
10769   /* Try to find the specific bindings for the symtrees in our target-list.  */
10770   gcc_assert (p->u.generic);
10771   for (target = p->u.generic; target; target = target->next)
10772     if (!target->specific)
10773       {
10774         gfc_typebound_proc* overridden_tbp;
10775         gfc_tbp_generic* g;
10776         const char* target_name;
10777
10778         target_name = target->specific_st->name;
10779
10780         /* Defined for this type directly.  */
10781         if (target->specific_st->n.tb && !target->specific_st->n.tb->error)
10782           {
10783             target->specific = target->specific_st->n.tb;
10784             goto specific_found;
10785           }
10786
10787         /* Look for an inherited specific binding.  */
10788         if (super_type)
10789           {
10790             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
10791                                                  true, NULL);
10792
10793             if (inherited)
10794               {
10795                 gcc_assert (inherited->n.tb);
10796                 target->specific = inherited->n.tb;
10797                 goto specific_found;
10798               }
10799           }
10800
10801         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
10802                    " at %L", target_name, name, &p->where);
10803         return FAILURE;
10804
10805         /* Once we've found the specific binding, check it is not ambiguous with
10806            other specifics already found or inherited for the same GENERIC.  */
10807 specific_found:
10808         gcc_assert (target->specific);
10809
10810         /* This must really be a specific binding!  */
10811         if (target->specific->is_generic)
10812           {
10813             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
10814                        " '%s' is GENERIC, too", name, &p->where, target_name);
10815             return FAILURE;
10816           }
10817
10818         /* Check those already resolved on this type directly.  */
10819         for (g = p->u.generic; g; g = g->next)
10820           if (g != target && g->specific
10821               && check_generic_tbp_ambiguity (target, g, name, p->where)
10822                   == FAILURE)
10823             return FAILURE;
10824
10825         /* Check for ambiguity with inherited specific targets.  */
10826         for (overridden_tbp = p->overridden; overridden_tbp;
10827              overridden_tbp = overridden_tbp->overridden)
10828           if (overridden_tbp->is_generic)
10829             {
10830               for (g = overridden_tbp->u.generic; g; g = g->next)
10831                 {
10832                   gcc_assert (g->specific);
10833                   if (check_generic_tbp_ambiguity (target, g,
10834                                                    name, p->where) == FAILURE)
10835                     return FAILURE;
10836                 }
10837             }
10838       }
10839
10840   /* If we attempt to "overwrite" a specific binding, this is an error.  */
10841   if (p->overridden && !p->overridden->is_generic)
10842     {
10843       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
10844                  " the same name", name, &p->where);
10845       return FAILURE;
10846     }
10847
10848   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
10849      all must have the same attributes here.  */
10850   first_target = p->u.generic->specific->u.specific;
10851   gcc_assert (first_target);
10852   p->subroutine = first_target->n.sym->attr.subroutine;
10853   p->function = first_target->n.sym->attr.function;
10854
10855   return SUCCESS;
10856 }
10857
10858
10859 /* Resolve a GENERIC procedure binding for a derived type.  */
10860
10861 static gfc_try
10862 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
10863 {
10864   gfc_symbol* super_type;
10865
10866   /* Find the overridden binding if any.  */
10867   st->n.tb->overridden = NULL;
10868   super_type = gfc_get_derived_super_type (derived);
10869   if (super_type)
10870     {
10871       gfc_symtree* overridden;
10872       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
10873                                             true, NULL);
10874
10875       if (overridden && overridden->n.tb)
10876         st->n.tb->overridden = overridden->n.tb;
10877     }
10878
10879   /* Resolve using worker function.  */
10880   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
10881 }
10882
10883
10884 /* Retrieve the target-procedure of an operator binding and do some checks in
10885    common for intrinsic and user-defined type-bound operators.  */
10886
10887 static gfc_symbol*
10888 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
10889 {
10890   gfc_symbol* target_proc;
10891
10892   gcc_assert (target->specific && !target->specific->is_generic);
10893   target_proc = target->specific->u.specific->n.sym;
10894   gcc_assert (target_proc);
10895
10896   /* All operator bindings must have a passed-object dummy argument.  */
10897   if (target->specific->nopass)
10898     {
10899       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
10900       return NULL;
10901     }
10902
10903   return target_proc;
10904 }
10905
10906
10907 /* Resolve a type-bound intrinsic operator.  */
10908
10909 static gfc_try
10910 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
10911                                 gfc_typebound_proc* p)
10912 {
10913   gfc_symbol* super_type;
10914   gfc_tbp_generic* target;
10915   
10916   /* If there's already an error here, do nothing (but don't fail again).  */
10917   if (p->error)
10918     return SUCCESS;
10919
10920   /* Operators should always be GENERIC bindings.  */
10921   gcc_assert (p->is_generic);
10922
10923   /* Look for an overridden binding.  */
10924   super_type = gfc_get_derived_super_type (derived);
10925   if (super_type && super_type->f2k_derived)
10926     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
10927                                                      op, true, NULL);
10928   else
10929     p->overridden = NULL;
10930
10931   /* Resolve general GENERIC properties using worker function.  */
10932   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
10933     goto error;
10934
10935   /* Check the targets to be procedures of correct interface.  */
10936   for (target = p->u.generic; target; target = target->next)
10937     {
10938       gfc_symbol* target_proc;
10939
10940       target_proc = get_checked_tb_operator_target (target, p->where);
10941       if (!target_proc)
10942         goto error;
10943
10944       if (!gfc_check_operator_interface (target_proc, op, p->where))
10945         goto error;
10946     }
10947
10948   return SUCCESS;
10949
10950 error:
10951   p->error = 1;
10952   return FAILURE;
10953 }
10954
10955
10956 /* Resolve a type-bound user operator (tree-walker callback).  */
10957
10958 static gfc_symbol* resolve_bindings_derived;
10959 static gfc_try resolve_bindings_result;
10960
10961 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
10962
10963 static void
10964 resolve_typebound_user_op (gfc_symtree* stree)
10965 {
10966   gfc_symbol* super_type;
10967   gfc_tbp_generic* target;
10968
10969   gcc_assert (stree && stree->n.tb);
10970
10971   if (stree->n.tb->error)
10972     return;
10973
10974   /* Operators should always be GENERIC bindings.  */
10975   gcc_assert (stree->n.tb->is_generic);
10976
10977   /* Find overridden procedure, if any.  */
10978   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10979   if (super_type && super_type->f2k_derived)
10980     {
10981       gfc_symtree* overridden;
10982       overridden = gfc_find_typebound_user_op (super_type, NULL,
10983                                                stree->name, true, NULL);
10984
10985       if (overridden && overridden->n.tb)
10986         stree->n.tb->overridden = overridden->n.tb;
10987     }
10988   else
10989     stree->n.tb->overridden = NULL;
10990
10991   /* Resolve basically using worker function.  */
10992   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
10993         == FAILURE)
10994     goto error;
10995
10996   /* Check the targets to be functions of correct interface.  */
10997   for (target = stree->n.tb->u.generic; target; target = target->next)
10998     {
10999       gfc_symbol* target_proc;
11000
11001       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
11002       if (!target_proc)
11003         goto error;
11004
11005       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
11006         goto error;
11007     }
11008
11009   return;
11010
11011 error:
11012   resolve_bindings_result = FAILURE;
11013   stree->n.tb->error = 1;
11014 }
11015
11016
11017 /* Resolve the type-bound procedures for a derived type.  */
11018
11019 static void
11020 resolve_typebound_procedure (gfc_symtree* stree)
11021 {
11022   gfc_symbol* proc;
11023   locus where;
11024   gfc_symbol* me_arg;
11025   gfc_symbol* super_type;
11026   gfc_component* comp;
11027
11028   gcc_assert (stree);
11029
11030   /* Undefined specific symbol from GENERIC target definition.  */
11031   if (!stree->n.tb)
11032     return;
11033
11034   if (stree->n.tb->error)
11035     return;
11036
11037   /* If this is a GENERIC binding, use that routine.  */
11038   if (stree->n.tb->is_generic)
11039     {
11040       if (resolve_typebound_generic (resolve_bindings_derived, stree)
11041             == FAILURE)
11042         goto error;
11043       return;
11044     }
11045
11046   /* Get the target-procedure to check it.  */
11047   gcc_assert (!stree->n.tb->is_generic);
11048   gcc_assert (stree->n.tb->u.specific);
11049   proc = stree->n.tb->u.specific->n.sym;
11050   where = stree->n.tb->where;
11051
11052   /* Default access should already be resolved from the parser.  */
11053   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
11054
11055   /* It should be a module procedure or an external procedure with explicit
11056      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
11057   if ((!proc->attr.subroutine && !proc->attr.function)
11058       || (proc->attr.proc != PROC_MODULE
11059           && proc->attr.if_source != IFSRC_IFBODY)
11060       || (proc->attr.abstract && !stree->n.tb->deferred))
11061     {
11062       gfc_error ("'%s' must be a module procedure or an external procedure with"
11063                  " an explicit interface at %L", proc->name, &where);
11064       goto error;
11065     }
11066   stree->n.tb->subroutine = proc->attr.subroutine;
11067   stree->n.tb->function = proc->attr.function;
11068
11069   /* Find the super-type of the current derived type.  We could do this once and
11070      store in a global if speed is needed, but as long as not I believe this is
11071      more readable and clearer.  */
11072   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
11073
11074   /* If PASS, resolve and check arguments if not already resolved / loaded
11075      from a .mod file.  */
11076   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
11077     {
11078       if (stree->n.tb->pass_arg)
11079         {
11080           gfc_formal_arglist* i;
11081
11082           /* If an explicit passing argument name is given, walk the arg-list
11083              and look for it.  */
11084
11085           me_arg = NULL;
11086           stree->n.tb->pass_arg_num = 1;
11087           for (i = proc->formal; i; i = i->next)
11088             {
11089               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
11090                 {
11091                   me_arg = i->sym;
11092                   break;
11093                 }
11094               ++stree->n.tb->pass_arg_num;
11095             }
11096
11097           if (!me_arg)
11098             {
11099               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
11100                          " argument '%s'",
11101                          proc->name, stree->n.tb->pass_arg, &where,
11102                          stree->n.tb->pass_arg);
11103               goto error;
11104             }
11105         }
11106       else
11107         {
11108           /* Otherwise, take the first one; there should in fact be at least
11109              one.  */
11110           stree->n.tb->pass_arg_num = 1;
11111           if (!proc->formal)
11112             {
11113               gfc_error ("Procedure '%s' with PASS at %L must have at"
11114                          " least one argument", proc->name, &where);
11115               goto error;
11116             }
11117           me_arg = proc->formal->sym;
11118         }
11119
11120       /* Now check that the argument-type matches and the passed-object
11121          dummy argument is generally fine.  */
11122
11123       gcc_assert (me_arg);
11124
11125       if (me_arg->ts.type != BT_CLASS)
11126         {
11127           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11128                      " at %L", proc->name, &where);
11129           goto error;
11130         }
11131
11132       if (CLASS_DATA (me_arg)->ts.u.derived
11133           != resolve_bindings_derived)
11134         {
11135           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11136                      " the derived-type '%s'", me_arg->name, proc->name,
11137                      me_arg->name, &where, resolve_bindings_derived->name);
11138           goto error;
11139         }
11140   
11141       gcc_assert (me_arg->ts.type == BT_CLASS);
11142       if (CLASS_DATA (me_arg)->as && CLASS_DATA (me_arg)->as->rank > 0)
11143         {
11144           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
11145                      " scalar", proc->name, &where);
11146           goto error;
11147         }
11148       if (CLASS_DATA (me_arg)->attr.allocatable)
11149         {
11150           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11151                      " be ALLOCATABLE", proc->name, &where);
11152           goto error;
11153         }
11154       if (CLASS_DATA (me_arg)->attr.class_pointer)
11155         {
11156           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11157                      " be POINTER", proc->name, &where);
11158           goto error;
11159         }
11160     }
11161
11162   /* If we are extending some type, check that we don't override a procedure
11163      flagged NON_OVERRIDABLE.  */
11164   stree->n.tb->overridden = NULL;
11165   if (super_type)
11166     {
11167       gfc_symtree* overridden;
11168       overridden = gfc_find_typebound_proc (super_type, NULL,
11169                                             stree->name, true, NULL);
11170
11171       if (overridden && overridden->n.tb)
11172         stree->n.tb->overridden = overridden->n.tb;
11173
11174       if (overridden && check_typebound_override (stree, overridden) == FAILURE)
11175         goto error;
11176     }
11177
11178   /* See if there's a name collision with a component directly in this type.  */
11179   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
11180     if (!strcmp (comp->name, stree->name))
11181       {
11182         gfc_error ("Procedure '%s' at %L has the same name as a component of"
11183                    " '%s'",
11184                    stree->name, &where, resolve_bindings_derived->name);
11185         goto error;
11186       }
11187
11188   /* Try to find a name collision with an inherited component.  */
11189   if (super_type && gfc_find_component (super_type, stree->name, true, true))
11190     {
11191       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
11192                  " component of '%s'",
11193                  stree->name, &where, resolve_bindings_derived->name);
11194       goto error;
11195     }
11196
11197   stree->n.tb->error = 0;
11198   return;
11199
11200 error:
11201   resolve_bindings_result = FAILURE;
11202   stree->n.tb->error = 1;
11203 }
11204
11205
11206 static gfc_try
11207 resolve_typebound_procedures (gfc_symbol* derived)
11208 {
11209   int op;
11210
11211   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
11212     return SUCCESS;
11213
11214   resolve_bindings_derived = derived;
11215   resolve_bindings_result = SUCCESS;
11216
11217   /* Make sure the vtab has been generated.  */
11218   gfc_find_derived_vtab (derived);
11219
11220   if (derived->f2k_derived->tb_sym_root)
11221     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
11222                           &resolve_typebound_procedure);
11223
11224   if (derived->f2k_derived->tb_uop_root)
11225     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
11226                           &resolve_typebound_user_op);
11227
11228   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
11229     {
11230       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
11231       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
11232                                                p) == FAILURE)
11233         resolve_bindings_result = FAILURE;
11234     }
11235
11236   return resolve_bindings_result;
11237 }
11238
11239
11240 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
11241    to give all identical derived types the same backend_decl.  */
11242 static void
11243 add_dt_to_dt_list (gfc_symbol *derived)
11244 {
11245   gfc_dt_list *dt_list;
11246
11247   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
11248     if (derived == dt_list->derived)
11249       return;
11250
11251   dt_list = gfc_get_dt_list ();
11252   dt_list->next = gfc_derived_types;
11253   dt_list->derived = derived;
11254   gfc_derived_types = dt_list;
11255 }
11256
11257
11258 /* Ensure that a derived-type is really not abstract, meaning that every
11259    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
11260
11261 static gfc_try
11262 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
11263 {
11264   if (!st)
11265     return SUCCESS;
11266
11267   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
11268     return FAILURE;
11269   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
11270     return FAILURE;
11271
11272   if (st->n.tb && st->n.tb->deferred)
11273     {
11274       gfc_symtree* overriding;
11275       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
11276       if (!overriding)
11277         return FAILURE;
11278       gcc_assert (overriding->n.tb);
11279       if (overriding->n.tb->deferred)
11280         {
11281           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
11282                      " '%s' is DEFERRED and not overridden",
11283                      sub->name, &sub->declared_at, st->name);
11284           return FAILURE;
11285         }
11286     }
11287
11288   return SUCCESS;
11289 }
11290
11291 static gfc_try
11292 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
11293 {
11294   /* The algorithm used here is to recursively travel up the ancestry of sub
11295      and for each ancestor-type, check all bindings.  If any of them is
11296      DEFERRED, look it up starting from sub and see if the found (overriding)
11297      binding is not DEFERRED.
11298      This is not the most efficient way to do this, but it should be ok and is
11299      clearer than something sophisticated.  */
11300
11301   gcc_assert (ancestor && !sub->attr.abstract);
11302   
11303   if (!ancestor->attr.abstract)
11304     return SUCCESS;
11305
11306   /* Walk bindings of this ancestor.  */
11307   if (ancestor->f2k_derived)
11308     {
11309       gfc_try t;
11310       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
11311       if (t == FAILURE)
11312         return FAILURE;
11313     }
11314
11315   /* Find next ancestor type and recurse on it.  */
11316   ancestor = gfc_get_derived_super_type (ancestor);
11317   if (ancestor)
11318     return ensure_not_abstract (sub, ancestor);
11319
11320   return SUCCESS;
11321 }
11322
11323
11324 /* Resolve the components of a derived type.  */
11325
11326 static gfc_try
11327 resolve_fl_derived (gfc_symbol *sym)
11328 {
11329   gfc_symbol* super_type;
11330   gfc_component *c;
11331
11332   super_type = gfc_get_derived_super_type (sym);
11333   
11334   if (sym->attr.is_class && sym->ts.u.derived == NULL)
11335     {
11336       /* Fix up incomplete CLASS symbols.  */
11337       gfc_component *data = gfc_find_component (sym, "_data", true, true);
11338       gfc_component *vptr = gfc_find_component (sym, "_vptr", true, true);
11339       if (vptr->ts.u.derived == NULL)
11340         {
11341           gfc_symbol *vtab = gfc_find_derived_vtab (data->ts.u.derived);
11342           gcc_assert (vtab);
11343           vptr->ts.u.derived = vtab->ts.u.derived;
11344         }
11345     }
11346
11347   /* F2008, C432. */
11348   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
11349     {
11350       gfc_error ("As extending type '%s' at %L has a coarray component, "
11351                  "parent type '%s' shall also have one", sym->name,
11352                  &sym->declared_at, super_type->name);
11353       return FAILURE;
11354     }
11355
11356   /* Ensure the extended type gets resolved before we do.  */
11357   if (super_type && resolve_fl_derived (super_type) == FAILURE)
11358     return FAILURE;
11359
11360   /* An ABSTRACT type must be extensible.  */
11361   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
11362     {
11363       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
11364                  sym->name, &sym->declared_at);
11365       return FAILURE;
11366     }
11367
11368   for (c = sym->components; c != NULL; c = c->next)
11369     {
11370       /* F2008, C442.  */
11371       if (c->attr.codimension /* FIXME: c->as check due to PR 43412.  */
11372           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
11373         {
11374           gfc_error ("Coarray component '%s' at %L must be allocatable with "
11375                      "deferred shape", c->name, &c->loc);
11376           return FAILURE;
11377         }
11378
11379       /* F2008, C443.  */
11380       if (c->attr.codimension && c->ts.type == BT_DERIVED
11381           && c->ts.u.derived->ts.is_iso_c)
11382         {
11383           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
11384                      "shall not be a coarray", c->name, &c->loc);
11385           return FAILURE;
11386         }
11387
11388       /* F2008, C444.  */
11389       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
11390           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
11391               || c->attr.allocatable))
11392         {
11393           gfc_error ("Component '%s' at %L with coarray component "
11394                      "shall be a nonpointer, nonallocatable scalar",
11395                      c->name, &c->loc);
11396           return FAILURE;
11397         }
11398
11399       /* F2008, C448.  */
11400       if (c->attr.contiguous && (!c->attr.dimension || !c->attr.pointer))
11401         {
11402           gfc_error ("Component '%s' at %L has the CONTIGUOUS attribute but "
11403                      "is not an array pointer", c->name, &c->loc);
11404           return FAILURE;
11405         }
11406
11407       if (c->attr.proc_pointer && c->ts.interface)
11408         {
11409           if (c->ts.interface->attr.procedure && !sym->attr.vtype)
11410             gfc_error ("Interface '%s', used by procedure pointer component "
11411                        "'%s' at %L, is declared in a later PROCEDURE statement",
11412                        c->ts.interface->name, c->name, &c->loc);
11413
11414           /* Get the attributes from the interface (now resolved).  */
11415           if (c->ts.interface->attr.if_source
11416               || c->ts.interface->attr.intrinsic)
11417             {
11418               gfc_symbol *ifc = c->ts.interface;
11419
11420               if (ifc->formal && !ifc->formal_ns)
11421                 resolve_symbol (ifc);
11422
11423               if (ifc->attr.intrinsic)
11424                 resolve_intrinsic (ifc, &ifc->declared_at);
11425
11426               if (ifc->result)
11427                 {
11428                   c->ts = ifc->result->ts;
11429                   c->attr.allocatable = ifc->result->attr.allocatable;
11430                   c->attr.pointer = ifc->result->attr.pointer;
11431                   c->attr.dimension = ifc->result->attr.dimension;
11432                   c->as = gfc_copy_array_spec (ifc->result->as);
11433                 }
11434               else
11435                 {   
11436                   c->ts = ifc->ts;
11437                   c->attr.allocatable = ifc->attr.allocatable;
11438                   c->attr.pointer = ifc->attr.pointer;
11439                   c->attr.dimension = ifc->attr.dimension;
11440                   c->as = gfc_copy_array_spec (ifc->as);
11441                 }
11442               c->ts.interface = ifc;
11443               c->attr.function = ifc->attr.function;
11444               c->attr.subroutine = ifc->attr.subroutine;
11445               gfc_copy_formal_args_ppc (c, ifc);
11446
11447               c->attr.pure = ifc->attr.pure;
11448               c->attr.elemental = ifc->attr.elemental;
11449               c->attr.recursive = ifc->attr.recursive;
11450               c->attr.always_explicit = ifc->attr.always_explicit;
11451               c->attr.ext_attr |= ifc->attr.ext_attr;
11452               /* Replace symbols in array spec.  */
11453               if (c->as)
11454                 {
11455                   int i;
11456                   for (i = 0; i < c->as->rank; i++)
11457                     {
11458                       gfc_expr_replace_comp (c->as->lower[i], c);
11459                       gfc_expr_replace_comp (c->as->upper[i], c);
11460                     }
11461                 }
11462               /* Copy char length.  */
11463               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
11464                 {
11465                   gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
11466                   gfc_expr_replace_comp (cl->length, c);
11467                   if (cl->length && !cl->resolved
11468                         && gfc_resolve_expr (cl->length) == FAILURE)
11469                     return FAILURE;
11470                   c->ts.u.cl = cl;
11471                 }
11472             }
11473           else if (!sym->attr.vtype && c->ts.interface->name[0] != '\0')
11474             {
11475               gfc_error ("Interface '%s' of procedure pointer component "
11476                          "'%s' at %L must be explicit", c->ts.interface->name,
11477                          c->name, &c->loc);
11478               return FAILURE;
11479             }
11480         }
11481       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
11482         {
11483           /* Since PPCs are not implicitly typed, a PPC without an explicit
11484              interface must be a subroutine.  */
11485           gfc_add_subroutine (&c->attr, c->name, &c->loc);
11486         }
11487
11488       /* Procedure pointer components: Check PASS arg.  */
11489       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
11490           && !sym->attr.vtype)
11491         {
11492           gfc_symbol* me_arg;
11493
11494           if (c->tb->pass_arg)
11495             {
11496               gfc_formal_arglist* i;
11497
11498               /* If an explicit passing argument name is given, walk the arg-list
11499                 and look for it.  */
11500
11501               me_arg = NULL;
11502               c->tb->pass_arg_num = 1;
11503               for (i = c->formal; i; i = i->next)
11504                 {
11505                   if (!strcmp (i->sym->name, c->tb->pass_arg))
11506                     {
11507                       me_arg = i->sym;
11508                       break;
11509                     }
11510                   c->tb->pass_arg_num++;
11511                 }
11512
11513               if (!me_arg)
11514                 {
11515                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
11516                              "at %L has no argument '%s'", c->name,
11517                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
11518                   c->tb->error = 1;
11519                   return FAILURE;
11520                 }
11521             }
11522           else
11523             {
11524               /* Otherwise, take the first one; there should in fact be at least
11525                 one.  */
11526               c->tb->pass_arg_num = 1;
11527               if (!c->formal)
11528                 {
11529                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
11530                              "must have at least one argument",
11531                              c->name, &c->loc);
11532                   c->tb->error = 1;
11533                   return FAILURE;
11534                 }
11535               me_arg = c->formal->sym;
11536             }
11537
11538           /* Now check that the argument-type matches.  */
11539           gcc_assert (me_arg);
11540           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
11541               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
11542               || (me_arg->ts.type == BT_CLASS
11543                   && CLASS_DATA (me_arg)->ts.u.derived != sym))
11544             {
11545               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11546                          " the derived type '%s'", me_arg->name, c->name,
11547                          me_arg->name, &c->loc, sym->name);
11548               c->tb->error = 1;
11549               return FAILURE;
11550             }
11551
11552           /* Check for C453.  */
11553           if (me_arg->attr.dimension)
11554             {
11555               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11556                          "must be scalar", me_arg->name, c->name, me_arg->name,
11557                          &c->loc);
11558               c->tb->error = 1;
11559               return FAILURE;
11560             }
11561
11562           if (me_arg->attr.pointer)
11563             {
11564               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11565                          "may not have the POINTER attribute", me_arg->name,
11566                          c->name, me_arg->name, &c->loc);
11567               c->tb->error = 1;
11568               return FAILURE;
11569             }
11570
11571           if (me_arg->attr.allocatable)
11572             {
11573               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11574                          "may not be ALLOCATABLE", me_arg->name, c->name,
11575                          me_arg->name, &c->loc);
11576               c->tb->error = 1;
11577               return FAILURE;
11578             }
11579
11580           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
11581             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11582                        " at %L", c->name, &c->loc);
11583
11584         }
11585
11586       /* Check type-spec if this is not the parent-type component.  */
11587       if ((!sym->attr.extension || c != sym->components) && !sym->attr.vtype
11588           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
11589         return FAILURE;
11590
11591       /* If this type is an extension, set the accessibility of the parent
11592          component.  */
11593       if (super_type && c == sym->components
11594           && strcmp (super_type->name, c->name) == 0)
11595         c->attr.access = super_type->attr.access;
11596       
11597       /* If this type is an extension, see if this component has the same name
11598          as an inherited type-bound procedure.  */
11599       if (super_type && !sym->attr.is_class
11600           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
11601         {
11602           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
11603                      " inherited type-bound procedure",
11604                      c->name, sym->name, &c->loc);
11605           return FAILURE;
11606         }
11607
11608       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer)
11609         {
11610          if (c->ts.u.cl->length == NULL
11611              || (resolve_charlen (c->ts.u.cl) == FAILURE)
11612              || !gfc_is_constant_expr (c->ts.u.cl->length))
11613            {
11614              gfc_error ("Character length of component '%s' needs to "
11615                         "be a constant specification expression at %L",
11616                         c->name,
11617                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
11618              return FAILURE;
11619            }
11620         }
11621
11622       if (c->ts.type == BT_DERIVED
11623           && sym->component_access != ACCESS_PRIVATE
11624           && gfc_check_access (sym->attr.access, sym->ns->default_access)
11625           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
11626           && !c->ts.u.derived->attr.use_assoc
11627           && !gfc_check_access (c->ts.u.derived->attr.access,
11628                                 c->ts.u.derived->ns->default_access)
11629           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
11630                              "is a PRIVATE type and cannot be a component of "
11631                              "'%s', which is PUBLIC at %L", c->name,
11632                              sym->name, &sym->declared_at) == FAILURE)
11633         return FAILURE;
11634
11635       if ((sym->attr.sequence || sym->attr.is_bind_c) && c->ts.type == BT_CLASS)
11636         {
11637           gfc_error ("Polymorphic component %s at %L in SEQUENCE or BIND(C) "
11638                      "type %s", c->name, &c->loc, sym->name);
11639           return FAILURE;
11640         }
11641
11642       if (sym->attr.sequence)
11643         {
11644           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
11645             {
11646               gfc_error ("Component %s of SEQUENCE type declared at %L does "
11647                          "not have the SEQUENCE attribute",
11648                          c->ts.u.derived->name, &sym->declared_at);
11649               return FAILURE;
11650             }
11651         }
11652
11653       if (!sym->attr.is_class && c->ts.type == BT_DERIVED && !sym->attr.vtype
11654           && c->attr.pointer && c->ts.u.derived->components == NULL
11655           && !c->ts.u.derived->attr.zero_comp)
11656         {
11657           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11658                      "that has not been declared", c->name, sym->name,
11659                      &c->loc);
11660           return FAILURE;
11661         }
11662
11663       if (c->ts.type == BT_CLASS && CLASS_DATA (c)->attr.class_pointer
11664           && CLASS_DATA (c)->ts.u.derived->components == NULL
11665           && !CLASS_DATA (c)->ts.u.derived->attr.zero_comp)
11666         {
11667           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11668                      "that has not been declared", c->name, sym->name,
11669                      &c->loc);
11670           return FAILURE;
11671         }
11672
11673       /* C437.  */
11674       if (c->ts.type == BT_CLASS
11675           && !(CLASS_DATA (c)->attr.class_pointer
11676                || CLASS_DATA (c)->attr.allocatable))
11677         {
11678           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
11679                      "or pointer", c->name, &c->loc);
11680           return FAILURE;
11681         }
11682
11683       /* Ensure that all the derived type components are put on the
11684          derived type list; even in formal namespaces, where derived type
11685          pointer components might not have been declared.  */
11686       if (c->ts.type == BT_DERIVED
11687             && c->ts.u.derived
11688             && c->ts.u.derived->components
11689             && c->attr.pointer
11690             && sym != c->ts.u.derived)
11691         add_dt_to_dt_list (c->ts.u.derived);
11692
11693       if (gfc_resolve_array_spec (c->as, !(c->attr.pointer
11694                                            || c->attr.proc_pointer
11695                                            || c->attr.allocatable)) == FAILURE)
11696         return FAILURE;
11697     }
11698
11699   /* Resolve the type-bound procedures.  */
11700   if (resolve_typebound_procedures (sym) == FAILURE)
11701     return FAILURE;
11702
11703   /* Resolve the finalizer procedures.  */
11704   if (gfc_resolve_finalizers (sym) == FAILURE)
11705     return FAILURE;
11706
11707   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
11708      all DEFERRED bindings are overridden.  */
11709   if (super_type && super_type->attr.abstract && !sym->attr.abstract
11710       && !sym->attr.is_class
11711       && ensure_not_abstract (sym, super_type) == FAILURE)
11712     return FAILURE;
11713
11714   /* Add derived type to the derived type list.  */
11715   add_dt_to_dt_list (sym);
11716
11717   return SUCCESS;
11718 }
11719
11720
11721 static gfc_try
11722 resolve_fl_namelist (gfc_symbol *sym)
11723 {
11724   gfc_namelist *nl;
11725   gfc_symbol *nlsym;
11726
11727   for (nl = sym->namelist; nl; nl = nl->next)
11728     {
11729       /* Reject namelist arrays of assumed shape.  */
11730       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
11731           && gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
11732                              "must not have assumed shape in namelist "
11733                              "'%s' at %L", nl->sym->name, sym->name,
11734                              &sym->declared_at) == FAILURE)
11735             return FAILURE;
11736
11737       /* Reject namelist arrays that are not constant shape.  */
11738       if (is_non_constant_shape_array (nl->sym))
11739         {
11740           gfc_error ("NAMELIST array object '%s' must have constant "
11741                      "shape in namelist '%s' at %L", nl->sym->name,
11742                      sym->name, &sym->declared_at);
11743           return FAILURE;
11744         }
11745
11746       /* Namelist objects cannot have allocatable or pointer components.  */
11747       if (nl->sym->ts.type != BT_DERIVED)
11748         continue;
11749
11750       if (nl->sym->ts.u.derived->attr.alloc_comp)
11751         {
11752           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11753                      "have ALLOCATABLE components",
11754                      nl->sym->name, sym->name, &sym->declared_at);
11755           return FAILURE;
11756         }
11757
11758       if (nl->sym->ts.u.derived->attr.pointer_comp)
11759         {
11760           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11761                      "have POINTER components", 
11762                      nl->sym->name, sym->name, &sym->declared_at);
11763           return FAILURE;
11764         }
11765     }
11766
11767   /* Reject PRIVATE objects in a PUBLIC namelist.  */
11768   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
11769     {
11770       for (nl = sym->namelist; nl; nl = nl->next)
11771         {
11772           if (!nl->sym->attr.use_assoc
11773               && !is_sym_host_assoc (nl->sym, sym->ns)
11774               && !gfc_check_access(nl->sym->attr.access,
11775                                 nl->sym->ns->default_access))
11776             {
11777               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
11778                          "cannot be member of PUBLIC namelist '%s' at %L",
11779                          nl->sym->name, sym->name, &sym->declared_at);
11780               return FAILURE;
11781             }
11782
11783           /* Types with private components that came here by USE-association.  */
11784           if (nl->sym->ts.type == BT_DERIVED
11785               && derived_inaccessible (nl->sym->ts.u.derived))
11786             {
11787               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
11788                          "components and cannot be member of namelist '%s' at %L",
11789                          nl->sym->name, sym->name, &sym->declared_at);
11790               return FAILURE;
11791             }
11792
11793           /* Types with private components that are defined in the same module.  */
11794           if (nl->sym->ts.type == BT_DERIVED
11795               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
11796               && !gfc_check_access (nl->sym->ts.u.derived->attr.private_comp
11797                                         ? ACCESS_PRIVATE : ACCESS_UNKNOWN,
11798                                         nl->sym->ns->default_access))
11799             {
11800               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
11801                          "cannot be a member of PUBLIC namelist '%s' at %L",
11802                          nl->sym->name, sym->name, &sym->declared_at);
11803               return FAILURE;
11804             }
11805         }
11806     }
11807
11808
11809   /* 14.1.2 A module or internal procedure represent local entities
11810      of the same type as a namelist member and so are not allowed.  */
11811   for (nl = sym->namelist; nl; nl = nl->next)
11812     {
11813       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
11814         continue;
11815
11816       if (nl->sym->attr.function && nl->sym == nl->sym->result)
11817         if ((nl->sym == sym->ns->proc_name)
11818                ||
11819             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
11820           continue;
11821
11822       nlsym = NULL;
11823       if (nl->sym && nl->sym->name)
11824         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
11825       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
11826         {
11827           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
11828                      "attribute in '%s' at %L", nlsym->name,
11829                      &sym->declared_at);
11830           return FAILURE;
11831         }
11832     }
11833
11834   return SUCCESS;
11835 }
11836
11837
11838 static gfc_try
11839 resolve_fl_parameter (gfc_symbol *sym)
11840 {
11841   /* A parameter array's shape needs to be constant.  */
11842   if (sym->as != NULL 
11843       && (sym->as->type == AS_DEFERRED
11844           || is_non_constant_shape_array (sym)))
11845     {
11846       gfc_error ("Parameter array '%s' at %L cannot be automatic "
11847                  "or of deferred shape", sym->name, &sym->declared_at);
11848       return FAILURE;
11849     }
11850
11851   /* Make sure a parameter that has been implicitly typed still
11852      matches the implicit type, since PARAMETER statements can precede
11853      IMPLICIT statements.  */
11854   if (sym->attr.implicit_type
11855       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
11856                                                              sym->ns)))
11857     {
11858       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
11859                  "later IMPLICIT type", sym->name, &sym->declared_at);
11860       return FAILURE;
11861     }
11862
11863   /* Make sure the types of derived parameters are consistent.  This
11864      type checking is deferred until resolution because the type may
11865      refer to a derived type from the host.  */
11866   if (sym->ts.type == BT_DERIVED
11867       && !gfc_compare_types (&sym->ts, &sym->value->ts))
11868     {
11869       gfc_error ("Incompatible derived type in PARAMETER at %L",
11870                  &sym->value->where);
11871       return FAILURE;
11872     }
11873   return SUCCESS;
11874 }
11875
11876
11877 /* Do anything necessary to resolve a symbol.  Right now, we just
11878    assume that an otherwise unknown symbol is a variable.  This sort
11879    of thing commonly happens for symbols in module.  */
11880
11881 static void
11882 resolve_symbol (gfc_symbol *sym)
11883 {
11884   int check_constant, mp_flag;
11885   gfc_symtree *symtree;
11886   gfc_symtree *this_symtree;
11887   gfc_namespace *ns;
11888   gfc_component *c;
11889
11890   /* Avoid double resolution of function result symbols.  */
11891   if ((sym->result || sym->attr.result) && !sym->attr.dummy
11892       && (sym->ns != gfc_current_ns))
11893     return;
11894   
11895   if (sym->attr.flavor == FL_UNKNOWN)
11896     {
11897
11898     /* If we find that a flavorless symbol is an interface in one of the
11899        parent namespaces, find its symtree in this namespace, free the
11900        symbol and set the symtree to point to the interface symbol.  */
11901       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
11902         {
11903           symtree = gfc_find_symtree (ns->sym_root, sym->name);
11904           if (symtree && (symtree->n.sym->generic ||
11905                           (symtree->n.sym->attr.flavor == FL_PROCEDURE
11906                            && sym->ns->construct_entities)))
11907             {
11908               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
11909                                                sym->name);
11910               gfc_release_symbol (sym);
11911               symtree->n.sym->refs++;
11912               this_symtree->n.sym = symtree->n.sym;
11913               return;
11914             }
11915         }
11916
11917       /* Otherwise give it a flavor according to such attributes as
11918          it has.  */
11919       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
11920         sym->attr.flavor = FL_VARIABLE;
11921       else
11922         {
11923           sym->attr.flavor = FL_PROCEDURE;
11924           if (sym->attr.dimension)
11925             sym->attr.function = 1;
11926         }
11927     }
11928
11929   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
11930     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
11931
11932   if (sym->attr.procedure && sym->ts.interface
11933       && sym->attr.if_source != IFSRC_DECL
11934       && resolve_procedure_interface (sym) == FAILURE)
11935     return;
11936
11937   if (sym->attr.is_protected && !sym->attr.proc_pointer
11938       && (sym->attr.procedure || sym->attr.external))
11939     {
11940       if (sym->attr.external)
11941         gfc_error ("PROTECTED attribute conflicts with EXTERNAL attribute "
11942                    "at %L", &sym->declared_at);
11943       else
11944         gfc_error ("PROCEDURE attribute conflicts with PROTECTED attribute "
11945                    "at %L", &sym->declared_at);
11946
11947       return;
11948     }
11949
11950
11951   /* F2008, C530. */
11952   if (sym->attr.contiguous
11953       && (!sym->attr.dimension || (sym->as->type != AS_ASSUMED_SHAPE
11954                                    && !sym->attr.pointer)))
11955     {
11956       gfc_error ("'%s' at %L has the CONTIGUOUS attribute but is not an "
11957                   "array pointer or an assumed-shape array", sym->name,
11958                   &sym->declared_at);
11959       return;
11960     }
11961
11962   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
11963     return;
11964
11965   /* Symbols that are module procedures with results (functions) have
11966      the types and array specification copied for type checking in
11967      procedures that call them, as well as for saving to a module
11968      file.  These symbols can't stand the scrutiny that their results
11969      can.  */
11970   mp_flag = (sym->result != NULL && sym->result != sym);
11971
11972   /* Make sure that the intrinsic is consistent with its internal 
11973      representation. This needs to be done before assigning a default 
11974      type to avoid spurious warnings.  */
11975   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
11976       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
11977     return;
11978
11979   /* Resolve associate names.  */
11980   if (sym->assoc)
11981     resolve_assoc_var (sym, true);
11982
11983   /* Assign default type to symbols that need one and don't have one.  */
11984   if (sym->ts.type == BT_UNKNOWN)
11985     {
11986       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
11987         gfc_set_default_type (sym, 1, NULL);
11988
11989       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
11990           && !sym->attr.function && !sym->attr.subroutine
11991           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
11992         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
11993
11994       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
11995         {
11996           /* The specific case of an external procedure should emit an error
11997              in the case that there is no implicit type.  */
11998           if (!mp_flag)
11999             gfc_set_default_type (sym, sym->attr.external, NULL);
12000           else
12001             {
12002               /* Result may be in another namespace.  */
12003               resolve_symbol (sym->result);
12004
12005               if (!sym->result->attr.proc_pointer)
12006                 {
12007                   sym->ts = sym->result->ts;
12008                   sym->as = gfc_copy_array_spec (sym->result->as);
12009                   sym->attr.dimension = sym->result->attr.dimension;
12010                   sym->attr.pointer = sym->result->attr.pointer;
12011                   sym->attr.allocatable = sym->result->attr.allocatable;
12012                   sym->attr.contiguous = sym->result->attr.contiguous;
12013                 }
12014             }
12015         }
12016     }
12017
12018   /* Assumed size arrays and assumed shape arrays must be dummy
12019      arguments.  Array-spec's of implied-shape should have been resolved to
12020      AS_EXPLICIT already.  */
12021
12022   if (sym->as)
12023     {
12024       gcc_assert (sym->as->type != AS_IMPLIED_SHAPE);
12025       if (((sym->as->type == AS_ASSUMED_SIZE && !sym->as->cp_was_assumed)
12026            || sym->as->type == AS_ASSUMED_SHAPE)
12027           && sym->attr.dummy == 0)
12028         {
12029           if (sym->as->type == AS_ASSUMED_SIZE)
12030             gfc_error ("Assumed size array at %L must be a dummy argument",
12031                        &sym->declared_at);
12032           else
12033             gfc_error ("Assumed shape array at %L must be a dummy argument",
12034                        &sym->declared_at);
12035           return;
12036         }
12037     }
12038
12039   /* Make sure symbols with known intent or optional are really dummy
12040      variable.  Because of ENTRY statement, this has to be deferred
12041      until resolution time.  */
12042
12043   if (!sym->attr.dummy
12044       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
12045     {
12046       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
12047       return;
12048     }
12049
12050   if (sym->attr.value && !sym->attr.dummy)
12051     {
12052       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
12053                  "it is not a dummy argument", sym->name, &sym->declared_at);
12054       return;
12055     }
12056
12057   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
12058     {
12059       gfc_charlen *cl = sym->ts.u.cl;
12060       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
12061         {
12062           gfc_error ("Character dummy variable '%s' at %L with VALUE "
12063                      "attribute must have constant length",
12064                      sym->name, &sym->declared_at);
12065           return;
12066         }
12067
12068       if (sym->ts.is_c_interop
12069           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
12070         {
12071           gfc_error ("C interoperable character dummy variable '%s' at %L "
12072                      "with VALUE attribute must have length one",
12073                      sym->name, &sym->declared_at);
12074           return;
12075         }
12076     }
12077
12078   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
12079      do this for something that was implicitly typed because that is handled
12080      in gfc_set_default_type.  Handle dummy arguments and procedure
12081      definitions separately.  Also, anything that is use associated is not
12082      handled here but instead is handled in the module it is declared in.
12083      Finally, derived type definitions are allowed to be BIND(C) since that
12084      only implies that they're interoperable, and they are checked fully for
12085      interoperability when a variable is declared of that type.  */
12086   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
12087       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
12088       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
12089     {
12090       gfc_try t = SUCCESS;
12091       
12092       /* First, make sure the variable is declared at the
12093          module-level scope (J3/04-007, Section 15.3).  */
12094       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
12095           sym->attr.in_common == 0)
12096         {
12097           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
12098                      "is neither a COMMON block nor declared at the "
12099                      "module level scope", sym->name, &(sym->declared_at));
12100           t = FAILURE;
12101         }
12102       else if (sym->common_head != NULL)
12103         {
12104           t = verify_com_block_vars_c_interop (sym->common_head);
12105         }
12106       else
12107         {
12108           /* If type() declaration, we need to verify that the components
12109              of the given type are all C interoperable, etc.  */
12110           if (sym->ts.type == BT_DERIVED &&
12111               sym->ts.u.derived->attr.is_c_interop != 1)
12112             {
12113               /* Make sure the user marked the derived type as BIND(C).  If
12114                  not, call the verify routine.  This could print an error
12115                  for the derived type more than once if multiple variables
12116                  of that type are declared.  */
12117               if (sym->ts.u.derived->attr.is_bind_c != 1)
12118                 verify_bind_c_derived_type (sym->ts.u.derived);
12119               t = FAILURE;
12120             }
12121           
12122           /* Verify the variable itself as C interoperable if it
12123              is BIND(C).  It is not possible for this to succeed if
12124              the verify_bind_c_derived_type failed, so don't have to handle
12125              any error returned by verify_bind_c_derived_type.  */
12126           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
12127                                  sym->common_block);
12128         }
12129
12130       if (t == FAILURE)
12131         {
12132           /* clear the is_bind_c flag to prevent reporting errors more than
12133              once if something failed.  */
12134           sym->attr.is_bind_c = 0;
12135           return;
12136         }
12137     }
12138
12139   /* If a derived type symbol has reached this point, without its
12140      type being declared, we have an error.  Notice that most
12141      conditions that produce undefined derived types have already
12142      been dealt with.  However, the likes of:
12143      implicit type(t) (t) ..... call foo (t) will get us here if
12144      the type is not declared in the scope of the implicit
12145      statement. Change the type to BT_UNKNOWN, both because it is so
12146      and to prevent an ICE.  */
12147   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->components == NULL
12148       && !sym->ts.u.derived->attr.zero_comp)
12149     {
12150       gfc_error ("The derived type '%s' at %L is of type '%s', "
12151                  "which has not been defined", sym->name,
12152                   &sym->declared_at, sym->ts.u.derived->name);
12153       sym->ts.type = BT_UNKNOWN;
12154       return;
12155     }
12156
12157   /* Make sure that the derived type has been resolved and that the
12158      derived type is visible in the symbol's namespace, if it is a
12159      module function and is not PRIVATE.  */
12160   if (sym->ts.type == BT_DERIVED
12161         && sym->ts.u.derived->attr.use_assoc
12162         && sym->ns->proc_name
12163         && sym->ns->proc_name->attr.flavor == FL_MODULE)
12164     {
12165       gfc_symbol *ds;
12166
12167       if (resolve_fl_derived (sym->ts.u.derived) == FAILURE)
12168         return;
12169
12170       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 1, &ds);
12171       if (!ds && sym->attr.function
12172             && gfc_check_access (sym->attr.access, sym->ns->default_access))
12173         {
12174           symtree = gfc_new_symtree (&sym->ns->sym_root,
12175                                      sym->ts.u.derived->name);
12176           symtree->n.sym = sym->ts.u.derived;
12177           sym->ts.u.derived->refs++;
12178         }
12179     }
12180
12181   /* Unless the derived-type declaration is use associated, Fortran 95
12182      does not allow public entries of private derived types.
12183      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
12184      161 in 95-006r3.  */
12185   if (sym->ts.type == BT_DERIVED
12186       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
12187       && !sym->ts.u.derived->attr.use_assoc
12188       && gfc_check_access (sym->attr.access, sym->ns->default_access)
12189       && !gfc_check_access (sym->ts.u.derived->attr.access,
12190                             sym->ts.u.derived->ns->default_access)
12191       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
12192                          "of PRIVATE derived type '%s'",
12193                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
12194                          : "variable", sym->name, &sym->declared_at,
12195                          sym->ts.u.derived->name) == FAILURE)
12196     return;
12197
12198   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
12199      default initialization is defined (5.1.2.4.4).  */
12200   if (sym->ts.type == BT_DERIVED
12201       && sym->attr.dummy
12202       && sym->attr.intent == INTENT_OUT
12203       && sym->as
12204       && sym->as->type == AS_ASSUMED_SIZE)
12205     {
12206       for (c = sym->ts.u.derived->components; c; c = c->next)
12207         {
12208           if (c->initializer)
12209             {
12210               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
12211                          "ASSUMED SIZE and so cannot have a default initializer",
12212                          sym->name, &sym->declared_at);
12213               return;
12214             }
12215         }
12216     }
12217
12218   /* F2008, C526.  */
12219   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12220        || sym->attr.codimension)
12221       && sym->attr.result)
12222     gfc_error ("Function result '%s' at %L shall not be a coarray or have "
12223                "a coarray component", sym->name, &sym->declared_at);
12224
12225   /* F2008, C524.  */
12226   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
12227       && sym->ts.u.derived->ts.is_iso_c)
12228     gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
12229                "shall not be a coarray", sym->name, &sym->declared_at);
12230
12231   /* F2008, C525.  */
12232   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp
12233       && (sym->attr.codimension || sym->attr.pointer || sym->attr.dimension
12234           || sym->attr.allocatable))
12235     gfc_error ("Variable '%s' at %L with coarray component "
12236                "shall be a nonpointer, nonallocatable scalar",
12237                sym->name, &sym->declared_at);
12238
12239   /* F2008, C526.  The function-result case was handled above.  */
12240   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12241        || sym->attr.codimension)
12242       && !(sym->attr.allocatable || sym->attr.dummy || sym->attr.save
12243            || sym->ns->proc_name->attr.flavor == FL_MODULE
12244            || sym->ns->proc_name->attr.is_main_program
12245            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
12246     gfc_error ("Variable '%s' at %L is a coarray or has a coarray "
12247                "component and is not ALLOCATABLE, SAVE nor a "
12248                "dummy argument", sym->name, &sym->declared_at);
12249   /* F2008, C528.  */  /* FIXME: sym->as check due to PR 43412.  */
12250   else if (sym->attr.codimension && !sym->attr.allocatable
12251       && sym->as && sym->as->cotype == AS_DEFERRED)
12252     gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
12253                 "deferred shape", sym->name, &sym->declared_at);
12254   else if (sym->attr.codimension && sym->attr.allocatable
12255       && (sym->as->type != AS_DEFERRED || sym->as->cotype != AS_DEFERRED))
12256     gfc_error ("Allocatable coarray variable '%s' at %L must have "
12257                "deferred shape", sym->name, &sym->declared_at);
12258
12259
12260   /* F2008, C541.  */
12261   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12262        || (sym->attr.codimension && sym->attr.allocatable))
12263       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
12264     gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
12265                "allocatable coarray or have coarray components",
12266                sym->name, &sym->declared_at);
12267
12268   if (sym->attr.codimension && sym->attr.dummy
12269       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
12270     gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
12271                "procedure '%s'", sym->name, &sym->declared_at,
12272                sym->ns->proc_name->name);
12273
12274   switch (sym->attr.flavor)
12275     {
12276     case FL_VARIABLE:
12277       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
12278         return;
12279       break;
12280
12281     case FL_PROCEDURE:
12282       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
12283         return;
12284       break;
12285
12286     case FL_NAMELIST:
12287       if (resolve_fl_namelist (sym) == FAILURE)
12288         return;
12289       break;
12290
12291     case FL_PARAMETER:
12292       if (resolve_fl_parameter (sym) == FAILURE)
12293         return;
12294       break;
12295
12296     default:
12297       break;
12298     }
12299
12300   /* Resolve array specifier. Check as well some constraints
12301      on COMMON blocks.  */
12302
12303   check_constant = sym->attr.in_common && !sym->attr.pointer;
12304
12305   /* Set the formal_arg_flag so that check_conflict will not throw
12306      an error for host associated variables in the specification
12307      expression for an array_valued function.  */
12308   if (sym->attr.function && sym->as)
12309     formal_arg_flag = 1;
12310
12311   gfc_resolve_array_spec (sym->as, check_constant);
12312
12313   formal_arg_flag = 0;
12314
12315   /* Resolve formal namespaces.  */
12316   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
12317       && !sym->attr.contained && !sym->attr.intrinsic)
12318     gfc_resolve (sym->formal_ns);
12319
12320   /* Make sure the formal namespace is present.  */
12321   if (sym->formal && !sym->formal_ns)
12322     {
12323       gfc_formal_arglist *formal = sym->formal;
12324       while (formal && !formal->sym)
12325         formal = formal->next;
12326
12327       if (formal)
12328         {
12329           sym->formal_ns = formal->sym->ns;
12330           sym->formal_ns->refs++;
12331         }
12332     }
12333
12334   /* Check threadprivate restrictions.  */
12335   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
12336       && (!sym->attr.in_common
12337           && sym->module == NULL
12338           && (sym->ns->proc_name == NULL
12339               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
12340     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
12341
12342   /* If we have come this far we can apply default-initializers, as
12343      described in 14.7.5, to those variables that have not already
12344      been assigned one.  */
12345   if (sym->ts.type == BT_DERIVED
12346       && sym->ns == gfc_current_ns
12347       && !sym->value
12348       && !sym->attr.allocatable
12349       && !sym->attr.alloc_comp)
12350     {
12351       symbol_attribute *a = &sym->attr;
12352
12353       if ((!a->save && !a->dummy && !a->pointer
12354            && !a->in_common && !a->use_assoc
12355            && (a->referenced || a->result)
12356            && !(a->function && sym != sym->result))
12357           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
12358         apply_default_init (sym);
12359     }
12360
12361   if (sym->ts.type == BT_CLASS && sym->ns == gfc_current_ns
12362       && sym->attr.dummy && sym->attr.intent == INTENT_OUT
12363       && !CLASS_DATA (sym)->attr.class_pointer
12364       && !CLASS_DATA (sym)->attr.allocatable)
12365     apply_default_init (sym);
12366
12367   /* If this symbol has a type-spec, check it.  */
12368   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
12369       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
12370     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
12371           == FAILURE)
12372       return;
12373 }
12374
12375
12376 /************* Resolve DATA statements *************/
12377
12378 static struct
12379 {
12380   gfc_data_value *vnode;
12381   mpz_t left;
12382 }
12383 values;
12384
12385
12386 /* Advance the values structure to point to the next value in the data list.  */
12387
12388 static gfc_try
12389 next_data_value (void)
12390 {
12391   while (mpz_cmp_ui (values.left, 0) == 0)
12392     {
12393
12394       if (values.vnode->next == NULL)
12395         return FAILURE;
12396
12397       values.vnode = values.vnode->next;
12398       mpz_set (values.left, values.vnode->repeat);
12399     }
12400
12401   return SUCCESS;
12402 }
12403
12404
12405 static gfc_try
12406 check_data_variable (gfc_data_variable *var, locus *where)
12407 {
12408   gfc_expr *e;
12409   mpz_t size;
12410   mpz_t offset;
12411   gfc_try t;
12412   ar_type mark = AR_UNKNOWN;
12413   int i;
12414   mpz_t section_index[GFC_MAX_DIMENSIONS];
12415   gfc_ref *ref;
12416   gfc_array_ref *ar;
12417   gfc_symbol *sym;
12418   int has_pointer;
12419
12420   if (gfc_resolve_expr (var->expr) == FAILURE)
12421     return FAILURE;
12422
12423   ar = NULL;
12424   mpz_init_set_si (offset, 0);
12425   e = var->expr;
12426
12427   if (e->expr_type != EXPR_VARIABLE)
12428     gfc_internal_error ("check_data_variable(): Bad expression");
12429
12430   sym = e->symtree->n.sym;
12431
12432   if (sym->ns->is_block_data && !sym->attr.in_common)
12433     {
12434       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
12435                  sym->name, &sym->declared_at);
12436     }
12437
12438   if (e->ref == NULL && sym->as)
12439     {
12440       gfc_error ("DATA array '%s' at %L must be specified in a previous"
12441                  " declaration", sym->name, where);
12442       return FAILURE;
12443     }
12444
12445   has_pointer = sym->attr.pointer;
12446
12447   for (ref = e->ref; ref; ref = ref->next)
12448     {
12449       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
12450         has_pointer = 1;
12451
12452       if (ref->type == REF_ARRAY && ref->u.ar.codimen)
12453         {
12454           gfc_error ("DATA element '%s' at %L cannot have a coindex",
12455                      sym->name, where);
12456           return FAILURE;
12457         }
12458
12459       if (has_pointer
12460             && ref->type == REF_ARRAY
12461             && ref->u.ar.type != AR_FULL)
12462           {
12463             gfc_error ("DATA element '%s' at %L is a pointer and so must "
12464                         "be a full array", sym->name, where);
12465             return FAILURE;
12466           }
12467     }
12468
12469   if (e->rank == 0 || has_pointer)
12470     {
12471       mpz_init_set_ui (size, 1);
12472       ref = NULL;
12473     }
12474   else
12475     {
12476       ref = e->ref;
12477
12478       /* Find the array section reference.  */
12479       for (ref = e->ref; ref; ref = ref->next)
12480         {
12481           if (ref->type != REF_ARRAY)
12482             continue;
12483           if (ref->u.ar.type == AR_ELEMENT)
12484             continue;
12485           break;
12486         }
12487       gcc_assert (ref);
12488
12489       /* Set marks according to the reference pattern.  */
12490       switch (ref->u.ar.type)
12491         {
12492         case AR_FULL:
12493           mark = AR_FULL;
12494           break;
12495
12496         case AR_SECTION:
12497           ar = &ref->u.ar;
12498           /* Get the start position of array section.  */
12499           gfc_get_section_index (ar, section_index, &offset);
12500           mark = AR_SECTION;
12501           break;
12502
12503         default:
12504           gcc_unreachable ();
12505         }
12506
12507       if (gfc_array_size (e, &size) == FAILURE)
12508         {
12509           gfc_error ("Nonconstant array section at %L in DATA statement",
12510                      &e->where);
12511           mpz_clear (offset);
12512           return FAILURE;
12513         }
12514     }
12515
12516   t = SUCCESS;
12517
12518   while (mpz_cmp_ui (size, 0) > 0)
12519     {
12520       if (next_data_value () == FAILURE)
12521         {
12522           gfc_error ("DATA statement at %L has more variables than values",
12523                      where);
12524           t = FAILURE;
12525           break;
12526         }
12527
12528       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
12529       if (t == FAILURE)
12530         break;
12531
12532       /* If we have more than one element left in the repeat count,
12533          and we have more than one element left in the target variable,
12534          then create a range assignment.  */
12535       /* FIXME: Only done for full arrays for now, since array sections
12536          seem tricky.  */
12537       if (mark == AR_FULL && ref && ref->next == NULL
12538           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
12539         {
12540           mpz_t range;
12541
12542           if (mpz_cmp (size, values.left) >= 0)
12543             {
12544               mpz_init_set (range, values.left);
12545               mpz_sub (size, size, values.left);
12546               mpz_set_ui (values.left, 0);
12547             }
12548           else
12549             {
12550               mpz_init_set (range, size);
12551               mpz_sub (values.left, values.left, size);
12552               mpz_set_ui (size, 0);
12553             }
12554
12555           t = gfc_assign_data_value_range (var->expr, values.vnode->expr,
12556                                            offset, range);
12557
12558           mpz_add (offset, offset, range);
12559           mpz_clear (range);
12560
12561           if (t == FAILURE)
12562             break;
12563         }
12564
12565       /* Assign initial value to symbol.  */
12566       else
12567         {
12568           mpz_sub_ui (values.left, values.left, 1);
12569           mpz_sub_ui (size, size, 1);
12570
12571           t = gfc_assign_data_value (var->expr, values.vnode->expr, offset);
12572           if (t == FAILURE)
12573             break;
12574
12575           if (mark == AR_FULL)
12576             mpz_add_ui (offset, offset, 1);
12577
12578           /* Modify the array section indexes and recalculate the offset
12579              for next element.  */
12580           else if (mark == AR_SECTION)
12581             gfc_advance_section (section_index, ar, &offset);
12582         }
12583     }
12584
12585   if (mark == AR_SECTION)
12586     {
12587       for (i = 0; i < ar->dimen; i++)
12588         mpz_clear (section_index[i]);
12589     }
12590
12591   mpz_clear (size);
12592   mpz_clear (offset);
12593
12594   return t;
12595 }
12596
12597
12598 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
12599
12600 /* Iterate over a list of elements in a DATA statement.  */
12601
12602 static gfc_try
12603 traverse_data_list (gfc_data_variable *var, locus *where)
12604 {
12605   mpz_t trip;
12606   iterator_stack frame;
12607   gfc_expr *e, *start, *end, *step;
12608   gfc_try retval = SUCCESS;
12609
12610   mpz_init (frame.value);
12611   mpz_init (trip);
12612
12613   start = gfc_copy_expr (var->iter.start);
12614   end = gfc_copy_expr (var->iter.end);
12615   step = gfc_copy_expr (var->iter.step);
12616
12617   if (gfc_simplify_expr (start, 1) == FAILURE
12618       || start->expr_type != EXPR_CONSTANT)
12619     {
12620       gfc_error ("start of implied-do loop at %L could not be "
12621                  "simplified to a constant value", &start->where);
12622       retval = FAILURE;
12623       goto cleanup;
12624     }
12625   if (gfc_simplify_expr (end, 1) == FAILURE
12626       || end->expr_type != EXPR_CONSTANT)
12627     {
12628       gfc_error ("end of implied-do loop at %L could not be "
12629                  "simplified to a constant value", &start->where);
12630       retval = FAILURE;
12631       goto cleanup;
12632     }
12633   if (gfc_simplify_expr (step, 1) == FAILURE
12634       || step->expr_type != EXPR_CONSTANT)
12635     {
12636       gfc_error ("step of implied-do loop at %L could not be "
12637                  "simplified to a constant value", &start->where);
12638       retval = FAILURE;
12639       goto cleanup;
12640     }
12641
12642   mpz_set (trip, end->value.integer);
12643   mpz_sub (trip, trip, start->value.integer);
12644   mpz_add (trip, trip, step->value.integer);
12645
12646   mpz_div (trip, trip, step->value.integer);
12647
12648   mpz_set (frame.value, start->value.integer);
12649
12650   frame.prev = iter_stack;
12651   frame.variable = var->iter.var->symtree;
12652   iter_stack = &frame;
12653
12654   while (mpz_cmp_ui (trip, 0) > 0)
12655     {
12656       if (traverse_data_var (var->list, where) == FAILURE)
12657         {
12658           retval = FAILURE;
12659           goto cleanup;
12660         }
12661
12662       e = gfc_copy_expr (var->expr);
12663       if (gfc_simplify_expr (e, 1) == FAILURE)
12664         {
12665           gfc_free_expr (e);
12666           retval = FAILURE;
12667           goto cleanup;
12668         }
12669
12670       mpz_add (frame.value, frame.value, step->value.integer);
12671
12672       mpz_sub_ui (trip, trip, 1);
12673     }
12674
12675 cleanup:
12676   mpz_clear (frame.value);
12677   mpz_clear (trip);
12678
12679   gfc_free_expr (start);
12680   gfc_free_expr (end);
12681   gfc_free_expr (step);
12682
12683   iter_stack = frame.prev;
12684   return retval;
12685 }
12686
12687
12688 /* Type resolve variables in the variable list of a DATA statement.  */
12689
12690 static gfc_try
12691 traverse_data_var (gfc_data_variable *var, locus *where)
12692 {
12693   gfc_try t;
12694
12695   for (; var; var = var->next)
12696     {
12697       if (var->expr == NULL)
12698         t = traverse_data_list (var, where);
12699       else
12700         t = check_data_variable (var, where);
12701
12702       if (t == FAILURE)
12703         return FAILURE;
12704     }
12705
12706   return SUCCESS;
12707 }
12708
12709
12710 /* Resolve the expressions and iterators associated with a data statement.
12711    This is separate from the assignment checking because data lists should
12712    only be resolved once.  */
12713
12714 static gfc_try
12715 resolve_data_variables (gfc_data_variable *d)
12716 {
12717   for (; d; d = d->next)
12718     {
12719       if (d->list == NULL)
12720         {
12721           if (gfc_resolve_expr (d->expr) == FAILURE)
12722             return FAILURE;
12723         }
12724       else
12725         {
12726           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
12727             return FAILURE;
12728
12729           if (resolve_data_variables (d->list) == FAILURE)
12730             return FAILURE;
12731         }
12732     }
12733
12734   return SUCCESS;
12735 }
12736
12737
12738 /* Resolve a single DATA statement.  We implement this by storing a pointer to
12739    the value list into static variables, and then recursively traversing the
12740    variables list, expanding iterators and such.  */
12741
12742 static void
12743 resolve_data (gfc_data *d)
12744 {
12745
12746   if (resolve_data_variables (d->var) == FAILURE)
12747     return;
12748
12749   values.vnode = d->value;
12750   if (d->value == NULL)
12751     mpz_set_ui (values.left, 0);
12752   else
12753     mpz_set (values.left, d->value->repeat);
12754
12755   if (traverse_data_var (d->var, &d->where) == FAILURE)
12756     return;
12757
12758   /* At this point, we better not have any values left.  */
12759
12760   if (next_data_value () == SUCCESS)
12761     gfc_error ("DATA statement at %L has more values than variables",
12762                &d->where);
12763 }
12764
12765
12766 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
12767    accessed by host or use association, is a dummy argument to a pure function,
12768    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
12769    is storage associated with any such variable, shall not be used in the
12770    following contexts: (clients of this function).  */
12771
12772 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
12773    procedure.  Returns zero if assignment is OK, nonzero if there is a
12774    problem.  */
12775 int
12776 gfc_impure_variable (gfc_symbol *sym)
12777 {
12778   gfc_symbol *proc;
12779   gfc_namespace *ns;
12780
12781   if (sym->attr.use_assoc || sym->attr.in_common)
12782     return 1;
12783
12784   /* Check if the symbol's ns is inside the pure procedure.  */
12785   for (ns = gfc_current_ns; ns; ns = ns->parent)
12786     {
12787       if (ns == sym->ns)
12788         break;
12789       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
12790         return 1;
12791     }
12792
12793   proc = sym->ns->proc_name;
12794   if (sym->attr.dummy && gfc_pure (proc)
12795         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
12796                 ||
12797              proc->attr.function))
12798     return 1;
12799
12800   /* TODO: Sort out what can be storage associated, if anything, and include
12801      it here.  In principle equivalences should be scanned but it does not
12802      seem to be possible to storage associate an impure variable this way.  */
12803   return 0;
12804 }
12805
12806
12807 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
12808    current namespace is inside a pure procedure.  */
12809
12810 int
12811 gfc_pure (gfc_symbol *sym)
12812 {
12813   symbol_attribute attr;
12814   gfc_namespace *ns;
12815
12816   if (sym == NULL)
12817     {
12818       /* Check if the current namespace or one of its parents
12819         belongs to a pure procedure.  */
12820       for (ns = gfc_current_ns; ns; ns = ns->parent)
12821         {
12822           sym = ns->proc_name;
12823           if (sym == NULL)
12824             return 0;
12825           attr = sym->attr;
12826           if (attr.flavor == FL_PROCEDURE && attr.pure)
12827             return 1;
12828         }
12829       return 0;
12830     }
12831
12832   attr = sym->attr;
12833
12834   return attr.flavor == FL_PROCEDURE && attr.pure;
12835 }
12836
12837
12838 /* Test whether a symbol is implicitly pure or not.  For a NULL pointer,
12839    checks if the current namespace is implicitly pure.  Note that this
12840    function returns false for a PURE procedure.  */
12841
12842 int
12843 gfc_implicit_pure (gfc_symbol *sym)
12844 {
12845   symbol_attribute attr;
12846
12847   if (sym == NULL)
12848     {
12849       /* Check if the current namespace is implicit_pure.  */
12850       sym = gfc_current_ns->proc_name;
12851       if (sym == NULL)
12852         return 0;
12853       attr = sym->attr;
12854       if (attr.flavor == FL_PROCEDURE
12855             && attr.implicit_pure && !attr.pure)
12856         return 1;
12857       return 0;
12858     }
12859
12860   attr = sym->attr;
12861
12862   return attr.flavor == FL_PROCEDURE && attr.implicit_pure && !attr.pure;
12863 }
12864
12865
12866 /* Test whether the current procedure is elemental or not.  */
12867
12868 int
12869 gfc_elemental (gfc_symbol *sym)
12870 {
12871   symbol_attribute attr;
12872
12873   if (sym == NULL)
12874     sym = gfc_current_ns->proc_name;
12875   if (sym == NULL)
12876     return 0;
12877   attr = sym->attr;
12878
12879   return attr.flavor == FL_PROCEDURE && attr.elemental;
12880 }
12881
12882
12883 /* Warn about unused labels.  */
12884
12885 static void
12886 warn_unused_fortran_label (gfc_st_label *label)
12887 {
12888   if (label == NULL)
12889     return;
12890
12891   warn_unused_fortran_label (label->left);
12892
12893   if (label->defined == ST_LABEL_UNKNOWN)
12894     return;
12895
12896   switch (label->referenced)
12897     {
12898     case ST_LABEL_UNKNOWN:
12899       gfc_warning ("Label %d at %L defined but not used", label->value,
12900                    &label->where);
12901       break;
12902
12903     case ST_LABEL_BAD_TARGET:
12904       gfc_warning ("Label %d at %L defined but cannot be used",
12905                    label->value, &label->where);
12906       break;
12907
12908     default:
12909       break;
12910     }
12911
12912   warn_unused_fortran_label (label->right);
12913 }
12914
12915
12916 /* Returns the sequence type of a symbol or sequence.  */
12917
12918 static seq_type
12919 sequence_type (gfc_typespec ts)
12920 {
12921   seq_type result;
12922   gfc_component *c;
12923
12924   switch (ts.type)
12925   {
12926     case BT_DERIVED:
12927
12928       if (ts.u.derived->components == NULL)
12929         return SEQ_NONDEFAULT;
12930
12931       result = sequence_type (ts.u.derived->components->ts);
12932       for (c = ts.u.derived->components->next; c; c = c->next)
12933         if (sequence_type (c->ts) != result)
12934           return SEQ_MIXED;
12935
12936       return result;
12937
12938     case BT_CHARACTER:
12939       if (ts.kind != gfc_default_character_kind)
12940           return SEQ_NONDEFAULT;
12941
12942       return SEQ_CHARACTER;
12943
12944     case BT_INTEGER:
12945       if (ts.kind != gfc_default_integer_kind)
12946           return SEQ_NONDEFAULT;
12947
12948       return SEQ_NUMERIC;
12949
12950     case BT_REAL:
12951       if (!(ts.kind == gfc_default_real_kind
12952             || ts.kind == gfc_default_double_kind))
12953           return SEQ_NONDEFAULT;
12954
12955       return SEQ_NUMERIC;
12956
12957     case BT_COMPLEX:
12958       if (ts.kind != gfc_default_complex_kind)
12959           return SEQ_NONDEFAULT;
12960
12961       return SEQ_NUMERIC;
12962
12963     case BT_LOGICAL:
12964       if (ts.kind != gfc_default_logical_kind)
12965           return SEQ_NONDEFAULT;
12966
12967       return SEQ_NUMERIC;
12968
12969     default:
12970       return SEQ_NONDEFAULT;
12971   }
12972 }
12973
12974
12975 /* Resolve derived type EQUIVALENCE object.  */
12976
12977 static gfc_try
12978 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
12979 {
12980   gfc_component *c = derived->components;
12981
12982   if (!derived)
12983     return SUCCESS;
12984
12985   /* Shall not be an object of nonsequence derived type.  */
12986   if (!derived->attr.sequence)
12987     {
12988       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
12989                  "attribute to be an EQUIVALENCE object", sym->name,
12990                  &e->where);
12991       return FAILURE;
12992     }
12993
12994   /* Shall not have allocatable components.  */
12995   if (derived->attr.alloc_comp)
12996     {
12997       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
12998                  "components to be an EQUIVALENCE object",sym->name,
12999                  &e->where);
13000       return FAILURE;
13001     }
13002
13003   if (sym->attr.in_common && gfc_has_default_initializer (sym->ts.u.derived))
13004     {
13005       gfc_error ("Derived type variable '%s' at %L with default "
13006                  "initialization cannot be in EQUIVALENCE with a variable "
13007                  "in COMMON", sym->name, &e->where);
13008       return FAILURE;
13009     }
13010
13011   for (; c ; c = c->next)
13012     {
13013       if (c->ts.type == BT_DERIVED
13014           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
13015         return FAILURE;
13016
13017       /* Shall not be an object of sequence derived type containing a pointer
13018          in the structure.  */
13019       if (c->attr.pointer)
13020         {
13021           gfc_error ("Derived type variable '%s' at %L with pointer "
13022                      "component(s) cannot be an EQUIVALENCE object",
13023                      sym->name, &e->where);
13024           return FAILURE;
13025         }
13026     }
13027   return SUCCESS;
13028 }
13029
13030
13031 /* Resolve equivalence object. 
13032    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
13033    an allocatable array, an object of nonsequence derived type, an object of
13034    sequence derived type containing a pointer at any level of component
13035    selection, an automatic object, a function name, an entry name, a result
13036    name, a named constant, a structure component, or a subobject of any of
13037    the preceding objects.  A substring shall not have length zero.  A
13038    derived type shall not have components with default initialization nor
13039    shall two objects of an equivalence group be initialized.
13040    Either all or none of the objects shall have an protected attribute.
13041    The simple constraints are done in symbol.c(check_conflict) and the rest
13042    are implemented here.  */
13043
13044 static void
13045 resolve_equivalence (gfc_equiv *eq)
13046 {
13047   gfc_symbol *sym;
13048   gfc_symbol *first_sym;
13049   gfc_expr *e;
13050   gfc_ref *r;
13051   locus *last_where = NULL;
13052   seq_type eq_type, last_eq_type;
13053   gfc_typespec *last_ts;
13054   int object, cnt_protected;
13055   const char *msg;
13056
13057   last_ts = &eq->expr->symtree->n.sym->ts;
13058
13059   first_sym = eq->expr->symtree->n.sym;
13060
13061   cnt_protected = 0;
13062
13063   for (object = 1; eq; eq = eq->eq, object++)
13064     {
13065       e = eq->expr;
13066
13067       e->ts = e->symtree->n.sym->ts;
13068       /* match_varspec might not know yet if it is seeing
13069          array reference or substring reference, as it doesn't
13070          know the types.  */
13071       if (e->ref && e->ref->type == REF_ARRAY)
13072         {
13073           gfc_ref *ref = e->ref;
13074           sym = e->symtree->n.sym;
13075
13076           if (sym->attr.dimension)
13077             {
13078               ref->u.ar.as = sym->as;
13079               ref = ref->next;
13080             }
13081
13082           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
13083           if (e->ts.type == BT_CHARACTER
13084               && ref
13085               && ref->type == REF_ARRAY
13086               && ref->u.ar.dimen == 1
13087               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
13088               && ref->u.ar.stride[0] == NULL)
13089             {
13090               gfc_expr *start = ref->u.ar.start[0];
13091               gfc_expr *end = ref->u.ar.end[0];
13092               void *mem = NULL;
13093
13094               /* Optimize away the (:) reference.  */
13095               if (start == NULL && end == NULL)
13096                 {
13097                   if (e->ref == ref)
13098                     e->ref = ref->next;
13099                   else
13100                     e->ref->next = ref->next;
13101                   mem = ref;
13102                 }
13103               else
13104                 {
13105                   ref->type = REF_SUBSTRING;
13106                   if (start == NULL)
13107                     start = gfc_get_int_expr (gfc_default_integer_kind,
13108                                               NULL, 1);
13109                   ref->u.ss.start = start;
13110                   if (end == NULL && e->ts.u.cl)
13111                     end = gfc_copy_expr (e->ts.u.cl->length);
13112                   ref->u.ss.end = end;
13113                   ref->u.ss.length = e->ts.u.cl;
13114                   e->ts.u.cl = NULL;
13115                 }
13116               ref = ref->next;
13117               gfc_free (mem);
13118             }
13119
13120           /* Any further ref is an error.  */
13121           if (ref)
13122             {
13123               gcc_assert (ref->type == REF_ARRAY);
13124               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
13125                          &ref->u.ar.where);
13126               continue;
13127             }
13128         }
13129
13130       if (gfc_resolve_expr (e) == FAILURE)
13131         continue;
13132
13133       sym = e->symtree->n.sym;
13134
13135       if (sym->attr.is_protected)
13136         cnt_protected++;
13137       if (cnt_protected > 0 && cnt_protected != object)
13138         {
13139               gfc_error ("Either all or none of the objects in the "
13140                          "EQUIVALENCE set at %L shall have the "
13141                          "PROTECTED attribute",
13142                          &e->where);
13143               break;
13144         }
13145
13146       /* Shall not equivalence common block variables in a PURE procedure.  */
13147       if (sym->ns->proc_name
13148           && sym->ns->proc_name->attr.pure
13149           && sym->attr.in_common)
13150         {
13151           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
13152                      "object in the pure procedure '%s'",
13153                      sym->name, &e->where, sym->ns->proc_name->name);
13154           break;
13155         }
13156
13157       /* Shall not be a named constant.  */
13158       if (e->expr_type == EXPR_CONSTANT)
13159         {
13160           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
13161                      "object", sym->name, &e->where);
13162           continue;
13163         }
13164
13165       if (e->ts.type == BT_DERIVED
13166           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
13167         continue;
13168
13169       /* Check that the types correspond correctly:
13170          Note 5.28:
13171          A numeric sequence structure may be equivalenced to another sequence
13172          structure, an object of default integer type, default real type, double
13173          precision real type, default logical type such that components of the
13174          structure ultimately only become associated to objects of the same
13175          kind. A character sequence structure may be equivalenced to an object
13176          of default character kind or another character sequence structure.
13177          Other objects may be equivalenced only to objects of the same type and
13178          kind parameters.  */
13179
13180       /* Identical types are unconditionally OK.  */
13181       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
13182         goto identical_types;
13183
13184       last_eq_type = sequence_type (*last_ts);
13185       eq_type = sequence_type (sym->ts);
13186
13187       /* Since the pair of objects is not of the same type, mixed or
13188          non-default sequences can be rejected.  */
13189
13190       msg = "Sequence %s with mixed components in EQUIVALENCE "
13191             "statement at %L with different type objects";
13192       if ((object ==2
13193            && last_eq_type == SEQ_MIXED
13194            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
13195               == FAILURE)
13196           || (eq_type == SEQ_MIXED
13197               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13198                                  &e->where) == FAILURE))
13199         continue;
13200
13201       msg = "Non-default type object or sequence %s in EQUIVALENCE "
13202             "statement at %L with objects of different type";
13203       if ((object ==2
13204            && last_eq_type == SEQ_NONDEFAULT
13205            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
13206                               last_where) == FAILURE)
13207           || (eq_type == SEQ_NONDEFAULT
13208               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13209                                  &e->where) == FAILURE))
13210         continue;
13211
13212       msg ="Non-CHARACTER object '%s' in default CHARACTER "
13213            "EQUIVALENCE statement at %L";
13214       if (last_eq_type == SEQ_CHARACTER
13215           && eq_type != SEQ_CHARACTER
13216           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13217                              &e->where) == FAILURE)
13218                 continue;
13219
13220       msg ="Non-NUMERIC object '%s' in default NUMERIC "
13221            "EQUIVALENCE statement at %L";
13222       if (last_eq_type == SEQ_NUMERIC
13223           && eq_type != SEQ_NUMERIC
13224           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13225                              &e->where) == FAILURE)
13226                 continue;
13227
13228   identical_types:
13229       last_ts =&sym->ts;
13230       last_where = &e->where;
13231
13232       if (!e->ref)
13233         continue;
13234
13235       /* Shall not be an automatic array.  */
13236       if (e->ref->type == REF_ARRAY
13237           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
13238         {
13239           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
13240                      "an EQUIVALENCE object", sym->name, &e->where);
13241           continue;
13242         }
13243
13244       r = e->ref;
13245       while (r)
13246         {
13247           /* Shall not be a structure component.  */
13248           if (r->type == REF_COMPONENT)
13249             {
13250               gfc_error ("Structure component '%s' at %L cannot be an "
13251                          "EQUIVALENCE object",
13252                          r->u.c.component->name, &e->where);
13253               break;
13254             }
13255
13256           /* A substring shall not have length zero.  */
13257           if (r->type == REF_SUBSTRING)
13258             {
13259               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
13260                 {
13261                   gfc_error ("Substring at %L has length zero",
13262                              &r->u.ss.start->where);
13263                   break;
13264                 }
13265             }
13266           r = r->next;
13267         }
13268     }
13269 }
13270
13271
13272 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
13273
13274 static void
13275 resolve_fntype (gfc_namespace *ns)
13276 {
13277   gfc_entry_list *el;
13278   gfc_symbol *sym;
13279
13280   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
13281     return;
13282
13283   /* If there are any entries, ns->proc_name is the entry master
13284      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
13285   if (ns->entries)
13286     sym = ns->entries->sym;
13287   else
13288     sym = ns->proc_name;
13289   if (sym->result == sym
13290       && sym->ts.type == BT_UNKNOWN
13291       && gfc_set_default_type (sym, 0, NULL) == FAILURE
13292       && !sym->attr.untyped)
13293     {
13294       gfc_error ("Function '%s' at %L has no IMPLICIT type",
13295                  sym->name, &sym->declared_at);
13296       sym->attr.untyped = 1;
13297     }
13298
13299   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
13300       && !sym->attr.contained
13301       && !gfc_check_access (sym->ts.u.derived->attr.access,
13302                             sym->ts.u.derived->ns->default_access)
13303       && gfc_check_access (sym->attr.access, sym->ns->default_access))
13304     {
13305       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
13306                       "%L of PRIVATE type '%s'", sym->name,
13307                       &sym->declared_at, sym->ts.u.derived->name);
13308     }
13309
13310     if (ns->entries)
13311     for (el = ns->entries->next; el; el = el->next)
13312       {
13313         if (el->sym->result == el->sym
13314             && el->sym->ts.type == BT_UNKNOWN
13315             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
13316             && !el->sym->attr.untyped)
13317           {
13318             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
13319                        el->sym->name, &el->sym->declared_at);
13320             el->sym->attr.untyped = 1;
13321           }
13322       }
13323 }
13324
13325
13326 /* 12.3.2.1.1 Defined operators.  */
13327
13328 static gfc_try
13329 check_uop_procedure (gfc_symbol *sym, locus where)
13330 {
13331   gfc_formal_arglist *formal;
13332
13333   if (!sym->attr.function)
13334     {
13335       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
13336                  sym->name, &where);
13337       return FAILURE;
13338     }
13339
13340   if (sym->ts.type == BT_CHARACTER
13341       && !(sym->ts.u.cl && sym->ts.u.cl->length)
13342       && !(sym->result && sym->result->ts.u.cl
13343            && sym->result->ts.u.cl->length))
13344     {
13345       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
13346                  "character length", sym->name, &where);
13347       return FAILURE;
13348     }
13349
13350   formal = sym->formal;
13351   if (!formal || !formal->sym)
13352     {
13353       gfc_error ("User operator procedure '%s' at %L must have at least "
13354                  "one argument", sym->name, &where);
13355       return FAILURE;
13356     }
13357
13358   if (formal->sym->attr.intent != INTENT_IN)
13359     {
13360       gfc_error ("First argument of operator interface at %L must be "
13361                  "INTENT(IN)", &where);
13362       return FAILURE;
13363     }
13364
13365   if (formal->sym->attr.optional)
13366     {
13367       gfc_error ("First argument of operator interface at %L cannot be "
13368                  "optional", &where);
13369       return FAILURE;
13370     }
13371
13372   formal = formal->next;
13373   if (!formal || !formal->sym)
13374     return SUCCESS;
13375
13376   if (formal->sym->attr.intent != INTENT_IN)
13377     {
13378       gfc_error ("Second argument of operator interface at %L must be "
13379                  "INTENT(IN)", &where);
13380       return FAILURE;
13381     }
13382
13383   if (formal->sym->attr.optional)
13384     {
13385       gfc_error ("Second argument of operator interface at %L cannot be "
13386                  "optional", &where);
13387       return FAILURE;
13388     }
13389
13390   if (formal->next)
13391     {
13392       gfc_error ("Operator interface at %L must have, at most, two "
13393                  "arguments", &where);
13394       return FAILURE;
13395     }
13396
13397   return SUCCESS;
13398 }
13399
13400 static void
13401 gfc_resolve_uops (gfc_symtree *symtree)
13402 {
13403   gfc_interface *itr;
13404
13405   if (symtree == NULL)
13406     return;
13407
13408   gfc_resolve_uops (symtree->left);
13409   gfc_resolve_uops (symtree->right);
13410
13411   for (itr = symtree->n.uop->op; itr; itr = itr->next)
13412     check_uop_procedure (itr->sym, itr->sym->declared_at);
13413 }
13414
13415
13416 /* Examine all of the expressions associated with a program unit,
13417    assign types to all intermediate expressions, make sure that all
13418    assignments are to compatible types and figure out which names
13419    refer to which functions or subroutines.  It doesn't check code
13420    block, which is handled by resolve_code.  */
13421
13422 static void
13423 resolve_types (gfc_namespace *ns)
13424 {
13425   gfc_namespace *n;
13426   gfc_charlen *cl;
13427   gfc_data *d;
13428   gfc_equiv *eq;
13429   gfc_namespace* old_ns = gfc_current_ns;
13430
13431   /* Check that all IMPLICIT types are ok.  */
13432   if (!ns->seen_implicit_none)
13433     {
13434       unsigned letter;
13435       for (letter = 0; letter != GFC_LETTERS; ++letter)
13436         if (ns->set_flag[letter]
13437             && resolve_typespec_used (&ns->default_type[letter],
13438                                       &ns->implicit_loc[letter],
13439                                       NULL) == FAILURE)
13440           return;
13441     }
13442
13443   gfc_current_ns = ns;
13444
13445   resolve_entries (ns);
13446
13447   resolve_common_vars (ns->blank_common.head, false);
13448   resolve_common_blocks (ns->common_root);
13449
13450   resolve_contained_functions (ns);
13451
13452   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
13453
13454   for (cl = ns->cl_list; cl; cl = cl->next)
13455     resolve_charlen (cl);
13456
13457   gfc_traverse_ns (ns, resolve_symbol);
13458
13459   resolve_fntype (ns);
13460
13461   for (n = ns->contained; n; n = n->sibling)
13462     {
13463       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
13464         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
13465                    "also be PURE", n->proc_name->name,
13466                    &n->proc_name->declared_at);
13467
13468       resolve_types (n);
13469     }
13470
13471   forall_flag = 0;
13472   gfc_check_interfaces (ns);
13473
13474   gfc_traverse_ns (ns, resolve_values);
13475
13476   if (ns->save_all)
13477     gfc_save_all (ns);
13478
13479   iter_stack = NULL;
13480   for (d = ns->data; d; d = d->next)
13481     resolve_data (d);
13482
13483   iter_stack = NULL;
13484   gfc_traverse_ns (ns, gfc_formalize_init_value);
13485
13486   gfc_traverse_ns (ns, gfc_verify_binding_labels);
13487
13488   if (ns->common_root != NULL)
13489     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
13490
13491   for (eq = ns->equiv; eq; eq = eq->next)
13492     resolve_equivalence (eq);
13493
13494   /* Warn about unused labels.  */
13495   if (warn_unused_label)
13496     warn_unused_fortran_label (ns->st_labels);
13497
13498   gfc_resolve_uops (ns->uop_root);
13499
13500   gfc_current_ns = old_ns;
13501 }
13502
13503
13504 /* Call resolve_code recursively.  */
13505
13506 static void
13507 resolve_codes (gfc_namespace *ns)
13508 {
13509   gfc_namespace *n;
13510   bitmap_obstack old_obstack;
13511
13512   if (ns->resolved == 1)
13513     return;
13514
13515   for (n = ns->contained; n; n = n->sibling)
13516     resolve_codes (n);
13517
13518   gfc_current_ns = ns;
13519
13520   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
13521   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
13522     cs_base = NULL;
13523
13524   /* Set to an out of range value.  */
13525   current_entry_id = -1;
13526
13527   old_obstack = labels_obstack;
13528   bitmap_obstack_initialize (&labels_obstack);
13529
13530   resolve_code (ns->code, ns);
13531
13532   bitmap_obstack_release (&labels_obstack);
13533   labels_obstack = old_obstack;
13534 }
13535
13536
13537 /* This function is called after a complete program unit has been compiled.
13538    Its purpose is to examine all of the expressions associated with a program
13539    unit, assign types to all intermediate expressions, make sure that all
13540    assignments are to compatible types and figure out which names refer to
13541    which functions or subroutines.  */
13542
13543 void
13544 gfc_resolve (gfc_namespace *ns)
13545 {
13546   gfc_namespace *old_ns;
13547   code_stack *old_cs_base;
13548
13549   if (ns->resolved)
13550     return;
13551
13552   ns->resolved = -1;
13553   old_ns = gfc_current_ns;
13554   old_cs_base = cs_base;
13555
13556   resolve_types (ns);
13557   resolve_codes (ns);
13558
13559   gfc_current_ns = old_ns;
13560   cs_base = old_cs_base;
13561   ns->resolved = 1;
13562
13563   gfc_run_passes (ns);
13564 }