OSDN Git Service

f3fce1b38ad576238e866f8819993cab005f40f2
[pf3gnuchains/gcc-fork.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    Free Software Foundation, Inc.
4    Contributed by Andy Vaught
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "flags.h"
25 #include "gfortran.h"
26 #include "obstack.h"
27 #include "bitmap.h"
28 #include "arith.h"  /* For gfc_compare_expr().  */
29 #include "dependency.h"
30 #include "data.h"
31 #include "target-memory.h" /* for gfc_simplify_transfer */
32
33 /* Types used in equivalence statements.  */
34
35 typedef enum seq_type
36 {
37   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
38 }
39 seq_type;
40
41 /* Stack to keep track of the nesting of blocks as we move through the
42    code.  See resolve_branch() and resolve_code().  */
43
44 typedef struct code_stack
45 {
46   struct gfc_code *head, *current;
47   struct code_stack *prev;
48
49   /* This bitmap keeps track of the targets valid for a branch from
50      inside this block except for END {IF|SELECT}s of enclosing
51      blocks.  */
52   bitmap reachable_labels;
53 }
54 code_stack;
55
56 static code_stack *cs_base = NULL;
57
58
59 /* Nonzero if we're inside a FORALL block.  */
60
61 static int forall_flag;
62
63 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
64
65 static int omp_workshare_flag;
66
67 /* Nonzero if we are processing a formal arglist. The corresponding function
68    resets the flag each time that it is read.  */
69 static int formal_arg_flag = 0;
70
71 /* True if we are resolving a specification expression.  */
72 static int specification_expr = 0;
73
74 /* The id of the last entry seen.  */
75 static int current_entry_id;
76
77 /* We use bitmaps to determine if a branch target is valid.  */
78 static bitmap_obstack labels_obstack;
79
80 int
81 gfc_is_formal_arg (void)
82 {
83   return formal_arg_flag;
84 }
85
86 /* Is the symbol host associated?  */
87 static bool
88 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
89 {
90   for (ns = ns->parent; ns; ns = ns->parent)
91     {      
92       if (sym->ns == ns)
93         return true;
94     }
95
96   return false;
97 }
98
99 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
100    an ABSTRACT derived-type.  If where is not NULL, an error message with that
101    locus is printed, optionally using name.  */
102
103 static gfc_try
104 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
105 {
106   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
107     {
108       if (where)
109         {
110           if (name)
111             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
112                        name, where, ts->u.derived->name);
113           else
114             gfc_error ("ABSTRACT type '%s' used at %L",
115                        ts->u.derived->name, where);
116         }
117
118       return FAILURE;
119     }
120
121   return SUCCESS;
122 }
123
124
125 /* Resolve types of formal argument lists.  These have to be done early so that
126    the formal argument lists of module procedures can be copied to the
127    containing module before the individual procedures are resolved
128    individually.  We also resolve argument lists of procedures in interface
129    blocks because they are self-contained scoping units.
130
131    Since a dummy argument cannot be a non-dummy procedure, the only
132    resort left for untyped names are the IMPLICIT types.  */
133
134 static void
135 resolve_formal_arglist (gfc_symbol *proc)
136 {
137   gfc_formal_arglist *f;
138   gfc_symbol *sym;
139   int i;
140
141   if (proc->result != NULL)
142     sym = proc->result;
143   else
144     sym = proc;
145
146   if (gfc_elemental (proc)
147       || sym->attr.pointer || sym->attr.allocatable
148       || (sym->as && sym->as->rank > 0))
149     {
150       proc->attr.always_explicit = 1;
151       sym->attr.always_explicit = 1;
152     }
153
154   formal_arg_flag = 1;
155
156   for (f = proc->formal; f; f = f->next)
157     {
158       sym = f->sym;
159
160       if (sym == NULL)
161         {
162           /* Alternate return placeholder.  */
163           if (gfc_elemental (proc))
164             gfc_error ("Alternate return specifier in elemental subroutine "
165                        "'%s' at %L is not allowed", proc->name,
166                        &proc->declared_at);
167           if (proc->attr.function)
168             gfc_error ("Alternate return specifier in function "
169                        "'%s' at %L is not allowed", proc->name,
170                        &proc->declared_at);
171           continue;
172         }
173
174       if (sym->attr.if_source != IFSRC_UNKNOWN)
175         resolve_formal_arglist (sym);
176
177       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
178         {
179           if (gfc_pure (proc) && !gfc_pure (sym))
180             {
181               gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
182                          "also be PURE", sym->name, &sym->declared_at);
183               continue;
184             }
185
186           if (gfc_elemental (proc))
187             {
188               gfc_error ("Dummy procedure at %L not allowed in ELEMENTAL "
189                          "procedure", &sym->declared_at);
190               continue;
191             }
192
193           if (sym->attr.function
194                 && sym->ts.type == BT_UNKNOWN
195                 && sym->attr.intrinsic)
196             {
197               gfc_intrinsic_sym *isym;
198               isym = gfc_find_function (sym->name);
199               if (isym == NULL || !isym->specific)
200                 {
201                   gfc_error ("Unable to find a specific INTRINSIC procedure "
202                              "for the reference '%s' at %L", sym->name,
203                              &sym->declared_at);
204                 }
205               sym->ts = isym->ts;
206             }
207
208           continue;
209         }
210
211       if (sym->ts.type == BT_UNKNOWN)
212         {
213           if (!sym->attr.function || sym->result == sym)
214             gfc_set_default_type (sym, 1, sym->ns);
215         }
216
217       gfc_resolve_array_spec (sym->as, 0);
218
219       /* We can't tell if an array with dimension (:) is assumed or deferred
220          shape until we know if it has the pointer or allocatable attributes.
221       */
222       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
223           && !(sym->attr.pointer || sym->attr.allocatable))
224         {
225           sym->as->type = AS_ASSUMED_SHAPE;
226           for (i = 0; i < sym->as->rank; i++)
227             sym->as->lower[i] = gfc_int_expr (1);
228         }
229
230       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
231           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
232           || sym->attr.optional)
233         {
234           proc->attr.always_explicit = 1;
235           if (proc->result)
236             proc->result->attr.always_explicit = 1;
237         }
238
239       /* If the flavor is unknown at this point, it has to be a variable.
240          A procedure specification would have already set the type.  */
241
242       if (sym->attr.flavor == FL_UNKNOWN)
243         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
244
245       if (gfc_pure (proc) && !sym->attr.pointer
246           && sym->attr.flavor != FL_PROCEDURE)
247         {
248           if (proc->attr.function && sym->attr.intent != INTENT_IN)
249             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
250                        "INTENT(IN)", sym->name, proc->name,
251                        &sym->declared_at);
252
253           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
254             gfc_error ("Argument '%s' of pure subroutine '%s' at %L must "
255                        "have its INTENT specified", sym->name, proc->name,
256                        &sym->declared_at);
257         }
258
259       if (gfc_elemental (proc))
260         {
261           if (sym->as != NULL)
262             {
263               gfc_error ("Argument '%s' of elemental procedure at %L must "
264                          "be scalar", sym->name, &sym->declared_at);
265               continue;
266             }
267
268           if (sym->attr.pointer)
269             {
270               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
271                          "have the POINTER attribute", sym->name,
272                          &sym->declared_at);
273               continue;
274             }
275
276           if (sym->attr.flavor == FL_PROCEDURE)
277             {
278               gfc_error ("Dummy procedure '%s' not allowed in elemental "
279                          "procedure '%s' at %L", sym->name, proc->name,
280                          &sym->declared_at);
281               continue;
282             }
283         }
284
285       /* Each dummy shall be specified to be scalar.  */
286       if (proc->attr.proc == PROC_ST_FUNCTION)
287         {
288           if (sym->as != NULL)
289             {
290               gfc_error ("Argument '%s' of statement function at %L must "
291                          "be scalar", sym->name, &sym->declared_at);
292               continue;
293             }
294
295           if (sym->ts.type == BT_CHARACTER)
296             {
297               gfc_charlen *cl = sym->ts.u.cl;
298               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
299                 {
300                   gfc_error ("Character-valued argument '%s' of statement "
301                              "function at %L must have constant length",
302                              sym->name, &sym->declared_at);
303                   continue;
304                 }
305             }
306         }
307     }
308   formal_arg_flag = 0;
309 }
310
311
312 /* Work function called when searching for symbols that have argument lists
313    associated with them.  */
314
315 static void
316 find_arglists (gfc_symbol *sym)
317 {
318   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
319     return;
320
321   resolve_formal_arglist (sym);
322 }
323
324
325 /* Given a namespace, resolve all formal argument lists within the namespace.
326  */
327
328 static void
329 resolve_formal_arglists (gfc_namespace *ns)
330 {
331   if (ns == NULL)
332     return;
333
334   gfc_traverse_ns (ns, find_arglists);
335 }
336
337
338 static void
339 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
340 {
341   gfc_try t;
342
343   /* If this namespace is not a function or an entry master function,
344      ignore it.  */
345   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
346       || sym->attr.entry_master)
347     return;
348
349   /* Try to find out of what the return type is.  */
350   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
351     {
352       t = gfc_set_default_type (sym->result, 0, ns);
353
354       if (t == FAILURE && !sym->result->attr.untyped)
355         {
356           if (sym->result == sym)
357             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
358                        sym->name, &sym->declared_at);
359           else if (!sym->result->attr.proc_pointer)
360             gfc_error ("Result '%s' of contained function '%s' at %L has "
361                        "no IMPLICIT type", sym->result->name, sym->name,
362                        &sym->result->declared_at);
363           sym->result->attr.untyped = 1;
364         }
365     }
366
367   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character 
368      type, lists the only ways a character length value of * can be used:
369      dummy arguments of procedures, named constants, and function results
370      in external functions.  Internal function results and results of module
371      procedures are not on this list, ergo, not permitted.  */
372
373   if (sym->result->ts.type == BT_CHARACTER)
374     {
375       gfc_charlen *cl = sym->result->ts.u.cl;
376       if (!cl || !cl->length)
377         {
378           /* See if this is a module-procedure and adapt error message
379              accordingly.  */
380           bool module_proc;
381           gcc_assert (ns->parent && ns->parent->proc_name);
382           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
383
384           gfc_error ("Character-valued %s '%s' at %L must not be"
385                      " assumed length",
386                      module_proc ? _("module procedure")
387                                  : _("internal function"),
388                      sym->name, &sym->declared_at);
389         }
390     }
391 }
392
393
394 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
395    introduce duplicates.  */
396
397 static void
398 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
399 {
400   gfc_formal_arglist *f, *new_arglist;
401   gfc_symbol *new_sym;
402
403   for (; new_args != NULL; new_args = new_args->next)
404     {
405       new_sym = new_args->sym;
406       /* See if this arg is already in the formal argument list.  */
407       for (f = proc->formal; f; f = f->next)
408         {
409           if (new_sym == f->sym)
410             break;
411         }
412
413       if (f)
414         continue;
415
416       /* Add a new argument.  Argument order is not important.  */
417       new_arglist = gfc_get_formal_arglist ();
418       new_arglist->sym = new_sym;
419       new_arglist->next = proc->formal;
420       proc->formal  = new_arglist;
421     }
422 }
423
424
425 /* Flag the arguments that are not present in all entries.  */
426
427 static void
428 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
429 {
430   gfc_formal_arglist *f, *head;
431   head = new_args;
432
433   for (f = proc->formal; f; f = f->next)
434     {
435       if (f->sym == NULL)
436         continue;
437
438       for (new_args = head; new_args; new_args = new_args->next)
439         {
440           if (new_args->sym == f->sym)
441             break;
442         }
443
444       if (new_args)
445         continue;
446
447       f->sym->attr.not_always_present = 1;
448     }
449 }
450
451
452 /* Resolve alternate entry points.  If a symbol has multiple entry points we
453    create a new master symbol for the main routine, and turn the existing
454    symbol into an entry point.  */
455
456 static void
457 resolve_entries (gfc_namespace *ns)
458 {
459   gfc_namespace *old_ns;
460   gfc_code *c;
461   gfc_symbol *proc;
462   gfc_entry_list *el;
463   char name[GFC_MAX_SYMBOL_LEN + 1];
464   static int master_count = 0;
465
466   if (ns->proc_name == NULL)
467     return;
468
469   /* No need to do anything if this procedure doesn't have alternate entry
470      points.  */
471   if (!ns->entries)
472     return;
473
474   /* We may already have resolved alternate entry points.  */
475   if (ns->proc_name->attr.entry_master)
476     return;
477
478   /* If this isn't a procedure something has gone horribly wrong.  */
479   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
480
481   /* Remember the current namespace.  */
482   old_ns = gfc_current_ns;
483
484   gfc_current_ns = ns;
485
486   /* Add the main entry point to the list of entry points.  */
487   el = gfc_get_entry_list ();
488   el->sym = ns->proc_name;
489   el->id = 0;
490   el->next = ns->entries;
491   ns->entries = el;
492   ns->proc_name->attr.entry = 1;
493
494   /* If it is a module function, it needs to be in the right namespace
495      so that gfc_get_fake_result_decl can gather up the results. The
496      need for this arose in get_proc_name, where these beasts were
497      left in their own namespace, to keep prior references linked to
498      the entry declaration.*/
499   if (ns->proc_name->attr.function
500       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
501     el->sym->ns = ns;
502
503   /* Do the same for entries where the master is not a module
504      procedure.  These are retained in the module namespace because
505      of the module procedure declaration.  */
506   for (el = el->next; el; el = el->next)
507     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
508           && el->sym->attr.mod_proc)
509       el->sym->ns = ns;
510   el = ns->entries;
511
512   /* Add an entry statement for it.  */
513   c = gfc_get_code ();
514   c->op = EXEC_ENTRY;
515   c->ext.entry = el;
516   c->next = ns->code;
517   ns->code = c;
518
519   /* Create a new symbol for the master function.  */
520   /* Give the internal function a unique name (within this file).
521      Also include the function name so the user has some hope of figuring
522      out what is going on.  */
523   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
524             master_count++, ns->proc_name->name);
525   gfc_get_ha_symbol (name, &proc);
526   gcc_assert (proc != NULL);
527
528   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
529   if (ns->proc_name->attr.subroutine)
530     gfc_add_subroutine (&proc->attr, proc->name, NULL);
531   else
532     {
533       gfc_symbol *sym;
534       gfc_typespec *ts, *fts;
535       gfc_array_spec *as, *fas;
536       gfc_add_function (&proc->attr, proc->name, NULL);
537       proc->result = proc;
538       fas = ns->entries->sym->as;
539       fas = fas ? fas : ns->entries->sym->result->as;
540       fts = &ns->entries->sym->result->ts;
541       if (fts->type == BT_UNKNOWN)
542         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
543       for (el = ns->entries->next; el; el = el->next)
544         {
545           ts = &el->sym->result->ts;
546           as = el->sym->as;
547           as = as ? as : el->sym->result->as;
548           if (ts->type == BT_UNKNOWN)
549             ts = gfc_get_default_type (el->sym->result->name, NULL);
550
551           if (! gfc_compare_types (ts, fts)
552               || (el->sym->result->attr.dimension
553                   != ns->entries->sym->result->attr.dimension)
554               || (el->sym->result->attr.pointer
555                   != ns->entries->sym->result->attr.pointer))
556             break;
557           else if (as && fas && ns->entries->sym->result != el->sym->result
558                       && gfc_compare_array_spec (as, fas) == 0)
559             gfc_error ("Function %s at %L has entries with mismatched "
560                        "array specifications", ns->entries->sym->name,
561                        &ns->entries->sym->declared_at);
562           /* The characteristics need to match and thus both need to have
563              the same string length, i.e. both len=*, or both len=4.
564              Having both len=<variable> is also possible, but difficult to
565              check at compile time.  */
566           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
567                    && (((ts->u.cl->length && !fts->u.cl->length)
568                         ||(!ts->u.cl->length && fts->u.cl->length))
569                        || (ts->u.cl->length
570                            && ts->u.cl->length->expr_type
571                               != fts->u.cl->length->expr_type)
572                        || (ts->u.cl->length
573                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
574                            && mpz_cmp (ts->u.cl->length->value.integer,
575                                        fts->u.cl->length->value.integer) != 0)))
576             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
577                             "entries returning variables of different "
578                             "string lengths", ns->entries->sym->name,
579                             &ns->entries->sym->declared_at);
580         }
581
582       if (el == NULL)
583         {
584           sym = ns->entries->sym->result;
585           /* All result types the same.  */
586           proc->ts = *fts;
587           if (sym->attr.dimension)
588             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
589           if (sym->attr.pointer)
590             gfc_add_pointer (&proc->attr, NULL);
591         }
592       else
593         {
594           /* Otherwise the result will be passed through a union by
595              reference.  */
596           proc->attr.mixed_entry_master = 1;
597           for (el = ns->entries; el; el = el->next)
598             {
599               sym = el->sym->result;
600               if (sym->attr.dimension)
601                 {
602                   if (el == ns->entries)
603                     gfc_error ("FUNCTION result %s can't be an array in "
604                                "FUNCTION %s at %L", sym->name,
605                                ns->entries->sym->name, &sym->declared_at);
606                   else
607                     gfc_error ("ENTRY result %s can't be an array in "
608                                "FUNCTION %s at %L", sym->name,
609                                ns->entries->sym->name, &sym->declared_at);
610                 }
611               else if (sym->attr.pointer)
612                 {
613                   if (el == ns->entries)
614                     gfc_error ("FUNCTION result %s can't be a POINTER in "
615                                "FUNCTION %s at %L", sym->name,
616                                ns->entries->sym->name, &sym->declared_at);
617                   else
618                     gfc_error ("ENTRY result %s can't be a POINTER in "
619                                "FUNCTION %s at %L", sym->name,
620                                ns->entries->sym->name, &sym->declared_at);
621                 }
622               else
623                 {
624                   ts = &sym->ts;
625                   if (ts->type == BT_UNKNOWN)
626                     ts = gfc_get_default_type (sym->name, NULL);
627                   switch (ts->type)
628                     {
629                     case BT_INTEGER:
630                       if (ts->kind == gfc_default_integer_kind)
631                         sym = NULL;
632                       break;
633                     case BT_REAL:
634                       if (ts->kind == gfc_default_real_kind
635                           || ts->kind == gfc_default_double_kind)
636                         sym = NULL;
637                       break;
638                     case BT_COMPLEX:
639                       if (ts->kind == gfc_default_complex_kind)
640                         sym = NULL;
641                       break;
642                     case BT_LOGICAL:
643                       if (ts->kind == gfc_default_logical_kind)
644                         sym = NULL;
645                       break;
646                     case BT_UNKNOWN:
647                       /* We will issue error elsewhere.  */
648                       sym = NULL;
649                       break;
650                     default:
651                       break;
652                     }
653                   if (sym)
654                     {
655                       if (el == ns->entries)
656                         gfc_error ("FUNCTION result %s can't be of type %s "
657                                    "in FUNCTION %s at %L", sym->name,
658                                    gfc_typename (ts), ns->entries->sym->name,
659                                    &sym->declared_at);
660                       else
661                         gfc_error ("ENTRY result %s can't be of type %s "
662                                    "in FUNCTION %s at %L", sym->name,
663                                    gfc_typename (ts), ns->entries->sym->name,
664                                    &sym->declared_at);
665                     }
666                 }
667             }
668         }
669     }
670   proc->attr.access = ACCESS_PRIVATE;
671   proc->attr.entry_master = 1;
672
673   /* Merge all the entry point arguments.  */
674   for (el = ns->entries; el; el = el->next)
675     merge_argument_lists (proc, el->sym->formal);
676
677   /* Check the master formal arguments for any that are not
678      present in all entry points.  */
679   for (el = ns->entries; el; el = el->next)
680     check_argument_lists (proc, el->sym->formal);
681
682   /* Use the master function for the function body.  */
683   ns->proc_name = proc;
684
685   /* Finalize the new symbols.  */
686   gfc_commit_symbols ();
687
688   /* Restore the original namespace.  */
689   gfc_current_ns = old_ns;
690 }
691
692
693 static bool
694 has_default_initializer (gfc_symbol *der)
695 {
696   gfc_component *c;
697
698   gcc_assert (der->attr.flavor == FL_DERIVED);
699   for (c = der->components; c; c = c->next)
700     if ((c->ts.type != BT_DERIVED && c->initializer)
701         || (c->ts.type == BT_DERIVED
702             && (!c->attr.pointer && has_default_initializer (c->ts.u.derived))))
703       break;
704
705   return c != NULL;
706 }
707
708 /* Resolve common variables.  */
709 static void
710 resolve_common_vars (gfc_symbol *sym, bool named_common)
711 {
712   gfc_symbol *csym = sym;
713
714   for (; csym; csym = csym->common_next)
715     {
716       if (csym->value || csym->attr.data)
717         {
718           if (!csym->ns->is_block_data)
719             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
720                             "but only in BLOCK DATA initialization is "
721                             "allowed", csym->name, &csym->declared_at);
722           else if (!named_common)
723             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
724                             "in a blank COMMON but initialization is only "
725                             "allowed in named common blocks", csym->name,
726                             &csym->declared_at);
727         }
728
729       if (csym->ts.type != BT_DERIVED)
730         continue;
731
732       if (!(csym->ts.u.derived->attr.sequence
733             || csym->ts.u.derived->attr.is_bind_c))
734         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
735                        "has neither the SEQUENCE nor the BIND(C) "
736                        "attribute", csym->name, &csym->declared_at);
737       if (csym->ts.u.derived->attr.alloc_comp)
738         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
739                        "has an ultimate component that is "
740                        "allocatable", csym->name, &csym->declared_at);
741       if (has_default_initializer (csym->ts.u.derived))
742         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
743                        "may not have default initializer", csym->name,
744                        &csym->declared_at);
745
746       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
747         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
748     }
749 }
750
751 /* Resolve common blocks.  */
752 static void
753 resolve_common_blocks (gfc_symtree *common_root)
754 {
755   gfc_symbol *sym;
756
757   if (common_root == NULL)
758     return;
759
760   if (common_root->left)
761     resolve_common_blocks (common_root->left);
762   if (common_root->right)
763     resolve_common_blocks (common_root->right);
764
765   resolve_common_vars (common_root->n.common->head, true);
766
767   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
768   if (sym == NULL)
769     return;
770
771   if (sym->attr.flavor == FL_PARAMETER)
772     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
773                sym->name, &common_root->n.common->where, &sym->declared_at);
774
775   if (sym->attr.intrinsic)
776     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
777                sym->name, &common_root->n.common->where);
778   else if (sym->attr.result
779            ||(sym->attr.function && gfc_current_ns->proc_name == sym))
780     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
781                     "that is also a function result", sym->name,
782                     &common_root->n.common->where);
783   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
784            && sym->attr.proc != PROC_ST_FUNCTION)
785     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
786                     "that is also a global procedure", sym->name,
787                     &common_root->n.common->where);
788 }
789
790
791 /* Resolve contained function types.  Because contained functions can call one
792    another, they have to be worked out before any of the contained procedures
793    can be resolved.
794
795    The good news is that if a function doesn't already have a type, the only
796    way it can get one is through an IMPLICIT type or a RESULT variable, because
797    by definition contained functions are contained namespace they're contained
798    in, not in a sibling or parent namespace.  */
799
800 static void
801 resolve_contained_functions (gfc_namespace *ns)
802 {
803   gfc_namespace *child;
804   gfc_entry_list *el;
805
806   resolve_formal_arglists (ns);
807
808   for (child = ns->contained; child; child = child->sibling)
809     {
810       /* Resolve alternate entry points first.  */
811       resolve_entries (child);
812
813       /* Then check function return types.  */
814       resolve_contained_fntype (child->proc_name, child);
815       for (el = child->entries; el; el = el->next)
816         resolve_contained_fntype (el->sym, child);
817     }
818 }
819
820
821 /* Resolve all of the elements of a structure constructor and make sure that
822    the types are correct.  */
823
824 static gfc_try
825 resolve_structure_cons (gfc_expr *expr)
826 {
827   gfc_constructor *cons;
828   gfc_component *comp;
829   gfc_try t;
830   symbol_attribute a;
831
832   t = SUCCESS;
833   cons = expr->value.constructor;
834   /* A constructor may have references if it is the result of substituting a
835      parameter variable.  In this case we just pull out the component we
836      want.  */
837   if (expr->ref)
838     comp = expr->ref->u.c.sym->components;
839   else
840     comp = expr->ts.u.derived->components;
841
842   /* See if the user is trying to invoke a structure constructor for one of
843      the iso_c_binding derived types.  */
844   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
845       && expr->ts.u.derived->ts.is_iso_c && cons && cons->expr != NULL)
846     {
847       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
848                  expr->ts.u.derived->name, &(expr->where));
849       return FAILURE;
850     }
851
852   for (; comp; comp = comp->next, cons = cons->next)
853     {
854       int rank;
855
856       if (!cons->expr)
857         continue;
858
859       if (gfc_resolve_expr (cons->expr) == FAILURE)
860         {
861           t = FAILURE;
862           continue;
863         }
864
865       rank = comp->as ? comp->as->rank : 0;
866       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
867           && (comp->attr.allocatable || cons->expr->rank))
868         {
869           gfc_error ("The rank of the element in the derived type "
870                      "constructor at %L does not match that of the "
871                      "component (%d/%d)", &cons->expr->where,
872                      cons->expr->rank, rank);
873           t = FAILURE;
874         }
875
876       /* If we don't have the right type, try to convert it.  */
877
878       if (!gfc_compare_types (&cons->expr->ts, &comp->ts))
879         {
880           t = FAILURE;
881           if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
882             gfc_error ("The element in the derived type constructor at %L, "
883                        "for pointer component '%s', is %s but should be %s",
884                        &cons->expr->where, comp->name,
885                        gfc_basic_typename (cons->expr->ts.type),
886                        gfc_basic_typename (comp->ts.type));
887           else
888             t = gfc_convert_type (cons->expr, &comp->ts, 1);
889         }
890
891       if (cons->expr->expr_type == EXPR_NULL
892           && !(comp->attr.pointer || comp->attr.allocatable
893                || comp->attr.proc_pointer
894                || (comp->ts.type == BT_CLASS
895                    && (comp->ts.u.derived->components->attr.pointer
896                        || comp->ts.u.derived->components->attr.allocatable))))
897         {
898           t = FAILURE;
899           gfc_error ("The NULL in the derived type constructor at %L is "
900                      "being applied to component '%s', which is neither "
901                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
902                      comp->name);
903         }
904
905       if (!comp->attr.pointer || cons->expr->expr_type == EXPR_NULL)
906         continue;
907
908       a = gfc_expr_attr (cons->expr);
909
910       if (!a.pointer && !a.target)
911         {
912           t = FAILURE;
913           gfc_error ("The element in the derived type constructor at %L, "
914                      "for pointer component '%s' should be a POINTER or "
915                      "a TARGET", &cons->expr->where, comp->name);
916         }
917     }
918
919   return t;
920 }
921
922
923 /****************** Expression name resolution ******************/
924
925 /* Returns 0 if a symbol was not declared with a type or
926    attribute declaration statement, nonzero otherwise.  */
927
928 static int
929 was_declared (gfc_symbol *sym)
930 {
931   symbol_attribute a;
932
933   a = sym->attr;
934
935   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
936     return 1;
937
938   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
939       || a.optional || a.pointer || a.save || a.target || a.volatile_
940       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN)
941     return 1;
942
943   return 0;
944 }
945
946
947 /* Determine if a symbol is generic or not.  */
948
949 static int
950 generic_sym (gfc_symbol *sym)
951 {
952   gfc_symbol *s;
953
954   if (sym->attr.generic ||
955       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
956     return 1;
957
958   if (was_declared (sym) || sym->ns->parent == NULL)
959     return 0;
960
961   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
962   
963   if (s != NULL)
964     {
965       if (s == sym)
966         return 0;
967       else
968         return generic_sym (s);
969     }
970
971   return 0;
972 }
973
974
975 /* Determine if a symbol is specific or not.  */
976
977 static int
978 specific_sym (gfc_symbol *sym)
979 {
980   gfc_symbol *s;
981
982   if (sym->attr.if_source == IFSRC_IFBODY
983       || sym->attr.proc == PROC_MODULE
984       || sym->attr.proc == PROC_INTERNAL
985       || sym->attr.proc == PROC_ST_FUNCTION
986       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
987       || sym->attr.external)
988     return 1;
989
990   if (was_declared (sym) || sym->ns->parent == NULL)
991     return 0;
992
993   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
994
995   return (s == NULL) ? 0 : specific_sym (s);
996 }
997
998
999 /* Figure out if the procedure is specific, generic or unknown.  */
1000
1001 typedef enum
1002 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1003 proc_type;
1004
1005 static proc_type
1006 procedure_kind (gfc_symbol *sym)
1007 {
1008   if (generic_sym (sym))
1009     return PTYPE_GENERIC;
1010
1011   if (specific_sym (sym))
1012     return PTYPE_SPECIFIC;
1013
1014   return PTYPE_UNKNOWN;
1015 }
1016
1017 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1018    is nonzero when matching actual arguments.  */
1019
1020 static int need_full_assumed_size = 0;
1021
1022 static bool
1023 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1024 {
1025   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1026       return false;
1027
1028   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1029      What should it be?  */
1030   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1031           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1032                && (e->ref->u.ar.type == AR_FULL))
1033     {
1034       gfc_error ("The upper bound in the last dimension must "
1035                  "appear in the reference to the assumed size "
1036                  "array '%s' at %L", sym->name, &e->where);
1037       return true;
1038     }
1039   return false;
1040 }
1041
1042
1043 /* Look for bad assumed size array references in argument expressions
1044   of elemental and array valued intrinsic procedures.  Since this is
1045   called from procedure resolution functions, it only recurses at
1046   operators.  */
1047
1048 static bool
1049 resolve_assumed_size_actual (gfc_expr *e)
1050 {
1051   if (e == NULL)
1052    return false;
1053
1054   switch (e->expr_type)
1055     {
1056     case EXPR_VARIABLE:
1057       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1058         return true;
1059       break;
1060
1061     case EXPR_OP:
1062       if (resolve_assumed_size_actual (e->value.op.op1)
1063           || resolve_assumed_size_actual (e->value.op.op2))
1064         return true;
1065       break;
1066
1067     default:
1068       break;
1069     }
1070   return false;
1071 }
1072
1073
1074 /* Check a generic procedure, passed as an actual argument, to see if
1075    there is a matching specific name.  If none, it is an error, and if
1076    more than one, the reference is ambiguous.  */
1077 static int
1078 count_specific_procs (gfc_expr *e)
1079 {
1080   int n;
1081   gfc_interface *p;
1082   gfc_symbol *sym;
1083         
1084   n = 0;
1085   sym = e->symtree->n.sym;
1086
1087   for (p = sym->generic; p; p = p->next)
1088     if (strcmp (sym->name, p->sym->name) == 0)
1089       {
1090         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1091                                        sym->name);
1092         n++;
1093       }
1094
1095   if (n > 1)
1096     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1097                &e->where);
1098
1099   if (n == 0)
1100     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1101                "argument at %L", sym->name, &e->where);
1102
1103   return n;
1104 }
1105
1106
1107 /* See if a call to sym could possibly be a not allowed RECURSION because of
1108    a missing RECURIVE declaration.  This means that either sym is the current
1109    context itself, or sym is the parent of a contained procedure calling its
1110    non-RECURSIVE containing procedure.
1111    This also works if sym is an ENTRY.  */
1112
1113 static bool
1114 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1115 {
1116   gfc_symbol* proc_sym;
1117   gfc_symbol* context_proc;
1118   gfc_namespace* real_context;
1119
1120   if (sym->attr.flavor == FL_PROGRAM)
1121     return false;
1122
1123   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1124
1125   /* If we've got an ENTRY, find real procedure.  */
1126   if (sym->attr.entry && sym->ns->entries)
1127     proc_sym = sym->ns->entries->sym;
1128   else
1129     proc_sym = sym;
1130
1131   /* If sym is RECURSIVE, all is well of course.  */
1132   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1133     return false;
1134
1135   /* Find the context procedure's "real" symbol if it has entries.
1136      We look for a procedure symbol, so recurse on the parents if we don't
1137      find one (like in case of a BLOCK construct).  */
1138   for (real_context = context; ; real_context = real_context->parent)
1139     {
1140       /* We should find something, eventually!  */
1141       gcc_assert (real_context);
1142
1143       context_proc = (real_context->entries ? real_context->entries->sym
1144                                             : real_context->proc_name);
1145
1146       /* In some special cases, there may not be a proc_name, like for this
1147          invalid code:
1148          real(bad_kind()) function foo () ...
1149          when checking the call to bad_kind ().
1150          In these cases, we simply return here and assume that the
1151          call is ok.  */
1152       if (!context_proc)
1153         return false;
1154
1155       if (context_proc->attr.flavor != FL_LABEL)
1156         break;
1157     }
1158
1159   /* A call from sym's body to itself is recursion, of course.  */
1160   if (context_proc == proc_sym)
1161     return true;
1162
1163   /* The same is true if context is a contained procedure and sym the
1164      containing one.  */
1165   if (context_proc->attr.contained)
1166     {
1167       gfc_symbol* parent_proc;
1168
1169       gcc_assert (context->parent);
1170       parent_proc = (context->parent->entries ? context->parent->entries->sym
1171                                               : context->parent->proc_name);
1172
1173       if (parent_proc == proc_sym)
1174         return true;
1175     }
1176
1177   return false;
1178 }
1179
1180
1181 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1182    its typespec and formal argument list.  */
1183
1184 static gfc_try
1185 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1186 {
1187   gfc_intrinsic_sym* isym;
1188   const char* symstd;
1189
1190   if (sym->formal)
1191     return SUCCESS;
1192
1193   /* We already know this one is an intrinsic, so we don't call
1194      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1195      gfc_find_subroutine directly to check whether it is a function or
1196      subroutine.  */
1197
1198   if ((isym = gfc_find_function (sym->name)))
1199     {
1200       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1201           && !sym->attr.implicit_type)
1202         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1203                       " ignored", sym->name, &sym->declared_at);
1204
1205       if (!sym->attr.function &&
1206           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1207         return FAILURE;
1208
1209       sym->ts = isym->ts;
1210     }
1211   else if ((isym = gfc_find_subroutine (sym->name)))
1212     {
1213       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1214         {
1215           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1216                       " specifier", sym->name, &sym->declared_at);
1217           return FAILURE;
1218         }
1219
1220       if (!sym->attr.subroutine &&
1221           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1222         return FAILURE;
1223     }
1224   else
1225     {
1226       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1227                  &sym->declared_at);
1228       return FAILURE;
1229     }
1230
1231   gfc_copy_formal_args_intr (sym, isym);
1232
1233   /* Check it is actually available in the standard settings.  */
1234   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1235       == FAILURE)
1236     {
1237       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1238                  " available in the current standard settings but %s.  Use"
1239                  " an appropriate -std=* option or enable -fall-intrinsics"
1240                  " in order to use it.",
1241                  sym->name, &sym->declared_at, symstd);
1242       return FAILURE;
1243     }
1244
1245   return SUCCESS;
1246 }
1247
1248
1249 /* Resolve a procedure expression, like passing it to a called procedure or as
1250    RHS for a procedure pointer assignment.  */
1251
1252 static gfc_try
1253 resolve_procedure_expression (gfc_expr* expr)
1254 {
1255   gfc_symbol* sym;
1256
1257   if (expr->expr_type != EXPR_VARIABLE)
1258     return SUCCESS;
1259   gcc_assert (expr->symtree);
1260
1261   sym = expr->symtree->n.sym;
1262
1263   if (sym->attr.intrinsic)
1264     resolve_intrinsic (sym, &expr->where);
1265
1266   if (sym->attr.flavor != FL_PROCEDURE
1267       || (sym->attr.function && sym->result == sym))
1268     return SUCCESS;
1269
1270   /* A non-RECURSIVE procedure that is used as procedure expression within its
1271      own body is in danger of being called recursively.  */
1272   if (is_illegal_recursion (sym, gfc_current_ns))
1273     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1274                  " itself recursively.  Declare it RECURSIVE or use"
1275                  " -frecursive", sym->name, &expr->where);
1276   
1277   return SUCCESS;
1278 }
1279
1280
1281 /* Resolve an actual argument list.  Most of the time, this is just
1282    resolving the expressions in the list.
1283    The exception is that we sometimes have to decide whether arguments
1284    that look like procedure arguments are really simple variable
1285    references.  */
1286
1287 static gfc_try
1288 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1289                         bool no_formal_args)
1290 {
1291   gfc_symbol *sym;
1292   gfc_symtree *parent_st;
1293   gfc_expr *e;
1294   int save_need_full_assumed_size;
1295   gfc_component *comp;
1296         
1297   for (; arg; arg = arg->next)
1298     {
1299       e = arg->expr;
1300       if (e == NULL)
1301         {
1302           /* Check the label is a valid branching target.  */
1303           if (arg->label)
1304             {
1305               if (arg->label->defined == ST_LABEL_UNKNOWN)
1306                 {
1307                   gfc_error ("Label %d referenced at %L is never defined",
1308                              arg->label->value, &arg->label->where);
1309                   return FAILURE;
1310                 }
1311             }
1312           continue;
1313         }
1314
1315       if (gfc_is_proc_ptr_comp (e, &comp))
1316         {
1317           e->ts = comp->ts;
1318           if (e->expr_type == EXPR_PPC)
1319             {
1320               if (comp->as != NULL)
1321                 e->rank = comp->as->rank;
1322               e->expr_type = EXPR_FUNCTION;
1323             }
1324           goto argument_list;
1325         }
1326
1327       if (e->expr_type == EXPR_VARIABLE
1328             && e->symtree->n.sym->attr.generic
1329             && no_formal_args
1330             && count_specific_procs (e) != 1)
1331         return FAILURE;
1332
1333       if (e->ts.type != BT_PROCEDURE)
1334         {
1335           save_need_full_assumed_size = need_full_assumed_size;
1336           if (e->expr_type != EXPR_VARIABLE)
1337             need_full_assumed_size = 0;
1338           if (gfc_resolve_expr (e) != SUCCESS)
1339             return FAILURE;
1340           need_full_assumed_size = save_need_full_assumed_size;
1341           goto argument_list;
1342         }
1343
1344       /* See if the expression node should really be a variable reference.  */
1345
1346       sym = e->symtree->n.sym;
1347
1348       if (sym->attr.flavor == FL_PROCEDURE
1349           || sym->attr.intrinsic
1350           || sym->attr.external)
1351         {
1352           int actual_ok;
1353
1354           /* If a procedure is not already determined to be something else
1355              check if it is intrinsic.  */
1356           if (!sym->attr.intrinsic
1357               && !(sym->attr.external || sym->attr.use_assoc
1358                    || sym->attr.if_source == IFSRC_IFBODY)
1359               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1360             sym->attr.intrinsic = 1;
1361
1362           if (sym->attr.proc == PROC_ST_FUNCTION)
1363             {
1364               gfc_error ("Statement function '%s' at %L is not allowed as an "
1365                          "actual argument", sym->name, &e->where);
1366             }
1367
1368           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1369                                                sym->attr.subroutine);
1370           if (sym->attr.intrinsic && actual_ok == 0)
1371             {
1372               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1373                          "actual argument", sym->name, &e->where);
1374             }
1375
1376           if (sym->attr.contained && !sym->attr.use_assoc
1377               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1378             {
1379               gfc_error ("Internal procedure '%s' is not allowed as an "
1380                          "actual argument at %L", sym->name, &e->where);
1381             }
1382
1383           if (sym->attr.elemental && !sym->attr.intrinsic)
1384             {
1385               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1386                          "allowed as an actual argument at %L", sym->name,
1387                          &e->where);
1388             }
1389
1390           /* Check if a generic interface has a specific procedure
1391             with the same name before emitting an error.  */
1392           if (sym->attr.generic && count_specific_procs (e) != 1)
1393             return FAILURE;
1394           
1395           /* Just in case a specific was found for the expression.  */
1396           sym = e->symtree->n.sym;
1397
1398           /* If the symbol is the function that names the current (or
1399              parent) scope, then we really have a variable reference.  */
1400
1401           if (sym->attr.function && sym->result == sym
1402               && (sym->ns->proc_name == sym
1403                   || (sym->ns->parent != NULL
1404                       && sym->ns->parent->proc_name == sym)))
1405             goto got_variable;
1406
1407           /* If all else fails, see if we have a specific intrinsic.  */
1408           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1409             {
1410               gfc_intrinsic_sym *isym;
1411
1412               isym = gfc_find_function (sym->name);
1413               if (isym == NULL || !isym->specific)
1414                 {
1415                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1416                              "for the reference '%s' at %L", sym->name,
1417                              &e->where);
1418                   return FAILURE;
1419                 }
1420               sym->ts = isym->ts;
1421               sym->attr.intrinsic = 1;
1422               sym->attr.function = 1;
1423             }
1424
1425           if (gfc_resolve_expr (e) == FAILURE)
1426             return FAILURE;
1427           goto argument_list;
1428         }
1429
1430       /* See if the name is a module procedure in a parent unit.  */
1431
1432       if (was_declared (sym) || sym->ns->parent == NULL)
1433         goto got_variable;
1434
1435       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1436         {
1437           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1438           return FAILURE;
1439         }
1440
1441       if (parent_st == NULL)
1442         goto got_variable;
1443
1444       sym = parent_st->n.sym;
1445       e->symtree = parent_st;           /* Point to the right thing.  */
1446
1447       if (sym->attr.flavor == FL_PROCEDURE
1448           || sym->attr.intrinsic
1449           || sym->attr.external)
1450         {
1451           if (gfc_resolve_expr (e) == FAILURE)
1452             return FAILURE;
1453           goto argument_list;
1454         }
1455
1456     got_variable:
1457       e->expr_type = EXPR_VARIABLE;
1458       e->ts = sym->ts;
1459       if (sym->as != NULL)
1460         {
1461           e->rank = sym->as->rank;
1462           e->ref = gfc_get_ref ();
1463           e->ref->type = REF_ARRAY;
1464           e->ref->u.ar.type = AR_FULL;
1465           e->ref->u.ar.as = sym->as;
1466         }
1467
1468       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1469          primary.c (match_actual_arg). If above code determines that it
1470          is a  variable instead, it needs to be resolved as it was not
1471          done at the beginning of this function.  */
1472       save_need_full_assumed_size = need_full_assumed_size;
1473       if (e->expr_type != EXPR_VARIABLE)
1474         need_full_assumed_size = 0;
1475       if (gfc_resolve_expr (e) != SUCCESS)
1476         return FAILURE;
1477       need_full_assumed_size = save_need_full_assumed_size;
1478
1479     argument_list:
1480       /* Check argument list functions %VAL, %LOC and %REF.  There is
1481          nothing to do for %REF.  */
1482       if (arg->name && arg->name[0] == '%')
1483         {
1484           if (strncmp ("%VAL", arg->name, 4) == 0)
1485             {
1486               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1487                 {
1488                   gfc_error ("By-value argument at %L is not of numeric "
1489                              "type", &e->where);
1490                   return FAILURE;
1491                 }
1492
1493               if (e->rank)
1494                 {
1495                   gfc_error ("By-value argument at %L cannot be an array or "
1496                              "an array section", &e->where);
1497                 return FAILURE;
1498                 }
1499
1500               /* Intrinsics are still PROC_UNKNOWN here.  However,
1501                  since same file external procedures are not resolvable
1502                  in gfortran, it is a good deal easier to leave them to
1503                  intrinsic.c.  */
1504               if (ptype != PROC_UNKNOWN
1505                   && ptype != PROC_DUMMY
1506                   && ptype != PROC_EXTERNAL
1507                   && ptype != PROC_MODULE)
1508                 {
1509                   gfc_error ("By-value argument at %L is not allowed "
1510                              "in this context", &e->where);
1511                   return FAILURE;
1512                 }
1513             }
1514
1515           /* Statement functions have already been excluded above.  */
1516           else if (strncmp ("%LOC", arg->name, 4) == 0
1517                    && e->ts.type == BT_PROCEDURE)
1518             {
1519               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1520                 {
1521                   gfc_error ("Passing internal procedure at %L by location "
1522                              "not allowed", &e->where);
1523                   return FAILURE;
1524                 }
1525             }
1526         }
1527     }
1528
1529   return SUCCESS;
1530 }
1531
1532
1533 /* Do the checks of the actual argument list that are specific to elemental
1534    procedures.  If called with c == NULL, we have a function, otherwise if
1535    expr == NULL, we have a subroutine.  */
1536
1537 static gfc_try
1538 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1539 {
1540   gfc_actual_arglist *arg0;
1541   gfc_actual_arglist *arg;
1542   gfc_symbol *esym = NULL;
1543   gfc_intrinsic_sym *isym = NULL;
1544   gfc_expr *e = NULL;
1545   gfc_intrinsic_arg *iformal = NULL;
1546   gfc_formal_arglist *eformal = NULL;
1547   bool formal_optional = false;
1548   bool set_by_optional = false;
1549   int i;
1550   int rank = 0;
1551
1552   /* Is this an elemental procedure?  */
1553   if (expr && expr->value.function.actual != NULL)
1554     {
1555       if (expr->value.function.esym != NULL
1556           && expr->value.function.esym->attr.elemental)
1557         {
1558           arg0 = expr->value.function.actual;
1559           esym = expr->value.function.esym;
1560         }
1561       else if (expr->value.function.isym != NULL
1562                && expr->value.function.isym->elemental)
1563         {
1564           arg0 = expr->value.function.actual;
1565           isym = expr->value.function.isym;
1566         }
1567       else
1568         return SUCCESS;
1569     }
1570   else if (c && c->ext.actual != NULL)
1571     {
1572       arg0 = c->ext.actual;
1573       
1574       if (c->resolved_sym)
1575         esym = c->resolved_sym;
1576       else
1577         esym = c->symtree->n.sym;
1578       gcc_assert (esym);
1579
1580       if (!esym->attr.elemental)
1581         return SUCCESS;
1582     }
1583   else
1584     return SUCCESS;
1585
1586   /* The rank of an elemental is the rank of its array argument(s).  */
1587   for (arg = arg0; arg; arg = arg->next)
1588     {
1589       if (arg->expr != NULL && arg->expr->rank > 0)
1590         {
1591           rank = arg->expr->rank;
1592           if (arg->expr->expr_type == EXPR_VARIABLE
1593               && arg->expr->symtree->n.sym->attr.optional)
1594             set_by_optional = true;
1595
1596           /* Function specific; set the result rank and shape.  */
1597           if (expr)
1598             {
1599               expr->rank = rank;
1600               if (!expr->shape && arg->expr->shape)
1601                 {
1602                   expr->shape = gfc_get_shape (rank);
1603                   for (i = 0; i < rank; i++)
1604                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1605                 }
1606             }
1607           break;
1608         }
1609     }
1610
1611   /* If it is an array, it shall not be supplied as an actual argument
1612      to an elemental procedure unless an array of the same rank is supplied
1613      as an actual argument corresponding to a nonoptional dummy argument of
1614      that elemental procedure(12.4.1.5).  */
1615   formal_optional = false;
1616   if (isym)
1617     iformal = isym->formal;
1618   else
1619     eformal = esym->formal;
1620
1621   for (arg = arg0; arg; arg = arg->next)
1622     {
1623       if (eformal)
1624         {
1625           if (eformal->sym && eformal->sym->attr.optional)
1626             formal_optional = true;
1627           eformal = eformal->next;
1628         }
1629       else if (isym && iformal)
1630         {
1631           if (iformal->optional)
1632             formal_optional = true;
1633           iformal = iformal->next;
1634         }
1635       else if (isym)
1636         formal_optional = true;
1637
1638       if (pedantic && arg->expr != NULL
1639           && arg->expr->expr_type == EXPR_VARIABLE
1640           && arg->expr->symtree->n.sym->attr.optional
1641           && formal_optional
1642           && arg->expr->rank
1643           && (set_by_optional || arg->expr->rank != rank)
1644           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1645         {
1646           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1647                        "MISSING, it cannot be the actual argument of an "
1648                        "ELEMENTAL procedure unless there is a non-optional "
1649                        "argument with the same rank (12.4.1.5)",
1650                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1651           return FAILURE;
1652         }
1653     }
1654
1655   for (arg = arg0; arg; arg = arg->next)
1656     {
1657       if (arg->expr == NULL || arg->expr->rank == 0)
1658         continue;
1659
1660       /* Being elemental, the last upper bound of an assumed size array
1661          argument must be present.  */
1662       if (resolve_assumed_size_actual (arg->expr))
1663         return FAILURE;
1664
1665       /* Elemental procedure's array actual arguments must conform.  */
1666       if (e != NULL)
1667         {
1668           if (gfc_check_conformance (arg->expr, e,
1669                                      "elemental procedure") == FAILURE)
1670             return FAILURE;
1671         }
1672       else
1673         e = arg->expr;
1674     }
1675
1676   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1677      is an array, the intent inout/out variable needs to be also an array.  */
1678   if (rank > 0 && esym && expr == NULL)
1679     for (eformal = esym->formal, arg = arg0; arg && eformal;
1680          arg = arg->next, eformal = eformal->next)
1681       if ((eformal->sym->attr.intent == INTENT_OUT
1682            || eformal->sym->attr.intent == INTENT_INOUT)
1683           && arg->expr && arg->expr->rank == 0)
1684         {
1685           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1686                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1687                      "actual argument is an array", &arg->expr->where,
1688                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1689                      : "INOUT", eformal->sym->name, esym->name);
1690           return FAILURE;
1691         }
1692   return SUCCESS;
1693 }
1694
1695
1696 /* Go through each actual argument in ACTUAL and see if it can be
1697    implemented as an inlined, non-copying intrinsic.  FNSYM is the
1698    function being called, or NULL if not known.  */
1699
1700 static void
1701 find_noncopying_intrinsics (gfc_symbol *fnsym, gfc_actual_arglist *actual)
1702 {
1703   gfc_actual_arglist *ap;
1704   gfc_expr *expr;
1705
1706   for (ap = actual; ap; ap = ap->next)
1707     if (ap->expr
1708         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
1709         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual,
1710                                          NOT_ELEMENTAL))
1711       ap->expr->inline_noncopying_intrinsic = 1;
1712 }
1713
1714
1715 /* This function does the checking of references to global procedures
1716    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1717    77 and 95 standards.  It checks for a gsymbol for the name, making
1718    one if it does not already exist.  If it already exists, then the
1719    reference being resolved must correspond to the type of gsymbol.
1720    Otherwise, the new symbol is equipped with the attributes of the
1721    reference.  The corresponding code that is called in creating
1722    global entities is parse.c.
1723
1724    In addition, for all but -std=legacy, the gsymbols are used to
1725    check the interfaces of external procedures from the same file.
1726    The namespace of the gsymbol is resolved and then, once this is
1727    done the interface is checked.  */
1728
1729
1730 static bool
1731 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
1732 {
1733   if (!gsym_ns->proc_name->attr.recursive)
1734     return true;
1735
1736   if (sym->ns == gsym_ns)
1737     return false;
1738
1739   if (sym->ns->parent && sym->ns->parent == gsym_ns)
1740     return false;
1741
1742   return true;
1743 }
1744
1745 static bool
1746 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
1747 {
1748   if (gsym_ns->entries)
1749     {
1750       gfc_entry_list *entry = gsym_ns->entries;
1751
1752       for (; entry; entry = entry->next)
1753         {
1754           if (strcmp (sym->name, entry->sym->name) == 0)
1755             {
1756               if (strcmp (gsym_ns->proc_name->name,
1757                           sym->ns->proc_name->name) == 0)
1758                 return false;
1759
1760               if (sym->ns->parent
1761                   && strcmp (gsym_ns->proc_name->name,
1762                              sym->ns->parent->proc_name->name) == 0)
1763                 return false;
1764             }
1765         }
1766     }
1767   return true;
1768 }
1769
1770 static void
1771 resolve_global_procedure (gfc_symbol *sym, locus *where,
1772                           gfc_actual_arglist **actual, int sub)
1773 {
1774   gfc_gsymbol * gsym;
1775   gfc_namespace *ns;
1776   enum gfc_symbol_type type;
1777
1778   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
1779
1780   gsym = gfc_get_gsymbol (sym->name);
1781
1782   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
1783     gfc_global_used (gsym, where);
1784
1785   if (gfc_option.flag_whole_file
1786         && sym->attr.if_source == IFSRC_UNKNOWN
1787         && gsym->type != GSYM_UNKNOWN
1788         && gsym->ns
1789         && gsym->ns->resolved != -1
1790         && gsym->ns->proc_name
1791         && not_in_recursive (sym, gsym->ns)
1792         && not_entry_self_reference (sym, gsym->ns))
1793     {
1794       /* Make sure that translation for the gsymbol occurs before
1795          the procedure currently being resolved.  */
1796       ns = gsym->ns->resolved ? NULL : gfc_global_ns_list;
1797       for (; ns && ns != gsym->ns; ns = ns->sibling)
1798         {
1799           if (ns->sibling == gsym->ns)
1800             {
1801               ns->sibling = gsym->ns->sibling;
1802               gsym->ns->sibling = gfc_global_ns_list;
1803               gfc_global_ns_list = gsym->ns;
1804               break;
1805             }
1806         }
1807
1808       if (!gsym->ns->resolved)
1809         {
1810           gfc_dt_list *old_dt_list;
1811
1812           /* Stash away derived types so that the backend_decls do not
1813              get mixed up.  */
1814           old_dt_list = gfc_derived_types;
1815           gfc_derived_types = NULL;
1816
1817           gfc_resolve (gsym->ns);
1818
1819           /* Store the new derived types with the global namespace.  */
1820           if (gfc_derived_types)
1821             gsym->ns->derived_types = gfc_derived_types;
1822
1823           /* Restore the derived types of this namespace.  */
1824           gfc_derived_types = old_dt_list;
1825         }
1826
1827       if (gsym->ns->proc_name->attr.function
1828             && gsym->ns->proc_name->as
1829             && gsym->ns->proc_name->as->rank
1830             && (!sym->as || sym->as->rank != gsym->ns->proc_name->as->rank))
1831         gfc_error ("The reference to function '%s' at %L either needs an "
1832                    "explicit INTERFACE or the rank is incorrect", sym->name,
1833                    where);
1834
1835       if (gfc_option.flag_whole_file == 1
1836             || ((gfc_option.warn_std & GFC_STD_LEGACY)
1837                   &&
1838                !(gfc_option.warn_std & GFC_STD_GNU)))
1839         gfc_errors_to_warnings (1);
1840
1841       gfc_procedure_use (gsym->ns->proc_name, actual, where);
1842
1843       gfc_errors_to_warnings (0);
1844     }
1845
1846   if (gsym->type == GSYM_UNKNOWN)
1847     {
1848       gsym->type = type;
1849       gsym->where = *where;
1850     }
1851
1852   gsym->used = 1;
1853 }
1854
1855
1856 /************* Function resolution *************/
1857
1858 /* Resolve a function call known to be generic.
1859    Section 14.1.2.4.1.  */
1860
1861 static match
1862 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
1863 {
1864   gfc_symbol *s;
1865
1866   if (sym->attr.generic)
1867     {
1868       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
1869       if (s != NULL)
1870         {
1871           expr->value.function.name = s->name;
1872           expr->value.function.esym = s;
1873
1874           if (s->ts.type != BT_UNKNOWN)
1875             expr->ts = s->ts;
1876           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
1877             expr->ts = s->result->ts;
1878
1879           if (s->as != NULL)
1880             expr->rank = s->as->rank;
1881           else if (s->result != NULL && s->result->as != NULL)
1882             expr->rank = s->result->as->rank;
1883
1884           gfc_set_sym_referenced (expr->value.function.esym);
1885
1886           return MATCH_YES;
1887         }
1888
1889       /* TODO: Need to search for elemental references in generic
1890          interface.  */
1891     }
1892
1893   if (sym->attr.intrinsic)
1894     return gfc_intrinsic_func_interface (expr, 0);
1895
1896   return MATCH_NO;
1897 }
1898
1899
1900 static gfc_try
1901 resolve_generic_f (gfc_expr *expr)
1902 {
1903   gfc_symbol *sym;
1904   match m;
1905
1906   sym = expr->symtree->n.sym;
1907
1908   for (;;)
1909     {
1910       m = resolve_generic_f0 (expr, sym);
1911       if (m == MATCH_YES)
1912         return SUCCESS;
1913       else if (m == MATCH_ERROR)
1914         return FAILURE;
1915
1916 generic:
1917       if (sym->ns->parent == NULL)
1918         break;
1919       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1920
1921       if (sym == NULL)
1922         break;
1923       if (!generic_sym (sym))
1924         goto generic;
1925     }
1926
1927   /* Last ditch attempt.  See if the reference is to an intrinsic
1928      that possesses a matching interface.  14.1.2.4  */
1929   if (sym && !gfc_is_intrinsic (sym, 0, expr->where))
1930     {
1931       gfc_error ("There is no specific function for the generic '%s' at %L",
1932                  expr->symtree->n.sym->name, &expr->where);
1933       return FAILURE;
1934     }
1935
1936   m = gfc_intrinsic_func_interface (expr, 0);
1937   if (m == MATCH_YES)
1938     return SUCCESS;
1939   if (m == MATCH_NO)
1940     gfc_error ("Generic function '%s' at %L is not consistent with a "
1941                "specific intrinsic interface", expr->symtree->n.sym->name,
1942                &expr->where);
1943
1944   return FAILURE;
1945 }
1946
1947
1948 /* Resolve a function call known to be specific.  */
1949
1950 static match
1951 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
1952 {
1953   match m;
1954
1955   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
1956     {
1957       if (sym->attr.dummy)
1958         {
1959           sym->attr.proc = PROC_DUMMY;
1960           goto found;
1961         }
1962
1963       sym->attr.proc = PROC_EXTERNAL;
1964       goto found;
1965     }
1966
1967   if (sym->attr.proc == PROC_MODULE
1968       || sym->attr.proc == PROC_ST_FUNCTION
1969       || sym->attr.proc == PROC_INTERNAL)
1970     goto found;
1971
1972   if (sym->attr.intrinsic)
1973     {
1974       m = gfc_intrinsic_func_interface (expr, 1);
1975       if (m == MATCH_YES)
1976         return MATCH_YES;
1977       if (m == MATCH_NO)
1978         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
1979                    "with an intrinsic", sym->name, &expr->where);
1980
1981       return MATCH_ERROR;
1982     }
1983
1984   return MATCH_NO;
1985
1986 found:
1987   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
1988
1989   if (sym->result)
1990     expr->ts = sym->result->ts;
1991   else
1992     expr->ts = sym->ts;
1993   expr->value.function.name = sym->name;
1994   expr->value.function.esym = sym;
1995   if (sym->as != NULL)
1996     expr->rank = sym->as->rank;
1997
1998   return MATCH_YES;
1999 }
2000
2001
2002 static gfc_try
2003 resolve_specific_f (gfc_expr *expr)
2004 {
2005   gfc_symbol *sym;
2006   match m;
2007
2008   sym = expr->symtree->n.sym;
2009
2010   for (;;)
2011     {
2012       m = resolve_specific_f0 (sym, expr);
2013       if (m == MATCH_YES)
2014         return SUCCESS;
2015       if (m == MATCH_ERROR)
2016         return FAILURE;
2017
2018       if (sym->ns->parent == NULL)
2019         break;
2020
2021       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2022
2023       if (sym == NULL)
2024         break;
2025     }
2026
2027   gfc_error ("Unable to resolve the specific function '%s' at %L",
2028              expr->symtree->n.sym->name, &expr->where);
2029
2030   return SUCCESS;
2031 }
2032
2033
2034 /* Resolve a procedure call not known to be generic nor specific.  */
2035
2036 static gfc_try
2037 resolve_unknown_f (gfc_expr *expr)
2038 {
2039   gfc_symbol *sym;
2040   gfc_typespec *ts;
2041
2042   sym = expr->symtree->n.sym;
2043
2044   if (sym->attr.dummy)
2045     {
2046       sym->attr.proc = PROC_DUMMY;
2047       expr->value.function.name = sym->name;
2048       goto set_type;
2049     }
2050
2051   /* See if we have an intrinsic function reference.  */
2052
2053   if (gfc_is_intrinsic (sym, 0, expr->where))
2054     {
2055       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2056         return SUCCESS;
2057       return FAILURE;
2058     }
2059
2060   /* The reference is to an external name.  */
2061
2062   sym->attr.proc = PROC_EXTERNAL;
2063   expr->value.function.name = sym->name;
2064   expr->value.function.esym = expr->symtree->n.sym;
2065
2066   if (sym->as != NULL)
2067     expr->rank = sym->as->rank;
2068
2069   /* Type of the expression is either the type of the symbol or the
2070      default type of the symbol.  */
2071
2072 set_type:
2073   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2074
2075   if (sym->ts.type != BT_UNKNOWN)
2076     expr->ts = sym->ts;
2077   else
2078     {
2079       ts = gfc_get_default_type (sym->name, sym->ns);
2080
2081       if (ts->type == BT_UNKNOWN)
2082         {
2083           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2084                      sym->name, &expr->where);
2085           return FAILURE;
2086         }
2087       else
2088         expr->ts = *ts;
2089     }
2090
2091   return SUCCESS;
2092 }
2093
2094
2095 /* Return true, if the symbol is an external procedure.  */
2096 static bool
2097 is_external_proc (gfc_symbol *sym)
2098 {
2099   if (!sym->attr.dummy && !sym->attr.contained
2100         && !(sym->attr.intrinsic
2101               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2102         && sym->attr.proc != PROC_ST_FUNCTION
2103         && !sym->attr.use_assoc
2104         && sym->name)
2105     return true;
2106
2107   return false;
2108 }
2109
2110
2111 /* Figure out if a function reference is pure or not.  Also set the name
2112    of the function for a potential error message.  Return nonzero if the
2113    function is PURE, zero if not.  */
2114 static int
2115 pure_stmt_function (gfc_expr *, gfc_symbol *);
2116
2117 static int
2118 pure_function (gfc_expr *e, const char **name)
2119 {
2120   int pure;
2121
2122   *name = NULL;
2123
2124   if (e->symtree != NULL
2125         && e->symtree->n.sym != NULL
2126         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2127     return pure_stmt_function (e, e->symtree->n.sym);
2128
2129   if (e->value.function.esym)
2130     {
2131       pure = gfc_pure (e->value.function.esym);
2132       *name = e->value.function.esym->name;
2133     }
2134   else if (e->value.function.isym)
2135     {
2136       pure = e->value.function.isym->pure
2137              || e->value.function.isym->elemental;
2138       *name = e->value.function.isym->name;
2139     }
2140   else
2141     {
2142       /* Implicit functions are not pure.  */
2143       pure = 0;
2144       *name = e->value.function.name;
2145     }
2146
2147   return pure;
2148 }
2149
2150
2151 static bool
2152 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2153                  int *f ATTRIBUTE_UNUSED)
2154 {
2155   const char *name;
2156
2157   /* Don't bother recursing into other statement functions
2158      since they will be checked individually for purity.  */
2159   if (e->expr_type != EXPR_FUNCTION
2160         || !e->symtree
2161         || e->symtree->n.sym == sym
2162         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2163     return false;
2164
2165   return pure_function (e, &name) ? false : true;
2166 }
2167
2168
2169 static int
2170 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2171 {
2172   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2173 }
2174
2175
2176 static gfc_try
2177 is_scalar_expr_ptr (gfc_expr *expr)
2178 {
2179   gfc_try retval = SUCCESS;
2180   gfc_ref *ref;
2181   int start;
2182   int end;
2183
2184   /* See if we have a gfc_ref, which means we have a substring, array
2185      reference, or a component.  */
2186   if (expr->ref != NULL)
2187     {
2188       ref = expr->ref;
2189       while (ref->next != NULL)
2190         ref = ref->next;
2191
2192       switch (ref->type)
2193         {
2194         case REF_SUBSTRING:
2195           if (ref->u.ss.length != NULL 
2196               && ref->u.ss.length->length != NULL
2197               && ref->u.ss.start
2198               && ref->u.ss.start->expr_type == EXPR_CONSTANT 
2199               && ref->u.ss.end
2200               && ref->u.ss.end->expr_type == EXPR_CONSTANT)
2201             {
2202               start = (int) mpz_get_si (ref->u.ss.start->value.integer);
2203               end = (int) mpz_get_si (ref->u.ss.end->value.integer);
2204               if (end - start + 1 != 1)
2205                 retval = FAILURE;
2206             }
2207           else
2208             retval = FAILURE;
2209           break;
2210         case REF_ARRAY:
2211           if (ref->u.ar.type == AR_ELEMENT)
2212             retval = SUCCESS;
2213           else if (ref->u.ar.type == AR_FULL)
2214             {
2215               /* The user can give a full array if the array is of size 1.  */
2216               if (ref->u.ar.as != NULL
2217                   && ref->u.ar.as->rank == 1
2218                   && ref->u.ar.as->type == AS_EXPLICIT
2219                   && ref->u.ar.as->lower[0] != NULL
2220                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2221                   && ref->u.ar.as->upper[0] != NULL
2222                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2223                 {
2224                   /* If we have a character string, we need to check if
2225                      its length is one.  */
2226                   if (expr->ts.type == BT_CHARACTER)
2227                     {
2228                       if (expr->ts.u.cl == NULL
2229                           || expr->ts.u.cl->length == NULL
2230                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2231                           != 0)
2232                         retval = FAILURE;
2233                     }
2234                   else
2235                     {
2236                       /* We have constant lower and upper bounds.  If the
2237                          difference between is 1, it can be considered a
2238                          scalar.  */
2239                       start = (int) mpz_get_si
2240                                 (ref->u.ar.as->lower[0]->value.integer);
2241                       end = (int) mpz_get_si
2242                                 (ref->u.ar.as->upper[0]->value.integer);
2243                       if (end - start + 1 != 1)
2244                         retval = FAILURE;
2245                    }
2246                 }
2247               else
2248                 retval = FAILURE;
2249             }
2250           else
2251             retval = FAILURE;
2252           break;
2253         default:
2254           retval = SUCCESS;
2255           break;
2256         }
2257     }
2258   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2259     {
2260       /* Character string.  Make sure it's of length 1.  */
2261       if (expr->ts.u.cl == NULL
2262           || expr->ts.u.cl->length == NULL
2263           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2264         retval = FAILURE;
2265     }
2266   else if (expr->rank != 0)
2267     retval = FAILURE;
2268
2269   return retval;
2270 }
2271
2272
2273 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2274    and, in the case of c_associated, set the binding label based on
2275    the arguments.  */
2276
2277 static gfc_try
2278 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2279                           gfc_symbol **new_sym)
2280 {
2281   char name[GFC_MAX_SYMBOL_LEN + 1];
2282   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2283   int optional_arg = 0, is_pointer = 0;
2284   gfc_try retval = SUCCESS;
2285   gfc_symbol *args_sym;
2286   gfc_typespec *arg_ts;
2287
2288   if (args->expr->expr_type == EXPR_CONSTANT
2289       || args->expr->expr_type == EXPR_OP
2290       || args->expr->expr_type == EXPR_NULL)
2291     {
2292       gfc_error ("Argument to '%s' at %L is not a variable",
2293                  sym->name, &(args->expr->where));
2294       return FAILURE;
2295     }
2296
2297   args_sym = args->expr->symtree->n.sym;
2298
2299   /* The typespec for the actual arg should be that stored in the expr
2300      and not necessarily that of the expr symbol (args_sym), because
2301      the actual expression could be a part-ref of the expr symbol.  */
2302   arg_ts = &(args->expr->ts);
2303
2304   is_pointer = gfc_is_data_pointer (args->expr);
2305     
2306   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2307     {
2308       /* If the user gave two args then they are providing something for
2309          the optional arg (the second cptr).  Therefore, set the name and
2310          binding label to the c_associated for two cptrs.  Otherwise,
2311          set c_associated to expect one cptr.  */
2312       if (args->next)
2313         {
2314           /* two args.  */
2315           sprintf (name, "%s_2", sym->name);
2316           sprintf (binding_label, "%s_2", sym->binding_label);
2317           optional_arg = 1;
2318         }
2319       else
2320         {
2321           /* one arg.  */
2322           sprintf (name, "%s_1", sym->name);
2323           sprintf (binding_label, "%s_1", sym->binding_label);
2324           optional_arg = 0;
2325         }
2326
2327       /* Get a new symbol for the version of c_associated that
2328          will get called.  */
2329       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2330     }
2331   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2332            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2333     {
2334       sprintf (name, "%s", sym->name);
2335       sprintf (binding_label, "%s", sym->binding_label);
2336
2337       /* Error check the call.  */
2338       if (args->next != NULL)
2339         {
2340           gfc_error_now ("More actual than formal arguments in '%s' "
2341                          "call at %L", name, &(args->expr->where));
2342           retval = FAILURE;
2343         }
2344       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2345         {
2346           /* Make sure we have either the target or pointer attribute.  */
2347           if (!args_sym->attr.target && !is_pointer)
2348             {
2349               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2350                              "a TARGET or an associated pointer",
2351                              args_sym->name,
2352                              sym->name, &(args->expr->where));
2353               retval = FAILURE;
2354             }
2355
2356           /* See if we have interoperable type and type param.  */
2357           if (verify_c_interop (arg_ts) == SUCCESS
2358               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2359             {
2360               if (args_sym->attr.target == 1)
2361                 {
2362                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2363                      has the target attribute and is interoperable.  */
2364                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2365                      allocatable variable that has the TARGET attribute and
2366                      is not an array of zero size.  */
2367                   if (args_sym->attr.allocatable == 1)
2368                     {
2369                       if (args_sym->attr.dimension != 0 
2370                           && (args_sym->as && args_sym->as->rank == 0))
2371                         {
2372                           gfc_error_now ("Allocatable variable '%s' used as a "
2373                                          "parameter to '%s' at %L must not be "
2374                                          "an array of zero size",
2375                                          args_sym->name, sym->name,
2376                                          &(args->expr->where));
2377                           retval = FAILURE;
2378                         }
2379                     }
2380                   else
2381                     {
2382                       /* A non-allocatable target variable with C
2383                          interoperable type and type parameters must be
2384                          interoperable.  */
2385                       if (args_sym && args_sym->attr.dimension)
2386                         {
2387                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2388                             {
2389                               gfc_error ("Assumed-shape array '%s' at %L "
2390                                          "cannot be an argument to the "
2391                                          "procedure '%s' because "
2392                                          "it is not C interoperable",
2393                                          args_sym->name,
2394                                          &(args->expr->where), sym->name);
2395                               retval = FAILURE;
2396                             }
2397                           else if (args_sym->as->type == AS_DEFERRED)
2398                             {
2399                               gfc_error ("Deferred-shape array '%s' at %L "
2400                                          "cannot be an argument to the "
2401                                          "procedure '%s' because "
2402                                          "it is not C interoperable",
2403                                          args_sym->name,
2404                                          &(args->expr->where), sym->name);
2405                               retval = FAILURE;
2406                             }
2407                         }
2408                               
2409                       /* Make sure it's not a character string.  Arrays of
2410                          any type should be ok if the variable is of a C
2411                          interoperable type.  */
2412                       if (arg_ts->type == BT_CHARACTER)
2413                         if (arg_ts->u.cl != NULL
2414                             && (arg_ts->u.cl->length == NULL
2415                                 || arg_ts->u.cl->length->expr_type
2416                                    != EXPR_CONSTANT
2417                                 || mpz_cmp_si
2418                                     (arg_ts->u.cl->length->value.integer, 1)
2419                                    != 0)
2420                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2421                           {
2422                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2423                                            "at %L must have a length of 1",
2424                                            args_sym->name, sym->name,
2425                                            &(args->expr->where));
2426                             retval = FAILURE;
2427                           }
2428                     }
2429                 }
2430               else if (is_pointer
2431                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2432                 {
2433                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2434                      scalar pointer.  */
2435                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2436                                  "associated scalar POINTER", args_sym->name,
2437                                  sym->name, &(args->expr->where));
2438                   retval = FAILURE;
2439                 }
2440             }
2441           else
2442             {
2443               /* The parameter is not required to be C interoperable.  If it
2444                  is not C interoperable, it must be a nonpolymorphic scalar
2445                  with no length type parameters.  It still must have either
2446                  the pointer or target attribute, and it can be
2447                  allocatable (but must be allocated when c_loc is called).  */
2448               if (args->expr->rank != 0 
2449                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2450                 {
2451                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2452                                  "scalar", args_sym->name, sym->name,
2453                                  &(args->expr->where));
2454                   retval = FAILURE;
2455                 }
2456               else if (arg_ts->type == BT_CHARACTER 
2457                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2458                 {
2459                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2460                                  "%L must have a length of 1",
2461                                  args_sym->name, sym->name,
2462                                  &(args->expr->where));
2463                   retval = FAILURE;
2464                 }
2465             }
2466         }
2467       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2468         {
2469           if (args_sym->attr.flavor != FL_PROCEDURE)
2470             {
2471               /* TODO: Update this error message to allow for procedure
2472                  pointers once they are implemented.  */
2473               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2474                              "procedure",
2475                              args_sym->name, sym->name,
2476                              &(args->expr->where));
2477               retval = FAILURE;
2478             }
2479           else if (args_sym->attr.is_bind_c != 1)
2480             {
2481               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2482                              "BIND(C)",
2483                              args_sym->name, sym->name,
2484                              &(args->expr->where));
2485               retval = FAILURE;
2486             }
2487         }
2488       
2489       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2490       *new_sym = sym;
2491     }
2492   else
2493     {
2494       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2495                           "iso_c_binding function: '%s'!\n", sym->name);
2496     }
2497
2498   return retval;
2499 }
2500
2501
2502 /* Resolve a function call, which means resolving the arguments, then figuring
2503    out which entity the name refers to.  */
2504 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
2505    to INTENT(OUT) or INTENT(INOUT).  */
2506
2507 static gfc_try
2508 resolve_function (gfc_expr *expr)
2509 {
2510   gfc_actual_arglist *arg;
2511   gfc_symbol *sym;
2512   const char *name;
2513   gfc_try t;
2514   int temp;
2515   procedure_type p = PROC_INTRINSIC;
2516   bool no_formal_args;
2517
2518   sym = NULL;
2519   if (expr->symtree)
2520     sym = expr->symtree->n.sym;
2521
2522   if (sym && sym->attr.intrinsic
2523       && resolve_intrinsic (sym, &expr->where) == FAILURE)
2524     return FAILURE;
2525
2526   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2527     {
2528       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2529       return FAILURE;
2530     }
2531
2532   /* If this ia a deferred TBP with an abstract interface (which may
2533      of course be referenced), expr->value.function.name will be set.  */
2534   if (sym && sym->attr.abstract && !expr->value.function.name)
2535     {
2536       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2537                  sym->name, &expr->where);
2538       return FAILURE;
2539     }
2540
2541   /* Switch off assumed size checking and do this again for certain kinds
2542      of procedure, once the procedure itself is resolved.  */
2543   need_full_assumed_size++;
2544
2545   if (expr->symtree && expr->symtree->n.sym)
2546     p = expr->symtree->n.sym->attr.proc;
2547
2548   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
2549   if (resolve_actual_arglist (expr->value.function.actual,
2550                               p, no_formal_args) == FAILURE)
2551       return FAILURE;
2552
2553   /* Need to setup the call to the correct c_associated, depending on
2554      the number of cptrs to user gives to compare.  */
2555   if (sym && sym->attr.is_iso_c == 1)
2556     {
2557       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
2558           == FAILURE)
2559         return FAILURE;
2560       
2561       /* Get the symtree for the new symbol (resolved func).
2562          the old one will be freed later, when it's no longer used.  */
2563       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
2564     }
2565   
2566   /* Resume assumed_size checking.  */
2567   need_full_assumed_size--;
2568
2569   /* If the procedure is external, check for usage.  */
2570   if (sym && is_external_proc (sym))
2571     resolve_global_procedure (sym, &expr->where,
2572                               &expr->value.function.actual, 0);
2573
2574   if (sym && sym->ts.type == BT_CHARACTER
2575       && sym->ts.u.cl
2576       && sym->ts.u.cl->length == NULL
2577       && !sym->attr.dummy
2578       && expr->value.function.esym == NULL
2579       && !sym->attr.contained)
2580     {
2581       /* Internal procedures are taken care of in resolve_contained_fntype.  */
2582       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
2583                  "be used at %L since it is not a dummy argument",
2584                  sym->name, &expr->where);
2585       return FAILURE;
2586     }
2587
2588   /* See if function is already resolved.  */
2589
2590   if (expr->value.function.name != NULL)
2591     {
2592       if (expr->ts.type == BT_UNKNOWN)
2593         expr->ts = sym->ts;
2594       t = SUCCESS;
2595     }
2596   else
2597     {
2598       /* Apply the rules of section 14.1.2.  */
2599
2600       switch (procedure_kind (sym))
2601         {
2602         case PTYPE_GENERIC:
2603           t = resolve_generic_f (expr);
2604           break;
2605
2606         case PTYPE_SPECIFIC:
2607           t = resolve_specific_f (expr);
2608           break;
2609
2610         case PTYPE_UNKNOWN:
2611           t = resolve_unknown_f (expr);
2612           break;
2613
2614         default:
2615           gfc_internal_error ("resolve_function(): bad function type");
2616         }
2617     }
2618
2619   /* If the expression is still a function (it might have simplified),
2620      then we check to see if we are calling an elemental function.  */
2621
2622   if (expr->expr_type != EXPR_FUNCTION)
2623     return t;
2624
2625   temp = need_full_assumed_size;
2626   need_full_assumed_size = 0;
2627
2628   if (resolve_elemental_actual (expr, NULL) == FAILURE)
2629     return FAILURE;
2630
2631   if (omp_workshare_flag
2632       && expr->value.function.esym
2633       && ! gfc_elemental (expr->value.function.esym))
2634     {
2635       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
2636                  "in WORKSHARE construct", expr->value.function.esym->name,
2637                  &expr->where);
2638       t = FAILURE;
2639     }
2640
2641 #define GENERIC_ID expr->value.function.isym->id
2642   else if (expr->value.function.actual != NULL
2643            && expr->value.function.isym != NULL
2644            && GENERIC_ID != GFC_ISYM_LBOUND
2645            && GENERIC_ID != GFC_ISYM_LEN
2646            && GENERIC_ID != GFC_ISYM_LOC
2647            && GENERIC_ID != GFC_ISYM_PRESENT)
2648     {
2649       /* Array intrinsics must also have the last upper bound of an
2650          assumed size array argument.  UBOUND and SIZE have to be
2651          excluded from the check if the second argument is anything
2652          than a constant.  */
2653
2654       for (arg = expr->value.function.actual; arg; arg = arg->next)
2655         {
2656           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
2657               && arg->next != NULL && arg->next->expr)
2658             {
2659               if (arg->next->expr->expr_type != EXPR_CONSTANT)
2660                 break;
2661
2662               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
2663                 break;
2664
2665               if ((int)mpz_get_si (arg->next->expr->value.integer)
2666                         < arg->expr->rank)
2667                 break;
2668             }
2669
2670           if (arg->expr != NULL
2671               && arg->expr->rank > 0
2672               && resolve_assumed_size_actual (arg->expr))
2673             return FAILURE;
2674         }
2675     }
2676 #undef GENERIC_ID
2677
2678   need_full_assumed_size = temp;
2679   name = NULL;
2680
2681   if (!pure_function (expr, &name) && name)
2682     {
2683       if (forall_flag)
2684         {
2685           gfc_error ("reference to non-PURE function '%s' at %L inside a "
2686                      "FORALL %s", name, &expr->where,
2687                      forall_flag == 2 ? "mask" : "block");
2688           t = FAILURE;
2689         }
2690       else if (gfc_pure (NULL))
2691         {
2692           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
2693                      "procedure within a PURE procedure", name, &expr->where);
2694           t = FAILURE;
2695         }
2696     }
2697
2698   /* Functions without the RECURSIVE attribution are not allowed to
2699    * call themselves.  */
2700   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
2701     {
2702       gfc_symbol *esym;
2703       esym = expr->value.function.esym;
2704
2705       if (is_illegal_recursion (esym, gfc_current_ns))
2706       {
2707         if (esym->attr.entry && esym->ns->entries)
2708           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
2709                      " function '%s' is not RECURSIVE",
2710                      esym->name, &expr->where, esym->ns->entries->sym->name);
2711         else
2712           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
2713                      " is not RECURSIVE", esym->name, &expr->where);
2714
2715         t = FAILURE;
2716       }
2717     }
2718
2719   /* Character lengths of use associated functions may contains references to
2720      symbols not referenced from the current program unit otherwise.  Make sure
2721      those symbols are marked as referenced.  */
2722
2723   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
2724       && expr->value.function.esym->attr.use_assoc)
2725     {
2726       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
2727     }
2728
2729   if (t == SUCCESS
2730         && !((expr->value.function.esym
2731                 && expr->value.function.esym->attr.elemental)
2732                         ||
2733              (expr->value.function.isym
2734                 && expr->value.function.isym->elemental)))
2735     find_noncopying_intrinsics (expr->value.function.esym,
2736                                 expr->value.function.actual);
2737
2738   /* Make sure that the expression has a typespec that works.  */
2739   if (expr->ts.type == BT_UNKNOWN)
2740     {
2741       if (expr->symtree->n.sym->result
2742             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
2743             && !expr->symtree->n.sym->result->attr.proc_pointer)
2744         expr->ts = expr->symtree->n.sym->result->ts;
2745     }
2746
2747   return t;
2748 }
2749
2750
2751 /************* Subroutine resolution *************/
2752
2753 static void
2754 pure_subroutine (gfc_code *c, gfc_symbol *sym)
2755 {
2756   if (gfc_pure (sym))
2757     return;
2758
2759   if (forall_flag)
2760     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
2761                sym->name, &c->loc);
2762   else if (gfc_pure (NULL))
2763     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
2764                &c->loc);
2765 }
2766
2767
2768 static match
2769 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
2770 {
2771   gfc_symbol *s;
2772
2773   if (sym->attr.generic)
2774     {
2775       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
2776       if (s != NULL)
2777         {
2778           c->resolved_sym = s;
2779           pure_subroutine (c, s);
2780           return MATCH_YES;
2781         }
2782
2783       /* TODO: Need to search for elemental references in generic interface.  */
2784     }
2785
2786   if (sym->attr.intrinsic)
2787     return gfc_intrinsic_sub_interface (c, 0);
2788
2789   return MATCH_NO;
2790 }
2791
2792
2793 static gfc_try
2794 resolve_generic_s (gfc_code *c)
2795 {
2796   gfc_symbol *sym;
2797   match m;
2798
2799   sym = c->symtree->n.sym;
2800
2801   for (;;)
2802     {
2803       m = resolve_generic_s0 (c, sym);
2804       if (m == MATCH_YES)
2805         return SUCCESS;
2806       else if (m == MATCH_ERROR)
2807         return FAILURE;
2808
2809 generic:
2810       if (sym->ns->parent == NULL)
2811         break;
2812       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2813
2814       if (sym == NULL)
2815         break;
2816       if (!generic_sym (sym))
2817         goto generic;
2818     }
2819
2820   /* Last ditch attempt.  See if the reference is to an intrinsic
2821      that possesses a matching interface.  14.1.2.4  */
2822   sym = c->symtree->n.sym;
2823
2824   if (!gfc_is_intrinsic (sym, 1, c->loc))
2825     {
2826       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
2827                  sym->name, &c->loc);
2828       return FAILURE;
2829     }
2830
2831   m = gfc_intrinsic_sub_interface (c, 0);
2832   if (m == MATCH_YES)
2833     return SUCCESS;
2834   if (m == MATCH_NO)
2835     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
2836                "intrinsic subroutine interface", sym->name, &c->loc);
2837
2838   return FAILURE;
2839 }
2840
2841
2842 /* Set the name and binding label of the subroutine symbol in the call
2843    expression represented by 'c' to include the type and kind of the
2844    second parameter.  This function is for resolving the appropriate
2845    version of c_f_pointer() and c_f_procpointer().  For example, a
2846    call to c_f_pointer() for a default integer pointer could have a
2847    name of c_f_pointer_i4.  If no second arg exists, which is an error
2848    for these two functions, it defaults to the generic symbol's name
2849    and binding label.  */
2850
2851 static void
2852 set_name_and_label (gfc_code *c, gfc_symbol *sym,
2853                     char *name, char *binding_label)
2854 {
2855   gfc_expr *arg = NULL;
2856   char type;
2857   int kind;
2858
2859   /* The second arg of c_f_pointer and c_f_procpointer determines
2860      the type and kind for the procedure name.  */
2861   arg = c->ext.actual->next->expr;
2862
2863   if (arg != NULL)
2864     {
2865       /* Set up the name to have the given symbol's name,
2866          plus the type and kind.  */
2867       /* a derived type is marked with the type letter 'u' */
2868       if (arg->ts.type == BT_DERIVED)
2869         {
2870           type = 'd';
2871           kind = 0; /* set the kind as 0 for now */
2872         }
2873       else
2874         {
2875           type = gfc_type_letter (arg->ts.type);
2876           kind = arg->ts.kind;
2877         }
2878
2879       if (arg->ts.type == BT_CHARACTER)
2880         /* Kind info for character strings not needed.  */
2881         kind = 0;
2882
2883       sprintf (name, "%s_%c%d", sym->name, type, kind);
2884       /* Set up the binding label as the given symbol's label plus
2885          the type and kind.  */
2886       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
2887     }
2888   else
2889     {
2890       /* If the second arg is missing, set the name and label as
2891          was, cause it should at least be found, and the missing
2892          arg error will be caught by compare_parameters().  */
2893       sprintf (name, "%s", sym->name);
2894       sprintf (binding_label, "%s", sym->binding_label);
2895     }
2896    
2897   return;
2898 }
2899
2900
2901 /* Resolve a generic version of the iso_c_binding procedure given
2902    (sym) to the specific one based on the type and kind of the
2903    argument(s).  Currently, this function resolves c_f_pointer() and
2904    c_f_procpointer based on the type and kind of the second argument
2905    (FPTR).  Other iso_c_binding procedures aren't specially handled.
2906    Upon successfully exiting, c->resolved_sym will hold the resolved
2907    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
2908    otherwise.  */
2909
2910 match
2911 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
2912 {
2913   gfc_symbol *new_sym;
2914   /* this is fine, since we know the names won't use the max */
2915   char name[GFC_MAX_SYMBOL_LEN + 1];
2916   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2917   /* default to success; will override if find error */
2918   match m = MATCH_YES;
2919
2920   /* Make sure the actual arguments are in the necessary order (based on the 
2921      formal args) before resolving.  */
2922   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
2923
2924   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
2925       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
2926     {
2927       set_name_and_label (c, sym, name, binding_label);
2928       
2929       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
2930         {
2931           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
2932             {
2933               /* Make sure we got a third arg if the second arg has non-zero
2934                  rank.  We must also check that the type and rank are
2935                  correct since we short-circuit this check in
2936                  gfc_procedure_use() (called above to sort actual args).  */
2937               if (c->ext.actual->next->expr->rank != 0)
2938                 {
2939                   if(c->ext.actual->next->next == NULL 
2940                      || c->ext.actual->next->next->expr == NULL)
2941                     {
2942                       m = MATCH_ERROR;
2943                       gfc_error ("Missing SHAPE parameter for call to %s "
2944                                  "at %L", sym->name, &(c->loc));
2945                     }
2946                   else if (c->ext.actual->next->next->expr->ts.type
2947                            != BT_INTEGER
2948                            || c->ext.actual->next->next->expr->rank != 1)
2949                     {
2950                       m = MATCH_ERROR;
2951                       gfc_error ("SHAPE parameter for call to %s at %L must "
2952                                  "be a rank 1 INTEGER array", sym->name,
2953                                  &(c->loc));
2954                     }
2955                 }
2956             }
2957         }
2958       
2959       if (m != MATCH_ERROR)
2960         {
2961           /* the 1 means to add the optional arg to formal list */
2962           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
2963          
2964           /* for error reporting, say it's declared where the original was */
2965           new_sym->declared_at = sym->declared_at;
2966         }
2967     }
2968   else
2969     {
2970       /* no differences for c_loc or c_funloc */
2971       new_sym = sym;
2972     }
2973
2974   /* set the resolved symbol */
2975   if (m != MATCH_ERROR)
2976     c->resolved_sym = new_sym;
2977   else
2978     c->resolved_sym = sym;
2979   
2980   return m;
2981 }
2982
2983
2984 /* Resolve a subroutine call known to be specific.  */
2985
2986 static match
2987 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
2988 {
2989   match m;
2990
2991   if(sym->attr.is_iso_c)
2992     {
2993       m = gfc_iso_c_sub_interface (c,sym);
2994       return m;
2995     }
2996   
2997   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2998     {
2999       if (sym->attr.dummy)
3000         {
3001           sym->attr.proc = PROC_DUMMY;
3002           goto found;
3003         }
3004
3005       sym->attr.proc = PROC_EXTERNAL;
3006       goto found;
3007     }
3008
3009   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3010     goto found;
3011
3012   if (sym->attr.intrinsic)
3013     {
3014       m = gfc_intrinsic_sub_interface (c, 1);
3015       if (m == MATCH_YES)
3016         return MATCH_YES;
3017       if (m == MATCH_NO)
3018         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3019                    "with an intrinsic", sym->name, &c->loc);
3020
3021       return MATCH_ERROR;
3022     }
3023
3024   return MATCH_NO;
3025
3026 found:
3027   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3028
3029   c->resolved_sym = sym;
3030   pure_subroutine (c, sym);
3031
3032   return MATCH_YES;
3033 }
3034
3035
3036 static gfc_try
3037 resolve_specific_s (gfc_code *c)
3038 {
3039   gfc_symbol *sym;
3040   match m;
3041
3042   sym = c->symtree->n.sym;
3043
3044   for (;;)
3045     {
3046       m = resolve_specific_s0 (c, sym);
3047       if (m == MATCH_YES)
3048         return SUCCESS;
3049       if (m == MATCH_ERROR)
3050         return FAILURE;
3051
3052       if (sym->ns->parent == NULL)
3053         break;
3054
3055       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3056
3057       if (sym == NULL)
3058         break;
3059     }
3060
3061   sym = c->symtree->n.sym;
3062   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3063              sym->name, &c->loc);
3064
3065   return FAILURE;
3066 }
3067
3068
3069 /* Resolve a subroutine call not known to be generic nor specific.  */
3070
3071 static gfc_try
3072 resolve_unknown_s (gfc_code *c)
3073 {
3074   gfc_symbol *sym;
3075
3076   sym = c->symtree->n.sym;
3077
3078   if (sym->attr.dummy)
3079     {
3080       sym->attr.proc = PROC_DUMMY;
3081       goto found;
3082     }
3083
3084   /* See if we have an intrinsic function reference.  */
3085
3086   if (gfc_is_intrinsic (sym, 1, c->loc))
3087     {
3088       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3089         return SUCCESS;
3090       return FAILURE;
3091     }
3092
3093   /* The reference is to an external name.  */
3094
3095 found:
3096   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3097
3098   c->resolved_sym = sym;
3099
3100   pure_subroutine (c, sym);
3101
3102   return SUCCESS;
3103 }
3104
3105
3106 /* Resolve a subroutine call.  Although it was tempting to use the same code
3107    for functions, subroutines and functions are stored differently and this
3108    makes things awkward.  */
3109
3110 static gfc_try
3111 resolve_call (gfc_code *c)
3112 {
3113   gfc_try t;
3114   procedure_type ptype = PROC_INTRINSIC;
3115   gfc_symbol *csym, *sym;
3116   bool no_formal_args;
3117
3118   csym = c->symtree ? c->symtree->n.sym : NULL;
3119
3120   if (csym && csym->ts.type != BT_UNKNOWN)
3121     {
3122       gfc_error ("'%s' at %L has a type, which is not consistent with "
3123                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3124       return FAILURE;
3125     }
3126
3127   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3128     {
3129       gfc_symtree *st;
3130       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
3131       sym = st ? st->n.sym : NULL;
3132       if (sym && csym != sym
3133               && sym->ns == gfc_current_ns
3134               && sym->attr.flavor == FL_PROCEDURE
3135               && sym->attr.contained)
3136         {
3137           sym->refs++;
3138           if (csym->attr.generic)
3139             c->symtree->n.sym = sym;
3140           else
3141             c->symtree = st;
3142           csym = c->symtree->n.sym;
3143         }
3144     }
3145
3146   /* If this ia a deferred TBP with an abstract interface
3147      (which may of course be referenced), c->expr1 will be set.  */
3148   if (csym && csym->attr.abstract && !c->expr1)
3149     {
3150       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3151                  csym->name, &c->loc);
3152       return FAILURE;
3153     }
3154
3155   /* Subroutines without the RECURSIVE attribution are not allowed to
3156    * call themselves.  */
3157   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3158     {
3159       if (csym->attr.entry && csym->ns->entries)
3160         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3161                    " subroutine '%s' is not RECURSIVE",
3162                    csym->name, &c->loc, csym->ns->entries->sym->name);
3163       else
3164         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3165                    " is not RECURSIVE", csym->name, &c->loc);
3166
3167       t = FAILURE;
3168     }
3169
3170   /* Switch off assumed size checking and do this again for certain kinds
3171      of procedure, once the procedure itself is resolved.  */
3172   need_full_assumed_size++;
3173
3174   if (csym)
3175     ptype = csym->attr.proc;
3176
3177   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3178   if (resolve_actual_arglist (c->ext.actual, ptype,
3179                               no_formal_args) == FAILURE)
3180     return FAILURE;
3181
3182   /* Resume assumed_size checking.  */
3183   need_full_assumed_size--;
3184
3185   /* If external, check for usage.  */
3186   if (csym && is_external_proc (csym))
3187     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3188
3189   t = SUCCESS;
3190   if (c->resolved_sym == NULL)
3191     {
3192       c->resolved_isym = NULL;
3193       switch (procedure_kind (csym))
3194         {
3195         case PTYPE_GENERIC:
3196           t = resolve_generic_s (c);
3197           break;
3198
3199         case PTYPE_SPECIFIC:
3200           t = resolve_specific_s (c);
3201           break;
3202
3203         case PTYPE_UNKNOWN:
3204           t = resolve_unknown_s (c);
3205           break;
3206
3207         default:
3208           gfc_internal_error ("resolve_subroutine(): bad function type");
3209         }
3210     }
3211
3212   /* Some checks of elemental subroutine actual arguments.  */
3213   if (resolve_elemental_actual (NULL, c) == FAILURE)
3214     return FAILURE;
3215
3216   if (t == SUCCESS && !(c->resolved_sym && c->resolved_sym->attr.elemental))
3217     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
3218   return t;
3219 }
3220
3221
3222 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3223    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3224    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3225    if their shapes do not match.  If either op1->shape or op2->shape is
3226    NULL, return SUCCESS.  */
3227
3228 static gfc_try
3229 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3230 {
3231   gfc_try t;
3232   int i;
3233
3234   t = SUCCESS;
3235
3236   if (op1->shape != NULL && op2->shape != NULL)
3237     {
3238       for (i = 0; i < op1->rank; i++)
3239         {
3240           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3241            {
3242              gfc_error ("Shapes for operands at %L and %L are not conformable",
3243                          &op1->where, &op2->where);
3244              t = FAILURE;
3245              break;
3246            }
3247         }
3248     }
3249
3250   return t;
3251 }
3252
3253
3254 /* Resolve an operator expression node.  This can involve replacing the
3255    operation with a user defined function call.  */
3256
3257 static gfc_try
3258 resolve_operator (gfc_expr *e)
3259 {
3260   gfc_expr *op1, *op2;
3261   char msg[200];
3262   bool dual_locus_error;
3263   gfc_try t;
3264
3265   /* Resolve all subnodes-- give them types.  */
3266
3267   switch (e->value.op.op)
3268     {
3269     default:
3270       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3271         return FAILURE;
3272
3273     /* Fall through...  */
3274
3275     case INTRINSIC_NOT:
3276     case INTRINSIC_UPLUS:
3277     case INTRINSIC_UMINUS:
3278     case INTRINSIC_PARENTHESES:
3279       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3280         return FAILURE;
3281       break;
3282     }
3283
3284   /* Typecheck the new node.  */
3285
3286   op1 = e->value.op.op1;
3287   op2 = e->value.op.op2;
3288   dual_locus_error = false;
3289
3290   if ((op1 && op1->expr_type == EXPR_NULL)
3291       || (op2 && op2->expr_type == EXPR_NULL))
3292     {
3293       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3294       goto bad_op;
3295     }
3296
3297   switch (e->value.op.op)
3298     {
3299     case INTRINSIC_UPLUS:
3300     case INTRINSIC_UMINUS:
3301       if (op1->ts.type == BT_INTEGER
3302           || op1->ts.type == BT_REAL
3303           || op1->ts.type == BT_COMPLEX)
3304         {
3305           e->ts = op1->ts;
3306           break;
3307         }
3308
3309       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3310                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3311       goto bad_op;
3312
3313     case INTRINSIC_PLUS:
3314     case INTRINSIC_MINUS:
3315     case INTRINSIC_TIMES:
3316     case INTRINSIC_DIVIDE:
3317     case INTRINSIC_POWER:
3318       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3319         {
3320           gfc_type_convert_binary (e);
3321           break;
3322         }
3323
3324       sprintf (msg,
3325                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3326                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3327                gfc_typename (&op2->ts));
3328       goto bad_op;
3329
3330     case INTRINSIC_CONCAT:
3331       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3332           && op1->ts.kind == op2->ts.kind)
3333         {
3334           e->ts.type = BT_CHARACTER;
3335           e->ts.kind = op1->ts.kind;
3336           break;
3337         }
3338
3339       sprintf (msg,
3340                _("Operands of string concatenation operator at %%L are %s/%s"),
3341                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3342       goto bad_op;
3343
3344     case INTRINSIC_AND:
3345     case INTRINSIC_OR:
3346     case INTRINSIC_EQV:
3347     case INTRINSIC_NEQV:
3348       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3349         {
3350           e->ts.type = BT_LOGICAL;
3351           e->ts.kind = gfc_kind_max (op1, op2);
3352           if (op1->ts.kind < e->ts.kind)
3353             gfc_convert_type (op1, &e->ts, 2);
3354           else if (op2->ts.kind < e->ts.kind)
3355             gfc_convert_type (op2, &e->ts, 2);
3356           break;
3357         }
3358
3359       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3360                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3361                gfc_typename (&op2->ts));
3362
3363       goto bad_op;
3364
3365     case INTRINSIC_NOT:
3366       if (op1->ts.type == BT_LOGICAL)
3367         {
3368           e->ts.type = BT_LOGICAL;
3369           e->ts.kind = op1->ts.kind;
3370           break;
3371         }
3372
3373       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3374                gfc_typename (&op1->ts));
3375       goto bad_op;
3376
3377     case INTRINSIC_GT:
3378     case INTRINSIC_GT_OS:
3379     case INTRINSIC_GE:
3380     case INTRINSIC_GE_OS:
3381     case INTRINSIC_LT:
3382     case INTRINSIC_LT_OS:
3383     case INTRINSIC_LE:
3384     case INTRINSIC_LE_OS:
3385       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3386         {
3387           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3388           goto bad_op;
3389         }
3390
3391       /* Fall through...  */
3392
3393     case INTRINSIC_EQ:
3394     case INTRINSIC_EQ_OS:
3395     case INTRINSIC_NE:
3396     case INTRINSIC_NE_OS:
3397       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3398           && op1->ts.kind == op2->ts.kind)
3399         {
3400           e->ts.type = BT_LOGICAL;
3401           e->ts.kind = gfc_default_logical_kind;
3402           break;
3403         }
3404
3405       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3406         {
3407           gfc_type_convert_binary (e);
3408
3409           e->ts.type = BT_LOGICAL;
3410           e->ts.kind = gfc_default_logical_kind;
3411           break;
3412         }
3413
3414       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3415         sprintf (msg,
3416                  _("Logicals at %%L must be compared with %s instead of %s"),
3417                  (e->value.op.op == INTRINSIC_EQ 
3418                   || e->value.op.op == INTRINSIC_EQ_OS)
3419                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3420       else
3421         sprintf (msg,
3422                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3423                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3424                  gfc_typename (&op2->ts));
3425
3426       goto bad_op;
3427
3428     case INTRINSIC_USER:
3429       if (e->value.op.uop->op == NULL)
3430         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3431       else if (op2 == NULL)
3432         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3433                  e->value.op.uop->name, gfc_typename (&op1->ts));
3434       else
3435         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3436                  e->value.op.uop->name, gfc_typename (&op1->ts),
3437                  gfc_typename (&op2->ts));
3438
3439       goto bad_op;
3440
3441     case INTRINSIC_PARENTHESES:
3442       e->ts = op1->ts;
3443       if (e->ts.type == BT_CHARACTER)
3444         e->ts.u.cl = op1->ts.u.cl;
3445       break;
3446
3447     default:
3448       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3449     }
3450
3451   /* Deal with arrayness of an operand through an operator.  */
3452
3453   t = SUCCESS;
3454
3455   switch (e->value.op.op)
3456     {
3457     case INTRINSIC_PLUS:
3458     case INTRINSIC_MINUS:
3459     case INTRINSIC_TIMES:
3460     case INTRINSIC_DIVIDE:
3461     case INTRINSIC_POWER:
3462     case INTRINSIC_CONCAT:
3463     case INTRINSIC_AND:
3464     case INTRINSIC_OR:
3465     case INTRINSIC_EQV:
3466     case INTRINSIC_NEQV:
3467     case INTRINSIC_EQ:
3468     case INTRINSIC_EQ_OS:
3469     case INTRINSIC_NE:
3470     case INTRINSIC_NE_OS:
3471     case INTRINSIC_GT:
3472     case INTRINSIC_GT_OS:
3473     case INTRINSIC_GE:
3474     case INTRINSIC_GE_OS:
3475     case INTRINSIC_LT:
3476     case INTRINSIC_LT_OS:
3477     case INTRINSIC_LE:
3478     case INTRINSIC_LE_OS:
3479
3480       if (op1->rank == 0 && op2->rank == 0)
3481         e->rank = 0;
3482
3483       if (op1->rank == 0 && op2->rank != 0)
3484         {
3485           e->rank = op2->rank;
3486
3487           if (e->shape == NULL)
3488             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3489         }
3490
3491       if (op1->rank != 0 && op2->rank == 0)
3492         {
3493           e->rank = op1->rank;
3494
3495           if (e->shape == NULL)
3496             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3497         }
3498
3499       if (op1->rank != 0 && op2->rank != 0)
3500         {
3501           if (op1->rank == op2->rank)
3502             {
3503               e->rank = op1->rank;
3504               if (e->shape == NULL)
3505                 {
3506                   t = compare_shapes(op1, op2);
3507                   if (t == FAILURE)
3508                     e->shape = NULL;
3509                   else
3510                 e->shape = gfc_copy_shape (op1->shape, op1->rank);
3511                 }
3512             }
3513           else
3514             {
3515               /* Allow higher level expressions to work.  */
3516               e->rank = 0;
3517
3518               /* Try user-defined operators, and otherwise throw an error.  */
3519               dual_locus_error = true;
3520               sprintf (msg,
3521                        _("Inconsistent ranks for operator at %%L and %%L"));
3522               goto bad_op;
3523             }
3524         }
3525
3526       break;
3527
3528     case INTRINSIC_PARENTHESES:
3529     case INTRINSIC_NOT:
3530     case INTRINSIC_UPLUS:
3531     case INTRINSIC_UMINUS:
3532       /* Simply copy arrayness attribute */
3533       e->rank = op1->rank;
3534
3535       if (e->shape == NULL)
3536         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3537
3538       break;
3539
3540     default:
3541       break;
3542     }
3543
3544   /* Attempt to simplify the expression.  */
3545   if (t == SUCCESS)
3546     {
3547       t = gfc_simplify_expr (e, 0);
3548       /* Some calls do not succeed in simplification and return FAILURE
3549          even though there is no error; e.g. variable references to
3550          PARAMETER arrays.  */
3551       if (!gfc_is_constant_expr (e))
3552         t = SUCCESS;
3553     }
3554   return t;
3555
3556 bad_op:
3557
3558   {
3559     bool real_error;
3560     if (gfc_extend_expr (e, &real_error) == SUCCESS)
3561       return SUCCESS;
3562
3563     if (real_error)
3564       return FAILURE;
3565   }
3566
3567   if (dual_locus_error)
3568     gfc_error (msg, &op1->where, &op2->where);
3569   else
3570     gfc_error (msg, &e->where);
3571
3572   return FAILURE;
3573 }
3574
3575
3576 /************** Array resolution subroutines **************/
3577
3578 typedef enum
3579 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
3580 comparison;
3581
3582 /* Compare two integer expressions.  */
3583
3584 static comparison
3585 compare_bound (gfc_expr *a, gfc_expr *b)
3586 {
3587   int i;
3588
3589   if (a == NULL || a->expr_type != EXPR_CONSTANT
3590       || b == NULL || b->expr_type != EXPR_CONSTANT)
3591     return CMP_UNKNOWN;
3592
3593   /* If either of the types isn't INTEGER, we must have
3594      raised an error earlier.  */
3595
3596   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
3597     return CMP_UNKNOWN;
3598
3599   i = mpz_cmp (a->value.integer, b->value.integer);
3600
3601   if (i < 0)
3602     return CMP_LT;
3603   if (i > 0)
3604     return CMP_GT;
3605   return CMP_EQ;
3606 }
3607
3608
3609 /* Compare an integer expression with an integer.  */
3610
3611 static comparison
3612 compare_bound_int (gfc_expr *a, int b)
3613 {
3614   int i;
3615
3616   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3617     return CMP_UNKNOWN;
3618
3619   if (a->ts.type != BT_INTEGER)
3620     gfc_internal_error ("compare_bound_int(): Bad expression");
3621
3622   i = mpz_cmp_si (a->value.integer, b);
3623
3624   if (i < 0)
3625     return CMP_LT;
3626   if (i > 0)
3627     return CMP_GT;
3628   return CMP_EQ;
3629 }
3630
3631
3632 /* Compare an integer expression with a mpz_t.  */
3633
3634 static comparison
3635 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
3636 {
3637   int i;
3638
3639   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3640     return CMP_UNKNOWN;
3641
3642   if (a->ts.type != BT_INTEGER)
3643     gfc_internal_error ("compare_bound_int(): Bad expression");
3644
3645   i = mpz_cmp (a->value.integer, b);
3646
3647   if (i < 0)
3648     return CMP_LT;
3649   if (i > 0)
3650     return CMP_GT;
3651   return CMP_EQ;
3652 }
3653
3654
3655 /* Compute the last value of a sequence given by a triplet.  
3656    Return 0 if it wasn't able to compute the last value, or if the
3657    sequence if empty, and 1 otherwise.  */
3658
3659 static int
3660 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
3661                                 gfc_expr *stride, mpz_t last)
3662 {
3663   mpz_t rem;
3664
3665   if (start == NULL || start->expr_type != EXPR_CONSTANT
3666       || end == NULL || end->expr_type != EXPR_CONSTANT
3667       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
3668     return 0;
3669
3670   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
3671       || (stride != NULL && stride->ts.type != BT_INTEGER))
3672     return 0;
3673
3674   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
3675     {
3676       if (compare_bound (start, end) == CMP_GT)
3677         return 0;
3678       mpz_set (last, end->value.integer);
3679       return 1;
3680     }
3681
3682   if (compare_bound_int (stride, 0) == CMP_GT)
3683     {
3684       /* Stride is positive */
3685       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
3686         return 0;
3687     }
3688   else
3689     {
3690       /* Stride is negative */
3691       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
3692         return 0;
3693     }
3694
3695   mpz_init (rem);
3696   mpz_sub (rem, end->value.integer, start->value.integer);
3697   mpz_tdiv_r (rem, rem, stride->value.integer);
3698   mpz_sub (last, end->value.integer, rem);
3699   mpz_clear (rem);
3700
3701   return 1;
3702 }
3703
3704
3705 /* Compare a single dimension of an array reference to the array
3706    specification.  */
3707
3708 static gfc_try
3709 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
3710 {
3711   mpz_t last_value;
3712
3713 /* Given start, end and stride values, calculate the minimum and
3714    maximum referenced indexes.  */
3715
3716   switch (ar->dimen_type[i])
3717     {
3718     case DIMEN_VECTOR:
3719       break;
3720
3721     case DIMEN_ELEMENT:
3722       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
3723         {
3724           gfc_warning ("Array reference at %L is out of bounds "
3725                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3726                        mpz_get_si (ar->start[i]->value.integer),
3727                        mpz_get_si (as->lower[i]->value.integer), i+1);
3728           return SUCCESS;
3729         }
3730       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
3731         {
3732           gfc_warning ("Array reference at %L is out of bounds "
3733                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3734                        mpz_get_si (ar->start[i]->value.integer),
3735                        mpz_get_si (as->upper[i]->value.integer), i+1);
3736           return SUCCESS;
3737         }
3738
3739       break;
3740
3741     case DIMEN_RANGE:
3742       {
3743 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
3744 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
3745
3746         comparison comp_start_end = compare_bound (AR_START, AR_END);
3747
3748         /* Check for zero stride, which is not allowed.  */
3749         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
3750           {
3751             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
3752             return FAILURE;
3753           }
3754
3755         /* if start == len || (stride > 0 && start < len)
3756                            || (stride < 0 && start > len),
3757            then the array section contains at least one element.  In this
3758            case, there is an out-of-bounds access if
3759            (start < lower || start > upper).  */
3760         if (compare_bound (AR_START, AR_END) == CMP_EQ
3761             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
3762                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
3763             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
3764                 && comp_start_end == CMP_GT))
3765           {
3766             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
3767               {
3768                 gfc_warning ("Lower array reference at %L is out of bounds "
3769                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3770                        mpz_get_si (AR_START->value.integer),
3771                        mpz_get_si (as->lower[i]->value.integer), i+1);
3772                 return SUCCESS;
3773               }
3774             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
3775               {
3776                 gfc_warning ("Lower array reference at %L is out of bounds "
3777                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3778                        mpz_get_si (AR_START->value.integer),
3779                        mpz_get_si (as->upper[i]->value.integer), i+1);
3780                 return SUCCESS;
3781               }
3782           }
3783
3784         /* If we can compute the highest index of the array section,
3785            then it also has to be between lower and upper.  */
3786         mpz_init (last_value);
3787         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
3788                                             last_value))
3789           {
3790             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
3791               {
3792                 gfc_warning ("Upper array reference at %L is out of bounds "
3793                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3794                        mpz_get_si (last_value),
3795                        mpz_get_si (as->lower[i]->value.integer), i+1);
3796                 mpz_clear (last_value);
3797                 return SUCCESS;
3798               }
3799             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
3800               {
3801                 gfc_warning ("Upper array reference at %L is out of bounds "
3802                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3803                        mpz_get_si (last_value),
3804                        mpz_get_si (as->upper[i]->value.integer), i+1);
3805                 mpz_clear (last_value);
3806                 return SUCCESS;
3807               }
3808           }
3809         mpz_clear (last_value);
3810
3811 #undef AR_START
3812 #undef AR_END
3813       }
3814       break;
3815
3816     default:
3817       gfc_internal_error ("check_dimension(): Bad array reference");
3818     }
3819
3820   return SUCCESS;
3821 }
3822
3823
3824 /* Compare an array reference with an array specification.  */
3825
3826 static gfc_try
3827 compare_spec_to_ref (gfc_array_ref *ar)
3828 {
3829   gfc_array_spec *as;
3830   int i;
3831
3832   as = ar->as;
3833   i = as->rank - 1;
3834   /* TODO: Full array sections are only allowed as actual parameters.  */
3835   if (as->type == AS_ASSUMED_SIZE
3836       && (/*ar->type == AR_FULL
3837           ||*/ (ar->type == AR_SECTION
3838               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
3839     {
3840       gfc_error ("Rightmost upper bound of assumed size array section "
3841                  "not specified at %L", &ar->where);
3842       return FAILURE;
3843     }
3844
3845   if (ar->type == AR_FULL)
3846     return SUCCESS;
3847
3848   if (as->rank != ar->dimen)
3849     {
3850       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
3851                  &ar->where, ar->dimen, as->rank);
3852       return FAILURE;
3853     }
3854
3855   for (i = 0; i < as->rank; i++)
3856     if (check_dimension (i, ar, as) == FAILURE)
3857       return FAILURE;
3858
3859   return SUCCESS;
3860 }
3861
3862
3863 /* Resolve one part of an array index.  */
3864
3865 gfc_try
3866 gfc_resolve_index (gfc_expr *index, int check_scalar)
3867 {
3868   gfc_typespec ts;
3869
3870   if (index == NULL)
3871     return SUCCESS;
3872
3873   if (gfc_resolve_expr (index) == FAILURE)
3874     return FAILURE;
3875
3876   if (check_scalar && index->rank != 0)
3877     {
3878       gfc_error ("Array index at %L must be scalar", &index->where);
3879       return FAILURE;
3880     }
3881
3882   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
3883     {
3884       gfc_error ("Array index at %L must be of INTEGER type, found %s",
3885                  &index->where, gfc_basic_typename (index->ts.type));
3886       return FAILURE;
3887     }
3888
3889   if (index->ts.type == BT_REAL)
3890     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
3891                         &index->where) == FAILURE)
3892       return FAILURE;
3893
3894   if (index->ts.kind != gfc_index_integer_kind
3895       || index->ts.type != BT_INTEGER)
3896     {
3897       gfc_clear_ts (&ts);
3898       ts.type = BT_INTEGER;
3899       ts.kind = gfc_index_integer_kind;
3900
3901       gfc_convert_type_warn (index, &ts, 2, 0);
3902     }
3903
3904   return SUCCESS;
3905 }
3906
3907 /* Resolve a dim argument to an intrinsic function.  */
3908
3909 gfc_try
3910 gfc_resolve_dim_arg (gfc_expr *dim)
3911 {
3912   if (dim == NULL)
3913     return SUCCESS;
3914
3915   if (gfc_resolve_expr (dim) == FAILURE)
3916     return FAILURE;
3917
3918   if (dim->rank != 0)
3919     {
3920       gfc_error ("Argument dim at %L must be scalar", &dim->where);
3921       return FAILURE;
3922
3923     }
3924
3925   if (dim->ts.type != BT_INTEGER)
3926     {
3927       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
3928       return FAILURE;
3929     }
3930
3931   if (dim->ts.kind != gfc_index_integer_kind)
3932     {
3933       gfc_typespec ts;
3934
3935       ts.type = BT_INTEGER;
3936       ts.kind = gfc_index_integer_kind;
3937
3938       gfc_convert_type_warn (dim, &ts, 2, 0);
3939     }
3940
3941   return SUCCESS;
3942 }
3943
3944 /* Given an expression that contains array references, update those array
3945    references to point to the right array specifications.  While this is
3946    filled in during matching, this information is difficult to save and load
3947    in a module, so we take care of it here.
3948
3949    The idea here is that the original array reference comes from the
3950    base symbol.  We traverse the list of reference structures, setting
3951    the stored reference to references.  Component references can
3952    provide an additional array specification.  */
3953
3954 static void
3955 find_array_spec (gfc_expr *e)
3956 {
3957   gfc_array_spec *as;
3958   gfc_component *c;
3959   gfc_symbol *derived;
3960   gfc_ref *ref;
3961
3962   if (e->symtree->n.sym->ts.type == BT_CLASS)
3963     as = e->symtree->n.sym->ts.u.derived->components->as;
3964   else
3965     as = e->symtree->n.sym->as;
3966   derived = NULL;
3967
3968   for (ref = e->ref; ref; ref = ref->next)
3969     switch (ref->type)
3970       {
3971       case REF_ARRAY:
3972         if (as == NULL)
3973           gfc_internal_error ("find_array_spec(): Missing spec");
3974
3975         ref->u.ar.as = as;
3976         as = NULL;
3977         break;
3978
3979       case REF_COMPONENT:
3980         if (derived == NULL)
3981           derived = e->symtree->n.sym->ts.u.derived;
3982
3983         c = derived->components;
3984
3985         for (; c; c = c->next)
3986           if (c == ref->u.c.component)
3987             {
3988               /* Track the sequence of component references.  */
3989               if (c->ts.type == BT_DERIVED)
3990                 derived = c->ts.u.derived;
3991               break;
3992             }
3993
3994         if (c == NULL)
3995           gfc_internal_error ("find_array_spec(): Component not found");
3996
3997         if (c->attr.dimension)
3998           {
3999             if (as != NULL)
4000               gfc_internal_error ("find_array_spec(): unused as(1)");
4001             as = c->as;
4002           }
4003
4004         break;
4005
4006       case REF_SUBSTRING:
4007         break;
4008       }
4009
4010   if (as != NULL)
4011     gfc_internal_error ("find_array_spec(): unused as(2)");
4012 }
4013
4014
4015 /* Resolve an array reference.  */
4016
4017 static gfc_try
4018 resolve_array_ref (gfc_array_ref *ar)
4019 {
4020   int i, check_scalar;
4021   gfc_expr *e;
4022
4023   for (i = 0; i < ar->dimen; i++)
4024     {
4025       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4026
4027       if (gfc_resolve_index (ar->start[i], check_scalar) == FAILURE)
4028         return FAILURE;
4029       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4030         return FAILURE;
4031       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4032         return FAILURE;
4033
4034       e = ar->start[i];
4035
4036       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4037         switch (e->rank)
4038           {
4039           case 0:
4040             ar->dimen_type[i] = DIMEN_ELEMENT;
4041             break;
4042
4043           case 1:
4044             ar->dimen_type[i] = DIMEN_VECTOR;
4045             if (e->expr_type == EXPR_VARIABLE
4046                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4047               ar->start[i] = gfc_get_parentheses (e);
4048             break;
4049
4050           default:
4051             gfc_error ("Array index at %L is an array of rank %d",
4052                        &ar->c_where[i], e->rank);
4053             return FAILURE;
4054           }
4055     }
4056
4057   /* If the reference type is unknown, figure out what kind it is.  */
4058
4059   if (ar->type == AR_UNKNOWN)
4060     {
4061       ar->type = AR_ELEMENT;
4062       for (i = 0; i < ar->dimen; i++)
4063         if (ar->dimen_type[i] == DIMEN_RANGE
4064             || ar->dimen_type[i] == DIMEN_VECTOR)
4065           {
4066             ar->type = AR_SECTION;
4067             break;
4068           }
4069     }
4070
4071   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4072     return FAILURE;
4073
4074   return SUCCESS;
4075 }
4076
4077
4078 static gfc_try
4079 resolve_substring (gfc_ref *ref)
4080 {
4081   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4082
4083   if (ref->u.ss.start != NULL)
4084     {
4085       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4086         return FAILURE;
4087
4088       if (ref->u.ss.start->ts.type != BT_INTEGER)
4089         {
4090           gfc_error ("Substring start index at %L must be of type INTEGER",
4091                      &ref->u.ss.start->where);
4092           return FAILURE;
4093         }
4094
4095       if (ref->u.ss.start->rank != 0)
4096         {
4097           gfc_error ("Substring start index at %L must be scalar",
4098                      &ref->u.ss.start->where);
4099           return FAILURE;
4100         }
4101
4102       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4103           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4104               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4105         {
4106           gfc_error ("Substring start index at %L is less than one",
4107                      &ref->u.ss.start->where);
4108           return FAILURE;
4109         }
4110     }
4111
4112   if (ref->u.ss.end != NULL)
4113     {
4114       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4115         return FAILURE;
4116
4117       if (ref->u.ss.end->ts.type != BT_INTEGER)
4118         {
4119           gfc_error ("Substring end index at %L must be of type INTEGER",
4120                      &ref->u.ss.end->where);
4121           return FAILURE;
4122         }
4123
4124       if (ref->u.ss.end->rank != 0)
4125         {
4126           gfc_error ("Substring end index at %L must be scalar",
4127                      &ref->u.ss.end->where);
4128           return FAILURE;
4129         }
4130
4131       if (ref->u.ss.length != NULL
4132           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4133           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4134               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4135         {
4136           gfc_error ("Substring end index at %L exceeds the string length",
4137                      &ref->u.ss.start->where);
4138           return FAILURE;
4139         }
4140
4141       if (compare_bound_mpz_t (ref->u.ss.end,
4142                                gfc_integer_kinds[k].huge) == CMP_GT
4143           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4144               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4145         {
4146           gfc_error ("Substring end index at %L is too large",
4147                      &ref->u.ss.end->where);
4148           return FAILURE;
4149         }
4150     }
4151
4152   return SUCCESS;
4153 }
4154
4155
4156 /* This function supplies missing substring charlens.  */
4157
4158 void
4159 gfc_resolve_substring_charlen (gfc_expr *e)
4160 {
4161   gfc_ref *char_ref;
4162   gfc_expr *start, *end;
4163
4164   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4165     if (char_ref->type == REF_SUBSTRING)
4166       break;
4167
4168   if (!char_ref)
4169     return;
4170
4171   gcc_assert (char_ref->next == NULL);
4172
4173   if (e->ts.u.cl)
4174     {
4175       if (e->ts.u.cl->length)
4176         gfc_free_expr (e->ts.u.cl->length);
4177       else if (e->expr_type == EXPR_VARIABLE
4178                  && e->symtree->n.sym->attr.dummy)
4179         return;
4180     }
4181
4182   e->ts.type = BT_CHARACTER;
4183   e->ts.kind = gfc_default_character_kind;
4184
4185   if (!e->ts.u.cl)
4186     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4187
4188   if (char_ref->u.ss.start)
4189     start = gfc_copy_expr (char_ref->u.ss.start);
4190   else
4191     start = gfc_int_expr (1);
4192
4193   if (char_ref->u.ss.end)
4194     end = gfc_copy_expr (char_ref->u.ss.end);
4195   else if (e->expr_type == EXPR_VARIABLE)
4196     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4197   else
4198     end = NULL;
4199
4200   if (!start || !end)
4201     return;
4202
4203   /* Length = (end - start +1).  */
4204   e->ts.u.cl->length = gfc_subtract (end, start);
4205   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length, gfc_int_expr (1));
4206
4207   e->ts.u.cl->length->ts.type = BT_INTEGER;
4208   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4209
4210   /* Make sure that the length is simplified.  */
4211   gfc_simplify_expr (e->ts.u.cl->length, 1);
4212   gfc_resolve_expr (e->ts.u.cl->length);
4213 }
4214
4215
4216 /* Resolve subtype references.  */
4217
4218 static gfc_try
4219 resolve_ref (gfc_expr *expr)
4220 {
4221   int current_part_dimension, n_components, seen_part_dimension;
4222   gfc_ref *ref;
4223
4224   for (ref = expr->ref; ref; ref = ref->next)
4225     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4226       {
4227         find_array_spec (expr);
4228         break;
4229       }
4230
4231   for (ref = expr->ref; ref; ref = ref->next)
4232     switch (ref->type)
4233       {
4234       case REF_ARRAY:
4235         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4236           return FAILURE;
4237         break;
4238
4239       case REF_COMPONENT:
4240         break;
4241
4242       case REF_SUBSTRING:
4243         resolve_substring (ref);
4244         break;
4245       }
4246
4247   /* Check constraints on part references.  */
4248
4249   current_part_dimension = 0;
4250   seen_part_dimension = 0;
4251   n_components = 0;
4252
4253   for (ref = expr->ref; ref; ref = ref->next)
4254     {
4255       switch (ref->type)
4256         {
4257         case REF_ARRAY:
4258           switch (ref->u.ar.type)
4259             {
4260             case AR_FULL:
4261             case AR_SECTION:
4262               current_part_dimension = 1;
4263               break;
4264
4265             case AR_ELEMENT:
4266               current_part_dimension = 0;
4267               break;
4268
4269             case AR_UNKNOWN:
4270               gfc_internal_error ("resolve_ref(): Bad array reference");
4271             }
4272
4273           break;
4274
4275         case REF_COMPONENT:
4276           if (current_part_dimension || seen_part_dimension)
4277             {
4278               /* F03:C614.  */
4279               if (ref->u.c.component->attr.pointer
4280                   || ref->u.c.component->attr.proc_pointer)
4281                 {
4282                   gfc_error ("Component to the right of a part reference "
4283                              "with nonzero rank must not have the POINTER "
4284                              "attribute at %L", &expr->where);
4285                   return FAILURE;
4286                 }
4287               else if (ref->u.c.component->attr.allocatable)
4288                 {
4289                   gfc_error ("Component to the right of a part reference "
4290                              "with nonzero rank must not have the ALLOCATABLE "
4291                              "attribute at %L", &expr->where);
4292                   return FAILURE;
4293                 }
4294             }
4295
4296           n_components++;
4297           break;
4298
4299         case REF_SUBSTRING:
4300           break;
4301         }
4302
4303       if (((ref->type == REF_COMPONENT && n_components > 1)
4304            || ref->next == NULL)
4305           && current_part_dimension
4306           && seen_part_dimension)
4307         {
4308           gfc_error ("Two or more part references with nonzero rank must "
4309                      "not be specified at %L", &expr->where);
4310           return FAILURE;
4311         }
4312
4313       if (ref->type == REF_COMPONENT)
4314         {
4315           if (current_part_dimension)
4316             seen_part_dimension = 1;
4317
4318           /* reset to make sure */
4319           current_part_dimension = 0;
4320         }
4321     }
4322
4323   return SUCCESS;
4324 }
4325
4326
4327 /* Given an expression, determine its shape.  This is easier than it sounds.
4328    Leaves the shape array NULL if it is not possible to determine the shape.  */
4329
4330 static void
4331 expression_shape (gfc_expr *e)
4332 {
4333   mpz_t array[GFC_MAX_DIMENSIONS];
4334   int i;
4335
4336   if (e->rank == 0 || e->shape != NULL)
4337     return;
4338
4339   for (i = 0; i < e->rank; i++)
4340     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4341       goto fail;
4342
4343   e->shape = gfc_get_shape (e->rank);
4344
4345   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4346
4347   return;
4348
4349 fail:
4350   for (i--; i >= 0; i--)
4351     mpz_clear (array[i]);
4352 }
4353
4354
4355 /* Given a variable expression node, compute the rank of the expression by
4356    examining the base symbol and any reference structures it may have.  */
4357
4358 static void
4359 expression_rank (gfc_expr *e)
4360 {
4361   gfc_ref *ref;
4362   int i, rank;
4363
4364   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4365      could lead to serious confusion...  */
4366   gcc_assert (e->expr_type != EXPR_COMPCALL);
4367
4368   if (e->ref == NULL)
4369     {
4370       if (e->expr_type == EXPR_ARRAY)
4371         goto done;
4372       /* Constructors can have a rank different from one via RESHAPE().  */
4373
4374       if (e->symtree == NULL)
4375         {
4376           e->rank = 0;
4377           goto done;
4378         }
4379
4380       e->rank = (e->symtree->n.sym->as == NULL)
4381                 ? 0 : e->symtree->n.sym->as->rank;
4382       goto done;
4383     }
4384
4385   rank = 0;
4386
4387   for (ref = e->ref; ref; ref = ref->next)
4388     {
4389       if (ref->type != REF_ARRAY)
4390         continue;
4391
4392       if (ref->u.ar.type == AR_FULL)
4393         {
4394           rank = ref->u.ar.as->rank;
4395           break;
4396         }
4397
4398       if (ref->u.ar.type == AR_SECTION)
4399         {
4400           /* Figure out the rank of the section.  */
4401           if (rank != 0)
4402             gfc_internal_error ("expression_rank(): Two array specs");
4403
4404           for (i = 0; i < ref->u.ar.dimen; i++)
4405             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4406                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4407               rank++;
4408
4409           break;
4410         }
4411     }
4412
4413   e->rank = rank;
4414
4415 done:
4416   expression_shape (e);
4417 }
4418
4419
4420 /* Resolve a variable expression.  */
4421
4422 static gfc_try
4423 resolve_variable (gfc_expr *e)
4424 {
4425   gfc_symbol *sym;
4426   gfc_try t;
4427
4428   t = SUCCESS;
4429
4430   if (e->symtree == NULL)
4431     return FAILURE;
4432
4433   if (e->ref && resolve_ref (e) == FAILURE)
4434     return FAILURE;
4435
4436   sym = e->symtree->n.sym;
4437   if (sym->attr.flavor == FL_PROCEDURE
4438       && (!sym->attr.function
4439           || (sym->attr.function && sym->result
4440               && sym->result->attr.proc_pointer
4441               && !sym->result->attr.function)))
4442     {
4443       e->ts.type = BT_PROCEDURE;
4444       goto resolve_procedure;
4445     }
4446
4447   if (sym->ts.type != BT_UNKNOWN)
4448     gfc_variable_attr (e, &e->ts);
4449   else
4450     {
4451       /* Must be a simple variable reference.  */
4452       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
4453         return FAILURE;
4454       e->ts = sym->ts;
4455     }
4456
4457   if (check_assumed_size_reference (sym, e))
4458     return FAILURE;
4459
4460   /* Deal with forward references to entries during resolve_code, to
4461      satisfy, at least partially, 12.5.2.5.  */
4462   if (gfc_current_ns->entries
4463       && current_entry_id == sym->entry_id
4464       && cs_base
4465       && cs_base->current
4466       && cs_base->current->op != EXEC_ENTRY)
4467     {
4468       gfc_entry_list *entry;
4469       gfc_formal_arglist *formal;
4470       int n;
4471       bool seen;
4472
4473       /* If the symbol is a dummy...  */
4474       if (sym->attr.dummy && sym->ns == gfc_current_ns)
4475         {
4476           entry = gfc_current_ns->entries;
4477           seen = false;
4478
4479           /* ...test if the symbol is a parameter of previous entries.  */
4480           for (; entry && entry->id <= current_entry_id; entry = entry->next)
4481             for (formal = entry->sym->formal; formal; formal = formal->next)
4482               {
4483                 if (formal->sym && sym->name == formal->sym->name)
4484                   seen = true;
4485               }
4486
4487           /*  If it has not been seen as a dummy, this is an error.  */
4488           if (!seen)
4489             {
4490               if (specification_expr)
4491                 gfc_error ("Variable '%s', used in a specification expression"
4492                            ", is referenced at %L before the ENTRY statement "
4493                            "in which it is a parameter",
4494                            sym->name, &cs_base->current->loc);
4495               else
4496                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
4497                            "statement in which it is a parameter",
4498                            sym->name, &cs_base->current->loc);
4499               t = FAILURE;
4500             }
4501         }
4502
4503       /* Now do the same check on the specification expressions.  */
4504       specification_expr = 1;
4505       if (sym->ts.type == BT_CHARACTER
4506           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
4507         t = FAILURE;
4508
4509       if (sym->as)
4510         for (n = 0; n < sym->as->rank; n++)
4511           {
4512              specification_expr = 1;
4513              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
4514                t = FAILURE;
4515              specification_expr = 1;
4516              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
4517                t = FAILURE;
4518           }
4519       specification_expr = 0;
4520
4521       if (t == SUCCESS)
4522         /* Update the symbol's entry level.  */
4523         sym->entry_id = current_entry_id + 1;
4524     }
4525
4526 resolve_procedure:
4527   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
4528     t = FAILURE;
4529
4530   return t;
4531 }
4532
4533
4534 /* Checks to see that the correct symbol has been host associated.
4535    The only situation where this arises is that in which a twice
4536    contained function is parsed after the host association is made.
4537    Therefore, on detecting this, change the symbol in the expression
4538    and convert the array reference into an actual arglist if the old
4539    symbol is a variable.  */
4540 static bool
4541 check_host_association (gfc_expr *e)
4542 {
4543   gfc_symbol *sym, *old_sym;
4544   gfc_symtree *st;
4545   int n;
4546   gfc_ref *ref;
4547   gfc_actual_arglist *arg, *tail = NULL;
4548   bool retval = e->expr_type == EXPR_FUNCTION;
4549
4550   /*  If the expression is the result of substitution in
4551       interface.c(gfc_extend_expr) because there is no way in
4552       which the host association can be wrong.  */
4553   if (e->symtree == NULL
4554         || e->symtree->n.sym == NULL
4555         || e->user_operator)
4556     return retval;
4557
4558   old_sym = e->symtree->n.sym;
4559
4560   if (gfc_current_ns->parent
4561         && old_sym->ns != gfc_current_ns)
4562     {
4563       /* Use the 'USE' name so that renamed module symbols are
4564          correctly handled.  */
4565       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
4566
4567       if (sym && old_sym != sym
4568               && sym->ts.type == old_sym->ts.type
4569               && sym->attr.flavor == FL_PROCEDURE
4570               && sym->attr.contained)
4571         {
4572           /* Clear the shape, since it might not be valid.  */
4573           if (e->shape != NULL)
4574             {
4575               for (n = 0; n < e->rank; n++)
4576                 mpz_clear (e->shape[n]);
4577
4578               gfc_free (e->shape);
4579             }
4580
4581           /* Give the expression the right symtree!  */
4582           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
4583           gcc_assert (st != NULL);
4584
4585           if (old_sym->attr.flavor == FL_PROCEDURE
4586                 || e->expr_type == EXPR_FUNCTION)
4587             {
4588               /* Original was function so point to the new symbol, since
4589                  the actual argument list is already attached to the
4590                  expression. */
4591               e->value.function.esym = NULL;
4592               e->symtree = st;
4593             }
4594           else
4595             {
4596               /* Original was variable so convert array references into
4597                  an actual arglist. This does not need any checking now
4598                  since gfc_resolve_function will take care of it.  */
4599               e->value.function.actual = NULL;
4600               e->expr_type = EXPR_FUNCTION;
4601               e->symtree = st;
4602
4603               /* Ambiguity will not arise if the array reference is not
4604                  the last reference.  */
4605               for (ref = e->ref; ref; ref = ref->next)
4606                 if (ref->type == REF_ARRAY && ref->next == NULL)
4607                   break;
4608
4609               gcc_assert (ref->type == REF_ARRAY);
4610
4611               /* Grab the start expressions from the array ref and
4612                  copy them into actual arguments.  */
4613               for (n = 0; n < ref->u.ar.dimen; n++)
4614                 {
4615                   arg = gfc_get_actual_arglist ();
4616                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
4617                   if (e->value.function.actual == NULL)
4618                     tail = e->value.function.actual = arg;
4619                   else
4620                     {
4621                       tail->next = arg;
4622                       tail = arg;
4623                     }
4624                 }
4625
4626               /* Dump the reference list and set the rank.  */
4627               gfc_free_ref_list (e->ref);
4628               e->ref = NULL;
4629               e->rank = sym->as ? sym->as->rank : 0;
4630             }
4631
4632           gfc_resolve_expr (e);
4633           sym->refs++;
4634         }
4635     }
4636   /* This might have changed!  */
4637   return e->expr_type == EXPR_FUNCTION;
4638 }
4639
4640
4641 static void
4642 gfc_resolve_character_operator (gfc_expr *e)
4643 {
4644   gfc_expr *op1 = e->value.op.op1;
4645   gfc_expr *op2 = e->value.op.op2;
4646   gfc_expr *e1 = NULL;
4647   gfc_expr *e2 = NULL;
4648
4649   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
4650
4651   if (op1->ts.u.cl && op1->ts.u.cl->length)
4652     e1 = gfc_copy_expr (op1->ts.u.cl->length);
4653   else if (op1->expr_type == EXPR_CONSTANT)
4654     e1 = gfc_int_expr (op1->value.character.length);
4655
4656   if (op2->ts.u.cl && op2->ts.u.cl->length)
4657     e2 = gfc_copy_expr (op2->ts.u.cl->length);
4658   else if (op2->expr_type == EXPR_CONSTANT)
4659     e2 = gfc_int_expr (op2->value.character.length);
4660
4661   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4662
4663   if (!e1 || !e2)
4664     return;
4665
4666   e->ts.u.cl->length = gfc_add (e1, e2);
4667   e->ts.u.cl->length->ts.type = BT_INTEGER;
4668   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4669   gfc_simplify_expr (e->ts.u.cl->length, 0);
4670   gfc_resolve_expr (e->ts.u.cl->length);
4671
4672   return;
4673 }
4674
4675
4676 /*  Ensure that an character expression has a charlen and, if possible, a
4677     length expression.  */
4678
4679 static void
4680 fixup_charlen (gfc_expr *e)
4681 {
4682   /* The cases fall through so that changes in expression type and the need
4683      for multiple fixes are picked up.  In all circumstances, a charlen should
4684      be available for the middle end to hang a backend_decl on.  */
4685   switch (e->expr_type)
4686     {
4687     case EXPR_OP:
4688       gfc_resolve_character_operator (e);
4689
4690     case EXPR_ARRAY:
4691       if (e->expr_type == EXPR_ARRAY)
4692         gfc_resolve_character_array_constructor (e);
4693
4694     case EXPR_SUBSTRING:
4695       if (!e->ts.u.cl && e->ref)
4696         gfc_resolve_substring_charlen (e);
4697
4698     default:
4699       if (!e->ts.u.cl)
4700         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4701
4702       break;
4703     }
4704 }
4705
4706
4707 /* Update an actual argument to include the passed-object for type-bound
4708    procedures at the right position.  */
4709
4710 static gfc_actual_arglist*
4711 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
4712                      const char *name)
4713 {
4714   gcc_assert (argpos > 0);
4715
4716   if (argpos == 1)
4717     {
4718       gfc_actual_arglist* result;
4719
4720       result = gfc_get_actual_arglist ();
4721       result->expr = po;
4722       result->next = lst;
4723       if (name)
4724         result->name = name;
4725
4726       return result;
4727     }
4728
4729   if (lst)
4730     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
4731   else
4732     lst = update_arglist_pass (NULL, po, argpos - 1, name);
4733   return lst;
4734 }
4735
4736
4737 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
4738
4739 static gfc_expr*
4740 extract_compcall_passed_object (gfc_expr* e)
4741 {
4742   gfc_expr* po;
4743
4744   gcc_assert (e->expr_type == EXPR_COMPCALL);
4745
4746   if (e->value.compcall.base_object)
4747     po = gfc_copy_expr (e->value.compcall.base_object);
4748   else
4749     {
4750       po = gfc_get_expr ();
4751       po->expr_type = EXPR_VARIABLE;
4752       po->symtree = e->symtree;
4753       po->ref = gfc_copy_ref (e->ref);
4754     }
4755
4756   if (gfc_resolve_expr (po) == FAILURE)
4757     return NULL;
4758
4759   return po;
4760 }
4761
4762
4763 /* Update the arglist of an EXPR_COMPCALL expression to include the
4764    passed-object.  */
4765
4766 static gfc_try
4767 update_compcall_arglist (gfc_expr* e)
4768 {
4769   gfc_expr* po;
4770   gfc_typebound_proc* tbp;
4771
4772   tbp = e->value.compcall.tbp;
4773
4774   if (tbp->error)
4775     return FAILURE;
4776
4777   po = extract_compcall_passed_object (e);
4778   if (!po)
4779     return FAILURE;
4780
4781   if (po->rank > 0)
4782     {
4783       gfc_error ("Passed-object at %L must be scalar", &e->where);
4784       return FAILURE;
4785     }
4786
4787   if (tbp->nopass || e->value.compcall.ignore_pass)
4788     {
4789       gfc_free_expr (po);
4790       return SUCCESS;
4791     }
4792
4793   gcc_assert (tbp->pass_arg_num > 0);
4794   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
4795                                                   tbp->pass_arg_num,
4796                                                   tbp->pass_arg);
4797
4798   return SUCCESS;
4799 }
4800
4801
4802 /* Extract the passed object from a PPC call (a copy of it).  */
4803
4804 static gfc_expr*
4805 extract_ppc_passed_object (gfc_expr *e)
4806 {
4807   gfc_expr *po;
4808   gfc_ref **ref;
4809
4810   po = gfc_get_expr ();
4811   po->expr_type = EXPR_VARIABLE;
4812   po->symtree = e->symtree;
4813   po->ref = gfc_copy_ref (e->ref);
4814
4815   /* Remove PPC reference.  */
4816   ref = &po->ref;
4817   while ((*ref)->next)
4818     (*ref) = (*ref)->next;
4819   gfc_free_ref_list (*ref);
4820   *ref = NULL;
4821
4822   if (gfc_resolve_expr (po) == FAILURE)
4823     return NULL;
4824
4825   return po;
4826 }
4827
4828
4829 /* Update the actual arglist of a procedure pointer component to include the
4830    passed-object.  */
4831
4832 static gfc_try
4833 update_ppc_arglist (gfc_expr* e)
4834 {
4835   gfc_expr* po;
4836   gfc_component *ppc;
4837   gfc_typebound_proc* tb;
4838
4839   if (!gfc_is_proc_ptr_comp (e, &ppc))
4840     return FAILURE;
4841
4842   tb = ppc->tb;
4843
4844   if (tb->error)
4845     return FAILURE;
4846   else if (tb->nopass)
4847     return SUCCESS;
4848
4849   po = extract_ppc_passed_object (e);
4850   if (!po)
4851     return FAILURE;
4852
4853   if (po->rank > 0)
4854     {
4855       gfc_error ("Passed-object at %L must be scalar", &e->where);
4856       return FAILURE;
4857     }
4858
4859   gcc_assert (tb->pass_arg_num > 0);
4860   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
4861                                                   tb->pass_arg_num,
4862                                                   tb->pass_arg);
4863
4864   return SUCCESS;
4865 }
4866
4867
4868 /* Check that the object a TBP is called on is valid, i.e. it must not be
4869    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
4870
4871 static gfc_try
4872 check_typebound_baseobject (gfc_expr* e)
4873 {
4874   gfc_expr* base;
4875
4876   base = extract_compcall_passed_object (e);
4877   if (!base)
4878     return FAILURE;
4879
4880   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
4881
4882   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
4883     {
4884       gfc_error ("Base object for type-bound procedure call at %L is of"
4885                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
4886       return FAILURE;
4887     }
4888
4889   return SUCCESS;
4890 }
4891
4892
4893 /* Resolve a call to a type-bound procedure, either function or subroutine,
4894    statically from the data in an EXPR_COMPCALL expression.  The adapted
4895    arglist and the target-procedure symtree are returned.  */
4896
4897 static gfc_try
4898 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
4899                           gfc_actual_arglist** actual)
4900 {
4901   gcc_assert (e->expr_type == EXPR_COMPCALL);
4902   gcc_assert (!e->value.compcall.tbp->is_generic);
4903
4904   /* Update the actual arglist for PASS.  */
4905   if (update_compcall_arglist (e) == FAILURE)
4906     return FAILURE;
4907
4908   *actual = e->value.compcall.actual;
4909   *target = e->value.compcall.tbp->u.specific;
4910
4911   gfc_free_ref_list (e->ref);
4912   e->ref = NULL;
4913   e->value.compcall.actual = NULL;
4914
4915   return SUCCESS;
4916 }
4917
4918
4919 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
4920    which of the specific bindings (if any) matches the arglist and transform
4921    the expression into a call of that binding.  */
4922
4923 static gfc_try
4924 resolve_typebound_generic_call (gfc_expr* e)
4925 {
4926   gfc_typebound_proc* genproc;
4927   const char* genname;
4928
4929   gcc_assert (e->expr_type == EXPR_COMPCALL);
4930   genname = e->value.compcall.name;
4931   genproc = e->value.compcall.tbp;
4932
4933   if (!genproc->is_generic)
4934     return SUCCESS;
4935
4936   /* Try the bindings on this type and in the inheritance hierarchy.  */
4937   for (; genproc; genproc = genproc->overridden)
4938     {
4939       gfc_tbp_generic* g;
4940
4941       gcc_assert (genproc->is_generic);
4942       for (g = genproc->u.generic; g; g = g->next)
4943         {
4944           gfc_symbol* target;
4945           gfc_actual_arglist* args;
4946           bool matches;
4947
4948           gcc_assert (g->specific);
4949
4950           if (g->specific->error)
4951             continue;
4952
4953           target = g->specific->u.specific->n.sym;
4954
4955           /* Get the right arglist by handling PASS/NOPASS.  */
4956           args = gfc_copy_actual_arglist (e->value.compcall.actual);
4957           if (!g->specific->nopass)
4958             {
4959               gfc_expr* po;
4960               po = extract_compcall_passed_object (e);
4961               if (!po)
4962                 return FAILURE;
4963
4964               gcc_assert (g->specific->pass_arg_num > 0);
4965               gcc_assert (!g->specific->error);
4966               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
4967                                           g->specific->pass_arg);
4968             }
4969           resolve_actual_arglist (args, target->attr.proc,
4970                                   is_external_proc (target) && !target->formal);
4971
4972           /* Check if this arglist matches the formal.  */
4973           matches = gfc_arglist_matches_symbol (&args, target);
4974
4975           /* Clean up and break out of the loop if we've found it.  */
4976           gfc_free_actual_arglist (args);
4977           if (matches)
4978             {
4979               e->value.compcall.tbp = g->specific;
4980               goto success;
4981             }
4982         }
4983     }
4984
4985   /* Nothing matching found!  */
4986   gfc_error ("Found no matching specific binding for the call to the GENERIC"
4987              " '%s' at %L", genname, &e->where);
4988   return FAILURE;
4989
4990 success:
4991   return SUCCESS;
4992 }
4993
4994
4995 /* Resolve a call to a type-bound subroutine.  */
4996
4997 static gfc_try
4998 resolve_typebound_call (gfc_code* c)
4999 {
5000   gfc_actual_arglist* newactual;
5001   gfc_symtree* target;
5002
5003   /* Check that's really a SUBROUTINE.  */
5004   if (!c->expr1->value.compcall.tbp->subroutine)
5005     {
5006       gfc_error ("'%s' at %L should be a SUBROUTINE",
5007                  c->expr1->value.compcall.name, &c->loc);
5008       return FAILURE;
5009     }
5010
5011   if (check_typebound_baseobject (c->expr1) == FAILURE)
5012     return FAILURE;
5013
5014   if (resolve_typebound_generic_call (c->expr1) == FAILURE)
5015     return FAILURE;
5016
5017   /* Transform into an ordinary EXEC_CALL for now.  */
5018
5019   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5020     return FAILURE;
5021
5022   c->ext.actual = newactual;
5023   c->symtree = target;
5024   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5025
5026   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5027
5028   gfc_free_expr (c->expr1);
5029   c->expr1 = gfc_get_expr ();
5030   c->expr1->expr_type = EXPR_FUNCTION;
5031   c->expr1->symtree = target;
5032   c->expr1->where = c->loc;
5033
5034   return resolve_call (c);
5035 }
5036
5037
5038 /* Resolve a component-call expression.  This originally was intended
5039    only to see functions.  However, it is convenient to use it in 
5040    resolving subroutine class methods, since we do not have to add a
5041    gfc_code each time. */
5042 static gfc_try
5043 resolve_compcall (gfc_expr* e, bool fcn)
5044 {
5045   gfc_actual_arglist* newactual;
5046   gfc_symtree* target;
5047
5048   /* Check that's really a FUNCTION.  */
5049   if (fcn && !e->value.compcall.tbp->function)
5050     {
5051       gfc_error ("'%s' at %L should be a FUNCTION",
5052                  e->value.compcall.name, &e->where);
5053       return FAILURE;
5054     }
5055   else if (!fcn && !e->value.compcall.tbp->subroutine)
5056     {
5057       /* To resolve class member calls, we borrow this bit
5058          of code to select the specific procedures.  */
5059       gfc_error ("'%s' at %L should be a SUBROUTINE",
5060                  e->value.compcall.name, &e->where);
5061       return FAILURE;
5062     }
5063
5064   /* These must not be assign-calls!  */
5065   gcc_assert (!e->value.compcall.assign);
5066
5067   if (check_typebound_baseobject (e) == FAILURE)
5068     return FAILURE;
5069
5070   if (resolve_typebound_generic_call (e) == FAILURE)
5071     return FAILURE;
5072   gcc_assert (!e->value.compcall.tbp->is_generic);
5073
5074   /* Take the rank from the function's symbol.  */
5075   if (e->value.compcall.tbp->u.specific->n.sym->as)
5076     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5077
5078   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5079      arglist to the TBP's binding target.  */
5080
5081   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5082     return FAILURE;
5083
5084   e->value.function.actual = newactual;
5085   e->value.function.name = e->value.compcall.name;
5086   e->value.function.esym = target->n.sym;
5087   e->value.function.class_esym = NULL;
5088   e->value.function.isym = NULL;
5089   e->symtree = target;
5090   e->ts = target->n.sym->ts;
5091   e->expr_type = EXPR_FUNCTION;
5092
5093   /* Resolution is not necessary if this is a class subroutine; this
5094      function only has to identify the specific proc. Resolution of
5095      the call will be done next in resolve_typebound_call.  */
5096   return fcn ? gfc_resolve_expr (e) : SUCCESS;
5097 }
5098
5099
5100 /* Resolve a typebound call for the members in a class.  This group of
5101    functions implements dynamic dispatch in the provisional version
5102    of f03 OOP.  As soon as vtables are in place and contain pointers
5103    to methods, this will no longer be necessary.  */
5104 static gfc_expr *list_e;
5105 static void check_class_members (gfc_symbol *);
5106 static gfc_try class_try;
5107 static bool fcn_flag;
5108 static gfc_symbol *class_object;
5109
5110
5111 static void
5112 check_members (gfc_symbol *derived)
5113 {
5114   if (derived->attr.flavor == FL_DERIVED)
5115     check_class_members (derived);
5116 }
5117
5118
5119 static void 
5120 check_class_members (gfc_symbol *derived)
5121 {
5122   gfc_symbol* tbp_sym;
5123   gfc_expr *e;
5124   gfc_symtree *tbp;
5125   gfc_class_esym_list *etmp;
5126
5127   e = gfc_copy_expr (list_e);
5128
5129   tbp = gfc_find_typebound_proc (derived, &class_try,
5130                                  e->value.compcall.name,
5131                                  false, &e->where);
5132
5133   if (tbp == NULL)
5134     {
5135       gfc_error ("no typebound available procedure named '%s' at %L",
5136                  e->value.compcall.name, &e->where);
5137       return;
5138     }
5139
5140   if (tbp->n.tb->is_generic)
5141     {
5142       tbp_sym = NULL;
5143
5144       /* If we have to match a passed class member, force the actual
5145          expression to have the correct type.  */
5146       if (!tbp->n.tb->nopass)
5147         {
5148           if (e->value.compcall.base_object == NULL)
5149             e->value.compcall.base_object =
5150                         extract_compcall_passed_object (e);
5151
5152           e->value.compcall.base_object->ts.type = BT_DERIVED;
5153           e->value.compcall.base_object->ts.u.derived = derived;
5154         }
5155     }
5156   else
5157     tbp_sym = tbp->n.tb->u.specific->n.sym;
5158
5159   e->value.compcall.tbp = tbp->n.tb;
5160   e->value.compcall.name = tbp->name;
5161
5162   /* Let the original expresssion catch the assertion in
5163      resolve_compcall, since this flag does not appear to be reset or
5164      copied in some systems.  */
5165   e->value.compcall.assign = 0;
5166
5167   /* Do the renaming, PASSing, generic => specific and other
5168      good things for each class member.  */
5169   class_try = (resolve_compcall (e, fcn_flag) == SUCCESS)
5170                                 ? class_try : FAILURE;
5171
5172   /* Now transfer the found symbol to the esym list.  */
5173   if (class_try == SUCCESS)
5174     {
5175       etmp = list_e->value.function.class_esym;
5176       list_e->value.function.class_esym
5177                 = gfc_get_class_esym_list();
5178       list_e->value.function.class_esym->next = etmp;
5179       list_e->value.function.class_esym->derived = derived;
5180       list_e->value.function.class_esym->esym
5181                 = e->value.function.esym;
5182     }
5183
5184   gfc_free_expr (e);
5185   
5186   /* Burrow down into grandchildren types.  */
5187   if (derived->f2k_derived)
5188     gfc_traverse_ns (derived->f2k_derived, check_members);
5189 }
5190
5191
5192 /* Eliminate esym_lists where all the members point to the
5193    typebound procedure of the declared type; ie. one where
5194    type selection has no effect..  */
5195 static void
5196 resolve_class_esym (gfc_expr *e)
5197 {
5198   gfc_class_esym_list *p, *q;
5199   bool empty = true;
5200
5201   gcc_assert (e && e->expr_type == EXPR_FUNCTION);
5202
5203   p = e->value.function.class_esym;
5204   if (p == NULL)
5205     return;
5206
5207   for (; p; p = p->next)
5208     empty = empty && (e->value.function.esym == p->esym);
5209
5210   if (empty)
5211     {
5212       p = e->value.function.class_esym;
5213       for (; p; p = q)
5214         {
5215           q = p->next;
5216           gfc_free (p);
5217         }
5218       e->value.function.class_esym = NULL;
5219    }
5220 }
5221
5222
5223 /* Generate an expression for the vindex, given the reference to
5224    the class of the final expression (class_ref), the base of the
5225    full reference list (new_ref), the declared type and the class
5226    object (st).  */
5227 static gfc_expr*
5228 vindex_expr (gfc_ref *class_ref, gfc_ref *new_ref,
5229              gfc_symbol *declared, gfc_symtree *st)
5230 {
5231   gfc_expr *vindex;
5232   gfc_ref *ref;
5233
5234   /* Build an expression for the correct vindex; ie. that of the last
5235      CLASS reference.  */
5236   ref = gfc_get_ref();
5237   ref->type = REF_COMPONENT;
5238   ref->u.c.component = declared->components->next;
5239   ref->u.c.sym = declared;
5240   ref->next = NULL;
5241   if (class_ref)
5242     {
5243       class_ref->next = ref;
5244     }
5245   else
5246     {
5247       gfc_free_ref_list (new_ref);
5248       new_ref = ref;
5249     }
5250   vindex = gfc_get_expr ();
5251   vindex->expr_type = EXPR_VARIABLE;
5252   vindex->symtree = st;
5253   vindex->symtree->n.sym->refs++;
5254   vindex->ts = ref->u.c.component->ts;
5255   vindex->ref = new_ref;
5256
5257   return vindex;
5258 }
5259
5260
5261 /* Get the ultimate declared type from an expression.  In addition,
5262    return the last class/derived type reference and the copy of the
5263    reference list.  */
5264 static gfc_symbol*
5265 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5266                         gfc_expr *e)
5267 {
5268   gfc_symbol *declared;
5269   gfc_ref *ref;
5270
5271   declared = NULL;
5272   *class_ref = NULL;
5273   *new_ref = gfc_copy_ref (e->ref);
5274   for (ref = *new_ref; ref; ref = ref->next)
5275     {
5276       if (ref->type != REF_COMPONENT)
5277         continue;
5278
5279       if (ref->u.c.component->ts.type == BT_CLASS
5280             || ref->u.c.component->ts.type == BT_DERIVED)
5281         {
5282           declared = ref->u.c.component->ts.u.derived;
5283           *class_ref = ref;
5284         }
5285     }
5286
5287   if (declared == NULL)
5288     declared = e->symtree->n.sym->ts.u.derived;
5289
5290   return declared;
5291 }
5292
5293
5294 /* Resolve the argument expressions so that any arguments expressions
5295    that include class methods are resolved before the current call.
5296    This is necessary because of the static variables used in CLASS
5297    method resolution.  */
5298 static void
5299 resolve_arg_exprs (gfc_actual_arglist *arg)
5300
5301   /* Resolve the actual arglist expressions.  */
5302   for (; arg; arg = arg->next)
5303     {
5304       if (arg->expr)
5305         gfc_resolve_expr (arg->expr);
5306     }
5307 }
5308
5309
5310 /* Resolve a CLASS typebound function, or 'method'.  */
5311 static gfc_try
5312 resolve_class_compcall (gfc_expr* e)
5313 {
5314   gfc_symbol *derived, *declared;
5315   gfc_ref *new_ref;
5316   gfc_ref *class_ref;
5317   gfc_symtree *st;
5318
5319   st = e->symtree;
5320   class_object = st->n.sym;
5321
5322   /* Get the CLASS declared type.  */
5323   declared = get_declared_from_expr (&class_ref, &new_ref, e);
5324
5325   /* Weed out cases of the ultimate component being a derived type.  */
5326   if (class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5327     {
5328       gfc_free_ref_list (new_ref);
5329       return resolve_compcall (e, true);
5330     }
5331
5332   /* Resolve the argument expressions,  */
5333   resolve_arg_exprs (e->value.function.actual); 
5334
5335   /* Get the data component, which is of the declared type.  */
5336   derived = declared->components->ts.u.derived;
5337
5338   /* Resolve the function call for each member of the class.  */
5339   class_try = SUCCESS;
5340   fcn_flag = true;
5341   list_e = gfc_copy_expr (e);
5342   check_class_members (derived);
5343
5344   class_try = (resolve_compcall (e, true) == SUCCESS)
5345                  ? class_try : FAILURE;
5346
5347   /* Transfer the class list to the original expression.  Note that
5348      the class_esym list is cleaned up in trans-expr.c, as the calls
5349      are translated.  */
5350   e->value.function.class_esym = list_e->value.function.class_esym;
5351   list_e->value.function.class_esym = NULL;
5352   gfc_free_expr (list_e);
5353
5354   resolve_class_esym (e);
5355
5356   /* More than one typebound procedure so transmit an expression for
5357      the vindex as the selector.  */
5358   if (e->value.function.class_esym != NULL)
5359     e->value.function.class_esym->vindex
5360                 = vindex_expr (class_ref, new_ref, declared, st);
5361
5362   return class_try;
5363 }
5364
5365 /* Resolve a CLASS typebound subroutine, or 'method'.  */
5366 static gfc_try
5367 resolve_class_typebound_call (gfc_code *code)
5368 {
5369   gfc_symbol *derived, *declared;
5370   gfc_ref *new_ref;
5371   gfc_ref *class_ref;
5372   gfc_symtree *st;
5373
5374   st = code->expr1->symtree;
5375   class_object = st->n.sym;
5376
5377   /* Get the CLASS declared type.  */
5378   declared = get_declared_from_expr (&class_ref, &new_ref, code->expr1);
5379
5380   /* Weed out cases of the ultimate component being a derived type.  */
5381   if (class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5382     {
5383       gfc_free_ref_list (new_ref);
5384       return resolve_typebound_call (code);
5385     } 
5386
5387   /* Resolve the argument expressions,  */
5388   resolve_arg_exprs (code->expr1->value.compcall.actual); 
5389
5390   /* Get the data component, which is of the declared type.  */
5391   derived = declared->components->ts.u.derived;
5392
5393   class_try = SUCCESS;
5394   fcn_flag = false;
5395   list_e = gfc_copy_expr (code->expr1);
5396   check_class_members (derived);
5397
5398   class_try = (resolve_typebound_call (code) == SUCCESS)
5399                  ? class_try : FAILURE;
5400
5401   /* Transfer the class list to the original expression.  Note that
5402      the class_esym list is cleaned up in trans-expr.c, as the calls
5403      are translated.  */
5404   code->expr1->value.function.class_esym
5405                         = list_e->value.function.class_esym;
5406   list_e->value.function.class_esym = NULL;
5407   gfc_free_expr (list_e);
5408
5409   resolve_class_esym (code->expr1);
5410
5411   /* More than one typebound procedure so transmit an expression for
5412      the vindex as the selector.  */
5413   if (code->expr1->value.function.class_esym != NULL)
5414     code->expr1->value.function.class_esym->vindex
5415                 = vindex_expr (class_ref, new_ref, declared, st);
5416
5417   return class_try;
5418 }
5419
5420
5421 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
5422
5423 static gfc_try
5424 resolve_ppc_call (gfc_code* c)
5425 {
5426   gfc_component *comp;
5427   bool b;
5428
5429   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
5430   gcc_assert (b);
5431
5432   c->resolved_sym = c->expr1->symtree->n.sym;
5433   c->expr1->expr_type = EXPR_VARIABLE;
5434
5435   if (!comp->attr.subroutine)
5436     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
5437
5438   if (resolve_ref (c->expr1) == FAILURE)
5439     return FAILURE;
5440
5441   if (update_ppc_arglist (c->expr1) == FAILURE)
5442     return FAILURE;
5443
5444   c->ext.actual = c->expr1->value.compcall.actual;
5445
5446   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
5447                               comp->formal == NULL) == FAILURE)
5448     return FAILURE;
5449
5450   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
5451
5452   return SUCCESS;
5453 }
5454
5455
5456 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
5457
5458 static gfc_try
5459 resolve_expr_ppc (gfc_expr* e)
5460 {
5461   gfc_component *comp;
5462   bool b;
5463
5464   b = gfc_is_proc_ptr_comp (e, &comp);
5465   gcc_assert (b);
5466
5467   /* Convert to EXPR_FUNCTION.  */
5468   e->expr_type = EXPR_FUNCTION;
5469   e->value.function.isym = NULL;
5470   e->value.function.actual = e->value.compcall.actual;
5471   e->ts = comp->ts;
5472   if (comp->as != NULL)
5473     e->rank = comp->as->rank;
5474
5475   if (!comp->attr.function)
5476     gfc_add_function (&comp->attr, comp->name, &e->where);
5477
5478   if (resolve_ref (e) == FAILURE)
5479     return FAILURE;
5480
5481   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
5482                               comp->formal == NULL) == FAILURE)
5483     return FAILURE;
5484
5485   if (update_ppc_arglist (e) == FAILURE)
5486     return FAILURE;
5487
5488   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
5489
5490   return SUCCESS;
5491 }
5492
5493
5494 /* Resolve an expression.  That is, make sure that types of operands agree
5495    with their operators, intrinsic operators are converted to function calls
5496    for overloaded types and unresolved function references are resolved.  */
5497
5498 gfc_try
5499 gfc_resolve_expr (gfc_expr *e)
5500 {
5501   gfc_try t;
5502
5503   if (e == NULL)
5504     return SUCCESS;
5505
5506   switch (e->expr_type)
5507     {
5508     case EXPR_OP:
5509       t = resolve_operator (e);
5510       break;
5511
5512     case EXPR_FUNCTION:
5513     case EXPR_VARIABLE:
5514
5515       if (check_host_association (e))
5516         t = resolve_function (e);
5517       else
5518         {
5519           t = resolve_variable (e);
5520           if (t == SUCCESS)
5521             expression_rank (e);
5522         }
5523
5524       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
5525           && e->ref->type != REF_SUBSTRING)
5526         gfc_resolve_substring_charlen (e);
5527
5528       break;
5529
5530     case EXPR_COMPCALL:
5531       if (e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
5532         t = resolve_class_compcall (e);
5533       else
5534         t = resolve_compcall (e, true);
5535       break;
5536
5537     case EXPR_SUBSTRING:
5538       t = resolve_ref (e);
5539       break;
5540
5541     case EXPR_CONSTANT:
5542     case EXPR_NULL:
5543       t = SUCCESS;
5544       break;
5545
5546     case EXPR_PPC:
5547       t = resolve_expr_ppc (e);
5548       break;
5549
5550     case EXPR_ARRAY:
5551       t = FAILURE;
5552       if (resolve_ref (e) == FAILURE)
5553         break;
5554
5555       t = gfc_resolve_array_constructor (e);
5556       /* Also try to expand a constructor.  */
5557       if (t == SUCCESS)
5558         {
5559           expression_rank (e);
5560           gfc_expand_constructor (e);
5561         }
5562
5563       /* This provides the opportunity for the length of constructors with
5564          character valued function elements to propagate the string length
5565          to the expression.  */
5566       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
5567         t = gfc_resolve_character_array_constructor (e);
5568
5569       break;
5570
5571     case EXPR_STRUCTURE:
5572       t = resolve_ref (e);
5573       if (t == FAILURE)
5574         break;
5575
5576       t = resolve_structure_cons (e);
5577       if (t == FAILURE)
5578         break;
5579
5580       t = gfc_simplify_expr (e, 0);
5581       break;
5582
5583     default:
5584       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
5585     }
5586
5587   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
5588     fixup_charlen (e);
5589
5590   return t;
5591 }
5592
5593
5594 /* Resolve an expression from an iterator.  They must be scalar and have
5595    INTEGER or (optionally) REAL type.  */
5596
5597 static gfc_try
5598 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
5599                            const char *name_msgid)
5600 {
5601   if (gfc_resolve_expr (expr) == FAILURE)
5602     return FAILURE;
5603
5604   if (expr->rank != 0)
5605     {
5606       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
5607       return FAILURE;
5608     }
5609
5610   if (expr->ts.type != BT_INTEGER)
5611     {
5612       if (expr->ts.type == BT_REAL)
5613         {
5614           if (real_ok)
5615             return gfc_notify_std (GFC_STD_F95_DEL,
5616                                    "Deleted feature: %s at %L must be integer",
5617                                    _(name_msgid), &expr->where);
5618           else
5619             {
5620               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
5621                          &expr->where);
5622               return FAILURE;
5623             }
5624         }
5625       else
5626         {
5627           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
5628           return FAILURE;
5629         }
5630     }
5631   return SUCCESS;
5632 }
5633
5634
5635 /* Resolve the expressions in an iterator structure.  If REAL_OK is
5636    false allow only INTEGER type iterators, otherwise allow REAL types.  */
5637
5638 gfc_try
5639 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
5640 {
5641   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
5642       == FAILURE)
5643     return FAILURE;
5644
5645   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
5646     {
5647       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
5648                  &iter->var->where);
5649       return FAILURE;
5650     }
5651
5652   if (gfc_resolve_iterator_expr (iter->start, real_ok,
5653                                  "Start expression in DO loop") == FAILURE)
5654     return FAILURE;
5655
5656   if (gfc_resolve_iterator_expr (iter->end, real_ok,
5657                                  "End expression in DO loop") == FAILURE)
5658     return FAILURE;
5659
5660   if (gfc_resolve_iterator_expr (iter->step, real_ok,
5661                                  "Step expression in DO loop") == FAILURE)
5662     return FAILURE;
5663
5664   if (iter->step->expr_type == EXPR_CONSTANT)
5665     {
5666       if ((iter->step->ts.type == BT_INTEGER
5667            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
5668           || (iter->step->ts.type == BT_REAL
5669               && mpfr_sgn (iter->step->value.real) == 0))
5670         {
5671           gfc_error ("Step expression in DO loop at %L cannot be zero",
5672                      &iter->step->where);
5673           return FAILURE;
5674         }
5675     }
5676
5677   /* Convert start, end, and step to the same type as var.  */
5678   if (iter->start->ts.kind != iter->var->ts.kind
5679       || iter->start->ts.type != iter->var->ts.type)
5680     gfc_convert_type (iter->start, &iter->var->ts, 2);
5681
5682   if (iter->end->ts.kind != iter->var->ts.kind
5683       || iter->end->ts.type != iter->var->ts.type)
5684     gfc_convert_type (iter->end, &iter->var->ts, 2);
5685
5686   if (iter->step->ts.kind != iter->var->ts.kind
5687       || iter->step->ts.type != iter->var->ts.type)
5688     gfc_convert_type (iter->step, &iter->var->ts, 2);
5689
5690   if (iter->start->expr_type == EXPR_CONSTANT
5691       && iter->end->expr_type == EXPR_CONSTANT
5692       && iter->step->expr_type == EXPR_CONSTANT)
5693     {
5694       int sgn, cmp;
5695       if (iter->start->ts.type == BT_INTEGER)
5696         {
5697           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
5698           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
5699         }
5700       else
5701         {
5702           sgn = mpfr_sgn (iter->step->value.real);
5703           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
5704         }
5705       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
5706         gfc_warning ("DO loop at %L will be executed zero times",
5707                      &iter->step->where);
5708     }
5709
5710   return SUCCESS;
5711 }
5712
5713
5714 /* Traversal function for find_forall_index.  f == 2 signals that
5715    that variable itself is not to be checked - only the references.  */
5716
5717 static bool
5718 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
5719 {
5720   if (expr->expr_type != EXPR_VARIABLE)
5721     return false;
5722   
5723   /* A scalar assignment  */
5724   if (!expr->ref || *f == 1)
5725     {
5726       if (expr->symtree->n.sym == sym)
5727         return true;
5728       else
5729         return false;
5730     }
5731
5732   if (*f == 2)
5733     *f = 1;
5734   return false;
5735 }
5736
5737
5738 /* Check whether the FORALL index appears in the expression or not.
5739    Returns SUCCESS if SYM is found in EXPR.  */
5740
5741 gfc_try
5742 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
5743 {
5744   if (gfc_traverse_expr (expr, sym, forall_index, f))
5745     return SUCCESS;
5746   else
5747     return FAILURE;
5748 }
5749
5750
5751 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
5752    to be a scalar INTEGER variable.  The subscripts and stride are scalar
5753    INTEGERs, and if stride is a constant it must be nonzero.
5754    Furthermore "A subscript or stride in a forall-triplet-spec shall
5755    not contain a reference to any index-name in the
5756    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
5757
5758 static void
5759 resolve_forall_iterators (gfc_forall_iterator *it)
5760 {
5761   gfc_forall_iterator *iter, *iter2;
5762
5763   for (iter = it; iter; iter = iter->next)
5764     {
5765       if (gfc_resolve_expr (iter->var) == SUCCESS
5766           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
5767         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
5768                    &iter->var->where);
5769
5770       if (gfc_resolve_expr (iter->start) == SUCCESS
5771           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
5772         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
5773                    &iter->start->where);
5774       if (iter->var->ts.kind != iter->start->ts.kind)
5775         gfc_convert_type (iter->start, &iter->var->ts, 2);
5776
5777       if (gfc_resolve_expr (iter->end) == SUCCESS
5778           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
5779         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
5780                    &iter->end->where);
5781       if (iter->var->ts.kind != iter->end->ts.kind)
5782         gfc_convert_type (iter->end, &iter->var->ts, 2);
5783
5784       if (gfc_resolve_expr (iter->stride) == SUCCESS)
5785         {
5786           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
5787             gfc_error ("FORALL stride expression at %L must be a scalar %s",
5788                        &iter->stride->where, "INTEGER");
5789
5790           if (iter->stride->expr_type == EXPR_CONSTANT
5791               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
5792             gfc_error ("FORALL stride expression at %L cannot be zero",
5793                        &iter->stride->where);
5794         }
5795       if (iter->var->ts.kind != iter->stride->ts.kind)
5796         gfc_convert_type (iter->stride, &iter->var->ts, 2);
5797     }
5798
5799   for (iter = it; iter; iter = iter->next)
5800     for (iter2 = iter; iter2; iter2 = iter2->next)
5801       {
5802         if (find_forall_index (iter2->start,
5803                                iter->var->symtree->n.sym, 0) == SUCCESS
5804             || find_forall_index (iter2->end,
5805                                   iter->var->symtree->n.sym, 0) == SUCCESS
5806             || find_forall_index (iter2->stride,
5807                                   iter->var->symtree->n.sym, 0) == SUCCESS)
5808           gfc_error ("FORALL index '%s' may not appear in triplet "
5809                      "specification at %L", iter->var->symtree->name,
5810                      &iter2->start->where);
5811       }
5812 }
5813
5814
5815 /* Given a pointer to a symbol that is a derived type, see if it's
5816    inaccessible, i.e. if it's defined in another module and the components are
5817    PRIVATE.  The search is recursive if necessary.  Returns zero if no
5818    inaccessible components are found, nonzero otherwise.  */
5819
5820 static int
5821 derived_inaccessible (gfc_symbol *sym)
5822 {
5823   gfc_component *c;
5824
5825   if (sym->attr.use_assoc && sym->attr.private_comp)
5826     return 1;
5827
5828   for (c = sym->components; c; c = c->next)
5829     {
5830         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
5831           return 1;
5832     }
5833
5834   return 0;
5835 }
5836
5837
5838 /* Resolve the argument of a deallocate expression.  The expression must be
5839    a pointer or a full array.  */
5840
5841 static gfc_try
5842 resolve_deallocate_expr (gfc_expr *e)
5843 {
5844   symbol_attribute attr;
5845   int allocatable, pointer, check_intent_in;
5846   gfc_ref *ref;
5847   gfc_symbol *sym;
5848   gfc_component *c;
5849
5850   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
5851   check_intent_in = 1;
5852
5853   if (gfc_resolve_expr (e) == FAILURE)
5854     return FAILURE;
5855
5856   if (e->expr_type != EXPR_VARIABLE)
5857     goto bad;
5858
5859   sym = e->symtree->n.sym;
5860
5861   if (sym->ts.type == BT_CLASS)
5862     {
5863       allocatable = sym->ts.u.derived->components->attr.allocatable;
5864       pointer = sym->ts.u.derived->components->attr.pointer;
5865     }
5866   else
5867     {
5868       allocatable = sym->attr.allocatable;
5869       pointer = sym->attr.pointer;
5870     }
5871   for (ref = e->ref; ref; ref = ref->next)
5872     {
5873       if (pointer)
5874         check_intent_in = 0;
5875
5876       switch (ref->type)
5877         {
5878         case REF_ARRAY:
5879           if (ref->u.ar.type != AR_FULL)
5880             allocatable = 0;
5881           break;
5882
5883         case REF_COMPONENT:
5884           c = ref->u.c.component;
5885           if (c->ts.type == BT_CLASS)
5886             {
5887               allocatable = c->ts.u.derived->components->attr.allocatable;
5888               pointer = c->ts.u.derived->components->attr.pointer;
5889             }
5890           else
5891             {
5892               allocatable = c->attr.allocatable;
5893               pointer = c->attr.pointer;
5894             }
5895           break;
5896
5897         case REF_SUBSTRING:
5898           allocatable = 0;
5899           break;
5900         }
5901     }
5902
5903   attr = gfc_expr_attr (e);
5904
5905   if (allocatable == 0 && attr.pointer == 0)
5906     {
5907     bad:
5908       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
5909                  &e->where);
5910     }
5911
5912   if (check_intent_in && sym->attr.intent == INTENT_IN)
5913     {
5914       gfc_error ("Cannot deallocate INTENT(IN) variable '%s' at %L",
5915                  sym->name, &e->where);
5916       return FAILURE;
5917     }
5918
5919   if (e->ts.type == BT_CLASS)
5920     {
5921       /* Only deallocate the DATA component.  */
5922       gfc_add_component_ref (e, "$data");
5923     }
5924
5925   return SUCCESS;
5926 }
5927
5928
5929 /* Returns true if the expression e contains a reference to the symbol sym.  */
5930 static bool
5931 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
5932 {
5933   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
5934     return true;
5935
5936   return false;
5937 }
5938
5939 bool
5940 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
5941 {
5942   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
5943 }
5944
5945
5946 /* Given the expression node e for an allocatable/pointer of derived type to be
5947    allocated, get the expression node to be initialized afterwards (needed for
5948    derived types with default initializers, and derived types with allocatable
5949    components that need nullification.)  */
5950
5951 gfc_expr *
5952 gfc_expr_to_initialize (gfc_expr *e)
5953 {
5954   gfc_expr *result;
5955   gfc_ref *ref;
5956   int i;
5957
5958   result = gfc_copy_expr (e);
5959
5960   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
5961   for (ref = result->ref; ref; ref = ref->next)
5962     if (ref->type == REF_ARRAY && ref->next == NULL)
5963       {
5964         ref->u.ar.type = AR_FULL;
5965
5966         for (i = 0; i < ref->u.ar.dimen; i++)
5967           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
5968
5969         result->rank = ref->u.ar.dimen;
5970         break;
5971       }
5972
5973   return result;
5974 }
5975
5976
5977 /* Used in resolve_allocate_expr to check that a allocation-object and
5978    a source-expr are conformable.  This does not catch all possible 
5979    cases; in particular a runtime checking is needed.  */
5980
5981 static gfc_try
5982 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
5983 {
5984   /* First compare rank.  */
5985   if (e2->ref && e1->rank != e2->ref->u.ar.as->rank)
5986     {
5987       gfc_error ("Source-expr at %L must be scalar or have the "
5988                  "same rank as the allocate-object at %L",
5989                  &e1->where, &e2->where);
5990       return FAILURE;
5991     }
5992
5993   if (e1->shape)
5994     {
5995       int i;
5996       mpz_t s;
5997
5998       mpz_init (s);
5999
6000       for (i = 0; i < e1->rank; i++)
6001         {
6002           if (e2->ref->u.ar.end[i])
6003             {
6004               mpz_set (s, e2->ref->u.ar.end[i]->value.integer);
6005               mpz_sub (s, s, e2->ref->u.ar.start[i]->value.integer);
6006               mpz_add_ui (s, s, 1);
6007             }
6008           else
6009             {
6010               mpz_set (s, e2->ref->u.ar.start[i]->value.integer);
6011             }
6012
6013           if (mpz_cmp (e1->shape[i], s) != 0)
6014             {
6015               gfc_error ("Source-expr at %L and allocate-object at %L must "
6016                          "have the same shape", &e1->where, &e2->where);
6017               mpz_clear (s);
6018               return FAILURE;
6019             }
6020         }
6021
6022       mpz_clear (s);
6023     }
6024
6025   return SUCCESS;
6026 }
6027
6028
6029 /* Resolve the expression in an ALLOCATE statement, doing the additional
6030    checks to see whether the expression is OK or not.  The expression must
6031    have a trailing array reference that gives the size of the array.  */
6032
6033 static gfc_try
6034 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6035 {
6036   int i, pointer, allocatable, dimension, check_intent_in, is_abstract;
6037   symbol_attribute attr;
6038   gfc_ref *ref, *ref2;
6039   gfc_array_ref *ar;
6040   gfc_symbol *sym;
6041   gfc_alloc *a;
6042   gfc_component *c;
6043
6044   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
6045   check_intent_in = 1;
6046
6047   if (gfc_resolve_expr (e) == FAILURE)
6048     return FAILURE;
6049
6050   /* Make sure the expression is allocatable or a pointer.  If it is
6051      pointer, the next-to-last reference must be a pointer.  */
6052
6053   ref2 = NULL;
6054   if (e->symtree)
6055     sym = e->symtree->n.sym;
6056
6057   /* Check whether ultimate component is abstract and CLASS.  */
6058   is_abstract = 0;
6059
6060   if (e->expr_type != EXPR_VARIABLE)
6061     {
6062       allocatable = 0;
6063       attr = gfc_expr_attr (e);
6064       pointer = attr.pointer;
6065       dimension = attr.dimension;
6066     }
6067   else
6068     {
6069       if (sym->ts.type == BT_CLASS)
6070         {
6071           allocatable = sym->ts.u.derived->components->attr.allocatable;
6072           pointer = sym->ts.u.derived->components->attr.pointer;
6073           dimension = sym->ts.u.derived->components->attr.dimension;
6074           is_abstract = sym->ts.u.derived->components->attr.abstract;
6075         }
6076       else
6077         {
6078           allocatable = sym->attr.allocatable;
6079           pointer = sym->attr.pointer;
6080           dimension = sym->attr.dimension;
6081         }
6082
6083       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6084         {
6085           if (pointer)
6086             check_intent_in = 0;
6087
6088           switch (ref->type)
6089             {
6090               case REF_ARRAY:
6091                 if (ref->next != NULL)
6092                   pointer = 0;
6093                 break;
6094
6095               case REF_COMPONENT:
6096                 c = ref->u.c.component;
6097                 if (c->ts.type == BT_CLASS)
6098                   {
6099                     allocatable = c->ts.u.derived->components->attr.allocatable;
6100                     pointer = c->ts.u.derived->components->attr.pointer;
6101                     dimension = c->ts.u.derived->components->attr.dimension;
6102                     is_abstract = c->ts.u.derived->components->attr.abstract;
6103                   }
6104                 else
6105                   {
6106                     allocatable = c->attr.allocatable;
6107                     pointer = c->attr.pointer;
6108                     dimension = c->attr.dimension;
6109                     is_abstract = c->attr.abstract;
6110                   }
6111                 break;
6112
6113               case REF_SUBSTRING:
6114                 allocatable = 0;
6115                 pointer = 0;
6116                 break;
6117             }
6118         }
6119     }
6120
6121   if (allocatable == 0 && pointer == 0)
6122     {
6123       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6124                  &e->where);
6125       return FAILURE;
6126     }
6127
6128   /* Some checks for the SOURCE tag.  */
6129   if (code->expr3)
6130     {
6131       /* Check F03:C631.  */
6132       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6133         {
6134           gfc_error ("Type of entity at %L is type incompatible with "
6135                       "source-expr at %L", &e->where, &code->expr3->where);
6136           return FAILURE;
6137         }
6138
6139       /* Check F03:C632 and restriction following Note 6.18.  */
6140       if (code->expr3->rank > 0
6141           && conformable_arrays (code->expr3, e) == FAILURE)
6142         return FAILURE;
6143
6144       /* Check F03:C633.  */
6145       if (code->expr3->ts.kind != e->ts.kind)
6146         {
6147           gfc_error ("The allocate-object at %L and the source-expr at %L "
6148                       "shall have the same kind type parameter",
6149                       &e->where, &code->expr3->where);
6150           return FAILURE;
6151         }
6152     }
6153   else if (is_abstract&& code->ext.alloc.ts.type == BT_UNKNOWN)
6154     {
6155       gcc_assert (e->ts.type == BT_CLASS);
6156       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6157                  "type-spec or SOURCE=", sym->name, &e->where);
6158       return FAILURE;
6159     }
6160
6161   if (check_intent_in && sym->attr.intent == INTENT_IN)
6162     {
6163       gfc_error ("Cannot allocate INTENT(IN) variable '%s' at %L",
6164                  sym->name, &e->where);
6165       return FAILURE;
6166     }
6167
6168   if (pointer || dimension == 0)
6169     return SUCCESS;
6170
6171   /* Make sure the next-to-last reference node is an array specification.  */
6172
6173   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL)
6174     {
6175       gfc_error ("Array specification required in ALLOCATE statement "
6176                  "at %L", &e->where);
6177       return FAILURE;
6178     }
6179
6180   /* Make sure that the array section reference makes sense in the
6181     context of an ALLOCATE specification.  */
6182
6183   ar = &ref2->u.ar;
6184
6185   for (i = 0; i < ar->dimen; i++)
6186     {
6187       if (ref2->u.ar.type == AR_ELEMENT)
6188         goto check_symbols;
6189
6190       switch (ar->dimen_type[i])
6191         {
6192         case DIMEN_ELEMENT:
6193           break;
6194
6195         case DIMEN_RANGE:
6196           if (ar->start[i] != NULL
6197               && ar->end[i] != NULL
6198               && ar->stride[i] == NULL)
6199             break;
6200
6201           /* Fall Through...  */
6202
6203         case DIMEN_UNKNOWN:
6204         case DIMEN_VECTOR:
6205           gfc_error ("Bad array specification in ALLOCATE statement at %L",
6206                      &e->where);
6207           return FAILURE;
6208         }
6209
6210 check_symbols:
6211
6212       for (a = code->ext.alloc.list; a; a = a->next)
6213         {
6214           sym = a->expr->symtree->n.sym;
6215
6216           /* TODO - check derived type components.  */
6217           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
6218             continue;
6219
6220           if ((ar->start[i] != NULL
6221                && gfc_find_sym_in_expr (sym, ar->start[i]))
6222               || (ar->end[i] != NULL
6223                   && gfc_find_sym_in_expr (sym, ar->end[i])))
6224             {
6225               gfc_error ("'%s' must not appear in the array specification at "
6226                          "%L in the same ALLOCATE statement where it is "
6227                          "itself allocated", sym->name, &ar->where);
6228               return FAILURE;
6229             }
6230         }
6231     }
6232
6233   return SUCCESS;
6234 }
6235
6236 static void
6237 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
6238 {
6239   gfc_expr *stat, *errmsg, *pe, *qe;
6240   gfc_alloc *a, *p, *q;
6241
6242   stat = code->expr1 ? code->expr1 : NULL;
6243
6244   errmsg = code->expr2 ? code->expr2 : NULL;
6245
6246   /* Check the stat variable.  */
6247   if (stat)
6248     {
6249       if (stat->symtree->n.sym->attr.intent == INTENT_IN)
6250         gfc_error ("Stat-variable '%s' at %L cannot be INTENT(IN)",
6251                    stat->symtree->n.sym->name, &stat->where);
6252
6253       if (gfc_pure (NULL) && gfc_impure_variable (stat->symtree->n.sym))
6254         gfc_error ("Illegal stat-variable at %L for a PURE procedure",
6255                    &stat->where);
6256
6257       if ((stat->ts.type != BT_INTEGER
6258            && !(stat->ref && (stat->ref->type == REF_ARRAY
6259                               || stat->ref->type == REF_COMPONENT)))
6260           || stat->rank > 0)
6261         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
6262                    "variable", &stat->where);
6263
6264       for (p = code->ext.alloc.list; p; p = p->next)
6265         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
6266           gfc_error ("Stat-variable at %L shall not be %sd within "
6267                      "the same %s statement", &stat->where, fcn, fcn);
6268     }
6269
6270   /* Check the errmsg variable.  */
6271   if (errmsg)
6272     {
6273       if (!stat)
6274         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
6275                      &errmsg->where);
6276
6277       if (errmsg->symtree->n.sym->attr.intent == INTENT_IN)
6278         gfc_error ("Errmsg-variable '%s' at %L cannot be INTENT(IN)",
6279                    errmsg->symtree->n.sym->name, &errmsg->where);
6280
6281       if (gfc_pure (NULL) && gfc_impure_variable (errmsg->symtree->n.sym))
6282         gfc_error ("Illegal errmsg-variable at %L for a PURE procedure",
6283                    &errmsg->where);
6284
6285       if ((errmsg->ts.type != BT_CHARACTER
6286            && !(errmsg->ref
6287                 && (errmsg->ref->type == REF_ARRAY
6288                     || errmsg->ref->type == REF_COMPONENT)))
6289           || errmsg->rank > 0 )
6290         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
6291                    "variable", &errmsg->where);
6292
6293       for (p = code->ext.alloc.list; p; p = p->next)
6294         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
6295           gfc_error ("Errmsg-variable at %L shall not be %sd within "
6296                      "the same %s statement", &errmsg->where, fcn, fcn);
6297     }
6298
6299   /* Check that an allocate-object appears only once in the statement.  
6300      FIXME: Checking derived types is disabled.  */
6301   for (p = code->ext.alloc.list; p; p = p->next)
6302     {
6303       pe = p->expr;
6304       if ((pe->ref && pe->ref->type != REF_COMPONENT)
6305            && (pe->symtree->n.sym->ts.type != BT_DERIVED))
6306         {
6307           for (q = p->next; q; q = q->next)
6308             {
6309               qe = q->expr;
6310               if ((qe->ref && qe->ref->type != REF_COMPONENT)
6311                   && (qe->symtree->n.sym->ts.type != BT_DERIVED)
6312                   && (pe->symtree->n.sym->name == qe->symtree->n.sym->name))
6313                 gfc_error ("Allocate-object at %L also appears at %L",
6314                            &pe->where, &qe->where);
6315             }
6316         }
6317     }
6318
6319   if (strcmp (fcn, "ALLOCATE") == 0)
6320     {
6321       for (a = code->ext.alloc.list; a; a = a->next)
6322         resolve_allocate_expr (a->expr, code);
6323     }
6324   else
6325     {
6326       for (a = code->ext.alloc.list; a; a = a->next)
6327         resolve_deallocate_expr (a->expr);
6328     }
6329 }
6330
6331
6332 /************ SELECT CASE resolution subroutines ************/
6333
6334 /* Callback function for our mergesort variant.  Determines interval
6335    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
6336    op1 > op2.  Assumes we're not dealing with the default case.  
6337    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
6338    There are nine situations to check.  */
6339
6340 static int
6341 compare_cases (const gfc_case *op1, const gfc_case *op2)
6342 {
6343   int retval;
6344
6345   if (op1->low == NULL) /* op1 = (:L)  */
6346     {
6347       /* op2 = (:N), so overlap.  */
6348       retval = 0;
6349       /* op2 = (M:) or (M:N),  L < M  */
6350       if (op2->low != NULL
6351           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6352         retval = -1;
6353     }
6354   else if (op1->high == NULL) /* op1 = (K:)  */
6355     {
6356       /* op2 = (M:), so overlap.  */
6357       retval = 0;
6358       /* op2 = (:N) or (M:N), K > N  */
6359       if (op2->high != NULL
6360           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6361         retval = 1;
6362     }
6363   else /* op1 = (K:L)  */
6364     {
6365       if (op2->low == NULL)       /* op2 = (:N), K > N  */
6366         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6367                  ? 1 : 0;
6368       else if (op2->high == NULL) /* op2 = (M:), L < M  */
6369         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6370                  ? -1 : 0;
6371       else                      /* op2 = (M:N)  */
6372         {
6373           retval =  0;
6374           /* L < M  */
6375           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6376             retval =  -1;
6377           /* K > N  */
6378           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6379             retval =  1;
6380         }
6381     }
6382
6383   return retval;
6384 }
6385
6386
6387 /* Merge-sort a double linked case list, detecting overlap in the
6388    process.  LIST is the head of the double linked case list before it
6389    is sorted.  Returns the head of the sorted list if we don't see any
6390    overlap, or NULL otherwise.  */
6391
6392 static gfc_case *
6393 check_case_overlap (gfc_case *list)
6394 {
6395   gfc_case *p, *q, *e, *tail;
6396   int insize, nmerges, psize, qsize, cmp, overlap_seen;
6397
6398   /* If the passed list was empty, return immediately.  */
6399   if (!list)
6400     return NULL;
6401
6402   overlap_seen = 0;
6403   insize = 1;
6404
6405   /* Loop unconditionally.  The only exit from this loop is a return
6406      statement, when we've finished sorting the case list.  */
6407   for (;;)
6408     {
6409       p = list;
6410       list = NULL;
6411       tail = NULL;
6412
6413       /* Count the number of merges we do in this pass.  */
6414       nmerges = 0;
6415
6416       /* Loop while there exists a merge to be done.  */
6417       while (p)
6418         {
6419           int i;
6420
6421           /* Count this merge.  */
6422           nmerges++;
6423
6424           /* Cut the list in two pieces by stepping INSIZE places
6425              forward in the list, starting from P.  */
6426           psize = 0;
6427           q = p;
6428           for (i = 0; i < insize; i++)
6429             {
6430               psize++;
6431               q = q->right;
6432               if (!q)
6433                 break;
6434             }
6435           qsize = insize;
6436
6437           /* Now we have two lists.  Merge them!  */
6438           while (psize > 0 || (qsize > 0 && q != NULL))
6439             {
6440               /* See from which the next case to merge comes from.  */
6441               if (psize == 0)
6442                 {
6443                   /* P is empty so the next case must come from Q.  */
6444                   e = q;
6445                   q = q->right;
6446                   qsize--;
6447                 }
6448               else if (qsize == 0 || q == NULL)
6449                 {
6450                   /* Q is empty.  */
6451                   e = p;
6452                   p = p->right;
6453                   psize--;
6454                 }
6455               else
6456                 {
6457                   cmp = compare_cases (p, q);
6458                   if (cmp < 0)
6459                     {
6460                       /* The whole case range for P is less than the
6461                          one for Q.  */
6462                       e = p;
6463                       p = p->right;
6464                       psize--;
6465                     }
6466                   else if (cmp > 0)
6467                     {
6468                       /* The whole case range for Q is greater than
6469                          the case range for P.  */
6470                       e = q;
6471                       q = q->right;
6472                       qsize--;
6473                     }
6474                   else
6475                     {
6476                       /* The cases overlap, or they are the same
6477                          element in the list.  Either way, we must
6478                          issue an error and get the next case from P.  */
6479                       /* FIXME: Sort P and Q by line number.  */
6480                       gfc_error ("CASE label at %L overlaps with CASE "
6481                                  "label at %L", &p->where, &q->where);
6482                       overlap_seen = 1;
6483                       e = p;
6484                       p = p->right;
6485                       psize--;
6486                     }
6487                 }
6488
6489                 /* Add the next element to the merged list.  */
6490               if (tail)
6491                 tail->right = e;
6492               else
6493                 list = e;
6494               e->left = tail;
6495               tail = e;
6496             }
6497
6498           /* P has now stepped INSIZE places along, and so has Q.  So
6499              they're the same.  */
6500           p = q;
6501         }
6502       tail->right = NULL;
6503
6504       /* If we have done only one merge or none at all, we've
6505          finished sorting the cases.  */
6506       if (nmerges <= 1)
6507         {
6508           if (!overlap_seen)
6509             return list;
6510           else
6511             return NULL;
6512         }
6513
6514       /* Otherwise repeat, merging lists twice the size.  */
6515       insize *= 2;
6516     }
6517 }
6518
6519
6520 /* Check to see if an expression is suitable for use in a CASE statement.
6521    Makes sure that all case expressions are scalar constants of the same
6522    type.  Return FAILURE if anything is wrong.  */
6523
6524 static gfc_try
6525 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
6526 {
6527   if (e == NULL) return SUCCESS;
6528
6529   if (e->ts.type != case_expr->ts.type)
6530     {
6531       gfc_error ("Expression in CASE statement at %L must be of type %s",
6532                  &e->where, gfc_basic_typename (case_expr->ts.type));
6533       return FAILURE;
6534     }
6535
6536   /* C805 (R808) For a given case-construct, each case-value shall be of
6537      the same type as case-expr.  For character type, length differences
6538      are allowed, but the kind type parameters shall be the same.  */
6539
6540   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
6541     {
6542       gfc_error ("Expression in CASE statement at %L must be of kind %d",
6543                  &e->where, case_expr->ts.kind);
6544       return FAILURE;
6545     }
6546
6547   /* Convert the case value kind to that of case expression kind, if needed.
6548      FIXME:  Should a warning be issued?  */
6549   if (e->ts.kind != case_expr->ts.kind)
6550     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
6551
6552   if (e->rank != 0)
6553     {
6554       gfc_error ("Expression in CASE statement at %L must be scalar",
6555                  &e->where);
6556       return FAILURE;
6557     }
6558
6559   return SUCCESS;
6560 }
6561
6562
6563 /* Given a completely parsed select statement, we:
6564
6565      - Validate all expressions and code within the SELECT.
6566      - Make sure that the selection expression is not of the wrong type.
6567      - Make sure that no case ranges overlap.
6568      - Eliminate unreachable cases and unreachable code resulting from
6569        removing case labels.
6570
6571    The standard does allow unreachable cases, e.g. CASE (5:3).  But
6572    they are a hassle for code generation, and to prevent that, we just
6573    cut them out here.  This is not necessary for overlapping cases
6574    because they are illegal and we never even try to generate code.
6575
6576    We have the additional caveat that a SELECT construct could have
6577    been a computed GOTO in the source code. Fortunately we can fairly
6578    easily work around that here: The case_expr for a "real" SELECT CASE
6579    is in code->expr1, but for a computed GOTO it is in code->expr2. All
6580    we have to do is make sure that the case_expr is a scalar integer
6581    expression.  */
6582
6583 static void
6584 resolve_select (gfc_code *code)
6585 {
6586   gfc_code *body;
6587   gfc_expr *case_expr;
6588   gfc_case *cp, *default_case, *tail, *head;
6589   int seen_unreachable;
6590   int seen_logical;
6591   int ncases;
6592   bt type;
6593   gfc_try t;
6594
6595   if (code->expr1 == NULL)
6596     {
6597       /* This was actually a computed GOTO statement.  */
6598       case_expr = code->expr2;
6599       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
6600         gfc_error ("Selection expression in computed GOTO statement "
6601                    "at %L must be a scalar integer expression",
6602                    &case_expr->where);
6603
6604       /* Further checking is not necessary because this SELECT was built
6605          by the compiler, so it should always be OK.  Just move the
6606          case_expr from expr2 to expr so that we can handle computed
6607          GOTOs as normal SELECTs from here on.  */
6608       code->expr1 = code->expr2;
6609       code->expr2 = NULL;
6610       return;
6611     }
6612
6613   case_expr = code->expr1;
6614
6615   type = case_expr->ts.type;
6616   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
6617     {
6618       gfc_error ("Argument of SELECT statement at %L cannot be %s",
6619                  &case_expr->where, gfc_typename (&case_expr->ts));
6620
6621       /* Punt. Going on here just produce more garbage error messages.  */
6622       return;
6623     }
6624
6625   if (case_expr->rank != 0)
6626     {
6627       gfc_error ("Argument of SELECT statement at %L must be a scalar "
6628                  "expression", &case_expr->where);
6629
6630       /* Punt.  */
6631       return;
6632     }
6633
6634   /* PR 19168 has a long discussion concerning a mismatch of the kinds
6635      of the SELECT CASE expression and its CASE values.  Walk the lists
6636      of case values, and if we find a mismatch, promote case_expr to
6637      the appropriate kind.  */
6638
6639   if (type == BT_LOGICAL || type == BT_INTEGER)
6640     {
6641       for (body = code->block; body; body = body->block)
6642         {
6643           /* Walk the case label list.  */
6644           for (cp = body->ext.case_list; cp; cp = cp->next)
6645             {
6646               /* Intercept the DEFAULT case.  It does not have a kind.  */
6647               if (cp->low == NULL && cp->high == NULL)
6648                 continue;
6649
6650               /* Unreachable case ranges are discarded, so ignore.  */
6651               if (cp->low != NULL && cp->high != NULL
6652                   && cp->low != cp->high
6653                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
6654                 continue;
6655
6656               /* FIXME: Should a warning be issued?  */
6657               if (cp->low != NULL
6658                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
6659                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
6660
6661               if (cp->high != NULL
6662                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
6663                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
6664             }
6665          }
6666     }
6667
6668   /* Assume there is no DEFAULT case.  */
6669   default_case = NULL;
6670   head = tail = NULL;
6671   ncases = 0;
6672   seen_logical = 0;
6673
6674   for (body = code->block; body; body = body->block)
6675     {
6676       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
6677       t = SUCCESS;
6678       seen_unreachable = 0;
6679
6680       /* Walk the case label list, making sure that all case labels
6681          are legal.  */
6682       for (cp = body->ext.case_list; cp; cp = cp->next)
6683         {
6684           /* Count the number of cases in the whole construct.  */
6685           ncases++;
6686
6687           /* Intercept the DEFAULT case.  */
6688           if (cp->low == NULL && cp->high == NULL)
6689             {
6690               if (default_case != NULL)
6691                 {
6692                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
6693                              "by a second DEFAULT CASE at %L",
6694                              &default_case->where, &cp->where);
6695                   t = FAILURE;
6696                   break;
6697                 }
6698               else
6699                 {
6700                   default_case = cp;
6701                   continue;
6702                 }
6703             }
6704
6705           /* Deal with single value cases and case ranges.  Errors are
6706              issued from the validation function.  */
6707           if(validate_case_label_expr (cp->low, case_expr) != SUCCESS
6708              || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
6709             {
6710               t = FAILURE;
6711               break;
6712             }
6713
6714           if (type == BT_LOGICAL
6715               && ((cp->low == NULL || cp->high == NULL)
6716                   || cp->low != cp->high))
6717             {
6718               gfc_error ("Logical range in CASE statement at %L is not "
6719                          "allowed", &cp->low->where);
6720               t = FAILURE;
6721               break;
6722             }
6723
6724           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
6725             {
6726               int value;
6727               value = cp->low->value.logical == 0 ? 2 : 1;
6728               if (value & seen_logical)
6729                 {
6730                   gfc_error ("constant logical value in CASE statement "
6731                              "is repeated at %L",
6732                              &cp->low->where);
6733                   t = FAILURE;
6734                   break;
6735                 }
6736               seen_logical |= value;
6737             }
6738
6739           if (cp->low != NULL && cp->high != NULL
6740               && cp->low != cp->high
6741               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
6742             {
6743               if (gfc_option.warn_surprising)
6744                 gfc_warning ("Range specification at %L can never "
6745                              "be matched", &cp->where);
6746
6747               cp->unreachable = 1;
6748               seen_unreachable = 1;
6749             }
6750           else
6751             {
6752               /* If the case range can be matched, it can also overlap with
6753                  other cases.  To make sure it does not, we put it in a
6754                  double linked list here.  We sort that with a merge sort
6755                  later on to detect any overlapping cases.  */
6756               if (!head)
6757                 {
6758                   head = tail = cp;
6759                   head->right = head->left = NULL;
6760                 }
6761               else
6762                 {
6763                   tail->right = cp;
6764                   tail->right->left = tail;
6765                   tail = tail->right;
6766                   tail->right = NULL;
6767                 }
6768             }
6769         }
6770
6771       /* It there was a failure in the previous case label, give up
6772          for this case label list.  Continue with the next block.  */
6773       if (t == FAILURE)
6774         continue;
6775
6776       /* See if any case labels that are unreachable have been seen.
6777          If so, we eliminate them.  This is a bit of a kludge because
6778          the case lists for a single case statement (label) is a
6779          single forward linked lists.  */
6780       if (seen_unreachable)
6781       {
6782         /* Advance until the first case in the list is reachable.  */
6783         while (body->ext.case_list != NULL
6784                && body->ext.case_list->unreachable)
6785           {
6786             gfc_case *n = body->ext.case_list;
6787             body->ext.case_list = body->ext.case_list->next;
6788             n->next = NULL;
6789             gfc_free_case_list (n);
6790           }
6791
6792         /* Strip all other unreachable cases.  */
6793         if (body->ext.case_list)
6794           {
6795             for (cp = body->ext.case_list; cp->next; cp = cp->next)
6796               {
6797                 if (cp->next->unreachable)
6798                   {
6799                     gfc_case *n = cp->next;
6800                     cp->next = cp->next->next;
6801                     n->next = NULL;
6802                     gfc_free_case_list (n);
6803                   }
6804               }
6805           }
6806       }
6807     }
6808
6809   /* See if there were overlapping cases.  If the check returns NULL,
6810      there was overlap.  In that case we don't do anything.  If head
6811      is non-NULL, we prepend the DEFAULT case.  The sorted list can
6812      then used during code generation for SELECT CASE constructs with
6813      a case expression of a CHARACTER type.  */
6814   if (head)
6815     {
6816       head = check_case_overlap (head);
6817
6818       /* Prepend the default_case if it is there.  */
6819       if (head != NULL && default_case)
6820         {
6821           default_case->left = NULL;
6822           default_case->right = head;
6823           head->left = default_case;
6824         }
6825     }
6826
6827   /* Eliminate dead blocks that may be the result if we've seen
6828      unreachable case labels for a block.  */
6829   for (body = code; body && body->block; body = body->block)
6830     {
6831       if (body->block->ext.case_list == NULL)
6832         {
6833           /* Cut the unreachable block from the code chain.  */
6834           gfc_code *c = body->block;
6835           body->block = c->block;
6836
6837           /* Kill the dead block, but not the blocks below it.  */
6838           c->block = NULL;
6839           gfc_free_statements (c);
6840         }
6841     }
6842
6843   /* More than two cases is legal but insane for logical selects.
6844      Issue a warning for it.  */
6845   if (gfc_option.warn_surprising && type == BT_LOGICAL
6846       && ncases > 2)
6847     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
6848                  &code->loc);
6849 }
6850
6851
6852 /* Check if a derived type is extensible.  */
6853
6854 bool
6855 gfc_type_is_extensible (gfc_symbol *sym)
6856 {
6857   return !(sym->attr.is_bind_c || sym->attr.sequence);
6858 }
6859
6860
6861 /* Resolve a SELECT TYPE statement.  */
6862
6863 static void
6864 resolve_select_type (gfc_code *code)
6865 {
6866   gfc_symbol *selector_type;
6867   gfc_code *body, *new_st;
6868   gfc_case *c, *default_case;
6869   gfc_symtree *st;
6870   char name[GFC_MAX_SYMBOL_LEN];
6871   gfc_namespace *ns;
6872
6873   ns = code->ext.ns;
6874   gfc_resolve (ns);
6875
6876   if (code->expr2)
6877     selector_type = code->expr2->ts.u.derived->components->ts.u.derived;
6878   else
6879     selector_type = code->expr1->ts.u.derived->components->ts.u.derived;
6880
6881   /* Assume there is no DEFAULT case.  */
6882   default_case = NULL;
6883
6884   /* Loop over TYPE IS / CLASS IS cases.  */
6885   for (body = code->block; body; body = body->block)
6886     {
6887       c = body->ext.case_list;
6888
6889       /* Check F03:C815.  */
6890       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
6891           && !gfc_type_is_extensible (c->ts.u.derived))
6892         {
6893           gfc_error ("Derived type '%s' at %L must be extensible",
6894                      c->ts.u.derived->name, &c->where);
6895           continue;
6896         }
6897
6898       /* Check F03:C816.  */
6899       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
6900           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
6901         {
6902           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
6903                      c->ts.u.derived->name, &c->where, selector_type->name);
6904           continue;
6905         }
6906
6907       /* Intercept the DEFAULT case.  */
6908       if (c->ts.type == BT_UNKNOWN)
6909         {
6910           /* Check F03:C818.  */
6911           if (default_case != NULL)
6912             gfc_error ("The DEFAULT CASE at %L cannot be followed "
6913                        "by a second DEFAULT CASE at %L",
6914                        &default_case->where, &c->where);
6915           else
6916             default_case = c;
6917           continue;
6918         }
6919     }
6920
6921   if (code->expr2)
6922     {
6923       /* Insert assignment for selector variable.  */
6924       new_st = gfc_get_code ();
6925       new_st->op = EXEC_ASSIGN;
6926       new_st->expr1 = gfc_copy_expr (code->expr1);
6927       new_st->expr2 = gfc_copy_expr (code->expr2);
6928       ns->code = new_st;
6929     }
6930
6931   /* Put SELECT TYPE statement inside a BLOCK.  */
6932   new_st = gfc_get_code ();
6933   new_st->op = code->op;
6934   new_st->expr1 = code->expr1;
6935   new_st->expr2 = code->expr2;
6936   new_st->block = code->block;
6937   if (!ns->code)
6938     ns->code = new_st;
6939   else
6940     ns->code->next = new_st;
6941   code->op = EXEC_BLOCK;
6942   code->expr1 = code->expr2 =  NULL;
6943   code->block = NULL;
6944
6945   code = new_st;
6946
6947   /* Transform to EXEC_SELECT.  */
6948   code->op = EXEC_SELECT;
6949   gfc_add_component_ref (code->expr1, "$vindex");
6950
6951   /* Loop over TYPE IS / CLASS IS cases.  */
6952   for (body = code->block; body; body = body->block)
6953     {
6954       c = body->ext.case_list;
6955       if (c->ts.type == BT_DERIVED)
6956         c->low = c->high = gfc_int_expr (c->ts.u.derived->vindex);
6957       else if (c->ts.type == BT_CLASS)
6958         /* Currently IS CLASS blocks are simply ignored.
6959            TODO: Implement IS CLASS.  */
6960         c->unreachable = 1;
6961
6962       if (c->ts.type != BT_DERIVED)
6963         continue;
6964       /* Assign temporary to selector.  */
6965       sprintf (name, "tmp$%s", c->ts.u.derived->name);
6966       st = gfc_find_symtree (ns->sym_root, name);
6967       new_st = gfc_get_code ();
6968       new_st->op = EXEC_POINTER_ASSIGN;
6969       new_st->expr1 = gfc_get_variable_expr (st);
6970       new_st->expr2 = gfc_get_variable_expr (code->expr1->symtree);
6971       gfc_add_component_ref (new_st->expr2, "$data");
6972       new_st->next = body->next;
6973       body->next = new_st;
6974     }
6975
6976   /* Eliminate dead blocks.  */
6977   for (body = code; body && body->block; body = body->block)
6978     {
6979       if (body->block->ext.case_list->unreachable)
6980         {
6981           /* Cut the unreachable block from the code chain.  */
6982           gfc_code *cd = body->block;
6983           body->block = cd->block;
6984           /* Kill the dead block, but not the blocks below it.  */
6985           cd->block = NULL;
6986           gfc_free_statements (cd);
6987         }
6988     }
6989
6990   resolve_select (code);
6991
6992 }
6993
6994
6995 /* Resolve a transfer statement. This is making sure that:
6996    -- a derived type being transferred has only non-pointer components
6997    -- a derived type being transferred doesn't have private components, unless 
6998       it's being transferred from the module where the type was defined
6999    -- we're not trying to transfer a whole assumed size array.  */
7000
7001 static void
7002 resolve_transfer (gfc_code *code)
7003 {
7004   gfc_typespec *ts;
7005   gfc_symbol *sym;
7006   gfc_ref *ref;
7007   gfc_expr *exp;
7008
7009   exp = code->expr1;
7010
7011   if (exp->expr_type != EXPR_VARIABLE && exp->expr_type != EXPR_FUNCTION)
7012     return;
7013
7014   sym = exp->symtree->n.sym;
7015   ts = &sym->ts;
7016
7017   /* Go to actual component transferred.  */
7018   for (ref = code->expr1->ref; ref; ref = ref->next)
7019     if (ref->type == REF_COMPONENT)
7020       ts = &ref->u.c.component->ts;
7021
7022   if (ts->type == BT_DERIVED)
7023     {
7024       /* Check that transferred derived type doesn't contain POINTER
7025          components.  */
7026       if (ts->u.derived->attr.pointer_comp)
7027         {
7028           gfc_error ("Data transfer element at %L cannot have "
7029                      "POINTER components", &code->loc);
7030           return;
7031         }
7032
7033       if (ts->u.derived->attr.alloc_comp)
7034         {
7035           gfc_error ("Data transfer element at %L cannot have "
7036                      "ALLOCATABLE components", &code->loc);
7037           return;
7038         }
7039
7040       if (derived_inaccessible (ts->u.derived))
7041         {
7042           gfc_error ("Data transfer element at %L cannot have "
7043                      "PRIVATE components",&code->loc);
7044           return;
7045         }
7046     }
7047
7048   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
7049       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
7050     {
7051       gfc_error ("Data transfer element at %L cannot be a full reference to "
7052                  "an assumed-size array", &code->loc);
7053       return;
7054     }
7055 }
7056
7057
7058 /*********** Toplevel code resolution subroutines ***********/
7059
7060 /* Find the set of labels that are reachable from this block.  We also
7061    record the last statement in each block.  */
7062      
7063 static void
7064 find_reachable_labels (gfc_code *block)
7065 {
7066   gfc_code *c;
7067
7068   if (!block)
7069     return;
7070
7071   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
7072
7073   /* Collect labels in this block.  We don't keep those corresponding
7074      to END {IF|SELECT}, these are checked in resolve_branch by going
7075      up through the code_stack.  */
7076   for (c = block; c; c = c->next)
7077     {
7078       if (c->here && c->op != EXEC_END_BLOCK)
7079         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
7080     }
7081
7082   /* Merge with labels from parent block.  */
7083   if (cs_base->prev)
7084     {
7085       gcc_assert (cs_base->prev->reachable_labels);
7086       bitmap_ior_into (cs_base->reachable_labels,
7087                        cs_base->prev->reachable_labels);
7088     }
7089 }
7090
7091 /* Given a branch to a label, see if the branch is conforming.
7092    The code node describes where the branch is located.  */
7093
7094 static void
7095 resolve_branch (gfc_st_label *label, gfc_code *code)
7096 {
7097   code_stack *stack;
7098
7099   if (label == NULL)
7100     return;
7101
7102   /* Step one: is this a valid branching target?  */
7103
7104   if (label->defined == ST_LABEL_UNKNOWN)
7105     {
7106       gfc_error ("Label %d referenced at %L is never defined", label->value,
7107                  &label->where);
7108       return;
7109     }
7110
7111   if (label->defined != ST_LABEL_TARGET)
7112     {
7113       gfc_error ("Statement at %L is not a valid branch target statement "
7114                  "for the branch statement at %L", &label->where, &code->loc);
7115       return;
7116     }
7117
7118   /* Step two: make sure this branch is not a branch to itself ;-)  */
7119
7120   if (code->here == label)
7121     {
7122       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
7123       return;
7124     }
7125
7126   /* Step three:  See if the label is in the same block as the
7127      branching statement.  The hard work has been done by setting up
7128      the bitmap reachable_labels.  */
7129
7130   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
7131     return;
7132
7133   /* Step four:  If we haven't found the label in the bitmap, it may
7134     still be the label of the END of the enclosing block, in which
7135     case we find it by going up the code_stack.  */
7136
7137   for (stack = cs_base; stack; stack = stack->prev)
7138     if (stack->current->next && stack->current->next->here == label)
7139       break;
7140
7141   if (stack)
7142     {
7143       gcc_assert (stack->current->next->op == EXEC_END_BLOCK);
7144       return;
7145     }
7146
7147   /* The label is not in an enclosing block, so illegal.  This was
7148      allowed in Fortran 66, so we allow it as extension.  No
7149      further checks are necessary in this case.  */
7150   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
7151                   "as the GOTO statement at %L", &label->where,
7152                   &code->loc);
7153   return;
7154 }
7155
7156
7157 /* Check whether EXPR1 has the same shape as EXPR2.  */
7158
7159 static gfc_try
7160 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
7161 {
7162   mpz_t shape[GFC_MAX_DIMENSIONS];
7163   mpz_t shape2[GFC_MAX_DIMENSIONS];
7164   gfc_try result = FAILURE;
7165   int i;
7166
7167   /* Compare the rank.  */
7168   if (expr1->rank != expr2->rank)
7169     return result;
7170
7171   /* Compare the size of each dimension.  */
7172   for (i=0; i<expr1->rank; i++)
7173     {
7174       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
7175         goto ignore;
7176
7177       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
7178         goto ignore;
7179
7180       if (mpz_cmp (shape[i], shape2[i]))
7181         goto over;
7182     }
7183
7184   /* When either of the two expression is an assumed size array, we
7185      ignore the comparison of dimension sizes.  */
7186 ignore:
7187   result = SUCCESS;
7188
7189 over:
7190   for (i--; i >= 0; i--)
7191     {
7192       mpz_clear (shape[i]);
7193       mpz_clear (shape2[i]);
7194     }
7195   return result;
7196 }
7197
7198
7199 /* Check whether a WHERE assignment target or a WHERE mask expression
7200    has the same shape as the outmost WHERE mask expression.  */
7201
7202 static void
7203 resolve_where (gfc_code *code, gfc_expr *mask)
7204 {
7205   gfc_code *cblock;
7206   gfc_code *cnext;
7207   gfc_expr *e = NULL;
7208
7209   cblock = code->block;
7210
7211   /* Store the first WHERE mask-expr of the WHERE statement or construct.
7212      In case of nested WHERE, only the outmost one is stored.  */
7213   if (mask == NULL) /* outmost WHERE */
7214     e = cblock->expr1;
7215   else /* inner WHERE */
7216     e = mask;
7217
7218   while (cblock)
7219     {
7220       if (cblock->expr1)
7221         {
7222           /* Check if the mask-expr has a consistent shape with the
7223              outmost WHERE mask-expr.  */
7224           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
7225             gfc_error ("WHERE mask at %L has inconsistent shape",
7226                        &cblock->expr1->where);
7227          }
7228
7229       /* the assignment statement of a WHERE statement, or the first
7230          statement in where-body-construct of a WHERE construct */
7231       cnext = cblock->next;
7232       while (cnext)
7233         {
7234           switch (cnext->op)
7235             {
7236             /* WHERE assignment statement */
7237             case EXEC_ASSIGN:
7238
7239               /* Check shape consistent for WHERE assignment target.  */
7240               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
7241                gfc_error ("WHERE assignment target at %L has "
7242                           "inconsistent shape", &cnext->expr1->where);
7243               break;
7244
7245   
7246             case EXEC_ASSIGN_CALL:
7247               resolve_call (cnext);
7248               if (!cnext->resolved_sym->attr.elemental)
7249                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
7250                           &cnext->ext.actual->expr->where);
7251               break;
7252
7253             /* WHERE or WHERE construct is part of a where-body-construct */
7254             case EXEC_WHERE:
7255               resolve_where (cnext, e);
7256               break;
7257
7258             default:
7259               gfc_error ("Unsupported statement inside WHERE at %L",
7260                          &cnext->loc);
7261             }
7262          /* the next statement within the same where-body-construct */
7263          cnext = cnext->next;
7264        }
7265     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
7266     cblock = cblock->block;
7267   }
7268 }
7269
7270
7271 /* Resolve assignment in FORALL construct.
7272    NVAR is the number of FORALL index variables, and VAR_EXPR records the
7273    FORALL index variables.  */
7274
7275 static void
7276 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
7277 {
7278   int n;
7279
7280   for (n = 0; n < nvar; n++)
7281     {
7282       gfc_symbol *forall_index;
7283
7284       forall_index = var_expr[n]->symtree->n.sym;
7285
7286       /* Check whether the assignment target is one of the FORALL index
7287          variable.  */
7288       if ((code->expr1->expr_type == EXPR_VARIABLE)
7289           && (code->expr1->symtree->n.sym == forall_index))
7290         gfc_error ("Assignment to a FORALL index variable at %L",
7291                    &code->expr1->where);
7292       else
7293         {
7294           /* If one of the FORALL index variables doesn't appear in the
7295              assignment variable, then there could be a many-to-one
7296              assignment.  Emit a warning rather than an error because the
7297              mask could be resolving this problem.  */
7298           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
7299             gfc_warning ("The FORALL with index '%s' is not used on the "
7300                          "left side of the assignment at %L and so might "
7301                          "cause multiple assignment to this object",
7302                          var_expr[n]->symtree->name, &code->expr1->where);
7303         }
7304     }
7305 }
7306
7307
7308 /* Resolve WHERE statement in FORALL construct.  */
7309
7310 static void
7311 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
7312                                   gfc_expr **var_expr)
7313 {
7314   gfc_code *cblock;
7315   gfc_code *cnext;
7316
7317   cblock = code->block;
7318   while (cblock)
7319     {
7320       /* the assignment statement of a WHERE statement, or the first
7321          statement in where-body-construct of a WHERE construct */
7322       cnext = cblock->next;
7323       while (cnext)
7324         {
7325           switch (cnext->op)
7326             {
7327             /* WHERE assignment statement */
7328             case EXEC_ASSIGN:
7329               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
7330               break;
7331   
7332             /* WHERE operator assignment statement */
7333             case EXEC_ASSIGN_CALL:
7334               resolve_call (cnext);
7335               if (!cnext->resolved_sym->attr.elemental)
7336                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
7337                           &cnext->ext.actual->expr->where);
7338               break;
7339
7340             /* WHERE or WHERE construct is part of a where-body-construct */
7341             case EXEC_WHERE:
7342               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
7343               break;
7344
7345             default:
7346               gfc_error ("Unsupported statement inside WHERE at %L",
7347                          &cnext->loc);
7348             }
7349           /* the next statement within the same where-body-construct */
7350           cnext = cnext->next;
7351         }
7352       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
7353       cblock = cblock->block;
7354     }
7355 }
7356
7357
7358 /* Traverse the FORALL body to check whether the following errors exist:
7359    1. For assignment, check if a many-to-one assignment happens.
7360    2. For WHERE statement, check the WHERE body to see if there is any
7361       many-to-one assignment.  */
7362
7363 static void
7364 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
7365 {
7366   gfc_code *c;
7367
7368   c = code->block->next;
7369   while (c)
7370     {
7371       switch (c->op)
7372         {
7373         case EXEC_ASSIGN:
7374         case EXEC_POINTER_ASSIGN:
7375           gfc_resolve_assign_in_forall (c, nvar, var_expr);
7376           break;
7377
7378         case EXEC_ASSIGN_CALL:
7379           resolve_call (c);
7380           break;
7381
7382         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
7383            there is no need to handle it here.  */
7384         case EXEC_FORALL:
7385           break;
7386         case EXEC_WHERE:
7387           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
7388           break;
7389         default:
7390           break;
7391         }
7392       /* The next statement in the FORALL body.  */
7393       c = c->next;
7394     }
7395 }
7396
7397
7398 /* Counts the number of iterators needed inside a forall construct, including
7399    nested forall constructs. This is used to allocate the needed memory 
7400    in gfc_resolve_forall.  */
7401
7402 static int 
7403 gfc_count_forall_iterators (gfc_code *code)
7404 {
7405   int max_iters, sub_iters, current_iters;
7406   gfc_forall_iterator *fa;
7407
7408   gcc_assert(code->op == EXEC_FORALL);
7409   max_iters = 0;
7410   current_iters = 0;
7411
7412   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
7413     current_iters ++;
7414   
7415   code = code->block->next;
7416
7417   while (code)
7418     {          
7419       if (code->op == EXEC_FORALL)
7420         {
7421           sub_iters = gfc_count_forall_iterators (code);
7422           if (sub_iters > max_iters)
7423             max_iters = sub_iters;
7424         }
7425       code = code->next;
7426     }
7427
7428   return current_iters + max_iters;
7429 }
7430
7431
7432 /* Given a FORALL construct, first resolve the FORALL iterator, then call
7433    gfc_resolve_forall_body to resolve the FORALL body.  */
7434
7435 static void
7436 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
7437 {
7438   static gfc_expr **var_expr;
7439   static int total_var = 0;
7440   static int nvar = 0;
7441   int old_nvar, tmp;
7442   gfc_forall_iterator *fa;
7443   int i;
7444
7445   old_nvar = nvar;
7446
7447   /* Start to resolve a FORALL construct   */
7448   if (forall_save == 0)
7449     {
7450       /* Count the total number of FORALL index in the nested FORALL
7451          construct in order to allocate the VAR_EXPR with proper size.  */
7452       total_var = gfc_count_forall_iterators (code);
7453
7454       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
7455       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
7456     }
7457
7458   /* The information about FORALL iterator, including FORALL index start, end
7459      and stride. The FORALL index can not appear in start, end or stride.  */
7460   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
7461     {
7462       /* Check if any outer FORALL index name is the same as the current
7463          one.  */
7464       for (i = 0; i < nvar; i++)
7465         {
7466           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
7467             {
7468               gfc_error ("An outer FORALL construct already has an index "
7469                          "with this name %L", &fa->var->where);
7470             }
7471         }
7472
7473       /* Record the current FORALL index.  */
7474       var_expr[nvar] = gfc_copy_expr (fa->var);
7475
7476       nvar++;
7477
7478       /* No memory leak.  */
7479       gcc_assert (nvar <= total_var);
7480     }
7481
7482   /* Resolve the FORALL body.  */
7483   gfc_resolve_forall_body (code, nvar, var_expr);
7484
7485   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
7486   gfc_resolve_blocks (code->block, ns);
7487
7488   tmp = nvar;
7489   nvar = old_nvar;
7490   /* Free only the VAR_EXPRs allocated in this frame.  */
7491   for (i = nvar; i < tmp; i++)
7492      gfc_free_expr (var_expr[i]);
7493
7494   if (nvar == 0)
7495     {
7496       /* We are in the outermost FORALL construct.  */
7497       gcc_assert (forall_save == 0);
7498
7499       /* VAR_EXPR is not needed any more.  */
7500       gfc_free (var_expr);
7501       total_var = 0;
7502     }
7503 }
7504
7505
7506 /* Resolve a BLOCK construct statement.  */
7507
7508 static void
7509 resolve_block_construct (gfc_code* code)
7510 {
7511   /* Eventually, we may want to do some checks here or handle special stuff.
7512      But so far the only thing we can do is resolving the local namespace.  */
7513
7514   gfc_resolve (code->ext.ns);
7515 }
7516
7517
7518 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
7519    DO code nodes.  */
7520
7521 static void resolve_code (gfc_code *, gfc_namespace *);
7522
7523 void
7524 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
7525 {
7526   gfc_try t;
7527
7528   for (; b; b = b->block)
7529     {
7530       t = gfc_resolve_expr (b->expr1);
7531       if (gfc_resolve_expr (b->expr2) == FAILURE)
7532         t = FAILURE;
7533
7534       switch (b->op)
7535         {
7536         case EXEC_IF:
7537           if (t == SUCCESS && b->expr1 != NULL
7538               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
7539             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
7540                        &b->expr1->where);
7541           break;
7542
7543         case EXEC_WHERE:
7544           if (t == SUCCESS
7545               && b->expr1 != NULL
7546               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
7547             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
7548                        &b->expr1->where);
7549           break;
7550
7551         case EXEC_GOTO:
7552           resolve_branch (b->label1, b);
7553           break;
7554
7555         case EXEC_BLOCK:
7556           resolve_block_construct (b);
7557           break;
7558
7559         case EXEC_SELECT:
7560         case EXEC_SELECT_TYPE:
7561         case EXEC_FORALL:
7562         case EXEC_DO:
7563         case EXEC_DO_WHILE:
7564         case EXEC_READ:
7565         case EXEC_WRITE:
7566         case EXEC_IOLENGTH:
7567         case EXEC_WAIT:
7568           break;
7569
7570         case EXEC_OMP_ATOMIC:
7571         case EXEC_OMP_CRITICAL:
7572         case EXEC_OMP_DO:
7573         case EXEC_OMP_MASTER:
7574         case EXEC_OMP_ORDERED:
7575         case EXEC_OMP_PARALLEL:
7576         case EXEC_OMP_PARALLEL_DO:
7577         case EXEC_OMP_PARALLEL_SECTIONS:
7578         case EXEC_OMP_PARALLEL_WORKSHARE:
7579         case EXEC_OMP_SECTIONS:
7580         case EXEC_OMP_SINGLE:
7581         case EXEC_OMP_TASK:
7582         case EXEC_OMP_TASKWAIT:
7583         case EXEC_OMP_WORKSHARE:
7584           break;
7585
7586         default:
7587           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
7588         }
7589
7590       resolve_code (b->next, ns);
7591     }
7592 }
7593
7594
7595 /* Does everything to resolve an ordinary assignment.  Returns true
7596    if this is an interface assignment.  */
7597 static bool
7598 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
7599 {
7600   bool rval = false;
7601   gfc_expr *lhs;
7602   gfc_expr *rhs;
7603   int llen = 0;
7604   int rlen = 0;
7605   int n;
7606   gfc_ref *ref;
7607
7608   if (gfc_extend_assign (code, ns) == SUCCESS)
7609     {
7610       gfc_symbol* assign_proc;
7611       gfc_expr** rhsptr;
7612
7613       if (code->op == EXEC_ASSIGN_CALL)
7614         {
7615           lhs = code->ext.actual->expr;
7616           rhsptr = &code->ext.actual->next->expr;
7617           assign_proc = code->symtree->n.sym;
7618         }
7619       else
7620         {
7621           gfc_actual_arglist* args;
7622           gfc_typebound_proc* tbp;
7623
7624           gcc_assert (code->op == EXEC_COMPCALL);
7625
7626           args = code->expr1->value.compcall.actual;
7627           lhs = args->expr;
7628           rhsptr = &args->next->expr;
7629
7630           tbp = code->expr1->value.compcall.tbp;
7631           gcc_assert (!tbp->is_generic);
7632           assign_proc = tbp->u.specific->n.sym;
7633         }
7634
7635       /* Make a temporary rhs when there is a default initializer
7636          and rhs is the same symbol as the lhs.  */
7637       if ((*rhsptr)->expr_type == EXPR_VARIABLE
7638             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
7639             && has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
7640             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
7641         *rhsptr = gfc_get_parentheses (*rhsptr);
7642
7643       return true;
7644     }
7645
7646   lhs = code->expr1;
7647   rhs = code->expr2;
7648
7649   if (rhs->is_boz
7650       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
7651                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
7652                          &code->loc) == FAILURE)
7653     return false;
7654
7655   /* Handle the case of a BOZ literal on the RHS.  */
7656   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
7657     {
7658       int rc;
7659       if (gfc_option.warn_surprising)
7660         gfc_warning ("BOZ literal at %L is bitwise transferred "
7661                      "non-integer symbol '%s'", &code->loc,
7662                      lhs->symtree->n.sym->name);
7663
7664       if (!gfc_convert_boz (rhs, &lhs->ts))
7665         return false;
7666       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
7667         {
7668           if (rc == ARITH_UNDERFLOW)
7669             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
7670                        ". This check can be disabled with the option "
7671                        "-fno-range-check", &rhs->where);
7672           else if (rc == ARITH_OVERFLOW)
7673             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
7674                        ". This check can be disabled with the option "
7675                        "-fno-range-check", &rhs->where);
7676           else if (rc == ARITH_NAN)
7677             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
7678                        ". This check can be disabled with the option "
7679                        "-fno-range-check", &rhs->where);
7680           return false;
7681         }
7682     }
7683
7684
7685   if (lhs->ts.type == BT_CHARACTER
7686         && gfc_option.warn_character_truncation)
7687     {
7688       if (lhs->ts.u.cl != NULL
7689             && lhs->ts.u.cl->length != NULL
7690             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
7691         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
7692
7693       if (rhs->expr_type == EXPR_CONSTANT)
7694         rlen = rhs->value.character.length;
7695
7696       else if (rhs->ts.u.cl != NULL
7697                  && rhs->ts.u.cl->length != NULL
7698                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
7699         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
7700
7701       if (rlen && llen && rlen > llen)
7702         gfc_warning_now ("CHARACTER expression will be truncated "
7703                          "in assignment (%d/%d) at %L",
7704                          llen, rlen, &code->loc);
7705     }
7706
7707   /* Ensure that a vector index expression for the lvalue is evaluated
7708      to a temporary if the lvalue symbol is referenced in it.  */
7709   if (lhs->rank)
7710     {
7711       for (ref = lhs->ref; ref; ref= ref->next)
7712         if (ref->type == REF_ARRAY)
7713           {
7714             for (n = 0; n < ref->u.ar.dimen; n++)
7715               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
7716                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
7717                                            ref->u.ar.start[n]))
7718                 ref->u.ar.start[n]
7719                         = gfc_get_parentheses (ref->u.ar.start[n]);
7720           }
7721     }
7722
7723   if (gfc_pure (NULL))
7724     {
7725       if (gfc_impure_variable (lhs->symtree->n.sym))
7726         {
7727           gfc_error ("Cannot assign to variable '%s' in PURE "
7728                      "procedure at %L",
7729                       lhs->symtree->n.sym->name,
7730                       &lhs->where);
7731           return rval;
7732         }
7733
7734       if (lhs->ts.type == BT_DERIVED
7735             && lhs->expr_type == EXPR_VARIABLE
7736             && lhs->ts.u.derived->attr.pointer_comp
7737             && gfc_impure_variable (rhs->symtree->n.sym))
7738         {
7739           gfc_error ("The impure variable at %L is assigned to "
7740                      "a derived type variable with a POINTER "
7741                      "component in a PURE procedure (12.6)",
7742                      &rhs->where);
7743           return rval;
7744         }
7745     }
7746
7747   /* F03:7.4.1.2.  */
7748   if (lhs->ts.type == BT_CLASS)
7749     {
7750       gfc_error ("Variable must not be polymorphic in assignment at %L",
7751                  &lhs->where);
7752       return false;
7753     }
7754
7755   gfc_check_assign (lhs, rhs, 1);
7756   return false;
7757 }
7758
7759
7760 /* Given a block of code, recursively resolve everything pointed to by this
7761    code block.  */
7762
7763 static void
7764 resolve_code (gfc_code *code, gfc_namespace *ns)
7765 {
7766   int omp_workshare_save;
7767   int forall_save;
7768   code_stack frame;
7769   gfc_try t;
7770
7771   frame.prev = cs_base;
7772   frame.head = code;
7773   cs_base = &frame;
7774
7775   find_reachable_labels (code);
7776
7777   for (; code; code = code->next)
7778     {
7779       frame.current = code;
7780       forall_save = forall_flag;
7781
7782       if (code->op == EXEC_FORALL)
7783         {
7784           forall_flag = 1;
7785           gfc_resolve_forall (code, ns, forall_save);
7786           forall_flag = 2;
7787         }
7788       else if (code->block)
7789         {
7790           omp_workshare_save = -1;
7791           switch (code->op)
7792             {
7793             case EXEC_OMP_PARALLEL_WORKSHARE:
7794               omp_workshare_save = omp_workshare_flag;
7795               omp_workshare_flag = 1;
7796               gfc_resolve_omp_parallel_blocks (code, ns);
7797               break;
7798             case EXEC_OMP_PARALLEL:
7799             case EXEC_OMP_PARALLEL_DO:
7800             case EXEC_OMP_PARALLEL_SECTIONS:
7801             case EXEC_OMP_TASK:
7802               omp_workshare_save = omp_workshare_flag;
7803               omp_workshare_flag = 0;
7804               gfc_resolve_omp_parallel_blocks (code, ns);
7805               break;
7806             case EXEC_OMP_DO:
7807               gfc_resolve_omp_do_blocks (code, ns);
7808               break;
7809             case EXEC_OMP_WORKSHARE:
7810               omp_workshare_save = omp_workshare_flag;
7811               omp_workshare_flag = 1;
7812               /* FALLTHROUGH */
7813             default:
7814               gfc_resolve_blocks (code->block, ns);
7815               break;
7816             }
7817
7818           if (omp_workshare_save != -1)
7819             omp_workshare_flag = omp_workshare_save;
7820         }
7821
7822       t = SUCCESS;
7823       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
7824         t = gfc_resolve_expr (code->expr1);
7825       forall_flag = forall_save;
7826
7827       if (gfc_resolve_expr (code->expr2) == FAILURE)
7828         t = FAILURE;
7829
7830       if (code->op == EXEC_ALLOCATE
7831           && gfc_resolve_expr (code->expr3) == FAILURE)
7832         t = FAILURE;
7833
7834       switch (code->op)
7835         {
7836         case EXEC_NOP:
7837         case EXEC_END_BLOCK:
7838         case EXEC_CYCLE:
7839         case EXEC_PAUSE:
7840         case EXEC_STOP:
7841         case EXEC_EXIT:
7842         case EXEC_CONTINUE:
7843         case EXEC_DT_END:
7844         case EXEC_ASSIGN_CALL:
7845           break;
7846
7847         case EXEC_ENTRY:
7848           /* Keep track of which entry we are up to.  */
7849           current_entry_id = code->ext.entry->id;
7850           break;
7851
7852         case EXEC_WHERE:
7853           resolve_where (code, NULL);
7854           break;
7855
7856         case EXEC_GOTO:
7857           if (code->expr1 != NULL)
7858             {
7859               if (code->expr1->ts.type != BT_INTEGER)
7860                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
7861                            "INTEGER variable", &code->expr1->where);
7862               else if (code->expr1->symtree->n.sym->attr.assign != 1)
7863                 gfc_error ("Variable '%s' has not been assigned a target "
7864                            "label at %L", code->expr1->symtree->n.sym->name,
7865                            &code->expr1->where);
7866             }
7867           else
7868             resolve_branch (code->label1, code);
7869           break;
7870
7871         case EXEC_RETURN:
7872           if (code->expr1 != NULL
7873                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
7874             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
7875                        "INTEGER return specifier", &code->expr1->where);
7876           break;
7877
7878         case EXEC_INIT_ASSIGN:
7879         case EXEC_END_PROCEDURE:
7880           break;
7881
7882         case EXEC_ASSIGN:
7883           if (t == FAILURE)
7884             break;
7885
7886           if (resolve_ordinary_assign (code, ns))
7887             {
7888               if (code->op == EXEC_COMPCALL)
7889                 goto compcall;
7890               else
7891                 goto call;
7892             }
7893           break;
7894
7895         case EXEC_LABEL_ASSIGN:
7896           if (code->label1->defined == ST_LABEL_UNKNOWN)
7897             gfc_error ("Label %d referenced at %L is never defined",
7898                        code->label1->value, &code->label1->where);
7899           if (t == SUCCESS
7900               && (code->expr1->expr_type != EXPR_VARIABLE
7901                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
7902                   || code->expr1->symtree->n.sym->ts.kind
7903                      != gfc_default_integer_kind
7904                   || code->expr1->symtree->n.sym->as != NULL))
7905             gfc_error ("ASSIGN statement at %L requires a scalar "
7906                        "default INTEGER variable", &code->expr1->where);
7907           break;
7908
7909         case EXEC_POINTER_ASSIGN:
7910           if (t == FAILURE)
7911             break;
7912
7913           gfc_check_pointer_assign (code->expr1, code->expr2);
7914           break;
7915
7916         case EXEC_ARITHMETIC_IF:
7917           if (t == SUCCESS
7918               && code->expr1->ts.type != BT_INTEGER
7919               && code->expr1->ts.type != BT_REAL)
7920             gfc_error ("Arithmetic IF statement at %L requires a numeric "
7921                        "expression", &code->expr1->where);
7922
7923           resolve_branch (code->label1, code);
7924           resolve_branch (code->label2, code);
7925           resolve_branch (code->label3, code);
7926           break;
7927
7928         case EXEC_IF:
7929           if (t == SUCCESS && code->expr1 != NULL
7930               && (code->expr1->ts.type != BT_LOGICAL
7931                   || code->expr1->rank != 0))
7932             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
7933                        &code->expr1->where);
7934           break;
7935
7936         case EXEC_CALL:
7937         call:
7938           resolve_call (code);
7939           break;
7940
7941         case EXEC_COMPCALL:
7942         compcall:
7943           if (code->expr1->symtree
7944                 && code->expr1->symtree->n.sym->ts.type == BT_CLASS)
7945             resolve_class_typebound_call (code);
7946           else
7947             resolve_typebound_call (code);
7948           break;
7949
7950         case EXEC_CALL_PPC:
7951           resolve_ppc_call (code);
7952           break;
7953
7954         case EXEC_SELECT:
7955           /* Select is complicated. Also, a SELECT construct could be
7956              a transformed computed GOTO.  */
7957           resolve_select (code);
7958           break;
7959
7960         case EXEC_SELECT_TYPE:
7961           resolve_select_type (code);
7962           break;
7963
7964         case EXEC_BLOCK:
7965           gfc_resolve (code->ext.ns);
7966           break;
7967
7968         case EXEC_DO:
7969           if (code->ext.iterator != NULL)
7970             {
7971               gfc_iterator *iter = code->ext.iterator;
7972               if (gfc_resolve_iterator (iter, true) != FAILURE)
7973                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
7974             }
7975           break;
7976
7977         case EXEC_DO_WHILE:
7978           if (code->expr1 == NULL)
7979             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
7980           if (t == SUCCESS
7981               && (code->expr1->rank != 0
7982                   || code->expr1->ts.type != BT_LOGICAL))
7983             gfc_error ("Exit condition of DO WHILE loop at %L must be "
7984                        "a scalar LOGICAL expression", &code->expr1->where);
7985           break;
7986
7987         case EXEC_ALLOCATE:
7988           if (t == SUCCESS)
7989             resolve_allocate_deallocate (code, "ALLOCATE");
7990
7991           break;
7992
7993         case EXEC_DEALLOCATE:
7994           if (t == SUCCESS)
7995             resolve_allocate_deallocate (code, "DEALLOCATE");
7996
7997           break;
7998
7999         case EXEC_OPEN:
8000           if (gfc_resolve_open (code->ext.open) == FAILURE)
8001             break;
8002
8003           resolve_branch (code->ext.open->err, code);
8004           break;
8005
8006         case EXEC_CLOSE:
8007           if (gfc_resolve_close (code->ext.close) == FAILURE)
8008             break;
8009
8010           resolve_branch (code->ext.close->err, code);
8011           break;
8012
8013         case EXEC_BACKSPACE:
8014         case EXEC_ENDFILE:
8015         case EXEC_REWIND:
8016         case EXEC_FLUSH:
8017           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
8018             break;
8019
8020           resolve_branch (code->ext.filepos->err, code);
8021           break;
8022
8023         case EXEC_INQUIRE:
8024           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
8025               break;
8026
8027           resolve_branch (code->ext.inquire->err, code);
8028           break;
8029
8030         case EXEC_IOLENGTH:
8031           gcc_assert (code->ext.inquire != NULL);
8032           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
8033             break;
8034
8035           resolve_branch (code->ext.inquire->err, code);
8036           break;
8037
8038         case EXEC_WAIT:
8039           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
8040             break;
8041
8042           resolve_branch (code->ext.wait->err, code);
8043           resolve_branch (code->ext.wait->end, code);
8044           resolve_branch (code->ext.wait->eor, code);
8045           break;
8046
8047         case EXEC_READ:
8048         case EXEC_WRITE:
8049           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
8050             break;
8051
8052           resolve_branch (code->ext.dt->err, code);
8053           resolve_branch (code->ext.dt->end, code);
8054           resolve_branch (code->ext.dt->eor, code);
8055           break;
8056
8057         case EXEC_TRANSFER:
8058           resolve_transfer (code);
8059           break;
8060
8061         case EXEC_FORALL:
8062           resolve_forall_iterators (code->ext.forall_iterator);
8063
8064           if (code->expr1 != NULL && code->expr1->ts.type != BT_LOGICAL)
8065             gfc_error ("FORALL mask clause at %L requires a LOGICAL "
8066                        "expression", &code->expr1->where);
8067           break;
8068
8069         case EXEC_OMP_ATOMIC:
8070         case EXEC_OMP_BARRIER:
8071         case EXEC_OMP_CRITICAL:
8072         case EXEC_OMP_FLUSH:
8073         case EXEC_OMP_DO:
8074         case EXEC_OMP_MASTER:
8075         case EXEC_OMP_ORDERED:
8076         case EXEC_OMP_SECTIONS:
8077         case EXEC_OMP_SINGLE:
8078         case EXEC_OMP_TASKWAIT:
8079         case EXEC_OMP_WORKSHARE:
8080           gfc_resolve_omp_directive (code, ns);
8081           break;
8082
8083         case EXEC_OMP_PARALLEL:
8084         case EXEC_OMP_PARALLEL_DO:
8085         case EXEC_OMP_PARALLEL_SECTIONS:
8086         case EXEC_OMP_PARALLEL_WORKSHARE:
8087         case EXEC_OMP_TASK:
8088           omp_workshare_save = omp_workshare_flag;
8089           omp_workshare_flag = 0;
8090           gfc_resolve_omp_directive (code, ns);
8091           omp_workshare_flag = omp_workshare_save;
8092           break;
8093
8094         default:
8095           gfc_internal_error ("resolve_code(): Bad statement code");
8096         }
8097     }
8098
8099   cs_base = frame.prev;
8100 }
8101
8102
8103 /* Resolve initial values and make sure they are compatible with
8104    the variable.  */
8105
8106 static void
8107 resolve_values (gfc_symbol *sym)
8108 {
8109   if (sym->value == NULL)
8110     return;
8111
8112   if (gfc_resolve_expr (sym->value) == FAILURE)
8113     return;
8114
8115   gfc_check_assign_symbol (sym, sym->value);
8116 }
8117
8118
8119 /* Verify the binding labels for common blocks that are BIND(C).  The label
8120    for a BIND(C) common block must be identical in all scoping units in which
8121    the common block is declared.  Further, the binding label can not collide
8122    with any other global entity in the program.  */
8123
8124 static void
8125 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
8126 {
8127   if (comm_block_tree->n.common->is_bind_c == 1)
8128     {
8129       gfc_gsymbol *binding_label_gsym;
8130       gfc_gsymbol *comm_name_gsym;
8131
8132       /* See if a global symbol exists by the common block's name.  It may
8133          be NULL if the common block is use-associated.  */
8134       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
8135                                          comm_block_tree->n.common->name);
8136       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
8137         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
8138                    "with the global entity '%s' at %L",
8139                    comm_block_tree->n.common->binding_label,
8140                    comm_block_tree->n.common->name,
8141                    &(comm_block_tree->n.common->where),
8142                    comm_name_gsym->name, &(comm_name_gsym->where));
8143       else if (comm_name_gsym != NULL
8144                && strcmp (comm_name_gsym->name,
8145                           comm_block_tree->n.common->name) == 0)
8146         {
8147           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
8148              as expected.  */
8149           if (comm_name_gsym->binding_label == NULL)
8150             /* No binding label for common block stored yet; save this one.  */
8151             comm_name_gsym->binding_label =
8152               comm_block_tree->n.common->binding_label;
8153           else
8154             if (strcmp (comm_name_gsym->binding_label,
8155                         comm_block_tree->n.common->binding_label) != 0)
8156               {
8157                 /* Common block names match but binding labels do not.  */
8158                 gfc_error ("Binding label '%s' for common block '%s' at %L "
8159                            "does not match the binding label '%s' for common "
8160                            "block '%s' at %L",
8161                            comm_block_tree->n.common->binding_label,
8162                            comm_block_tree->n.common->name,
8163                            &(comm_block_tree->n.common->where),
8164                            comm_name_gsym->binding_label,
8165                            comm_name_gsym->name,
8166                            &(comm_name_gsym->where));
8167                 return;
8168               }
8169         }
8170
8171       /* There is no binding label (NAME="") so we have nothing further to
8172          check and nothing to add as a global symbol for the label.  */
8173       if (comm_block_tree->n.common->binding_label[0] == '\0' )
8174         return;
8175       
8176       binding_label_gsym =
8177         gfc_find_gsymbol (gfc_gsym_root,
8178                           comm_block_tree->n.common->binding_label);
8179       if (binding_label_gsym == NULL)
8180         {
8181           /* Need to make a global symbol for the binding label to prevent
8182              it from colliding with another.  */
8183           binding_label_gsym =
8184             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
8185           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
8186           binding_label_gsym->type = GSYM_COMMON;
8187         }
8188       else
8189         {
8190           /* If comm_name_gsym is NULL, the name common block is use
8191              associated and the name could be colliding.  */
8192           if (binding_label_gsym->type != GSYM_COMMON)
8193             gfc_error ("Binding label '%s' for common block '%s' at %L "
8194                        "collides with the global entity '%s' at %L",
8195                        comm_block_tree->n.common->binding_label,
8196                        comm_block_tree->n.common->name,
8197                        &(comm_block_tree->n.common->where),
8198                        binding_label_gsym->name,
8199                        &(binding_label_gsym->where));
8200           else if (comm_name_gsym != NULL
8201                    && (strcmp (binding_label_gsym->name,
8202                                comm_name_gsym->binding_label) != 0)
8203                    && (strcmp (binding_label_gsym->sym_name,
8204                                comm_name_gsym->name) != 0))
8205             gfc_error ("Binding label '%s' for common block '%s' at %L "
8206                        "collides with global entity '%s' at %L",
8207                        binding_label_gsym->name, binding_label_gsym->sym_name,
8208                        &(comm_block_tree->n.common->where),
8209                        comm_name_gsym->name, &(comm_name_gsym->where));
8210         }
8211     }
8212   
8213   return;
8214 }
8215
8216
8217 /* Verify any BIND(C) derived types in the namespace so we can report errors
8218    for them once, rather than for each variable declared of that type.  */
8219
8220 static void
8221 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
8222 {
8223   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
8224       && derived_sym->attr.is_bind_c == 1)
8225     verify_bind_c_derived_type (derived_sym);
8226   
8227   return;
8228 }
8229
8230
8231 /* Verify that any binding labels used in a given namespace do not collide 
8232    with the names or binding labels of any global symbols.  */
8233
8234 static void
8235 gfc_verify_binding_labels (gfc_symbol *sym)
8236 {
8237   int has_error = 0;
8238   
8239   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
8240       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
8241     {
8242       gfc_gsymbol *bind_c_sym;
8243
8244       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
8245       if (bind_c_sym != NULL 
8246           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
8247         {
8248           if (sym->attr.if_source == IFSRC_DECL 
8249               && (bind_c_sym->type != GSYM_SUBROUTINE 
8250                   && bind_c_sym->type != GSYM_FUNCTION) 
8251               && ((sym->attr.contained == 1 
8252                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
8253                   || (sym->attr.use_assoc == 1 
8254                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
8255             {
8256               /* Make sure global procedures don't collide with anything.  */
8257               gfc_error ("Binding label '%s' at %L collides with the global "
8258                          "entity '%s' at %L", sym->binding_label,
8259                          &(sym->declared_at), bind_c_sym->name,
8260                          &(bind_c_sym->where));
8261               has_error = 1;
8262             }
8263           else if (sym->attr.contained == 0 
8264                    && (sym->attr.if_source == IFSRC_IFBODY 
8265                        && sym->attr.flavor == FL_PROCEDURE) 
8266                    && (bind_c_sym->sym_name != NULL 
8267                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
8268             {
8269               /* Make sure procedures in interface bodies don't collide.  */
8270               gfc_error ("Binding label '%s' in interface body at %L collides "
8271                          "with the global entity '%s' at %L",
8272                          sym->binding_label,
8273                          &(sym->declared_at), bind_c_sym->name,
8274                          &(bind_c_sym->where));
8275               has_error = 1;
8276             }
8277           else if (sym->attr.contained == 0 
8278                    && sym->attr.if_source == IFSRC_UNKNOWN)
8279             if ((sym->attr.use_assoc && bind_c_sym->mod_name
8280                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
8281                 || sym->attr.use_assoc == 0)
8282               {
8283                 gfc_error ("Binding label '%s' at %L collides with global "
8284                            "entity '%s' at %L", sym->binding_label,
8285                            &(sym->declared_at), bind_c_sym->name,
8286                            &(bind_c_sym->where));
8287                 has_error = 1;
8288               }
8289
8290           if (has_error != 0)
8291             /* Clear the binding label to prevent checking multiple times.  */
8292             sym->binding_label[0] = '\0';
8293         }
8294       else if (bind_c_sym == NULL)
8295         {
8296           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
8297           bind_c_sym->where = sym->declared_at;
8298           bind_c_sym->sym_name = sym->name;
8299
8300           if (sym->attr.use_assoc == 1)
8301             bind_c_sym->mod_name = sym->module;
8302           else
8303             if (sym->ns->proc_name != NULL)
8304               bind_c_sym->mod_name = sym->ns->proc_name->name;
8305
8306           if (sym->attr.contained == 0)
8307             {
8308               if (sym->attr.subroutine)
8309                 bind_c_sym->type = GSYM_SUBROUTINE;
8310               else if (sym->attr.function)
8311                 bind_c_sym->type = GSYM_FUNCTION;
8312             }
8313         }
8314     }
8315   return;
8316 }
8317
8318
8319 /* Resolve an index expression.  */
8320
8321 static gfc_try
8322 resolve_index_expr (gfc_expr *e)
8323 {
8324   if (gfc_resolve_expr (e) == FAILURE)
8325     return FAILURE;
8326
8327   if (gfc_simplify_expr (e, 0) == FAILURE)
8328     return FAILURE;
8329
8330   if (gfc_specification_expr (e) == FAILURE)
8331     return FAILURE;
8332
8333   return SUCCESS;
8334 }
8335
8336 /* Resolve a charlen structure.  */
8337
8338 static gfc_try
8339 resolve_charlen (gfc_charlen *cl)
8340 {
8341   int i, k;
8342
8343   if (cl->resolved)
8344     return SUCCESS;
8345
8346   cl->resolved = 1;
8347
8348   specification_expr = 1;
8349
8350   if (resolve_index_expr (cl->length) == FAILURE)
8351     {
8352       specification_expr = 0;
8353       return FAILURE;
8354     }
8355
8356   /* "If the character length parameter value evaluates to a negative
8357      value, the length of character entities declared is zero."  */
8358   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
8359     {
8360       gfc_warning_now ("CHARACTER variable has zero length at %L",
8361                        &cl->length->where);
8362       gfc_replace_expr (cl->length, gfc_int_expr (0));
8363     }
8364
8365   /* Check that the character length is not too large.  */
8366   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
8367   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
8368       && cl->length->ts.type == BT_INTEGER
8369       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
8370     {
8371       gfc_error ("String length at %L is too large", &cl->length->where);
8372       return FAILURE;
8373     }
8374
8375   return SUCCESS;
8376 }
8377
8378
8379 /* Test for non-constant shape arrays.  */
8380
8381 static bool
8382 is_non_constant_shape_array (gfc_symbol *sym)
8383 {
8384   gfc_expr *e;
8385   int i;
8386   bool not_constant;
8387
8388   not_constant = false;
8389   if (sym->as != NULL)
8390     {
8391       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
8392          has not been simplified; parameter array references.  Do the
8393          simplification now.  */
8394       for (i = 0; i < sym->as->rank; i++)
8395         {
8396           e = sym->as->lower[i];
8397           if (e && (resolve_index_expr (e) == FAILURE
8398                     || !gfc_is_constant_expr (e)))
8399             not_constant = true;
8400
8401           e = sym->as->upper[i];
8402           if (e && (resolve_index_expr (e) == FAILURE
8403                     || !gfc_is_constant_expr (e)))
8404             not_constant = true;
8405         }
8406     }
8407   return not_constant;
8408 }
8409
8410 /* Given a symbol and an initialization expression, add code to initialize
8411    the symbol to the function entry.  */
8412 static void
8413 build_init_assign (gfc_symbol *sym, gfc_expr *init)
8414 {
8415   gfc_expr *lval;
8416   gfc_code *init_st;
8417   gfc_namespace *ns = sym->ns;
8418
8419   /* Search for the function namespace if this is a contained
8420      function without an explicit result.  */
8421   if (sym->attr.function && sym == sym->result
8422       && sym->name != sym->ns->proc_name->name)
8423     {
8424       ns = ns->contained;
8425       for (;ns; ns = ns->sibling)
8426         if (strcmp (ns->proc_name->name, sym->name) == 0)
8427           break;
8428     }
8429
8430   if (ns == NULL)
8431     {
8432       gfc_free_expr (init);
8433       return;
8434     }
8435
8436   /* Build an l-value expression for the result.  */
8437   lval = gfc_lval_expr_from_sym (sym);
8438
8439   /* Add the code at scope entry.  */
8440   init_st = gfc_get_code ();
8441   init_st->next = ns->code;
8442   ns->code = init_st;
8443
8444   /* Assign the default initializer to the l-value.  */
8445   init_st->loc = sym->declared_at;
8446   init_st->op = EXEC_INIT_ASSIGN;
8447   init_st->expr1 = lval;
8448   init_st->expr2 = init;
8449 }
8450
8451 /* Assign the default initializer to a derived type variable or result.  */
8452
8453 static void
8454 apply_default_init (gfc_symbol *sym)
8455 {
8456   gfc_expr *init = NULL;
8457
8458   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
8459     return;
8460
8461   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
8462     init = gfc_default_initializer (&sym->ts);
8463
8464   if (init == NULL)
8465     return;
8466
8467   build_init_assign (sym, init);
8468 }
8469
8470 /* Build an initializer for a local integer, real, complex, logical, or
8471    character variable, based on the command line flags finit-local-zero,
8472    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
8473    null if the symbol should not have a default initialization.  */
8474 static gfc_expr *
8475 build_default_init_expr (gfc_symbol *sym)
8476 {
8477   int char_len;
8478   gfc_expr *init_expr;
8479   int i;
8480
8481   /* These symbols should never have a default initialization.  */
8482   if ((sym->attr.dimension && !gfc_is_compile_time_shape (sym->as))
8483       || sym->attr.external
8484       || sym->attr.dummy
8485       || sym->attr.pointer
8486       || sym->attr.in_equivalence
8487       || sym->attr.in_common
8488       || sym->attr.data
8489       || sym->module
8490       || sym->attr.cray_pointee
8491       || sym->attr.cray_pointer)
8492     return NULL;
8493
8494   /* Now we'll try to build an initializer expression.  */
8495   init_expr = gfc_get_expr ();
8496   init_expr->expr_type = EXPR_CONSTANT;
8497   init_expr->ts.type = sym->ts.type;
8498   init_expr->ts.kind = sym->ts.kind;
8499   init_expr->where = sym->declared_at;
8500   
8501   /* We will only initialize integers, reals, complex, logicals, and
8502      characters, and only if the corresponding command-line flags
8503      were set.  Otherwise, we free init_expr and return null.  */
8504   switch (sym->ts.type)
8505     {    
8506     case BT_INTEGER:
8507       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
8508         mpz_init_set_si (init_expr->value.integer, 
8509                          gfc_option.flag_init_integer_value);
8510       else
8511         {
8512           gfc_free_expr (init_expr);
8513           init_expr = NULL;
8514         }
8515       break;
8516
8517     case BT_REAL:
8518       mpfr_init (init_expr->value.real);
8519       switch (gfc_option.flag_init_real)
8520         {
8521         case GFC_INIT_REAL_SNAN:
8522           init_expr->is_snan = 1;
8523           /* Fall through.  */
8524         case GFC_INIT_REAL_NAN:
8525           mpfr_set_nan (init_expr->value.real);
8526           break;
8527
8528         case GFC_INIT_REAL_INF:
8529           mpfr_set_inf (init_expr->value.real, 1);
8530           break;
8531
8532         case GFC_INIT_REAL_NEG_INF:
8533           mpfr_set_inf (init_expr->value.real, -1);
8534           break;
8535
8536         case GFC_INIT_REAL_ZERO:
8537           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
8538           break;
8539
8540         default:
8541           gfc_free_expr (init_expr);
8542           init_expr = NULL;
8543           break;
8544         }
8545       break;
8546           
8547     case BT_COMPLEX:
8548 #ifdef HAVE_mpc
8549       mpc_init2 (init_expr->value.complex, mpfr_get_default_prec());
8550 #else
8551       mpfr_init (init_expr->value.complex.r);
8552       mpfr_init (init_expr->value.complex.i);
8553 #endif
8554       switch (gfc_option.flag_init_real)
8555         {
8556         case GFC_INIT_REAL_SNAN:
8557           init_expr->is_snan = 1;
8558           /* Fall through.  */
8559         case GFC_INIT_REAL_NAN:
8560           mpfr_set_nan (mpc_realref (init_expr->value.complex));
8561           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
8562           break;
8563
8564         case GFC_INIT_REAL_INF:
8565           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
8566           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
8567           break;
8568
8569         case GFC_INIT_REAL_NEG_INF:
8570           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
8571           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
8572           break;
8573
8574         case GFC_INIT_REAL_ZERO:
8575 #ifdef HAVE_mpc
8576           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
8577 #else
8578           mpfr_set_ui (init_expr->value.complex.r, 0.0, GFC_RND_MODE);
8579           mpfr_set_ui (init_expr->value.complex.i, 0.0, GFC_RND_MODE);
8580 #endif
8581           break;
8582
8583         default:
8584           gfc_free_expr (init_expr);
8585           init_expr = NULL;
8586           break;
8587         }
8588       break;
8589           
8590     case BT_LOGICAL:
8591       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
8592         init_expr->value.logical = 0;
8593       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
8594         init_expr->value.logical = 1;
8595       else
8596         {
8597           gfc_free_expr (init_expr);
8598           init_expr = NULL;
8599         }
8600       break;
8601           
8602     case BT_CHARACTER:
8603       /* For characters, the length must be constant in order to 
8604          create a default initializer.  */
8605       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
8606           && sym->ts.u.cl->length
8607           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8608         {
8609           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
8610           init_expr->value.character.length = char_len;
8611           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
8612           for (i = 0; i < char_len; i++)
8613             init_expr->value.character.string[i]
8614               = (unsigned char) gfc_option.flag_init_character_value;
8615         }
8616       else
8617         {
8618           gfc_free_expr (init_expr);
8619           init_expr = NULL;
8620         }
8621       break;
8622           
8623     default:
8624      gfc_free_expr (init_expr);
8625      init_expr = NULL;
8626     }
8627   return init_expr;
8628 }
8629
8630 /* Add an initialization expression to a local variable.  */
8631 static void
8632 apply_default_init_local (gfc_symbol *sym)
8633 {
8634   gfc_expr *init = NULL;
8635
8636   /* The symbol should be a variable or a function return value.  */
8637   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
8638       || (sym->attr.function && sym->result != sym))
8639     return;
8640
8641   /* Try to build the initializer expression.  If we can't initialize
8642      this symbol, then init will be NULL.  */
8643   init = build_default_init_expr (sym);
8644   if (init == NULL)
8645     return;
8646
8647   /* For saved variables, we don't want to add an initializer at 
8648      function entry, so we just add a static initializer.  */
8649   if (sym->attr.save || sym->ns->save_all 
8650       || gfc_option.flag_max_stack_var_size == 0)
8651     {
8652       /* Don't clobber an existing initializer!  */
8653       gcc_assert (sym->value == NULL);
8654       sym->value = init;
8655       return;
8656     }
8657
8658   build_init_assign (sym, init);
8659 }
8660
8661 /* Resolution of common features of flavors variable and procedure.  */
8662
8663 static gfc_try
8664 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
8665 {
8666   /* Constraints on deferred shape variable.  */
8667   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
8668     {
8669       if (sym->attr.allocatable)
8670         {
8671           if (sym->attr.dimension)
8672             {
8673               gfc_error ("Allocatable array '%s' at %L must have "
8674                          "a deferred shape", sym->name, &sym->declared_at);
8675               return FAILURE;
8676             }
8677           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
8678                                    "may not be ALLOCATABLE", sym->name,
8679                                    &sym->declared_at) == FAILURE)
8680             return FAILURE;
8681         }
8682
8683       if (sym->attr.pointer && sym->attr.dimension)
8684         {
8685           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
8686                      sym->name, &sym->declared_at);
8687           return FAILURE;
8688         }
8689
8690     }
8691   else
8692     {
8693       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
8694           && !sym->attr.dummy && sym->ts.type != BT_CLASS)
8695         {
8696           gfc_error ("Array '%s' at %L cannot have a deferred shape",
8697                      sym->name, &sym->declared_at);
8698           return FAILURE;
8699          }
8700     }
8701   return SUCCESS;
8702 }
8703
8704
8705 /* Additional checks for symbols with flavor variable and derived
8706    type.  To be called from resolve_fl_variable.  */
8707
8708 static gfc_try
8709 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
8710 {
8711   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
8712
8713   /* Check to see if a derived type is blocked from being host
8714      associated by the presence of another class I symbol in the same
8715      namespace.  14.6.1.3 of the standard and the discussion on
8716      comp.lang.fortran.  */
8717   if (sym->ns != sym->ts.u.derived->ns
8718       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
8719     {
8720       gfc_symbol *s;
8721       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
8722       if (s && s->attr.flavor != FL_DERIVED)
8723         {
8724           gfc_error ("The type '%s' cannot be host associated at %L "
8725                      "because it is blocked by an incompatible object "
8726                      "of the same name declared at %L",
8727                      sym->ts.u.derived->name, &sym->declared_at,
8728                      &s->declared_at);
8729           return FAILURE;
8730         }
8731     }
8732
8733   /* 4th constraint in section 11.3: "If an object of a type for which
8734      component-initialization is specified (R429) appears in the
8735      specification-part of a module and does not have the ALLOCATABLE
8736      or POINTER attribute, the object shall have the SAVE attribute."
8737
8738      The check for initializers is performed with
8739      has_default_initializer because gfc_default_initializer generates
8740      a hidden default for allocatable components.  */
8741   if (!(sym->value || no_init_flag) && sym->ns->proc_name
8742       && sym->ns->proc_name->attr.flavor == FL_MODULE
8743       && !sym->ns->save_all && !sym->attr.save
8744       && !sym->attr.pointer && !sym->attr.allocatable
8745       && has_default_initializer (sym->ts.u.derived))
8746     {
8747       gfc_error("Object '%s' at %L must have the SAVE attribute for "
8748                 "default initialization of a component",
8749                 sym->name, &sym->declared_at);
8750       return FAILURE;
8751     }
8752
8753   if (sym->ts.type == BT_CLASS)
8754     {
8755       /* C502.  */
8756       if (!gfc_type_is_extensible (sym->ts.u.derived->components->ts.u.derived))
8757         {
8758           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
8759                      sym->ts.u.derived->name, sym->name, &sym->declared_at);
8760           return FAILURE;
8761         }
8762
8763       /* C509.  */
8764       /* Assume that use associated symbols were checked in the module ns.  */ 
8765       if (!sym->attr.class_ok && !sym->attr.use_assoc)
8766         {
8767           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
8768                      "or pointer", sym->name, &sym->declared_at);
8769           return FAILURE;
8770         }
8771     }
8772
8773   /* Assign default initializer.  */
8774   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
8775       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
8776     {
8777       sym->value = gfc_default_initializer (&sym->ts);
8778     }
8779
8780   return SUCCESS;
8781 }
8782
8783
8784 /* Resolve symbols with flavor variable.  */
8785
8786 static gfc_try
8787 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
8788 {
8789   int no_init_flag, automatic_flag;
8790   gfc_expr *e;
8791   const char *auto_save_msg;
8792
8793   auto_save_msg = "Automatic object '%s' at %L cannot have the "
8794                   "SAVE attribute";
8795
8796   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
8797     return FAILURE;
8798
8799   /* Set this flag to check that variables are parameters of all entries.
8800      This check is effected by the call to gfc_resolve_expr through
8801      is_non_constant_shape_array.  */
8802   specification_expr = 1;
8803
8804   if (sym->ns->proc_name
8805       && (sym->ns->proc_name->attr.flavor == FL_MODULE
8806           || sym->ns->proc_name->attr.is_main_program)
8807       && !sym->attr.use_assoc
8808       && !sym->attr.allocatable
8809       && !sym->attr.pointer
8810       && is_non_constant_shape_array (sym))
8811     {
8812       /* The shape of a main program or module array needs to be
8813          constant.  */
8814       gfc_error ("The module or main program array '%s' at %L must "
8815                  "have constant shape", sym->name, &sym->declared_at);
8816       specification_expr = 0;
8817       return FAILURE;
8818     }
8819
8820   if (sym->ts.type == BT_CHARACTER)
8821     {
8822       /* Make sure that character string variables with assumed length are
8823          dummy arguments.  */
8824       e = sym->ts.u.cl->length;
8825       if (e == NULL && !sym->attr.dummy && !sym->attr.result)
8826         {
8827           gfc_error ("Entity with assumed character length at %L must be a "
8828                      "dummy argument or a PARAMETER", &sym->declared_at);
8829           return FAILURE;
8830         }
8831
8832       if (e && sym->attr.save && !gfc_is_constant_expr (e))
8833         {
8834           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
8835           return FAILURE;
8836         }
8837
8838       if (!gfc_is_constant_expr (e)
8839           && !(e->expr_type == EXPR_VARIABLE
8840                && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
8841           && sym->ns->proc_name
8842           && (sym->ns->proc_name->attr.flavor == FL_MODULE
8843               || sym->ns->proc_name->attr.is_main_program)
8844           && !sym->attr.use_assoc)
8845         {
8846           gfc_error ("'%s' at %L must have constant character length "
8847                      "in this context", sym->name, &sym->declared_at);
8848           return FAILURE;
8849         }
8850     }
8851
8852   if (sym->value == NULL && sym->attr.referenced)
8853     apply_default_init_local (sym); /* Try to apply a default initialization.  */
8854
8855   /* Determine if the symbol may not have an initializer.  */
8856   no_init_flag = automatic_flag = 0;
8857   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
8858       || sym->attr.intrinsic || sym->attr.result)
8859     no_init_flag = 1;
8860   else if (sym->attr.dimension && !sym->attr.pointer
8861            && is_non_constant_shape_array (sym))
8862     {
8863       no_init_flag = automatic_flag = 1;
8864
8865       /* Also, they must not have the SAVE attribute.
8866          SAVE_IMPLICIT is checked below.  */
8867       if (sym->attr.save == SAVE_EXPLICIT)
8868         {
8869           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
8870           return FAILURE;
8871         }
8872     }
8873
8874   /* Ensure that any initializer is simplified.  */
8875   if (sym->value)
8876     gfc_simplify_expr (sym->value, 1);
8877
8878   /* Reject illegal initializers.  */
8879   if (!sym->mark && sym->value)
8880     {
8881       if (sym->attr.allocatable)
8882         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
8883                    sym->name, &sym->declared_at);
8884       else if (sym->attr.external)
8885         gfc_error ("External '%s' at %L cannot have an initializer",
8886                    sym->name, &sym->declared_at);
8887       else if (sym->attr.dummy
8888         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
8889         gfc_error ("Dummy '%s' at %L cannot have an initializer",
8890                    sym->name, &sym->declared_at);
8891       else if (sym->attr.intrinsic)
8892         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
8893                    sym->name, &sym->declared_at);
8894       else if (sym->attr.result)
8895         gfc_error ("Function result '%s' at %L cannot have an initializer",
8896                    sym->name, &sym->declared_at);
8897       else if (automatic_flag)
8898         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
8899                    sym->name, &sym->declared_at);
8900       else
8901         goto no_init_error;
8902       return FAILURE;
8903     }
8904
8905 no_init_error:
8906   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
8907     return resolve_fl_variable_derived (sym, no_init_flag);
8908
8909   return SUCCESS;
8910 }
8911
8912
8913 /* Resolve a procedure.  */
8914
8915 static gfc_try
8916 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
8917 {
8918   gfc_formal_arglist *arg;
8919
8920   if (sym->attr.ambiguous_interfaces && !sym->attr.referenced)
8921     gfc_warning ("Although not referenced, '%s' at %L has ambiguous "
8922                  "interfaces", sym->name, &sym->declared_at);
8923
8924   if (sym->attr.function
8925       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
8926     return FAILURE;
8927
8928   if (sym->ts.type == BT_CHARACTER)
8929     {
8930       gfc_charlen *cl = sym->ts.u.cl;
8931
8932       if (cl && cl->length && gfc_is_constant_expr (cl->length)
8933              && resolve_charlen (cl) == FAILURE)
8934         return FAILURE;
8935
8936       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
8937         {
8938           if (sym->attr.proc == PROC_ST_FUNCTION)
8939             {
8940               gfc_error ("Character-valued statement function '%s' at %L must "
8941                          "have constant length", sym->name, &sym->declared_at);
8942               return FAILURE;
8943             }
8944
8945           if (sym->attr.external && sym->formal == NULL
8946               && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
8947             {
8948               gfc_error ("Automatic character length function '%s' at %L must "
8949                          "have an explicit interface", sym->name,
8950                          &sym->declared_at);
8951               return FAILURE;
8952             }
8953         }
8954     }
8955
8956   /* Ensure that derived type for are not of a private type.  Internal
8957      module procedures are excluded by 2.2.3.3 - i.e., they are not
8958      externally accessible and can access all the objects accessible in
8959      the host.  */
8960   if (!(sym->ns->parent
8961         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
8962       && gfc_check_access(sym->attr.access, sym->ns->default_access))
8963     {
8964       gfc_interface *iface;
8965
8966       for (arg = sym->formal; arg; arg = arg->next)
8967         {
8968           if (arg->sym
8969               && arg->sym->ts.type == BT_DERIVED
8970               && !arg->sym->ts.u.derived->attr.use_assoc
8971               && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
8972                                     arg->sym->ts.u.derived->ns->default_access)
8973               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
8974                                  "PRIVATE type and cannot be a dummy argument"
8975                                  " of '%s', which is PUBLIC at %L",
8976                                  arg->sym->name, sym->name, &sym->declared_at)
8977                  == FAILURE)
8978             {
8979               /* Stop this message from recurring.  */
8980               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
8981               return FAILURE;
8982             }
8983         }
8984
8985       /* PUBLIC interfaces may expose PRIVATE procedures that take types
8986          PRIVATE to the containing module.  */
8987       for (iface = sym->generic; iface; iface = iface->next)
8988         {
8989           for (arg = iface->sym->formal; arg; arg = arg->next)
8990             {
8991               if (arg->sym
8992                   && arg->sym->ts.type == BT_DERIVED
8993                   && !arg->sym->ts.u.derived->attr.use_assoc
8994                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
8995                                         arg->sym->ts.u.derived->ns->default_access)
8996                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
8997                                      "'%s' in PUBLIC interface '%s' at %L "
8998                                      "takes dummy arguments of '%s' which is "
8999                                      "PRIVATE", iface->sym->name, sym->name,
9000                                      &iface->sym->declared_at,
9001                                      gfc_typename (&arg->sym->ts)) == FAILURE)
9002                 {
9003                   /* Stop this message from recurring.  */
9004                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9005                   return FAILURE;
9006                 }
9007              }
9008         }
9009
9010       /* PUBLIC interfaces may expose PRIVATE procedures that take types
9011          PRIVATE to the containing module.  */
9012       for (iface = sym->generic; iface; iface = iface->next)
9013         {
9014           for (arg = iface->sym->formal; arg; arg = arg->next)
9015             {
9016               if (arg->sym
9017                   && arg->sym->ts.type == BT_DERIVED
9018                   && !arg->sym->ts.u.derived->attr.use_assoc
9019                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9020                                         arg->sym->ts.u.derived->ns->default_access)
9021                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
9022                                      "'%s' in PUBLIC interface '%s' at %L "
9023                                      "takes dummy arguments of '%s' which is "
9024                                      "PRIVATE", iface->sym->name, sym->name,
9025                                      &iface->sym->declared_at,
9026                                      gfc_typename (&arg->sym->ts)) == FAILURE)
9027                 {
9028                   /* Stop this message from recurring.  */
9029                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9030                   return FAILURE;
9031                 }
9032              }
9033         }
9034     }
9035
9036   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
9037       && !sym->attr.proc_pointer)
9038     {
9039       gfc_error ("Function '%s' at %L cannot have an initializer",
9040                  sym->name, &sym->declared_at);
9041       return FAILURE;
9042     }
9043
9044   /* An external symbol may not have an initializer because it is taken to be
9045      a procedure. Exception: Procedure Pointers.  */
9046   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
9047     {
9048       gfc_error ("External object '%s' at %L may not have an initializer",
9049                  sym->name, &sym->declared_at);
9050       return FAILURE;
9051     }
9052
9053   /* An elemental function is required to return a scalar 12.7.1  */
9054   if (sym->attr.elemental && sym->attr.function && sym->as)
9055     {
9056       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
9057                  "result", sym->name, &sym->declared_at);
9058       /* Reset so that the error only occurs once.  */
9059       sym->attr.elemental = 0;
9060       return FAILURE;
9061     }
9062
9063   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
9064      char-len-param shall not be array-valued, pointer-valued, recursive
9065      or pure.  ....snip... A character value of * may only be used in the
9066      following ways: (i) Dummy arg of procedure - dummy associates with
9067      actual length; (ii) To declare a named constant; or (iii) External
9068      function - but length must be declared in calling scoping unit.  */
9069   if (sym->attr.function
9070       && sym->ts.type == BT_CHARACTER
9071       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
9072     {
9073       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
9074           || (sym->attr.recursive) || (sym->attr.pure))
9075         {
9076           if (sym->as && sym->as->rank)
9077             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9078                        "array-valued", sym->name, &sym->declared_at);
9079
9080           if (sym->attr.pointer)
9081             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9082                        "pointer-valued", sym->name, &sym->declared_at);
9083
9084           if (sym->attr.pure)
9085             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9086                        "pure", sym->name, &sym->declared_at);
9087
9088           if (sym->attr.recursive)
9089             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9090                        "recursive", sym->name, &sym->declared_at);
9091
9092           return FAILURE;
9093         }
9094
9095       /* Appendix B.2 of the standard.  Contained functions give an
9096          error anyway.  Fixed-form is likely to be F77/legacy.  */
9097       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
9098         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
9099                         "CHARACTER(*) function '%s' at %L",
9100                         sym->name, &sym->declared_at);
9101     }
9102
9103   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
9104     {
9105       gfc_formal_arglist *curr_arg;
9106       int has_non_interop_arg = 0;
9107
9108       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
9109                              sym->common_block) == FAILURE)
9110         {
9111           /* Clear these to prevent looking at them again if there was an
9112              error.  */
9113           sym->attr.is_bind_c = 0;
9114           sym->attr.is_c_interop = 0;
9115           sym->ts.is_c_interop = 0;
9116         }
9117       else
9118         {
9119           /* So far, no errors have been found.  */
9120           sym->attr.is_c_interop = 1;
9121           sym->ts.is_c_interop = 1;
9122         }
9123       
9124       curr_arg = sym->formal;
9125       while (curr_arg != NULL)
9126         {
9127           /* Skip implicitly typed dummy args here.  */
9128           if (curr_arg->sym->attr.implicit_type == 0)
9129             if (verify_c_interop_param (curr_arg->sym) == FAILURE)
9130               /* If something is found to fail, record the fact so we
9131                  can mark the symbol for the procedure as not being
9132                  BIND(C) to try and prevent multiple errors being
9133                  reported.  */
9134               has_non_interop_arg = 1;
9135           
9136           curr_arg = curr_arg->next;
9137         }
9138
9139       /* See if any of the arguments were not interoperable and if so, clear
9140          the procedure symbol to prevent duplicate error messages.  */
9141       if (has_non_interop_arg != 0)
9142         {
9143           sym->attr.is_c_interop = 0;
9144           sym->ts.is_c_interop = 0;
9145           sym->attr.is_bind_c = 0;
9146         }
9147     }
9148   
9149   if (!sym->attr.proc_pointer)
9150     {
9151       if (sym->attr.save == SAVE_EXPLICIT)
9152         {
9153           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
9154                      "in '%s' at %L", sym->name, &sym->declared_at);
9155           return FAILURE;
9156         }
9157       if (sym->attr.intent)
9158         {
9159           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
9160                      "in '%s' at %L", sym->name, &sym->declared_at);
9161           return FAILURE;
9162         }
9163       if (sym->attr.subroutine && sym->attr.result)
9164         {
9165           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
9166                      "in '%s' at %L", sym->name, &sym->declared_at);
9167           return FAILURE;
9168         }
9169       if (sym->attr.external && sym->attr.function
9170           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
9171               || sym->attr.contained))
9172         {
9173           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
9174                      "in '%s' at %L", sym->name, &sym->declared_at);
9175           return FAILURE;
9176         }
9177       if (strcmp ("ppr@", sym->name) == 0)
9178         {
9179           gfc_error ("Procedure pointer result '%s' at %L "
9180                      "is missing the pointer attribute",
9181                      sym->ns->proc_name->name, &sym->declared_at);
9182           return FAILURE;
9183         }
9184     }
9185
9186   return SUCCESS;
9187 }
9188
9189
9190 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
9191    been defined and we now know their defined arguments, check that they fulfill
9192    the requirements of the standard for procedures used as finalizers.  */
9193
9194 static gfc_try
9195 gfc_resolve_finalizers (gfc_symbol* derived)
9196 {
9197   gfc_finalizer* list;
9198   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
9199   gfc_try result = SUCCESS;
9200   bool seen_scalar = false;
9201
9202   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
9203     return SUCCESS;
9204
9205   /* Walk over the list of finalizer-procedures, check them, and if any one
9206      does not fit in with the standard's definition, print an error and remove
9207      it from the list.  */
9208   prev_link = &derived->f2k_derived->finalizers;
9209   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
9210     {
9211       gfc_symbol* arg;
9212       gfc_finalizer* i;
9213       int my_rank;
9214
9215       /* Skip this finalizer if we already resolved it.  */
9216       if (list->proc_tree)
9217         {
9218           prev_link = &(list->next);
9219           continue;
9220         }
9221
9222       /* Check this exists and is a SUBROUTINE.  */
9223       if (!list->proc_sym->attr.subroutine)
9224         {
9225           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
9226                      list->proc_sym->name, &list->where);
9227           goto error;
9228         }
9229
9230       /* We should have exactly one argument.  */
9231       if (!list->proc_sym->formal || list->proc_sym->formal->next)
9232         {
9233           gfc_error ("FINAL procedure at %L must have exactly one argument",
9234                      &list->where);
9235           goto error;
9236         }
9237       arg = list->proc_sym->formal->sym;
9238
9239       /* This argument must be of our type.  */
9240       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
9241         {
9242           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
9243                      &arg->declared_at, derived->name);
9244           goto error;
9245         }
9246
9247       /* It must neither be a pointer nor allocatable nor optional.  */
9248       if (arg->attr.pointer)
9249         {
9250           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
9251                      &arg->declared_at);
9252           goto error;
9253         }
9254       if (arg->attr.allocatable)
9255         {
9256           gfc_error ("Argument of FINAL procedure at %L must not be"
9257                      " ALLOCATABLE", &arg->declared_at);
9258           goto error;
9259         }
9260       if (arg->attr.optional)
9261         {
9262           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
9263                      &arg->declared_at);
9264           goto error;
9265         }
9266
9267       /* It must not be INTENT(OUT).  */
9268       if (arg->attr.intent == INTENT_OUT)
9269         {
9270           gfc_error ("Argument of FINAL procedure at %L must not be"
9271                      " INTENT(OUT)", &arg->declared_at);
9272           goto error;
9273         }
9274
9275       /* Warn if the procedure is non-scalar and not assumed shape.  */
9276       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
9277           && arg->as->type != AS_ASSUMED_SHAPE)
9278         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
9279                      " shape argument", &arg->declared_at);
9280
9281       /* Check that it does not match in kind and rank with a FINAL procedure
9282          defined earlier.  To really loop over the *earlier* declarations,
9283          we need to walk the tail of the list as new ones were pushed at the
9284          front.  */
9285       /* TODO: Handle kind parameters once they are implemented.  */
9286       my_rank = (arg->as ? arg->as->rank : 0);
9287       for (i = list->next; i; i = i->next)
9288         {
9289           /* Argument list might be empty; that is an error signalled earlier,
9290              but we nevertheless continued resolving.  */
9291           if (i->proc_sym->formal)
9292             {
9293               gfc_symbol* i_arg = i->proc_sym->formal->sym;
9294               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
9295               if (i_rank == my_rank)
9296                 {
9297                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
9298                              " rank (%d) as '%s'",
9299                              list->proc_sym->name, &list->where, my_rank, 
9300                              i->proc_sym->name);
9301                   goto error;
9302                 }
9303             }
9304         }
9305
9306         /* Is this the/a scalar finalizer procedure?  */
9307         if (!arg->as || arg->as->rank == 0)
9308           seen_scalar = true;
9309
9310         /* Find the symtree for this procedure.  */
9311         gcc_assert (!list->proc_tree);
9312         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
9313
9314         prev_link = &list->next;
9315         continue;
9316
9317         /* Remove wrong nodes immediately from the list so we don't risk any
9318            troubles in the future when they might fail later expectations.  */
9319 error:
9320         result = FAILURE;
9321         i = list;
9322         *prev_link = list->next;
9323         gfc_free_finalizer (i);
9324     }
9325
9326   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
9327      were nodes in the list, must have been for arrays.  It is surely a good
9328      idea to have a scalar version there if there's something to finalize.  */
9329   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
9330     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
9331                  " defined at %L, suggest also scalar one",
9332                  derived->name, &derived->declared_at);
9333
9334   /* TODO:  Remove this error when finalization is finished.  */
9335   gfc_error ("Finalization at %L is not yet implemented",
9336              &derived->declared_at);
9337
9338   return result;
9339 }
9340
9341
9342 /* Check that it is ok for the typebound procedure proc to override the
9343    procedure old.  */
9344
9345 static gfc_try
9346 check_typebound_override (gfc_symtree* proc, gfc_symtree* old)
9347 {
9348   locus where;
9349   const gfc_symbol* proc_target;
9350   const gfc_symbol* old_target;
9351   unsigned proc_pass_arg, old_pass_arg, argpos;
9352   gfc_formal_arglist* proc_formal;
9353   gfc_formal_arglist* old_formal;
9354
9355   /* This procedure should only be called for non-GENERIC proc.  */
9356   gcc_assert (!proc->n.tb->is_generic);
9357
9358   /* If the overwritten procedure is GENERIC, this is an error.  */
9359   if (old->n.tb->is_generic)
9360     {
9361       gfc_error ("Can't overwrite GENERIC '%s' at %L",
9362                  old->name, &proc->n.tb->where);
9363       return FAILURE;
9364     }
9365
9366   where = proc->n.tb->where;
9367   proc_target = proc->n.tb->u.specific->n.sym;
9368   old_target = old->n.tb->u.specific->n.sym;
9369
9370   /* Check that overridden binding is not NON_OVERRIDABLE.  */
9371   if (old->n.tb->non_overridable)
9372     {
9373       gfc_error ("'%s' at %L overrides a procedure binding declared"
9374                  " NON_OVERRIDABLE", proc->name, &where);
9375       return FAILURE;
9376     }
9377
9378   /* It's an error to override a non-DEFERRED procedure with a DEFERRED one.  */
9379   if (!old->n.tb->deferred && proc->n.tb->deferred)
9380     {
9381       gfc_error ("'%s' at %L must not be DEFERRED as it overrides a"
9382                  " non-DEFERRED binding", proc->name, &where);
9383       return FAILURE;
9384     }
9385
9386   /* If the overridden binding is PURE, the overriding must be, too.  */
9387   if (old_target->attr.pure && !proc_target->attr.pure)
9388     {
9389       gfc_error ("'%s' at %L overrides a PURE procedure and must also be PURE",
9390                  proc->name, &where);
9391       return FAILURE;
9392     }
9393
9394   /* If the overridden binding is ELEMENTAL, the overriding must be, too.  If it
9395      is not, the overriding must not be either.  */
9396   if (old_target->attr.elemental && !proc_target->attr.elemental)
9397     {
9398       gfc_error ("'%s' at %L overrides an ELEMENTAL procedure and must also be"
9399                  " ELEMENTAL", proc->name, &where);
9400       return FAILURE;
9401     }
9402   if (!old_target->attr.elemental && proc_target->attr.elemental)
9403     {
9404       gfc_error ("'%s' at %L overrides a non-ELEMENTAL procedure and must not"
9405                  " be ELEMENTAL, either", proc->name, &where);
9406       return FAILURE;
9407     }
9408
9409   /* If the overridden binding is a SUBROUTINE, the overriding must also be a
9410      SUBROUTINE.  */
9411   if (old_target->attr.subroutine && !proc_target->attr.subroutine)
9412     {
9413       gfc_error ("'%s' at %L overrides a SUBROUTINE and must also be a"
9414                  " SUBROUTINE", proc->name, &where);
9415       return FAILURE;
9416     }
9417
9418   /* If the overridden binding is a FUNCTION, the overriding must also be a
9419      FUNCTION and have the same characteristics.  */
9420   if (old_target->attr.function)
9421     {
9422       if (!proc_target->attr.function)
9423         {
9424           gfc_error ("'%s' at %L overrides a FUNCTION and must also be a"
9425                      " FUNCTION", proc->name, &where);
9426           return FAILURE;
9427         }
9428
9429       /* FIXME:  Do more comprehensive checking (including, for instance, the
9430          rank and array-shape).  */
9431       gcc_assert (proc_target->result && old_target->result);
9432       if (!gfc_compare_types (&proc_target->result->ts,
9433                               &old_target->result->ts))
9434         {
9435           gfc_error ("'%s' at %L and the overridden FUNCTION should have"
9436                      " matching result types", proc->name, &where);
9437           return FAILURE;
9438         }
9439     }
9440
9441   /* If the overridden binding is PUBLIC, the overriding one must not be
9442      PRIVATE.  */
9443   if (old->n.tb->access == ACCESS_PUBLIC
9444       && proc->n.tb->access == ACCESS_PRIVATE)
9445     {
9446       gfc_error ("'%s' at %L overrides a PUBLIC procedure and must not be"
9447                  " PRIVATE", proc->name, &where);
9448       return FAILURE;
9449     }
9450
9451   /* Compare the formal argument lists of both procedures.  This is also abused
9452      to find the position of the passed-object dummy arguments of both
9453      bindings as at least the overridden one might not yet be resolved and we
9454      need those positions in the check below.  */
9455   proc_pass_arg = old_pass_arg = 0;
9456   if (!proc->n.tb->nopass && !proc->n.tb->pass_arg)
9457     proc_pass_arg = 1;
9458   if (!old->n.tb->nopass && !old->n.tb->pass_arg)
9459     old_pass_arg = 1;
9460   argpos = 1;
9461   for (proc_formal = proc_target->formal, old_formal = old_target->formal;
9462        proc_formal && old_formal;
9463        proc_formal = proc_formal->next, old_formal = old_formal->next)
9464     {
9465       if (proc->n.tb->pass_arg
9466           && !strcmp (proc->n.tb->pass_arg, proc_formal->sym->name))
9467         proc_pass_arg = argpos;
9468       if (old->n.tb->pass_arg
9469           && !strcmp (old->n.tb->pass_arg, old_formal->sym->name))
9470         old_pass_arg = argpos;
9471
9472       /* Check that the names correspond.  */
9473       if (strcmp (proc_formal->sym->name, old_formal->sym->name))
9474         {
9475           gfc_error ("Dummy argument '%s' of '%s' at %L should be named '%s' as"
9476                      " to match the corresponding argument of the overridden"
9477                      " procedure", proc_formal->sym->name, proc->name, &where,
9478                      old_formal->sym->name);
9479           return FAILURE;
9480         }
9481
9482       /* Check that the types correspond if neither is the passed-object
9483          argument.  */
9484       /* FIXME:  Do more comprehensive testing here.  */
9485       if (proc_pass_arg != argpos && old_pass_arg != argpos
9486           && !gfc_compare_types (&proc_formal->sym->ts, &old_formal->sym->ts))
9487         {
9488           gfc_error ("Types mismatch for dummy argument '%s' of '%s' %L "
9489                      "in respect to the overridden procedure",
9490                      proc_formal->sym->name, proc->name, &where);
9491           return FAILURE;
9492         }
9493
9494       ++argpos;
9495     }
9496   if (proc_formal || old_formal)
9497     {
9498       gfc_error ("'%s' at %L must have the same number of formal arguments as"
9499                  " the overridden procedure", proc->name, &where);
9500       return FAILURE;
9501     }
9502
9503   /* If the overridden binding is NOPASS, the overriding one must also be
9504      NOPASS.  */
9505   if (old->n.tb->nopass && !proc->n.tb->nopass)
9506     {
9507       gfc_error ("'%s' at %L overrides a NOPASS binding and must also be"
9508                  " NOPASS", proc->name, &where);
9509       return FAILURE;
9510     }
9511
9512   /* If the overridden binding is PASS(x), the overriding one must also be
9513      PASS and the passed-object dummy arguments must correspond.  */
9514   if (!old->n.tb->nopass)
9515     {
9516       if (proc->n.tb->nopass)
9517         {
9518           gfc_error ("'%s' at %L overrides a binding with PASS and must also be"
9519                      " PASS", proc->name, &where);
9520           return FAILURE;
9521         }
9522
9523       if (proc_pass_arg != old_pass_arg)
9524         {
9525           gfc_error ("Passed-object dummy argument of '%s' at %L must be at"
9526                      " the same position as the passed-object dummy argument of"
9527                      " the overridden procedure", proc->name, &where);
9528           return FAILURE;
9529         }
9530     }
9531
9532   return SUCCESS;
9533 }
9534
9535
9536 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
9537
9538 static gfc_try
9539 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
9540                              const char* generic_name, locus where)
9541 {
9542   gfc_symbol* sym1;
9543   gfc_symbol* sym2;
9544
9545   gcc_assert (t1->specific && t2->specific);
9546   gcc_assert (!t1->specific->is_generic);
9547   gcc_assert (!t2->specific->is_generic);
9548
9549   sym1 = t1->specific->u.specific->n.sym;
9550   sym2 = t2->specific->u.specific->n.sym;
9551
9552   if (sym1 == sym2)
9553     return SUCCESS;
9554
9555   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
9556   if (sym1->attr.subroutine != sym2->attr.subroutine
9557       || sym1->attr.function != sym2->attr.function)
9558     {
9559       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
9560                  " GENERIC '%s' at %L",
9561                  sym1->name, sym2->name, generic_name, &where);
9562       return FAILURE;
9563     }
9564
9565   /* Compare the interfaces.  */
9566   if (gfc_compare_interfaces (sym1, sym2, NULL, 1, 0, NULL, 0))
9567     {
9568       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
9569                  sym1->name, sym2->name, generic_name, &where);
9570       return FAILURE;
9571     }
9572
9573   return SUCCESS;
9574 }
9575
9576
9577 /* Worker function for resolving a generic procedure binding; this is used to
9578    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
9579
9580    The difference between those cases is finding possible inherited bindings
9581    that are overridden, as one has to look for them in tb_sym_root,
9582    tb_uop_root or tb_op, respectively.  Thus the caller must already find
9583    the super-type and set p->overridden correctly.  */
9584
9585 static gfc_try
9586 resolve_tb_generic_targets (gfc_symbol* super_type,
9587                             gfc_typebound_proc* p, const char* name)
9588 {
9589   gfc_tbp_generic* target;
9590   gfc_symtree* first_target;
9591   gfc_symtree* inherited;
9592
9593   gcc_assert (p && p->is_generic);
9594
9595   /* Try to find the specific bindings for the symtrees in our target-list.  */
9596   gcc_assert (p->u.generic);
9597   for (target = p->u.generic; target; target = target->next)
9598     if (!target->specific)
9599       {
9600         gfc_typebound_proc* overridden_tbp;
9601         gfc_tbp_generic* g;
9602         const char* target_name;
9603
9604         target_name = target->specific_st->name;
9605
9606         /* Defined for this type directly.  */
9607         if (target->specific_st->n.tb)
9608           {
9609             target->specific = target->specific_st->n.tb;
9610             goto specific_found;
9611           }
9612
9613         /* Look for an inherited specific binding.  */
9614         if (super_type)
9615           {
9616             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
9617                                                  true, NULL);
9618
9619             if (inherited)
9620               {
9621                 gcc_assert (inherited->n.tb);
9622                 target->specific = inherited->n.tb;
9623                 goto specific_found;
9624               }
9625           }
9626
9627         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
9628                    " at %L", target_name, name, &p->where);
9629         return FAILURE;
9630
9631         /* Once we've found the specific binding, check it is not ambiguous with
9632            other specifics already found or inherited for the same GENERIC.  */
9633 specific_found:
9634         gcc_assert (target->specific);
9635
9636         /* This must really be a specific binding!  */
9637         if (target->specific->is_generic)
9638           {
9639             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
9640                        " '%s' is GENERIC, too", name, &p->where, target_name);
9641             return FAILURE;
9642           }
9643
9644         /* Check those already resolved on this type directly.  */
9645         for (g = p->u.generic; g; g = g->next)
9646           if (g != target && g->specific
9647               && check_generic_tbp_ambiguity (target, g, name, p->where)
9648                   == FAILURE)
9649             return FAILURE;
9650
9651         /* Check for ambiguity with inherited specific targets.  */
9652         for (overridden_tbp = p->overridden; overridden_tbp;
9653              overridden_tbp = overridden_tbp->overridden)
9654           if (overridden_tbp->is_generic)
9655             {
9656               for (g = overridden_tbp->u.generic; g; g = g->next)
9657                 {
9658                   gcc_assert (g->specific);
9659                   if (check_generic_tbp_ambiguity (target, g,
9660                                                    name, p->where) == FAILURE)
9661                     return FAILURE;
9662                 }
9663             }
9664       }
9665
9666   /* If we attempt to "overwrite" a specific binding, this is an error.  */
9667   if (p->overridden && !p->overridden->is_generic)
9668     {
9669       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
9670                  " the same name", name, &p->where);
9671       return FAILURE;
9672     }
9673
9674   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
9675      all must have the same attributes here.  */
9676   first_target = p->u.generic->specific->u.specific;
9677   gcc_assert (first_target);
9678   p->subroutine = first_target->n.sym->attr.subroutine;
9679   p->function = first_target->n.sym->attr.function;
9680
9681   return SUCCESS;
9682 }
9683
9684
9685 /* Resolve a GENERIC procedure binding for a derived type.  */
9686
9687 static gfc_try
9688 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
9689 {
9690   gfc_symbol* super_type;
9691
9692   /* Find the overridden binding if any.  */
9693   st->n.tb->overridden = NULL;
9694   super_type = gfc_get_derived_super_type (derived);
9695   if (super_type)
9696     {
9697       gfc_symtree* overridden;
9698       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
9699                                             true, NULL);
9700
9701       if (overridden && overridden->n.tb)
9702         st->n.tb->overridden = overridden->n.tb;
9703     }
9704
9705   /* Resolve using worker function.  */
9706   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
9707 }
9708
9709
9710 /* Retrieve the target-procedure of an operator binding and do some checks in
9711    common for intrinsic and user-defined type-bound operators.  */
9712
9713 static gfc_symbol*
9714 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
9715 {
9716   gfc_symbol* target_proc;
9717
9718   gcc_assert (target->specific && !target->specific->is_generic);
9719   target_proc = target->specific->u.specific->n.sym;
9720   gcc_assert (target_proc);
9721
9722   /* All operator bindings must have a passed-object dummy argument.  */
9723   if (target->specific->nopass)
9724     {
9725       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
9726       return NULL;
9727     }
9728
9729   return target_proc;
9730 }
9731
9732
9733 /* Resolve a type-bound intrinsic operator.  */
9734
9735 static gfc_try
9736 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
9737                                 gfc_typebound_proc* p)
9738 {
9739   gfc_symbol* super_type;
9740   gfc_tbp_generic* target;
9741   
9742   /* If there's already an error here, do nothing (but don't fail again).  */
9743   if (p->error)
9744     return SUCCESS;
9745
9746   /* Operators should always be GENERIC bindings.  */
9747   gcc_assert (p->is_generic);
9748
9749   /* Look for an overridden binding.  */
9750   super_type = gfc_get_derived_super_type (derived);
9751   if (super_type && super_type->f2k_derived)
9752     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
9753                                                      op, true, NULL);
9754   else
9755     p->overridden = NULL;
9756
9757   /* Resolve general GENERIC properties using worker function.  */
9758   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
9759     goto error;
9760
9761   /* Check the targets to be procedures of correct interface.  */
9762   for (target = p->u.generic; target; target = target->next)
9763     {
9764       gfc_symbol* target_proc;
9765
9766       target_proc = get_checked_tb_operator_target (target, p->where);
9767       if (!target_proc)
9768         goto error;
9769
9770       if (!gfc_check_operator_interface (target_proc, op, p->where))
9771         goto error;
9772     }
9773
9774   return SUCCESS;
9775
9776 error:
9777   p->error = 1;
9778   return FAILURE;
9779 }
9780
9781
9782 /* Resolve a type-bound user operator (tree-walker callback).  */
9783
9784 static gfc_symbol* resolve_bindings_derived;
9785 static gfc_try resolve_bindings_result;
9786
9787 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
9788
9789 static void
9790 resolve_typebound_user_op (gfc_symtree* stree)
9791 {
9792   gfc_symbol* super_type;
9793   gfc_tbp_generic* target;
9794
9795   gcc_assert (stree && stree->n.tb);
9796
9797   if (stree->n.tb->error)
9798     return;
9799
9800   /* Operators should always be GENERIC bindings.  */
9801   gcc_assert (stree->n.tb->is_generic);
9802
9803   /* Find overridden procedure, if any.  */
9804   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
9805   if (super_type && super_type->f2k_derived)
9806     {
9807       gfc_symtree* overridden;
9808       overridden = gfc_find_typebound_user_op (super_type, NULL,
9809                                                stree->name, true, NULL);
9810
9811       if (overridden && overridden->n.tb)
9812         stree->n.tb->overridden = overridden->n.tb;
9813     }
9814   else
9815     stree->n.tb->overridden = NULL;
9816
9817   /* Resolve basically using worker function.  */
9818   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
9819         == FAILURE)
9820     goto error;
9821
9822   /* Check the targets to be functions of correct interface.  */
9823   for (target = stree->n.tb->u.generic; target; target = target->next)
9824     {
9825       gfc_symbol* target_proc;
9826
9827       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
9828       if (!target_proc)
9829         goto error;
9830
9831       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
9832         goto error;
9833     }
9834
9835   return;
9836
9837 error:
9838   resolve_bindings_result = FAILURE;
9839   stree->n.tb->error = 1;
9840 }
9841
9842
9843 /* Resolve the type-bound procedures for a derived type.  */
9844
9845 static void
9846 resolve_typebound_procedure (gfc_symtree* stree)
9847 {
9848   gfc_symbol* proc;
9849   locus where;
9850   gfc_symbol* me_arg;
9851   gfc_symbol* super_type;
9852   gfc_component* comp;
9853
9854   gcc_assert (stree);
9855
9856   /* Undefined specific symbol from GENERIC target definition.  */
9857   if (!stree->n.tb)
9858     return;
9859
9860   if (stree->n.tb->error)
9861     return;
9862
9863   /* If this is a GENERIC binding, use that routine.  */
9864   if (stree->n.tb->is_generic)
9865     {
9866       if (resolve_typebound_generic (resolve_bindings_derived, stree)
9867             == FAILURE)
9868         goto error;
9869       return;
9870     }
9871
9872   /* Get the target-procedure to check it.  */
9873   gcc_assert (!stree->n.tb->is_generic);
9874   gcc_assert (stree->n.tb->u.specific);
9875   proc = stree->n.tb->u.specific->n.sym;
9876   where = stree->n.tb->where;
9877
9878   /* Default access should already be resolved from the parser.  */
9879   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
9880
9881   /* It should be a module procedure or an external procedure with explicit
9882      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
9883   if ((!proc->attr.subroutine && !proc->attr.function)
9884       || (proc->attr.proc != PROC_MODULE
9885           && proc->attr.if_source != IFSRC_IFBODY)
9886       || (proc->attr.abstract && !stree->n.tb->deferred))
9887     {
9888       gfc_error ("'%s' must be a module procedure or an external procedure with"
9889                  " an explicit interface at %L", proc->name, &where);
9890       goto error;
9891     }
9892   stree->n.tb->subroutine = proc->attr.subroutine;
9893   stree->n.tb->function = proc->attr.function;
9894
9895   /* Find the super-type of the current derived type.  We could do this once and
9896      store in a global if speed is needed, but as long as not I believe this is
9897      more readable and clearer.  */
9898   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
9899
9900   /* If PASS, resolve and check arguments if not already resolved / loaded
9901      from a .mod file.  */
9902   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
9903     {
9904       if (stree->n.tb->pass_arg)
9905         {
9906           gfc_formal_arglist* i;
9907
9908           /* If an explicit passing argument name is given, walk the arg-list
9909              and look for it.  */
9910
9911           me_arg = NULL;
9912           stree->n.tb->pass_arg_num = 1;
9913           for (i = proc->formal; i; i = i->next)
9914             {
9915               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
9916                 {
9917                   me_arg = i->sym;
9918                   break;
9919                 }
9920               ++stree->n.tb->pass_arg_num;
9921             }
9922
9923           if (!me_arg)
9924             {
9925               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
9926                          " argument '%s'",
9927                          proc->name, stree->n.tb->pass_arg, &where,
9928                          stree->n.tb->pass_arg);
9929               goto error;
9930             }
9931         }
9932       else
9933         {
9934           /* Otherwise, take the first one; there should in fact be at least
9935              one.  */
9936           stree->n.tb->pass_arg_num = 1;
9937           if (!proc->formal)
9938             {
9939               gfc_error ("Procedure '%s' with PASS at %L must have at"
9940                          " least one argument", proc->name, &where);
9941               goto error;
9942             }
9943           me_arg = proc->formal->sym;
9944         }
9945
9946       /* Now check that the argument-type matches.  */
9947       gcc_assert (me_arg);
9948       if (me_arg->ts.type != BT_CLASS)
9949         {
9950           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
9951                      " at %L", proc->name, &where);
9952           goto error;
9953         }
9954
9955       if (me_arg->ts.u.derived->components->ts.u.derived
9956           != resolve_bindings_derived)
9957         {
9958           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
9959                      " the derived-type '%s'", me_arg->name, proc->name,
9960                      me_arg->name, &where, resolve_bindings_derived->name);
9961           goto error;
9962         }
9963
9964     }
9965
9966   /* If we are extending some type, check that we don't override a procedure
9967      flagged NON_OVERRIDABLE.  */
9968   stree->n.tb->overridden = NULL;
9969   if (super_type)
9970     {
9971       gfc_symtree* overridden;
9972       overridden = gfc_find_typebound_proc (super_type, NULL,
9973                                             stree->name, true, NULL);
9974
9975       if (overridden && overridden->n.tb)
9976         stree->n.tb->overridden = overridden->n.tb;
9977
9978       if (overridden && check_typebound_override (stree, overridden) == FAILURE)
9979         goto error;
9980     }
9981
9982   /* See if there's a name collision with a component directly in this type.  */
9983   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
9984     if (!strcmp (comp->name, stree->name))
9985       {
9986         gfc_error ("Procedure '%s' at %L has the same name as a component of"
9987                    " '%s'",
9988                    stree->name, &where, resolve_bindings_derived->name);
9989         goto error;
9990       }
9991
9992   /* Try to find a name collision with an inherited component.  */
9993   if (super_type && gfc_find_component (super_type, stree->name, true, true))
9994     {
9995       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
9996                  " component of '%s'",
9997                  stree->name, &where, resolve_bindings_derived->name);
9998       goto error;
9999     }
10000
10001   stree->n.tb->error = 0;
10002   return;
10003
10004 error:
10005   resolve_bindings_result = FAILURE;
10006   stree->n.tb->error = 1;
10007 }
10008
10009 static gfc_try
10010 resolve_typebound_procedures (gfc_symbol* derived)
10011 {
10012   int op;
10013
10014   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
10015     return SUCCESS;
10016
10017   resolve_bindings_derived = derived;
10018   resolve_bindings_result = SUCCESS;
10019
10020   if (derived->f2k_derived->tb_sym_root)
10021     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
10022                           &resolve_typebound_procedure);
10023
10024   if (derived->f2k_derived->tb_uop_root)
10025     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
10026                           &resolve_typebound_user_op);
10027
10028   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
10029     {
10030       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
10031       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
10032                                                p) == FAILURE)
10033         resolve_bindings_result = FAILURE;
10034     }
10035
10036   return resolve_bindings_result;
10037 }
10038
10039
10040 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
10041    to give all identical derived types the same backend_decl.  */
10042 static void
10043 add_dt_to_dt_list (gfc_symbol *derived)
10044 {
10045   gfc_dt_list *dt_list;
10046
10047   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
10048     if (derived == dt_list->derived)
10049       break;
10050
10051   if (dt_list == NULL)
10052     {
10053       dt_list = gfc_get_dt_list ();
10054       dt_list->next = gfc_derived_types;
10055       dt_list->derived = derived;
10056       gfc_derived_types = dt_list;
10057     }
10058 }
10059
10060
10061 /* Ensure that a derived-type is really not abstract, meaning that every
10062    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
10063
10064 static gfc_try
10065 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
10066 {
10067   if (!st)
10068     return SUCCESS;
10069
10070   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
10071     return FAILURE;
10072   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
10073     return FAILURE;
10074
10075   if (st->n.tb && st->n.tb->deferred)
10076     {
10077       gfc_symtree* overriding;
10078       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
10079       gcc_assert (overriding && overriding->n.tb);
10080       if (overriding->n.tb->deferred)
10081         {
10082           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
10083                      " '%s' is DEFERRED and not overridden",
10084                      sub->name, &sub->declared_at, st->name);
10085           return FAILURE;
10086         }
10087     }
10088
10089   return SUCCESS;
10090 }
10091
10092 static gfc_try
10093 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
10094 {
10095   /* The algorithm used here is to recursively travel up the ancestry of sub
10096      and for each ancestor-type, check all bindings.  If any of them is
10097      DEFERRED, look it up starting from sub and see if the found (overriding)
10098      binding is not DEFERRED.
10099      This is not the most efficient way to do this, but it should be ok and is
10100      clearer than something sophisticated.  */
10101
10102   gcc_assert (ancestor && ancestor->attr.abstract && !sub->attr.abstract);
10103
10104   /* Walk bindings of this ancestor.  */
10105   if (ancestor->f2k_derived)
10106     {
10107       gfc_try t;
10108       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
10109       if (t == FAILURE)
10110         return FAILURE;
10111     }
10112
10113   /* Find next ancestor type and recurse on it.  */
10114   ancestor = gfc_get_derived_super_type (ancestor);
10115   if (ancestor)
10116     return ensure_not_abstract (sub, ancestor);
10117
10118   return SUCCESS;
10119 }
10120
10121
10122 static void resolve_symbol (gfc_symbol *sym);
10123
10124
10125 /* Resolve the components of a derived type.  */
10126
10127 static gfc_try
10128 resolve_fl_derived (gfc_symbol *sym)
10129 {
10130   gfc_symbol* super_type;
10131   gfc_component *c;
10132   int i;
10133
10134   super_type = gfc_get_derived_super_type (sym);
10135
10136   /* Ensure the extended type gets resolved before we do.  */
10137   if (super_type && resolve_fl_derived (super_type) == FAILURE)
10138     return FAILURE;
10139
10140   /* An ABSTRACT type must be extensible.  */
10141   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
10142     {
10143       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
10144                  sym->name, &sym->declared_at);
10145       return FAILURE;
10146     }
10147
10148   for (c = sym->components; c != NULL; c = c->next)
10149     {
10150       if (c->attr.proc_pointer && c->ts.interface)
10151         {
10152           if (c->ts.interface->attr.procedure)
10153             gfc_error ("Interface '%s', used by procedure pointer component "
10154                        "'%s' at %L, is declared in a later PROCEDURE statement",
10155                        c->ts.interface->name, c->name, &c->loc);
10156
10157           /* Get the attributes from the interface (now resolved).  */
10158           if (c->ts.interface->attr.if_source
10159               || c->ts.interface->attr.intrinsic)
10160             {
10161               gfc_symbol *ifc = c->ts.interface;
10162
10163               if (ifc->formal && !ifc->formal_ns)
10164                 resolve_symbol (ifc);
10165
10166               if (ifc->attr.intrinsic)
10167                 resolve_intrinsic (ifc, &ifc->declared_at);
10168
10169               if (ifc->result)
10170                 {
10171                   c->ts = ifc->result->ts;
10172                   c->attr.allocatable = ifc->result->attr.allocatable;
10173                   c->attr.pointer = ifc->result->attr.pointer;
10174                   c->attr.dimension = ifc->result->attr.dimension;
10175                   c->as = gfc_copy_array_spec (ifc->result->as);
10176                 }
10177               else
10178                 {   
10179                   c->ts = ifc->ts;
10180                   c->attr.allocatable = ifc->attr.allocatable;
10181                   c->attr.pointer = ifc->attr.pointer;
10182                   c->attr.dimension = ifc->attr.dimension;
10183                   c->as = gfc_copy_array_spec (ifc->as);
10184                 }
10185               c->ts.interface = ifc;
10186               c->attr.function = ifc->attr.function;
10187               c->attr.subroutine = ifc->attr.subroutine;
10188               gfc_copy_formal_args_ppc (c, ifc);
10189
10190               c->attr.pure = ifc->attr.pure;
10191               c->attr.elemental = ifc->attr.elemental;
10192               c->attr.recursive = ifc->attr.recursive;
10193               c->attr.always_explicit = ifc->attr.always_explicit;
10194               c->attr.ext_attr |= ifc->attr.ext_attr;
10195               /* Replace symbols in array spec.  */
10196               if (c->as)
10197                 {
10198                   int i;
10199                   for (i = 0; i < c->as->rank; i++)
10200                     {
10201                       gfc_expr_replace_comp (c->as->lower[i], c);
10202                       gfc_expr_replace_comp (c->as->upper[i], c);
10203                     }
10204                 }
10205               /* Copy char length.  */
10206               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
10207                 {
10208                   c->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
10209                   gfc_expr_replace_comp (c->ts.u.cl->length, c);
10210                 }
10211             }
10212           else if (c->ts.interface->name[0] != '\0')
10213             {
10214               gfc_error ("Interface '%s' of procedure pointer component "
10215                          "'%s' at %L must be explicit", c->ts.interface->name,
10216                          c->name, &c->loc);
10217               return FAILURE;
10218             }
10219         }
10220       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
10221         {
10222           c->ts = *gfc_get_default_type (c->name, NULL);
10223           c->attr.implicit_type = 1;
10224         }
10225
10226       /* Procedure pointer components: Check PASS arg.  */
10227       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0)
10228         {
10229           gfc_symbol* me_arg;
10230
10231           if (c->tb->pass_arg)
10232             {
10233               gfc_formal_arglist* i;
10234
10235               /* If an explicit passing argument name is given, walk the arg-list
10236                 and look for it.  */
10237
10238               me_arg = NULL;
10239               c->tb->pass_arg_num = 1;
10240               for (i = c->formal; i; i = i->next)
10241                 {
10242                   if (!strcmp (i->sym->name, c->tb->pass_arg))
10243                     {
10244                       me_arg = i->sym;
10245                       break;
10246                     }
10247                   c->tb->pass_arg_num++;
10248                 }
10249
10250               if (!me_arg)
10251                 {
10252                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
10253                              "at %L has no argument '%s'", c->name,
10254                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
10255                   c->tb->error = 1;
10256                   return FAILURE;
10257                 }
10258             }
10259           else
10260             {
10261               /* Otherwise, take the first one; there should in fact be at least
10262                 one.  */
10263               c->tb->pass_arg_num = 1;
10264               if (!c->formal)
10265                 {
10266                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
10267                              "must have at least one argument",
10268                              c->name, &c->loc);
10269                   c->tb->error = 1;
10270                   return FAILURE;
10271                 }
10272               me_arg = c->formal->sym;
10273             }
10274
10275           /* Now check that the argument-type matches.  */
10276           gcc_assert (me_arg);
10277           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
10278               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
10279               || (me_arg->ts.type == BT_CLASS
10280                   && me_arg->ts.u.derived->components->ts.u.derived != sym))
10281             {
10282               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
10283                          " the derived type '%s'", me_arg->name, c->name,
10284                          me_arg->name, &c->loc, sym->name);
10285               c->tb->error = 1;
10286               return FAILURE;
10287             }
10288
10289           /* Check for C453.  */
10290           if (me_arg->attr.dimension)
10291             {
10292               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10293                          "must be scalar", me_arg->name, c->name, me_arg->name,
10294                          &c->loc);
10295               c->tb->error = 1;
10296               return FAILURE;
10297             }
10298
10299           if (me_arg->attr.pointer)
10300             {
10301               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10302                          "may not have the POINTER attribute", me_arg->name,
10303                          c->name, me_arg->name, &c->loc);
10304               c->tb->error = 1;
10305               return FAILURE;
10306             }
10307
10308           if (me_arg->attr.allocatable)
10309             {
10310               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10311                          "may not be ALLOCATABLE", me_arg->name, c->name,
10312                          me_arg->name, &c->loc);
10313               c->tb->error = 1;
10314               return FAILURE;
10315             }
10316
10317           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
10318             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
10319                        " at %L", c->name, &c->loc);
10320
10321         }
10322
10323       /* Check type-spec if this is not the parent-type component.  */
10324       if ((!sym->attr.extension || c != sym->components)
10325           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
10326         return FAILURE;
10327
10328       /* If this type is an extension, see if this component has the same name
10329          as an inherited type-bound procedure.  */
10330       if (super_type
10331           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
10332         {
10333           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
10334                      " inherited type-bound procedure",
10335                      c->name, sym->name, &c->loc);
10336           return FAILURE;
10337         }
10338
10339       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer)
10340         {
10341          if (c->ts.u.cl->length == NULL
10342              || (resolve_charlen (c->ts.u.cl) == FAILURE)
10343              || !gfc_is_constant_expr (c->ts.u.cl->length))
10344            {
10345              gfc_error ("Character length of component '%s' needs to "
10346                         "be a constant specification expression at %L",
10347                         c->name,
10348                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
10349              return FAILURE;
10350            }
10351         }
10352
10353       if (c->ts.type == BT_DERIVED
10354           && sym->component_access != ACCESS_PRIVATE
10355           && gfc_check_access (sym->attr.access, sym->ns->default_access)
10356           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
10357           && !c->ts.u.derived->attr.use_assoc
10358           && !gfc_check_access (c->ts.u.derived->attr.access,
10359                                 c->ts.u.derived->ns->default_access)
10360           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
10361                              "is a PRIVATE type and cannot be a component of "
10362                              "'%s', which is PUBLIC at %L", c->name,
10363                              sym->name, &sym->declared_at) == FAILURE)
10364         return FAILURE;
10365
10366       if (sym->attr.sequence)
10367         {
10368           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
10369             {
10370               gfc_error ("Component %s of SEQUENCE type declared at %L does "
10371                          "not have the SEQUENCE attribute",
10372                          c->ts.u.derived->name, &sym->declared_at);
10373               return FAILURE;
10374             }
10375         }
10376
10377       if (c->ts.type == BT_DERIVED && c->attr.pointer
10378           && c->ts.u.derived->components == NULL
10379           && !c->ts.u.derived->attr.zero_comp)
10380         {
10381           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
10382                      "that has not been declared", c->name, sym->name,
10383                      &c->loc);
10384           return FAILURE;
10385         }
10386
10387       /* C437.  */
10388       if (c->ts.type == BT_CLASS
10389           && !(c->ts.u.derived->components->attr.pointer
10390                || c->ts.u.derived->components->attr.allocatable))
10391         {
10392           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
10393                      "or pointer", c->name, &c->loc);
10394           return FAILURE;
10395         }
10396
10397       /* Ensure that all the derived type components are put on the
10398          derived type list; even in formal namespaces, where derived type
10399          pointer components might not have been declared.  */
10400       if (c->ts.type == BT_DERIVED
10401             && c->ts.u.derived
10402             && c->ts.u.derived->components
10403             && c->attr.pointer
10404             && sym != c->ts.u.derived)
10405         add_dt_to_dt_list (c->ts.u.derived);
10406
10407       if (c->attr.pointer || c->attr.proc_pointer || c->attr.allocatable
10408           || c->as == NULL)
10409         continue;
10410
10411       for (i = 0; i < c->as->rank; i++)
10412         {
10413           if (c->as->lower[i] == NULL
10414               || (resolve_index_expr (c->as->lower[i]) == FAILURE)
10415               || !gfc_is_constant_expr (c->as->lower[i])
10416               || c->as->upper[i] == NULL
10417               || (resolve_index_expr (c->as->upper[i]) == FAILURE)
10418               || !gfc_is_constant_expr (c->as->upper[i]))
10419             {
10420               gfc_error ("Component '%s' of '%s' at %L must have "
10421                          "constant array bounds",
10422                          c->name, sym->name, &c->loc);
10423               return FAILURE;
10424             }
10425         }
10426     }
10427
10428   /* Resolve the type-bound procedures.  */
10429   if (resolve_typebound_procedures (sym) == FAILURE)
10430     return FAILURE;
10431
10432   /* Resolve the finalizer procedures.  */
10433   if (gfc_resolve_finalizers (sym) == FAILURE)
10434     return FAILURE;
10435
10436   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
10437      all DEFERRED bindings are overridden.  */
10438   if (super_type && super_type->attr.abstract && !sym->attr.abstract
10439       && ensure_not_abstract (sym, super_type) == FAILURE)
10440     return FAILURE;
10441
10442   /* Add derived type to the derived type list.  */
10443   add_dt_to_dt_list (sym);
10444
10445   return SUCCESS;
10446 }
10447
10448
10449 static gfc_try
10450 resolve_fl_namelist (gfc_symbol *sym)
10451 {
10452   gfc_namelist *nl;
10453   gfc_symbol *nlsym;
10454
10455   /* Reject PRIVATE objects in a PUBLIC namelist.  */
10456   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
10457     {
10458       for (nl = sym->namelist; nl; nl = nl->next)
10459         {
10460           if (!nl->sym->attr.use_assoc
10461               && !is_sym_host_assoc (nl->sym, sym->ns)
10462               && !gfc_check_access(nl->sym->attr.access,
10463                                 nl->sym->ns->default_access))
10464             {
10465               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
10466                          "cannot be member of PUBLIC namelist '%s' at %L",
10467                          nl->sym->name, sym->name, &sym->declared_at);
10468               return FAILURE;
10469             }
10470
10471           /* Types with private components that came here by USE-association.  */
10472           if (nl->sym->ts.type == BT_DERIVED
10473               && derived_inaccessible (nl->sym->ts.u.derived))
10474             {
10475               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
10476                          "components and cannot be member of namelist '%s' at %L",
10477                          nl->sym->name, sym->name, &sym->declared_at);
10478               return FAILURE;
10479             }
10480
10481           /* Types with private components that are defined in the same module.  */
10482           if (nl->sym->ts.type == BT_DERIVED
10483               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
10484               && !gfc_check_access (nl->sym->ts.u.derived->attr.private_comp
10485                                         ? ACCESS_PRIVATE : ACCESS_UNKNOWN,
10486                                         nl->sym->ns->default_access))
10487             {
10488               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
10489                          "cannot be a member of PUBLIC namelist '%s' at %L",
10490                          nl->sym->name, sym->name, &sym->declared_at);
10491               return FAILURE;
10492             }
10493         }
10494     }
10495
10496   for (nl = sym->namelist; nl; nl = nl->next)
10497     {
10498       /* Reject namelist arrays of assumed shape.  */
10499       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
10500           && gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
10501                              "must not have assumed shape in namelist "
10502                              "'%s' at %L", nl->sym->name, sym->name,
10503                              &sym->declared_at) == FAILURE)
10504             return FAILURE;
10505
10506       /* Reject namelist arrays that are not constant shape.  */
10507       if (is_non_constant_shape_array (nl->sym))
10508         {
10509           gfc_error ("NAMELIST array object '%s' must have constant "
10510                      "shape in namelist '%s' at %L", nl->sym->name,
10511                      sym->name, &sym->declared_at);
10512           return FAILURE;
10513         }
10514
10515       /* Namelist objects cannot have allocatable or pointer components.  */
10516       if (nl->sym->ts.type != BT_DERIVED)
10517         continue;
10518
10519       if (nl->sym->ts.u.derived->attr.alloc_comp)
10520         {
10521           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
10522                      "have ALLOCATABLE components",
10523                      nl->sym->name, sym->name, &sym->declared_at);
10524           return FAILURE;
10525         }
10526
10527       if (nl->sym->ts.u.derived->attr.pointer_comp)
10528         {
10529           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
10530                      "have POINTER components", 
10531                      nl->sym->name, sym->name, &sym->declared_at);
10532           return FAILURE;
10533         }
10534     }
10535
10536
10537   /* 14.1.2 A module or internal procedure represent local entities
10538      of the same type as a namelist member and so are not allowed.  */
10539   for (nl = sym->namelist; nl; nl = nl->next)
10540     {
10541       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
10542         continue;
10543
10544       if (nl->sym->attr.function && nl->sym == nl->sym->result)
10545         if ((nl->sym == sym->ns->proc_name)
10546                ||
10547             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
10548           continue;
10549
10550       nlsym = NULL;
10551       if (nl->sym && nl->sym->name)
10552         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
10553       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
10554         {
10555           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
10556                      "attribute in '%s' at %L", nlsym->name,
10557                      &sym->declared_at);
10558           return FAILURE;
10559         }
10560     }
10561
10562   return SUCCESS;
10563 }
10564
10565
10566 static gfc_try
10567 resolve_fl_parameter (gfc_symbol *sym)
10568 {
10569   /* A parameter array's shape needs to be constant.  */
10570   if (sym->as != NULL 
10571       && (sym->as->type == AS_DEFERRED
10572           || is_non_constant_shape_array (sym)))
10573     {
10574       gfc_error ("Parameter array '%s' at %L cannot be automatic "
10575                  "or of deferred shape", sym->name, &sym->declared_at);
10576       return FAILURE;
10577     }
10578
10579   /* Make sure a parameter that has been implicitly typed still
10580      matches the implicit type, since PARAMETER statements can precede
10581      IMPLICIT statements.  */
10582   if (sym->attr.implicit_type
10583       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
10584                                                              sym->ns)))
10585     {
10586       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
10587                  "later IMPLICIT type", sym->name, &sym->declared_at);
10588       return FAILURE;
10589     }
10590
10591   /* Make sure the types of derived parameters are consistent.  This
10592      type checking is deferred until resolution because the type may
10593      refer to a derived type from the host.  */
10594   if (sym->ts.type == BT_DERIVED
10595       && !gfc_compare_types (&sym->ts, &sym->value->ts))
10596     {
10597       gfc_error ("Incompatible derived type in PARAMETER at %L",
10598                  &sym->value->where);
10599       return FAILURE;
10600     }
10601   return SUCCESS;
10602 }
10603
10604
10605 /* Do anything necessary to resolve a symbol.  Right now, we just
10606    assume that an otherwise unknown symbol is a variable.  This sort
10607    of thing commonly happens for symbols in module.  */
10608
10609 static void
10610 resolve_symbol (gfc_symbol *sym)
10611 {
10612   int check_constant, mp_flag;
10613   gfc_symtree *symtree;
10614   gfc_symtree *this_symtree;
10615   gfc_namespace *ns;
10616   gfc_component *c;
10617
10618   if (sym->attr.flavor == FL_UNKNOWN)
10619     {
10620
10621     /* If we find that a flavorless symbol is an interface in one of the
10622        parent namespaces, find its symtree in this namespace, free the
10623        symbol and set the symtree to point to the interface symbol.  */
10624       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
10625         {
10626           symtree = gfc_find_symtree (ns->sym_root, sym->name);
10627           if (symtree && symtree->n.sym->generic)
10628             {
10629               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
10630                                                sym->name);
10631               sym->refs--;
10632               if (!sym->refs)
10633                 gfc_free_symbol (sym);
10634               symtree->n.sym->refs++;
10635               this_symtree->n.sym = symtree->n.sym;
10636               return;
10637             }
10638         }
10639
10640       /* Otherwise give it a flavor according to such attributes as
10641          it has.  */
10642       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
10643         sym->attr.flavor = FL_VARIABLE;
10644       else
10645         {
10646           sym->attr.flavor = FL_PROCEDURE;
10647           if (sym->attr.dimension)
10648             sym->attr.function = 1;
10649         }
10650     }
10651
10652   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
10653     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
10654
10655   if (sym->attr.procedure && sym->ts.interface
10656       && sym->attr.if_source != IFSRC_DECL)
10657     {
10658       if (sym->ts.interface == sym)
10659         {
10660           gfc_error ("PROCEDURE '%s' at %L may not be used as its own "
10661                      "interface", sym->name, &sym->declared_at);
10662           return;
10663         }
10664       if (sym->ts.interface->attr.procedure)
10665         {
10666           gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared"
10667                      " in a later PROCEDURE statement", sym->ts.interface->name,
10668                      sym->name,&sym->declared_at);
10669           return;
10670         }
10671
10672       /* Get the attributes from the interface (now resolved).  */
10673       if (sym->ts.interface->attr.if_source
10674           || sym->ts.interface->attr.intrinsic)
10675         {
10676           gfc_symbol *ifc = sym->ts.interface;
10677           resolve_symbol (ifc);
10678
10679           if (ifc->attr.intrinsic)
10680             resolve_intrinsic (ifc, &ifc->declared_at);
10681
10682           if (ifc->result)
10683             sym->ts = ifc->result->ts;
10684           else   
10685             sym->ts = ifc->ts;
10686           sym->ts.interface = ifc;
10687           sym->attr.function = ifc->attr.function;
10688           sym->attr.subroutine = ifc->attr.subroutine;
10689           gfc_copy_formal_args (sym, ifc);
10690
10691           sym->attr.allocatable = ifc->attr.allocatable;
10692           sym->attr.pointer = ifc->attr.pointer;
10693           sym->attr.pure = ifc->attr.pure;
10694           sym->attr.elemental = ifc->attr.elemental;
10695           sym->attr.dimension = ifc->attr.dimension;
10696           sym->attr.recursive = ifc->attr.recursive;
10697           sym->attr.always_explicit = ifc->attr.always_explicit;
10698           sym->attr.ext_attr |= ifc->attr.ext_attr;
10699           /* Copy array spec.  */
10700           sym->as = gfc_copy_array_spec (ifc->as);
10701           if (sym->as)
10702             {
10703               int i;
10704               for (i = 0; i < sym->as->rank; i++)
10705                 {
10706                   gfc_expr_replace_symbols (sym->as->lower[i], sym);
10707                   gfc_expr_replace_symbols (sym->as->upper[i], sym);
10708                 }
10709             }
10710           /* Copy char length.  */
10711           if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
10712             {
10713               sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
10714               gfc_expr_replace_symbols (sym->ts.u.cl->length, sym);
10715             }
10716         }
10717       else if (sym->ts.interface->name[0] != '\0')
10718         {
10719           gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
10720                     sym->ts.interface->name, sym->name, &sym->declared_at);
10721           return;
10722         }
10723     }
10724
10725   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
10726     return;
10727
10728   /* Symbols that are module procedures with results (functions) have
10729      the types and array specification copied for type checking in
10730      procedures that call them, as well as for saving to a module
10731      file.  These symbols can't stand the scrutiny that their results
10732      can.  */
10733   mp_flag = (sym->result != NULL && sym->result != sym);
10734
10735
10736   /* Make sure that the intrinsic is consistent with its internal 
10737      representation. This needs to be done before assigning a default 
10738      type to avoid spurious warnings.  */
10739   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
10740       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
10741     return;
10742
10743   /* Assign default type to symbols that need one and don't have one.  */
10744   if (sym->ts.type == BT_UNKNOWN)
10745     {
10746       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
10747         gfc_set_default_type (sym, 1, NULL);
10748
10749       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
10750           && !sym->attr.function && !sym->attr.subroutine
10751           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
10752         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
10753
10754       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
10755         {
10756           /* The specific case of an external procedure should emit an error
10757              in the case that there is no implicit type.  */
10758           if (!mp_flag)
10759             gfc_set_default_type (sym, sym->attr.external, NULL);
10760           else
10761             {
10762               /* Result may be in another namespace.  */
10763               resolve_symbol (sym->result);
10764
10765               if (!sym->result->attr.proc_pointer)
10766                 {
10767                   sym->ts = sym->result->ts;
10768                   sym->as = gfc_copy_array_spec (sym->result->as);
10769                   sym->attr.dimension = sym->result->attr.dimension;
10770                   sym->attr.pointer = sym->result->attr.pointer;
10771                   sym->attr.allocatable = sym->result->attr.allocatable;
10772                 }
10773             }
10774         }
10775     }
10776
10777   /* Assumed size arrays and assumed shape arrays must be dummy
10778      arguments.  */
10779
10780   if (sym->as != NULL
10781       && (sym->as->type == AS_ASSUMED_SIZE
10782           || sym->as->type == AS_ASSUMED_SHAPE)
10783       && sym->attr.dummy == 0)
10784     {
10785       if (sym->as->type == AS_ASSUMED_SIZE)
10786         gfc_error ("Assumed size array at %L must be a dummy argument",
10787                    &sym->declared_at);
10788       else
10789         gfc_error ("Assumed shape array at %L must be a dummy argument",
10790                    &sym->declared_at);
10791       return;
10792     }
10793
10794   /* Make sure symbols with known intent or optional are really dummy
10795      variable.  Because of ENTRY statement, this has to be deferred
10796      until resolution time.  */
10797
10798   if (!sym->attr.dummy
10799       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
10800     {
10801       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
10802       return;
10803     }
10804
10805   if (sym->attr.value && !sym->attr.dummy)
10806     {
10807       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
10808                  "it is not a dummy argument", sym->name, &sym->declared_at);
10809       return;
10810     }
10811
10812   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
10813     {
10814       gfc_charlen *cl = sym->ts.u.cl;
10815       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
10816         {
10817           gfc_error ("Character dummy variable '%s' at %L with VALUE "
10818                      "attribute must have constant length",
10819                      sym->name, &sym->declared_at);
10820           return;
10821         }
10822
10823       if (sym->ts.is_c_interop
10824           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
10825         {
10826           gfc_error ("C interoperable character dummy variable '%s' at %L "
10827                      "with VALUE attribute must have length one",
10828                      sym->name, &sym->declared_at);
10829           return;
10830         }
10831     }
10832
10833   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
10834      do this for something that was implicitly typed because that is handled
10835      in gfc_set_default_type.  Handle dummy arguments and procedure
10836      definitions separately.  Also, anything that is use associated is not
10837      handled here but instead is handled in the module it is declared in.
10838      Finally, derived type definitions are allowed to be BIND(C) since that
10839      only implies that they're interoperable, and they are checked fully for
10840      interoperability when a variable is declared of that type.  */
10841   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
10842       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
10843       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
10844     {
10845       gfc_try t = SUCCESS;
10846       
10847       /* First, make sure the variable is declared at the
10848          module-level scope (J3/04-007, Section 15.3).  */
10849       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
10850           sym->attr.in_common == 0)
10851         {
10852           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
10853                      "is neither a COMMON block nor declared at the "
10854                      "module level scope", sym->name, &(sym->declared_at));
10855           t = FAILURE;
10856         }
10857       else if (sym->common_head != NULL)
10858         {
10859           t = verify_com_block_vars_c_interop (sym->common_head);
10860         }
10861       else
10862         {
10863           /* If type() declaration, we need to verify that the components
10864              of the given type are all C interoperable, etc.  */
10865           if (sym->ts.type == BT_DERIVED &&
10866               sym->ts.u.derived->attr.is_c_interop != 1)
10867             {
10868               /* Make sure the user marked the derived type as BIND(C).  If
10869                  not, call the verify routine.  This could print an error
10870                  for the derived type more than once if multiple variables
10871                  of that type are declared.  */
10872               if (sym->ts.u.derived->attr.is_bind_c != 1)
10873                 verify_bind_c_derived_type (sym->ts.u.derived);
10874               t = FAILURE;
10875             }
10876           
10877           /* Verify the variable itself as C interoperable if it
10878              is BIND(C).  It is not possible for this to succeed if
10879              the verify_bind_c_derived_type failed, so don't have to handle
10880              any error returned by verify_bind_c_derived_type.  */
10881           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
10882                                  sym->common_block);
10883         }
10884
10885       if (t == FAILURE)
10886         {
10887           /* clear the is_bind_c flag to prevent reporting errors more than
10888              once if something failed.  */
10889           sym->attr.is_bind_c = 0;
10890           return;
10891         }
10892     }
10893
10894   /* If a derived type symbol has reached this point, without its
10895      type being declared, we have an error.  Notice that most
10896      conditions that produce undefined derived types have already
10897      been dealt with.  However, the likes of:
10898      implicit type(t) (t) ..... call foo (t) will get us here if
10899      the type is not declared in the scope of the implicit
10900      statement. Change the type to BT_UNKNOWN, both because it is so
10901      and to prevent an ICE.  */
10902   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->components == NULL
10903       && !sym->ts.u.derived->attr.zero_comp)
10904     {
10905       gfc_error ("The derived type '%s' at %L is of type '%s', "
10906                  "which has not been defined", sym->name,
10907                   &sym->declared_at, sym->ts.u.derived->name);
10908       sym->ts.type = BT_UNKNOWN;
10909       return;
10910     }
10911
10912   /* Make sure that the derived type has been resolved and that the
10913      derived type is visible in the symbol's namespace, if it is a
10914      module function and is not PRIVATE.  */
10915   if (sym->ts.type == BT_DERIVED
10916         && sym->ts.u.derived->attr.use_assoc
10917         && sym->ns->proc_name
10918         && sym->ns->proc_name->attr.flavor == FL_MODULE)
10919     {
10920       gfc_symbol *ds;
10921
10922       if (resolve_fl_derived (sym->ts.u.derived) == FAILURE)
10923         return;
10924
10925       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 1, &ds);
10926       if (!ds && sym->attr.function
10927             && gfc_check_access (sym->attr.access, sym->ns->default_access))
10928         {
10929           symtree = gfc_new_symtree (&sym->ns->sym_root,
10930                                      sym->ts.u.derived->name);
10931           symtree->n.sym = sym->ts.u.derived;
10932           sym->ts.u.derived->refs++;
10933         }
10934     }
10935
10936   /* Unless the derived-type declaration is use associated, Fortran 95
10937      does not allow public entries of private derived types.
10938      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
10939      161 in 95-006r3.  */
10940   if (sym->ts.type == BT_DERIVED
10941       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
10942       && !sym->ts.u.derived->attr.use_assoc
10943       && gfc_check_access (sym->attr.access, sym->ns->default_access)
10944       && !gfc_check_access (sym->ts.u.derived->attr.access,
10945                             sym->ts.u.derived->ns->default_access)
10946       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
10947                          "of PRIVATE derived type '%s'",
10948                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
10949                          : "variable", sym->name, &sym->declared_at,
10950                          sym->ts.u.derived->name) == FAILURE)
10951     return;
10952
10953   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
10954      default initialization is defined (5.1.2.4.4).  */
10955   if (sym->ts.type == BT_DERIVED
10956       && sym->attr.dummy
10957       && sym->attr.intent == INTENT_OUT
10958       && sym->as
10959       && sym->as->type == AS_ASSUMED_SIZE)
10960     {
10961       for (c = sym->ts.u.derived->components; c; c = c->next)
10962         {
10963           if (c->initializer)
10964             {
10965               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
10966                          "ASSUMED SIZE and so cannot have a default initializer",
10967                          sym->name, &sym->declared_at);
10968               return;
10969             }
10970         }
10971     }
10972
10973   switch (sym->attr.flavor)
10974     {
10975     case FL_VARIABLE:
10976       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
10977         return;
10978       break;
10979
10980     case FL_PROCEDURE:
10981       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
10982         return;
10983       break;
10984
10985     case FL_NAMELIST:
10986       if (resolve_fl_namelist (sym) == FAILURE)
10987         return;
10988       break;
10989
10990     case FL_PARAMETER:
10991       if (resolve_fl_parameter (sym) == FAILURE)
10992         return;
10993       break;
10994
10995     default:
10996       break;
10997     }
10998
10999   /* Resolve array specifier. Check as well some constraints
11000      on COMMON blocks.  */
11001
11002   check_constant = sym->attr.in_common && !sym->attr.pointer;
11003
11004   /* Set the formal_arg_flag so that check_conflict will not throw
11005      an error for host associated variables in the specification
11006      expression for an array_valued function.  */
11007   if (sym->attr.function && sym->as)
11008     formal_arg_flag = 1;
11009
11010   gfc_resolve_array_spec (sym->as, check_constant);
11011
11012   formal_arg_flag = 0;
11013
11014   /* Resolve formal namespaces.  */
11015   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
11016       && !sym->attr.contained && !sym->attr.intrinsic)
11017     gfc_resolve (sym->formal_ns);
11018
11019   /* Make sure the formal namespace is present.  */
11020   if (sym->formal && !sym->formal_ns)
11021     {
11022       gfc_formal_arglist *formal = sym->formal;
11023       while (formal && !formal->sym)
11024         formal = formal->next;
11025
11026       if (formal)
11027         {
11028           sym->formal_ns = formal->sym->ns;
11029           sym->formal_ns->refs++;
11030         }
11031     }
11032
11033   /* Check threadprivate restrictions.  */
11034   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
11035       && (!sym->attr.in_common
11036           && sym->module == NULL
11037           && (sym->ns->proc_name == NULL
11038               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
11039     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
11040
11041   /* If we have come this far we can apply default-initializers, as
11042      described in 14.7.5, to those variables that have not already
11043      been assigned one.  */
11044   if (sym->ts.type == BT_DERIVED
11045       && sym->attr.referenced
11046       && sym->ns == gfc_current_ns
11047       && !sym->value
11048       && !sym->attr.allocatable
11049       && !sym->attr.alloc_comp)
11050     {
11051       symbol_attribute *a = &sym->attr;
11052
11053       if ((!a->save && !a->dummy && !a->pointer
11054            && !a->in_common && !a->use_assoc
11055            && !(a->function && sym != sym->result))
11056           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
11057         apply_default_init (sym);
11058     }
11059
11060   /* If this symbol has a type-spec, check it.  */
11061   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
11062       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
11063     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
11064           == FAILURE)
11065       return;
11066 }
11067
11068
11069 /************* Resolve DATA statements *************/
11070
11071 static struct
11072 {
11073   gfc_data_value *vnode;
11074   mpz_t left;
11075 }
11076 values;
11077
11078
11079 /* Advance the values structure to point to the next value in the data list.  */
11080
11081 static gfc_try
11082 next_data_value (void)
11083 {
11084   while (mpz_cmp_ui (values.left, 0) == 0)
11085     {
11086       if (!gfc_is_constant_expr (values.vnode->expr))
11087         gfc_error ("non-constant DATA value at %L",
11088                    &values.vnode->expr->where);
11089
11090       if (values.vnode->next == NULL)
11091         return FAILURE;
11092
11093       values.vnode = values.vnode->next;
11094       mpz_set (values.left, values.vnode->repeat);
11095     }
11096
11097   return SUCCESS;
11098 }
11099
11100
11101 static gfc_try
11102 check_data_variable (gfc_data_variable *var, locus *where)
11103 {
11104   gfc_expr *e;
11105   mpz_t size;
11106   mpz_t offset;
11107   gfc_try t;
11108   ar_type mark = AR_UNKNOWN;
11109   int i;
11110   mpz_t section_index[GFC_MAX_DIMENSIONS];
11111   gfc_ref *ref;
11112   gfc_array_ref *ar;
11113   gfc_symbol *sym;
11114   int has_pointer;
11115
11116   if (gfc_resolve_expr (var->expr) == FAILURE)
11117     return FAILURE;
11118
11119   ar = NULL;
11120   mpz_init_set_si (offset, 0);
11121   e = var->expr;
11122
11123   if (e->expr_type != EXPR_VARIABLE)
11124     gfc_internal_error ("check_data_variable(): Bad expression");
11125
11126   sym = e->symtree->n.sym;
11127
11128   if (sym->ns->is_block_data && !sym->attr.in_common)
11129     {
11130       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
11131                  sym->name, &sym->declared_at);
11132     }
11133
11134   if (e->ref == NULL && sym->as)
11135     {
11136       gfc_error ("DATA array '%s' at %L must be specified in a previous"
11137                  " declaration", sym->name, where);
11138       return FAILURE;
11139     }
11140
11141   has_pointer = sym->attr.pointer;
11142
11143   for (ref = e->ref; ref; ref = ref->next)
11144     {
11145       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
11146         has_pointer = 1;
11147
11148       if (has_pointer
11149             && ref->type == REF_ARRAY
11150             && ref->u.ar.type != AR_FULL)
11151           {
11152             gfc_error ("DATA element '%s' at %L is a pointer and so must "
11153                         "be a full array", sym->name, where);
11154             return FAILURE;
11155           }
11156     }
11157
11158   if (e->rank == 0 || has_pointer)
11159     {
11160       mpz_init_set_ui (size, 1);
11161       ref = NULL;
11162     }
11163   else
11164     {
11165       ref = e->ref;
11166
11167       /* Find the array section reference.  */
11168       for (ref = e->ref; ref; ref = ref->next)
11169         {
11170           if (ref->type != REF_ARRAY)
11171             continue;
11172           if (ref->u.ar.type == AR_ELEMENT)
11173             continue;
11174           break;
11175         }
11176       gcc_assert (ref);
11177
11178       /* Set marks according to the reference pattern.  */
11179       switch (ref->u.ar.type)
11180         {
11181         case AR_FULL:
11182           mark = AR_FULL;
11183           break;
11184
11185         case AR_SECTION:
11186           ar = &ref->u.ar;
11187           /* Get the start position of array section.  */
11188           gfc_get_section_index (ar, section_index, &offset);
11189           mark = AR_SECTION;
11190           break;
11191
11192         default:
11193           gcc_unreachable ();
11194         }
11195
11196       if (gfc_array_size (e, &size) == FAILURE)
11197         {
11198           gfc_error ("Nonconstant array section at %L in DATA statement",
11199                      &e->where);
11200           mpz_clear (offset);
11201           return FAILURE;
11202         }
11203     }
11204
11205   t = SUCCESS;
11206
11207   while (mpz_cmp_ui (size, 0) > 0)
11208     {
11209       if (next_data_value () == FAILURE)
11210         {
11211           gfc_error ("DATA statement at %L has more variables than values",
11212                      where);
11213           t = FAILURE;
11214           break;
11215         }
11216
11217       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
11218       if (t == FAILURE)
11219         break;
11220
11221       /* If we have more than one element left in the repeat count,
11222          and we have more than one element left in the target variable,
11223          then create a range assignment.  */
11224       /* FIXME: Only done for full arrays for now, since array sections
11225          seem tricky.  */
11226       if (mark == AR_FULL && ref && ref->next == NULL
11227           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
11228         {
11229           mpz_t range;
11230
11231           if (mpz_cmp (size, values.left) >= 0)
11232             {
11233               mpz_init_set (range, values.left);
11234               mpz_sub (size, size, values.left);
11235               mpz_set_ui (values.left, 0);
11236             }
11237           else
11238             {
11239               mpz_init_set (range, size);
11240               mpz_sub (values.left, values.left, size);
11241               mpz_set_ui (size, 0);
11242             }
11243
11244           gfc_assign_data_value_range (var->expr, values.vnode->expr,
11245                                        offset, range);
11246
11247           mpz_add (offset, offset, range);
11248           mpz_clear (range);
11249         }
11250
11251       /* Assign initial value to symbol.  */
11252       else
11253         {
11254           mpz_sub_ui (values.left, values.left, 1);
11255           mpz_sub_ui (size, size, 1);
11256
11257           t = gfc_assign_data_value (var->expr, values.vnode->expr, offset);
11258           if (t == FAILURE)
11259             break;
11260
11261           if (mark == AR_FULL)
11262             mpz_add_ui (offset, offset, 1);
11263
11264           /* Modify the array section indexes and recalculate the offset
11265              for next element.  */
11266           else if (mark == AR_SECTION)
11267             gfc_advance_section (section_index, ar, &offset);
11268         }
11269     }
11270
11271   if (mark == AR_SECTION)
11272     {
11273       for (i = 0; i < ar->dimen; i++)
11274         mpz_clear (section_index[i]);
11275     }
11276
11277   mpz_clear (size);
11278   mpz_clear (offset);
11279
11280   return t;
11281 }
11282
11283
11284 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
11285
11286 /* Iterate over a list of elements in a DATA statement.  */
11287
11288 static gfc_try
11289 traverse_data_list (gfc_data_variable *var, locus *where)
11290 {
11291   mpz_t trip;
11292   iterator_stack frame;
11293   gfc_expr *e, *start, *end, *step;
11294   gfc_try retval = SUCCESS;
11295
11296   mpz_init (frame.value);
11297
11298   start = gfc_copy_expr (var->iter.start);
11299   end = gfc_copy_expr (var->iter.end);
11300   step = gfc_copy_expr (var->iter.step);
11301
11302   if (gfc_simplify_expr (start, 1) == FAILURE
11303       || start->expr_type != EXPR_CONSTANT)
11304     {
11305       gfc_error ("iterator start at %L does not simplify", &start->where);
11306       retval = FAILURE;
11307       goto cleanup;
11308     }
11309   if (gfc_simplify_expr (end, 1) == FAILURE
11310       || end->expr_type != EXPR_CONSTANT)
11311     {
11312       gfc_error ("iterator end at %L does not simplify", &end->where);
11313       retval = FAILURE;
11314       goto cleanup;
11315     }
11316   if (gfc_simplify_expr (step, 1) == FAILURE
11317       || step->expr_type != EXPR_CONSTANT)
11318     {
11319       gfc_error ("iterator step at %L does not simplify", &step->where);
11320       retval = FAILURE;
11321       goto cleanup;
11322     }
11323
11324   mpz_init_set (trip, end->value.integer);
11325   mpz_sub (trip, trip, start->value.integer);
11326   mpz_add (trip, trip, step->value.integer);
11327
11328   mpz_div (trip, trip, step->value.integer);
11329
11330   mpz_set (frame.value, start->value.integer);
11331
11332   frame.prev = iter_stack;
11333   frame.variable = var->iter.var->symtree;
11334   iter_stack = &frame;
11335
11336   while (mpz_cmp_ui (trip, 0) > 0)
11337     {
11338       if (traverse_data_var (var->list, where) == FAILURE)
11339         {
11340           mpz_clear (trip);
11341           retval = FAILURE;
11342           goto cleanup;
11343         }
11344
11345       e = gfc_copy_expr (var->expr);
11346       if (gfc_simplify_expr (e, 1) == FAILURE)
11347         {
11348           gfc_free_expr (e);
11349           mpz_clear (trip);
11350           retval = FAILURE;
11351           goto cleanup;
11352         }
11353
11354       mpz_add (frame.value, frame.value, step->value.integer);
11355
11356       mpz_sub_ui (trip, trip, 1);
11357     }
11358
11359   mpz_clear (trip);
11360 cleanup:
11361   mpz_clear (frame.value);
11362
11363   gfc_free_expr (start);
11364   gfc_free_expr (end);
11365   gfc_free_expr (step);
11366
11367   iter_stack = frame.prev;
11368   return retval;
11369 }
11370
11371
11372 /* Type resolve variables in the variable list of a DATA statement.  */
11373
11374 static gfc_try
11375 traverse_data_var (gfc_data_variable *var, locus *where)
11376 {
11377   gfc_try t;
11378
11379   for (; var; var = var->next)
11380     {
11381       if (var->expr == NULL)
11382         t = traverse_data_list (var, where);
11383       else
11384         t = check_data_variable (var, where);
11385
11386       if (t == FAILURE)
11387         return FAILURE;
11388     }
11389
11390   return SUCCESS;
11391 }
11392
11393
11394 /* Resolve the expressions and iterators associated with a data statement.
11395    This is separate from the assignment checking because data lists should
11396    only be resolved once.  */
11397
11398 static gfc_try
11399 resolve_data_variables (gfc_data_variable *d)
11400 {
11401   for (; d; d = d->next)
11402     {
11403       if (d->list == NULL)
11404         {
11405           if (gfc_resolve_expr (d->expr) == FAILURE)
11406             return FAILURE;
11407         }
11408       else
11409         {
11410           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
11411             return FAILURE;
11412
11413           if (resolve_data_variables (d->list) == FAILURE)
11414             return FAILURE;
11415         }
11416     }
11417
11418   return SUCCESS;
11419 }
11420
11421
11422 /* Resolve a single DATA statement.  We implement this by storing a pointer to
11423    the value list into static variables, and then recursively traversing the
11424    variables list, expanding iterators and such.  */
11425
11426 static void
11427 resolve_data (gfc_data *d)
11428 {
11429
11430   if (resolve_data_variables (d->var) == FAILURE)
11431     return;
11432
11433   values.vnode = d->value;
11434   if (d->value == NULL)
11435     mpz_set_ui (values.left, 0);
11436   else
11437     mpz_set (values.left, d->value->repeat);
11438
11439   if (traverse_data_var (d->var, &d->where) == FAILURE)
11440     return;
11441
11442   /* At this point, we better not have any values left.  */
11443
11444   if (next_data_value () == SUCCESS)
11445     gfc_error ("DATA statement at %L has more values than variables",
11446                &d->where);
11447 }
11448
11449
11450 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
11451    accessed by host or use association, is a dummy argument to a pure function,
11452    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
11453    is storage associated with any such variable, shall not be used in the
11454    following contexts: (clients of this function).  */
11455
11456 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
11457    procedure.  Returns zero if assignment is OK, nonzero if there is a
11458    problem.  */
11459 int
11460 gfc_impure_variable (gfc_symbol *sym)
11461 {
11462   gfc_symbol *proc;
11463
11464   if (sym->attr.use_assoc || sym->attr.in_common)
11465     return 1;
11466
11467   if (sym->ns != gfc_current_ns)
11468     return !sym->attr.function;
11469
11470   proc = sym->ns->proc_name;
11471   if (sym->attr.dummy && gfc_pure (proc)
11472         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
11473                 ||
11474              proc->attr.function))
11475     return 1;
11476
11477   /* TODO: Sort out what can be storage associated, if anything, and include
11478      it here.  In principle equivalences should be scanned but it does not
11479      seem to be possible to storage associate an impure variable this way.  */
11480   return 0;
11481 }
11482
11483
11484 /* Test whether a symbol is pure or not.  For a NULL pointer, checks the
11485    symbol of the current procedure.  */
11486
11487 int
11488 gfc_pure (gfc_symbol *sym)
11489 {
11490   symbol_attribute attr;
11491
11492   if (sym == NULL)
11493     sym = gfc_current_ns->proc_name;
11494   if (sym == NULL)
11495     return 0;
11496
11497   attr = sym->attr;
11498
11499   return attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental);
11500 }
11501
11502
11503 /* Test whether the current procedure is elemental or not.  */
11504
11505 int
11506 gfc_elemental (gfc_symbol *sym)
11507 {
11508   symbol_attribute attr;
11509
11510   if (sym == NULL)
11511     sym = gfc_current_ns->proc_name;
11512   if (sym == NULL)
11513     return 0;
11514   attr = sym->attr;
11515
11516   return attr.flavor == FL_PROCEDURE && attr.elemental;
11517 }
11518
11519
11520 /* Warn about unused labels.  */
11521
11522 static void
11523 warn_unused_fortran_label (gfc_st_label *label)
11524 {
11525   if (label == NULL)
11526     return;
11527
11528   warn_unused_fortran_label (label->left);
11529
11530   if (label->defined == ST_LABEL_UNKNOWN)
11531     return;
11532
11533   switch (label->referenced)
11534     {
11535     case ST_LABEL_UNKNOWN:
11536       gfc_warning ("Label %d at %L defined but not used", label->value,
11537                    &label->where);
11538       break;
11539
11540     case ST_LABEL_BAD_TARGET:
11541       gfc_warning ("Label %d at %L defined but cannot be used",
11542                    label->value, &label->where);
11543       break;
11544
11545     default:
11546       break;
11547     }
11548
11549   warn_unused_fortran_label (label->right);
11550 }
11551
11552
11553 /* Returns the sequence type of a symbol or sequence.  */
11554
11555 static seq_type
11556 sequence_type (gfc_typespec ts)
11557 {
11558   seq_type result;
11559   gfc_component *c;
11560
11561   switch (ts.type)
11562   {
11563     case BT_DERIVED:
11564
11565       if (ts.u.derived->components == NULL)
11566         return SEQ_NONDEFAULT;
11567
11568       result = sequence_type (ts.u.derived->components->ts);
11569       for (c = ts.u.derived->components->next; c; c = c->next)
11570         if (sequence_type (c->ts) != result)
11571           return SEQ_MIXED;
11572
11573       return result;
11574
11575     case BT_CHARACTER:
11576       if (ts.kind != gfc_default_character_kind)
11577           return SEQ_NONDEFAULT;
11578
11579       return SEQ_CHARACTER;
11580
11581     case BT_INTEGER:
11582       if (ts.kind != gfc_default_integer_kind)
11583           return SEQ_NONDEFAULT;
11584
11585       return SEQ_NUMERIC;
11586
11587     case BT_REAL:
11588       if (!(ts.kind == gfc_default_real_kind
11589             || ts.kind == gfc_default_double_kind))
11590           return SEQ_NONDEFAULT;
11591
11592       return SEQ_NUMERIC;
11593
11594     case BT_COMPLEX:
11595       if (ts.kind != gfc_default_complex_kind)
11596           return SEQ_NONDEFAULT;
11597
11598       return SEQ_NUMERIC;
11599
11600     case BT_LOGICAL:
11601       if (ts.kind != gfc_default_logical_kind)
11602           return SEQ_NONDEFAULT;
11603
11604       return SEQ_NUMERIC;
11605
11606     default:
11607       return SEQ_NONDEFAULT;
11608   }
11609 }
11610
11611
11612 /* Resolve derived type EQUIVALENCE object.  */
11613
11614 static gfc_try
11615 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
11616 {
11617   gfc_component *c = derived->components;
11618
11619   if (!derived)
11620     return SUCCESS;
11621
11622   /* Shall not be an object of nonsequence derived type.  */
11623   if (!derived->attr.sequence)
11624     {
11625       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
11626                  "attribute to be an EQUIVALENCE object", sym->name,
11627                  &e->where);
11628       return FAILURE;
11629     }
11630
11631   /* Shall not have allocatable components.  */
11632   if (derived->attr.alloc_comp)
11633     {
11634       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
11635                  "components to be an EQUIVALENCE object",sym->name,
11636                  &e->where);
11637       return FAILURE;
11638     }
11639
11640   if (sym->attr.in_common && has_default_initializer (sym->ts.u.derived))
11641     {
11642       gfc_error ("Derived type variable '%s' at %L with default "
11643                  "initialization cannot be in EQUIVALENCE with a variable "
11644                  "in COMMON", sym->name, &e->where);
11645       return FAILURE;
11646     }
11647
11648   for (; c ; c = c->next)
11649     {
11650       if (c->ts.type == BT_DERIVED
11651           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
11652         return FAILURE;
11653
11654       /* Shall not be an object of sequence derived type containing a pointer
11655          in the structure.  */
11656       if (c->attr.pointer)
11657         {
11658           gfc_error ("Derived type variable '%s' at %L with pointer "
11659                      "component(s) cannot be an EQUIVALENCE object",
11660                      sym->name, &e->where);
11661           return FAILURE;
11662         }
11663     }
11664   return SUCCESS;
11665 }
11666
11667
11668 /* Resolve equivalence object. 
11669    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
11670    an allocatable array, an object of nonsequence derived type, an object of
11671    sequence derived type containing a pointer at any level of component
11672    selection, an automatic object, a function name, an entry name, a result
11673    name, a named constant, a structure component, or a subobject of any of
11674    the preceding objects.  A substring shall not have length zero.  A
11675    derived type shall not have components with default initialization nor
11676    shall two objects of an equivalence group be initialized.
11677    Either all or none of the objects shall have an protected attribute.
11678    The simple constraints are done in symbol.c(check_conflict) and the rest
11679    are implemented here.  */
11680
11681 static void
11682 resolve_equivalence (gfc_equiv *eq)
11683 {
11684   gfc_symbol *sym;
11685   gfc_symbol *first_sym;
11686   gfc_expr *e;
11687   gfc_ref *r;
11688   locus *last_where = NULL;
11689   seq_type eq_type, last_eq_type;
11690   gfc_typespec *last_ts;
11691   int object, cnt_protected;
11692   const char *value_name;
11693   const char *msg;
11694
11695   value_name = NULL;
11696   last_ts = &eq->expr->symtree->n.sym->ts;
11697
11698   first_sym = eq->expr->symtree->n.sym;
11699
11700   cnt_protected = 0;
11701
11702   for (object = 1; eq; eq = eq->eq, object++)
11703     {
11704       e = eq->expr;
11705
11706       e->ts = e->symtree->n.sym->ts;
11707       /* match_varspec might not know yet if it is seeing
11708          array reference or substring reference, as it doesn't
11709          know the types.  */
11710       if (e->ref && e->ref->type == REF_ARRAY)
11711         {
11712           gfc_ref *ref = e->ref;
11713           sym = e->symtree->n.sym;
11714
11715           if (sym->attr.dimension)
11716             {
11717               ref->u.ar.as = sym->as;
11718               ref = ref->next;
11719             }
11720
11721           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
11722           if (e->ts.type == BT_CHARACTER
11723               && ref
11724               && ref->type == REF_ARRAY
11725               && ref->u.ar.dimen == 1
11726               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
11727               && ref->u.ar.stride[0] == NULL)
11728             {
11729               gfc_expr *start = ref->u.ar.start[0];
11730               gfc_expr *end = ref->u.ar.end[0];
11731               void *mem = NULL;
11732
11733               /* Optimize away the (:) reference.  */
11734               if (start == NULL && end == NULL)
11735                 {
11736                   if (e->ref == ref)
11737                     e->ref = ref->next;
11738                   else
11739                     e->ref->next = ref->next;
11740                   mem = ref;
11741                 }
11742               else
11743                 {
11744                   ref->type = REF_SUBSTRING;
11745                   if (start == NULL)
11746                     start = gfc_int_expr (1);
11747                   ref->u.ss.start = start;
11748                   if (end == NULL && e->ts.u.cl)
11749                     end = gfc_copy_expr (e->ts.u.cl->length);
11750                   ref->u.ss.end = end;
11751                   ref->u.ss.length = e->ts.u.cl;
11752                   e->ts.u.cl = NULL;
11753                 }
11754               ref = ref->next;
11755               gfc_free (mem);
11756             }
11757
11758           /* Any further ref is an error.  */
11759           if (ref)
11760             {
11761               gcc_assert (ref->type == REF_ARRAY);
11762               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
11763                          &ref->u.ar.where);
11764               continue;
11765             }
11766         }
11767
11768       if (gfc_resolve_expr (e) == FAILURE)
11769         continue;
11770
11771       sym = e->symtree->n.sym;
11772
11773       if (sym->attr.is_protected)
11774         cnt_protected++;
11775       if (cnt_protected > 0 && cnt_protected != object)
11776         {
11777               gfc_error ("Either all or none of the objects in the "
11778                          "EQUIVALENCE set at %L shall have the "
11779                          "PROTECTED attribute",
11780                          &e->where);
11781               break;
11782         }
11783
11784       /* Shall not equivalence common block variables in a PURE procedure.  */
11785       if (sym->ns->proc_name
11786           && sym->ns->proc_name->attr.pure
11787           && sym->attr.in_common)
11788         {
11789           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
11790                      "object in the pure procedure '%s'",
11791                      sym->name, &e->where, sym->ns->proc_name->name);
11792           break;
11793         }
11794
11795       /* Shall not be a named constant.  */
11796       if (e->expr_type == EXPR_CONSTANT)
11797         {
11798           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
11799                      "object", sym->name, &e->where);
11800           continue;
11801         }
11802
11803       if (e->ts.type == BT_DERIVED
11804           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
11805         continue;
11806
11807       /* Check that the types correspond correctly:
11808          Note 5.28:
11809          A numeric sequence structure may be equivalenced to another sequence
11810          structure, an object of default integer type, default real type, double
11811          precision real type, default logical type such that components of the
11812          structure ultimately only become associated to objects of the same
11813          kind. A character sequence structure may be equivalenced to an object
11814          of default character kind or another character sequence structure.
11815          Other objects may be equivalenced only to objects of the same type and
11816          kind parameters.  */
11817
11818       /* Identical types are unconditionally OK.  */
11819       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
11820         goto identical_types;
11821
11822       last_eq_type = sequence_type (*last_ts);
11823       eq_type = sequence_type (sym->ts);
11824
11825       /* Since the pair of objects is not of the same type, mixed or
11826          non-default sequences can be rejected.  */
11827
11828       msg = "Sequence %s with mixed components in EQUIVALENCE "
11829             "statement at %L with different type objects";
11830       if ((object ==2
11831            && last_eq_type == SEQ_MIXED
11832            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
11833               == FAILURE)
11834           || (eq_type == SEQ_MIXED
11835               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
11836                                  &e->where) == FAILURE))
11837         continue;
11838
11839       msg = "Non-default type object or sequence %s in EQUIVALENCE "
11840             "statement at %L with objects of different type";
11841       if ((object ==2
11842            && last_eq_type == SEQ_NONDEFAULT
11843            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
11844                               last_where) == FAILURE)
11845           || (eq_type == SEQ_NONDEFAULT
11846               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
11847                                  &e->where) == FAILURE))
11848         continue;
11849
11850       msg ="Non-CHARACTER object '%s' in default CHARACTER "
11851            "EQUIVALENCE statement at %L";
11852       if (last_eq_type == SEQ_CHARACTER
11853           && eq_type != SEQ_CHARACTER
11854           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
11855                              &e->where) == FAILURE)
11856                 continue;
11857
11858       msg ="Non-NUMERIC object '%s' in default NUMERIC "
11859            "EQUIVALENCE statement at %L";
11860       if (last_eq_type == SEQ_NUMERIC
11861           && eq_type != SEQ_NUMERIC
11862           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
11863                              &e->where) == FAILURE)
11864                 continue;
11865
11866   identical_types:
11867       last_ts =&sym->ts;
11868       last_where = &e->where;
11869
11870       if (!e->ref)
11871         continue;
11872
11873       /* Shall not be an automatic array.  */
11874       if (e->ref->type == REF_ARRAY
11875           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
11876         {
11877           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
11878                      "an EQUIVALENCE object", sym->name, &e->where);
11879           continue;
11880         }
11881
11882       r = e->ref;
11883       while (r)
11884         {
11885           /* Shall not be a structure component.  */
11886           if (r->type == REF_COMPONENT)
11887             {
11888               gfc_error ("Structure component '%s' at %L cannot be an "
11889                          "EQUIVALENCE object",
11890                          r->u.c.component->name, &e->where);
11891               break;
11892             }
11893
11894           /* A substring shall not have length zero.  */
11895           if (r->type == REF_SUBSTRING)
11896             {
11897               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
11898                 {
11899                   gfc_error ("Substring at %L has length zero",
11900                              &r->u.ss.start->where);
11901                   break;
11902                 }
11903             }
11904           r = r->next;
11905         }
11906     }
11907 }
11908
11909
11910 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
11911
11912 static void
11913 resolve_fntype (gfc_namespace *ns)
11914 {
11915   gfc_entry_list *el;
11916   gfc_symbol *sym;
11917
11918   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
11919     return;
11920
11921   /* If there are any entries, ns->proc_name is the entry master
11922      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
11923   if (ns->entries)
11924     sym = ns->entries->sym;
11925   else
11926     sym = ns->proc_name;
11927   if (sym->result == sym
11928       && sym->ts.type == BT_UNKNOWN
11929       && gfc_set_default_type (sym, 0, NULL) == FAILURE
11930       && !sym->attr.untyped)
11931     {
11932       gfc_error ("Function '%s' at %L has no IMPLICIT type",
11933                  sym->name, &sym->declared_at);
11934       sym->attr.untyped = 1;
11935     }
11936
11937   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
11938       && !sym->attr.contained
11939       && !gfc_check_access (sym->ts.u.derived->attr.access,
11940                             sym->ts.u.derived->ns->default_access)
11941       && gfc_check_access (sym->attr.access, sym->ns->default_access))
11942     {
11943       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
11944                       "%L of PRIVATE type '%s'", sym->name,
11945                       &sym->declared_at, sym->ts.u.derived->name);
11946     }
11947
11948     if (ns->entries)
11949     for (el = ns->entries->next; el; el = el->next)
11950       {
11951         if (el->sym->result == el->sym
11952             && el->sym->ts.type == BT_UNKNOWN
11953             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
11954             && !el->sym->attr.untyped)
11955           {
11956             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
11957                        el->sym->name, &el->sym->declared_at);
11958             el->sym->attr.untyped = 1;
11959           }
11960       }
11961 }
11962
11963
11964 /* 12.3.2.1.1 Defined operators.  */
11965
11966 static gfc_try
11967 check_uop_procedure (gfc_symbol *sym, locus where)
11968 {
11969   gfc_formal_arglist *formal;
11970
11971   if (!sym->attr.function)
11972     {
11973       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
11974                  sym->name, &where);
11975       return FAILURE;
11976     }
11977
11978   if (sym->ts.type == BT_CHARACTER
11979       && !(sym->ts.u.cl && sym->ts.u.cl->length)
11980       && !(sym->result && sym->result->ts.u.cl
11981            && sym->result->ts.u.cl->length))
11982     {
11983       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
11984                  "character length", sym->name, &where);
11985       return FAILURE;
11986     }
11987
11988   formal = sym->formal;
11989   if (!formal || !formal->sym)
11990     {
11991       gfc_error ("User operator procedure '%s' at %L must have at least "
11992                  "one argument", sym->name, &where);
11993       return FAILURE;
11994     }
11995
11996   if (formal->sym->attr.intent != INTENT_IN)
11997     {
11998       gfc_error ("First argument of operator interface at %L must be "
11999                  "INTENT(IN)", &where);
12000       return FAILURE;
12001     }
12002
12003   if (formal->sym->attr.optional)
12004     {
12005       gfc_error ("First argument of operator interface at %L cannot be "
12006                  "optional", &where);
12007       return FAILURE;
12008     }
12009
12010   formal = formal->next;
12011   if (!formal || !formal->sym)
12012     return SUCCESS;
12013
12014   if (formal->sym->attr.intent != INTENT_IN)
12015     {
12016       gfc_error ("Second argument of operator interface at %L must be "
12017                  "INTENT(IN)", &where);
12018       return FAILURE;
12019     }
12020
12021   if (formal->sym->attr.optional)
12022     {
12023       gfc_error ("Second argument of operator interface at %L cannot be "
12024                  "optional", &where);
12025       return FAILURE;
12026     }
12027
12028   if (formal->next)
12029     {
12030       gfc_error ("Operator interface at %L must have, at most, two "
12031                  "arguments", &where);
12032       return FAILURE;
12033     }
12034
12035   return SUCCESS;
12036 }
12037
12038 static void
12039 gfc_resolve_uops (gfc_symtree *symtree)
12040 {
12041   gfc_interface *itr;
12042
12043   if (symtree == NULL)
12044     return;
12045
12046   gfc_resolve_uops (symtree->left);
12047   gfc_resolve_uops (symtree->right);
12048
12049   for (itr = symtree->n.uop->op; itr; itr = itr->next)
12050     check_uop_procedure (itr->sym, itr->sym->declared_at);
12051 }
12052
12053
12054 /* Examine all of the expressions associated with a program unit,
12055    assign types to all intermediate expressions, make sure that all
12056    assignments are to compatible types and figure out which names
12057    refer to which functions or subroutines.  It doesn't check code
12058    block, which is handled by resolve_code.  */
12059
12060 static void
12061 resolve_types (gfc_namespace *ns)
12062 {
12063   gfc_namespace *n;
12064   gfc_charlen *cl;
12065   gfc_data *d;
12066   gfc_equiv *eq;
12067   gfc_namespace* old_ns = gfc_current_ns;
12068
12069   /* Check that all IMPLICIT types are ok.  */
12070   if (!ns->seen_implicit_none)
12071     {
12072       unsigned letter;
12073       for (letter = 0; letter != GFC_LETTERS; ++letter)
12074         if (ns->set_flag[letter]
12075             && resolve_typespec_used (&ns->default_type[letter],
12076                                       &ns->implicit_loc[letter],
12077                                       NULL) == FAILURE)
12078           return;
12079     }
12080
12081   gfc_current_ns = ns;
12082
12083   resolve_entries (ns);
12084
12085   resolve_common_vars (ns->blank_common.head, false);
12086   resolve_common_blocks (ns->common_root);
12087
12088   resolve_contained_functions (ns);
12089
12090   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
12091
12092   for (cl = ns->cl_list; cl; cl = cl->next)
12093     resolve_charlen (cl);
12094
12095   gfc_traverse_ns (ns, resolve_symbol);
12096
12097   resolve_fntype (ns);
12098
12099   for (n = ns->contained; n; n = n->sibling)
12100     {
12101       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
12102         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
12103                    "also be PURE", n->proc_name->name,
12104                    &n->proc_name->declared_at);
12105
12106       resolve_types (n);
12107     }
12108
12109   forall_flag = 0;
12110   gfc_check_interfaces (ns);
12111
12112   gfc_traverse_ns (ns, resolve_values);
12113
12114   if (ns->save_all)
12115     gfc_save_all (ns);
12116
12117   iter_stack = NULL;
12118   for (d = ns->data; d; d = d->next)
12119     resolve_data (d);
12120
12121   iter_stack = NULL;
12122   gfc_traverse_ns (ns, gfc_formalize_init_value);
12123
12124   gfc_traverse_ns (ns, gfc_verify_binding_labels);
12125
12126   if (ns->common_root != NULL)
12127     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
12128
12129   for (eq = ns->equiv; eq; eq = eq->next)
12130     resolve_equivalence (eq);
12131
12132   /* Warn about unused labels.  */
12133   if (warn_unused_label)
12134     warn_unused_fortran_label (ns->st_labels);
12135
12136   gfc_resolve_uops (ns->uop_root);
12137
12138   gfc_current_ns = old_ns;
12139 }
12140
12141
12142 /* Call resolve_code recursively.  */
12143
12144 static void
12145 resolve_codes (gfc_namespace *ns)
12146 {
12147   gfc_namespace *n;
12148   bitmap_obstack old_obstack;
12149
12150   for (n = ns->contained; n; n = n->sibling)
12151     resolve_codes (n);
12152
12153   gfc_current_ns = ns;
12154
12155   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
12156   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
12157     cs_base = NULL;
12158
12159   /* Set to an out of range value.  */
12160   current_entry_id = -1;
12161
12162   old_obstack = labels_obstack;
12163   bitmap_obstack_initialize (&labels_obstack);
12164
12165   resolve_code (ns->code, ns);
12166
12167   bitmap_obstack_release (&labels_obstack);
12168   labels_obstack = old_obstack;
12169 }
12170
12171
12172 /* This function is called after a complete program unit has been compiled.
12173    Its purpose is to examine all of the expressions associated with a program
12174    unit, assign types to all intermediate expressions, make sure that all
12175    assignments are to compatible types and figure out which names refer to
12176    which functions or subroutines.  */
12177
12178 void
12179 gfc_resolve (gfc_namespace *ns)
12180 {
12181   gfc_namespace *old_ns;
12182   code_stack *old_cs_base;
12183
12184   if (ns->resolved)
12185     return;
12186
12187   ns->resolved = -1;
12188   old_ns = gfc_current_ns;
12189   old_cs_base = cs_base;
12190
12191   resolve_types (ns);
12192   resolve_codes (ns);
12193
12194   gfc_current_ns = old_ns;
12195   cs_base = old_cs_base;
12196   ns->resolved = 1;
12197 }