OSDN Git Service

2010-04-09 Tobias Burnus <burnus@net-b.de>
[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, 2010
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 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
81 static bool inquiry_argument = false;
82
83 int
84 gfc_is_formal_arg (void)
85 {
86   return formal_arg_flag;
87 }
88
89 /* Is the symbol host associated?  */
90 static bool
91 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
92 {
93   for (ns = ns->parent; ns; ns = ns->parent)
94     {      
95       if (sym->ns == ns)
96         return true;
97     }
98
99   return false;
100 }
101
102 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
103    an ABSTRACT derived-type.  If where is not NULL, an error message with that
104    locus is printed, optionally using name.  */
105
106 static gfc_try
107 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
108 {
109   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
110     {
111       if (where)
112         {
113           if (name)
114             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
115                        name, where, ts->u.derived->name);
116           else
117             gfc_error ("ABSTRACT type '%s' used at %L",
118                        ts->u.derived->name, where);
119         }
120
121       return FAILURE;
122     }
123
124   return SUCCESS;
125 }
126
127
128 /* Resolve types of formal argument lists.  These have to be done early so that
129    the formal argument lists of module procedures can be copied to the
130    containing module before the individual procedures are resolved
131    individually.  We also resolve argument lists of procedures in interface
132    blocks because they are self-contained scoping units.
133
134    Since a dummy argument cannot be a non-dummy procedure, the only
135    resort left for untyped names are the IMPLICIT types.  */
136
137 static void
138 resolve_formal_arglist (gfc_symbol *proc)
139 {
140   gfc_formal_arglist *f;
141   gfc_symbol *sym;
142   int i;
143
144   if (proc->result != NULL)
145     sym = proc->result;
146   else
147     sym = proc;
148
149   if (gfc_elemental (proc)
150       || sym->attr.pointer || sym->attr.allocatable
151       || (sym->as && sym->as->rank > 0))
152     {
153       proc->attr.always_explicit = 1;
154       sym->attr.always_explicit = 1;
155     }
156
157   formal_arg_flag = 1;
158
159   for (f = proc->formal; f; f = f->next)
160     {
161       sym = f->sym;
162
163       if (sym == NULL)
164         {
165           /* Alternate return placeholder.  */
166           if (gfc_elemental (proc))
167             gfc_error ("Alternate return specifier in elemental subroutine "
168                        "'%s' at %L is not allowed", proc->name,
169                        &proc->declared_at);
170           if (proc->attr.function)
171             gfc_error ("Alternate return specifier in function "
172                        "'%s' at %L is not allowed", proc->name,
173                        &proc->declared_at);
174           continue;
175         }
176
177       if (sym->attr.if_source != IFSRC_UNKNOWN)
178         resolve_formal_arglist (sym);
179
180       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
181         {
182           if (gfc_pure (proc) && !gfc_pure (sym))
183             {
184               gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
185                          "also be PURE", sym->name, &sym->declared_at);
186               continue;
187             }
188
189           if (gfc_elemental (proc))
190             {
191               gfc_error ("Dummy procedure at %L not allowed in ELEMENTAL "
192                          "procedure", &sym->declared_at);
193               continue;
194             }
195
196           if (sym->attr.function
197                 && sym->ts.type == BT_UNKNOWN
198                 && sym->attr.intrinsic)
199             {
200               gfc_intrinsic_sym *isym;
201               isym = gfc_find_function (sym->name);
202               if (isym == NULL || !isym->specific)
203                 {
204                   gfc_error ("Unable to find a specific INTRINSIC procedure "
205                              "for the reference '%s' at %L", sym->name,
206                              &sym->declared_at);
207                 }
208               sym->ts = isym->ts;
209             }
210
211           continue;
212         }
213
214       if (sym->ts.type == BT_UNKNOWN)
215         {
216           if (!sym->attr.function || sym->result == sym)
217             gfc_set_default_type (sym, 1, sym->ns);
218         }
219
220       gfc_resolve_array_spec (sym->as, 0);
221
222       /* We can't tell if an array with dimension (:) is assumed or deferred
223          shape until we know if it has the pointer or allocatable attributes.
224       */
225       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
226           && !(sym->attr.pointer || sym->attr.allocatable))
227         {
228           sym->as->type = AS_ASSUMED_SHAPE;
229           for (i = 0; i < sym->as->rank; i++)
230             sym->as->lower[i] = gfc_int_expr (1);
231         }
232
233       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
234           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
235           || sym->attr.optional)
236         {
237           proc->attr.always_explicit = 1;
238           if (proc->result)
239             proc->result->attr.always_explicit = 1;
240         }
241
242       /* If the flavor is unknown at this point, it has to be a variable.
243          A procedure specification would have already set the type.  */
244
245       if (sym->attr.flavor == FL_UNKNOWN)
246         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
247
248       if (gfc_pure (proc) && !sym->attr.pointer
249           && sym->attr.flavor != FL_PROCEDURE)
250         {
251           if (proc->attr.function && sym->attr.intent != INTENT_IN)
252             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
253                        "INTENT(IN)", sym->name, proc->name,
254                        &sym->declared_at);
255
256           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
257             gfc_error ("Argument '%s' of pure subroutine '%s' at %L must "
258                        "have its INTENT specified", sym->name, proc->name,
259                        &sym->declared_at);
260         }
261
262       if (gfc_elemental (proc))
263         {
264           /* F2008, C1289.  */
265           if (sym->attr.codimension)
266             {
267               gfc_error ("Coarray dummy argument '%s' at %L to elemental "
268                          "procedure", sym->name, &sym->declared_at);
269               continue;
270             }
271
272           if (sym->as != NULL)
273             {
274               gfc_error ("Argument '%s' of elemental procedure at %L must "
275                          "be scalar", sym->name, &sym->declared_at);
276               continue;
277             }
278
279           if (sym->attr.pointer)
280             {
281               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
282                          "have the POINTER attribute", sym->name,
283                          &sym->declared_at);
284               continue;
285             }
286
287           if (sym->attr.flavor == FL_PROCEDURE)
288             {
289               gfc_error ("Dummy procedure '%s' not allowed in elemental "
290                          "procedure '%s' at %L", sym->name, proc->name,
291                          &sym->declared_at);
292               continue;
293             }
294         }
295
296       /* Each dummy shall be specified to be scalar.  */
297       if (proc->attr.proc == PROC_ST_FUNCTION)
298         {
299           if (sym->as != NULL)
300             {
301               gfc_error ("Argument '%s' of statement function at %L must "
302                          "be scalar", sym->name, &sym->declared_at);
303               continue;
304             }
305
306           if (sym->ts.type == BT_CHARACTER)
307             {
308               gfc_charlen *cl = sym->ts.u.cl;
309               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
310                 {
311                   gfc_error ("Character-valued argument '%s' of statement "
312                              "function at %L must have constant length",
313                              sym->name, &sym->declared_at);
314                   continue;
315                 }
316             }
317         }
318     }
319   formal_arg_flag = 0;
320 }
321
322
323 /* Work function called when searching for symbols that have argument lists
324    associated with them.  */
325
326 static void
327 find_arglists (gfc_symbol *sym)
328 {
329   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
330     return;
331
332   resolve_formal_arglist (sym);
333 }
334
335
336 /* Given a namespace, resolve all formal argument lists within the namespace.
337  */
338
339 static void
340 resolve_formal_arglists (gfc_namespace *ns)
341 {
342   if (ns == NULL)
343     return;
344
345   gfc_traverse_ns (ns, find_arglists);
346 }
347
348
349 static void
350 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
351 {
352   gfc_try t;
353
354   /* If this namespace is not a function or an entry master function,
355      ignore it.  */
356   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
357       || sym->attr.entry_master)
358     return;
359
360   /* Try to find out of what the return type is.  */
361   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
362     {
363       t = gfc_set_default_type (sym->result, 0, ns);
364
365       if (t == FAILURE && !sym->result->attr.untyped)
366         {
367           if (sym->result == sym)
368             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
369                        sym->name, &sym->declared_at);
370           else if (!sym->result->attr.proc_pointer)
371             gfc_error ("Result '%s' of contained function '%s' at %L has "
372                        "no IMPLICIT type", sym->result->name, sym->name,
373                        &sym->result->declared_at);
374           sym->result->attr.untyped = 1;
375         }
376     }
377
378   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character 
379      type, lists the only ways a character length value of * can be used:
380      dummy arguments of procedures, named constants, and function results
381      in external functions.  Internal function results and results of module
382      procedures are not on this list, ergo, not permitted.  */
383
384   if (sym->result->ts.type == BT_CHARACTER)
385     {
386       gfc_charlen *cl = sym->result->ts.u.cl;
387       if (!cl || !cl->length)
388         {
389           /* See if this is a module-procedure and adapt error message
390              accordingly.  */
391           bool module_proc;
392           gcc_assert (ns->parent && ns->parent->proc_name);
393           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
394
395           gfc_error ("Character-valued %s '%s' at %L must not be"
396                      " assumed length",
397                      module_proc ? _("module procedure")
398                                  : _("internal function"),
399                      sym->name, &sym->declared_at);
400         }
401     }
402 }
403
404
405 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
406    introduce duplicates.  */
407
408 static void
409 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
410 {
411   gfc_formal_arglist *f, *new_arglist;
412   gfc_symbol *new_sym;
413
414   for (; new_args != NULL; new_args = new_args->next)
415     {
416       new_sym = new_args->sym;
417       /* See if this arg is already in the formal argument list.  */
418       for (f = proc->formal; f; f = f->next)
419         {
420           if (new_sym == f->sym)
421             break;
422         }
423
424       if (f)
425         continue;
426
427       /* Add a new argument.  Argument order is not important.  */
428       new_arglist = gfc_get_formal_arglist ();
429       new_arglist->sym = new_sym;
430       new_arglist->next = proc->formal;
431       proc->formal  = new_arglist;
432     }
433 }
434
435
436 /* Flag the arguments that are not present in all entries.  */
437
438 static void
439 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
440 {
441   gfc_formal_arglist *f, *head;
442   head = new_args;
443
444   for (f = proc->formal; f; f = f->next)
445     {
446       if (f->sym == NULL)
447         continue;
448
449       for (new_args = head; new_args; new_args = new_args->next)
450         {
451           if (new_args->sym == f->sym)
452             break;
453         }
454
455       if (new_args)
456         continue;
457
458       f->sym->attr.not_always_present = 1;
459     }
460 }
461
462
463 /* Resolve alternate entry points.  If a symbol has multiple entry points we
464    create a new master symbol for the main routine, and turn the existing
465    symbol into an entry point.  */
466
467 static void
468 resolve_entries (gfc_namespace *ns)
469 {
470   gfc_namespace *old_ns;
471   gfc_code *c;
472   gfc_symbol *proc;
473   gfc_entry_list *el;
474   char name[GFC_MAX_SYMBOL_LEN + 1];
475   static int master_count = 0;
476
477   if (ns->proc_name == NULL)
478     return;
479
480   /* No need to do anything if this procedure doesn't have alternate entry
481      points.  */
482   if (!ns->entries)
483     return;
484
485   /* We may already have resolved alternate entry points.  */
486   if (ns->proc_name->attr.entry_master)
487     return;
488
489   /* If this isn't a procedure something has gone horribly wrong.  */
490   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
491
492   /* Remember the current namespace.  */
493   old_ns = gfc_current_ns;
494
495   gfc_current_ns = ns;
496
497   /* Add the main entry point to the list of entry points.  */
498   el = gfc_get_entry_list ();
499   el->sym = ns->proc_name;
500   el->id = 0;
501   el->next = ns->entries;
502   ns->entries = el;
503   ns->proc_name->attr.entry = 1;
504
505   /* If it is a module function, it needs to be in the right namespace
506      so that gfc_get_fake_result_decl can gather up the results. The
507      need for this arose in get_proc_name, where these beasts were
508      left in their own namespace, to keep prior references linked to
509      the entry declaration.*/
510   if (ns->proc_name->attr.function
511       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
512     el->sym->ns = ns;
513
514   /* Do the same for entries where the master is not a module
515      procedure.  These are retained in the module namespace because
516      of the module procedure declaration.  */
517   for (el = el->next; el; el = el->next)
518     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
519           && el->sym->attr.mod_proc)
520       el->sym->ns = ns;
521   el = ns->entries;
522
523   /* Add an entry statement for it.  */
524   c = gfc_get_code ();
525   c->op = EXEC_ENTRY;
526   c->ext.entry = el;
527   c->next = ns->code;
528   ns->code = c;
529
530   /* Create a new symbol for the master function.  */
531   /* Give the internal function a unique name (within this file).
532      Also include the function name so the user has some hope of figuring
533      out what is going on.  */
534   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
535             master_count++, ns->proc_name->name);
536   gfc_get_ha_symbol (name, &proc);
537   gcc_assert (proc != NULL);
538
539   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
540   if (ns->proc_name->attr.subroutine)
541     gfc_add_subroutine (&proc->attr, proc->name, NULL);
542   else
543     {
544       gfc_symbol *sym;
545       gfc_typespec *ts, *fts;
546       gfc_array_spec *as, *fas;
547       gfc_add_function (&proc->attr, proc->name, NULL);
548       proc->result = proc;
549       fas = ns->entries->sym->as;
550       fas = fas ? fas : ns->entries->sym->result->as;
551       fts = &ns->entries->sym->result->ts;
552       if (fts->type == BT_UNKNOWN)
553         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
554       for (el = ns->entries->next; el; el = el->next)
555         {
556           ts = &el->sym->result->ts;
557           as = el->sym->as;
558           as = as ? as : el->sym->result->as;
559           if (ts->type == BT_UNKNOWN)
560             ts = gfc_get_default_type (el->sym->result->name, NULL);
561
562           if (! gfc_compare_types (ts, fts)
563               || (el->sym->result->attr.dimension
564                   != ns->entries->sym->result->attr.dimension)
565               || (el->sym->result->attr.pointer
566                   != ns->entries->sym->result->attr.pointer))
567             break;
568           else if (as && fas && ns->entries->sym->result != el->sym->result
569                       && gfc_compare_array_spec (as, fas) == 0)
570             gfc_error ("Function %s at %L has entries with mismatched "
571                        "array specifications", ns->entries->sym->name,
572                        &ns->entries->sym->declared_at);
573           /* The characteristics need to match and thus both need to have
574              the same string length, i.e. both len=*, or both len=4.
575              Having both len=<variable> is also possible, but difficult to
576              check at compile time.  */
577           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
578                    && (((ts->u.cl->length && !fts->u.cl->length)
579                         ||(!ts->u.cl->length && fts->u.cl->length))
580                        || (ts->u.cl->length
581                            && ts->u.cl->length->expr_type
582                               != fts->u.cl->length->expr_type)
583                        || (ts->u.cl->length
584                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
585                            && mpz_cmp (ts->u.cl->length->value.integer,
586                                        fts->u.cl->length->value.integer) != 0)))
587             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
588                             "entries returning variables of different "
589                             "string lengths", ns->entries->sym->name,
590                             &ns->entries->sym->declared_at);
591         }
592
593       if (el == NULL)
594         {
595           sym = ns->entries->sym->result;
596           /* All result types the same.  */
597           proc->ts = *fts;
598           if (sym->attr.dimension)
599             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
600           if (sym->attr.pointer)
601             gfc_add_pointer (&proc->attr, NULL);
602         }
603       else
604         {
605           /* Otherwise the result will be passed through a union by
606              reference.  */
607           proc->attr.mixed_entry_master = 1;
608           for (el = ns->entries; el; el = el->next)
609             {
610               sym = el->sym->result;
611               if (sym->attr.dimension)
612                 {
613                   if (el == ns->entries)
614                     gfc_error ("FUNCTION result %s can't be an array 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 an array in "
619                                "FUNCTION %s at %L", sym->name,
620                                ns->entries->sym->name, &sym->declared_at);
621                 }
622               else if (sym->attr.pointer)
623                 {
624                   if (el == ns->entries)
625                     gfc_error ("FUNCTION result %s can't be a POINTER in "
626                                "FUNCTION %s at %L", sym->name,
627                                ns->entries->sym->name, &sym->declared_at);
628                   else
629                     gfc_error ("ENTRY result %s can't be a POINTER in "
630                                "FUNCTION %s at %L", sym->name,
631                                ns->entries->sym->name, &sym->declared_at);
632                 }
633               else
634                 {
635                   ts = &sym->ts;
636                   if (ts->type == BT_UNKNOWN)
637                     ts = gfc_get_default_type (sym->name, NULL);
638                   switch (ts->type)
639                     {
640                     case BT_INTEGER:
641                       if (ts->kind == gfc_default_integer_kind)
642                         sym = NULL;
643                       break;
644                     case BT_REAL:
645                       if (ts->kind == gfc_default_real_kind
646                           || ts->kind == gfc_default_double_kind)
647                         sym = NULL;
648                       break;
649                     case BT_COMPLEX:
650                       if (ts->kind == gfc_default_complex_kind)
651                         sym = NULL;
652                       break;
653                     case BT_LOGICAL:
654                       if (ts->kind == gfc_default_logical_kind)
655                         sym = NULL;
656                       break;
657                     case BT_UNKNOWN:
658                       /* We will issue error elsewhere.  */
659                       sym = NULL;
660                       break;
661                     default:
662                       break;
663                     }
664                   if (sym)
665                     {
666                       if (el == ns->entries)
667                         gfc_error ("FUNCTION result %s can't be of type %s "
668                                    "in FUNCTION %s at %L", sym->name,
669                                    gfc_typename (ts), ns->entries->sym->name,
670                                    &sym->declared_at);
671                       else
672                         gfc_error ("ENTRY result %s can't be of type %s "
673                                    "in FUNCTION %s at %L", sym->name,
674                                    gfc_typename (ts), ns->entries->sym->name,
675                                    &sym->declared_at);
676                     }
677                 }
678             }
679         }
680     }
681   proc->attr.access = ACCESS_PRIVATE;
682   proc->attr.entry_master = 1;
683
684   /* Merge all the entry point arguments.  */
685   for (el = ns->entries; el; el = el->next)
686     merge_argument_lists (proc, el->sym->formal);
687
688   /* Check the master formal arguments for any that are not
689      present in all entry points.  */
690   for (el = ns->entries; el; el = el->next)
691     check_argument_lists (proc, el->sym->formal);
692
693   /* Use the master function for the function body.  */
694   ns->proc_name = proc;
695
696   /* Finalize the new symbols.  */
697   gfc_commit_symbols ();
698
699   /* Restore the original namespace.  */
700   gfc_current_ns = old_ns;
701 }
702
703
704 static bool
705 has_default_initializer (gfc_symbol *der)
706 {
707   gfc_component *c;
708
709   gcc_assert (der->attr.flavor == FL_DERIVED);
710   for (c = der->components; c; c = c->next)
711     if ((c->ts.type != BT_DERIVED && c->initializer)
712         || (c->ts.type == BT_DERIVED
713             && (!c->attr.pointer && has_default_initializer (c->ts.u.derived))))
714       break;
715
716   return c != NULL;
717 }
718
719 /* Resolve common variables.  */
720 static void
721 resolve_common_vars (gfc_symbol *sym, bool named_common)
722 {
723   gfc_symbol *csym = sym;
724
725   for (; csym; csym = csym->common_next)
726     {
727       if (csym->value || csym->attr.data)
728         {
729           if (!csym->ns->is_block_data)
730             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
731                             "but only in BLOCK DATA initialization is "
732                             "allowed", csym->name, &csym->declared_at);
733           else if (!named_common)
734             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
735                             "in a blank COMMON but initialization is only "
736                             "allowed in named common blocks", csym->name,
737                             &csym->declared_at);
738         }
739
740       if (csym->ts.type != BT_DERIVED)
741         continue;
742
743       if (!(csym->ts.u.derived->attr.sequence
744             || csym->ts.u.derived->attr.is_bind_c))
745         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
746                        "has neither the SEQUENCE nor the BIND(C) "
747                        "attribute", csym->name, &csym->declared_at);
748       if (csym->ts.u.derived->attr.alloc_comp)
749         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
750                        "has an ultimate component that is "
751                        "allocatable", csym->name, &csym->declared_at);
752       if (has_default_initializer (csym->ts.u.derived))
753         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
754                        "may not have default initializer", csym->name,
755                        &csym->declared_at);
756
757       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
758         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
759     }
760 }
761
762 /* Resolve common blocks.  */
763 static void
764 resolve_common_blocks (gfc_symtree *common_root)
765 {
766   gfc_symbol *sym;
767
768   if (common_root == NULL)
769     return;
770
771   if (common_root->left)
772     resolve_common_blocks (common_root->left);
773   if (common_root->right)
774     resolve_common_blocks (common_root->right);
775
776   resolve_common_vars (common_root->n.common->head, true);
777
778   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
779   if (sym == NULL)
780     return;
781
782   if (sym->attr.flavor == FL_PARAMETER)
783     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
784                sym->name, &common_root->n.common->where, &sym->declared_at);
785
786   if (sym->attr.intrinsic)
787     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
788                sym->name, &common_root->n.common->where);
789   else if (sym->attr.result
790            || gfc_is_function_return_value (sym, gfc_current_ns))
791     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
792                     "that is also a function result", sym->name,
793                     &common_root->n.common->where);
794   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
795            && sym->attr.proc != PROC_ST_FUNCTION)
796     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
797                     "that is also a global procedure", sym->name,
798                     &common_root->n.common->where);
799 }
800
801
802 /* Resolve contained function types.  Because contained functions can call one
803    another, they have to be worked out before any of the contained procedures
804    can be resolved.
805
806    The good news is that if a function doesn't already have a type, the only
807    way it can get one is through an IMPLICIT type or a RESULT variable, because
808    by definition contained functions are contained namespace they're contained
809    in, not in a sibling or parent namespace.  */
810
811 static void
812 resolve_contained_functions (gfc_namespace *ns)
813 {
814   gfc_namespace *child;
815   gfc_entry_list *el;
816
817   resolve_formal_arglists (ns);
818
819   for (child = ns->contained; child; child = child->sibling)
820     {
821       /* Resolve alternate entry points first.  */
822       resolve_entries (child);
823
824       /* Then check function return types.  */
825       resolve_contained_fntype (child->proc_name, child);
826       for (el = child->entries; el; el = el->next)
827         resolve_contained_fntype (el->sym, child);
828     }
829 }
830
831
832 /* Resolve all of the elements of a structure constructor and make sure that
833    the types are correct.  */
834
835 static gfc_try
836 resolve_structure_cons (gfc_expr *expr)
837 {
838   gfc_constructor *cons;
839   gfc_component *comp;
840   gfc_try t;
841   symbol_attribute a;
842
843   t = SUCCESS;
844   cons = expr->value.constructor;
845   /* A constructor may have references if it is the result of substituting a
846      parameter variable.  In this case we just pull out the component we
847      want.  */
848   if (expr->ref)
849     comp = expr->ref->u.c.sym->components;
850   else
851     comp = expr->ts.u.derived->components;
852
853   /* See if the user is trying to invoke a structure constructor for one of
854      the iso_c_binding derived types.  */
855   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
856       && expr->ts.u.derived->ts.is_iso_c && cons
857       && (cons->expr == NULL || cons->expr->expr_type != EXPR_NULL))
858     {
859       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
860                  expr->ts.u.derived->name, &(expr->where));
861       return FAILURE;
862     }
863
864   /* Return if structure constructor is c_null_(fun)prt.  */
865   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
866       && expr->ts.u.derived->ts.is_iso_c && cons
867       && cons->expr && cons->expr->expr_type == EXPR_NULL)
868     return SUCCESS;
869
870   for (; comp; comp = comp->next, cons = cons->next)
871     {
872       int rank;
873
874       if (!cons->expr)
875         continue;
876
877       if (gfc_resolve_expr (cons->expr) == FAILURE)
878         {
879           t = FAILURE;
880           continue;
881         }
882
883       rank = comp->as ? comp->as->rank : 0;
884       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
885           && (comp->attr.allocatable || cons->expr->rank))
886         {
887           gfc_error ("The rank of the element in the derived type "
888                      "constructor at %L does not match that of the "
889                      "component (%d/%d)", &cons->expr->where,
890                      cons->expr->rank, rank);
891           t = FAILURE;
892         }
893
894       /* If we don't have the right type, try to convert it.  */
895
896       if (!gfc_compare_types (&cons->expr->ts, &comp->ts))
897         {
898           t = FAILURE;
899           if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
900             gfc_error ("The element in the derived type constructor at %L, "
901                        "for pointer component '%s', is %s but should be %s",
902                        &cons->expr->where, comp->name,
903                        gfc_basic_typename (cons->expr->ts.type),
904                        gfc_basic_typename (comp->ts.type));
905           else
906             t = gfc_convert_type (cons->expr, &comp->ts, 1);
907         }
908
909       if (cons->expr->expr_type == EXPR_NULL
910           && !(comp->attr.pointer || comp->attr.allocatable
911                || comp->attr.proc_pointer
912                || (comp->ts.type == BT_CLASS
913                    && (comp->ts.u.derived->components->attr.pointer
914                        || comp->ts.u.derived->components->attr.allocatable))))
915         {
916           t = FAILURE;
917           gfc_error ("The NULL in the derived type constructor at %L is "
918                      "being applied to component '%s', which is neither "
919                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
920                      comp->name);
921         }
922
923       if (!comp->attr.pointer || cons->expr->expr_type == EXPR_NULL)
924         continue;
925
926       a = gfc_expr_attr (cons->expr);
927
928       if (!a.pointer && !a.target)
929         {
930           t = FAILURE;
931           gfc_error ("The element in the derived type constructor at %L, "
932                      "for pointer component '%s' should be a POINTER or "
933                      "a TARGET", &cons->expr->where, comp->name);
934         }
935
936       /* F2003, C1272 (3).  */
937       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
938           && (gfc_impure_variable (cons->expr->symtree->n.sym)
939               || gfc_is_coindexed (cons->expr)))
940         {
941           t = FAILURE;
942           gfc_error ("Invalid expression in the derived type constructor for "
943                      "pointer component '%s' at %L in PURE procedure",
944                      comp->name, &cons->expr->where);
945         }
946     }
947
948   return t;
949 }
950
951
952 /****************** Expression name resolution ******************/
953
954 /* Returns 0 if a symbol was not declared with a type or
955    attribute declaration statement, nonzero otherwise.  */
956
957 static int
958 was_declared (gfc_symbol *sym)
959 {
960   symbol_attribute a;
961
962   a = sym->attr;
963
964   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
965     return 1;
966
967   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
968       || a.optional || a.pointer || a.save || a.target || a.volatile_
969       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
970       || a.asynchronous || a.codimension)
971     return 1;
972
973   return 0;
974 }
975
976
977 /* Determine if a symbol is generic or not.  */
978
979 static int
980 generic_sym (gfc_symbol *sym)
981 {
982   gfc_symbol *s;
983
984   if (sym->attr.generic ||
985       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
986     return 1;
987
988   if (was_declared (sym) || sym->ns->parent == NULL)
989     return 0;
990
991   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
992   
993   if (s != NULL)
994     {
995       if (s == sym)
996         return 0;
997       else
998         return generic_sym (s);
999     }
1000
1001   return 0;
1002 }
1003
1004
1005 /* Determine if a symbol is specific or not.  */
1006
1007 static int
1008 specific_sym (gfc_symbol *sym)
1009 {
1010   gfc_symbol *s;
1011
1012   if (sym->attr.if_source == IFSRC_IFBODY
1013       || sym->attr.proc == PROC_MODULE
1014       || sym->attr.proc == PROC_INTERNAL
1015       || sym->attr.proc == PROC_ST_FUNCTION
1016       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1017       || sym->attr.external)
1018     return 1;
1019
1020   if (was_declared (sym) || sym->ns->parent == NULL)
1021     return 0;
1022
1023   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1024
1025   return (s == NULL) ? 0 : specific_sym (s);
1026 }
1027
1028
1029 /* Figure out if the procedure is specific, generic or unknown.  */
1030
1031 typedef enum
1032 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1033 proc_type;
1034
1035 static proc_type
1036 procedure_kind (gfc_symbol *sym)
1037 {
1038   if (generic_sym (sym))
1039     return PTYPE_GENERIC;
1040
1041   if (specific_sym (sym))
1042     return PTYPE_SPECIFIC;
1043
1044   return PTYPE_UNKNOWN;
1045 }
1046
1047 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1048    is nonzero when matching actual arguments.  */
1049
1050 static int need_full_assumed_size = 0;
1051
1052 static bool
1053 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1054 {
1055   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1056       return false;
1057
1058   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1059      What should it be?  */
1060   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1061           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1062                && (e->ref->u.ar.type == AR_FULL))
1063     {
1064       gfc_error ("The upper bound in the last dimension must "
1065                  "appear in the reference to the assumed size "
1066                  "array '%s' at %L", sym->name, &e->where);
1067       return true;
1068     }
1069   return false;
1070 }
1071
1072
1073 /* Look for bad assumed size array references in argument expressions
1074   of elemental and array valued intrinsic procedures.  Since this is
1075   called from procedure resolution functions, it only recurses at
1076   operators.  */
1077
1078 static bool
1079 resolve_assumed_size_actual (gfc_expr *e)
1080 {
1081   if (e == NULL)
1082    return false;
1083
1084   switch (e->expr_type)
1085     {
1086     case EXPR_VARIABLE:
1087       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1088         return true;
1089       break;
1090
1091     case EXPR_OP:
1092       if (resolve_assumed_size_actual (e->value.op.op1)
1093           || resolve_assumed_size_actual (e->value.op.op2))
1094         return true;
1095       break;
1096
1097     default:
1098       break;
1099     }
1100   return false;
1101 }
1102
1103
1104 /* Check a generic procedure, passed as an actual argument, to see if
1105    there is a matching specific name.  If none, it is an error, and if
1106    more than one, the reference is ambiguous.  */
1107 static int
1108 count_specific_procs (gfc_expr *e)
1109 {
1110   int n;
1111   gfc_interface *p;
1112   gfc_symbol *sym;
1113         
1114   n = 0;
1115   sym = e->symtree->n.sym;
1116
1117   for (p = sym->generic; p; p = p->next)
1118     if (strcmp (sym->name, p->sym->name) == 0)
1119       {
1120         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1121                                        sym->name);
1122         n++;
1123       }
1124
1125   if (n > 1)
1126     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1127                &e->where);
1128
1129   if (n == 0)
1130     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1131                "argument at %L", sym->name, &e->where);
1132
1133   return n;
1134 }
1135
1136
1137 /* See if a call to sym could possibly be a not allowed RECURSION because of
1138    a missing RECURIVE declaration.  This means that either sym is the current
1139    context itself, or sym is the parent of a contained procedure calling its
1140    non-RECURSIVE containing procedure.
1141    This also works if sym is an ENTRY.  */
1142
1143 static bool
1144 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1145 {
1146   gfc_symbol* proc_sym;
1147   gfc_symbol* context_proc;
1148   gfc_namespace* real_context;
1149
1150   if (sym->attr.flavor == FL_PROGRAM)
1151     return false;
1152
1153   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1154
1155   /* If we've got an ENTRY, find real procedure.  */
1156   if (sym->attr.entry && sym->ns->entries)
1157     proc_sym = sym->ns->entries->sym;
1158   else
1159     proc_sym = sym;
1160
1161   /* If sym is RECURSIVE, all is well of course.  */
1162   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1163     return false;
1164
1165   /* Find the context procedure's "real" symbol if it has entries.
1166      We look for a procedure symbol, so recurse on the parents if we don't
1167      find one (like in case of a BLOCK construct).  */
1168   for (real_context = context; ; real_context = real_context->parent)
1169     {
1170       /* We should find something, eventually!  */
1171       gcc_assert (real_context);
1172
1173       context_proc = (real_context->entries ? real_context->entries->sym
1174                                             : real_context->proc_name);
1175
1176       /* In some special cases, there may not be a proc_name, like for this
1177          invalid code:
1178          real(bad_kind()) function foo () ...
1179          when checking the call to bad_kind ().
1180          In these cases, we simply return here and assume that the
1181          call is ok.  */
1182       if (!context_proc)
1183         return false;
1184
1185       if (context_proc->attr.flavor != FL_LABEL)
1186         break;
1187     }
1188
1189   /* A call from sym's body to itself is recursion, of course.  */
1190   if (context_proc == proc_sym)
1191     return true;
1192
1193   /* The same is true if context is a contained procedure and sym the
1194      containing one.  */
1195   if (context_proc->attr.contained)
1196     {
1197       gfc_symbol* parent_proc;
1198
1199       gcc_assert (context->parent);
1200       parent_proc = (context->parent->entries ? context->parent->entries->sym
1201                                               : context->parent->proc_name);
1202
1203       if (parent_proc == proc_sym)
1204         return true;
1205     }
1206
1207   return false;
1208 }
1209
1210
1211 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1212    its typespec and formal argument list.  */
1213
1214 static gfc_try
1215 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1216 {
1217   gfc_intrinsic_sym* isym;
1218   const char* symstd;
1219
1220   if (sym->formal)
1221     return SUCCESS;
1222
1223   /* We already know this one is an intrinsic, so we don't call
1224      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1225      gfc_find_subroutine directly to check whether it is a function or
1226      subroutine.  */
1227
1228   if ((isym = gfc_find_function (sym->name)))
1229     {
1230       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1231           && !sym->attr.implicit_type)
1232         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1233                       " ignored", sym->name, &sym->declared_at);
1234
1235       if (!sym->attr.function &&
1236           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1237         return FAILURE;
1238
1239       sym->ts = isym->ts;
1240     }
1241   else if ((isym = gfc_find_subroutine (sym->name)))
1242     {
1243       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1244         {
1245           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1246                       " specifier", sym->name, &sym->declared_at);
1247           return FAILURE;
1248         }
1249
1250       if (!sym->attr.subroutine &&
1251           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1252         return FAILURE;
1253     }
1254   else
1255     {
1256       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1257                  &sym->declared_at);
1258       return FAILURE;
1259     }
1260
1261   gfc_copy_formal_args_intr (sym, isym);
1262
1263   /* Check it is actually available in the standard settings.  */
1264   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1265       == FAILURE)
1266     {
1267       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1268                  " available in the current standard settings but %s.  Use"
1269                  " an appropriate -std=* option or enable -fall-intrinsics"
1270                  " in order to use it.",
1271                  sym->name, &sym->declared_at, symstd);
1272       return FAILURE;
1273     }
1274
1275   return SUCCESS;
1276 }
1277
1278
1279 /* Resolve a procedure expression, like passing it to a called procedure or as
1280    RHS for a procedure pointer assignment.  */
1281
1282 static gfc_try
1283 resolve_procedure_expression (gfc_expr* expr)
1284 {
1285   gfc_symbol* sym;
1286
1287   if (expr->expr_type != EXPR_VARIABLE)
1288     return SUCCESS;
1289   gcc_assert (expr->symtree);
1290
1291   sym = expr->symtree->n.sym;
1292
1293   if (sym->attr.intrinsic)
1294     resolve_intrinsic (sym, &expr->where);
1295
1296   if (sym->attr.flavor != FL_PROCEDURE
1297       || (sym->attr.function && sym->result == sym))
1298     return SUCCESS;
1299
1300   /* A non-RECURSIVE procedure that is used as procedure expression within its
1301      own body is in danger of being called recursively.  */
1302   if (is_illegal_recursion (sym, gfc_current_ns))
1303     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1304                  " itself recursively.  Declare it RECURSIVE or use"
1305                  " -frecursive", sym->name, &expr->where);
1306   
1307   return SUCCESS;
1308 }
1309
1310
1311 /* Resolve an actual argument list.  Most of the time, this is just
1312    resolving the expressions in the list.
1313    The exception is that we sometimes have to decide whether arguments
1314    that look like procedure arguments are really simple variable
1315    references.  */
1316
1317 static gfc_try
1318 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1319                         bool no_formal_args)
1320 {
1321   gfc_symbol *sym;
1322   gfc_symtree *parent_st;
1323   gfc_expr *e;
1324   int save_need_full_assumed_size;
1325   gfc_component *comp;
1326
1327   for (; arg; arg = arg->next)
1328     {
1329       e = arg->expr;
1330       if (e == NULL)
1331         {
1332           /* Check the label is a valid branching target.  */
1333           if (arg->label)
1334             {
1335               if (arg->label->defined == ST_LABEL_UNKNOWN)
1336                 {
1337                   gfc_error ("Label %d referenced at %L is never defined",
1338                              arg->label->value, &arg->label->where);
1339                   return FAILURE;
1340                 }
1341             }
1342           continue;
1343         }
1344
1345       if (gfc_is_proc_ptr_comp (e, &comp))
1346         {
1347           e->ts = comp->ts;
1348           if (e->expr_type == EXPR_PPC)
1349             {
1350               if (comp->as != NULL)
1351                 e->rank = comp->as->rank;
1352               e->expr_type = EXPR_FUNCTION;
1353             }
1354           if (gfc_resolve_expr (e) == FAILURE)                          
1355             return FAILURE; 
1356           goto argument_list;
1357         }
1358
1359       if (e->expr_type == EXPR_VARIABLE
1360             && e->symtree->n.sym->attr.generic
1361             && no_formal_args
1362             && count_specific_procs (e) != 1)
1363         return FAILURE;
1364
1365       if (e->ts.type != BT_PROCEDURE)
1366         {
1367           save_need_full_assumed_size = need_full_assumed_size;
1368           if (e->expr_type != EXPR_VARIABLE)
1369             need_full_assumed_size = 0;
1370           if (gfc_resolve_expr (e) != SUCCESS)
1371             return FAILURE;
1372           need_full_assumed_size = save_need_full_assumed_size;
1373           goto argument_list;
1374         }
1375
1376       /* See if the expression node should really be a variable reference.  */
1377
1378       sym = e->symtree->n.sym;
1379
1380       if (sym->attr.flavor == FL_PROCEDURE
1381           || sym->attr.intrinsic
1382           || sym->attr.external)
1383         {
1384           int actual_ok;
1385
1386           /* If a procedure is not already determined to be something else
1387              check if it is intrinsic.  */
1388           if (!sym->attr.intrinsic
1389               && !(sym->attr.external || sym->attr.use_assoc
1390                    || sym->attr.if_source == IFSRC_IFBODY)
1391               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1392             sym->attr.intrinsic = 1;
1393
1394           if (sym->attr.proc == PROC_ST_FUNCTION)
1395             {
1396               gfc_error ("Statement function '%s' at %L is not allowed as an "
1397                          "actual argument", sym->name, &e->where);
1398             }
1399
1400           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1401                                                sym->attr.subroutine);
1402           if (sym->attr.intrinsic && actual_ok == 0)
1403             {
1404               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1405                          "actual argument", sym->name, &e->where);
1406             }
1407
1408           if (sym->attr.contained && !sym->attr.use_assoc
1409               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1410             {
1411               gfc_error ("Internal procedure '%s' is not allowed as an "
1412                          "actual argument at %L", sym->name, &e->where);
1413             }
1414
1415           if (sym->attr.elemental && !sym->attr.intrinsic)
1416             {
1417               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1418                          "allowed as an actual argument at %L", sym->name,
1419                          &e->where);
1420             }
1421
1422           /* Check if a generic interface has a specific procedure
1423             with the same name before emitting an error.  */
1424           if (sym->attr.generic && count_specific_procs (e) != 1)
1425             return FAILURE;
1426           
1427           /* Just in case a specific was found for the expression.  */
1428           sym = e->symtree->n.sym;
1429
1430           /* If the symbol is the function that names the current (or
1431              parent) scope, then we really have a variable reference.  */
1432
1433           if (gfc_is_function_return_value (sym, sym->ns))
1434             goto got_variable;
1435
1436           /* If all else fails, see if we have a specific intrinsic.  */
1437           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1438             {
1439               gfc_intrinsic_sym *isym;
1440
1441               isym = gfc_find_function (sym->name);
1442               if (isym == NULL || !isym->specific)
1443                 {
1444                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1445                              "for the reference '%s' at %L", sym->name,
1446                              &e->where);
1447                   return FAILURE;
1448                 }
1449               sym->ts = isym->ts;
1450               sym->attr.intrinsic = 1;
1451               sym->attr.function = 1;
1452             }
1453
1454           if (gfc_resolve_expr (e) == FAILURE)
1455             return FAILURE;
1456           goto argument_list;
1457         }
1458
1459       /* See if the name is a module procedure in a parent unit.  */
1460
1461       if (was_declared (sym) || sym->ns->parent == NULL)
1462         goto got_variable;
1463
1464       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1465         {
1466           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1467           return FAILURE;
1468         }
1469
1470       if (parent_st == NULL)
1471         goto got_variable;
1472
1473       sym = parent_st->n.sym;
1474       e->symtree = parent_st;           /* Point to the right thing.  */
1475
1476       if (sym->attr.flavor == FL_PROCEDURE
1477           || sym->attr.intrinsic
1478           || sym->attr.external)
1479         {
1480           if (gfc_resolve_expr (e) == FAILURE)
1481             return FAILURE;
1482           goto argument_list;
1483         }
1484
1485     got_variable:
1486       e->expr_type = EXPR_VARIABLE;
1487       e->ts = sym->ts;
1488       if (sym->as != NULL)
1489         {
1490           e->rank = sym->as->rank;
1491           e->ref = gfc_get_ref ();
1492           e->ref->type = REF_ARRAY;
1493           e->ref->u.ar.type = AR_FULL;
1494           e->ref->u.ar.as = sym->as;
1495         }
1496
1497       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1498          primary.c (match_actual_arg). If above code determines that it
1499          is a  variable instead, it needs to be resolved as it was not
1500          done at the beginning of this function.  */
1501       save_need_full_assumed_size = need_full_assumed_size;
1502       if (e->expr_type != EXPR_VARIABLE)
1503         need_full_assumed_size = 0;
1504       if (gfc_resolve_expr (e) != SUCCESS)
1505         return FAILURE;
1506       need_full_assumed_size = save_need_full_assumed_size;
1507
1508     argument_list:
1509       /* Check argument list functions %VAL, %LOC and %REF.  There is
1510          nothing to do for %REF.  */
1511       if (arg->name && arg->name[0] == '%')
1512         {
1513           if (strncmp ("%VAL", arg->name, 4) == 0)
1514             {
1515               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1516                 {
1517                   gfc_error ("By-value argument at %L is not of numeric "
1518                              "type", &e->where);
1519                   return FAILURE;
1520                 }
1521
1522               if (e->rank)
1523                 {
1524                   gfc_error ("By-value argument at %L cannot be an array or "
1525                              "an array section", &e->where);
1526                 return FAILURE;
1527                 }
1528
1529               /* Intrinsics are still PROC_UNKNOWN here.  However,
1530                  since same file external procedures are not resolvable
1531                  in gfortran, it is a good deal easier to leave them to
1532                  intrinsic.c.  */
1533               if (ptype != PROC_UNKNOWN
1534                   && ptype != PROC_DUMMY
1535                   && ptype != PROC_EXTERNAL
1536                   && ptype != PROC_MODULE)
1537                 {
1538                   gfc_error ("By-value argument at %L is not allowed "
1539                              "in this context", &e->where);
1540                   return FAILURE;
1541                 }
1542             }
1543
1544           /* Statement functions have already been excluded above.  */
1545           else if (strncmp ("%LOC", arg->name, 4) == 0
1546                    && e->ts.type == BT_PROCEDURE)
1547             {
1548               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1549                 {
1550                   gfc_error ("Passing internal procedure at %L by location "
1551                              "not allowed", &e->where);
1552                   return FAILURE;
1553                 }
1554             }
1555         }
1556
1557       /* Fortran 2008, C1237.  */
1558       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1559           && gfc_has_ultimate_pointer (e))
1560         {
1561           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1562                      "component", &e->where);
1563           return FAILURE;
1564         }
1565     }
1566
1567   return SUCCESS;
1568 }
1569
1570
1571 /* Do the checks of the actual argument list that are specific to elemental
1572    procedures.  If called with c == NULL, we have a function, otherwise if
1573    expr == NULL, we have a subroutine.  */
1574
1575 static gfc_try
1576 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1577 {
1578   gfc_actual_arglist *arg0;
1579   gfc_actual_arglist *arg;
1580   gfc_symbol *esym = NULL;
1581   gfc_intrinsic_sym *isym = NULL;
1582   gfc_expr *e = NULL;
1583   gfc_intrinsic_arg *iformal = NULL;
1584   gfc_formal_arglist *eformal = NULL;
1585   bool formal_optional = false;
1586   bool set_by_optional = false;
1587   int i;
1588   int rank = 0;
1589
1590   /* Is this an elemental procedure?  */
1591   if (expr && expr->value.function.actual != NULL)
1592     {
1593       if (expr->value.function.esym != NULL
1594           && expr->value.function.esym->attr.elemental)
1595         {
1596           arg0 = expr->value.function.actual;
1597           esym = expr->value.function.esym;
1598         }
1599       else if (expr->value.function.isym != NULL
1600                && expr->value.function.isym->elemental)
1601         {
1602           arg0 = expr->value.function.actual;
1603           isym = expr->value.function.isym;
1604         }
1605       else
1606         return SUCCESS;
1607     }
1608   else if (c && c->ext.actual != NULL)
1609     {
1610       arg0 = c->ext.actual;
1611       
1612       if (c->resolved_sym)
1613         esym = c->resolved_sym;
1614       else
1615         esym = c->symtree->n.sym;
1616       gcc_assert (esym);
1617
1618       if (!esym->attr.elemental)
1619         return SUCCESS;
1620     }
1621   else
1622     return SUCCESS;
1623
1624   /* The rank of an elemental is the rank of its array argument(s).  */
1625   for (arg = arg0; arg; arg = arg->next)
1626     {
1627       if (arg->expr != NULL && arg->expr->rank > 0)
1628         {
1629           rank = arg->expr->rank;
1630           if (arg->expr->expr_type == EXPR_VARIABLE
1631               && arg->expr->symtree->n.sym->attr.optional)
1632             set_by_optional = true;
1633
1634           /* Function specific; set the result rank and shape.  */
1635           if (expr)
1636             {
1637               expr->rank = rank;
1638               if (!expr->shape && arg->expr->shape)
1639                 {
1640                   expr->shape = gfc_get_shape (rank);
1641                   for (i = 0; i < rank; i++)
1642                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1643                 }
1644             }
1645           break;
1646         }
1647     }
1648
1649   /* If it is an array, it shall not be supplied as an actual argument
1650      to an elemental procedure unless an array of the same rank is supplied
1651      as an actual argument corresponding to a nonoptional dummy argument of
1652      that elemental procedure(12.4.1.5).  */
1653   formal_optional = false;
1654   if (isym)
1655     iformal = isym->formal;
1656   else
1657     eformal = esym->formal;
1658
1659   for (arg = arg0; arg; arg = arg->next)
1660     {
1661       if (eformal)
1662         {
1663           if (eformal->sym && eformal->sym->attr.optional)
1664             formal_optional = true;
1665           eformal = eformal->next;
1666         }
1667       else if (isym && iformal)
1668         {
1669           if (iformal->optional)
1670             formal_optional = true;
1671           iformal = iformal->next;
1672         }
1673       else if (isym)
1674         formal_optional = true;
1675
1676       if (pedantic && arg->expr != NULL
1677           && arg->expr->expr_type == EXPR_VARIABLE
1678           && arg->expr->symtree->n.sym->attr.optional
1679           && formal_optional
1680           && arg->expr->rank
1681           && (set_by_optional || arg->expr->rank != rank)
1682           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1683         {
1684           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1685                        "MISSING, it cannot be the actual argument of an "
1686                        "ELEMENTAL procedure unless there is a non-optional "
1687                        "argument with the same rank (12.4.1.5)",
1688                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1689           return FAILURE;
1690         }
1691     }
1692
1693   for (arg = arg0; arg; arg = arg->next)
1694     {
1695       if (arg->expr == NULL || arg->expr->rank == 0)
1696         continue;
1697
1698       /* Being elemental, the last upper bound of an assumed size array
1699          argument must be present.  */
1700       if (resolve_assumed_size_actual (arg->expr))
1701         return FAILURE;
1702
1703       /* Elemental procedure's array actual arguments must conform.  */
1704       if (e != NULL)
1705         {
1706           if (gfc_check_conformance (arg->expr, e,
1707                                      "elemental procedure") == FAILURE)
1708             return FAILURE;
1709         }
1710       else
1711         e = arg->expr;
1712     }
1713
1714   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1715      is an array, the intent inout/out variable needs to be also an array.  */
1716   if (rank > 0 && esym && expr == NULL)
1717     for (eformal = esym->formal, arg = arg0; arg && eformal;
1718          arg = arg->next, eformal = eformal->next)
1719       if ((eformal->sym->attr.intent == INTENT_OUT
1720            || eformal->sym->attr.intent == INTENT_INOUT)
1721           && arg->expr && arg->expr->rank == 0)
1722         {
1723           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1724                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1725                      "actual argument is an array", &arg->expr->where,
1726                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1727                      : "INOUT", eformal->sym->name, esym->name);
1728           return FAILURE;
1729         }
1730   return SUCCESS;
1731 }
1732
1733
1734 /* Go through each actual argument in ACTUAL and see if it can be
1735    implemented as an inlined, non-copying intrinsic.  FNSYM is the
1736    function being called, or NULL if not known.  */
1737
1738 static void
1739 find_noncopying_intrinsics (gfc_symbol *fnsym, gfc_actual_arglist *actual)
1740 {
1741   gfc_actual_arglist *ap;
1742   gfc_expr *expr;
1743
1744   for (ap = actual; ap; ap = ap->next)
1745     if (ap->expr
1746         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
1747         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual,
1748                                          NOT_ELEMENTAL))
1749       ap->expr->inline_noncopying_intrinsic = 1;
1750 }
1751
1752
1753 /* This function does the checking of references to global procedures
1754    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1755    77 and 95 standards.  It checks for a gsymbol for the name, making
1756    one if it does not already exist.  If it already exists, then the
1757    reference being resolved must correspond to the type of gsymbol.
1758    Otherwise, the new symbol is equipped with the attributes of the
1759    reference.  The corresponding code that is called in creating
1760    global entities is parse.c.
1761
1762    In addition, for all but -std=legacy, the gsymbols are used to
1763    check the interfaces of external procedures from the same file.
1764    The namespace of the gsymbol is resolved and then, once this is
1765    done the interface is checked.  */
1766
1767
1768 static bool
1769 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
1770 {
1771   if (!gsym_ns->proc_name->attr.recursive)
1772     return true;
1773
1774   if (sym->ns == gsym_ns)
1775     return false;
1776
1777   if (sym->ns->parent && sym->ns->parent == gsym_ns)
1778     return false;
1779
1780   return true;
1781 }
1782
1783 static bool
1784 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
1785 {
1786   if (gsym_ns->entries)
1787     {
1788       gfc_entry_list *entry = gsym_ns->entries;
1789
1790       for (; entry; entry = entry->next)
1791         {
1792           if (strcmp (sym->name, entry->sym->name) == 0)
1793             {
1794               if (strcmp (gsym_ns->proc_name->name,
1795                           sym->ns->proc_name->name) == 0)
1796                 return false;
1797
1798               if (sym->ns->parent
1799                   && strcmp (gsym_ns->proc_name->name,
1800                              sym->ns->parent->proc_name->name) == 0)
1801                 return false;
1802             }
1803         }
1804     }
1805   return true;
1806 }
1807
1808 static void
1809 resolve_global_procedure (gfc_symbol *sym, locus *where,
1810                           gfc_actual_arglist **actual, int sub)
1811 {
1812   gfc_gsymbol * gsym;
1813   gfc_namespace *ns;
1814   enum gfc_symbol_type type;
1815
1816   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
1817
1818   gsym = gfc_get_gsymbol (sym->name);
1819
1820   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
1821     gfc_global_used (gsym, where);
1822
1823   if (gfc_option.flag_whole_file
1824         && sym->attr.if_source == IFSRC_UNKNOWN
1825         && gsym->type != GSYM_UNKNOWN
1826         && gsym->ns
1827         && gsym->ns->resolved != -1
1828         && gsym->ns->proc_name
1829         && not_in_recursive (sym, gsym->ns)
1830         && not_entry_self_reference (sym, gsym->ns))
1831     {
1832       /* Make sure that translation for the gsymbol occurs before
1833          the procedure currently being resolved.  */
1834       ns = gsym->ns->resolved ? NULL : gfc_global_ns_list;
1835       for (; ns && ns != gsym->ns; ns = ns->sibling)
1836         {
1837           if (ns->sibling == gsym->ns)
1838             {
1839               ns->sibling = gsym->ns->sibling;
1840               gsym->ns->sibling = gfc_global_ns_list;
1841               gfc_global_ns_list = gsym->ns;
1842               break;
1843             }
1844         }
1845
1846       if (!gsym->ns->resolved)
1847         {
1848           gfc_dt_list *old_dt_list;
1849
1850           /* Stash away derived types so that the backend_decls do not
1851              get mixed up.  */
1852           old_dt_list = gfc_derived_types;
1853           gfc_derived_types = NULL;
1854
1855           gfc_resolve (gsym->ns);
1856
1857           /* Store the new derived types with the global namespace.  */
1858           if (gfc_derived_types)
1859             gsym->ns->derived_types = gfc_derived_types;
1860
1861           /* Restore the derived types of this namespace.  */
1862           gfc_derived_types = old_dt_list;
1863         }
1864
1865       if (gsym->ns->proc_name->attr.function
1866             && gsym->ns->proc_name->as
1867             && gsym->ns->proc_name->as->rank
1868             && (!sym->as || sym->as->rank != gsym->ns->proc_name->as->rank))
1869         gfc_error ("The reference to function '%s' at %L either needs an "
1870                    "explicit INTERFACE or the rank is incorrect", sym->name,
1871                    where);
1872      
1873       /* Non-assumed length character functions.  */
1874       if (sym->attr.function && sym->ts.type == BT_CHARACTER
1875             && gsym->ns->proc_name->ts.u.cl != NULL
1876             && gsym->ns->proc_name->ts.u.cl->length != NULL)
1877         {
1878           gfc_charlen *cl = sym->ts.u.cl;
1879
1880           if (!sym->attr.entry_master && sym->attr.if_source == IFSRC_UNKNOWN
1881                 && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
1882             {
1883               gfc_error ("Nonconstant character-length function '%s' at %L "
1884                          "must have an explicit interface", sym->name,
1885                          &sym->declared_at);
1886             }
1887         }
1888
1889       if (gfc_option.flag_whole_file == 1
1890             || ((gfc_option.warn_std & GFC_STD_LEGACY)
1891                   &&
1892                !(gfc_option.warn_std & GFC_STD_GNU)))
1893         gfc_errors_to_warnings (1);
1894
1895       gfc_procedure_use (gsym->ns->proc_name, actual, where);
1896
1897       gfc_errors_to_warnings (0);
1898     }
1899
1900   if (gsym->type == GSYM_UNKNOWN)
1901     {
1902       gsym->type = type;
1903       gsym->where = *where;
1904     }
1905
1906   gsym->used = 1;
1907 }
1908
1909
1910 /************* Function resolution *************/
1911
1912 /* Resolve a function call known to be generic.
1913    Section 14.1.2.4.1.  */
1914
1915 static match
1916 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
1917 {
1918   gfc_symbol *s;
1919
1920   if (sym->attr.generic)
1921     {
1922       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
1923       if (s != NULL)
1924         {
1925           expr->value.function.name = s->name;
1926           expr->value.function.esym = s;
1927
1928           if (s->ts.type != BT_UNKNOWN)
1929             expr->ts = s->ts;
1930           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
1931             expr->ts = s->result->ts;
1932
1933           if (s->as != NULL)
1934             expr->rank = s->as->rank;
1935           else if (s->result != NULL && s->result->as != NULL)
1936             expr->rank = s->result->as->rank;
1937
1938           gfc_set_sym_referenced (expr->value.function.esym);
1939
1940           return MATCH_YES;
1941         }
1942
1943       /* TODO: Need to search for elemental references in generic
1944          interface.  */
1945     }
1946
1947   if (sym->attr.intrinsic)
1948     return gfc_intrinsic_func_interface (expr, 0);
1949
1950   return MATCH_NO;
1951 }
1952
1953
1954 static gfc_try
1955 resolve_generic_f (gfc_expr *expr)
1956 {
1957   gfc_symbol *sym;
1958   match m;
1959
1960   sym = expr->symtree->n.sym;
1961
1962   for (;;)
1963     {
1964       m = resolve_generic_f0 (expr, sym);
1965       if (m == MATCH_YES)
1966         return SUCCESS;
1967       else if (m == MATCH_ERROR)
1968         return FAILURE;
1969
1970 generic:
1971       if (sym->ns->parent == NULL)
1972         break;
1973       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1974
1975       if (sym == NULL)
1976         break;
1977       if (!generic_sym (sym))
1978         goto generic;
1979     }
1980
1981   /* Last ditch attempt.  See if the reference is to an intrinsic
1982      that possesses a matching interface.  14.1.2.4  */
1983   if (sym && !gfc_is_intrinsic (sym, 0, expr->where))
1984     {
1985       gfc_error ("There is no specific function for the generic '%s' at %L",
1986                  expr->symtree->n.sym->name, &expr->where);
1987       return FAILURE;
1988     }
1989
1990   m = gfc_intrinsic_func_interface (expr, 0);
1991   if (m == MATCH_YES)
1992     return SUCCESS;
1993   if (m == MATCH_NO)
1994     gfc_error ("Generic function '%s' at %L is not consistent with a "
1995                "specific intrinsic interface", expr->symtree->n.sym->name,
1996                &expr->where);
1997
1998   return FAILURE;
1999 }
2000
2001
2002 /* Resolve a function call known to be specific.  */
2003
2004 static match
2005 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2006 {
2007   match m;
2008
2009   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2010     {
2011       if (sym->attr.dummy)
2012         {
2013           sym->attr.proc = PROC_DUMMY;
2014           goto found;
2015         }
2016
2017       sym->attr.proc = PROC_EXTERNAL;
2018       goto found;
2019     }
2020
2021   if (sym->attr.proc == PROC_MODULE
2022       || sym->attr.proc == PROC_ST_FUNCTION
2023       || sym->attr.proc == PROC_INTERNAL)
2024     goto found;
2025
2026   if (sym->attr.intrinsic)
2027     {
2028       m = gfc_intrinsic_func_interface (expr, 1);
2029       if (m == MATCH_YES)
2030         return MATCH_YES;
2031       if (m == MATCH_NO)
2032         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2033                    "with an intrinsic", sym->name, &expr->where);
2034
2035       return MATCH_ERROR;
2036     }
2037
2038   return MATCH_NO;
2039
2040 found:
2041   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2042
2043   if (sym->result)
2044     expr->ts = sym->result->ts;
2045   else
2046     expr->ts = sym->ts;
2047   expr->value.function.name = sym->name;
2048   expr->value.function.esym = sym;
2049   if (sym->as != NULL)
2050     expr->rank = sym->as->rank;
2051
2052   return MATCH_YES;
2053 }
2054
2055
2056 static gfc_try
2057 resolve_specific_f (gfc_expr *expr)
2058 {
2059   gfc_symbol *sym;
2060   match m;
2061
2062   sym = expr->symtree->n.sym;
2063
2064   for (;;)
2065     {
2066       m = resolve_specific_f0 (sym, expr);
2067       if (m == MATCH_YES)
2068         return SUCCESS;
2069       if (m == MATCH_ERROR)
2070         return FAILURE;
2071
2072       if (sym->ns->parent == NULL)
2073         break;
2074
2075       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2076
2077       if (sym == NULL)
2078         break;
2079     }
2080
2081   gfc_error ("Unable to resolve the specific function '%s' at %L",
2082              expr->symtree->n.sym->name, &expr->where);
2083
2084   return SUCCESS;
2085 }
2086
2087
2088 /* Resolve a procedure call not known to be generic nor specific.  */
2089
2090 static gfc_try
2091 resolve_unknown_f (gfc_expr *expr)
2092 {
2093   gfc_symbol *sym;
2094   gfc_typespec *ts;
2095
2096   sym = expr->symtree->n.sym;
2097
2098   if (sym->attr.dummy)
2099     {
2100       sym->attr.proc = PROC_DUMMY;
2101       expr->value.function.name = sym->name;
2102       goto set_type;
2103     }
2104
2105   /* See if we have an intrinsic function reference.  */
2106
2107   if (gfc_is_intrinsic (sym, 0, expr->where))
2108     {
2109       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2110         return SUCCESS;
2111       return FAILURE;
2112     }
2113
2114   /* The reference is to an external name.  */
2115
2116   sym->attr.proc = PROC_EXTERNAL;
2117   expr->value.function.name = sym->name;
2118   expr->value.function.esym = expr->symtree->n.sym;
2119
2120   if (sym->as != NULL)
2121     expr->rank = sym->as->rank;
2122
2123   /* Type of the expression is either the type of the symbol or the
2124      default type of the symbol.  */
2125
2126 set_type:
2127   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2128
2129   if (sym->ts.type != BT_UNKNOWN)
2130     expr->ts = sym->ts;
2131   else
2132     {
2133       ts = gfc_get_default_type (sym->name, sym->ns);
2134
2135       if (ts->type == BT_UNKNOWN)
2136         {
2137           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2138                      sym->name, &expr->where);
2139           return FAILURE;
2140         }
2141       else
2142         expr->ts = *ts;
2143     }
2144
2145   return SUCCESS;
2146 }
2147
2148
2149 /* Return true, if the symbol is an external procedure.  */
2150 static bool
2151 is_external_proc (gfc_symbol *sym)
2152 {
2153   if (!sym->attr.dummy && !sym->attr.contained
2154         && !(sym->attr.intrinsic
2155               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2156         && sym->attr.proc != PROC_ST_FUNCTION
2157         && !sym->attr.use_assoc
2158         && sym->name)
2159     return true;
2160
2161   return false;
2162 }
2163
2164
2165 /* Figure out if a function reference is pure or not.  Also set the name
2166    of the function for a potential error message.  Return nonzero if the
2167    function is PURE, zero if not.  */
2168 static int
2169 pure_stmt_function (gfc_expr *, gfc_symbol *);
2170
2171 static int
2172 pure_function (gfc_expr *e, const char **name)
2173 {
2174   int pure;
2175
2176   *name = NULL;
2177
2178   if (e->symtree != NULL
2179         && e->symtree->n.sym != NULL
2180         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2181     return pure_stmt_function (e, e->symtree->n.sym);
2182
2183   if (e->value.function.esym)
2184     {
2185       pure = gfc_pure (e->value.function.esym);
2186       *name = e->value.function.esym->name;
2187     }
2188   else if (e->value.function.isym)
2189     {
2190       pure = e->value.function.isym->pure
2191              || e->value.function.isym->elemental;
2192       *name = e->value.function.isym->name;
2193     }
2194   else
2195     {
2196       /* Implicit functions are not pure.  */
2197       pure = 0;
2198       *name = e->value.function.name;
2199     }
2200
2201   return pure;
2202 }
2203
2204
2205 static bool
2206 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2207                  int *f ATTRIBUTE_UNUSED)
2208 {
2209   const char *name;
2210
2211   /* Don't bother recursing into other statement functions
2212      since they will be checked individually for purity.  */
2213   if (e->expr_type != EXPR_FUNCTION
2214         || !e->symtree
2215         || e->symtree->n.sym == sym
2216         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2217     return false;
2218
2219   return pure_function (e, &name) ? false : true;
2220 }
2221
2222
2223 static int
2224 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2225 {
2226   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2227 }
2228
2229
2230 static gfc_try
2231 is_scalar_expr_ptr (gfc_expr *expr)
2232 {
2233   gfc_try retval = SUCCESS;
2234   gfc_ref *ref;
2235   int start;
2236   int end;
2237
2238   /* See if we have a gfc_ref, which means we have a substring, array
2239      reference, or a component.  */
2240   if (expr->ref != NULL)
2241     {
2242       ref = expr->ref;
2243       while (ref->next != NULL)
2244         ref = ref->next;
2245
2246       switch (ref->type)
2247         {
2248         case REF_SUBSTRING:
2249           if (ref->u.ss.length != NULL 
2250               && ref->u.ss.length->length != NULL
2251               && ref->u.ss.start
2252               && ref->u.ss.start->expr_type == EXPR_CONSTANT 
2253               && ref->u.ss.end
2254               && ref->u.ss.end->expr_type == EXPR_CONSTANT)
2255             {
2256               start = (int) mpz_get_si (ref->u.ss.start->value.integer);
2257               end = (int) mpz_get_si (ref->u.ss.end->value.integer);
2258               if (end - start + 1 != 1)
2259                 retval = FAILURE;
2260             }
2261           else
2262             retval = FAILURE;
2263           break;
2264         case REF_ARRAY:
2265           if (ref->u.ar.type == AR_ELEMENT)
2266             retval = SUCCESS;
2267           else if (ref->u.ar.type == AR_FULL)
2268             {
2269               /* The user can give a full array if the array is of size 1.  */
2270               if (ref->u.ar.as != NULL
2271                   && ref->u.ar.as->rank == 1
2272                   && ref->u.ar.as->type == AS_EXPLICIT
2273                   && ref->u.ar.as->lower[0] != NULL
2274                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2275                   && ref->u.ar.as->upper[0] != NULL
2276                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2277                 {
2278                   /* If we have a character string, we need to check if
2279                      its length is one.  */
2280                   if (expr->ts.type == BT_CHARACTER)
2281                     {
2282                       if (expr->ts.u.cl == NULL
2283                           || expr->ts.u.cl->length == NULL
2284                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2285                           != 0)
2286                         retval = FAILURE;
2287                     }
2288                   else
2289                     {
2290                       /* We have constant lower and upper bounds.  If the
2291                          difference between is 1, it can be considered a
2292                          scalar.  */
2293                       start = (int) mpz_get_si
2294                                 (ref->u.ar.as->lower[0]->value.integer);
2295                       end = (int) mpz_get_si
2296                                 (ref->u.ar.as->upper[0]->value.integer);
2297                       if (end - start + 1 != 1)
2298                         retval = FAILURE;
2299                    }
2300                 }
2301               else
2302                 retval = FAILURE;
2303             }
2304           else
2305             retval = FAILURE;
2306           break;
2307         default:
2308           retval = SUCCESS;
2309           break;
2310         }
2311     }
2312   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2313     {
2314       /* Character string.  Make sure it's of length 1.  */
2315       if (expr->ts.u.cl == NULL
2316           || expr->ts.u.cl->length == NULL
2317           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2318         retval = FAILURE;
2319     }
2320   else if (expr->rank != 0)
2321     retval = FAILURE;
2322
2323   return retval;
2324 }
2325
2326
2327 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2328    and, in the case of c_associated, set the binding label based on
2329    the arguments.  */
2330
2331 static gfc_try
2332 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2333                           gfc_symbol **new_sym)
2334 {
2335   char name[GFC_MAX_SYMBOL_LEN + 1];
2336   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2337   int optional_arg = 0, is_pointer = 0;
2338   gfc_try retval = SUCCESS;
2339   gfc_symbol *args_sym;
2340   gfc_typespec *arg_ts;
2341
2342   if (args->expr->expr_type == EXPR_CONSTANT
2343       || args->expr->expr_type == EXPR_OP
2344       || args->expr->expr_type == EXPR_NULL)
2345     {
2346       gfc_error ("Argument to '%s' at %L is not a variable",
2347                  sym->name, &(args->expr->where));
2348       return FAILURE;
2349     }
2350
2351   args_sym = args->expr->symtree->n.sym;
2352
2353   /* The typespec for the actual arg should be that stored in the expr
2354      and not necessarily that of the expr symbol (args_sym), because
2355      the actual expression could be a part-ref of the expr symbol.  */
2356   arg_ts = &(args->expr->ts);
2357
2358   is_pointer = gfc_is_data_pointer (args->expr);
2359     
2360   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2361     {
2362       /* If the user gave two args then they are providing something for
2363          the optional arg (the second cptr).  Therefore, set the name and
2364          binding label to the c_associated for two cptrs.  Otherwise,
2365          set c_associated to expect one cptr.  */
2366       if (args->next)
2367         {
2368           /* two args.  */
2369           sprintf (name, "%s_2", sym->name);
2370           sprintf (binding_label, "%s_2", sym->binding_label);
2371           optional_arg = 1;
2372         }
2373       else
2374         {
2375           /* one arg.  */
2376           sprintf (name, "%s_1", sym->name);
2377           sprintf (binding_label, "%s_1", sym->binding_label);
2378           optional_arg = 0;
2379         }
2380
2381       /* Get a new symbol for the version of c_associated that
2382          will get called.  */
2383       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2384     }
2385   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2386            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2387     {
2388       sprintf (name, "%s", sym->name);
2389       sprintf (binding_label, "%s", sym->binding_label);
2390
2391       /* Error check the call.  */
2392       if (args->next != NULL)
2393         {
2394           gfc_error_now ("More actual than formal arguments in '%s' "
2395                          "call at %L", name, &(args->expr->where));
2396           retval = FAILURE;
2397         }
2398       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2399         {
2400           /* Make sure we have either the target or pointer attribute.  */
2401           if (!args_sym->attr.target && !is_pointer)
2402             {
2403               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2404                              "a TARGET or an associated pointer",
2405                              args_sym->name,
2406                              sym->name, &(args->expr->where));
2407               retval = FAILURE;
2408             }
2409
2410           /* See if we have interoperable type and type param.  */
2411           if (verify_c_interop (arg_ts) == SUCCESS
2412               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2413             {
2414               if (args_sym->attr.target == 1)
2415                 {
2416                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2417                      has the target attribute and is interoperable.  */
2418                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2419                      allocatable variable that has the TARGET attribute and
2420                      is not an array of zero size.  */
2421                   if (args_sym->attr.allocatable == 1)
2422                     {
2423                       if (args_sym->attr.dimension != 0 
2424                           && (args_sym->as && args_sym->as->rank == 0))
2425                         {
2426                           gfc_error_now ("Allocatable variable '%s' used as a "
2427                                          "parameter to '%s' at %L must not be "
2428                                          "an array of zero size",
2429                                          args_sym->name, sym->name,
2430                                          &(args->expr->where));
2431                           retval = FAILURE;
2432                         }
2433                     }
2434                   else
2435                     {
2436                       /* A non-allocatable target variable with C
2437                          interoperable type and type parameters must be
2438                          interoperable.  */
2439                       if (args_sym && args_sym->attr.dimension)
2440                         {
2441                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2442                             {
2443                               gfc_error ("Assumed-shape array '%s' at %L "
2444                                          "cannot be an argument to the "
2445                                          "procedure '%s' because "
2446                                          "it is not C interoperable",
2447                                          args_sym->name,
2448                                          &(args->expr->where), sym->name);
2449                               retval = FAILURE;
2450                             }
2451                           else if (args_sym->as->type == AS_DEFERRED)
2452                             {
2453                               gfc_error ("Deferred-shape array '%s' at %L "
2454                                          "cannot be an argument to the "
2455                                          "procedure '%s' because "
2456                                          "it is not C interoperable",
2457                                          args_sym->name,
2458                                          &(args->expr->where), sym->name);
2459                               retval = FAILURE;
2460                             }
2461                         }
2462                               
2463                       /* Make sure it's not a character string.  Arrays of
2464                          any type should be ok if the variable is of a C
2465                          interoperable type.  */
2466                       if (arg_ts->type == BT_CHARACTER)
2467                         if (arg_ts->u.cl != NULL
2468                             && (arg_ts->u.cl->length == NULL
2469                                 || arg_ts->u.cl->length->expr_type
2470                                    != EXPR_CONSTANT
2471                                 || mpz_cmp_si
2472                                     (arg_ts->u.cl->length->value.integer, 1)
2473                                    != 0)
2474                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2475                           {
2476                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2477                                            "at %L must have a length of 1",
2478                                            args_sym->name, sym->name,
2479                                            &(args->expr->where));
2480                             retval = FAILURE;
2481                           }
2482                     }
2483                 }
2484               else if (is_pointer
2485                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2486                 {
2487                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2488                      scalar pointer.  */
2489                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2490                                  "associated scalar POINTER", args_sym->name,
2491                                  sym->name, &(args->expr->where));
2492                   retval = FAILURE;
2493                 }
2494             }
2495           else
2496             {
2497               /* The parameter is not required to be C interoperable.  If it
2498                  is not C interoperable, it must be a nonpolymorphic scalar
2499                  with no length type parameters.  It still must have either
2500                  the pointer or target attribute, and it can be
2501                  allocatable (but must be allocated when c_loc is called).  */
2502               if (args->expr->rank != 0 
2503                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2504                 {
2505                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2506                                  "scalar", args_sym->name, sym->name,
2507                                  &(args->expr->where));
2508                   retval = FAILURE;
2509                 }
2510               else if (arg_ts->type == BT_CHARACTER 
2511                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2512                 {
2513                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2514                                  "%L must have a length of 1",
2515                                  args_sym->name, sym->name,
2516                                  &(args->expr->where));
2517                   retval = FAILURE;
2518                 }
2519             }
2520         }
2521       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2522         {
2523           if (args_sym->attr.flavor != FL_PROCEDURE)
2524             {
2525               /* TODO: Update this error message to allow for procedure
2526                  pointers once they are implemented.  */
2527               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2528                              "procedure",
2529                              args_sym->name, sym->name,
2530                              &(args->expr->where));
2531               retval = FAILURE;
2532             }
2533           else if (args_sym->attr.is_bind_c != 1)
2534             {
2535               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2536                              "BIND(C)",
2537                              args_sym->name, sym->name,
2538                              &(args->expr->where));
2539               retval = FAILURE;
2540             }
2541         }
2542       
2543       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2544       *new_sym = sym;
2545     }
2546   else
2547     {
2548       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2549                           "iso_c_binding function: '%s'!\n", sym->name);
2550     }
2551
2552   return retval;
2553 }
2554
2555
2556 /* Resolve a function call, which means resolving the arguments, then figuring
2557    out which entity the name refers to.  */
2558 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
2559    to INTENT(OUT) or INTENT(INOUT).  */
2560
2561 static gfc_try
2562 resolve_function (gfc_expr *expr)
2563 {
2564   gfc_actual_arglist *arg;
2565   gfc_symbol *sym;
2566   const char *name;
2567   gfc_try t;
2568   int temp;
2569   procedure_type p = PROC_INTRINSIC;
2570   bool no_formal_args;
2571
2572   sym = NULL;
2573   if (expr->symtree)
2574     sym = expr->symtree->n.sym;
2575
2576   /* If this is a procedure pointer component, it has already been resolved.  */
2577   if (gfc_is_proc_ptr_comp (expr, NULL))
2578     return SUCCESS;
2579   
2580   if (sym && sym->attr.intrinsic
2581       && resolve_intrinsic (sym, &expr->where) == FAILURE)
2582     return FAILURE;
2583
2584   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2585     {
2586       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2587       return FAILURE;
2588     }
2589
2590   /* If this ia a deferred TBP with an abstract interface (which may
2591      of course be referenced), expr->value.function.esym will be set.  */
2592   if (sym && sym->attr.abstract && !expr->value.function.esym)
2593     {
2594       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2595                  sym->name, &expr->where);
2596       return FAILURE;
2597     }
2598
2599   /* Switch off assumed size checking and do this again for certain kinds
2600      of procedure, once the procedure itself is resolved.  */
2601   need_full_assumed_size++;
2602
2603   if (expr->symtree && expr->symtree->n.sym)
2604     p = expr->symtree->n.sym->attr.proc;
2605
2606   if (expr->value.function.isym && expr->value.function.isym->inquiry)
2607     inquiry_argument = true;
2608   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
2609
2610   if (resolve_actual_arglist (expr->value.function.actual,
2611                               p, no_formal_args) == FAILURE)
2612     {
2613       inquiry_argument = false;
2614       return FAILURE;
2615     }
2616
2617   inquiry_argument = false;
2618  
2619   /* Need to setup the call to the correct c_associated, depending on
2620      the number of cptrs to user gives to compare.  */
2621   if (sym && sym->attr.is_iso_c == 1)
2622     {
2623       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
2624           == FAILURE)
2625         return FAILURE;
2626       
2627       /* Get the symtree for the new symbol (resolved func).
2628          the old one will be freed later, when it's no longer used.  */
2629       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
2630     }
2631   
2632   /* Resume assumed_size checking.  */
2633   need_full_assumed_size--;
2634
2635   /* If the procedure is external, check for usage.  */
2636   if (sym && is_external_proc (sym))
2637     resolve_global_procedure (sym, &expr->where,
2638                               &expr->value.function.actual, 0);
2639
2640   if (sym && sym->ts.type == BT_CHARACTER
2641       && sym->ts.u.cl
2642       && sym->ts.u.cl->length == NULL
2643       && !sym->attr.dummy
2644       && expr->value.function.esym == NULL
2645       && !sym->attr.contained)
2646     {
2647       /* Internal procedures are taken care of in resolve_contained_fntype.  */
2648       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
2649                  "be used at %L since it is not a dummy argument",
2650                  sym->name, &expr->where);
2651       return FAILURE;
2652     }
2653
2654   /* See if function is already resolved.  */
2655
2656   if (expr->value.function.name != NULL)
2657     {
2658       if (expr->ts.type == BT_UNKNOWN)
2659         expr->ts = sym->ts;
2660       t = SUCCESS;
2661     }
2662   else
2663     {
2664       /* Apply the rules of section 14.1.2.  */
2665
2666       switch (procedure_kind (sym))
2667         {
2668         case PTYPE_GENERIC:
2669           t = resolve_generic_f (expr);
2670           break;
2671
2672         case PTYPE_SPECIFIC:
2673           t = resolve_specific_f (expr);
2674           break;
2675
2676         case PTYPE_UNKNOWN:
2677           t = resolve_unknown_f (expr);
2678           break;
2679
2680         default:
2681           gfc_internal_error ("resolve_function(): bad function type");
2682         }
2683     }
2684
2685   /* If the expression is still a function (it might have simplified),
2686      then we check to see if we are calling an elemental function.  */
2687
2688   if (expr->expr_type != EXPR_FUNCTION)
2689     return t;
2690
2691   temp = need_full_assumed_size;
2692   need_full_assumed_size = 0;
2693
2694   if (resolve_elemental_actual (expr, NULL) == FAILURE)
2695     return FAILURE;
2696
2697   if (omp_workshare_flag
2698       && expr->value.function.esym
2699       && ! gfc_elemental (expr->value.function.esym))
2700     {
2701       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
2702                  "in WORKSHARE construct", expr->value.function.esym->name,
2703                  &expr->where);
2704       t = FAILURE;
2705     }
2706
2707 #define GENERIC_ID expr->value.function.isym->id
2708   else if (expr->value.function.actual != NULL
2709            && expr->value.function.isym != NULL
2710            && GENERIC_ID != GFC_ISYM_LBOUND
2711            && GENERIC_ID != GFC_ISYM_LEN
2712            && GENERIC_ID != GFC_ISYM_LOC
2713            && GENERIC_ID != GFC_ISYM_PRESENT)
2714     {
2715       /* Array intrinsics must also have the last upper bound of an
2716          assumed size array argument.  UBOUND and SIZE have to be
2717          excluded from the check if the second argument is anything
2718          than a constant.  */
2719
2720       for (arg = expr->value.function.actual; arg; arg = arg->next)
2721         {
2722           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
2723               && arg->next != NULL && arg->next->expr)
2724             {
2725               if (arg->next->expr->expr_type != EXPR_CONSTANT)
2726                 break;
2727
2728               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
2729                 break;
2730
2731               if ((int)mpz_get_si (arg->next->expr->value.integer)
2732                         < arg->expr->rank)
2733                 break;
2734             }
2735
2736           if (arg->expr != NULL
2737               && arg->expr->rank > 0
2738               && resolve_assumed_size_actual (arg->expr))
2739             return FAILURE;
2740         }
2741     }
2742 #undef GENERIC_ID
2743
2744   need_full_assumed_size = temp;
2745   name = NULL;
2746
2747   if (!pure_function (expr, &name) && name)
2748     {
2749       if (forall_flag)
2750         {
2751           gfc_error ("reference to non-PURE function '%s' at %L inside a "
2752                      "FORALL %s", name, &expr->where,
2753                      forall_flag == 2 ? "mask" : "block");
2754           t = FAILURE;
2755         }
2756       else if (gfc_pure (NULL))
2757         {
2758           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
2759                      "procedure within a PURE procedure", name, &expr->where);
2760           t = FAILURE;
2761         }
2762     }
2763
2764   /* Functions without the RECURSIVE attribution are not allowed to
2765    * call themselves.  */
2766   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
2767     {
2768       gfc_symbol *esym;
2769       esym = expr->value.function.esym;
2770
2771       if (is_illegal_recursion (esym, gfc_current_ns))
2772       {
2773         if (esym->attr.entry && esym->ns->entries)
2774           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
2775                      " function '%s' is not RECURSIVE",
2776                      esym->name, &expr->where, esym->ns->entries->sym->name);
2777         else
2778           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
2779                      " is not RECURSIVE", esym->name, &expr->where);
2780
2781         t = FAILURE;
2782       }
2783     }
2784
2785   /* Character lengths of use associated functions may contains references to
2786      symbols not referenced from the current program unit otherwise.  Make sure
2787      those symbols are marked as referenced.  */
2788
2789   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
2790       && expr->value.function.esym->attr.use_assoc)
2791     {
2792       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
2793     }
2794
2795   if (t == SUCCESS
2796         && !((expr->value.function.esym
2797                 && expr->value.function.esym->attr.elemental)
2798                         ||
2799              (expr->value.function.isym
2800                 && expr->value.function.isym->elemental)))
2801     find_noncopying_intrinsics (expr->value.function.esym,
2802                                 expr->value.function.actual);
2803
2804   /* Make sure that the expression has a typespec that works.  */
2805   if (expr->ts.type == BT_UNKNOWN)
2806     {
2807       if (expr->symtree->n.sym->result
2808             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
2809             && !expr->symtree->n.sym->result->attr.proc_pointer)
2810         expr->ts = expr->symtree->n.sym->result->ts;
2811     }
2812
2813   return t;
2814 }
2815
2816
2817 /************* Subroutine resolution *************/
2818
2819 static void
2820 pure_subroutine (gfc_code *c, gfc_symbol *sym)
2821 {
2822   if (gfc_pure (sym))
2823     return;
2824
2825   if (forall_flag)
2826     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
2827                sym->name, &c->loc);
2828   else if (gfc_pure (NULL))
2829     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
2830                &c->loc);
2831 }
2832
2833
2834 static match
2835 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
2836 {
2837   gfc_symbol *s;
2838
2839   if (sym->attr.generic)
2840     {
2841       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
2842       if (s != NULL)
2843         {
2844           c->resolved_sym = s;
2845           pure_subroutine (c, s);
2846           return MATCH_YES;
2847         }
2848
2849       /* TODO: Need to search for elemental references in generic interface.  */
2850     }
2851
2852   if (sym->attr.intrinsic)
2853     return gfc_intrinsic_sub_interface (c, 0);
2854
2855   return MATCH_NO;
2856 }
2857
2858
2859 static gfc_try
2860 resolve_generic_s (gfc_code *c)
2861 {
2862   gfc_symbol *sym;
2863   match m;
2864
2865   sym = c->symtree->n.sym;
2866
2867   for (;;)
2868     {
2869       m = resolve_generic_s0 (c, sym);
2870       if (m == MATCH_YES)
2871         return SUCCESS;
2872       else if (m == MATCH_ERROR)
2873         return FAILURE;
2874
2875 generic:
2876       if (sym->ns->parent == NULL)
2877         break;
2878       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2879
2880       if (sym == NULL)
2881         break;
2882       if (!generic_sym (sym))
2883         goto generic;
2884     }
2885
2886   /* Last ditch attempt.  See if the reference is to an intrinsic
2887      that possesses a matching interface.  14.1.2.4  */
2888   sym = c->symtree->n.sym;
2889
2890   if (!gfc_is_intrinsic (sym, 1, c->loc))
2891     {
2892       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
2893                  sym->name, &c->loc);
2894       return FAILURE;
2895     }
2896
2897   m = gfc_intrinsic_sub_interface (c, 0);
2898   if (m == MATCH_YES)
2899     return SUCCESS;
2900   if (m == MATCH_NO)
2901     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
2902                "intrinsic subroutine interface", sym->name, &c->loc);
2903
2904   return FAILURE;
2905 }
2906
2907
2908 /* Set the name and binding label of the subroutine symbol in the call
2909    expression represented by 'c' to include the type and kind of the
2910    second parameter.  This function is for resolving the appropriate
2911    version of c_f_pointer() and c_f_procpointer().  For example, a
2912    call to c_f_pointer() for a default integer pointer could have a
2913    name of c_f_pointer_i4.  If no second arg exists, which is an error
2914    for these two functions, it defaults to the generic symbol's name
2915    and binding label.  */
2916
2917 static void
2918 set_name_and_label (gfc_code *c, gfc_symbol *sym,
2919                     char *name, char *binding_label)
2920 {
2921   gfc_expr *arg = NULL;
2922   char type;
2923   int kind;
2924
2925   /* The second arg of c_f_pointer and c_f_procpointer determines
2926      the type and kind for the procedure name.  */
2927   arg = c->ext.actual->next->expr;
2928
2929   if (arg != NULL)
2930     {
2931       /* Set up the name to have the given symbol's name,
2932          plus the type and kind.  */
2933       /* a derived type is marked with the type letter 'u' */
2934       if (arg->ts.type == BT_DERIVED)
2935         {
2936           type = 'd';
2937           kind = 0; /* set the kind as 0 for now */
2938         }
2939       else
2940         {
2941           type = gfc_type_letter (arg->ts.type);
2942           kind = arg->ts.kind;
2943         }
2944
2945       if (arg->ts.type == BT_CHARACTER)
2946         /* Kind info for character strings not needed.  */
2947         kind = 0;
2948
2949       sprintf (name, "%s_%c%d", sym->name, type, kind);
2950       /* Set up the binding label as the given symbol's label plus
2951          the type and kind.  */
2952       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
2953     }
2954   else
2955     {
2956       /* If the second arg is missing, set the name and label as
2957          was, cause it should at least be found, and the missing
2958          arg error will be caught by compare_parameters().  */
2959       sprintf (name, "%s", sym->name);
2960       sprintf (binding_label, "%s", sym->binding_label);
2961     }
2962    
2963   return;
2964 }
2965
2966
2967 /* Resolve a generic version of the iso_c_binding procedure given
2968    (sym) to the specific one based on the type and kind of the
2969    argument(s).  Currently, this function resolves c_f_pointer() and
2970    c_f_procpointer based on the type and kind of the second argument
2971    (FPTR).  Other iso_c_binding procedures aren't specially handled.
2972    Upon successfully exiting, c->resolved_sym will hold the resolved
2973    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
2974    otherwise.  */
2975
2976 match
2977 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
2978 {
2979   gfc_symbol *new_sym;
2980   /* this is fine, since we know the names won't use the max */
2981   char name[GFC_MAX_SYMBOL_LEN + 1];
2982   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2983   /* default to success; will override if find error */
2984   match m = MATCH_YES;
2985
2986   /* Make sure the actual arguments are in the necessary order (based on the 
2987      formal args) before resolving.  */
2988   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
2989
2990   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
2991       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
2992     {
2993       set_name_and_label (c, sym, name, binding_label);
2994       
2995       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
2996         {
2997           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
2998             {
2999               /* Make sure we got a third arg if the second arg has non-zero
3000                  rank.  We must also check that the type and rank are
3001                  correct since we short-circuit this check in
3002                  gfc_procedure_use() (called above to sort actual args).  */
3003               if (c->ext.actual->next->expr->rank != 0)
3004                 {
3005                   if(c->ext.actual->next->next == NULL 
3006                      || c->ext.actual->next->next->expr == NULL)
3007                     {
3008                       m = MATCH_ERROR;
3009                       gfc_error ("Missing SHAPE parameter for call to %s "
3010                                  "at %L", sym->name, &(c->loc));
3011                     }
3012                   else if (c->ext.actual->next->next->expr->ts.type
3013                            != BT_INTEGER
3014                            || c->ext.actual->next->next->expr->rank != 1)
3015                     {
3016                       m = MATCH_ERROR;
3017                       gfc_error ("SHAPE parameter for call to %s at %L must "
3018                                  "be a rank 1 INTEGER array", sym->name,
3019                                  &(c->loc));
3020                     }
3021                 }
3022             }
3023         }
3024       
3025       if (m != MATCH_ERROR)
3026         {
3027           /* the 1 means to add the optional arg to formal list */
3028           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
3029          
3030           /* for error reporting, say it's declared where the original was */
3031           new_sym->declared_at = sym->declared_at;
3032         }
3033     }
3034   else
3035     {
3036       /* no differences for c_loc or c_funloc */
3037       new_sym = sym;
3038     }
3039
3040   /* set the resolved symbol */
3041   if (m != MATCH_ERROR)
3042     c->resolved_sym = new_sym;
3043   else
3044     c->resolved_sym = sym;
3045   
3046   return m;
3047 }
3048
3049
3050 /* Resolve a subroutine call known to be specific.  */
3051
3052 static match
3053 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3054 {
3055   match m;
3056
3057   if(sym->attr.is_iso_c)
3058     {
3059       m = gfc_iso_c_sub_interface (c,sym);
3060       return m;
3061     }
3062   
3063   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3064     {
3065       if (sym->attr.dummy)
3066         {
3067           sym->attr.proc = PROC_DUMMY;
3068           goto found;
3069         }
3070
3071       sym->attr.proc = PROC_EXTERNAL;
3072       goto found;
3073     }
3074
3075   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3076     goto found;
3077
3078   if (sym->attr.intrinsic)
3079     {
3080       m = gfc_intrinsic_sub_interface (c, 1);
3081       if (m == MATCH_YES)
3082         return MATCH_YES;
3083       if (m == MATCH_NO)
3084         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3085                    "with an intrinsic", sym->name, &c->loc);
3086
3087       return MATCH_ERROR;
3088     }
3089
3090   return MATCH_NO;
3091
3092 found:
3093   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3094
3095   c->resolved_sym = sym;
3096   pure_subroutine (c, sym);
3097
3098   return MATCH_YES;
3099 }
3100
3101
3102 static gfc_try
3103 resolve_specific_s (gfc_code *c)
3104 {
3105   gfc_symbol *sym;
3106   match m;
3107
3108   sym = c->symtree->n.sym;
3109
3110   for (;;)
3111     {
3112       m = resolve_specific_s0 (c, sym);
3113       if (m == MATCH_YES)
3114         return SUCCESS;
3115       if (m == MATCH_ERROR)
3116         return FAILURE;
3117
3118       if (sym->ns->parent == NULL)
3119         break;
3120
3121       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3122
3123       if (sym == NULL)
3124         break;
3125     }
3126
3127   sym = c->symtree->n.sym;
3128   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3129              sym->name, &c->loc);
3130
3131   return FAILURE;
3132 }
3133
3134
3135 /* Resolve a subroutine call not known to be generic nor specific.  */
3136
3137 static gfc_try
3138 resolve_unknown_s (gfc_code *c)
3139 {
3140   gfc_symbol *sym;
3141
3142   sym = c->symtree->n.sym;
3143
3144   if (sym->attr.dummy)
3145     {
3146       sym->attr.proc = PROC_DUMMY;
3147       goto found;
3148     }
3149
3150   /* See if we have an intrinsic function reference.  */
3151
3152   if (gfc_is_intrinsic (sym, 1, c->loc))
3153     {
3154       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3155         return SUCCESS;
3156       return FAILURE;
3157     }
3158
3159   /* The reference is to an external name.  */
3160
3161 found:
3162   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3163
3164   c->resolved_sym = sym;
3165
3166   pure_subroutine (c, sym);
3167
3168   return SUCCESS;
3169 }
3170
3171
3172 /* Resolve a subroutine call.  Although it was tempting to use the same code
3173    for functions, subroutines and functions are stored differently and this
3174    makes things awkward.  */
3175
3176 static gfc_try
3177 resolve_call (gfc_code *c)
3178 {
3179   gfc_try t;
3180   procedure_type ptype = PROC_INTRINSIC;
3181   gfc_symbol *csym, *sym;
3182   bool no_formal_args;
3183
3184   csym = c->symtree ? c->symtree->n.sym : NULL;
3185
3186   if (csym && csym->ts.type != BT_UNKNOWN)
3187     {
3188       gfc_error ("'%s' at %L has a type, which is not consistent with "
3189                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3190       return FAILURE;
3191     }
3192
3193   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3194     {
3195       gfc_symtree *st;
3196       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
3197       sym = st ? st->n.sym : NULL;
3198       if (sym && csym != sym
3199               && sym->ns == gfc_current_ns
3200               && sym->attr.flavor == FL_PROCEDURE
3201               && sym->attr.contained)
3202         {
3203           sym->refs++;
3204           if (csym->attr.generic)
3205             c->symtree->n.sym = sym;
3206           else
3207             c->symtree = st;
3208           csym = c->symtree->n.sym;
3209         }
3210     }
3211
3212   /* If this ia a deferred TBP with an abstract interface
3213      (which may of course be referenced), c->expr1 will be set.  */
3214   if (csym && csym->attr.abstract && !c->expr1)
3215     {
3216       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3217                  csym->name, &c->loc);
3218       return FAILURE;
3219     }
3220
3221   /* Subroutines without the RECURSIVE attribution are not allowed to
3222    * call themselves.  */
3223   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3224     {
3225       if (csym->attr.entry && csym->ns->entries)
3226         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3227                    " subroutine '%s' is not RECURSIVE",
3228                    csym->name, &c->loc, csym->ns->entries->sym->name);
3229       else
3230         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3231                    " is not RECURSIVE", csym->name, &c->loc);
3232
3233       t = FAILURE;
3234     }
3235
3236   /* Switch off assumed size checking and do this again for certain kinds
3237      of procedure, once the procedure itself is resolved.  */
3238   need_full_assumed_size++;
3239
3240   if (csym)
3241     ptype = csym->attr.proc;
3242
3243   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3244   if (resolve_actual_arglist (c->ext.actual, ptype,
3245                               no_formal_args) == FAILURE)
3246     return FAILURE;
3247
3248   /* Resume assumed_size checking.  */
3249   need_full_assumed_size--;
3250
3251   /* If external, check for usage.  */
3252   if (csym && is_external_proc (csym))
3253     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3254
3255   t = SUCCESS;
3256   if (c->resolved_sym == NULL)
3257     {
3258       c->resolved_isym = NULL;
3259       switch (procedure_kind (csym))
3260         {
3261         case PTYPE_GENERIC:
3262           t = resolve_generic_s (c);
3263           break;
3264
3265         case PTYPE_SPECIFIC:
3266           t = resolve_specific_s (c);
3267           break;
3268
3269         case PTYPE_UNKNOWN:
3270           t = resolve_unknown_s (c);
3271           break;
3272
3273         default:
3274           gfc_internal_error ("resolve_subroutine(): bad function type");
3275         }
3276     }
3277
3278   /* Some checks of elemental subroutine actual arguments.  */
3279   if (resolve_elemental_actual (NULL, c) == FAILURE)
3280     return FAILURE;
3281
3282   if (t == SUCCESS && !(c->resolved_sym && c->resolved_sym->attr.elemental))
3283     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
3284   return t;
3285 }
3286
3287
3288 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3289    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3290    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3291    if their shapes do not match.  If either op1->shape or op2->shape is
3292    NULL, return SUCCESS.  */
3293
3294 static gfc_try
3295 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3296 {
3297   gfc_try t;
3298   int i;
3299
3300   t = SUCCESS;
3301
3302   if (op1->shape != NULL && op2->shape != NULL)
3303     {
3304       for (i = 0; i < op1->rank; i++)
3305         {
3306           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3307            {
3308              gfc_error ("Shapes for operands at %L and %L are not conformable",
3309                          &op1->where, &op2->where);
3310              t = FAILURE;
3311              break;
3312            }
3313         }
3314     }
3315
3316   return t;
3317 }
3318
3319
3320 /* Resolve an operator expression node.  This can involve replacing the
3321    operation with a user defined function call.  */
3322
3323 static gfc_try
3324 resolve_operator (gfc_expr *e)
3325 {
3326   gfc_expr *op1, *op2;
3327   char msg[200];
3328   bool dual_locus_error;
3329   gfc_try t;
3330
3331   /* Resolve all subnodes-- give them types.  */
3332
3333   switch (e->value.op.op)
3334     {
3335     default:
3336       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3337         return FAILURE;
3338
3339     /* Fall through...  */
3340
3341     case INTRINSIC_NOT:
3342     case INTRINSIC_UPLUS:
3343     case INTRINSIC_UMINUS:
3344     case INTRINSIC_PARENTHESES:
3345       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3346         return FAILURE;
3347       break;
3348     }
3349
3350   /* Typecheck the new node.  */
3351
3352   op1 = e->value.op.op1;
3353   op2 = e->value.op.op2;
3354   dual_locus_error = false;
3355
3356   if ((op1 && op1->expr_type == EXPR_NULL)
3357       || (op2 && op2->expr_type == EXPR_NULL))
3358     {
3359       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3360       goto bad_op;
3361     }
3362
3363   switch (e->value.op.op)
3364     {
3365     case INTRINSIC_UPLUS:
3366     case INTRINSIC_UMINUS:
3367       if (op1->ts.type == BT_INTEGER
3368           || op1->ts.type == BT_REAL
3369           || op1->ts.type == BT_COMPLEX)
3370         {
3371           e->ts = op1->ts;
3372           break;
3373         }
3374
3375       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3376                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3377       goto bad_op;
3378
3379     case INTRINSIC_PLUS:
3380     case INTRINSIC_MINUS:
3381     case INTRINSIC_TIMES:
3382     case INTRINSIC_DIVIDE:
3383     case INTRINSIC_POWER:
3384       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3385         {
3386           gfc_type_convert_binary (e, 1);
3387           break;
3388         }
3389
3390       sprintf (msg,
3391                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3392                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3393                gfc_typename (&op2->ts));
3394       goto bad_op;
3395
3396     case INTRINSIC_CONCAT:
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_CHARACTER;
3401           e->ts.kind = op1->ts.kind;
3402           break;
3403         }
3404
3405       sprintf (msg,
3406                _("Operands of string concatenation operator at %%L are %s/%s"),
3407                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3408       goto bad_op;
3409
3410     case INTRINSIC_AND:
3411     case INTRINSIC_OR:
3412     case INTRINSIC_EQV:
3413     case INTRINSIC_NEQV:
3414       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3415         {
3416           e->ts.type = BT_LOGICAL;
3417           e->ts.kind = gfc_kind_max (op1, op2);
3418           if (op1->ts.kind < e->ts.kind)
3419             gfc_convert_type (op1, &e->ts, 2);
3420           else if (op2->ts.kind < e->ts.kind)
3421             gfc_convert_type (op2, &e->ts, 2);
3422           break;
3423         }
3424
3425       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3426                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3427                gfc_typename (&op2->ts));
3428
3429       goto bad_op;
3430
3431     case INTRINSIC_NOT:
3432       if (op1->ts.type == BT_LOGICAL)
3433         {
3434           e->ts.type = BT_LOGICAL;
3435           e->ts.kind = op1->ts.kind;
3436           break;
3437         }
3438
3439       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3440                gfc_typename (&op1->ts));
3441       goto bad_op;
3442
3443     case INTRINSIC_GT:
3444     case INTRINSIC_GT_OS:
3445     case INTRINSIC_GE:
3446     case INTRINSIC_GE_OS:
3447     case INTRINSIC_LT:
3448     case INTRINSIC_LT_OS:
3449     case INTRINSIC_LE:
3450     case INTRINSIC_LE_OS:
3451       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3452         {
3453           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3454           goto bad_op;
3455         }
3456
3457       /* Fall through...  */
3458
3459     case INTRINSIC_EQ:
3460     case INTRINSIC_EQ_OS:
3461     case INTRINSIC_NE:
3462     case INTRINSIC_NE_OS:
3463       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3464           && op1->ts.kind == op2->ts.kind)
3465         {
3466           e->ts.type = BT_LOGICAL;
3467           e->ts.kind = gfc_default_logical_kind;
3468           break;
3469         }
3470
3471       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3472         {
3473           gfc_type_convert_binary (e, 1);
3474
3475           e->ts.type = BT_LOGICAL;
3476           e->ts.kind = gfc_default_logical_kind;
3477           break;
3478         }
3479
3480       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3481         sprintf (msg,
3482                  _("Logicals at %%L must be compared with %s instead of %s"),
3483                  (e->value.op.op == INTRINSIC_EQ 
3484                   || e->value.op.op == INTRINSIC_EQ_OS)
3485                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3486       else
3487         sprintf (msg,
3488                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3489                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3490                  gfc_typename (&op2->ts));
3491
3492       goto bad_op;
3493
3494     case INTRINSIC_USER:
3495       if (e->value.op.uop->op == NULL)
3496         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3497       else if (op2 == NULL)
3498         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3499                  e->value.op.uop->name, gfc_typename (&op1->ts));
3500       else
3501         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3502                  e->value.op.uop->name, gfc_typename (&op1->ts),
3503                  gfc_typename (&op2->ts));
3504
3505       goto bad_op;
3506
3507     case INTRINSIC_PARENTHESES:
3508       e->ts = op1->ts;
3509       if (e->ts.type == BT_CHARACTER)
3510         e->ts.u.cl = op1->ts.u.cl;
3511       break;
3512
3513     default:
3514       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3515     }
3516
3517   /* Deal with arrayness of an operand through an operator.  */
3518
3519   t = SUCCESS;
3520
3521   switch (e->value.op.op)
3522     {
3523     case INTRINSIC_PLUS:
3524     case INTRINSIC_MINUS:
3525     case INTRINSIC_TIMES:
3526     case INTRINSIC_DIVIDE:
3527     case INTRINSIC_POWER:
3528     case INTRINSIC_CONCAT:
3529     case INTRINSIC_AND:
3530     case INTRINSIC_OR:
3531     case INTRINSIC_EQV:
3532     case INTRINSIC_NEQV:
3533     case INTRINSIC_EQ:
3534     case INTRINSIC_EQ_OS:
3535     case INTRINSIC_NE:
3536     case INTRINSIC_NE_OS:
3537     case INTRINSIC_GT:
3538     case INTRINSIC_GT_OS:
3539     case INTRINSIC_GE:
3540     case INTRINSIC_GE_OS:
3541     case INTRINSIC_LT:
3542     case INTRINSIC_LT_OS:
3543     case INTRINSIC_LE:
3544     case INTRINSIC_LE_OS:
3545
3546       if (op1->rank == 0 && op2->rank == 0)
3547         e->rank = 0;
3548
3549       if (op1->rank == 0 && op2->rank != 0)
3550         {
3551           e->rank = op2->rank;
3552
3553           if (e->shape == NULL)
3554             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3555         }
3556
3557       if (op1->rank != 0 && op2->rank == 0)
3558         {
3559           e->rank = op1->rank;
3560
3561           if (e->shape == NULL)
3562             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3563         }
3564
3565       if (op1->rank != 0 && op2->rank != 0)
3566         {
3567           if (op1->rank == op2->rank)
3568             {
3569               e->rank = op1->rank;
3570               if (e->shape == NULL)
3571                 {
3572                   t = compare_shapes(op1, op2);
3573                   if (t == FAILURE)
3574                     e->shape = NULL;
3575                   else
3576                 e->shape = gfc_copy_shape (op1->shape, op1->rank);
3577                 }
3578             }
3579           else
3580             {
3581               /* Allow higher level expressions to work.  */
3582               e->rank = 0;
3583
3584               /* Try user-defined operators, and otherwise throw an error.  */
3585               dual_locus_error = true;
3586               sprintf (msg,
3587                        _("Inconsistent ranks for operator at %%L and %%L"));
3588               goto bad_op;
3589             }
3590         }
3591
3592       break;
3593
3594     case INTRINSIC_PARENTHESES:
3595     case INTRINSIC_NOT:
3596     case INTRINSIC_UPLUS:
3597     case INTRINSIC_UMINUS:
3598       /* Simply copy arrayness attribute */
3599       e->rank = op1->rank;
3600
3601       if (e->shape == NULL)
3602         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3603
3604       break;
3605
3606     default:
3607       break;
3608     }
3609
3610   /* Attempt to simplify the expression.  */
3611   if (t == SUCCESS)
3612     {
3613       t = gfc_simplify_expr (e, 0);
3614       /* Some calls do not succeed in simplification and return FAILURE
3615          even though there is no error; e.g. variable references to
3616          PARAMETER arrays.  */
3617       if (!gfc_is_constant_expr (e))
3618         t = SUCCESS;
3619     }
3620   return t;
3621
3622 bad_op:
3623
3624   {
3625     bool real_error;
3626     if (gfc_extend_expr (e, &real_error) == SUCCESS)
3627       return SUCCESS;
3628
3629     if (real_error)
3630       return FAILURE;
3631   }
3632
3633   if (dual_locus_error)
3634     gfc_error (msg, &op1->where, &op2->where);
3635   else
3636     gfc_error (msg, &e->where);
3637
3638   return FAILURE;
3639 }
3640
3641
3642 /************** Array resolution subroutines **************/
3643
3644 typedef enum
3645 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
3646 comparison;
3647
3648 /* Compare two integer expressions.  */
3649
3650 static comparison
3651 compare_bound (gfc_expr *a, gfc_expr *b)
3652 {
3653   int i;
3654
3655   if (a == NULL || a->expr_type != EXPR_CONSTANT
3656       || b == NULL || b->expr_type != EXPR_CONSTANT)
3657     return CMP_UNKNOWN;
3658
3659   /* If either of the types isn't INTEGER, we must have
3660      raised an error earlier.  */
3661
3662   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
3663     return CMP_UNKNOWN;
3664
3665   i = mpz_cmp (a->value.integer, b->value.integer);
3666
3667   if (i < 0)
3668     return CMP_LT;
3669   if (i > 0)
3670     return CMP_GT;
3671   return CMP_EQ;
3672 }
3673
3674
3675 /* Compare an integer expression with an integer.  */
3676
3677 static comparison
3678 compare_bound_int (gfc_expr *a, int b)
3679 {
3680   int i;
3681
3682   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3683     return CMP_UNKNOWN;
3684
3685   if (a->ts.type != BT_INTEGER)
3686     gfc_internal_error ("compare_bound_int(): Bad expression");
3687
3688   i = mpz_cmp_si (a->value.integer, b);
3689
3690   if (i < 0)
3691     return CMP_LT;
3692   if (i > 0)
3693     return CMP_GT;
3694   return CMP_EQ;
3695 }
3696
3697
3698 /* Compare an integer expression with a mpz_t.  */
3699
3700 static comparison
3701 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
3702 {
3703   int i;
3704
3705   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3706     return CMP_UNKNOWN;
3707
3708   if (a->ts.type != BT_INTEGER)
3709     gfc_internal_error ("compare_bound_int(): Bad expression");
3710
3711   i = mpz_cmp (a->value.integer, b);
3712
3713   if (i < 0)
3714     return CMP_LT;
3715   if (i > 0)
3716     return CMP_GT;
3717   return CMP_EQ;
3718 }
3719
3720
3721 /* Compute the last value of a sequence given by a triplet.  
3722    Return 0 if it wasn't able to compute the last value, or if the
3723    sequence if empty, and 1 otherwise.  */
3724
3725 static int
3726 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
3727                                 gfc_expr *stride, mpz_t last)
3728 {
3729   mpz_t rem;
3730
3731   if (start == NULL || start->expr_type != EXPR_CONSTANT
3732       || end == NULL || end->expr_type != EXPR_CONSTANT
3733       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
3734     return 0;
3735
3736   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
3737       || (stride != NULL && stride->ts.type != BT_INTEGER))
3738     return 0;
3739
3740   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
3741     {
3742       if (compare_bound (start, end) == CMP_GT)
3743         return 0;
3744       mpz_set (last, end->value.integer);
3745       return 1;
3746     }
3747
3748   if (compare_bound_int (stride, 0) == CMP_GT)
3749     {
3750       /* Stride is positive */
3751       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
3752         return 0;
3753     }
3754   else
3755     {
3756       /* Stride is negative */
3757       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
3758         return 0;
3759     }
3760
3761   mpz_init (rem);
3762   mpz_sub (rem, end->value.integer, start->value.integer);
3763   mpz_tdiv_r (rem, rem, stride->value.integer);
3764   mpz_sub (last, end->value.integer, rem);
3765   mpz_clear (rem);
3766
3767   return 1;
3768 }
3769
3770
3771 /* Compare a single dimension of an array reference to the array
3772    specification.  */
3773
3774 static gfc_try
3775 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
3776 {
3777   mpz_t last_value;
3778
3779   if (ar->dimen_type[i] == DIMEN_STAR)
3780     {
3781       gcc_assert (ar->stride[i] == NULL);
3782       /* This implies [*] as [*:] and [*:3] are not possible.  */
3783       if (ar->start[i] == NULL)
3784         {
3785           gcc_assert (ar->end[i] == NULL);
3786           return SUCCESS;
3787         }
3788     }
3789
3790 /* Given start, end and stride values, calculate the minimum and
3791    maximum referenced indexes.  */
3792
3793   switch (ar->dimen_type[i])
3794     {
3795     case DIMEN_VECTOR:
3796       break;
3797
3798     case DIMEN_STAR:
3799     case DIMEN_ELEMENT:
3800       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
3801         {
3802           if (i < as->rank)
3803             gfc_warning ("Array reference at %L is out of bounds "
3804                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
3805                          mpz_get_si (ar->start[i]->value.integer),
3806                          mpz_get_si (as->lower[i]->value.integer), i+1);
3807           else
3808             gfc_warning ("Array reference at %L is out of bounds "
3809                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
3810                          mpz_get_si (ar->start[i]->value.integer),
3811                          mpz_get_si (as->lower[i]->value.integer),
3812                          i + 1 - as->rank);
3813           return SUCCESS;
3814         }
3815       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
3816         {
3817           if (i < as->rank)
3818             gfc_warning ("Array reference at %L is out of bounds "
3819                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
3820                          mpz_get_si (ar->start[i]->value.integer),
3821                          mpz_get_si (as->upper[i]->value.integer), i+1);
3822           else
3823             gfc_warning ("Array reference at %L is out of bounds "
3824                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
3825                          mpz_get_si (ar->start[i]->value.integer),
3826                          mpz_get_si (as->upper[i]->value.integer),
3827                          i + 1 - as->rank);
3828           return SUCCESS;
3829         }
3830
3831       break;
3832
3833     case DIMEN_RANGE:
3834       {
3835 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
3836 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
3837
3838         comparison comp_start_end = compare_bound (AR_START, AR_END);
3839
3840         /* Check for zero stride, which is not allowed.  */
3841         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
3842           {
3843             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
3844             return FAILURE;
3845           }
3846
3847         /* if start == len || (stride > 0 && start < len)
3848                            || (stride < 0 && start > len),
3849            then the array section contains at least one element.  In this
3850            case, there is an out-of-bounds access if
3851            (start < lower || start > upper).  */
3852         if (compare_bound (AR_START, AR_END) == CMP_EQ
3853             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
3854                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
3855             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
3856                 && comp_start_end == CMP_GT))
3857           {
3858             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
3859               {
3860                 gfc_warning ("Lower array reference at %L is out of bounds "
3861                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3862                        mpz_get_si (AR_START->value.integer),
3863                        mpz_get_si (as->lower[i]->value.integer), i+1);
3864                 return SUCCESS;
3865               }
3866             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
3867               {
3868                 gfc_warning ("Lower array reference at %L is out of bounds "
3869                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3870                        mpz_get_si (AR_START->value.integer),
3871                        mpz_get_si (as->upper[i]->value.integer), i+1);
3872                 return SUCCESS;
3873               }
3874           }
3875
3876         /* If we can compute the highest index of the array section,
3877            then it also has to be between lower and upper.  */
3878         mpz_init (last_value);
3879         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
3880                                             last_value))
3881           {
3882             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
3883               {
3884                 gfc_warning ("Upper array reference at %L is out of bounds "
3885                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3886                        mpz_get_si (last_value),
3887                        mpz_get_si (as->lower[i]->value.integer), i+1);
3888                 mpz_clear (last_value);
3889                 return SUCCESS;
3890               }
3891             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
3892               {
3893                 gfc_warning ("Upper array reference at %L is out of bounds "
3894                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3895                        mpz_get_si (last_value),
3896                        mpz_get_si (as->upper[i]->value.integer), i+1);
3897                 mpz_clear (last_value);
3898                 return SUCCESS;
3899               }
3900           }
3901         mpz_clear (last_value);
3902
3903 #undef AR_START
3904 #undef AR_END
3905       }
3906       break;
3907
3908     default:
3909       gfc_internal_error ("check_dimension(): Bad array reference");
3910     }
3911
3912   return SUCCESS;
3913 }
3914
3915
3916 /* Compare an array reference with an array specification.  */
3917
3918 static gfc_try
3919 compare_spec_to_ref (gfc_array_ref *ar)
3920 {
3921   gfc_array_spec *as;
3922   int i;
3923
3924   as = ar->as;
3925   i = as->rank - 1;
3926   /* TODO: Full array sections are only allowed as actual parameters.  */
3927   if (as->type == AS_ASSUMED_SIZE
3928       && (/*ar->type == AR_FULL
3929           ||*/ (ar->type == AR_SECTION
3930               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
3931     {
3932       gfc_error ("Rightmost upper bound of assumed size array section "
3933                  "not specified at %L", &ar->where);
3934       return FAILURE;
3935     }
3936
3937   if (ar->type == AR_FULL)
3938     return SUCCESS;
3939
3940   if (as->rank != ar->dimen)
3941     {
3942       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
3943                  &ar->where, ar->dimen, as->rank);
3944       return FAILURE;
3945     }
3946
3947   /* ar->codimen == 0 is a local array.  */
3948   if (as->corank != ar->codimen && ar->codimen != 0)
3949     {
3950       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
3951                  &ar->where, ar->codimen, as->corank);
3952       return FAILURE;
3953     }
3954
3955   for (i = 0; i < as->rank; i++)
3956     if (check_dimension (i, ar, as) == FAILURE)
3957       return FAILURE;
3958
3959   /* Local access has no coarray spec.  */
3960   if (ar->codimen != 0)
3961     for (i = as->rank; i < as->rank + as->corank; i++)
3962       {
3963         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate)
3964           {
3965             gfc_error ("Coindex of codimension %d must be a scalar at %L",
3966                        i + 1 - as->rank, &ar->where);
3967             return FAILURE;
3968           }
3969         if (check_dimension (i, ar, as) == FAILURE)
3970           return FAILURE;
3971       }
3972
3973   return SUCCESS;
3974 }
3975
3976
3977 /* Resolve one part of an array index.  */
3978
3979 gfc_try
3980 gfc_resolve_index (gfc_expr *index, int check_scalar)
3981 {
3982   gfc_typespec ts;
3983
3984   if (index == NULL)
3985     return SUCCESS;
3986
3987   if (gfc_resolve_expr (index) == FAILURE)
3988     return FAILURE;
3989
3990   if (check_scalar && index->rank != 0)
3991     {
3992       gfc_error ("Array index at %L must be scalar", &index->where);
3993       return FAILURE;
3994     }
3995
3996   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
3997     {
3998       gfc_error ("Array index at %L must be of INTEGER type, found %s",
3999                  &index->where, gfc_basic_typename (index->ts.type));
4000       return FAILURE;
4001     }
4002
4003   if (index->ts.type == BT_REAL)
4004     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
4005                         &index->where) == FAILURE)
4006       return FAILURE;
4007
4008   if (index->ts.kind != gfc_index_integer_kind
4009       || index->ts.type != BT_INTEGER)
4010     {
4011       gfc_clear_ts (&ts);
4012       ts.type = BT_INTEGER;
4013       ts.kind = gfc_index_integer_kind;
4014
4015       gfc_convert_type_warn (index, &ts, 2, 0);
4016     }
4017
4018   return SUCCESS;
4019 }
4020
4021 /* Resolve a dim argument to an intrinsic function.  */
4022
4023 gfc_try
4024 gfc_resolve_dim_arg (gfc_expr *dim)
4025 {
4026   if (dim == NULL)
4027     return SUCCESS;
4028
4029   if (gfc_resolve_expr (dim) == FAILURE)
4030     return FAILURE;
4031
4032   if (dim->rank != 0)
4033     {
4034       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4035       return FAILURE;
4036
4037     }
4038
4039   if (dim->ts.type != BT_INTEGER)
4040     {
4041       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4042       return FAILURE;
4043     }
4044
4045   if (dim->ts.kind != gfc_index_integer_kind)
4046     {
4047       gfc_typespec ts;
4048
4049       gfc_clear_ts (&ts);
4050       ts.type = BT_INTEGER;
4051       ts.kind = gfc_index_integer_kind;
4052
4053       gfc_convert_type_warn (dim, &ts, 2, 0);
4054     }
4055
4056   return SUCCESS;
4057 }
4058
4059 /* Given an expression that contains array references, update those array
4060    references to point to the right array specifications.  While this is
4061    filled in during matching, this information is difficult to save and load
4062    in a module, so we take care of it here.
4063
4064    The idea here is that the original array reference comes from the
4065    base symbol.  We traverse the list of reference structures, setting
4066    the stored reference to references.  Component references can
4067    provide an additional array specification.  */
4068
4069 static void
4070 find_array_spec (gfc_expr *e)
4071 {
4072   gfc_array_spec *as;
4073   gfc_component *c;
4074   gfc_symbol *derived;
4075   gfc_ref *ref;
4076
4077   if (e->symtree->n.sym->ts.type == BT_CLASS)
4078     as = e->symtree->n.sym->ts.u.derived->components->as;
4079   else
4080     as = e->symtree->n.sym->as;
4081   derived = NULL;
4082
4083   for (ref = e->ref; ref; ref = ref->next)
4084     switch (ref->type)
4085       {
4086       case REF_ARRAY:
4087         if (as == NULL)
4088           gfc_internal_error ("find_array_spec(): Missing spec");
4089
4090         ref->u.ar.as = as;
4091         as = NULL;
4092         break;
4093
4094       case REF_COMPONENT:
4095         if (derived == NULL)
4096           derived = e->symtree->n.sym->ts.u.derived;
4097
4098         if (derived->attr.is_class)
4099           derived = derived->components->ts.u.derived;
4100
4101         c = derived->components;
4102
4103         for (; c; c = c->next)
4104           if (c == ref->u.c.component)
4105             {
4106               /* Track the sequence of component references.  */
4107               if (c->ts.type == BT_DERIVED)
4108                 derived = c->ts.u.derived;
4109               break;
4110             }
4111
4112         if (c == NULL)
4113           gfc_internal_error ("find_array_spec(): Component not found");
4114
4115         if (c->attr.dimension)
4116           {
4117             if (as != NULL)
4118               gfc_internal_error ("find_array_spec(): unused as(1)");
4119             as = c->as;
4120           }
4121
4122         break;
4123
4124       case REF_SUBSTRING:
4125         break;
4126       }
4127
4128   if (as != NULL)
4129     gfc_internal_error ("find_array_spec(): unused as(2)");
4130 }
4131
4132
4133 /* Resolve an array reference.  */
4134
4135 static gfc_try
4136 resolve_array_ref (gfc_array_ref *ar)
4137 {
4138   int i, check_scalar;
4139   gfc_expr *e;
4140
4141   for (i = 0; i < ar->dimen + ar->codimen; i++)
4142     {
4143       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4144
4145       if (gfc_resolve_index (ar->start[i], check_scalar) == FAILURE)
4146         return FAILURE;
4147       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4148         return FAILURE;
4149       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4150         return FAILURE;
4151
4152       e = ar->start[i];
4153
4154       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4155         switch (e->rank)
4156           {
4157           case 0:
4158             ar->dimen_type[i] = DIMEN_ELEMENT;
4159             break;
4160
4161           case 1:
4162             ar->dimen_type[i] = DIMEN_VECTOR;
4163             if (e->expr_type == EXPR_VARIABLE
4164                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4165               ar->start[i] = gfc_get_parentheses (e);
4166             break;
4167
4168           default:
4169             gfc_error ("Array index at %L is an array of rank %d",
4170                        &ar->c_where[i], e->rank);
4171             return FAILURE;
4172           }
4173     }
4174
4175   if (ar->type == AR_FULL && ar->as->rank == 0)
4176     ar->type = AR_ELEMENT;
4177
4178   /* If the reference type is unknown, figure out what kind it is.  */
4179
4180   if (ar->type == AR_UNKNOWN)
4181     {
4182       ar->type = AR_ELEMENT;
4183       for (i = 0; i < ar->dimen; i++)
4184         if (ar->dimen_type[i] == DIMEN_RANGE
4185             || ar->dimen_type[i] == DIMEN_VECTOR)
4186           {
4187             ar->type = AR_SECTION;
4188             break;
4189           }
4190     }
4191
4192   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4193     return FAILURE;
4194
4195   return SUCCESS;
4196 }
4197
4198
4199 static gfc_try
4200 resolve_substring (gfc_ref *ref)
4201 {
4202   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4203
4204   if (ref->u.ss.start != NULL)
4205     {
4206       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4207         return FAILURE;
4208
4209       if (ref->u.ss.start->ts.type != BT_INTEGER)
4210         {
4211           gfc_error ("Substring start index at %L must be of type INTEGER",
4212                      &ref->u.ss.start->where);
4213           return FAILURE;
4214         }
4215
4216       if (ref->u.ss.start->rank != 0)
4217         {
4218           gfc_error ("Substring start index at %L must be scalar",
4219                      &ref->u.ss.start->where);
4220           return FAILURE;
4221         }
4222
4223       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4224           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4225               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4226         {
4227           gfc_error ("Substring start index at %L is less than one",
4228                      &ref->u.ss.start->where);
4229           return FAILURE;
4230         }
4231     }
4232
4233   if (ref->u.ss.end != NULL)
4234     {
4235       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4236         return FAILURE;
4237
4238       if (ref->u.ss.end->ts.type != BT_INTEGER)
4239         {
4240           gfc_error ("Substring end index at %L must be of type INTEGER",
4241                      &ref->u.ss.end->where);
4242           return FAILURE;
4243         }
4244
4245       if (ref->u.ss.end->rank != 0)
4246         {
4247           gfc_error ("Substring end index at %L must be scalar",
4248                      &ref->u.ss.end->where);
4249           return FAILURE;
4250         }
4251
4252       if (ref->u.ss.length != NULL
4253           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4254           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4255               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4256         {
4257           gfc_error ("Substring end index at %L exceeds the string length",
4258                      &ref->u.ss.start->where);
4259           return FAILURE;
4260         }
4261
4262       if (compare_bound_mpz_t (ref->u.ss.end,
4263                                gfc_integer_kinds[k].huge) == CMP_GT
4264           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4265               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4266         {
4267           gfc_error ("Substring end index at %L is too large",
4268                      &ref->u.ss.end->where);
4269           return FAILURE;
4270         }
4271     }
4272
4273   return SUCCESS;
4274 }
4275
4276
4277 /* This function supplies missing substring charlens.  */
4278
4279 void
4280 gfc_resolve_substring_charlen (gfc_expr *e)
4281 {
4282   gfc_ref *char_ref;
4283   gfc_expr *start, *end;
4284
4285   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4286     if (char_ref->type == REF_SUBSTRING)
4287       break;
4288
4289   if (!char_ref)
4290     return;
4291
4292   gcc_assert (char_ref->next == NULL);
4293
4294   if (e->ts.u.cl)
4295     {
4296       if (e->ts.u.cl->length)
4297         gfc_free_expr (e->ts.u.cl->length);
4298       else if (e->expr_type == EXPR_VARIABLE
4299                  && e->symtree->n.sym->attr.dummy)
4300         return;
4301     }
4302
4303   e->ts.type = BT_CHARACTER;
4304   e->ts.kind = gfc_default_character_kind;
4305
4306   if (!e->ts.u.cl)
4307     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4308
4309   if (char_ref->u.ss.start)
4310     start = gfc_copy_expr (char_ref->u.ss.start);
4311   else
4312     start = gfc_int_expr (1);
4313
4314   if (char_ref->u.ss.end)
4315     end = gfc_copy_expr (char_ref->u.ss.end);
4316   else if (e->expr_type == EXPR_VARIABLE)
4317     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4318   else
4319     end = NULL;
4320
4321   if (!start || !end)
4322     return;
4323
4324   /* Length = (end - start +1).  */
4325   e->ts.u.cl->length = gfc_subtract (end, start);
4326   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length, gfc_int_expr (1));
4327
4328   e->ts.u.cl->length->ts.type = BT_INTEGER;
4329   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4330
4331   /* Make sure that the length is simplified.  */
4332   gfc_simplify_expr (e->ts.u.cl->length, 1);
4333   gfc_resolve_expr (e->ts.u.cl->length);
4334 }
4335
4336
4337 /* Resolve subtype references.  */
4338
4339 static gfc_try
4340 resolve_ref (gfc_expr *expr)
4341 {
4342   int current_part_dimension, n_components, seen_part_dimension;
4343   gfc_ref *ref;
4344
4345   for (ref = expr->ref; ref; ref = ref->next)
4346     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4347       {
4348         find_array_spec (expr);
4349         break;
4350       }
4351
4352   for (ref = expr->ref; ref; ref = ref->next)
4353     switch (ref->type)
4354       {
4355       case REF_ARRAY:
4356         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4357           return FAILURE;
4358         break;
4359
4360       case REF_COMPONENT:
4361         break;
4362
4363       case REF_SUBSTRING:
4364         resolve_substring (ref);
4365         break;
4366       }
4367
4368   /* Check constraints on part references.  */
4369
4370   current_part_dimension = 0;
4371   seen_part_dimension = 0;
4372   n_components = 0;
4373
4374   for (ref = expr->ref; ref; ref = ref->next)
4375     {
4376       switch (ref->type)
4377         {
4378         case REF_ARRAY:
4379           switch (ref->u.ar.type)
4380             {
4381             case AR_FULL:
4382               /* Coarray scalar.  */
4383               if (ref->u.ar.as->rank == 0)
4384                 {
4385                   current_part_dimension = 0;
4386                   break;
4387                 }
4388               /* Fall through.  */
4389             case AR_SECTION:
4390               current_part_dimension = 1;
4391               break;
4392
4393             case AR_ELEMENT:
4394               current_part_dimension = 0;
4395               break;
4396
4397             case AR_UNKNOWN:
4398               gfc_internal_error ("resolve_ref(): Bad array reference");
4399             }
4400
4401           break;
4402
4403         case REF_COMPONENT:
4404           if (current_part_dimension || seen_part_dimension)
4405             {
4406               /* F03:C614.  */
4407               if (ref->u.c.component->attr.pointer
4408                   || ref->u.c.component->attr.proc_pointer)
4409                 {
4410                   gfc_error ("Component to the right of a part reference "
4411                              "with nonzero rank must not have the POINTER "
4412                              "attribute at %L", &expr->where);
4413                   return FAILURE;
4414                 }
4415               else if (ref->u.c.component->attr.allocatable)
4416                 {
4417                   gfc_error ("Component to the right of a part reference "
4418                              "with nonzero rank must not have the ALLOCATABLE "
4419                              "attribute at %L", &expr->where);
4420                   return FAILURE;
4421                 }
4422             }
4423
4424           n_components++;
4425           break;
4426
4427         case REF_SUBSTRING:
4428           break;
4429         }
4430
4431       if (((ref->type == REF_COMPONENT && n_components > 1)
4432            || ref->next == NULL)
4433           && current_part_dimension
4434           && seen_part_dimension)
4435         {
4436           gfc_error ("Two or more part references with nonzero rank must "
4437                      "not be specified at %L", &expr->where);
4438           return FAILURE;
4439         }
4440
4441       if (ref->type == REF_COMPONENT)
4442         {
4443           if (current_part_dimension)
4444             seen_part_dimension = 1;
4445
4446           /* reset to make sure */
4447           current_part_dimension = 0;
4448         }
4449     }
4450
4451   return SUCCESS;
4452 }
4453
4454
4455 /* Given an expression, determine its shape.  This is easier than it sounds.
4456    Leaves the shape array NULL if it is not possible to determine the shape.  */
4457
4458 static void
4459 expression_shape (gfc_expr *e)
4460 {
4461   mpz_t array[GFC_MAX_DIMENSIONS];
4462   int i;
4463
4464   if (e->rank == 0 || e->shape != NULL)
4465     return;
4466
4467   for (i = 0; i < e->rank; i++)
4468     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4469       goto fail;
4470
4471   e->shape = gfc_get_shape (e->rank);
4472
4473   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4474
4475   return;
4476
4477 fail:
4478   for (i--; i >= 0; i--)
4479     mpz_clear (array[i]);
4480 }
4481
4482
4483 /* Given a variable expression node, compute the rank of the expression by
4484    examining the base symbol and any reference structures it may have.  */
4485
4486 static void
4487 expression_rank (gfc_expr *e)
4488 {
4489   gfc_ref *ref;
4490   int i, rank;
4491
4492   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4493      could lead to serious confusion...  */
4494   gcc_assert (e->expr_type != EXPR_COMPCALL);
4495
4496   if (e->ref == NULL)
4497     {
4498       if (e->expr_type == EXPR_ARRAY)
4499         goto done;
4500       /* Constructors can have a rank different from one via RESHAPE().  */
4501
4502       if (e->symtree == NULL)
4503         {
4504           e->rank = 0;
4505           goto done;
4506         }
4507
4508       e->rank = (e->symtree->n.sym->as == NULL)
4509                 ? 0 : e->symtree->n.sym->as->rank;
4510       goto done;
4511     }
4512
4513   rank = 0;
4514
4515   for (ref = e->ref; ref; ref = ref->next)
4516     {
4517       if (ref->type != REF_ARRAY)
4518         continue;
4519
4520       if (ref->u.ar.type == AR_FULL)
4521         {
4522           rank = ref->u.ar.as->rank;
4523           break;
4524         }
4525
4526       if (ref->u.ar.type == AR_SECTION)
4527         {
4528           /* Figure out the rank of the section.  */
4529           if (rank != 0)
4530             gfc_internal_error ("expression_rank(): Two array specs");
4531
4532           for (i = 0; i < ref->u.ar.dimen; i++)
4533             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4534                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4535               rank++;
4536
4537           break;
4538         }
4539     }
4540
4541   e->rank = rank;
4542
4543 done:
4544   expression_shape (e);
4545 }
4546
4547
4548 /* Resolve a variable expression.  */
4549
4550 static gfc_try
4551 resolve_variable (gfc_expr *e)
4552 {
4553   gfc_symbol *sym;
4554   gfc_try t;
4555
4556   t = SUCCESS;
4557
4558   if (e->symtree == NULL)
4559     return FAILURE;
4560
4561   if (e->ref && resolve_ref (e) == FAILURE)
4562     return FAILURE;
4563
4564   sym = e->symtree->n.sym;
4565   if (sym->attr.flavor == FL_PROCEDURE
4566       && (!sym->attr.function
4567           || (sym->attr.function && sym->result
4568               && sym->result->attr.proc_pointer
4569               && !sym->result->attr.function)))
4570     {
4571       e->ts.type = BT_PROCEDURE;
4572       goto resolve_procedure;
4573     }
4574
4575   if (sym->ts.type != BT_UNKNOWN)
4576     gfc_variable_attr (e, &e->ts);
4577   else
4578     {
4579       /* Must be a simple variable reference.  */
4580       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
4581         return FAILURE;
4582       e->ts = sym->ts;
4583     }
4584
4585   if (check_assumed_size_reference (sym, e))
4586     return FAILURE;
4587
4588   /* Deal with forward references to entries during resolve_code, to
4589      satisfy, at least partially, 12.5.2.5.  */
4590   if (gfc_current_ns->entries
4591       && current_entry_id == sym->entry_id
4592       && cs_base
4593       && cs_base->current
4594       && cs_base->current->op != EXEC_ENTRY)
4595     {
4596       gfc_entry_list *entry;
4597       gfc_formal_arglist *formal;
4598       int n;
4599       bool seen;
4600
4601       /* If the symbol is a dummy...  */
4602       if (sym->attr.dummy && sym->ns == gfc_current_ns)
4603         {
4604           entry = gfc_current_ns->entries;
4605           seen = false;
4606
4607           /* ...test if the symbol is a parameter of previous entries.  */
4608           for (; entry && entry->id <= current_entry_id; entry = entry->next)
4609             for (formal = entry->sym->formal; formal; formal = formal->next)
4610               {
4611                 if (formal->sym && sym->name == formal->sym->name)
4612                   seen = true;
4613               }
4614
4615           /*  If it has not been seen as a dummy, this is an error.  */
4616           if (!seen)
4617             {
4618               if (specification_expr)
4619                 gfc_error ("Variable '%s', used in a specification expression"
4620                            ", is referenced at %L before the ENTRY statement "
4621                            "in which it is a parameter",
4622                            sym->name, &cs_base->current->loc);
4623               else
4624                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
4625                            "statement in which it is a parameter",
4626                            sym->name, &cs_base->current->loc);
4627               t = FAILURE;
4628             }
4629         }
4630
4631       /* Now do the same check on the specification expressions.  */
4632       specification_expr = 1;
4633       if (sym->ts.type == BT_CHARACTER
4634           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
4635         t = FAILURE;
4636
4637       if (sym->as)
4638         for (n = 0; n < sym->as->rank; n++)
4639           {
4640              specification_expr = 1;
4641              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
4642                t = FAILURE;
4643              specification_expr = 1;
4644              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
4645                t = FAILURE;
4646           }
4647       specification_expr = 0;
4648
4649       if (t == SUCCESS)
4650         /* Update the symbol's entry level.  */
4651         sym->entry_id = current_entry_id + 1;
4652     }
4653
4654 resolve_procedure:
4655   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
4656     t = FAILURE;
4657
4658   /* F2008, C617 and C1229.  */
4659   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
4660       && gfc_is_coindexed (e))
4661     {
4662       gfc_ref *ref, *ref2 = NULL;
4663
4664       if (e->ts.type == BT_CLASS)
4665         {
4666           gfc_error ("Polymorphic subobject of coindexed object at %L",
4667                      &e->where);
4668           t = FAILURE;
4669         }
4670
4671       for (ref = e->ref; ref; ref = ref->next)
4672         {
4673           if (ref->type == REF_COMPONENT)
4674             ref2 = ref;
4675           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
4676             break;
4677         }
4678
4679       for ( ; ref; ref = ref->next)
4680         if (ref->type == REF_COMPONENT)
4681           break;
4682
4683       /* Expression itself is coindexed object.  */
4684       if (ref == NULL)
4685         {
4686           gfc_component *c;
4687           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
4688           for ( ; c; c = c->next)
4689             if (c->attr.allocatable && c->ts.type == BT_CLASS)
4690               {
4691                 gfc_error ("Coindexed object with polymorphic allocatable "
4692                          "subcomponent at %L", &e->where);
4693                 t = FAILURE;
4694                 break;
4695               }
4696         }
4697     }
4698
4699   return t;
4700 }
4701
4702
4703 /* Checks to see that the correct symbol has been host associated.
4704    The only situation where this arises is that in which a twice
4705    contained function is parsed after the host association is made.
4706    Therefore, on detecting this, change the symbol in the expression
4707    and convert the array reference into an actual arglist if the old
4708    symbol is a variable.  */
4709 static bool
4710 check_host_association (gfc_expr *e)
4711 {
4712   gfc_symbol *sym, *old_sym;
4713   gfc_symtree *st;
4714   int n;
4715   gfc_ref *ref;
4716   gfc_actual_arglist *arg, *tail = NULL;
4717   bool retval = e->expr_type == EXPR_FUNCTION;
4718
4719   /*  If the expression is the result of substitution in
4720       interface.c(gfc_extend_expr) because there is no way in
4721       which the host association can be wrong.  */
4722   if (e->symtree == NULL
4723         || e->symtree->n.sym == NULL
4724         || e->user_operator)
4725     return retval;
4726
4727   old_sym = e->symtree->n.sym;
4728
4729   if (gfc_current_ns->parent
4730         && old_sym->ns != gfc_current_ns)
4731     {
4732       /* Use the 'USE' name so that renamed module symbols are
4733          correctly handled.  */
4734       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
4735
4736       if (sym && old_sym != sym
4737               && sym->ts.type == old_sym->ts.type
4738               && sym->attr.flavor == FL_PROCEDURE
4739               && sym->attr.contained)
4740         {
4741           /* Clear the shape, since it might not be valid.  */
4742           if (e->shape != NULL)
4743             {
4744               for (n = 0; n < e->rank; n++)
4745                 mpz_clear (e->shape[n]);
4746
4747               gfc_free (e->shape);
4748             }
4749
4750           /* Give the expression the right symtree!  */
4751           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
4752           gcc_assert (st != NULL);
4753
4754           if (old_sym->attr.flavor == FL_PROCEDURE
4755                 || e->expr_type == EXPR_FUNCTION)
4756             {
4757               /* Original was function so point to the new symbol, since
4758                  the actual argument list is already attached to the
4759                  expression. */
4760               e->value.function.esym = NULL;
4761               e->symtree = st;
4762             }
4763           else
4764             {
4765               /* Original was variable so convert array references into
4766                  an actual arglist. This does not need any checking now
4767                  since gfc_resolve_function will take care of it.  */
4768               e->value.function.actual = NULL;
4769               e->expr_type = EXPR_FUNCTION;
4770               e->symtree = st;
4771
4772               /* Ambiguity will not arise if the array reference is not
4773                  the last reference.  */
4774               for (ref = e->ref; ref; ref = ref->next)
4775                 if (ref->type == REF_ARRAY && ref->next == NULL)
4776                   break;
4777
4778               gcc_assert (ref->type == REF_ARRAY);
4779
4780               /* Grab the start expressions from the array ref and
4781                  copy them into actual arguments.  */
4782               for (n = 0; n < ref->u.ar.dimen; n++)
4783                 {
4784                   arg = gfc_get_actual_arglist ();
4785                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
4786                   if (e->value.function.actual == NULL)
4787                     tail = e->value.function.actual = arg;
4788                   else
4789                     {
4790                       tail->next = arg;
4791                       tail = arg;
4792                     }
4793                 }
4794
4795               /* Dump the reference list and set the rank.  */
4796               gfc_free_ref_list (e->ref);
4797               e->ref = NULL;
4798               e->rank = sym->as ? sym->as->rank : 0;
4799             }
4800
4801           gfc_resolve_expr (e);
4802           sym->refs++;
4803         }
4804     }
4805   /* This might have changed!  */
4806   return e->expr_type == EXPR_FUNCTION;
4807 }
4808
4809
4810 static void
4811 gfc_resolve_character_operator (gfc_expr *e)
4812 {
4813   gfc_expr *op1 = e->value.op.op1;
4814   gfc_expr *op2 = e->value.op.op2;
4815   gfc_expr *e1 = NULL;
4816   gfc_expr *e2 = NULL;
4817
4818   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
4819
4820   if (op1->ts.u.cl && op1->ts.u.cl->length)
4821     e1 = gfc_copy_expr (op1->ts.u.cl->length);
4822   else if (op1->expr_type == EXPR_CONSTANT)
4823     e1 = gfc_int_expr (op1->value.character.length);
4824
4825   if (op2->ts.u.cl && op2->ts.u.cl->length)
4826     e2 = gfc_copy_expr (op2->ts.u.cl->length);
4827   else if (op2->expr_type == EXPR_CONSTANT)
4828     e2 = gfc_int_expr (op2->value.character.length);
4829
4830   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4831
4832   if (!e1 || !e2)
4833     return;
4834
4835   e->ts.u.cl->length = gfc_add (e1, e2);
4836   e->ts.u.cl->length->ts.type = BT_INTEGER;
4837   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4838   gfc_simplify_expr (e->ts.u.cl->length, 0);
4839   gfc_resolve_expr (e->ts.u.cl->length);
4840
4841   return;
4842 }
4843
4844
4845 /*  Ensure that an character expression has a charlen and, if possible, a
4846     length expression.  */
4847
4848 static void
4849 fixup_charlen (gfc_expr *e)
4850 {
4851   /* The cases fall through so that changes in expression type and the need
4852      for multiple fixes are picked up.  In all circumstances, a charlen should
4853      be available for the middle end to hang a backend_decl on.  */
4854   switch (e->expr_type)
4855     {
4856     case EXPR_OP:
4857       gfc_resolve_character_operator (e);
4858
4859     case EXPR_ARRAY:
4860       if (e->expr_type == EXPR_ARRAY)
4861         gfc_resolve_character_array_constructor (e);
4862
4863     case EXPR_SUBSTRING:
4864       if (!e->ts.u.cl && e->ref)
4865         gfc_resolve_substring_charlen (e);
4866
4867     default:
4868       if (!e->ts.u.cl)
4869         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4870
4871       break;
4872     }
4873 }
4874
4875
4876 /* Update an actual argument to include the passed-object for type-bound
4877    procedures at the right position.  */
4878
4879 static gfc_actual_arglist*
4880 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
4881                      const char *name)
4882 {
4883   gcc_assert (argpos > 0);
4884
4885   if (argpos == 1)
4886     {
4887       gfc_actual_arglist* result;
4888
4889       result = gfc_get_actual_arglist ();
4890       result->expr = po;
4891       result->next = lst;
4892       if (name)
4893         result->name = name;
4894
4895       return result;
4896     }
4897
4898   if (lst)
4899     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
4900   else
4901     lst = update_arglist_pass (NULL, po, argpos - 1, name);
4902   return lst;
4903 }
4904
4905
4906 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
4907
4908 static gfc_expr*
4909 extract_compcall_passed_object (gfc_expr* e)
4910 {
4911   gfc_expr* po;
4912
4913   gcc_assert (e->expr_type == EXPR_COMPCALL);
4914
4915   if (e->value.compcall.base_object)
4916     po = gfc_copy_expr (e->value.compcall.base_object);
4917   else
4918     {
4919       po = gfc_get_expr ();
4920       po->expr_type = EXPR_VARIABLE;
4921       po->symtree = e->symtree;
4922       po->ref = gfc_copy_ref (e->ref);
4923       po->where = e->where;
4924     }
4925
4926   if (gfc_resolve_expr (po) == FAILURE)
4927     return NULL;
4928
4929   return po;
4930 }
4931
4932
4933 /* Update the arglist of an EXPR_COMPCALL expression to include the
4934    passed-object.  */
4935
4936 static gfc_try
4937 update_compcall_arglist (gfc_expr* e)
4938 {
4939   gfc_expr* po;
4940   gfc_typebound_proc* tbp;
4941
4942   tbp = e->value.compcall.tbp;
4943
4944   if (tbp->error)
4945     return FAILURE;
4946
4947   po = extract_compcall_passed_object (e);
4948   if (!po)
4949     return FAILURE;
4950
4951   if (tbp->nopass || e->value.compcall.ignore_pass)
4952     {
4953       gfc_free_expr (po);
4954       return SUCCESS;
4955     }
4956
4957   gcc_assert (tbp->pass_arg_num > 0);
4958   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
4959                                                   tbp->pass_arg_num,
4960                                                   tbp->pass_arg);
4961
4962   return SUCCESS;
4963 }
4964
4965
4966 /* Extract the passed object from a PPC call (a copy of it).  */
4967
4968 static gfc_expr*
4969 extract_ppc_passed_object (gfc_expr *e)
4970 {
4971   gfc_expr *po;
4972   gfc_ref **ref;
4973
4974   po = gfc_get_expr ();
4975   po->expr_type = EXPR_VARIABLE;
4976   po->symtree = e->symtree;
4977   po->ref = gfc_copy_ref (e->ref);
4978   po->where = e->where;
4979
4980   /* Remove PPC reference.  */
4981   ref = &po->ref;
4982   while ((*ref)->next)
4983     ref = &(*ref)->next;
4984   gfc_free_ref_list (*ref);
4985   *ref = NULL;
4986
4987   if (gfc_resolve_expr (po) == FAILURE)
4988     return NULL;
4989
4990   return po;
4991 }
4992
4993
4994 /* Update the actual arglist of a procedure pointer component to include the
4995    passed-object.  */
4996
4997 static gfc_try
4998 update_ppc_arglist (gfc_expr* e)
4999 {
5000   gfc_expr* po;
5001   gfc_component *ppc;
5002   gfc_typebound_proc* tb;
5003
5004   if (!gfc_is_proc_ptr_comp (e, &ppc))
5005     return FAILURE;
5006
5007   tb = ppc->tb;
5008
5009   if (tb->error)
5010     return FAILURE;
5011   else if (tb->nopass)
5012     return SUCCESS;
5013
5014   po = extract_ppc_passed_object (e);
5015   if (!po)
5016     return FAILURE;
5017
5018   if (po->rank > 0)
5019     {
5020       gfc_error ("Passed-object at %L must be scalar", &e->where);
5021       return FAILURE;
5022     }
5023
5024   gcc_assert (tb->pass_arg_num > 0);
5025   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5026                                                   tb->pass_arg_num,
5027                                                   tb->pass_arg);
5028
5029   return SUCCESS;
5030 }
5031
5032
5033 /* Check that the object a TBP is called on is valid, i.e. it must not be
5034    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5035
5036 static gfc_try
5037 check_typebound_baseobject (gfc_expr* e)
5038 {
5039   gfc_expr* base;
5040
5041   base = extract_compcall_passed_object (e);
5042   if (!base)
5043     return FAILURE;
5044
5045   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5046
5047   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5048     {
5049       gfc_error ("Base object for type-bound procedure call at %L is of"
5050                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5051       return FAILURE;
5052     }
5053
5054   /* If the procedure called is NOPASS, the base object must be scalar.  */
5055   if (e->value.compcall.tbp->nopass && base->rank > 0)
5056     {
5057       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5058                  " be scalar", &e->where);
5059       return FAILURE;
5060     }
5061
5062   /* FIXME: Remove once PR 41177 (this problem) is fixed completely.  */
5063   if (base->rank > 0)
5064     {
5065       gfc_error ("Non-scalar base object at %L currently not implemented",
5066                  &e->where);
5067       return FAILURE;
5068     }
5069
5070   return SUCCESS;
5071 }
5072
5073
5074 /* Resolve a call to a type-bound procedure, either function or subroutine,
5075    statically from the data in an EXPR_COMPCALL expression.  The adapted
5076    arglist and the target-procedure symtree are returned.  */
5077
5078 static gfc_try
5079 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5080                           gfc_actual_arglist** actual)
5081 {
5082   gcc_assert (e->expr_type == EXPR_COMPCALL);
5083   gcc_assert (!e->value.compcall.tbp->is_generic);
5084
5085   /* Update the actual arglist for PASS.  */
5086   if (update_compcall_arglist (e) == FAILURE)
5087     return FAILURE;
5088
5089   *actual = e->value.compcall.actual;
5090   *target = e->value.compcall.tbp->u.specific;
5091
5092   gfc_free_ref_list (e->ref);
5093   e->ref = NULL;
5094   e->value.compcall.actual = NULL;
5095
5096   return SUCCESS;
5097 }
5098
5099
5100 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5101    which of the specific bindings (if any) matches the arglist and transform
5102    the expression into a call of that binding.  */
5103
5104 static gfc_try
5105 resolve_typebound_generic_call (gfc_expr* e)
5106 {
5107   gfc_typebound_proc* genproc;
5108   const char* genname;
5109
5110   gcc_assert (e->expr_type == EXPR_COMPCALL);
5111   genname = e->value.compcall.name;
5112   genproc = e->value.compcall.tbp;
5113
5114   if (!genproc->is_generic)
5115     return SUCCESS;
5116
5117   /* Try the bindings on this type and in the inheritance hierarchy.  */
5118   for (; genproc; genproc = genproc->overridden)
5119     {
5120       gfc_tbp_generic* g;
5121
5122       gcc_assert (genproc->is_generic);
5123       for (g = genproc->u.generic; g; g = g->next)
5124         {
5125           gfc_symbol* target;
5126           gfc_actual_arglist* args;
5127           bool matches;
5128
5129           gcc_assert (g->specific);
5130
5131           if (g->specific->error)
5132             continue;
5133
5134           target = g->specific->u.specific->n.sym;
5135
5136           /* Get the right arglist by handling PASS/NOPASS.  */
5137           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5138           if (!g->specific->nopass)
5139             {
5140               gfc_expr* po;
5141               po = extract_compcall_passed_object (e);
5142               if (!po)
5143                 return FAILURE;
5144
5145               gcc_assert (g->specific->pass_arg_num > 0);
5146               gcc_assert (!g->specific->error);
5147               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5148                                           g->specific->pass_arg);
5149             }
5150           resolve_actual_arglist (args, target->attr.proc,
5151                                   is_external_proc (target) && !target->formal);
5152
5153           /* Check if this arglist matches the formal.  */
5154           matches = gfc_arglist_matches_symbol (&args, target);
5155
5156           /* Clean up and break out of the loop if we've found it.  */
5157           gfc_free_actual_arglist (args);
5158           if (matches)
5159             {
5160               e->value.compcall.tbp = g->specific;
5161               goto success;
5162             }
5163         }
5164     }
5165
5166   /* Nothing matching found!  */
5167   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5168              " '%s' at %L", genname, &e->where);
5169   return FAILURE;
5170
5171 success:
5172   return SUCCESS;
5173 }
5174
5175
5176 /* Resolve a call to a type-bound subroutine.  */
5177
5178 static gfc_try
5179 resolve_typebound_call (gfc_code* c)
5180 {
5181   gfc_actual_arglist* newactual;
5182   gfc_symtree* target;
5183
5184   /* Check that's really a SUBROUTINE.  */
5185   if (!c->expr1->value.compcall.tbp->subroutine)
5186     {
5187       gfc_error ("'%s' at %L should be a SUBROUTINE",
5188                  c->expr1->value.compcall.name, &c->loc);
5189       return FAILURE;
5190     }
5191
5192   if (check_typebound_baseobject (c->expr1) == FAILURE)
5193     return FAILURE;
5194
5195   if (resolve_typebound_generic_call (c->expr1) == FAILURE)
5196     return FAILURE;
5197
5198   /* Transform into an ordinary EXEC_CALL for now.  */
5199
5200   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5201     return FAILURE;
5202
5203   c->ext.actual = newactual;
5204   c->symtree = target;
5205   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5206
5207   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5208
5209   gfc_free_expr (c->expr1);
5210   c->expr1 = gfc_get_expr ();
5211   c->expr1->expr_type = EXPR_FUNCTION;
5212   c->expr1->symtree = target;
5213   c->expr1->where = c->loc;
5214
5215   return resolve_call (c);
5216 }
5217
5218
5219 /* Resolve a component-call expression.  This originally was intended
5220    only to see functions.  However, it is convenient to use it in 
5221    resolving subroutine class methods, since we do not have to add a
5222    gfc_code each time. */
5223 static gfc_try
5224 resolve_compcall (gfc_expr* e, bool fcn, bool class_members)
5225 {
5226   gfc_actual_arglist* newactual;
5227   gfc_symtree* target;
5228
5229   /* Check that's really a FUNCTION.  */
5230   if (fcn && !e->value.compcall.tbp->function)
5231     {
5232       gfc_error ("'%s' at %L should be a FUNCTION",
5233                  e->value.compcall.name, &e->where);
5234       return FAILURE;
5235     }
5236   else if (!fcn && !e->value.compcall.tbp->subroutine)
5237     {
5238       /* To resolve class member calls, we borrow this bit
5239          of code to select the specific procedures.  */
5240       gfc_error ("'%s' at %L should be a SUBROUTINE",
5241                  e->value.compcall.name, &e->where);
5242       return FAILURE;
5243     }
5244
5245   /* These must not be assign-calls!  */
5246   gcc_assert (!e->value.compcall.assign);
5247
5248   if (check_typebound_baseobject (e) == FAILURE)
5249     return FAILURE;
5250
5251   if (resolve_typebound_generic_call (e) == FAILURE)
5252     return FAILURE;
5253   gcc_assert (!e->value.compcall.tbp->is_generic);
5254
5255   /* Take the rank from the function's symbol.  */
5256   if (e->value.compcall.tbp->u.specific->n.sym->as)
5257     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5258
5259   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5260      arglist to the TBP's binding target.  */
5261
5262   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5263     return FAILURE;
5264
5265   e->value.function.actual = newactual;
5266   e->value.function.name = NULL;
5267   e->value.function.esym = target->n.sym;
5268   e->value.function.class_esym = NULL;
5269   e->value.function.isym = NULL;
5270   e->symtree = target;
5271   e->ts = target->n.sym->ts;
5272   e->expr_type = EXPR_FUNCTION;
5273
5274   /* Resolution is not necessary when constructing component calls
5275      for class members, since this must only be done for the
5276      declared type, which is done afterwards.  */
5277   return !class_members ? gfc_resolve_expr (e) : SUCCESS;
5278 }
5279
5280
5281 /* Resolve a typebound call for the members in a class.  This group of
5282    functions implements dynamic dispatch in the provisional version
5283    of f03 OOP.  As soon as vtables are in place and contain pointers
5284    to methods, this will no longer be necessary.  */
5285 static gfc_expr *list_e;
5286 static gfc_try check_class_members (gfc_symbol *);
5287 static gfc_try class_try;
5288 static bool fcn_flag;
5289
5290
5291 static void
5292 check_members (gfc_symbol *derived)
5293 {
5294   if (derived->attr.flavor == FL_DERIVED)
5295     (void) check_class_members (derived);
5296 }
5297
5298
5299 static gfc_try 
5300 check_class_members (gfc_symbol *derived)
5301 {
5302   gfc_expr *e;
5303   gfc_symtree *tbp;
5304   gfc_class_esym_list *etmp;
5305
5306   e = gfc_copy_expr (list_e);
5307
5308   tbp = gfc_find_typebound_proc (derived, &class_try,
5309                                  e->value.compcall.name,
5310                                  false, &e->where);
5311
5312   if (tbp == NULL)
5313     {
5314       gfc_error ("no typebound available procedure named '%s' at %L",
5315                  e->value.compcall.name, &e->where);
5316       return FAILURE;
5317     }
5318
5319   /* If we have to match a passed class member, force the actual
5320       expression to have the correct type.  */
5321   if (!tbp->n.tb->nopass)
5322     {
5323       if (e->value.compcall.base_object == NULL)
5324         e->value.compcall.base_object = extract_compcall_passed_object (e);
5325
5326       if (e->value.compcall.base_object == NULL)
5327         return FAILURE;
5328
5329       if (!derived->attr.abstract)
5330         {
5331           e->value.compcall.base_object->ts.type = BT_DERIVED;
5332           e->value.compcall.base_object->ts.u.derived = derived;
5333         }
5334     }
5335
5336   e->value.compcall.tbp = tbp->n.tb;
5337   e->value.compcall.name = tbp->name;
5338
5339   /* Let the original expresssion catch the assertion in
5340      resolve_compcall, since this flag does not appear to be reset or
5341      copied in some systems.  */
5342   e->value.compcall.assign = 0;
5343
5344   /* Do the renaming, PASSing, generic => specific and other
5345      good things for each class member.  */
5346   class_try = (resolve_compcall (e, fcn_flag, true) == SUCCESS)
5347                                 ? class_try : FAILURE;
5348
5349   /* Now transfer the found symbol to the esym list.  */
5350   if (class_try == SUCCESS)
5351     {
5352       etmp = list_e->value.function.class_esym;
5353       list_e->value.function.class_esym
5354                 = gfc_get_class_esym_list();
5355       list_e->value.function.class_esym->next = etmp;
5356       list_e->value.function.class_esym->derived = derived;
5357       list_e->value.function.class_esym->esym
5358                 = e->value.function.esym;
5359     }
5360
5361   gfc_free_expr (e);
5362   
5363   /* Burrow down into grandchildren types.  */
5364   if (derived->f2k_derived)
5365     gfc_traverse_ns (derived->f2k_derived, check_members);
5366
5367   return SUCCESS;
5368 }
5369
5370
5371 /* Eliminate esym_lists where all the members point to the
5372    typebound procedure of the declared type; ie. one where
5373    type selection has no effect..  */
5374 static void
5375 resolve_class_esym (gfc_expr *e)
5376 {
5377   gfc_class_esym_list *p, *q;
5378   bool empty = true;
5379
5380   gcc_assert (e && e->expr_type == EXPR_FUNCTION);
5381
5382   p = e->value.function.class_esym;
5383   if (p == NULL)
5384     return;
5385
5386   for (; p; p = p->next)
5387     empty = empty && (e->value.function.esym == p->esym);
5388
5389   if (empty)
5390     {
5391       p = e->value.function.class_esym;
5392       for (; p; p = q)
5393         {
5394           q = p->next;
5395           gfc_free (p);
5396         }
5397       e->value.function.class_esym = NULL;
5398    }
5399 }
5400
5401
5402 /* Generate an expression for the hash value, given the reference to
5403    the class of the final expression (class_ref), the base of the
5404    full reference list (new_ref), the declared type and the class
5405    object (st).  */
5406 static gfc_expr*
5407 hash_value_expr (gfc_ref *class_ref, gfc_ref *new_ref, gfc_symtree *st)
5408 {
5409   gfc_expr *hash_value;
5410
5411   /* Build an expression for the correct hash_value; ie. that of the last
5412      CLASS reference.  */
5413   if (class_ref)
5414     {
5415       class_ref->next = NULL;
5416     }
5417   else
5418     {
5419       gfc_free_ref_list (new_ref);
5420       new_ref = NULL;
5421     }
5422   hash_value = gfc_get_expr ();
5423   hash_value->expr_type = EXPR_VARIABLE;
5424   hash_value->symtree = st;
5425   hash_value->symtree->n.sym->refs++;
5426   hash_value->ref = new_ref;
5427   gfc_add_component_ref (hash_value, "$vptr");
5428   gfc_add_component_ref (hash_value, "$hash");
5429
5430   return hash_value;
5431 }
5432
5433
5434 /* Get the ultimate declared type from an expression.  In addition,
5435    return the last class/derived type reference and the copy of the
5436    reference list.  */
5437 static gfc_symbol*
5438 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5439                         gfc_expr *e)
5440 {
5441   gfc_symbol *declared;
5442   gfc_ref *ref;
5443
5444   declared = NULL;
5445   *class_ref = NULL;
5446   *new_ref = gfc_copy_ref (e->ref);
5447   for (ref = *new_ref; ref; ref = ref->next)
5448     {
5449       if (ref->type != REF_COMPONENT)
5450         continue;
5451
5452       if (ref->u.c.component->ts.type == BT_CLASS
5453             || ref->u.c.component->ts.type == BT_DERIVED)
5454         {
5455           declared = ref->u.c.component->ts.u.derived;
5456           *class_ref = ref;
5457         }
5458     }
5459
5460   if (declared == NULL)
5461     declared = e->symtree->n.sym->ts.u.derived;
5462
5463   return declared;
5464 }
5465
5466
5467 /* Resolve the argument expressions so that any arguments expressions
5468    that include class methods are resolved before the current call.
5469    This is necessary because of the static variables used in CLASS
5470    method resolution.  */
5471 static void
5472 resolve_arg_exprs (gfc_actual_arglist *arg)
5473
5474   /* Resolve the actual arglist expressions.  */
5475   for (; arg; arg = arg->next)
5476     {
5477       if (arg->expr)
5478         gfc_resolve_expr (arg->expr);
5479     }
5480 }
5481
5482
5483 /* Resolve a typebound function, or 'method'.  First separate all
5484    the non-CLASS references by calling resolve_compcall directly.
5485    Then treat the CLASS references by resolving for each of the class
5486    members in turn.  */
5487
5488 static gfc_try
5489 resolve_typebound_function (gfc_expr* e)
5490 {
5491   gfc_symbol *derived, *declared;
5492   gfc_ref *new_ref;
5493   gfc_ref *class_ref;
5494   gfc_symtree *st;
5495
5496   st = e->symtree;
5497   if (st == NULL)
5498     return resolve_compcall (e, true, false);
5499
5500   /* Get the CLASS declared type.  */
5501   declared = get_declared_from_expr (&class_ref, &new_ref, e);
5502
5503   /* Weed out cases of the ultimate component being a derived type.  */
5504   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5505         || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5506     {
5507       gfc_free_ref_list (new_ref);
5508       return resolve_compcall (e, true, false);
5509     }
5510
5511   /* Resolve the argument expressions,  */
5512   resolve_arg_exprs (e->value.function.actual); 
5513
5514   /* Get the data component, which is of the declared type.  */
5515   derived = declared->components->ts.u.derived;
5516
5517   /* Resolve the function call for each member of the class.  */
5518   class_try = SUCCESS;
5519   fcn_flag = true;
5520   list_e = gfc_copy_expr (e);
5521
5522   if (check_class_members (derived) == FAILURE)
5523     return FAILURE;
5524
5525   class_try = (resolve_compcall (e, true, false) == SUCCESS)
5526                  ? class_try : FAILURE;
5527
5528   /* Transfer the class list to the original expression.  Note that
5529      the class_esym list is cleaned up in trans-expr.c, as the calls
5530      are translated.  */
5531   e->value.function.class_esym = list_e->value.function.class_esym;
5532   list_e->value.function.class_esym = NULL;
5533   gfc_free_expr (list_e);
5534
5535   resolve_class_esym (e);
5536
5537   /* More than one typebound procedure so transmit an expression for
5538      the hash_value as the selector.  */
5539   if (e->value.function.class_esym != NULL)
5540     e->value.function.class_esym->hash_value
5541                 = hash_value_expr (class_ref, new_ref, st);
5542
5543   return class_try;
5544 }
5545
5546 /* Resolve a typebound subroutine, or 'method'.  First separate all
5547    the non-CLASS references by calling resolve_typebound_call directly.
5548    Then treat the CLASS references by resolving for each of the class
5549    members in turn.  */
5550
5551 static gfc_try
5552 resolve_typebound_subroutine (gfc_code *code)
5553 {
5554   gfc_symbol *derived, *declared;
5555   gfc_ref *new_ref;
5556   gfc_ref *class_ref;
5557   gfc_symtree *st;
5558
5559   st = code->expr1->symtree;
5560   if (st == NULL)
5561     return resolve_typebound_call (code);
5562
5563   /* Get the CLASS declared type.  */
5564   declared = get_declared_from_expr (&class_ref, &new_ref, code->expr1);
5565
5566   /* Weed out cases of the ultimate component being a derived type.  */
5567   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5568         || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5569     {
5570       gfc_free_ref_list (new_ref);
5571       return resolve_typebound_call (code);
5572     } 
5573
5574   /* Resolve the argument expressions,  */
5575   resolve_arg_exprs (code->expr1->value.compcall.actual); 
5576
5577   /* Get the data component, which is of the declared type.  */
5578   derived = declared->components->ts.u.derived;
5579
5580   class_try = SUCCESS;
5581   fcn_flag = false;
5582   list_e = gfc_copy_expr (code->expr1);
5583
5584   if (check_class_members (derived) == FAILURE)
5585     return FAILURE;
5586
5587   class_try = (resolve_typebound_call (code) == SUCCESS)
5588                  ? class_try : FAILURE;
5589
5590   /* Transfer the class list to the original expression.  Note that
5591      the class_esym list is cleaned up in trans-expr.c, as the calls
5592      are translated.  */
5593   code->expr1->value.function.class_esym
5594                         = list_e->value.function.class_esym;
5595   list_e->value.function.class_esym = NULL;
5596   gfc_free_expr (list_e);
5597
5598   resolve_class_esym (code->expr1);
5599
5600   /* More than one typebound procedure so transmit an expression for
5601      the hash_value as the selector.  */
5602   if (code->expr1->value.function.class_esym != NULL)
5603     code->expr1->value.function.class_esym->hash_value
5604                 = hash_value_expr (class_ref, new_ref, st);
5605
5606   return class_try;
5607 }
5608
5609
5610 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
5611
5612 static gfc_try
5613 resolve_ppc_call (gfc_code* c)
5614 {
5615   gfc_component *comp;
5616   bool b;
5617
5618   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
5619   gcc_assert (b);
5620
5621   c->resolved_sym = c->expr1->symtree->n.sym;
5622   c->expr1->expr_type = EXPR_VARIABLE;
5623
5624   if (!comp->attr.subroutine)
5625     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
5626
5627   if (resolve_ref (c->expr1) == FAILURE)
5628     return FAILURE;
5629
5630   if (update_ppc_arglist (c->expr1) == FAILURE)
5631     return FAILURE;
5632
5633   c->ext.actual = c->expr1->value.compcall.actual;
5634
5635   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
5636                               comp->formal == NULL) == FAILURE)
5637     return FAILURE;
5638
5639   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
5640
5641   return SUCCESS;
5642 }
5643
5644
5645 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
5646
5647 static gfc_try
5648 resolve_expr_ppc (gfc_expr* e)
5649 {
5650   gfc_component *comp;
5651   bool b;
5652
5653   b = gfc_is_proc_ptr_comp (e, &comp);
5654   gcc_assert (b);
5655
5656   /* Convert to EXPR_FUNCTION.  */
5657   e->expr_type = EXPR_FUNCTION;
5658   e->value.function.isym = NULL;
5659   e->value.function.actual = e->value.compcall.actual;
5660   e->ts = comp->ts;
5661   if (comp->as != NULL)
5662     e->rank = comp->as->rank;
5663
5664   if (!comp->attr.function)
5665     gfc_add_function (&comp->attr, comp->name, &e->where);
5666
5667   if (resolve_ref (e) == FAILURE)
5668     return FAILURE;
5669
5670   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
5671                               comp->formal == NULL) == FAILURE)
5672     return FAILURE;
5673
5674   if (update_ppc_arglist (e) == FAILURE)
5675     return FAILURE;
5676
5677   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
5678
5679   return SUCCESS;
5680 }
5681
5682
5683 static bool
5684 gfc_is_expandable_expr (gfc_expr *e)
5685 {
5686   gfc_constructor *con;
5687
5688   if (e->expr_type == EXPR_ARRAY)
5689     {
5690       /* Traverse the constructor looking for variables that are flavor
5691          parameter.  Parameters must be expanded since they are fully used at
5692          compile time.  */
5693       for (con = e->value.constructor; con; con = con->next)
5694         {
5695           if (con->expr->expr_type == EXPR_VARIABLE
5696           && con->expr->symtree
5697           && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
5698               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
5699             return true;
5700           if (con->expr->expr_type == EXPR_ARRAY
5701             && gfc_is_expandable_expr (con->expr))
5702             return true;
5703         }
5704     }
5705
5706   return false;
5707 }
5708
5709 /* Resolve an expression.  That is, make sure that types of operands agree
5710    with their operators, intrinsic operators are converted to function calls
5711    for overloaded types and unresolved function references are resolved.  */
5712
5713 gfc_try
5714 gfc_resolve_expr (gfc_expr *e)
5715 {
5716   gfc_try t;
5717   bool inquiry_save;
5718
5719   if (e == NULL)
5720     return SUCCESS;
5721
5722   /* inquiry_argument only applies to variables.  */
5723   inquiry_save = inquiry_argument;
5724   if (e->expr_type != EXPR_VARIABLE)
5725     inquiry_argument = false;
5726
5727   switch (e->expr_type)
5728     {
5729     case EXPR_OP:
5730       t = resolve_operator (e);
5731       break;
5732
5733     case EXPR_FUNCTION:
5734     case EXPR_VARIABLE:
5735
5736       if (check_host_association (e))
5737         t = resolve_function (e);
5738       else
5739         {
5740           t = resolve_variable (e);
5741           if (t == SUCCESS)
5742             expression_rank (e);
5743         }
5744
5745       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
5746           && e->ref->type != REF_SUBSTRING)
5747         gfc_resolve_substring_charlen (e);
5748
5749       break;
5750
5751     case EXPR_COMPCALL:
5752       t = resolve_typebound_function (e);
5753       break;
5754
5755     case EXPR_SUBSTRING:
5756       t = resolve_ref (e);
5757       break;
5758
5759     case EXPR_CONSTANT:
5760     case EXPR_NULL:
5761       t = SUCCESS;
5762       break;
5763
5764     case EXPR_PPC:
5765       t = resolve_expr_ppc (e);
5766       break;
5767
5768     case EXPR_ARRAY:
5769       t = FAILURE;
5770       if (resolve_ref (e) == FAILURE)
5771         break;
5772
5773       t = gfc_resolve_array_constructor (e);
5774       /* Also try to expand a constructor.  */
5775       if (t == SUCCESS)
5776         {
5777           expression_rank (e);
5778           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
5779             gfc_expand_constructor (e);
5780         }
5781
5782       /* This provides the opportunity for the length of constructors with
5783          character valued function elements to propagate the string length
5784          to the expression.  */
5785       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
5786         {
5787           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
5788              here rather then add a duplicate test for it above.  */ 
5789           gfc_expand_constructor (e);
5790           t = gfc_resolve_character_array_constructor (e);
5791         }
5792
5793       break;
5794
5795     case EXPR_STRUCTURE:
5796       t = resolve_ref (e);
5797       if (t == FAILURE)
5798         break;
5799
5800       t = resolve_structure_cons (e);
5801       if (t == FAILURE)
5802         break;
5803
5804       t = gfc_simplify_expr (e, 0);
5805       break;
5806
5807     default:
5808       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
5809     }
5810
5811   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
5812     fixup_charlen (e);
5813
5814   inquiry_argument = inquiry_save;
5815
5816   return t;
5817 }
5818
5819
5820 /* Resolve an expression from an iterator.  They must be scalar and have
5821    INTEGER or (optionally) REAL type.  */
5822
5823 static gfc_try
5824 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
5825                            const char *name_msgid)
5826 {
5827   if (gfc_resolve_expr (expr) == FAILURE)
5828     return FAILURE;
5829
5830   if (expr->rank != 0)
5831     {
5832       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
5833       return FAILURE;
5834     }
5835
5836   if (expr->ts.type != BT_INTEGER)
5837     {
5838       if (expr->ts.type == BT_REAL)
5839         {
5840           if (real_ok)
5841             return gfc_notify_std (GFC_STD_F95_DEL,
5842                                    "Deleted feature: %s at %L must be integer",
5843                                    _(name_msgid), &expr->where);
5844           else
5845             {
5846               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
5847                          &expr->where);
5848               return FAILURE;
5849             }
5850         }
5851       else
5852         {
5853           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
5854           return FAILURE;
5855         }
5856     }
5857   return SUCCESS;
5858 }
5859
5860
5861 /* Resolve the expressions in an iterator structure.  If REAL_OK is
5862    false allow only INTEGER type iterators, otherwise allow REAL types.  */
5863
5864 gfc_try
5865 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
5866 {
5867   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
5868       == FAILURE)
5869     return FAILURE;
5870
5871   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
5872     {
5873       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
5874                  &iter->var->where);
5875       return FAILURE;
5876     }
5877
5878   if (gfc_resolve_iterator_expr (iter->start, real_ok,
5879                                  "Start expression in DO loop") == FAILURE)
5880     return FAILURE;
5881
5882   if (gfc_resolve_iterator_expr (iter->end, real_ok,
5883                                  "End expression in DO loop") == FAILURE)
5884     return FAILURE;
5885
5886   if (gfc_resolve_iterator_expr (iter->step, real_ok,
5887                                  "Step expression in DO loop") == FAILURE)
5888     return FAILURE;
5889
5890   if (iter->step->expr_type == EXPR_CONSTANT)
5891     {
5892       if ((iter->step->ts.type == BT_INTEGER
5893            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
5894           || (iter->step->ts.type == BT_REAL
5895               && mpfr_sgn (iter->step->value.real) == 0))
5896         {
5897           gfc_error ("Step expression in DO loop at %L cannot be zero",
5898                      &iter->step->where);
5899           return FAILURE;
5900         }
5901     }
5902
5903   /* Convert start, end, and step to the same type as var.  */
5904   if (iter->start->ts.kind != iter->var->ts.kind
5905       || iter->start->ts.type != iter->var->ts.type)
5906     gfc_convert_type (iter->start, &iter->var->ts, 2);
5907
5908   if (iter->end->ts.kind != iter->var->ts.kind
5909       || iter->end->ts.type != iter->var->ts.type)
5910     gfc_convert_type (iter->end, &iter->var->ts, 2);
5911
5912   if (iter->step->ts.kind != iter->var->ts.kind
5913       || iter->step->ts.type != iter->var->ts.type)
5914     gfc_convert_type (iter->step, &iter->var->ts, 2);
5915
5916   if (iter->start->expr_type == EXPR_CONSTANT
5917       && iter->end->expr_type == EXPR_CONSTANT
5918       && iter->step->expr_type == EXPR_CONSTANT)
5919     {
5920       int sgn, cmp;
5921       if (iter->start->ts.type == BT_INTEGER)
5922         {
5923           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
5924           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
5925         }
5926       else
5927         {
5928           sgn = mpfr_sgn (iter->step->value.real);
5929           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
5930         }
5931       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
5932         gfc_warning ("DO loop at %L will be executed zero times",
5933                      &iter->step->where);
5934     }
5935
5936   return SUCCESS;
5937 }
5938
5939
5940 /* Traversal function for find_forall_index.  f == 2 signals that
5941    that variable itself is not to be checked - only the references.  */
5942
5943 static bool
5944 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
5945 {
5946   if (expr->expr_type != EXPR_VARIABLE)
5947     return false;
5948   
5949   /* A scalar assignment  */
5950   if (!expr->ref || *f == 1)
5951     {
5952       if (expr->symtree->n.sym == sym)
5953         return true;
5954       else
5955         return false;
5956     }
5957
5958   if (*f == 2)
5959     *f = 1;
5960   return false;
5961 }
5962
5963
5964 /* Check whether the FORALL index appears in the expression or not.
5965    Returns SUCCESS if SYM is found in EXPR.  */
5966
5967 gfc_try
5968 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
5969 {
5970   if (gfc_traverse_expr (expr, sym, forall_index, f))
5971     return SUCCESS;
5972   else
5973     return FAILURE;
5974 }
5975
5976
5977 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
5978    to be a scalar INTEGER variable.  The subscripts and stride are scalar
5979    INTEGERs, and if stride is a constant it must be nonzero.
5980    Furthermore "A subscript or stride in a forall-triplet-spec shall
5981    not contain a reference to any index-name in the
5982    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
5983
5984 static void
5985 resolve_forall_iterators (gfc_forall_iterator *it)
5986 {
5987   gfc_forall_iterator *iter, *iter2;
5988
5989   for (iter = it; iter; iter = iter->next)
5990     {
5991       if (gfc_resolve_expr (iter->var) == SUCCESS
5992           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
5993         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
5994                    &iter->var->where);
5995
5996       if (gfc_resolve_expr (iter->start) == SUCCESS
5997           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
5998         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
5999                    &iter->start->where);
6000       if (iter->var->ts.kind != iter->start->ts.kind)
6001         gfc_convert_type (iter->start, &iter->var->ts, 2);
6002
6003       if (gfc_resolve_expr (iter->end) == SUCCESS
6004           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
6005         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
6006                    &iter->end->where);
6007       if (iter->var->ts.kind != iter->end->ts.kind)
6008         gfc_convert_type (iter->end, &iter->var->ts, 2);
6009
6010       if (gfc_resolve_expr (iter->stride) == SUCCESS)
6011         {
6012           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
6013             gfc_error ("FORALL stride expression at %L must be a scalar %s",
6014                        &iter->stride->where, "INTEGER");
6015
6016           if (iter->stride->expr_type == EXPR_CONSTANT
6017               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
6018             gfc_error ("FORALL stride expression at %L cannot be zero",
6019                        &iter->stride->where);
6020         }
6021       if (iter->var->ts.kind != iter->stride->ts.kind)
6022         gfc_convert_type (iter->stride, &iter->var->ts, 2);
6023     }
6024
6025   for (iter = it; iter; iter = iter->next)
6026     for (iter2 = iter; iter2; iter2 = iter2->next)
6027       {
6028         if (find_forall_index (iter2->start,
6029                                iter->var->symtree->n.sym, 0) == SUCCESS
6030             || find_forall_index (iter2->end,
6031                                   iter->var->symtree->n.sym, 0) == SUCCESS
6032             || find_forall_index (iter2->stride,
6033                                   iter->var->symtree->n.sym, 0) == SUCCESS)
6034           gfc_error ("FORALL index '%s' may not appear in triplet "
6035                      "specification at %L", iter->var->symtree->name,
6036                      &iter2->start->where);
6037       }
6038 }
6039
6040
6041 /* Given a pointer to a symbol that is a derived type, see if it's
6042    inaccessible, i.e. if it's defined in another module and the components are
6043    PRIVATE.  The search is recursive if necessary.  Returns zero if no
6044    inaccessible components are found, nonzero otherwise.  */
6045
6046 static int
6047 derived_inaccessible (gfc_symbol *sym)
6048 {
6049   gfc_component *c;
6050
6051   if (sym->attr.use_assoc && sym->attr.private_comp)
6052     return 1;
6053
6054   for (c = sym->components; c; c = c->next)
6055     {
6056         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
6057           return 1;
6058     }
6059
6060   return 0;
6061 }
6062
6063
6064 /* Resolve the argument of a deallocate expression.  The expression must be
6065    a pointer or a full array.  */
6066
6067 static gfc_try
6068 resolve_deallocate_expr (gfc_expr *e)
6069 {
6070   symbol_attribute attr;
6071   int allocatable, pointer, check_intent_in;
6072   gfc_ref *ref;
6073   gfc_symbol *sym;
6074   gfc_component *c;
6075
6076   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
6077   check_intent_in = 1;
6078
6079   if (gfc_resolve_expr (e) == FAILURE)
6080     return FAILURE;
6081
6082   if (e->expr_type != EXPR_VARIABLE)
6083     goto bad;
6084
6085   sym = e->symtree->n.sym;
6086
6087   if (sym->ts.type == BT_CLASS)
6088     {
6089       allocatable = sym->ts.u.derived->components->attr.allocatable;
6090       pointer = sym->ts.u.derived->components->attr.pointer;
6091     }
6092   else
6093     {
6094       allocatable = sym->attr.allocatable;
6095       pointer = sym->attr.pointer;
6096     }
6097   for (ref = e->ref; ref; ref = ref->next)
6098     {
6099       if (pointer)
6100         check_intent_in = 0;
6101
6102       switch (ref->type)
6103         {
6104         case REF_ARRAY:
6105           if (ref->u.ar.type != AR_FULL)
6106             allocatable = 0;
6107           break;
6108
6109         case REF_COMPONENT:
6110           c = ref->u.c.component;
6111           if (c->ts.type == BT_CLASS)
6112             {
6113               allocatable = c->ts.u.derived->components->attr.allocatable;
6114               pointer = c->ts.u.derived->components->attr.pointer;
6115             }
6116           else
6117             {
6118               allocatable = c->attr.allocatable;
6119               pointer = c->attr.pointer;
6120             }
6121           break;
6122
6123         case REF_SUBSTRING:
6124           allocatable = 0;
6125           break;
6126         }
6127     }
6128
6129   attr = gfc_expr_attr (e);
6130
6131   if (allocatable == 0 && attr.pointer == 0)
6132     {
6133     bad:
6134       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6135                  &e->where);
6136     }
6137
6138   if (check_intent_in && sym->attr.intent == INTENT_IN)
6139     {
6140       gfc_error ("Cannot deallocate INTENT(IN) variable '%s' at %L",
6141                  sym->name, &e->where);
6142       return FAILURE;
6143     }
6144
6145   if (e->ts.type == BT_CLASS)
6146     {
6147       /* Only deallocate the DATA component.  */
6148       gfc_add_component_ref (e, "$data");
6149     }
6150
6151   return SUCCESS;
6152 }
6153
6154
6155 /* Returns true if the expression e contains a reference to the symbol sym.  */
6156 static bool
6157 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6158 {
6159   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6160     return true;
6161
6162   return false;
6163 }
6164
6165 bool
6166 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6167 {
6168   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6169 }
6170
6171
6172 /* Given the expression node e for an allocatable/pointer of derived type to be
6173    allocated, get the expression node to be initialized afterwards (needed for
6174    derived types with default initializers, and derived types with allocatable
6175    components that need nullification.)  */
6176
6177 gfc_expr *
6178 gfc_expr_to_initialize (gfc_expr *e)
6179 {
6180   gfc_expr *result;
6181   gfc_ref *ref;
6182   int i;
6183
6184   result = gfc_copy_expr (e);
6185
6186   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6187   for (ref = result->ref; ref; ref = ref->next)
6188     if (ref->type == REF_ARRAY && ref->next == NULL)
6189       {
6190         ref->u.ar.type = AR_FULL;
6191
6192         for (i = 0; i < ref->u.ar.dimen; i++)
6193           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6194
6195         result->rank = ref->u.ar.dimen;
6196         break;
6197       }
6198
6199   return result;
6200 }
6201
6202
6203 /* Used in resolve_allocate_expr to check that a allocation-object and
6204    a source-expr are conformable.  This does not catch all possible 
6205    cases; in particular a runtime checking is needed.  */
6206
6207 static gfc_try
6208 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6209 {
6210   /* First compare rank.  */
6211   if (e2->ref && e1->rank != e2->ref->u.ar.as->rank)
6212     {
6213       gfc_error ("Source-expr at %L must be scalar or have the "
6214                  "same rank as the allocate-object at %L",
6215                  &e1->where, &e2->where);
6216       return FAILURE;
6217     }
6218
6219   if (e1->shape)
6220     {
6221       int i;
6222       mpz_t s;
6223
6224       mpz_init (s);
6225
6226       for (i = 0; i < e1->rank; i++)
6227         {
6228           if (e2->ref->u.ar.end[i])
6229             {
6230               mpz_set (s, e2->ref->u.ar.end[i]->value.integer);
6231               mpz_sub (s, s, e2->ref->u.ar.start[i]->value.integer);
6232               mpz_add_ui (s, s, 1);
6233             }
6234           else
6235             {
6236               mpz_set (s, e2->ref->u.ar.start[i]->value.integer);
6237             }
6238
6239           if (mpz_cmp (e1->shape[i], s) != 0)
6240             {
6241               gfc_error ("Source-expr at %L and allocate-object at %L must "
6242                          "have the same shape", &e1->where, &e2->where);
6243               mpz_clear (s);
6244               return FAILURE;
6245             }
6246         }
6247
6248       mpz_clear (s);
6249     }
6250
6251   return SUCCESS;
6252 }
6253
6254
6255 /* Resolve the expression in an ALLOCATE statement, doing the additional
6256    checks to see whether the expression is OK or not.  The expression must
6257    have a trailing array reference that gives the size of the array.  */
6258
6259 static gfc_try
6260 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6261 {
6262   int i, pointer, allocatable, dimension, check_intent_in, is_abstract;
6263   int codimension;
6264   symbol_attribute attr;
6265   gfc_ref *ref, *ref2;
6266   gfc_array_ref *ar;
6267   gfc_symbol *sym;
6268   gfc_alloc *a;
6269   gfc_component *c;
6270   gfc_expr *init_e;
6271
6272   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
6273   check_intent_in = 1;
6274
6275   /* Mark the ultimost array component as being in allocate to allow DIMEN_STAR
6276      checking of coarrays.  */
6277   for (ref = e->ref; ref; ref = ref->next)
6278     if (ref->next == NULL)
6279       break;
6280
6281   if (ref && ref->type == REF_ARRAY)
6282     ref->u.ar.in_allocate = true;
6283
6284   if (gfc_resolve_expr (e) == FAILURE)
6285     goto failure;
6286
6287   /* Make sure the expression is allocatable or a pointer.  If it is
6288      pointer, the next-to-last reference must be a pointer.  */
6289
6290   ref2 = NULL;
6291   if (e->symtree)
6292     sym = e->symtree->n.sym;
6293
6294   /* Check whether ultimate component is abstract and CLASS.  */
6295   is_abstract = 0;
6296
6297   if (e->expr_type != EXPR_VARIABLE)
6298     {
6299       allocatable = 0;
6300       attr = gfc_expr_attr (e);
6301       pointer = attr.pointer;
6302       dimension = attr.dimension;
6303       codimension = attr.codimension;
6304     }
6305   else
6306     {
6307       if (sym->ts.type == BT_CLASS)
6308         {
6309           allocatable = sym->ts.u.derived->components->attr.allocatable;
6310           pointer = sym->ts.u.derived->components->attr.pointer;
6311           dimension = sym->ts.u.derived->components->attr.dimension;
6312           codimension = sym->ts.u.derived->components->attr.codimension;
6313           is_abstract = sym->ts.u.derived->components->attr.abstract;
6314         }
6315       else
6316         {
6317           allocatable = sym->attr.allocatable;
6318           pointer = sym->attr.pointer;
6319           dimension = sym->attr.dimension;
6320           codimension = sym->attr.codimension;
6321         }
6322
6323       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6324         {
6325           if (pointer)
6326             check_intent_in = 0;
6327
6328           switch (ref->type)
6329             {
6330               case REF_ARRAY:
6331                 if (ref->next != NULL)
6332                   pointer = 0;
6333                 break;
6334
6335               case REF_COMPONENT:
6336                 /* F2008, C644.  */
6337                 if (gfc_is_coindexed (e))
6338                   {
6339                     gfc_error ("Coindexed allocatable object at %L",
6340                                &e->where);
6341                     goto failure;
6342                   }
6343
6344                 c = ref->u.c.component;
6345                 if (c->ts.type == BT_CLASS)
6346                   {
6347                     allocatable = c->ts.u.derived->components->attr.allocatable;
6348                     pointer = c->ts.u.derived->components->attr.pointer;
6349                     dimension = c->ts.u.derived->components->attr.dimension;
6350                     codimension = c->ts.u.derived->components->attr.codimension;
6351                     is_abstract = c->ts.u.derived->components->attr.abstract;
6352                   }
6353                 else
6354                   {
6355                     allocatable = c->attr.allocatable;
6356                     pointer = c->attr.pointer;
6357                     dimension = c->attr.dimension;
6358                     codimension = c->attr.codimension;
6359                     is_abstract = c->attr.abstract;
6360                   }
6361                 break;
6362
6363               case REF_SUBSTRING:
6364                 allocatable = 0;
6365                 pointer = 0;
6366                 break;
6367             }
6368         }
6369     }
6370
6371   if (allocatable == 0 && pointer == 0)
6372     {
6373       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6374                  &e->where);
6375       goto failure;
6376     }
6377
6378   /* Some checks for the SOURCE tag.  */
6379   if (code->expr3)
6380     {
6381       /* Check F03:C631.  */
6382       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6383         {
6384           gfc_error ("Type of entity at %L is type incompatible with "
6385                       "source-expr at %L", &e->where, &code->expr3->where);
6386           goto failure;
6387         }
6388
6389       /* Check F03:C632 and restriction following Note 6.18.  */
6390       if (code->expr3->rank > 0
6391           && conformable_arrays (code->expr3, e) == FAILURE)
6392         goto failure;
6393
6394       /* Check F03:C633.  */
6395       if (code->expr3->ts.kind != e->ts.kind)
6396         {
6397           gfc_error ("The allocate-object at %L and the source-expr at %L "
6398                       "shall have the same kind type parameter",
6399                       &e->where, &code->expr3->where);
6400           goto failure;
6401         }
6402     }
6403   else if (is_abstract&& code->ext.alloc.ts.type == BT_UNKNOWN)
6404     {
6405       gcc_assert (e->ts.type == BT_CLASS);
6406       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6407                  "type-spec or SOURCE=", sym->name, &e->where);
6408       goto failure;
6409     }
6410
6411   if (check_intent_in && sym->attr.intent == INTENT_IN)
6412     {
6413       gfc_error ("Cannot allocate INTENT(IN) variable '%s' at %L",
6414                  sym->name, &e->where);
6415       goto failure;
6416     }
6417     
6418   if (!code->expr3)
6419     {
6420       /* Add default initializer for those derived types that need them.  */
6421       if (e->ts.type == BT_DERIVED
6422           && (init_e = gfc_default_initializer (&e->ts)))
6423         {
6424           gfc_code *init_st = gfc_get_code ();
6425           init_st->loc = code->loc;
6426           init_st->op = EXEC_INIT_ASSIGN;
6427           init_st->expr1 = gfc_expr_to_initialize (e);
6428           init_st->expr2 = init_e;
6429           init_st->next = code->next;
6430           code->next = init_st;
6431         }
6432       else if (e->ts.type == BT_CLASS
6433                && ((code->ext.alloc.ts.type == BT_UNKNOWN
6434                     && (init_e = gfc_default_initializer (&e->ts.u.derived->components->ts)))
6435                    || (code->ext.alloc.ts.type == BT_DERIVED
6436                        && (init_e = gfc_default_initializer (&code->ext.alloc.ts)))))
6437         {
6438           gfc_code *init_st = gfc_get_code ();
6439           init_st->loc = code->loc;
6440           init_st->op = EXEC_INIT_ASSIGN;
6441           init_st->expr1 = gfc_expr_to_initialize (e);
6442           init_st->expr2 = init_e;
6443           init_st->next = code->next;
6444           code->next = init_st;
6445         }
6446     }
6447
6448   if (pointer || (dimension == 0 && codimension == 0))
6449     goto success;
6450
6451   /* Make sure the next-to-last reference node is an array specification.  */
6452
6453   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
6454       || (dimension && ref2->u.ar.dimen == 0))
6455     {
6456       gfc_error ("Array specification required in ALLOCATE statement "
6457                  "at %L", &e->where);
6458       goto failure;
6459     }
6460
6461   /* Make sure that the array section reference makes sense in the
6462     context of an ALLOCATE specification.  */
6463
6464   ar = &ref2->u.ar;
6465
6466   if (codimension && ar->codimen == 0)
6467     {
6468       gfc_error ("Coarray specification required in ALLOCATE statement "
6469                  "at %L", &e->where);
6470       goto failure;
6471     }
6472
6473   for (i = 0; i < ar->dimen; i++)
6474     {
6475       if (ref2->u.ar.type == AR_ELEMENT)
6476         goto check_symbols;
6477
6478       switch (ar->dimen_type[i])
6479         {
6480         case DIMEN_ELEMENT:
6481           break;
6482
6483         case DIMEN_RANGE:
6484           if (ar->start[i] != NULL
6485               && ar->end[i] != NULL
6486               && ar->stride[i] == NULL)
6487             break;
6488
6489           /* Fall Through...  */
6490
6491         case DIMEN_UNKNOWN:
6492         case DIMEN_VECTOR:
6493         case DIMEN_STAR:
6494           gfc_error ("Bad array specification in ALLOCATE statement at %L",
6495                      &e->where);
6496           goto failure;
6497         }
6498
6499 check_symbols:
6500       for (a = code->ext.alloc.list; a; a = a->next)
6501         {
6502           sym = a->expr->symtree->n.sym;
6503
6504           /* TODO - check derived type components.  */
6505           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
6506             continue;
6507
6508           if ((ar->start[i] != NULL
6509                && gfc_find_sym_in_expr (sym, ar->start[i]))
6510               || (ar->end[i] != NULL
6511                   && gfc_find_sym_in_expr (sym, ar->end[i])))
6512             {
6513               gfc_error ("'%s' must not appear in the array specification at "
6514                          "%L in the same ALLOCATE statement where it is "
6515                          "itself allocated", sym->name, &ar->where);
6516               goto failure;
6517             }
6518         }
6519     }
6520
6521   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
6522     {
6523       if (ar->dimen_type[i] == DIMEN_ELEMENT
6524           || ar->dimen_type[i] == DIMEN_RANGE)
6525         {
6526           if (i == (ar->dimen + ar->codimen - 1))
6527             {
6528               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
6529                          "statement at %L", &e->where);
6530               goto failure;
6531             }
6532           break;
6533         }
6534
6535       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
6536           && ar->stride[i] == NULL)
6537         break;
6538
6539       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
6540                  &e->where);
6541       goto failure;
6542     }
6543
6544   if (codimension)
6545     {
6546       gfc_error ("Sorry, allocatable coarrays are no yet supported coarray "
6547                  "at %L", &e->where);
6548       goto failure;
6549     }
6550
6551 success:
6552   return SUCCESS;
6553
6554 failure:
6555   return FAILURE;
6556 }
6557
6558 static void
6559 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
6560 {
6561   gfc_expr *stat, *errmsg, *pe, *qe;
6562   gfc_alloc *a, *p, *q;
6563
6564   stat = code->expr1 ? code->expr1 : NULL;
6565
6566   errmsg = code->expr2 ? code->expr2 : NULL;
6567
6568   /* Check the stat variable.  */
6569   if (stat)
6570     {
6571       if (stat->symtree->n.sym->attr.intent == INTENT_IN)
6572         gfc_error ("Stat-variable '%s' at %L cannot be INTENT(IN)",
6573                    stat->symtree->n.sym->name, &stat->where);
6574
6575       if (gfc_pure (NULL) && gfc_impure_variable (stat->symtree->n.sym))
6576         gfc_error ("Illegal stat-variable at %L for a PURE procedure",
6577                    &stat->where);
6578
6579       if ((stat->ts.type != BT_INTEGER
6580            && !(stat->ref && (stat->ref->type == REF_ARRAY
6581                               || stat->ref->type == REF_COMPONENT)))
6582           || stat->rank > 0)
6583         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
6584                    "variable", &stat->where);
6585
6586       for (p = code->ext.alloc.list; p; p = p->next)
6587         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
6588           gfc_error ("Stat-variable at %L shall not be %sd within "
6589                      "the same %s statement", &stat->where, fcn, fcn);
6590     }
6591
6592   /* Check the errmsg variable.  */
6593   if (errmsg)
6594     {
6595       if (!stat)
6596         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
6597                      &errmsg->where);
6598
6599       if (errmsg->symtree->n.sym->attr.intent == INTENT_IN)
6600         gfc_error ("Errmsg-variable '%s' at %L cannot be INTENT(IN)",
6601                    errmsg->symtree->n.sym->name, &errmsg->where);
6602
6603       if (gfc_pure (NULL) && gfc_impure_variable (errmsg->symtree->n.sym))
6604         gfc_error ("Illegal errmsg-variable at %L for a PURE procedure",
6605                    &errmsg->where);
6606
6607       if ((errmsg->ts.type != BT_CHARACTER
6608            && !(errmsg->ref
6609                 && (errmsg->ref->type == REF_ARRAY
6610                     || errmsg->ref->type == REF_COMPONENT)))
6611           || errmsg->rank > 0 )
6612         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
6613                    "variable", &errmsg->where);
6614
6615       for (p = code->ext.alloc.list; p; p = p->next)
6616         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
6617           gfc_error ("Errmsg-variable at %L shall not be %sd within "
6618                      "the same %s statement", &errmsg->where, fcn, fcn);
6619     }
6620
6621   /* Check that an allocate-object appears only once in the statement.  
6622      FIXME: Checking derived types is disabled.  */
6623   for (p = code->ext.alloc.list; p; p = p->next)
6624     {
6625       pe = p->expr;
6626       if ((pe->ref && pe->ref->type != REF_COMPONENT)
6627            && (pe->symtree->n.sym->ts.type != BT_DERIVED))
6628         {
6629           for (q = p->next; q; q = q->next)
6630             {
6631               qe = q->expr;
6632               if ((qe->ref && qe->ref->type != REF_COMPONENT)
6633                   && (qe->symtree->n.sym->ts.type != BT_DERIVED)
6634                   && (pe->symtree->n.sym->name == qe->symtree->n.sym->name))
6635                 gfc_error ("Allocate-object at %L also appears at %L",
6636                            &pe->where, &qe->where);
6637             }
6638         }
6639     }
6640
6641   if (strcmp (fcn, "ALLOCATE") == 0)
6642     {
6643       for (a = code->ext.alloc.list; a; a = a->next)
6644         resolve_allocate_expr (a->expr, code);
6645     }
6646   else
6647     {
6648       for (a = code->ext.alloc.list; a; a = a->next)
6649         resolve_deallocate_expr (a->expr);
6650     }
6651 }
6652
6653
6654 /************ SELECT CASE resolution subroutines ************/
6655
6656 /* Callback function for our mergesort variant.  Determines interval
6657    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
6658    op1 > op2.  Assumes we're not dealing with the default case.  
6659    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
6660    There are nine situations to check.  */
6661
6662 static int
6663 compare_cases (const gfc_case *op1, const gfc_case *op2)
6664 {
6665   int retval;
6666
6667   if (op1->low == NULL) /* op1 = (:L)  */
6668     {
6669       /* op2 = (:N), so overlap.  */
6670       retval = 0;
6671       /* op2 = (M:) or (M:N),  L < M  */
6672       if (op2->low != NULL
6673           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6674         retval = -1;
6675     }
6676   else if (op1->high == NULL) /* op1 = (K:)  */
6677     {
6678       /* op2 = (M:), so overlap.  */
6679       retval = 0;
6680       /* op2 = (:N) or (M:N), K > N  */
6681       if (op2->high != NULL
6682           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6683         retval = 1;
6684     }
6685   else /* op1 = (K:L)  */
6686     {
6687       if (op2->low == NULL)       /* op2 = (:N), K > N  */
6688         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6689                  ? 1 : 0;
6690       else if (op2->high == NULL) /* op2 = (M:), L < M  */
6691         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6692                  ? -1 : 0;
6693       else                      /* op2 = (M:N)  */
6694         {
6695           retval =  0;
6696           /* L < M  */
6697           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6698             retval =  -1;
6699           /* K > N  */
6700           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6701             retval =  1;
6702         }
6703     }
6704
6705   return retval;
6706 }
6707
6708
6709 /* Merge-sort a double linked case list, detecting overlap in the
6710    process.  LIST is the head of the double linked case list before it
6711    is sorted.  Returns the head of the sorted list if we don't see any
6712    overlap, or NULL otherwise.  */
6713
6714 static gfc_case *
6715 check_case_overlap (gfc_case *list)
6716 {
6717   gfc_case *p, *q, *e, *tail;
6718   int insize, nmerges, psize, qsize, cmp, overlap_seen;
6719
6720   /* If the passed list was empty, return immediately.  */
6721   if (!list)
6722     return NULL;
6723
6724   overlap_seen = 0;
6725   insize = 1;
6726
6727   /* Loop unconditionally.  The only exit from this loop is a return
6728      statement, when we've finished sorting the case list.  */
6729   for (;;)
6730     {
6731       p = list;
6732       list = NULL;
6733       tail = NULL;
6734
6735       /* Count the number of merges we do in this pass.  */
6736       nmerges = 0;
6737
6738       /* Loop while there exists a merge to be done.  */
6739       while (p)
6740         {
6741           int i;
6742
6743           /* Count this merge.  */
6744           nmerges++;
6745
6746           /* Cut the list in two pieces by stepping INSIZE places
6747              forward in the list, starting from P.  */
6748           psize = 0;
6749           q = p;
6750           for (i = 0; i < insize; i++)
6751             {
6752               psize++;
6753               q = q->right;
6754               if (!q)
6755                 break;
6756             }
6757           qsize = insize;
6758
6759           /* Now we have two lists.  Merge them!  */
6760           while (psize > 0 || (qsize > 0 && q != NULL))
6761             {
6762               /* See from which the next case to merge comes from.  */
6763               if (psize == 0)
6764                 {
6765                   /* P is empty so the next case must come from Q.  */
6766                   e = q;
6767                   q = q->right;
6768                   qsize--;
6769                 }
6770               else if (qsize == 0 || q == NULL)
6771                 {
6772                   /* Q is empty.  */
6773                   e = p;
6774                   p = p->right;
6775                   psize--;
6776                 }
6777               else
6778                 {
6779                   cmp = compare_cases (p, q);
6780                   if (cmp < 0)
6781                     {
6782                       /* The whole case range for P is less than the
6783                          one for Q.  */
6784                       e = p;
6785                       p = p->right;
6786                       psize--;
6787                     }
6788                   else if (cmp > 0)
6789                     {
6790                       /* The whole case range for Q is greater than
6791                          the case range for P.  */
6792                       e = q;
6793                       q = q->right;
6794                       qsize--;
6795                     }
6796                   else
6797                     {
6798                       /* The cases overlap, or they are the same
6799                          element in the list.  Either way, we must
6800                          issue an error and get the next case from P.  */
6801                       /* FIXME: Sort P and Q by line number.  */
6802                       gfc_error ("CASE label at %L overlaps with CASE "
6803                                  "label at %L", &p->where, &q->where);
6804                       overlap_seen = 1;
6805                       e = p;
6806                       p = p->right;
6807                       psize--;
6808                     }
6809                 }
6810
6811                 /* Add the next element to the merged list.  */
6812               if (tail)
6813                 tail->right = e;
6814               else
6815                 list = e;
6816               e->left = tail;
6817               tail = e;
6818             }
6819
6820           /* P has now stepped INSIZE places along, and so has Q.  So
6821              they're the same.  */
6822           p = q;
6823         }
6824       tail->right = NULL;
6825
6826       /* If we have done only one merge or none at all, we've
6827          finished sorting the cases.  */
6828       if (nmerges <= 1)
6829         {
6830           if (!overlap_seen)
6831             return list;
6832           else
6833             return NULL;
6834         }
6835
6836       /* Otherwise repeat, merging lists twice the size.  */
6837       insize *= 2;
6838     }
6839 }
6840
6841
6842 /* Check to see if an expression is suitable for use in a CASE statement.
6843    Makes sure that all case expressions are scalar constants of the same
6844    type.  Return FAILURE if anything is wrong.  */
6845
6846 static gfc_try
6847 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
6848 {
6849   if (e == NULL) return SUCCESS;
6850
6851   if (e->ts.type != case_expr->ts.type)
6852     {
6853       gfc_error ("Expression in CASE statement at %L must be of type %s",
6854                  &e->where, gfc_basic_typename (case_expr->ts.type));
6855       return FAILURE;
6856     }
6857
6858   /* C805 (R808) For a given case-construct, each case-value shall be of
6859      the same type as case-expr.  For character type, length differences
6860      are allowed, but the kind type parameters shall be the same.  */
6861
6862   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
6863     {
6864       gfc_error ("Expression in CASE statement at %L must be of kind %d",
6865                  &e->where, case_expr->ts.kind);
6866       return FAILURE;
6867     }
6868
6869   /* Convert the case value kind to that of case expression kind, if needed.
6870      FIXME:  Should a warning be issued?  */
6871   if (e->ts.kind != case_expr->ts.kind)
6872     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
6873
6874   if (e->rank != 0)
6875     {
6876       gfc_error ("Expression in CASE statement at %L must be scalar",
6877                  &e->where);
6878       return FAILURE;
6879     }
6880
6881   return SUCCESS;
6882 }
6883
6884
6885 /* Given a completely parsed select statement, we:
6886
6887      - Validate all expressions and code within the SELECT.
6888      - Make sure that the selection expression is not of the wrong type.
6889      - Make sure that no case ranges overlap.
6890      - Eliminate unreachable cases and unreachable code resulting from
6891        removing case labels.
6892
6893    The standard does allow unreachable cases, e.g. CASE (5:3).  But
6894    they are a hassle for code generation, and to prevent that, we just
6895    cut them out here.  This is not necessary for overlapping cases
6896    because they are illegal and we never even try to generate code.
6897
6898    We have the additional caveat that a SELECT construct could have
6899    been a computed GOTO in the source code. Fortunately we can fairly
6900    easily work around that here: The case_expr for a "real" SELECT CASE
6901    is in code->expr1, but for a computed GOTO it is in code->expr2. All
6902    we have to do is make sure that the case_expr is a scalar integer
6903    expression.  */
6904
6905 static void
6906 resolve_select (gfc_code *code)
6907 {
6908   gfc_code *body;
6909   gfc_expr *case_expr;
6910   gfc_case *cp, *default_case, *tail, *head;
6911   int seen_unreachable;
6912   int seen_logical;
6913   int ncases;
6914   bt type;
6915   gfc_try t;
6916
6917   if (code->expr1 == NULL)
6918     {
6919       /* This was actually a computed GOTO statement.  */
6920       case_expr = code->expr2;
6921       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
6922         gfc_error ("Selection expression in computed GOTO statement "
6923                    "at %L must be a scalar integer expression",
6924                    &case_expr->where);
6925
6926       /* Further checking is not necessary because this SELECT was built
6927          by the compiler, so it should always be OK.  Just move the
6928          case_expr from expr2 to expr so that we can handle computed
6929          GOTOs as normal SELECTs from here on.  */
6930       code->expr1 = code->expr2;
6931       code->expr2 = NULL;
6932       return;
6933     }
6934
6935   case_expr = code->expr1;
6936
6937   type = case_expr->ts.type;
6938   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
6939     {
6940       gfc_error ("Argument of SELECT statement at %L cannot be %s",
6941                  &case_expr->where, gfc_typename (&case_expr->ts));
6942
6943       /* Punt. Going on here just produce more garbage error messages.  */
6944       return;
6945     }
6946
6947   if (case_expr->rank != 0)
6948     {
6949       gfc_error ("Argument of SELECT statement at %L must be a scalar "
6950                  "expression", &case_expr->where);
6951
6952       /* Punt.  */
6953       return;
6954     }
6955
6956   /* PR 19168 has a long discussion concerning a mismatch of the kinds
6957      of the SELECT CASE expression and its CASE values.  Walk the lists
6958      of case values, and if we find a mismatch, promote case_expr to
6959      the appropriate kind.  */
6960
6961   if (type == BT_LOGICAL || type == BT_INTEGER)
6962     {
6963       for (body = code->block; body; body = body->block)
6964         {
6965           /* Walk the case label list.  */
6966           for (cp = body->ext.case_list; cp; cp = cp->next)
6967             {
6968               /* Intercept the DEFAULT case.  It does not have a kind.  */
6969               if (cp->low == NULL && cp->high == NULL)
6970                 continue;
6971
6972               /* Unreachable case ranges are discarded, so ignore.  */
6973               if (cp->low != NULL && cp->high != NULL
6974                   && cp->low != cp->high
6975                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
6976                 continue;
6977
6978               /* FIXME: Should a warning be issued?  */
6979               if (cp->low != NULL
6980                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
6981                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
6982
6983               if (cp->high != NULL
6984                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
6985                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
6986             }
6987          }
6988     }
6989
6990   /* Assume there is no DEFAULT case.  */
6991   default_case = NULL;
6992   head = tail = NULL;
6993   ncases = 0;
6994   seen_logical = 0;
6995
6996   for (body = code->block; body; body = body->block)
6997     {
6998       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
6999       t = SUCCESS;
7000       seen_unreachable = 0;
7001
7002       /* Walk the case label list, making sure that all case labels
7003          are legal.  */
7004       for (cp = body->ext.case_list; cp; cp = cp->next)
7005         {
7006           /* Count the number of cases in the whole construct.  */
7007           ncases++;
7008
7009           /* Intercept the DEFAULT case.  */
7010           if (cp->low == NULL && cp->high == NULL)
7011             {
7012               if (default_case != NULL)
7013                 {
7014                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
7015                              "by a second DEFAULT CASE at %L",
7016                              &default_case->where, &cp->where);
7017                   t = FAILURE;
7018                   break;
7019                 }
7020               else
7021                 {
7022                   default_case = cp;
7023                   continue;
7024                 }
7025             }
7026
7027           /* Deal with single value cases and case ranges.  Errors are
7028              issued from the validation function.  */
7029           if(validate_case_label_expr (cp->low, case_expr) != SUCCESS
7030              || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
7031             {
7032               t = FAILURE;
7033               break;
7034             }
7035
7036           if (type == BT_LOGICAL
7037               && ((cp->low == NULL || cp->high == NULL)
7038                   || cp->low != cp->high))
7039             {
7040               gfc_error ("Logical range in CASE statement at %L is not "
7041                          "allowed", &cp->low->where);
7042               t = FAILURE;
7043               break;
7044             }
7045
7046           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
7047             {
7048               int value;
7049               value = cp->low->value.logical == 0 ? 2 : 1;
7050               if (value & seen_logical)
7051                 {
7052                   gfc_error ("constant logical value in CASE statement "
7053                              "is repeated at %L",
7054                              &cp->low->where);
7055                   t = FAILURE;
7056                   break;
7057                 }
7058               seen_logical |= value;
7059             }
7060
7061           if (cp->low != NULL && cp->high != NULL
7062               && cp->low != cp->high
7063               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7064             {
7065               if (gfc_option.warn_surprising)
7066                 gfc_warning ("Range specification at %L can never "
7067                              "be matched", &cp->where);
7068
7069               cp->unreachable = 1;
7070               seen_unreachable = 1;
7071             }
7072           else
7073             {
7074               /* If the case range can be matched, it can also overlap with
7075                  other cases.  To make sure it does not, we put it in a
7076                  double linked list here.  We sort that with a merge sort
7077                  later on to detect any overlapping cases.  */
7078               if (!head)
7079                 {
7080                   head = tail = cp;
7081                   head->right = head->left = NULL;
7082                 }
7083               else
7084                 {
7085                   tail->right = cp;
7086                   tail->right->left = tail;
7087                   tail = tail->right;
7088                   tail->right = NULL;
7089                 }
7090             }
7091         }
7092
7093       /* It there was a failure in the previous case label, give up
7094          for this case label list.  Continue with the next block.  */
7095       if (t == FAILURE)
7096         continue;
7097
7098       /* See if any case labels that are unreachable have been seen.
7099          If so, we eliminate them.  This is a bit of a kludge because
7100          the case lists for a single case statement (label) is a
7101          single forward linked lists.  */
7102       if (seen_unreachable)
7103       {
7104         /* Advance until the first case in the list is reachable.  */
7105         while (body->ext.case_list != NULL
7106                && body->ext.case_list->unreachable)
7107           {
7108             gfc_case *n = body->ext.case_list;
7109             body->ext.case_list = body->ext.case_list->next;
7110             n->next = NULL;
7111             gfc_free_case_list (n);
7112           }
7113
7114         /* Strip all other unreachable cases.  */
7115         if (body->ext.case_list)
7116           {
7117             for (cp = body->ext.case_list; cp->next; cp = cp->next)
7118               {
7119                 if (cp->next->unreachable)
7120                   {
7121                     gfc_case *n = cp->next;
7122                     cp->next = cp->next->next;
7123                     n->next = NULL;
7124                     gfc_free_case_list (n);
7125                   }
7126               }
7127           }
7128       }
7129     }
7130
7131   /* See if there were overlapping cases.  If the check returns NULL,
7132      there was overlap.  In that case we don't do anything.  If head
7133      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7134      then used during code generation for SELECT CASE constructs with
7135      a case expression of a CHARACTER type.  */
7136   if (head)
7137     {
7138       head = check_case_overlap (head);
7139
7140       /* Prepend the default_case if it is there.  */
7141       if (head != NULL && default_case)
7142         {
7143           default_case->left = NULL;
7144           default_case->right = head;
7145           head->left = default_case;
7146         }
7147     }
7148
7149   /* Eliminate dead blocks that may be the result if we've seen
7150      unreachable case labels for a block.  */
7151   for (body = code; body && body->block; body = body->block)
7152     {
7153       if (body->block->ext.case_list == NULL)
7154         {
7155           /* Cut the unreachable block from the code chain.  */
7156           gfc_code *c = body->block;
7157           body->block = c->block;
7158
7159           /* Kill the dead block, but not the blocks below it.  */
7160           c->block = NULL;
7161           gfc_free_statements (c);
7162         }
7163     }
7164
7165   /* More than two cases is legal but insane for logical selects.
7166      Issue a warning for it.  */
7167   if (gfc_option.warn_surprising && type == BT_LOGICAL
7168       && ncases > 2)
7169     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7170                  &code->loc);
7171 }
7172
7173
7174 /* Check if a derived type is extensible.  */
7175
7176 bool
7177 gfc_type_is_extensible (gfc_symbol *sym)
7178 {
7179   return !(sym->attr.is_bind_c || sym->attr.sequence);
7180 }
7181
7182
7183 /* Resolve a SELECT TYPE statement.  */
7184
7185 static void
7186 resolve_select_type (gfc_code *code)
7187 {
7188   gfc_symbol *selector_type;
7189   gfc_code *body, *new_st, *if_st, *tail;
7190   gfc_code *class_is = NULL, *default_case = NULL;
7191   gfc_case *c;
7192   gfc_symtree *st;
7193   char name[GFC_MAX_SYMBOL_LEN];
7194   gfc_namespace *ns;
7195   int error = 0;
7196
7197   ns = code->ext.ns;
7198   gfc_resolve (ns);
7199
7200   if (code->expr2)
7201     selector_type = code->expr2->ts.u.derived->components->ts.u.derived;
7202   else
7203     selector_type = code->expr1->ts.u.derived->components->ts.u.derived;
7204
7205   /* Loop over TYPE IS / CLASS IS cases.  */
7206   for (body = code->block; body; body = body->block)
7207     {
7208       c = body->ext.case_list;
7209
7210       /* Check F03:C815.  */
7211       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7212           && !gfc_type_is_extensible (c->ts.u.derived))
7213         {
7214           gfc_error ("Derived type '%s' at %L must be extensible",
7215                      c->ts.u.derived->name, &c->where);
7216           error++;
7217           continue;
7218         }
7219
7220       /* Check F03:C816.  */
7221       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7222           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
7223         {
7224           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
7225                      c->ts.u.derived->name, &c->where, selector_type->name);
7226           error++;
7227           continue;
7228         }
7229
7230       /* Intercept the DEFAULT case.  */
7231       if (c->ts.type == BT_UNKNOWN)
7232         {
7233           /* Check F03:C818.  */
7234           if (default_case)
7235             {
7236               gfc_error ("The DEFAULT CASE at %L cannot be followed "
7237                          "by a second DEFAULT CASE at %L",
7238                          &default_case->ext.case_list->where, &c->where);
7239               error++;
7240               continue;
7241             }
7242           else
7243             default_case = body;
7244         }
7245     }
7246     
7247   if (error>0)
7248     return;
7249
7250   if (code->expr2)
7251     {
7252       /* Insert assignment for selector variable.  */
7253       new_st = gfc_get_code ();
7254       new_st->op = EXEC_ASSIGN;
7255       new_st->expr1 = gfc_copy_expr (code->expr1);
7256       new_st->expr2 = gfc_copy_expr (code->expr2);
7257       ns->code = new_st;
7258     }
7259
7260   /* Put SELECT TYPE statement inside a BLOCK.  */
7261   new_st = gfc_get_code ();
7262   new_st->op = code->op;
7263   new_st->expr1 = code->expr1;
7264   new_st->expr2 = code->expr2;
7265   new_st->block = code->block;
7266   if (!ns->code)
7267     ns->code = new_st;
7268   else
7269     ns->code->next = new_st;
7270   code->op = EXEC_BLOCK;
7271   code->expr1 = code->expr2 =  NULL;
7272   code->block = NULL;
7273
7274   code = new_st;
7275
7276   /* Transform to EXEC_SELECT.  */
7277   code->op = EXEC_SELECT;
7278   gfc_add_component_ref (code->expr1, "$vptr");
7279   gfc_add_component_ref (code->expr1, "$hash");
7280
7281   /* Loop over TYPE IS / CLASS IS cases.  */
7282   for (body = code->block; body; body = body->block)
7283     {
7284       c = body->ext.case_list;
7285       
7286       if (c->ts.type == BT_DERIVED)
7287         c->low = c->high = gfc_int_expr (c->ts.u.derived->hash_value);
7288       else if (c->ts.type == BT_UNKNOWN)
7289         continue;
7290       
7291       /* Assign temporary to selector.  */
7292       if (c->ts.type == BT_CLASS)
7293         sprintf (name, "tmp$class$%s", c->ts.u.derived->name);
7294       else
7295         sprintf (name, "tmp$type$%s", c->ts.u.derived->name);
7296       st = gfc_find_symtree (ns->sym_root, name);
7297       new_st = gfc_get_code ();
7298       new_st->expr1 = gfc_get_variable_expr (st);
7299       new_st->expr2 = gfc_get_variable_expr (code->expr1->symtree);
7300       if (c->ts.type == BT_DERIVED)
7301         {
7302           new_st->op = EXEC_POINTER_ASSIGN;
7303           gfc_add_component_ref (new_st->expr2, "$data");
7304         }
7305       else
7306         new_st->op = EXEC_POINTER_ASSIGN;
7307       new_st->next = body->next;
7308       body->next = new_st;
7309     }
7310     
7311   /* Take out CLASS IS cases for separate treatment.  */
7312   body = code;
7313   while (body && body->block)
7314     {
7315       if (body->block->ext.case_list->ts.type == BT_CLASS)
7316         {
7317           /* Add to class_is list.  */
7318           if (class_is == NULL)
7319             { 
7320               class_is = body->block;
7321               tail = class_is;
7322             }
7323           else
7324             {
7325               for (tail = class_is; tail->block; tail = tail->block) ;
7326               tail->block = body->block;
7327               tail = tail->block;
7328             }
7329           /* Remove from EXEC_SELECT list.  */
7330           body->block = body->block->block;
7331           tail->block = NULL;
7332         }
7333       else
7334         body = body->block;
7335     }
7336
7337   if (class_is)
7338     {
7339       gfc_symbol *vtab;
7340       
7341       if (!default_case)
7342         {
7343           /* Add a default case to hold the CLASS IS cases.  */
7344           for (tail = code; tail->block; tail = tail->block) ;
7345           tail->block = gfc_get_code ();
7346           tail = tail->block;
7347           tail->op = EXEC_SELECT_TYPE;
7348           tail->ext.case_list = gfc_get_case ();
7349           tail->ext.case_list->ts.type = BT_UNKNOWN;
7350           tail->next = NULL;
7351           default_case = tail;
7352         }
7353       
7354       /* More than one CLASS IS block?  */
7355       if (class_is->block)
7356         {
7357           gfc_code **c1,*c2;
7358           bool swapped;
7359           /* Sort CLASS IS blocks by extension level.  */
7360           do
7361             {
7362               swapped = false;
7363               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
7364                 {
7365                   c2 = (*c1)->block;
7366                   /* F03:C817 (check for doubles).  */
7367                   if ((*c1)->ext.case_list->ts.u.derived->hash_value
7368                       == c2->ext.case_list->ts.u.derived->hash_value)
7369                     {
7370                       gfc_error ("Double CLASS IS block in SELECT TYPE "
7371                                  "statement at %L", &c2->ext.case_list->where);
7372                       return;
7373                     }
7374                   if ((*c1)->ext.case_list->ts.u.derived->attr.extension
7375                       < c2->ext.case_list->ts.u.derived->attr.extension)
7376                     {
7377                       /* Swap.  */
7378                       (*c1)->block = c2->block;
7379                       c2->block = *c1;
7380                       *c1 = c2;
7381                       swapped = true;
7382                     }
7383                 }
7384             }
7385           while (swapped);
7386         }
7387         
7388       /* Generate IF chain.  */
7389       if_st = gfc_get_code ();
7390       if_st->op = EXEC_IF;
7391       new_st = if_st;
7392       for (body = class_is; body; body = body->block)
7393         {
7394           new_st->block = gfc_get_code ();
7395           new_st = new_st->block;
7396           new_st->op = EXEC_IF;
7397           /* Set up IF condition: Call _gfortran_is_extension_of.  */
7398           new_st->expr1 = gfc_get_expr ();
7399           new_st->expr1->expr_type = EXPR_FUNCTION;
7400           new_st->expr1->ts.type = BT_LOGICAL;
7401           new_st->expr1->ts.kind = 4;
7402           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
7403           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
7404           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
7405           /* Set up arguments.  */
7406           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
7407           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
7408           gfc_add_component_ref (new_st->expr1->value.function.actual->expr, "$vptr");
7409           vtab = gfc_find_derived_vtab (body->ext.case_list->ts.u.derived);
7410           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
7411           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
7412           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
7413           new_st->next = body->next;
7414         }
7415         if (default_case->next)
7416           {
7417             new_st->block = gfc_get_code ();
7418             new_st = new_st->block;
7419             new_st->op = EXEC_IF;
7420             new_st->next = default_case->next;
7421           }
7422           
7423         /* Replace CLASS DEFAULT code by the IF chain.  */
7424         default_case->next = if_st;
7425     }
7426
7427   resolve_select (code);
7428
7429 }
7430
7431
7432 /* Resolve a transfer statement. This is making sure that:
7433    -- a derived type being transferred has only non-pointer components
7434    -- a derived type being transferred doesn't have private components, unless 
7435       it's being transferred from the module where the type was defined
7436    -- we're not trying to transfer a whole assumed size array.  */
7437
7438 static void
7439 resolve_transfer (gfc_code *code)
7440 {
7441   gfc_typespec *ts;
7442   gfc_symbol *sym;
7443   gfc_ref *ref;
7444   gfc_expr *exp;
7445
7446   exp = code->expr1;
7447
7448   if (exp->expr_type != EXPR_VARIABLE && exp->expr_type != EXPR_FUNCTION)
7449     return;
7450
7451   sym = exp->symtree->n.sym;
7452   ts = &sym->ts;
7453
7454   /* Go to actual component transferred.  */
7455   for (ref = code->expr1->ref; ref; ref = ref->next)
7456     if (ref->type == REF_COMPONENT)
7457       ts = &ref->u.c.component->ts;
7458
7459   if (ts->type == BT_DERIVED)
7460     {
7461       /* Check that transferred derived type doesn't contain POINTER
7462          components.  */
7463       if (ts->u.derived->attr.pointer_comp)
7464         {
7465           gfc_error ("Data transfer element at %L cannot have "
7466                      "POINTER components", &code->loc);
7467           return;
7468         }
7469
7470       if (ts->u.derived->attr.alloc_comp)
7471         {
7472           gfc_error ("Data transfer element at %L cannot have "
7473                      "ALLOCATABLE components", &code->loc);
7474           return;
7475         }
7476
7477       if (derived_inaccessible (ts->u.derived))
7478         {
7479           gfc_error ("Data transfer element at %L cannot have "
7480                      "PRIVATE components",&code->loc);
7481           return;
7482         }
7483     }
7484
7485   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
7486       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
7487     {
7488       gfc_error ("Data transfer element at %L cannot be a full reference to "
7489                  "an assumed-size array", &code->loc);
7490       return;
7491     }
7492 }
7493
7494
7495 /*********** Toplevel code resolution subroutines ***********/
7496
7497 /* Find the set of labels that are reachable from this block.  We also
7498    record the last statement in each block.  */
7499      
7500 static void
7501 find_reachable_labels (gfc_code *block)
7502 {
7503   gfc_code *c;
7504
7505   if (!block)
7506     return;
7507
7508   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
7509
7510   /* Collect labels in this block.  We don't keep those corresponding
7511      to END {IF|SELECT}, these are checked in resolve_branch by going
7512      up through the code_stack.  */
7513   for (c = block; c; c = c->next)
7514     {
7515       if (c->here && c->op != EXEC_END_BLOCK)
7516         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
7517     }
7518
7519   /* Merge with labels from parent block.  */
7520   if (cs_base->prev)
7521     {
7522       gcc_assert (cs_base->prev->reachable_labels);
7523       bitmap_ior_into (cs_base->reachable_labels,
7524                        cs_base->prev->reachable_labels);
7525     }
7526 }
7527
7528
7529 static void
7530 resolve_sync (gfc_code *code)
7531 {
7532   /* Check imageset. The * case matches expr1 == NULL.  */
7533   if (code->expr1)
7534     {
7535       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
7536         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
7537                    "INTEGER expression", &code->expr1->where);
7538       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
7539           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
7540         gfc_error ("Imageset argument at %L must between 1 and num_images()",
7541                    &code->expr1->where);
7542       else if (code->expr1->expr_type == EXPR_ARRAY
7543                && gfc_simplify_expr (code->expr1, 0) == SUCCESS)
7544         {
7545            gfc_constructor *cons;
7546            for (cons = code->expr1->value.constructor; cons; cons = cons->next)
7547              if (cons->expr->expr_type == EXPR_CONSTANT
7548                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
7549                gfc_error ("Imageset argument at %L must between 1 and "
7550                           "num_images()", &cons->expr->where);
7551         }
7552     }
7553
7554   /* Check STAT.  */
7555   if (code->expr2
7556       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
7557           || code->expr2->expr_type != EXPR_VARIABLE))
7558     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
7559                &code->expr2->where);
7560
7561   /* Check ERRMSG.  */
7562   if (code->expr3
7563       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
7564           || code->expr3->expr_type != EXPR_VARIABLE))
7565     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
7566                &code->expr3->where);
7567 }
7568
7569
7570 /* Given a branch to a label, see if the branch is conforming.
7571    The code node describes where the branch is located.  */
7572
7573 static void
7574 resolve_branch (gfc_st_label *label, gfc_code *code)
7575 {
7576   code_stack *stack;
7577
7578   if (label == NULL)
7579     return;
7580
7581   /* Step one: is this a valid branching target?  */
7582
7583   if (label->defined == ST_LABEL_UNKNOWN)
7584     {
7585       gfc_error ("Label %d referenced at %L is never defined", label->value,
7586                  &label->where);
7587       return;
7588     }
7589
7590   if (label->defined != ST_LABEL_TARGET)
7591     {
7592       gfc_error ("Statement at %L is not a valid branch target statement "
7593                  "for the branch statement at %L", &label->where, &code->loc);
7594       return;
7595     }
7596
7597   /* Step two: make sure this branch is not a branch to itself ;-)  */
7598
7599   if (code->here == label)
7600     {
7601       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
7602       return;
7603     }
7604
7605   /* Step three:  See if the label is in the same block as the
7606      branching statement.  The hard work has been done by setting up
7607      the bitmap reachable_labels.  */
7608
7609   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
7610     {
7611       /* Check now whether there is a CRITICAL construct; if so, check
7612          whether the label is still visible outside of the CRITICAL block,
7613          which is invalid.  */
7614       for (stack = cs_base; stack; stack = stack->prev)
7615         if (stack->current->op == EXEC_CRITICAL
7616             && bitmap_bit_p (stack->reachable_labels, label->value))
7617           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
7618                       " at %L", &code->loc, &label->where);
7619
7620       return;
7621     }
7622
7623   /* Step four:  If we haven't found the label in the bitmap, it may
7624     still be the label of the END of the enclosing block, in which
7625     case we find it by going up the code_stack.  */
7626
7627   for (stack = cs_base; stack; stack = stack->prev)
7628     {
7629       if (stack->current->next && stack->current->next->here == label)
7630         break;
7631       if (stack->current->op == EXEC_CRITICAL)
7632         {
7633           /* Note: A label at END CRITICAL does not leave the CRITICAL
7634              construct as END CRITICAL is still part of it.  */
7635           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
7636                       " at %L", &code->loc, &label->where);
7637           return;
7638         }
7639     }
7640
7641   if (stack)
7642     {
7643       gcc_assert (stack->current->next->op == EXEC_END_BLOCK);
7644       return;
7645     }
7646
7647   /* The label is not in an enclosing block, so illegal.  This was
7648      allowed in Fortran 66, so we allow it as extension.  No
7649      further checks are necessary in this case.  */
7650   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
7651                   "as the GOTO statement at %L", &label->where,
7652                   &code->loc);
7653   return;
7654 }
7655
7656
7657 /* Check whether EXPR1 has the same shape as EXPR2.  */
7658
7659 static gfc_try
7660 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
7661 {
7662   mpz_t shape[GFC_MAX_DIMENSIONS];
7663   mpz_t shape2[GFC_MAX_DIMENSIONS];
7664   gfc_try result = FAILURE;
7665   int i;
7666
7667   /* Compare the rank.  */
7668   if (expr1->rank != expr2->rank)
7669     return result;
7670
7671   /* Compare the size of each dimension.  */
7672   for (i=0; i<expr1->rank; i++)
7673     {
7674       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
7675         goto ignore;
7676
7677       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
7678         goto ignore;
7679
7680       if (mpz_cmp (shape[i], shape2[i]))
7681         goto over;
7682     }
7683
7684   /* When either of the two expression is an assumed size array, we
7685      ignore the comparison of dimension sizes.  */
7686 ignore:
7687   result = SUCCESS;
7688
7689 over:
7690   for (i--; i >= 0; i--)
7691     {
7692       mpz_clear (shape[i]);
7693       mpz_clear (shape2[i]);
7694     }
7695   return result;
7696 }
7697
7698
7699 /* Check whether a WHERE assignment target or a WHERE mask expression
7700    has the same shape as the outmost WHERE mask expression.  */
7701
7702 static void
7703 resolve_where (gfc_code *code, gfc_expr *mask)
7704 {
7705   gfc_code *cblock;
7706   gfc_code *cnext;
7707   gfc_expr *e = NULL;
7708
7709   cblock = code->block;
7710
7711   /* Store the first WHERE mask-expr of the WHERE statement or construct.
7712      In case of nested WHERE, only the outmost one is stored.  */
7713   if (mask == NULL) /* outmost WHERE */
7714     e = cblock->expr1;
7715   else /* inner WHERE */
7716     e = mask;
7717
7718   while (cblock)
7719     {
7720       if (cblock->expr1)
7721         {
7722           /* Check if the mask-expr has a consistent shape with the
7723              outmost WHERE mask-expr.  */
7724           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
7725             gfc_error ("WHERE mask at %L has inconsistent shape",
7726                        &cblock->expr1->where);
7727          }
7728
7729       /* the assignment statement of a WHERE statement, or the first
7730          statement in where-body-construct of a WHERE construct */
7731       cnext = cblock->next;
7732       while (cnext)
7733         {
7734           switch (cnext->op)
7735             {
7736             /* WHERE assignment statement */
7737             case EXEC_ASSIGN:
7738
7739               /* Check shape consistent for WHERE assignment target.  */
7740               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
7741                gfc_error ("WHERE assignment target at %L has "
7742                           "inconsistent shape", &cnext->expr1->where);
7743               break;
7744
7745   
7746             case EXEC_ASSIGN_CALL:
7747               resolve_call (cnext);
7748               if (!cnext->resolved_sym->attr.elemental)
7749                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
7750                           &cnext->ext.actual->expr->where);
7751               break;
7752
7753             /* WHERE or WHERE construct is part of a where-body-construct */
7754             case EXEC_WHERE:
7755               resolve_where (cnext, e);
7756               break;
7757
7758             default:
7759               gfc_error ("Unsupported statement inside WHERE at %L",
7760                          &cnext->loc);
7761             }
7762          /* the next statement within the same where-body-construct */
7763          cnext = cnext->next;
7764        }
7765     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
7766     cblock = cblock->block;
7767   }
7768 }
7769
7770
7771 /* Resolve assignment in FORALL construct.
7772    NVAR is the number of FORALL index variables, and VAR_EXPR records the
7773    FORALL index variables.  */
7774
7775 static void
7776 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
7777 {
7778   int n;
7779
7780   for (n = 0; n < nvar; n++)
7781     {
7782       gfc_symbol *forall_index;
7783
7784       forall_index = var_expr[n]->symtree->n.sym;
7785
7786       /* Check whether the assignment target is one of the FORALL index
7787          variable.  */
7788       if ((code->expr1->expr_type == EXPR_VARIABLE)
7789           && (code->expr1->symtree->n.sym == forall_index))
7790         gfc_error ("Assignment to a FORALL index variable at %L",
7791                    &code->expr1->where);
7792       else
7793         {
7794           /* If one of the FORALL index variables doesn't appear in the
7795              assignment variable, then there could be a many-to-one
7796              assignment.  Emit a warning rather than an error because the
7797              mask could be resolving this problem.  */
7798           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
7799             gfc_warning ("The FORALL with index '%s' is not used on the "
7800                          "left side of the assignment at %L and so might "
7801                          "cause multiple assignment to this object",
7802                          var_expr[n]->symtree->name, &code->expr1->where);
7803         }
7804     }
7805 }
7806
7807
7808 /* Resolve WHERE statement in FORALL construct.  */
7809
7810 static void
7811 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
7812                                   gfc_expr **var_expr)
7813 {
7814   gfc_code *cblock;
7815   gfc_code *cnext;
7816
7817   cblock = code->block;
7818   while (cblock)
7819     {
7820       /* the assignment statement of a WHERE statement, or the first
7821          statement in where-body-construct of a WHERE construct */
7822       cnext = cblock->next;
7823       while (cnext)
7824         {
7825           switch (cnext->op)
7826             {
7827             /* WHERE assignment statement */
7828             case EXEC_ASSIGN:
7829               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
7830               break;
7831   
7832             /* WHERE operator assignment statement */
7833             case EXEC_ASSIGN_CALL:
7834               resolve_call (cnext);
7835               if (!cnext->resolved_sym->attr.elemental)
7836                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
7837                           &cnext->ext.actual->expr->where);
7838               break;
7839
7840             /* WHERE or WHERE construct is part of a where-body-construct */
7841             case EXEC_WHERE:
7842               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
7843               break;
7844
7845             default:
7846               gfc_error ("Unsupported statement inside WHERE at %L",
7847                          &cnext->loc);
7848             }
7849           /* the next statement within the same where-body-construct */
7850           cnext = cnext->next;
7851         }
7852       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
7853       cblock = cblock->block;
7854     }
7855 }
7856
7857
7858 /* Traverse the FORALL body to check whether the following errors exist:
7859    1. For assignment, check if a many-to-one assignment happens.
7860    2. For WHERE statement, check the WHERE body to see if there is any
7861       many-to-one assignment.  */
7862
7863 static void
7864 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
7865 {
7866   gfc_code *c;
7867
7868   c = code->block->next;
7869   while (c)
7870     {
7871       switch (c->op)
7872         {
7873         case EXEC_ASSIGN:
7874         case EXEC_POINTER_ASSIGN:
7875           gfc_resolve_assign_in_forall (c, nvar, var_expr);
7876           break;
7877
7878         case EXEC_ASSIGN_CALL:
7879           resolve_call (c);
7880           break;
7881
7882         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
7883            there is no need to handle it here.  */
7884         case EXEC_FORALL:
7885           break;
7886         case EXEC_WHERE:
7887           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
7888           break;
7889         default:
7890           break;
7891         }
7892       /* The next statement in the FORALL body.  */
7893       c = c->next;
7894     }
7895 }
7896
7897
7898 /* Counts the number of iterators needed inside a forall construct, including
7899    nested forall constructs. This is used to allocate the needed memory 
7900    in gfc_resolve_forall.  */
7901
7902 static int 
7903 gfc_count_forall_iterators (gfc_code *code)
7904 {
7905   int max_iters, sub_iters, current_iters;
7906   gfc_forall_iterator *fa;
7907
7908   gcc_assert(code->op == EXEC_FORALL);
7909   max_iters = 0;
7910   current_iters = 0;
7911
7912   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
7913     current_iters ++;
7914   
7915   code = code->block->next;
7916
7917   while (code)
7918     {          
7919       if (code->op == EXEC_FORALL)
7920         {
7921           sub_iters = gfc_count_forall_iterators (code);
7922           if (sub_iters > max_iters)
7923             max_iters = sub_iters;
7924         }
7925       code = code->next;
7926     }
7927
7928   return current_iters + max_iters;
7929 }
7930
7931
7932 /* Given a FORALL construct, first resolve the FORALL iterator, then call
7933    gfc_resolve_forall_body to resolve the FORALL body.  */
7934
7935 static void
7936 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
7937 {
7938   static gfc_expr **var_expr;
7939   static int total_var = 0;
7940   static int nvar = 0;
7941   int old_nvar, tmp;
7942   gfc_forall_iterator *fa;
7943   int i;
7944
7945   old_nvar = nvar;
7946
7947   /* Start to resolve a FORALL construct   */
7948   if (forall_save == 0)
7949     {
7950       /* Count the total number of FORALL index in the nested FORALL
7951          construct in order to allocate the VAR_EXPR with proper size.  */
7952       total_var = gfc_count_forall_iterators (code);
7953
7954       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
7955       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
7956     }
7957
7958   /* The information about FORALL iterator, including FORALL index start, end
7959      and stride. The FORALL index can not appear in start, end or stride.  */
7960   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
7961     {
7962       /* Check if any outer FORALL index name is the same as the current
7963          one.  */
7964       for (i = 0; i < nvar; i++)
7965         {
7966           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
7967             {
7968               gfc_error ("An outer FORALL construct already has an index "
7969                          "with this name %L", &fa->var->where);
7970             }
7971         }
7972
7973       /* Record the current FORALL index.  */
7974       var_expr[nvar] = gfc_copy_expr (fa->var);
7975
7976       nvar++;
7977
7978       /* No memory leak.  */
7979       gcc_assert (nvar <= total_var);
7980     }
7981
7982   /* Resolve the FORALL body.  */
7983   gfc_resolve_forall_body (code, nvar, var_expr);
7984
7985   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
7986   gfc_resolve_blocks (code->block, ns);
7987
7988   tmp = nvar;
7989   nvar = old_nvar;
7990   /* Free only the VAR_EXPRs allocated in this frame.  */
7991   for (i = nvar; i < tmp; i++)
7992      gfc_free_expr (var_expr[i]);
7993
7994   if (nvar == 0)
7995     {
7996       /* We are in the outermost FORALL construct.  */
7997       gcc_assert (forall_save == 0);
7998
7999       /* VAR_EXPR is not needed any more.  */
8000       gfc_free (var_expr);
8001       total_var = 0;
8002     }
8003 }
8004
8005
8006 /* Resolve a BLOCK construct statement.  */
8007
8008 static void
8009 resolve_block_construct (gfc_code* code)
8010 {
8011   /* Eventually, we may want to do some checks here or handle special stuff.
8012      But so far the only thing we can do is resolving the local namespace.  */
8013
8014   gfc_resolve (code->ext.ns);
8015 }
8016
8017
8018 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
8019    DO code nodes.  */
8020
8021 static void resolve_code (gfc_code *, gfc_namespace *);
8022
8023 void
8024 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
8025 {
8026   gfc_try t;
8027
8028   for (; b; b = b->block)
8029     {
8030       t = gfc_resolve_expr (b->expr1);
8031       if (gfc_resolve_expr (b->expr2) == FAILURE)
8032         t = FAILURE;
8033
8034       switch (b->op)
8035         {
8036         case EXEC_IF:
8037           if (t == SUCCESS && b->expr1 != NULL
8038               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
8039             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8040                        &b->expr1->where);
8041           break;
8042
8043         case EXEC_WHERE:
8044           if (t == SUCCESS
8045               && b->expr1 != NULL
8046               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
8047             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
8048                        &b->expr1->where);
8049           break;
8050
8051         case EXEC_GOTO:
8052           resolve_branch (b->label1, b);
8053           break;
8054
8055         case EXEC_BLOCK:
8056           resolve_block_construct (b);
8057           break;
8058
8059         case EXEC_SELECT:
8060         case EXEC_SELECT_TYPE:
8061         case EXEC_FORALL:
8062         case EXEC_DO:
8063         case EXEC_DO_WHILE:
8064         case EXEC_CRITICAL:
8065         case EXEC_READ:
8066         case EXEC_WRITE:
8067         case EXEC_IOLENGTH:
8068         case EXEC_WAIT:
8069           break;
8070
8071         case EXEC_OMP_ATOMIC:
8072         case EXEC_OMP_CRITICAL:
8073         case EXEC_OMP_DO:
8074         case EXEC_OMP_MASTER:
8075         case EXEC_OMP_ORDERED:
8076         case EXEC_OMP_PARALLEL:
8077         case EXEC_OMP_PARALLEL_DO:
8078         case EXEC_OMP_PARALLEL_SECTIONS:
8079         case EXEC_OMP_PARALLEL_WORKSHARE:
8080         case EXEC_OMP_SECTIONS:
8081         case EXEC_OMP_SINGLE:
8082         case EXEC_OMP_TASK:
8083         case EXEC_OMP_TASKWAIT:
8084         case EXEC_OMP_WORKSHARE:
8085           break;
8086
8087         default:
8088           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
8089         }
8090
8091       resolve_code (b->next, ns);
8092     }
8093 }
8094
8095
8096 /* Does everything to resolve an ordinary assignment.  Returns true
8097    if this is an interface assignment.  */
8098 static bool
8099 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
8100 {
8101   bool rval = false;
8102   gfc_expr *lhs;
8103   gfc_expr *rhs;
8104   int llen = 0;
8105   int rlen = 0;
8106   int n;
8107   gfc_ref *ref;
8108
8109   if (gfc_extend_assign (code, ns) == SUCCESS)
8110     {
8111       gfc_expr** rhsptr;
8112
8113       if (code->op == EXEC_ASSIGN_CALL)
8114         {
8115           lhs = code->ext.actual->expr;
8116           rhsptr = &code->ext.actual->next->expr;
8117         }
8118       else
8119         {
8120           gfc_actual_arglist* args;
8121           gfc_typebound_proc* tbp;
8122
8123           gcc_assert (code->op == EXEC_COMPCALL);
8124
8125           args = code->expr1->value.compcall.actual;
8126           lhs = args->expr;
8127           rhsptr = &args->next->expr;
8128
8129           tbp = code->expr1->value.compcall.tbp;
8130           gcc_assert (!tbp->is_generic);
8131         }
8132
8133       /* Make a temporary rhs when there is a default initializer
8134          and rhs is the same symbol as the lhs.  */
8135       if ((*rhsptr)->expr_type == EXPR_VARIABLE
8136             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
8137             && has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
8138             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
8139         *rhsptr = gfc_get_parentheses (*rhsptr);
8140
8141       return true;
8142     }
8143
8144   lhs = code->expr1;
8145   rhs = code->expr2;
8146
8147   if (rhs->is_boz
8148       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
8149                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
8150                          &code->loc) == FAILURE)
8151     return false;
8152
8153   /* Handle the case of a BOZ literal on the RHS.  */
8154   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
8155     {
8156       int rc;
8157       if (gfc_option.warn_surprising)
8158         gfc_warning ("BOZ literal at %L is bitwise transferred "
8159                      "non-integer symbol '%s'", &code->loc,
8160                      lhs->symtree->n.sym->name);
8161
8162       if (!gfc_convert_boz (rhs, &lhs->ts))
8163         return false;
8164       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
8165         {
8166           if (rc == ARITH_UNDERFLOW)
8167             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
8168                        ". This check can be disabled with the option "
8169                        "-fno-range-check", &rhs->where);
8170           else if (rc == ARITH_OVERFLOW)
8171             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
8172                        ". This check can be disabled with the option "
8173                        "-fno-range-check", &rhs->where);
8174           else if (rc == ARITH_NAN)
8175             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
8176                        ". This check can be disabled with the option "
8177                        "-fno-range-check", &rhs->where);
8178           return false;
8179         }
8180     }
8181
8182
8183   if (lhs->ts.type == BT_CHARACTER
8184         && gfc_option.warn_character_truncation)
8185     {
8186       if (lhs->ts.u.cl != NULL
8187             && lhs->ts.u.cl->length != NULL
8188             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8189         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
8190
8191       if (rhs->expr_type == EXPR_CONSTANT)
8192         rlen = rhs->value.character.length;
8193
8194       else if (rhs->ts.u.cl != NULL
8195                  && rhs->ts.u.cl->length != NULL
8196                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8197         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
8198
8199       if (rlen && llen && rlen > llen)
8200         gfc_warning_now ("CHARACTER expression will be truncated "
8201                          "in assignment (%d/%d) at %L",
8202                          llen, rlen, &code->loc);
8203     }
8204
8205   /* Ensure that a vector index expression for the lvalue is evaluated
8206      to a temporary if the lvalue symbol is referenced in it.  */
8207   if (lhs->rank)
8208     {
8209       for (ref = lhs->ref; ref; ref= ref->next)
8210         if (ref->type == REF_ARRAY)
8211           {
8212             for (n = 0; n < ref->u.ar.dimen; n++)
8213               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
8214                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
8215                                            ref->u.ar.start[n]))
8216                 ref->u.ar.start[n]
8217                         = gfc_get_parentheses (ref->u.ar.start[n]);
8218           }
8219     }
8220
8221   if (gfc_pure (NULL))
8222     {
8223       if (gfc_impure_variable (lhs->symtree->n.sym))
8224         {
8225           gfc_error ("Cannot assign to variable '%s' in PURE "
8226                      "procedure at %L",
8227                       lhs->symtree->n.sym->name,
8228                       &lhs->where);
8229           return rval;
8230         }
8231
8232       if (lhs->ts.type == BT_DERIVED
8233             && lhs->expr_type == EXPR_VARIABLE
8234             && lhs->ts.u.derived->attr.pointer_comp
8235             && rhs->expr_type == EXPR_VARIABLE
8236             && (gfc_impure_variable (rhs->symtree->n.sym)
8237                 || gfc_is_coindexed (rhs)))
8238         {
8239           /* F2008, C1283.  */
8240           if (gfc_is_coindexed (rhs))
8241             gfc_error ("Coindexed expression at %L is assigned to "
8242                         "a derived type variable with a POINTER "
8243                         "component in a PURE procedure",
8244                         &rhs->where);
8245           else
8246             gfc_error ("The impure variable at %L is assigned to "
8247                         "a derived type variable with a POINTER "
8248                         "component in a PURE procedure (12.6)",
8249                         &rhs->where);
8250           return rval;
8251         }
8252
8253       /* Fortran 2008, C1283.  */
8254       if (gfc_is_coindexed (lhs))
8255         {
8256           gfc_error ("Assignment to coindexed variable at %L in a PURE "
8257                      "procedure", &rhs->where);
8258           return rval;
8259         }
8260     }
8261
8262   /* F03:7.4.1.2.  */
8263   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
8264      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
8265   if (lhs->ts.type == BT_CLASS)
8266     {
8267       gfc_error ("Variable must not be polymorphic in assignment at %L",
8268                  &lhs->where);
8269       return false;
8270     }
8271
8272   /* F2008, Section 7.2.1.2.  */
8273   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
8274     {
8275       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
8276                  "component in assignment at %L", &lhs->where);
8277       return false;
8278     }
8279
8280   gfc_check_assign (lhs, rhs, 1);
8281   return false;
8282 }
8283
8284
8285 /* Given a block of code, recursively resolve everything pointed to by this
8286    code block.  */
8287
8288 static void
8289 resolve_code (gfc_code *code, gfc_namespace *ns)
8290 {
8291   int omp_workshare_save;
8292   int forall_save;
8293   code_stack frame;
8294   gfc_try t;
8295
8296   frame.prev = cs_base;
8297   frame.head = code;
8298   cs_base = &frame;
8299
8300   find_reachable_labels (code);
8301
8302   for (; code; code = code->next)
8303     {
8304       frame.current = code;
8305       forall_save = forall_flag;
8306
8307       if (code->op == EXEC_FORALL)
8308         {
8309           forall_flag = 1;
8310           gfc_resolve_forall (code, ns, forall_save);
8311           forall_flag = 2;
8312         }
8313       else if (code->block)
8314         {
8315           omp_workshare_save = -1;
8316           switch (code->op)
8317             {
8318             case EXEC_OMP_PARALLEL_WORKSHARE:
8319               omp_workshare_save = omp_workshare_flag;
8320               omp_workshare_flag = 1;
8321               gfc_resolve_omp_parallel_blocks (code, ns);
8322               break;
8323             case EXEC_OMP_PARALLEL:
8324             case EXEC_OMP_PARALLEL_DO:
8325             case EXEC_OMP_PARALLEL_SECTIONS:
8326             case EXEC_OMP_TASK:
8327               omp_workshare_save = omp_workshare_flag;
8328               omp_workshare_flag = 0;
8329               gfc_resolve_omp_parallel_blocks (code, ns);
8330               break;
8331             case EXEC_OMP_DO:
8332               gfc_resolve_omp_do_blocks (code, ns);
8333               break;
8334             case EXEC_SELECT_TYPE:
8335               gfc_current_ns = code->ext.ns;
8336               gfc_resolve_blocks (code->block, gfc_current_ns);
8337               gfc_current_ns = ns;
8338               break;
8339             case EXEC_OMP_WORKSHARE:
8340               omp_workshare_save = omp_workshare_flag;
8341               omp_workshare_flag = 1;
8342               /* FALLTHROUGH */
8343             default:
8344               gfc_resolve_blocks (code->block, ns);
8345               break;
8346             }
8347
8348           if (omp_workshare_save != -1)
8349             omp_workshare_flag = omp_workshare_save;
8350         }
8351
8352       t = SUCCESS;
8353       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
8354         t = gfc_resolve_expr (code->expr1);
8355       forall_flag = forall_save;
8356
8357       if (gfc_resolve_expr (code->expr2) == FAILURE)
8358         t = FAILURE;
8359
8360       if (code->op == EXEC_ALLOCATE
8361           && gfc_resolve_expr (code->expr3) == FAILURE)
8362         t = FAILURE;
8363
8364       switch (code->op)
8365         {
8366         case EXEC_NOP:
8367         case EXEC_END_BLOCK:
8368         case EXEC_CYCLE:
8369         case EXEC_PAUSE:
8370         case EXEC_STOP:
8371         case EXEC_ERROR_STOP:
8372         case EXEC_EXIT:
8373         case EXEC_CONTINUE:
8374         case EXEC_DT_END:
8375         case EXEC_ASSIGN_CALL:
8376         case EXEC_CRITICAL:
8377           break;
8378
8379         case EXEC_SYNC_ALL:
8380         case EXEC_SYNC_IMAGES:
8381         case EXEC_SYNC_MEMORY:
8382           resolve_sync (code);
8383           break;
8384
8385         case EXEC_ENTRY:
8386           /* Keep track of which entry we are up to.  */
8387           current_entry_id = code->ext.entry->id;
8388           break;
8389
8390         case EXEC_WHERE:
8391           resolve_where (code, NULL);
8392           break;
8393
8394         case EXEC_GOTO:
8395           if (code->expr1 != NULL)
8396             {
8397               if (code->expr1->ts.type != BT_INTEGER)
8398                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
8399                            "INTEGER variable", &code->expr1->where);
8400               else if (code->expr1->symtree->n.sym->attr.assign != 1)
8401                 gfc_error ("Variable '%s' has not been assigned a target "
8402                            "label at %L", code->expr1->symtree->n.sym->name,
8403                            &code->expr1->where);
8404             }
8405           else
8406             resolve_branch (code->label1, code);
8407           break;
8408
8409         case EXEC_RETURN:
8410           if (code->expr1 != NULL
8411                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
8412             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
8413                        "INTEGER return specifier", &code->expr1->where);
8414           break;
8415
8416         case EXEC_INIT_ASSIGN:
8417         case EXEC_END_PROCEDURE:
8418           break;
8419
8420         case EXEC_ASSIGN:
8421           if (t == FAILURE)
8422             break;
8423
8424           if (resolve_ordinary_assign (code, ns))
8425             {
8426               if (code->op == EXEC_COMPCALL)
8427                 goto compcall;
8428               else
8429                 goto call;
8430             }
8431           break;
8432
8433         case EXEC_LABEL_ASSIGN:
8434           if (code->label1->defined == ST_LABEL_UNKNOWN)
8435             gfc_error ("Label %d referenced at %L is never defined",
8436                        code->label1->value, &code->label1->where);
8437           if (t == SUCCESS
8438               && (code->expr1->expr_type != EXPR_VARIABLE
8439                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
8440                   || code->expr1->symtree->n.sym->ts.kind
8441                      != gfc_default_integer_kind
8442                   || code->expr1->symtree->n.sym->as != NULL))
8443             gfc_error ("ASSIGN statement at %L requires a scalar "
8444                        "default INTEGER variable", &code->expr1->where);
8445           break;
8446
8447         case EXEC_POINTER_ASSIGN:
8448           if (t == FAILURE)
8449             break;
8450
8451           gfc_check_pointer_assign (code->expr1, code->expr2);
8452           break;
8453
8454         case EXEC_ARITHMETIC_IF:
8455           if (t == SUCCESS
8456               && code->expr1->ts.type != BT_INTEGER
8457               && code->expr1->ts.type != BT_REAL)
8458             gfc_error ("Arithmetic IF statement at %L requires a numeric "
8459                        "expression", &code->expr1->where);
8460
8461           resolve_branch (code->label1, code);
8462           resolve_branch (code->label2, code);
8463           resolve_branch (code->label3, code);
8464           break;
8465
8466         case EXEC_IF:
8467           if (t == SUCCESS && code->expr1 != NULL
8468               && (code->expr1->ts.type != BT_LOGICAL
8469                   || code->expr1->rank != 0))
8470             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8471                        &code->expr1->where);
8472           break;
8473
8474         case EXEC_CALL:
8475         call:
8476           resolve_call (code);
8477           break;
8478
8479         case EXEC_COMPCALL:
8480         compcall:
8481           resolve_typebound_subroutine (code);
8482           break;
8483
8484         case EXEC_CALL_PPC:
8485           resolve_ppc_call (code);
8486           break;
8487
8488         case EXEC_SELECT:
8489           /* Select is complicated. Also, a SELECT construct could be
8490              a transformed computed GOTO.  */
8491           resolve_select (code);
8492           break;
8493
8494         case EXEC_SELECT_TYPE:
8495           resolve_select_type (code);
8496           break;
8497
8498         case EXEC_BLOCK:
8499           gfc_resolve (code->ext.ns);
8500           break;
8501
8502         case EXEC_DO:
8503           if (code->ext.iterator != NULL)
8504             {
8505               gfc_iterator *iter = code->ext.iterator;
8506               if (gfc_resolve_iterator (iter, true) != FAILURE)
8507                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
8508             }
8509           break;
8510
8511         case EXEC_DO_WHILE:
8512           if (code->expr1 == NULL)
8513             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
8514           if (t == SUCCESS
8515               && (code->expr1->rank != 0
8516                   || code->expr1->ts.type != BT_LOGICAL))
8517             gfc_error ("Exit condition of DO WHILE loop at %L must be "
8518                        "a scalar LOGICAL expression", &code->expr1->where);
8519           break;
8520
8521         case EXEC_ALLOCATE:
8522           if (t == SUCCESS)
8523             resolve_allocate_deallocate (code, "ALLOCATE");
8524
8525           break;
8526
8527         case EXEC_DEALLOCATE:
8528           if (t == SUCCESS)
8529             resolve_allocate_deallocate (code, "DEALLOCATE");
8530
8531           break;
8532
8533         case EXEC_OPEN:
8534           if (gfc_resolve_open (code->ext.open) == FAILURE)
8535             break;
8536
8537           resolve_branch (code->ext.open->err, code);
8538           break;
8539
8540         case EXEC_CLOSE:
8541           if (gfc_resolve_close (code->ext.close) == FAILURE)
8542             break;
8543
8544           resolve_branch (code->ext.close->err, code);
8545           break;
8546
8547         case EXEC_BACKSPACE:
8548         case EXEC_ENDFILE:
8549         case EXEC_REWIND:
8550         case EXEC_FLUSH:
8551           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
8552             break;
8553
8554           resolve_branch (code->ext.filepos->err, code);
8555           break;
8556
8557         case EXEC_INQUIRE:
8558           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
8559               break;
8560
8561           resolve_branch (code->ext.inquire->err, code);
8562           break;
8563
8564         case EXEC_IOLENGTH:
8565           gcc_assert (code->ext.inquire != NULL);
8566           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
8567             break;
8568
8569           resolve_branch (code->ext.inquire->err, code);
8570           break;
8571
8572         case EXEC_WAIT:
8573           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
8574             break;
8575
8576           resolve_branch (code->ext.wait->err, code);
8577           resolve_branch (code->ext.wait->end, code);
8578           resolve_branch (code->ext.wait->eor, code);
8579           break;
8580
8581         case EXEC_READ:
8582         case EXEC_WRITE:
8583           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
8584             break;
8585
8586           resolve_branch (code->ext.dt->err, code);
8587           resolve_branch (code->ext.dt->end, code);
8588           resolve_branch (code->ext.dt->eor, code);
8589           break;
8590
8591         case EXEC_TRANSFER:
8592           resolve_transfer (code);
8593           break;
8594
8595         case EXEC_FORALL:
8596           resolve_forall_iterators (code->ext.forall_iterator);
8597
8598           if (code->expr1 != NULL && code->expr1->ts.type != BT_LOGICAL)
8599             gfc_error ("FORALL mask clause at %L requires a LOGICAL "
8600                        "expression", &code->expr1->where);
8601           break;
8602
8603         case EXEC_OMP_ATOMIC:
8604         case EXEC_OMP_BARRIER:
8605         case EXEC_OMP_CRITICAL:
8606         case EXEC_OMP_FLUSH:
8607         case EXEC_OMP_DO:
8608         case EXEC_OMP_MASTER:
8609         case EXEC_OMP_ORDERED:
8610         case EXEC_OMP_SECTIONS:
8611         case EXEC_OMP_SINGLE:
8612         case EXEC_OMP_TASKWAIT:
8613         case EXEC_OMP_WORKSHARE:
8614           gfc_resolve_omp_directive (code, ns);
8615           break;
8616
8617         case EXEC_OMP_PARALLEL:
8618         case EXEC_OMP_PARALLEL_DO:
8619         case EXEC_OMP_PARALLEL_SECTIONS:
8620         case EXEC_OMP_PARALLEL_WORKSHARE:
8621         case EXEC_OMP_TASK:
8622           omp_workshare_save = omp_workshare_flag;
8623           omp_workshare_flag = 0;
8624           gfc_resolve_omp_directive (code, ns);
8625           omp_workshare_flag = omp_workshare_save;
8626           break;
8627
8628         default:
8629           gfc_internal_error ("resolve_code(): Bad statement code");
8630         }
8631     }
8632
8633   cs_base = frame.prev;
8634 }
8635
8636
8637 /* Resolve initial values and make sure they are compatible with
8638    the variable.  */
8639
8640 static void
8641 resolve_values (gfc_symbol *sym)
8642 {
8643   if (sym->value == NULL)
8644     return;
8645
8646   if (gfc_resolve_expr (sym->value) == FAILURE)
8647     return;
8648
8649   gfc_check_assign_symbol (sym, sym->value);
8650 }
8651
8652
8653 /* Verify the binding labels for common blocks that are BIND(C).  The label
8654    for a BIND(C) common block must be identical in all scoping units in which
8655    the common block is declared.  Further, the binding label can not collide
8656    with any other global entity in the program.  */
8657
8658 static void
8659 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
8660 {
8661   if (comm_block_tree->n.common->is_bind_c == 1)
8662     {
8663       gfc_gsymbol *binding_label_gsym;
8664       gfc_gsymbol *comm_name_gsym;
8665
8666       /* See if a global symbol exists by the common block's name.  It may
8667          be NULL if the common block is use-associated.  */
8668       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
8669                                          comm_block_tree->n.common->name);
8670       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
8671         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
8672                    "with the global entity '%s' at %L",
8673                    comm_block_tree->n.common->binding_label,
8674                    comm_block_tree->n.common->name,
8675                    &(comm_block_tree->n.common->where),
8676                    comm_name_gsym->name, &(comm_name_gsym->where));
8677       else if (comm_name_gsym != NULL
8678                && strcmp (comm_name_gsym->name,
8679                           comm_block_tree->n.common->name) == 0)
8680         {
8681           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
8682              as expected.  */
8683           if (comm_name_gsym->binding_label == NULL)
8684             /* No binding label for common block stored yet; save this one.  */
8685             comm_name_gsym->binding_label =
8686               comm_block_tree->n.common->binding_label;
8687           else
8688             if (strcmp (comm_name_gsym->binding_label,
8689                         comm_block_tree->n.common->binding_label) != 0)
8690               {
8691                 /* Common block names match but binding labels do not.  */
8692                 gfc_error ("Binding label '%s' for common block '%s' at %L "
8693                            "does not match the binding label '%s' for common "
8694                            "block '%s' at %L",
8695                            comm_block_tree->n.common->binding_label,
8696                            comm_block_tree->n.common->name,
8697                            &(comm_block_tree->n.common->where),
8698                            comm_name_gsym->binding_label,
8699                            comm_name_gsym->name,
8700                            &(comm_name_gsym->where));
8701                 return;
8702               }
8703         }
8704
8705       /* There is no binding label (NAME="") so we have nothing further to
8706          check and nothing to add as a global symbol for the label.  */
8707       if (comm_block_tree->n.common->binding_label[0] == '\0' )
8708         return;
8709       
8710       binding_label_gsym =
8711         gfc_find_gsymbol (gfc_gsym_root,
8712                           comm_block_tree->n.common->binding_label);
8713       if (binding_label_gsym == NULL)
8714         {
8715           /* Need to make a global symbol for the binding label to prevent
8716              it from colliding with another.  */
8717           binding_label_gsym =
8718             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
8719           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
8720           binding_label_gsym->type = GSYM_COMMON;
8721         }
8722       else
8723         {
8724           /* If comm_name_gsym is NULL, the name common block is use
8725              associated and the name could be colliding.  */
8726           if (binding_label_gsym->type != GSYM_COMMON)
8727             gfc_error ("Binding label '%s' for common block '%s' at %L "
8728                        "collides with the global entity '%s' at %L",
8729                        comm_block_tree->n.common->binding_label,
8730                        comm_block_tree->n.common->name,
8731                        &(comm_block_tree->n.common->where),
8732                        binding_label_gsym->name,
8733                        &(binding_label_gsym->where));
8734           else if (comm_name_gsym != NULL
8735                    && (strcmp (binding_label_gsym->name,
8736                                comm_name_gsym->binding_label) != 0)
8737                    && (strcmp (binding_label_gsym->sym_name,
8738                                comm_name_gsym->name) != 0))
8739             gfc_error ("Binding label '%s' for common block '%s' at %L "
8740                        "collides with global entity '%s' at %L",
8741                        binding_label_gsym->name, binding_label_gsym->sym_name,
8742                        &(comm_block_tree->n.common->where),
8743                        comm_name_gsym->name, &(comm_name_gsym->where));
8744         }
8745     }
8746   
8747   return;
8748 }
8749
8750
8751 /* Verify any BIND(C) derived types in the namespace so we can report errors
8752    for them once, rather than for each variable declared of that type.  */
8753
8754 static void
8755 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
8756 {
8757   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
8758       && derived_sym->attr.is_bind_c == 1)
8759     verify_bind_c_derived_type (derived_sym);
8760   
8761   return;
8762 }
8763
8764
8765 /* Verify that any binding labels used in a given namespace do not collide 
8766    with the names or binding labels of any global symbols.  */
8767
8768 static void
8769 gfc_verify_binding_labels (gfc_symbol *sym)
8770 {
8771   int has_error = 0;
8772   
8773   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
8774       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
8775     {
8776       gfc_gsymbol *bind_c_sym;
8777
8778       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
8779       if (bind_c_sym != NULL 
8780           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
8781         {
8782           if (sym->attr.if_source == IFSRC_DECL 
8783               && (bind_c_sym->type != GSYM_SUBROUTINE 
8784                   && bind_c_sym->type != GSYM_FUNCTION) 
8785               && ((sym->attr.contained == 1 
8786                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
8787                   || (sym->attr.use_assoc == 1 
8788                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
8789             {
8790               /* Make sure global procedures don't collide with anything.  */
8791               gfc_error ("Binding label '%s' at %L collides with the global "
8792                          "entity '%s' at %L", sym->binding_label,
8793                          &(sym->declared_at), bind_c_sym->name,
8794                          &(bind_c_sym->where));
8795               has_error = 1;
8796             }
8797           else if (sym->attr.contained == 0 
8798                    && (sym->attr.if_source == IFSRC_IFBODY 
8799                        && sym->attr.flavor == FL_PROCEDURE) 
8800                    && (bind_c_sym->sym_name != NULL 
8801                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
8802             {
8803               /* Make sure procedures in interface bodies don't collide.  */
8804               gfc_error ("Binding label '%s' in interface body at %L collides "
8805                          "with the global entity '%s' at %L",
8806                          sym->binding_label,
8807                          &(sym->declared_at), bind_c_sym->name,
8808                          &(bind_c_sym->where));
8809               has_error = 1;
8810             }
8811           else if (sym->attr.contained == 0 
8812                    && sym->attr.if_source == IFSRC_UNKNOWN)
8813             if ((sym->attr.use_assoc && bind_c_sym->mod_name
8814                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
8815                 || sym->attr.use_assoc == 0)
8816               {
8817                 gfc_error ("Binding label '%s' at %L collides with global "
8818                            "entity '%s' at %L", sym->binding_label,
8819                            &(sym->declared_at), bind_c_sym->name,
8820                            &(bind_c_sym->where));
8821                 has_error = 1;
8822               }
8823
8824           if (has_error != 0)
8825             /* Clear the binding label to prevent checking multiple times.  */
8826             sym->binding_label[0] = '\0';
8827         }
8828       else if (bind_c_sym == NULL)
8829         {
8830           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
8831           bind_c_sym->where = sym->declared_at;
8832           bind_c_sym->sym_name = sym->name;
8833
8834           if (sym->attr.use_assoc == 1)
8835             bind_c_sym->mod_name = sym->module;
8836           else
8837             if (sym->ns->proc_name != NULL)
8838               bind_c_sym->mod_name = sym->ns->proc_name->name;
8839
8840           if (sym->attr.contained == 0)
8841             {
8842               if (sym->attr.subroutine)
8843                 bind_c_sym->type = GSYM_SUBROUTINE;
8844               else if (sym->attr.function)
8845                 bind_c_sym->type = GSYM_FUNCTION;
8846             }
8847         }
8848     }
8849   return;
8850 }
8851
8852
8853 /* Resolve an index expression.  */
8854
8855 static gfc_try
8856 resolve_index_expr (gfc_expr *e)
8857 {
8858   if (gfc_resolve_expr (e) == FAILURE)
8859     return FAILURE;
8860
8861   if (gfc_simplify_expr (e, 0) == FAILURE)
8862     return FAILURE;
8863
8864   if (gfc_specification_expr (e) == FAILURE)
8865     return FAILURE;
8866
8867   return SUCCESS;
8868 }
8869
8870 /* Resolve a charlen structure.  */
8871
8872 static gfc_try
8873 resolve_charlen (gfc_charlen *cl)
8874 {
8875   int i, k;
8876
8877   if (cl->resolved)
8878     return SUCCESS;
8879
8880   cl->resolved = 1;
8881
8882   specification_expr = 1;
8883
8884   if (resolve_index_expr (cl->length) == FAILURE)
8885     {
8886       specification_expr = 0;
8887       return FAILURE;
8888     }
8889
8890   /* "If the character length parameter value evaluates to a negative
8891      value, the length of character entities declared is zero."  */
8892   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
8893     {
8894       if (gfc_option.warn_surprising)
8895         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
8896                          " the length has been set to zero",
8897                          &cl->length->where, i);
8898       gfc_replace_expr (cl->length, gfc_int_expr (0));
8899     }
8900
8901   /* Check that the character length is not too large.  */
8902   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
8903   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
8904       && cl->length->ts.type == BT_INTEGER
8905       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
8906     {
8907       gfc_error ("String length at %L is too large", &cl->length->where);
8908       return FAILURE;
8909     }
8910
8911   return SUCCESS;
8912 }
8913
8914
8915 /* Test for non-constant shape arrays.  */
8916
8917 static bool
8918 is_non_constant_shape_array (gfc_symbol *sym)
8919 {
8920   gfc_expr *e;
8921   int i;
8922   bool not_constant;
8923
8924   not_constant = false;
8925   if (sym->as != NULL)
8926     {
8927       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
8928          has not been simplified; parameter array references.  Do the
8929          simplification now.  */
8930       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
8931         {
8932           e = sym->as->lower[i];
8933           if (e && (resolve_index_expr (e) == FAILURE
8934                     || !gfc_is_constant_expr (e)))
8935             not_constant = true;
8936           e = sym->as->upper[i];
8937           if (e && (resolve_index_expr (e) == FAILURE
8938                     || !gfc_is_constant_expr (e)))
8939             not_constant = true;
8940         }
8941     }
8942   return not_constant;
8943 }
8944
8945 /* Given a symbol and an initialization expression, add code to initialize
8946    the symbol to the function entry.  */
8947 static void
8948 build_init_assign (gfc_symbol *sym, gfc_expr *init)
8949 {
8950   gfc_expr *lval;
8951   gfc_code *init_st;
8952   gfc_namespace *ns = sym->ns;
8953
8954   /* Search for the function namespace if this is a contained
8955      function without an explicit result.  */
8956   if (sym->attr.function && sym == sym->result
8957       && sym->name != sym->ns->proc_name->name)
8958     {
8959       ns = ns->contained;
8960       for (;ns; ns = ns->sibling)
8961         if (strcmp (ns->proc_name->name, sym->name) == 0)
8962           break;
8963     }
8964
8965   if (ns == NULL)
8966     {
8967       gfc_free_expr (init);
8968       return;
8969     }
8970
8971   /* Build an l-value expression for the result.  */
8972   lval = gfc_lval_expr_from_sym (sym);
8973
8974   /* Add the code at scope entry.  */
8975   init_st = gfc_get_code ();
8976   init_st->next = ns->code;
8977   ns->code = init_st;
8978
8979   /* Assign the default initializer to the l-value.  */
8980   init_st->loc = sym->declared_at;
8981   init_st->op = EXEC_INIT_ASSIGN;
8982   init_st->expr1 = lval;
8983   init_st->expr2 = init;
8984 }
8985
8986 /* Assign the default initializer to a derived type variable or result.  */
8987
8988 static void
8989 apply_default_init (gfc_symbol *sym)
8990 {
8991   gfc_expr *init = NULL;
8992
8993   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
8994     return;
8995
8996   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
8997     init = gfc_default_initializer (&sym->ts);
8998
8999   if (init == NULL)
9000     return;
9001
9002   build_init_assign (sym, init);
9003 }
9004
9005 /* Build an initializer for a local integer, real, complex, logical, or
9006    character variable, based on the command line flags finit-local-zero,
9007    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
9008    null if the symbol should not have a default initialization.  */
9009 static gfc_expr *
9010 build_default_init_expr (gfc_symbol *sym)
9011 {
9012   int char_len;
9013   gfc_expr *init_expr;
9014   int i;
9015
9016   /* These symbols should never have a default initialization.  */
9017   if ((sym->attr.dimension && !gfc_is_compile_time_shape (sym->as))
9018       || sym->attr.external
9019       || sym->attr.dummy
9020       || sym->attr.pointer
9021       || sym->attr.in_equivalence
9022       || sym->attr.in_common
9023       || sym->attr.data
9024       || sym->module
9025       || sym->attr.cray_pointee
9026       || sym->attr.cray_pointer)
9027     return NULL;
9028
9029   /* Now we'll try to build an initializer expression.  */
9030   init_expr = gfc_get_expr ();
9031   init_expr->expr_type = EXPR_CONSTANT;
9032   init_expr->ts.type = sym->ts.type;
9033   init_expr->ts.kind = sym->ts.kind;
9034   init_expr->where = sym->declared_at;
9035   
9036   /* We will only initialize integers, reals, complex, logicals, and
9037      characters, and only if the corresponding command-line flags
9038      were set.  Otherwise, we free init_expr and return null.  */
9039   switch (sym->ts.type)
9040     {    
9041     case BT_INTEGER:
9042       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
9043         mpz_init_set_si (init_expr->value.integer, 
9044                          gfc_option.flag_init_integer_value);
9045       else
9046         {
9047           gfc_free_expr (init_expr);
9048           init_expr = NULL;
9049         }
9050       break;
9051
9052     case BT_REAL:
9053       mpfr_init (init_expr->value.real);
9054       switch (gfc_option.flag_init_real)
9055         {
9056         case GFC_INIT_REAL_SNAN:
9057           init_expr->is_snan = 1;
9058           /* Fall through.  */
9059         case GFC_INIT_REAL_NAN:
9060           mpfr_set_nan (init_expr->value.real);
9061           break;
9062
9063         case GFC_INIT_REAL_INF:
9064           mpfr_set_inf (init_expr->value.real, 1);
9065           break;
9066
9067         case GFC_INIT_REAL_NEG_INF:
9068           mpfr_set_inf (init_expr->value.real, -1);
9069           break;
9070
9071         case GFC_INIT_REAL_ZERO:
9072           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
9073           break;
9074
9075         default:
9076           gfc_free_expr (init_expr);
9077           init_expr = NULL;
9078           break;
9079         }
9080       break;
9081           
9082     case BT_COMPLEX:
9083       mpc_init2 (init_expr->value.complex, mpfr_get_default_prec());
9084       switch (gfc_option.flag_init_real)
9085         {
9086         case GFC_INIT_REAL_SNAN:
9087           init_expr->is_snan = 1;
9088           /* Fall through.  */
9089         case GFC_INIT_REAL_NAN:
9090           mpfr_set_nan (mpc_realref (init_expr->value.complex));
9091           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
9092           break;
9093
9094         case GFC_INIT_REAL_INF:
9095           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
9096           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
9097           break;
9098
9099         case GFC_INIT_REAL_NEG_INF:
9100           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
9101           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
9102           break;
9103
9104         case GFC_INIT_REAL_ZERO:
9105           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
9106           break;
9107
9108         default:
9109           gfc_free_expr (init_expr);
9110           init_expr = NULL;
9111           break;
9112         }
9113       break;
9114           
9115     case BT_LOGICAL:
9116       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
9117         init_expr->value.logical = 0;
9118       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
9119         init_expr->value.logical = 1;
9120       else
9121         {
9122           gfc_free_expr (init_expr);
9123           init_expr = NULL;
9124         }
9125       break;
9126           
9127     case BT_CHARACTER:
9128       /* For characters, the length must be constant in order to 
9129          create a default initializer.  */
9130       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
9131           && sym->ts.u.cl->length
9132           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9133         {
9134           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
9135           init_expr->value.character.length = char_len;
9136           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
9137           for (i = 0; i < char_len; i++)
9138             init_expr->value.character.string[i]
9139               = (unsigned char) gfc_option.flag_init_character_value;
9140         }
9141       else
9142         {
9143           gfc_free_expr (init_expr);
9144           init_expr = NULL;
9145         }
9146       break;
9147           
9148     default:
9149      gfc_free_expr (init_expr);
9150      init_expr = NULL;
9151     }
9152   return init_expr;
9153 }
9154
9155 /* Add an initialization expression to a local variable.  */
9156 static void
9157 apply_default_init_local (gfc_symbol *sym)
9158 {
9159   gfc_expr *init = NULL;
9160
9161   /* The symbol should be a variable or a function return value.  */
9162   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9163       || (sym->attr.function && sym->result != sym))
9164     return;
9165
9166   /* Try to build the initializer expression.  If we can't initialize
9167      this symbol, then init will be NULL.  */
9168   init = build_default_init_expr (sym);
9169   if (init == NULL)
9170     return;
9171
9172   /* For saved variables, we don't want to add an initializer at 
9173      function entry, so we just add a static initializer.  */
9174   if (sym->attr.save || sym->ns->save_all 
9175       || gfc_option.flag_max_stack_var_size == 0)
9176     {
9177       /* Don't clobber an existing initializer!  */
9178       gcc_assert (sym->value == NULL);
9179       sym->value = init;
9180       return;
9181     }
9182
9183   build_init_assign (sym, init);
9184 }
9185
9186 /* Resolution of common features of flavors variable and procedure.  */
9187
9188 static gfc_try
9189 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
9190 {
9191   /* Constraints on deferred shape variable.  */
9192   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
9193     {
9194       if (sym->attr.allocatable)
9195         {
9196           if (sym->attr.dimension)
9197             {
9198               gfc_error ("Allocatable array '%s' at %L must have "
9199                          "a deferred shape", sym->name, &sym->declared_at);
9200               return FAILURE;
9201             }
9202           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
9203                                    "may not be ALLOCATABLE", sym->name,
9204                                    &sym->declared_at) == FAILURE)
9205             return FAILURE;
9206         }
9207
9208       if (sym->attr.pointer && sym->attr.dimension)
9209         {
9210           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
9211                      sym->name, &sym->declared_at);
9212           return FAILURE;
9213         }
9214
9215     }
9216   else
9217     {
9218       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
9219           && !sym->attr.dummy && sym->ts.type != BT_CLASS)
9220         {
9221           gfc_error ("Array '%s' at %L cannot have a deferred shape",
9222                      sym->name, &sym->declared_at);
9223           return FAILURE;
9224          }
9225     }
9226   return SUCCESS;
9227 }
9228
9229
9230 /* Additional checks for symbols with flavor variable and derived
9231    type.  To be called from resolve_fl_variable.  */
9232
9233 static gfc_try
9234 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
9235 {
9236   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
9237
9238   /* Check to see if a derived type is blocked from being host
9239      associated by the presence of another class I symbol in the same
9240      namespace.  14.6.1.3 of the standard and the discussion on
9241      comp.lang.fortran.  */
9242   if (sym->ns != sym->ts.u.derived->ns
9243       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
9244     {
9245       gfc_symbol *s;
9246       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
9247       if (s && s->attr.flavor != FL_DERIVED)
9248         {
9249           gfc_error ("The type '%s' cannot be host associated at %L "
9250                      "because it is blocked by an incompatible object "
9251                      "of the same name declared at %L",
9252                      sym->ts.u.derived->name, &sym->declared_at,
9253                      &s->declared_at);
9254           return FAILURE;
9255         }
9256     }
9257
9258   /* 4th constraint in section 11.3: "If an object of a type for which
9259      component-initialization is specified (R429) appears in the
9260      specification-part of a module and does not have the ALLOCATABLE
9261      or POINTER attribute, the object shall have the SAVE attribute."
9262
9263      The check for initializers is performed with
9264      has_default_initializer because gfc_default_initializer generates
9265      a hidden default for allocatable components.  */
9266   if (!(sym->value || no_init_flag) && sym->ns->proc_name
9267       && sym->ns->proc_name->attr.flavor == FL_MODULE
9268       && !sym->ns->save_all && !sym->attr.save
9269       && !sym->attr.pointer && !sym->attr.allocatable
9270       && has_default_initializer (sym->ts.u.derived)
9271       && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Implied SAVE for "
9272                          "module variable '%s' at %L, needed due to "
9273                          "the default initialization", sym->name,
9274                          &sym->declared_at) == FAILURE)
9275     return FAILURE;
9276
9277   if (sym->ts.type == BT_CLASS)
9278     {
9279       /* C502.  */
9280       if (!gfc_type_is_extensible (sym->ts.u.derived->components->ts.u.derived))
9281         {
9282           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
9283                      sym->ts.u.derived->components->ts.u.derived->name,
9284                      sym->name, &sym->declared_at);
9285           return FAILURE;
9286         }
9287
9288       /* C509.  */
9289       /* Assume that use associated symbols were checked in the module ns.  */ 
9290       if (!sym->attr.class_ok && !sym->attr.use_assoc)
9291         {
9292           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
9293                      "or pointer", sym->name, &sym->declared_at);
9294           return FAILURE;
9295         }
9296     }
9297
9298   /* Assign default initializer.  */
9299   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
9300       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
9301     {
9302       sym->value = gfc_default_initializer (&sym->ts);
9303     }
9304
9305   return SUCCESS;
9306 }
9307
9308
9309 /* Resolve symbols with flavor variable.  */
9310
9311 static gfc_try
9312 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
9313 {
9314   int no_init_flag, automatic_flag;
9315   gfc_expr *e;
9316   const char *auto_save_msg;
9317
9318   auto_save_msg = "Automatic object '%s' at %L cannot have the "
9319                   "SAVE attribute";
9320
9321   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9322     return FAILURE;
9323
9324   /* Set this flag to check that variables are parameters of all entries.
9325      This check is effected by the call to gfc_resolve_expr through
9326      is_non_constant_shape_array.  */
9327   specification_expr = 1;
9328
9329   if (sym->ns->proc_name
9330       && (sym->ns->proc_name->attr.flavor == FL_MODULE
9331           || sym->ns->proc_name->attr.is_main_program)
9332       && !sym->attr.use_assoc
9333       && !sym->attr.allocatable
9334       && !sym->attr.pointer
9335       && is_non_constant_shape_array (sym))
9336     {
9337       /* The shape of a main program or module array needs to be
9338          constant.  */
9339       gfc_error ("The module or main program array '%s' at %L must "
9340                  "have constant shape", sym->name, &sym->declared_at);
9341       specification_expr = 0;
9342       return FAILURE;
9343     }
9344
9345   if (sym->ts.type == BT_CHARACTER)
9346     {
9347       /* Make sure that character string variables with assumed length are
9348          dummy arguments.  */
9349       e = sym->ts.u.cl->length;
9350       if (e == NULL && !sym->attr.dummy && !sym->attr.result)
9351         {
9352           gfc_error ("Entity with assumed character length at %L must be a "
9353                      "dummy argument or a PARAMETER", &sym->declared_at);
9354           return FAILURE;
9355         }
9356
9357       if (e && sym->attr.save && !gfc_is_constant_expr (e))
9358         {
9359           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
9360           return FAILURE;
9361         }
9362
9363       if (!gfc_is_constant_expr (e)
9364           && !(e->expr_type == EXPR_VARIABLE
9365                && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
9366           && sym->ns->proc_name
9367           && (sym->ns->proc_name->attr.flavor == FL_MODULE
9368               || sym->ns->proc_name->attr.is_main_program)
9369           && !sym->attr.use_assoc)
9370         {
9371           gfc_error ("'%s' at %L must have constant character length "
9372                      "in this context", sym->name, &sym->declared_at);
9373           return FAILURE;
9374         }
9375     }
9376
9377   if (sym->value == NULL && sym->attr.referenced)
9378     apply_default_init_local (sym); /* Try to apply a default initialization.  */
9379
9380   /* Determine if the symbol may not have an initializer.  */
9381   no_init_flag = automatic_flag = 0;
9382   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
9383       || sym->attr.intrinsic || sym->attr.result)
9384     no_init_flag = 1;
9385   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
9386            && is_non_constant_shape_array (sym))
9387     {
9388       no_init_flag = automatic_flag = 1;
9389
9390       /* Also, they must not have the SAVE attribute.
9391          SAVE_IMPLICIT is checked below.  */
9392       if (sym->attr.save == SAVE_EXPLICIT)
9393         {
9394           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
9395           return FAILURE;
9396         }
9397     }
9398
9399   /* Ensure that any initializer is simplified.  */
9400   if (sym->value)
9401     gfc_simplify_expr (sym->value, 1);
9402
9403   /* Reject illegal initializers.  */
9404   if (!sym->mark && sym->value)
9405     {
9406       if (sym->attr.allocatable)
9407         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
9408                    sym->name, &sym->declared_at);
9409       else if (sym->attr.external)
9410         gfc_error ("External '%s' at %L cannot have an initializer",
9411                    sym->name, &sym->declared_at);
9412       else if (sym->attr.dummy
9413         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
9414         gfc_error ("Dummy '%s' at %L cannot have an initializer",
9415                    sym->name, &sym->declared_at);
9416       else if (sym->attr.intrinsic)
9417         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
9418                    sym->name, &sym->declared_at);
9419       else if (sym->attr.result)
9420         gfc_error ("Function result '%s' at %L cannot have an initializer",
9421                    sym->name, &sym->declared_at);
9422       else if (automatic_flag)
9423         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
9424                    sym->name, &sym->declared_at);
9425       else
9426         goto no_init_error;
9427       return FAILURE;
9428     }
9429
9430 no_init_error:
9431   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
9432     return resolve_fl_variable_derived (sym, no_init_flag);
9433
9434   return SUCCESS;
9435 }
9436
9437
9438 /* Resolve a procedure.  */
9439
9440 static gfc_try
9441 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
9442 {
9443   gfc_formal_arglist *arg;
9444
9445   if (sym->attr.function
9446       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9447     return FAILURE;
9448
9449   if (sym->ts.type == BT_CHARACTER)
9450     {
9451       gfc_charlen *cl = sym->ts.u.cl;
9452
9453       if (cl && cl->length && gfc_is_constant_expr (cl->length)
9454              && resolve_charlen (cl) == FAILURE)
9455         return FAILURE;
9456
9457       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
9458           && sym->attr.proc == PROC_ST_FUNCTION)
9459         {
9460           gfc_error ("Character-valued statement function '%s' at %L must "
9461                      "have constant length", sym->name, &sym->declared_at);
9462           return FAILURE;
9463         }
9464     }
9465
9466   /* Ensure that derived type for are not of a private type.  Internal
9467      module procedures are excluded by 2.2.3.3 - i.e., they are not
9468      externally accessible and can access all the objects accessible in
9469      the host.  */
9470   if (!(sym->ns->parent
9471         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
9472       && gfc_check_access(sym->attr.access, sym->ns->default_access))
9473     {
9474       gfc_interface *iface;
9475
9476       for (arg = sym->formal; arg; arg = arg->next)
9477         {
9478           if (arg->sym
9479               && arg->sym->ts.type == BT_DERIVED
9480               && !arg->sym->ts.u.derived->attr.use_assoc
9481               && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9482                                     arg->sym->ts.u.derived->ns->default_access)
9483               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
9484                                  "PRIVATE type and cannot be a dummy argument"
9485                                  " of '%s', which is PUBLIC at %L",
9486                                  arg->sym->name, sym->name, &sym->declared_at)
9487                  == FAILURE)
9488             {
9489               /* Stop this message from recurring.  */
9490               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9491               return FAILURE;
9492             }
9493         }
9494
9495       /* PUBLIC interfaces may expose PRIVATE procedures that take types
9496          PRIVATE to the containing module.  */
9497       for (iface = sym->generic; iface; iface = iface->next)
9498         {
9499           for (arg = iface->sym->formal; arg; arg = arg->next)
9500             {
9501               if (arg->sym
9502                   && arg->sym->ts.type == BT_DERIVED
9503                   && !arg->sym->ts.u.derived->attr.use_assoc
9504                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9505                                         arg->sym->ts.u.derived->ns->default_access)
9506                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
9507                                      "'%s' in PUBLIC interface '%s' at %L "
9508                                      "takes dummy arguments of '%s' which is "
9509                                      "PRIVATE", iface->sym->name, sym->name,
9510                                      &iface->sym->declared_at,
9511                                      gfc_typename (&arg->sym->ts)) == FAILURE)
9512                 {
9513                   /* Stop this message from recurring.  */
9514                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9515                   return FAILURE;
9516                 }
9517              }
9518         }
9519
9520       /* PUBLIC interfaces may expose PRIVATE procedures that take types
9521          PRIVATE to the containing module.  */
9522       for (iface = sym->generic; iface; iface = iface->next)
9523         {
9524           for (arg = iface->sym->formal; arg; arg = arg->next)
9525             {
9526               if (arg->sym
9527                   && arg->sym->ts.type == BT_DERIVED
9528                   && !arg->sym->ts.u.derived->attr.use_assoc
9529                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9530                                         arg->sym->ts.u.derived->ns->default_access)
9531                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
9532                                      "'%s' in PUBLIC interface '%s' at %L "
9533                                      "takes dummy arguments of '%s' which is "
9534                                      "PRIVATE", iface->sym->name, sym->name,
9535                                      &iface->sym->declared_at,
9536                                      gfc_typename (&arg->sym->ts)) == FAILURE)
9537                 {
9538                   /* Stop this message from recurring.  */
9539                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9540                   return FAILURE;
9541                 }
9542              }
9543         }
9544     }
9545
9546   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
9547       && !sym->attr.proc_pointer)
9548     {
9549       gfc_error ("Function '%s' at %L cannot have an initializer",
9550                  sym->name, &sym->declared_at);
9551       return FAILURE;
9552     }
9553
9554   /* An external symbol may not have an initializer because it is taken to be
9555      a procedure. Exception: Procedure Pointers.  */
9556   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
9557     {
9558       gfc_error ("External object '%s' at %L may not have an initializer",
9559                  sym->name, &sym->declared_at);
9560       return FAILURE;
9561     }
9562
9563   /* An elemental function is required to return a scalar 12.7.1  */
9564   if (sym->attr.elemental && sym->attr.function && sym->as)
9565     {
9566       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
9567                  "result", sym->name, &sym->declared_at);
9568       /* Reset so that the error only occurs once.  */
9569       sym->attr.elemental = 0;
9570       return FAILURE;
9571     }
9572
9573   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
9574      char-len-param shall not be array-valued, pointer-valued, recursive
9575      or pure.  ....snip... A character value of * may only be used in the
9576      following ways: (i) Dummy arg of procedure - dummy associates with
9577      actual length; (ii) To declare a named constant; or (iii) External
9578      function - but length must be declared in calling scoping unit.  */
9579   if (sym->attr.function
9580       && sym->ts.type == BT_CHARACTER
9581       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
9582     {
9583       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
9584           || (sym->attr.recursive) || (sym->attr.pure))
9585         {
9586           if (sym->as && sym->as->rank)
9587             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9588                        "array-valued", sym->name, &sym->declared_at);
9589
9590           if (sym->attr.pointer)
9591             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9592                        "pointer-valued", sym->name, &sym->declared_at);
9593
9594           if (sym->attr.pure)
9595             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9596                        "pure", sym->name, &sym->declared_at);
9597
9598           if (sym->attr.recursive)
9599             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9600                        "recursive", sym->name, &sym->declared_at);
9601
9602           return FAILURE;
9603         }
9604
9605       /* Appendix B.2 of the standard.  Contained functions give an
9606          error anyway.  Fixed-form is likely to be F77/legacy.  */
9607       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
9608         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
9609                         "CHARACTER(*) function '%s' at %L",
9610                         sym->name, &sym->declared_at);
9611     }
9612
9613   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
9614     {
9615       gfc_formal_arglist *curr_arg;
9616       int has_non_interop_arg = 0;
9617
9618       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
9619                              sym->common_block) == FAILURE)
9620         {
9621           /* Clear these to prevent looking at them again if there was an
9622              error.  */
9623           sym->attr.is_bind_c = 0;
9624           sym->attr.is_c_interop = 0;
9625           sym->ts.is_c_interop = 0;
9626         }
9627       else
9628         {
9629           /* So far, no errors have been found.  */
9630           sym->attr.is_c_interop = 1;
9631           sym->ts.is_c_interop = 1;
9632         }
9633       
9634       curr_arg = sym->formal;
9635       while (curr_arg != NULL)
9636         {
9637           /* Skip implicitly typed dummy args here.  */
9638           if (curr_arg->sym->attr.implicit_type == 0)
9639             if (verify_c_interop_param (curr_arg->sym) == FAILURE)
9640               /* If something is found to fail, record the fact so we
9641                  can mark the symbol for the procedure as not being
9642                  BIND(C) to try and prevent multiple errors being
9643                  reported.  */
9644               has_non_interop_arg = 1;
9645           
9646           curr_arg = curr_arg->next;
9647         }
9648
9649       /* See if any of the arguments were not interoperable and if so, clear
9650          the procedure symbol to prevent duplicate error messages.  */
9651       if (has_non_interop_arg != 0)
9652         {
9653           sym->attr.is_c_interop = 0;
9654           sym->ts.is_c_interop = 0;
9655           sym->attr.is_bind_c = 0;
9656         }
9657     }
9658   
9659   if (!sym->attr.proc_pointer)
9660     {
9661       if (sym->attr.save == SAVE_EXPLICIT)
9662         {
9663           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
9664                      "in '%s' at %L", sym->name, &sym->declared_at);
9665           return FAILURE;
9666         }
9667       if (sym->attr.intent)
9668         {
9669           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
9670                      "in '%s' at %L", sym->name, &sym->declared_at);
9671           return FAILURE;
9672         }
9673       if (sym->attr.subroutine && sym->attr.result)
9674         {
9675           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
9676                      "in '%s' at %L", sym->name, &sym->declared_at);
9677           return FAILURE;
9678         }
9679       if (sym->attr.external && sym->attr.function
9680           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
9681               || sym->attr.contained))
9682         {
9683           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
9684                      "in '%s' at %L", sym->name, &sym->declared_at);
9685           return FAILURE;
9686         }
9687       if (strcmp ("ppr@", sym->name) == 0)
9688         {
9689           gfc_error ("Procedure pointer result '%s' at %L "
9690                      "is missing the pointer attribute",
9691                      sym->ns->proc_name->name, &sym->declared_at);
9692           return FAILURE;
9693         }
9694     }
9695
9696   return SUCCESS;
9697 }
9698
9699
9700 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
9701    been defined and we now know their defined arguments, check that they fulfill
9702    the requirements of the standard for procedures used as finalizers.  */
9703
9704 static gfc_try
9705 gfc_resolve_finalizers (gfc_symbol* derived)
9706 {
9707   gfc_finalizer* list;
9708   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
9709   gfc_try result = SUCCESS;
9710   bool seen_scalar = false;
9711
9712   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
9713     return SUCCESS;
9714
9715   /* Walk over the list of finalizer-procedures, check them, and if any one
9716      does not fit in with the standard's definition, print an error and remove
9717      it from the list.  */
9718   prev_link = &derived->f2k_derived->finalizers;
9719   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
9720     {
9721       gfc_symbol* arg;
9722       gfc_finalizer* i;
9723       int my_rank;
9724
9725       /* Skip this finalizer if we already resolved it.  */
9726       if (list->proc_tree)
9727         {
9728           prev_link = &(list->next);
9729           continue;
9730         }
9731
9732       /* Check this exists and is a SUBROUTINE.  */
9733       if (!list->proc_sym->attr.subroutine)
9734         {
9735           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
9736                      list->proc_sym->name, &list->where);
9737           goto error;
9738         }
9739
9740       /* We should have exactly one argument.  */
9741       if (!list->proc_sym->formal || list->proc_sym->formal->next)
9742         {
9743           gfc_error ("FINAL procedure at %L must have exactly one argument",
9744                      &list->where);
9745           goto error;
9746         }
9747       arg = list->proc_sym->formal->sym;
9748
9749       /* This argument must be of our type.  */
9750       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
9751         {
9752           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
9753                      &arg->declared_at, derived->name);
9754           goto error;
9755         }
9756
9757       /* It must neither be a pointer nor allocatable nor optional.  */
9758       if (arg->attr.pointer)
9759         {
9760           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
9761                      &arg->declared_at);
9762           goto error;
9763         }
9764       if (arg->attr.allocatable)
9765         {
9766           gfc_error ("Argument of FINAL procedure at %L must not be"
9767                      " ALLOCATABLE", &arg->declared_at);
9768           goto error;
9769         }
9770       if (arg->attr.optional)
9771         {
9772           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
9773                      &arg->declared_at);
9774           goto error;
9775         }
9776
9777       /* It must not be INTENT(OUT).  */
9778       if (arg->attr.intent == INTENT_OUT)
9779         {
9780           gfc_error ("Argument of FINAL procedure at %L must not be"
9781                      " INTENT(OUT)", &arg->declared_at);
9782           goto error;
9783         }
9784
9785       /* Warn if the procedure is non-scalar and not assumed shape.  */
9786       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
9787           && arg->as->type != AS_ASSUMED_SHAPE)
9788         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
9789                      " shape argument", &arg->declared_at);
9790
9791       /* Check that it does not match in kind and rank with a FINAL procedure
9792          defined earlier.  To really loop over the *earlier* declarations,
9793          we need to walk the tail of the list as new ones were pushed at the
9794          front.  */
9795       /* TODO: Handle kind parameters once they are implemented.  */
9796       my_rank = (arg->as ? arg->as->rank : 0);
9797       for (i = list->next; i; i = i->next)
9798         {
9799           /* Argument list might be empty; that is an error signalled earlier,
9800              but we nevertheless continued resolving.  */
9801           if (i->proc_sym->formal)
9802             {
9803               gfc_symbol* i_arg = i->proc_sym->formal->sym;
9804               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
9805               if (i_rank == my_rank)
9806                 {
9807                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
9808                              " rank (%d) as '%s'",
9809                              list->proc_sym->name, &list->where, my_rank, 
9810                              i->proc_sym->name);
9811                   goto error;
9812                 }
9813             }
9814         }
9815
9816         /* Is this the/a scalar finalizer procedure?  */
9817         if (!arg->as || arg->as->rank == 0)
9818           seen_scalar = true;
9819
9820         /* Find the symtree for this procedure.  */
9821         gcc_assert (!list->proc_tree);
9822         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
9823
9824         prev_link = &list->next;
9825         continue;
9826
9827         /* Remove wrong nodes immediately from the list so we don't risk any
9828            troubles in the future when they might fail later expectations.  */
9829 error:
9830         result = FAILURE;
9831         i = list;
9832         *prev_link = list->next;
9833         gfc_free_finalizer (i);
9834     }
9835
9836   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
9837      were nodes in the list, must have been for arrays.  It is surely a good
9838      idea to have a scalar version there if there's something to finalize.  */
9839   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
9840     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
9841                  " defined at %L, suggest also scalar one",
9842                  derived->name, &derived->declared_at);
9843
9844   /* TODO:  Remove this error when finalization is finished.  */
9845   gfc_error ("Finalization at %L is not yet implemented",
9846              &derived->declared_at);
9847
9848   return result;
9849 }
9850
9851
9852 /* Check that it is ok for the typebound procedure proc to override the
9853    procedure old.  */
9854
9855 static gfc_try
9856 check_typebound_override (gfc_symtree* proc, gfc_symtree* old)
9857 {
9858   locus where;
9859   const gfc_symbol* proc_target;
9860   const gfc_symbol* old_target;
9861   unsigned proc_pass_arg, old_pass_arg, argpos;
9862   gfc_formal_arglist* proc_formal;
9863   gfc_formal_arglist* old_formal;
9864
9865   /* This procedure should only be called for non-GENERIC proc.  */
9866   gcc_assert (!proc->n.tb->is_generic);
9867
9868   /* If the overwritten procedure is GENERIC, this is an error.  */
9869   if (old->n.tb->is_generic)
9870     {
9871       gfc_error ("Can't overwrite GENERIC '%s' at %L",
9872                  old->name, &proc->n.tb->where);
9873       return FAILURE;
9874     }
9875
9876   where = proc->n.tb->where;
9877   proc_target = proc->n.tb->u.specific->n.sym;
9878   old_target = old->n.tb->u.specific->n.sym;
9879
9880   /* Check that overridden binding is not NON_OVERRIDABLE.  */
9881   if (old->n.tb->non_overridable)
9882     {
9883       gfc_error ("'%s' at %L overrides a procedure binding declared"
9884                  " NON_OVERRIDABLE", proc->name, &where);
9885       return FAILURE;
9886     }
9887
9888   /* It's an error to override a non-DEFERRED procedure with a DEFERRED one.  */
9889   if (!old->n.tb->deferred && proc->n.tb->deferred)
9890     {
9891       gfc_error ("'%s' at %L must not be DEFERRED as it overrides a"
9892                  " non-DEFERRED binding", proc->name, &where);
9893       return FAILURE;
9894     }
9895
9896   /* If the overridden binding is PURE, the overriding must be, too.  */
9897   if (old_target->attr.pure && !proc_target->attr.pure)
9898     {
9899       gfc_error ("'%s' at %L overrides a PURE procedure and must also be PURE",
9900                  proc->name, &where);
9901       return FAILURE;
9902     }
9903
9904   /* If the overridden binding is ELEMENTAL, the overriding must be, too.  If it
9905      is not, the overriding must not be either.  */
9906   if (old_target->attr.elemental && !proc_target->attr.elemental)
9907     {
9908       gfc_error ("'%s' at %L overrides an ELEMENTAL procedure and must also be"
9909                  " ELEMENTAL", proc->name, &where);
9910       return FAILURE;
9911     }
9912   if (!old_target->attr.elemental && proc_target->attr.elemental)
9913     {
9914       gfc_error ("'%s' at %L overrides a non-ELEMENTAL procedure and must not"
9915                  " be ELEMENTAL, either", proc->name, &where);
9916       return FAILURE;
9917     }
9918
9919   /* If the overridden binding is a SUBROUTINE, the overriding must also be a
9920      SUBROUTINE.  */
9921   if (old_target->attr.subroutine && !proc_target->attr.subroutine)
9922     {
9923       gfc_error ("'%s' at %L overrides a SUBROUTINE and must also be a"
9924                  " SUBROUTINE", proc->name, &where);
9925       return FAILURE;
9926     }
9927
9928   /* If the overridden binding is a FUNCTION, the overriding must also be a
9929      FUNCTION and have the same characteristics.  */
9930   if (old_target->attr.function)
9931     {
9932       if (!proc_target->attr.function)
9933         {
9934           gfc_error ("'%s' at %L overrides a FUNCTION and must also be a"
9935                      " FUNCTION", proc->name, &where);
9936           return FAILURE;
9937         }
9938
9939       /* FIXME:  Do more comprehensive checking (including, for instance, the
9940          rank and array-shape).  */
9941       gcc_assert (proc_target->result && old_target->result);
9942       if (!gfc_compare_types (&proc_target->result->ts,
9943                               &old_target->result->ts))
9944         {
9945           gfc_error ("'%s' at %L and the overridden FUNCTION should have"
9946                      " matching result types", proc->name, &where);
9947           return FAILURE;
9948         }
9949     }
9950
9951   /* If the overridden binding is PUBLIC, the overriding one must not be
9952      PRIVATE.  */
9953   if (old->n.tb->access == ACCESS_PUBLIC
9954       && proc->n.tb->access == ACCESS_PRIVATE)
9955     {
9956       gfc_error ("'%s' at %L overrides a PUBLIC procedure and must not be"
9957                  " PRIVATE", proc->name, &where);
9958       return FAILURE;
9959     }
9960
9961   /* Compare the formal argument lists of both procedures.  This is also abused
9962      to find the position of the passed-object dummy arguments of both
9963      bindings as at least the overridden one might not yet be resolved and we
9964      need those positions in the check below.  */
9965   proc_pass_arg = old_pass_arg = 0;
9966   if (!proc->n.tb->nopass && !proc->n.tb->pass_arg)
9967     proc_pass_arg = 1;
9968   if (!old->n.tb->nopass && !old->n.tb->pass_arg)
9969     old_pass_arg = 1;
9970   argpos = 1;
9971   for (proc_formal = proc_target->formal, old_formal = old_target->formal;
9972        proc_formal && old_formal;
9973        proc_formal = proc_formal->next, old_formal = old_formal->next)
9974     {
9975       if (proc->n.tb->pass_arg
9976           && !strcmp (proc->n.tb->pass_arg, proc_formal->sym->name))
9977         proc_pass_arg = argpos;
9978       if (old->n.tb->pass_arg
9979           && !strcmp (old->n.tb->pass_arg, old_formal->sym->name))
9980         old_pass_arg = argpos;
9981
9982       /* Check that the names correspond.  */
9983       if (strcmp (proc_formal->sym->name, old_formal->sym->name))
9984         {
9985           gfc_error ("Dummy argument '%s' of '%s' at %L should be named '%s' as"
9986                      " to match the corresponding argument of the overridden"
9987                      " procedure", proc_formal->sym->name, proc->name, &where,
9988                      old_formal->sym->name);
9989           return FAILURE;
9990         }
9991
9992       /* Check that the types correspond if neither is the passed-object
9993          argument.  */
9994       /* FIXME:  Do more comprehensive testing here.  */
9995       if (proc_pass_arg != argpos && old_pass_arg != argpos
9996           && !gfc_compare_types (&proc_formal->sym->ts, &old_formal->sym->ts))
9997         {
9998           gfc_error ("Types mismatch for dummy argument '%s' of '%s' %L "
9999                      "in respect to the overridden procedure",
10000                      proc_formal->sym->name, proc->name, &where);
10001           return FAILURE;
10002         }
10003
10004       ++argpos;
10005     }
10006   if (proc_formal || old_formal)
10007     {
10008       gfc_error ("'%s' at %L must have the same number of formal arguments as"
10009                  " the overridden procedure", proc->name, &where);
10010       return FAILURE;
10011     }
10012
10013   /* If the overridden binding is NOPASS, the overriding one must also be
10014      NOPASS.  */
10015   if (old->n.tb->nopass && !proc->n.tb->nopass)
10016     {
10017       gfc_error ("'%s' at %L overrides a NOPASS binding and must also be"
10018                  " NOPASS", proc->name, &where);
10019       return FAILURE;
10020     }
10021
10022   /* If the overridden binding is PASS(x), the overriding one must also be
10023      PASS and the passed-object dummy arguments must correspond.  */
10024   if (!old->n.tb->nopass)
10025     {
10026       if (proc->n.tb->nopass)
10027         {
10028           gfc_error ("'%s' at %L overrides a binding with PASS and must also be"
10029                      " PASS", proc->name, &where);
10030           return FAILURE;
10031         }
10032
10033       if (proc_pass_arg != old_pass_arg)
10034         {
10035           gfc_error ("Passed-object dummy argument of '%s' at %L must be at"
10036                      " the same position as the passed-object dummy argument of"
10037                      " the overridden procedure", proc->name, &where);
10038           return FAILURE;
10039         }
10040     }
10041
10042   return SUCCESS;
10043 }
10044
10045
10046 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
10047
10048 static gfc_try
10049 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
10050                              const char* generic_name, locus where)
10051 {
10052   gfc_symbol* sym1;
10053   gfc_symbol* sym2;
10054
10055   gcc_assert (t1->specific && t2->specific);
10056   gcc_assert (!t1->specific->is_generic);
10057   gcc_assert (!t2->specific->is_generic);
10058
10059   sym1 = t1->specific->u.specific->n.sym;
10060   sym2 = t2->specific->u.specific->n.sym;
10061
10062   if (sym1 == sym2)
10063     return SUCCESS;
10064
10065   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
10066   if (sym1->attr.subroutine != sym2->attr.subroutine
10067       || sym1->attr.function != sym2->attr.function)
10068     {
10069       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
10070                  " GENERIC '%s' at %L",
10071                  sym1->name, sym2->name, generic_name, &where);
10072       return FAILURE;
10073     }
10074
10075   /* Compare the interfaces.  */
10076   if (gfc_compare_interfaces (sym1, sym2, sym2->name, 1, 0, NULL, 0))
10077     {
10078       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
10079                  sym1->name, sym2->name, generic_name, &where);
10080       return FAILURE;
10081     }
10082
10083   return SUCCESS;
10084 }
10085
10086
10087 /* Worker function for resolving a generic procedure binding; this is used to
10088    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
10089
10090    The difference between those cases is finding possible inherited bindings
10091    that are overridden, as one has to look for them in tb_sym_root,
10092    tb_uop_root or tb_op, respectively.  Thus the caller must already find
10093    the super-type and set p->overridden correctly.  */
10094
10095 static gfc_try
10096 resolve_tb_generic_targets (gfc_symbol* super_type,
10097                             gfc_typebound_proc* p, const char* name)
10098 {
10099   gfc_tbp_generic* target;
10100   gfc_symtree* first_target;
10101   gfc_symtree* inherited;
10102
10103   gcc_assert (p && p->is_generic);
10104
10105   /* Try to find the specific bindings for the symtrees in our target-list.  */
10106   gcc_assert (p->u.generic);
10107   for (target = p->u.generic; target; target = target->next)
10108     if (!target->specific)
10109       {
10110         gfc_typebound_proc* overridden_tbp;
10111         gfc_tbp_generic* g;
10112         const char* target_name;
10113
10114         target_name = target->specific_st->name;
10115
10116         /* Defined for this type directly.  */
10117         if (target->specific_st->n.tb)
10118           {
10119             target->specific = target->specific_st->n.tb;
10120             goto specific_found;
10121           }
10122
10123         /* Look for an inherited specific binding.  */
10124         if (super_type)
10125           {
10126             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
10127                                                  true, NULL);
10128
10129             if (inherited)
10130               {
10131                 gcc_assert (inherited->n.tb);
10132                 target->specific = inherited->n.tb;
10133                 goto specific_found;
10134               }
10135           }
10136
10137         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
10138                    " at %L", target_name, name, &p->where);
10139         return FAILURE;
10140
10141         /* Once we've found the specific binding, check it is not ambiguous with
10142            other specifics already found or inherited for the same GENERIC.  */
10143 specific_found:
10144         gcc_assert (target->specific);
10145
10146         /* This must really be a specific binding!  */
10147         if (target->specific->is_generic)
10148           {
10149             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
10150                        " '%s' is GENERIC, too", name, &p->where, target_name);
10151             return FAILURE;
10152           }
10153
10154         /* Check those already resolved on this type directly.  */
10155         for (g = p->u.generic; g; g = g->next)
10156           if (g != target && g->specific
10157               && check_generic_tbp_ambiguity (target, g, name, p->where)
10158                   == FAILURE)
10159             return FAILURE;
10160
10161         /* Check for ambiguity with inherited specific targets.  */
10162         for (overridden_tbp = p->overridden; overridden_tbp;
10163              overridden_tbp = overridden_tbp->overridden)
10164           if (overridden_tbp->is_generic)
10165             {
10166               for (g = overridden_tbp->u.generic; g; g = g->next)
10167                 {
10168                   gcc_assert (g->specific);
10169                   if (check_generic_tbp_ambiguity (target, g,
10170                                                    name, p->where) == FAILURE)
10171                     return FAILURE;
10172                 }
10173             }
10174       }
10175
10176   /* If we attempt to "overwrite" a specific binding, this is an error.  */
10177   if (p->overridden && !p->overridden->is_generic)
10178     {
10179       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
10180                  " the same name", name, &p->where);
10181       return FAILURE;
10182     }
10183
10184   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
10185      all must have the same attributes here.  */
10186   first_target = p->u.generic->specific->u.specific;
10187   gcc_assert (first_target);
10188   p->subroutine = first_target->n.sym->attr.subroutine;
10189   p->function = first_target->n.sym->attr.function;
10190
10191   return SUCCESS;
10192 }
10193
10194
10195 /* Resolve a GENERIC procedure binding for a derived type.  */
10196
10197 static gfc_try
10198 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
10199 {
10200   gfc_symbol* super_type;
10201
10202   /* Find the overridden binding if any.  */
10203   st->n.tb->overridden = NULL;
10204   super_type = gfc_get_derived_super_type (derived);
10205   if (super_type)
10206     {
10207       gfc_symtree* overridden;
10208       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
10209                                             true, NULL);
10210
10211       if (overridden && overridden->n.tb)
10212         st->n.tb->overridden = overridden->n.tb;
10213     }
10214
10215   /* Resolve using worker function.  */
10216   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
10217 }
10218
10219
10220 /* Retrieve the target-procedure of an operator binding and do some checks in
10221    common for intrinsic and user-defined type-bound operators.  */
10222
10223 static gfc_symbol*
10224 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
10225 {
10226   gfc_symbol* target_proc;
10227
10228   gcc_assert (target->specific && !target->specific->is_generic);
10229   target_proc = target->specific->u.specific->n.sym;
10230   gcc_assert (target_proc);
10231
10232   /* All operator bindings must have a passed-object dummy argument.  */
10233   if (target->specific->nopass)
10234     {
10235       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
10236       return NULL;
10237     }
10238
10239   return target_proc;
10240 }
10241
10242
10243 /* Resolve a type-bound intrinsic operator.  */
10244
10245 static gfc_try
10246 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
10247                                 gfc_typebound_proc* p)
10248 {
10249   gfc_symbol* super_type;
10250   gfc_tbp_generic* target;
10251   
10252   /* If there's already an error here, do nothing (but don't fail again).  */
10253   if (p->error)
10254     return SUCCESS;
10255
10256   /* Operators should always be GENERIC bindings.  */
10257   gcc_assert (p->is_generic);
10258
10259   /* Look for an overridden binding.  */
10260   super_type = gfc_get_derived_super_type (derived);
10261   if (super_type && super_type->f2k_derived)
10262     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
10263                                                      op, true, NULL);
10264   else
10265     p->overridden = NULL;
10266
10267   /* Resolve general GENERIC properties using worker function.  */
10268   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
10269     goto error;
10270
10271   /* Check the targets to be procedures of correct interface.  */
10272   for (target = p->u.generic; target; target = target->next)
10273     {
10274       gfc_symbol* target_proc;
10275
10276       target_proc = get_checked_tb_operator_target (target, p->where);
10277       if (!target_proc)
10278         goto error;
10279
10280       if (!gfc_check_operator_interface (target_proc, op, p->where))
10281         goto error;
10282     }
10283
10284   return SUCCESS;
10285
10286 error:
10287   p->error = 1;
10288   return FAILURE;
10289 }
10290
10291
10292 /* Resolve a type-bound user operator (tree-walker callback).  */
10293
10294 static gfc_symbol* resolve_bindings_derived;
10295 static gfc_try resolve_bindings_result;
10296
10297 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
10298
10299 static void
10300 resolve_typebound_user_op (gfc_symtree* stree)
10301 {
10302   gfc_symbol* super_type;
10303   gfc_tbp_generic* target;
10304
10305   gcc_assert (stree && stree->n.tb);
10306
10307   if (stree->n.tb->error)
10308     return;
10309
10310   /* Operators should always be GENERIC bindings.  */
10311   gcc_assert (stree->n.tb->is_generic);
10312
10313   /* Find overridden procedure, if any.  */
10314   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10315   if (super_type && super_type->f2k_derived)
10316     {
10317       gfc_symtree* overridden;
10318       overridden = gfc_find_typebound_user_op (super_type, NULL,
10319                                                stree->name, true, NULL);
10320
10321       if (overridden && overridden->n.tb)
10322         stree->n.tb->overridden = overridden->n.tb;
10323     }
10324   else
10325     stree->n.tb->overridden = NULL;
10326
10327   /* Resolve basically using worker function.  */
10328   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
10329         == FAILURE)
10330     goto error;
10331
10332   /* Check the targets to be functions of correct interface.  */
10333   for (target = stree->n.tb->u.generic; target; target = target->next)
10334     {
10335       gfc_symbol* target_proc;
10336
10337       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
10338       if (!target_proc)
10339         goto error;
10340
10341       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
10342         goto error;
10343     }
10344
10345   return;
10346
10347 error:
10348   resolve_bindings_result = FAILURE;
10349   stree->n.tb->error = 1;
10350 }
10351
10352
10353 /* Resolve the type-bound procedures for a derived type.  */
10354
10355 static void
10356 resolve_typebound_procedure (gfc_symtree* stree)
10357 {
10358   gfc_symbol* proc;
10359   locus where;
10360   gfc_symbol* me_arg;
10361   gfc_symbol* super_type;
10362   gfc_component* comp;
10363
10364   gcc_assert (stree);
10365
10366   /* Undefined specific symbol from GENERIC target definition.  */
10367   if (!stree->n.tb)
10368     return;
10369
10370   if (stree->n.tb->error)
10371     return;
10372
10373   /* If this is a GENERIC binding, use that routine.  */
10374   if (stree->n.tb->is_generic)
10375     {
10376       if (resolve_typebound_generic (resolve_bindings_derived, stree)
10377             == FAILURE)
10378         goto error;
10379       return;
10380     }
10381
10382   /* Get the target-procedure to check it.  */
10383   gcc_assert (!stree->n.tb->is_generic);
10384   gcc_assert (stree->n.tb->u.specific);
10385   proc = stree->n.tb->u.specific->n.sym;
10386   where = stree->n.tb->where;
10387
10388   /* Default access should already be resolved from the parser.  */
10389   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
10390
10391   /* It should be a module procedure or an external procedure with explicit
10392      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
10393   if ((!proc->attr.subroutine && !proc->attr.function)
10394       || (proc->attr.proc != PROC_MODULE
10395           && proc->attr.if_source != IFSRC_IFBODY)
10396       || (proc->attr.abstract && !stree->n.tb->deferred))
10397     {
10398       gfc_error ("'%s' must be a module procedure or an external procedure with"
10399                  " an explicit interface at %L", proc->name, &where);
10400       goto error;
10401     }
10402   stree->n.tb->subroutine = proc->attr.subroutine;
10403   stree->n.tb->function = proc->attr.function;
10404
10405   /* Find the super-type of the current derived type.  We could do this once and
10406      store in a global if speed is needed, but as long as not I believe this is
10407      more readable and clearer.  */
10408   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10409
10410   /* If PASS, resolve and check arguments if not already resolved / loaded
10411      from a .mod file.  */
10412   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
10413     {
10414       if (stree->n.tb->pass_arg)
10415         {
10416           gfc_formal_arglist* i;
10417
10418           /* If an explicit passing argument name is given, walk the arg-list
10419              and look for it.  */
10420
10421           me_arg = NULL;
10422           stree->n.tb->pass_arg_num = 1;
10423           for (i = proc->formal; i; i = i->next)
10424             {
10425               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
10426                 {
10427                   me_arg = i->sym;
10428                   break;
10429                 }
10430               ++stree->n.tb->pass_arg_num;
10431             }
10432
10433           if (!me_arg)
10434             {
10435               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
10436                          " argument '%s'",
10437                          proc->name, stree->n.tb->pass_arg, &where,
10438                          stree->n.tb->pass_arg);
10439               goto error;
10440             }
10441         }
10442       else
10443         {
10444           /* Otherwise, take the first one; there should in fact be at least
10445              one.  */
10446           stree->n.tb->pass_arg_num = 1;
10447           if (!proc->formal)
10448             {
10449               gfc_error ("Procedure '%s' with PASS at %L must have at"
10450                          " least one argument", proc->name, &where);
10451               goto error;
10452             }
10453           me_arg = proc->formal->sym;
10454         }
10455
10456       /* Now check that the argument-type matches and the passed-object
10457          dummy argument is generally fine.  */
10458
10459       gcc_assert (me_arg);
10460
10461       if (me_arg->ts.type != BT_CLASS)
10462         {
10463           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
10464                      " at %L", proc->name, &where);
10465           goto error;
10466         }
10467
10468       if (me_arg->ts.u.derived->components->ts.u.derived
10469           != resolve_bindings_derived)
10470         {
10471           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
10472                      " the derived-type '%s'", me_arg->name, proc->name,
10473                      me_arg->name, &where, resolve_bindings_derived->name);
10474           goto error;
10475         }
10476   
10477       gcc_assert (me_arg->ts.type == BT_CLASS);
10478       if (me_arg->ts.u.derived->components->as
10479           && me_arg->ts.u.derived->components->as->rank > 0)
10480         {
10481           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
10482                      " scalar", proc->name, &where);
10483           goto error;
10484         }
10485       if (me_arg->ts.u.derived->components->attr.allocatable)
10486         {
10487           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
10488                      " be ALLOCATABLE", proc->name, &where);
10489           goto error;
10490         }
10491       if (me_arg->ts.u.derived->components->attr.class_pointer)
10492         {
10493           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
10494                      " be POINTER", proc->name, &where);
10495           goto error;
10496         }
10497     }
10498
10499   /* If we are extending some type, check that we don't override a procedure
10500      flagged NON_OVERRIDABLE.  */
10501   stree->n.tb->overridden = NULL;
10502   if (super_type)
10503     {
10504       gfc_symtree* overridden;
10505       overridden = gfc_find_typebound_proc (super_type, NULL,
10506                                             stree->name, true, NULL);
10507
10508       if (overridden && overridden->n.tb)
10509         stree->n.tb->overridden = overridden->n.tb;
10510
10511       if (overridden && check_typebound_override (stree, overridden) == FAILURE)
10512         goto error;
10513     }
10514
10515   /* See if there's a name collision with a component directly in this type.  */
10516   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
10517     if (!strcmp (comp->name, stree->name))
10518       {
10519         gfc_error ("Procedure '%s' at %L has the same name as a component of"
10520                    " '%s'",
10521                    stree->name, &where, resolve_bindings_derived->name);
10522         goto error;
10523       }
10524
10525   /* Try to find a name collision with an inherited component.  */
10526   if (super_type && gfc_find_component (super_type, stree->name, true, true))
10527     {
10528       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
10529                  " component of '%s'",
10530                  stree->name, &where, resolve_bindings_derived->name);
10531       goto error;
10532     }
10533
10534   stree->n.tb->error = 0;
10535   return;
10536
10537 error:
10538   resolve_bindings_result = FAILURE;
10539   stree->n.tb->error = 1;
10540 }
10541
10542 static gfc_try
10543 resolve_typebound_procedures (gfc_symbol* derived)
10544 {
10545   int op;
10546
10547   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
10548     return SUCCESS;
10549
10550   resolve_bindings_derived = derived;
10551   resolve_bindings_result = SUCCESS;
10552
10553   if (derived->f2k_derived->tb_sym_root)
10554     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
10555                           &resolve_typebound_procedure);
10556
10557   if (derived->f2k_derived->tb_uop_root)
10558     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
10559                           &resolve_typebound_user_op);
10560
10561   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
10562     {
10563       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
10564       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
10565                                                p) == FAILURE)
10566         resolve_bindings_result = FAILURE;
10567     }
10568
10569   return resolve_bindings_result;
10570 }
10571
10572
10573 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
10574    to give all identical derived types the same backend_decl.  */
10575 static void
10576 add_dt_to_dt_list (gfc_symbol *derived)
10577 {
10578   gfc_dt_list *dt_list;
10579
10580   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
10581     if (derived == dt_list->derived)
10582       break;
10583
10584   if (dt_list == NULL)
10585     {
10586       dt_list = gfc_get_dt_list ();
10587       dt_list->next = gfc_derived_types;
10588       dt_list->derived = derived;
10589       gfc_derived_types = dt_list;
10590     }
10591 }
10592
10593
10594 /* Ensure that a derived-type is really not abstract, meaning that every
10595    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
10596
10597 static gfc_try
10598 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
10599 {
10600   if (!st)
10601     return SUCCESS;
10602
10603   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
10604     return FAILURE;
10605   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
10606     return FAILURE;
10607
10608   if (st->n.tb && st->n.tb->deferred)
10609     {
10610       gfc_symtree* overriding;
10611       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
10612       gcc_assert (overriding && overriding->n.tb);
10613       if (overriding->n.tb->deferred)
10614         {
10615           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
10616                      " '%s' is DEFERRED and not overridden",
10617                      sub->name, &sub->declared_at, st->name);
10618           return FAILURE;
10619         }
10620     }
10621
10622   return SUCCESS;
10623 }
10624
10625 static gfc_try
10626 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
10627 {
10628   /* The algorithm used here is to recursively travel up the ancestry of sub
10629      and for each ancestor-type, check all bindings.  If any of them is
10630      DEFERRED, look it up starting from sub and see if the found (overriding)
10631      binding is not DEFERRED.
10632      This is not the most efficient way to do this, but it should be ok and is
10633      clearer than something sophisticated.  */
10634
10635   gcc_assert (ancestor && ancestor->attr.abstract && !sub->attr.abstract);
10636
10637   /* Walk bindings of this ancestor.  */
10638   if (ancestor->f2k_derived)
10639     {
10640       gfc_try t;
10641       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
10642       if (t == FAILURE)
10643         return FAILURE;
10644     }
10645
10646   /* Find next ancestor type and recurse on it.  */
10647   ancestor = gfc_get_derived_super_type (ancestor);
10648   if (ancestor)
10649     return ensure_not_abstract (sub, ancestor);
10650
10651   return SUCCESS;
10652 }
10653
10654
10655 static void resolve_symbol (gfc_symbol *sym);
10656
10657
10658 /* Resolve the components of a derived type.  */
10659
10660 static gfc_try
10661 resolve_fl_derived (gfc_symbol *sym)
10662 {
10663   gfc_symbol* super_type;
10664   gfc_component *c;
10665   int i;
10666
10667   super_type = gfc_get_derived_super_type (sym);
10668
10669   /* F2008, C432. */
10670   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
10671     {
10672       gfc_error ("As extending type '%s' at %L has a coarray component, "
10673                  "parent type '%s' shall also have one", sym->name,
10674                  &sym->declared_at, super_type->name);
10675       return FAILURE;
10676     }
10677
10678   /* Ensure the extended type gets resolved before we do.  */
10679   if (super_type && resolve_fl_derived (super_type) == FAILURE)
10680     return FAILURE;
10681
10682   /* An ABSTRACT type must be extensible.  */
10683   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
10684     {
10685       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
10686                  sym->name, &sym->declared_at);
10687       return FAILURE;
10688     }
10689
10690   for (c = sym->components; c != NULL; c = c->next)
10691     {
10692       /* F2008, C442.  */
10693       if (c->attr.codimension /* FIXME: c->as check due to PR 43412.  */
10694           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
10695         {
10696           gfc_error ("Coarray component '%s' at %L must be allocatable with "
10697                      "deferred shape", c->name, &c->loc);
10698           return FAILURE;
10699         }
10700
10701       /* F2008, C443.  */
10702       if (c->attr.codimension && c->ts.type == BT_DERIVED
10703           && c->ts.u.derived->ts.is_iso_c)
10704         {
10705           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
10706                      "shall not be a coarray", c->name, &c->loc);
10707           return FAILURE;
10708         }
10709
10710       /* F2008, C444.  */
10711       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
10712           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
10713               || c->attr.allocatable))
10714         {
10715           gfc_error ("Component '%s' at %L with coarray component "
10716                      "shall be a nonpointer, nonallocatable scalar",
10717                      c->name, &c->loc);
10718           return FAILURE;
10719         }
10720
10721       if (c->attr.proc_pointer && c->ts.interface)
10722         {
10723           if (c->ts.interface->attr.procedure)
10724             gfc_error ("Interface '%s', used by procedure pointer component "
10725                        "'%s' at %L, is declared in a later PROCEDURE statement",
10726                        c->ts.interface->name, c->name, &c->loc);
10727
10728           /* Get the attributes from the interface (now resolved).  */
10729           if (c->ts.interface->attr.if_source
10730               || c->ts.interface->attr.intrinsic)
10731             {
10732               gfc_symbol *ifc = c->ts.interface;
10733
10734               if (ifc->formal && !ifc->formal_ns)
10735                 resolve_symbol (ifc);
10736
10737               if (ifc->attr.intrinsic)
10738                 resolve_intrinsic (ifc, &ifc->declared_at);
10739
10740               if (ifc->result)
10741                 {
10742                   c->ts = ifc->result->ts;
10743                   c->attr.allocatable = ifc->result->attr.allocatable;
10744                   c->attr.pointer = ifc->result->attr.pointer;
10745                   c->attr.dimension = ifc->result->attr.dimension;
10746                   c->as = gfc_copy_array_spec (ifc->result->as);
10747                 }
10748               else
10749                 {   
10750                   c->ts = ifc->ts;
10751                   c->attr.allocatable = ifc->attr.allocatable;
10752                   c->attr.pointer = ifc->attr.pointer;
10753                   c->attr.dimension = ifc->attr.dimension;
10754                   c->as = gfc_copy_array_spec (ifc->as);
10755                 }
10756               c->ts.interface = ifc;
10757               c->attr.function = ifc->attr.function;
10758               c->attr.subroutine = ifc->attr.subroutine;
10759               gfc_copy_formal_args_ppc (c, ifc);
10760
10761               c->attr.pure = ifc->attr.pure;
10762               c->attr.elemental = ifc->attr.elemental;
10763               c->attr.recursive = ifc->attr.recursive;
10764               c->attr.always_explicit = ifc->attr.always_explicit;
10765               c->attr.ext_attr |= ifc->attr.ext_attr;
10766               /* Replace symbols in array spec.  */
10767               if (c->as)
10768                 {
10769                   int i;
10770                   for (i = 0; i < c->as->rank; i++)
10771                     {
10772                       gfc_expr_replace_comp (c->as->lower[i], c);
10773                       gfc_expr_replace_comp (c->as->upper[i], c);
10774                     }
10775                 }
10776               /* Copy char length.  */
10777               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
10778                 {
10779                   c->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
10780                   gfc_expr_replace_comp (c->ts.u.cl->length, c);
10781                 }
10782             }
10783           else if (c->ts.interface->name[0] != '\0')
10784             {
10785               gfc_error ("Interface '%s' of procedure pointer component "
10786                          "'%s' at %L must be explicit", c->ts.interface->name,
10787                          c->name, &c->loc);
10788               return FAILURE;
10789             }
10790         }
10791       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
10792         {
10793           /* Since PPCs are not implicitly typed, a PPC without an explicit
10794              interface must be a subroutine.  */
10795           gfc_add_subroutine (&c->attr, c->name, &c->loc);
10796         }
10797
10798       /* Procedure pointer components: Check PASS arg.  */
10799       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0)
10800         {
10801           gfc_symbol* me_arg;
10802
10803           if (c->tb->pass_arg)
10804             {
10805               gfc_formal_arglist* i;
10806
10807               /* If an explicit passing argument name is given, walk the arg-list
10808                 and look for it.  */
10809
10810               me_arg = NULL;
10811               c->tb->pass_arg_num = 1;
10812               for (i = c->formal; i; i = i->next)
10813                 {
10814                   if (!strcmp (i->sym->name, c->tb->pass_arg))
10815                     {
10816                       me_arg = i->sym;
10817                       break;
10818                     }
10819                   c->tb->pass_arg_num++;
10820                 }
10821
10822               if (!me_arg)
10823                 {
10824                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
10825                              "at %L has no argument '%s'", c->name,
10826                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
10827                   c->tb->error = 1;
10828                   return FAILURE;
10829                 }
10830             }
10831           else
10832             {
10833               /* Otherwise, take the first one; there should in fact be at least
10834                 one.  */
10835               c->tb->pass_arg_num = 1;
10836               if (!c->formal)
10837                 {
10838                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
10839                              "must have at least one argument",
10840                              c->name, &c->loc);
10841                   c->tb->error = 1;
10842                   return FAILURE;
10843                 }
10844               me_arg = c->formal->sym;
10845             }
10846
10847           /* Now check that the argument-type matches.  */
10848           gcc_assert (me_arg);
10849           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
10850               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
10851               || (me_arg->ts.type == BT_CLASS
10852                   && me_arg->ts.u.derived->components->ts.u.derived != sym))
10853             {
10854               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
10855                          " the derived type '%s'", me_arg->name, c->name,
10856                          me_arg->name, &c->loc, sym->name);
10857               c->tb->error = 1;
10858               return FAILURE;
10859             }
10860
10861           /* Check for C453.  */
10862           if (me_arg->attr.dimension)
10863             {
10864               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10865                          "must be scalar", me_arg->name, c->name, me_arg->name,
10866                          &c->loc);
10867               c->tb->error = 1;
10868               return FAILURE;
10869             }
10870
10871           if (me_arg->attr.pointer)
10872             {
10873               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10874                          "may not have the POINTER attribute", me_arg->name,
10875                          c->name, me_arg->name, &c->loc);
10876               c->tb->error = 1;
10877               return FAILURE;
10878             }
10879
10880           if (me_arg->attr.allocatable)
10881             {
10882               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10883                          "may not be ALLOCATABLE", me_arg->name, c->name,
10884                          me_arg->name, &c->loc);
10885               c->tb->error = 1;
10886               return FAILURE;
10887             }
10888
10889           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
10890             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
10891                        " at %L", c->name, &c->loc);
10892
10893         }
10894
10895       /* Check type-spec if this is not the parent-type component.  */
10896       if ((!sym->attr.extension || c != sym->components)
10897           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
10898         return FAILURE;
10899
10900       /* If this type is an extension, set the accessibility of the parent
10901          component.  */
10902       if (super_type && c == sym->components
10903           && strcmp (super_type->name, c->name) == 0)
10904         c->attr.access = super_type->attr.access;
10905       
10906       /* If this type is an extension, see if this component has the same name
10907          as an inherited type-bound procedure.  */
10908       if (super_type
10909           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
10910         {
10911           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
10912                      " inherited type-bound procedure",
10913                      c->name, sym->name, &c->loc);
10914           return FAILURE;
10915         }
10916
10917       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer)
10918         {
10919          if (c->ts.u.cl->length == NULL
10920              || (resolve_charlen (c->ts.u.cl) == FAILURE)
10921              || !gfc_is_constant_expr (c->ts.u.cl->length))
10922            {
10923              gfc_error ("Character length of component '%s' needs to "
10924                         "be a constant specification expression at %L",
10925                         c->name,
10926                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
10927              return FAILURE;
10928            }
10929         }
10930
10931       if (c->ts.type == BT_DERIVED
10932           && sym->component_access != ACCESS_PRIVATE
10933           && gfc_check_access (sym->attr.access, sym->ns->default_access)
10934           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
10935           && !c->ts.u.derived->attr.use_assoc
10936           && !gfc_check_access (c->ts.u.derived->attr.access,
10937                                 c->ts.u.derived->ns->default_access)
10938           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
10939                              "is a PRIVATE type and cannot be a component of "
10940                              "'%s', which is PUBLIC at %L", c->name,
10941                              sym->name, &sym->declared_at) == FAILURE)
10942         return FAILURE;
10943
10944       if (sym->attr.sequence)
10945         {
10946           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
10947             {
10948               gfc_error ("Component %s of SEQUENCE type declared at %L does "
10949                          "not have the SEQUENCE attribute",
10950                          c->ts.u.derived->name, &sym->declared_at);
10951               return FAILURE;
10952             }
10953         }
10954
10955       if (c->ts.type == BT_DERIVED && c->attr.pointer
10956           && c->ts.u.derived->components == NULL
10957           && !c->ts.u.derived->attr.zero_comp)
10958         {
10959           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
10960                      "that has not been declared", c->name, sym->name,
10961                      &c->loc);
10962           return FAILURE;
10963         }
10964
10965       /* C437.  */
10966       if (c->ts.type == BT_CLASS
10967           && !(c->ts.u.derived->components->attr.pointer
10968                || c->ts.u.derived->components->attr.allocatable))
10969         {
10970           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
10971                      "or pointer", c->name, &c->loc);
10972           return FAILURE;
10973         }
10974
10975       /* Ensure that all the derived type components are put on the
10976          derived type list; even in formal namespaces, where derived type
10977          pointer components might not have been declared.  */
10978       if (c->ts.type == BT_DERIVED
10979             && c->ts.u.derived
10980             && c->ts.u.derived->components
10981             && c->attr.pointer
10982             && sym != c->ts.u.derived)
10983         add_dt_to_dt_list (c->ts.u.derived);
10984
10985       if (c->attr.pointer || c->attr.proc_pointer || c->attr.allocatable
10986           || c->as == NULL)
10987         continue;
10988
10989       for (i = 0; i < c->as->rank; i++)
10990         {
10991           if (c->as->lower[i] == NULL
10992               || (resolve_index_expr (c->as->lower[i]) == FAILURE)
10993               || !gfc_is_constant_expr (c->as->lower[i])
10994               || c->as->upper[i] == NULL
10995               || (resolve_index_expr (c->as->upper[i]) == FAILURE)
10996               || !gfc_is_constant_expr (c->as->upper[i]))
10997             {
10998               gfc_error ("Component '%s' of '%s' at %L must have "
10999                          "constant array bounds",
11000                          c->name, sym->name, &c->loc);
11001               return FAILURE;
11002             }
11003         }
11004     }
11005
11006   /* Resolve the type-bound procedures.  */
11007   if (resolve_typebound_procedures (sym) == FAILURE)
11008     return FAILURE;
11009
11010   /* Resolve the finalizer procedures.  */
11011   if (gfc_resolve_finalizers (sym) == FAILURE)
11012     return FAILURE;
11013
11014   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
11015      all DEFERRED bindings are overridden.  */
11016   if (super_type && super_type->attr.abstract && !sym->attr.abstract
11017       && ensure_not_abstract (sym, super_type) == FAILURE)
11018     return FAILURE;
11019
11020   /* Add derived type to the derived type list.  */
11021   add_dt_to_dt_list (sym);
11022
11023   return SUCCESS;
11024 }
11025
11026
11027 static gfc_try
11028 resolve_fl_namelist (gfc_symbol *sym)
11029 {
11030   gfc_namelist *nl;
11031   gfc_symbol *nlsym;
11032
11033   /* Reject PRIVATE objects in a PUBLIC namelist.  */
11034   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
11035     {
11036       for (nl = sym->namelist; nl; nl = nl->next)
11037         {
11038           if (!nl->sym->attr.use_assoc
11039               && !is_sym_host_assoc (nl->sym, sym->ns)
11040               && !gfc_check_access(nl->sym->attr.access,
11041                                 nl->sym->ns->default_access))
11042             {
11043               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
11044                          "cannot be member of PUBLIC namelist '%s' at %L",
11045                          nl->sym->name, sym->name, &sym->declared_at);
11046               return FAILURE;
11047             }
11048
11049           /* Types with private components that came here by USE-association.  */
11050           if (nl->sym->ts.type == BT_DERIVED
11051               && derived_inaccessible (nl->sym->ts.u.derived))
11052             {
11053               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
11054                          "components and cannot be member of namelist '%s' at %L",
11055                          nl->sym->name, sym->name, &sym->declared_at);
11056               return FAILURE;
11057             }
11058
11059           /* Types with private components that are defined in the same module.  */
11060           if (nl->sym->ts.type == BT_DERIVED
11061               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
11062               && !gfc_check_access (nl->sym->ts.u.derived->attr.private_comp
11063                                         ? ACCESS_PRIVATE : ACCESS_UNKNOWN,
11064                                         nl->sym->ns->default_access))
11065             {
11066               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
11067                          "cannot be a member of PUBLIC namelist '%s' at %L",
11068                          nl->sym->name, sym->name, &sym->declared_at);
11069               return FAILURE;
11070             }
11071         }
11072     }
11073
11074   for (nl = sym->namelist; nl; nl = nl->next)
11075     {
11076       /* Reject namelist arrays of assumed shape.  */
11077       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
11078           && gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
11079                              "must not have assumed shape in namelist "
11080                              "'%s' at %L", nl->sym->name, sym->name,
11081                              &sym->declared_at) == FAILURE)
11082             return FAILURE;
11083
11084       /* Reject namelist arrays that are not constant shape.  */
11085       if (is_non_constant_shape_array (nl->sym))
11086         {
11087           gfc_error ("NAMELIST array object '%s' must have constant "
11088                      "shape in namelist '%s' at %L", nl->sym->name,
11089                      sym->name, &sym->declared_at);
11090           return FAILURE;
11091         }
11092
11093       /* Namelist objects cannot have allocatable or pointer components.  */
11094       if (nl->sym->ts.type != BT_DERIVED)
11095         continue;
11096
11097       if (nl->sym->ts.u.derived->attr.alloc_comp)
11098         {
11099           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11100                      "have ALLOCATABLE components",
11101                      nl->sym->name, sym->name, &sym->declared_at);
11102           return FAILURE;
11103         }
11104
11105       if (nl->sym->ts.u.derived->attr.pointer_comp)
11106         {
11107           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11108                      "have POINTER components", 
11109                      nl->sym->name, sym->name, &sym->declared_at);
11110           return FAILURE;
11111         }
11112     }
11113
11114
11115   /* 14.1.2 A module or internal procedure represent local entities
11116      of the same type as a namelist member and so are not allowed.  */
11117   for (nl = sym->namelist; nl; nl = nl->next)
11118     {
11119       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
11120         continue;
11121
11122       if (nl->sym->attr.function && nl->sym == nl->sym->result)
11123         if ((nl->sym == sym->ns->proc_name)
11124                ||
11125             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
11126           continue;
11127
11128       nlsym = NULL;
11129       if (nl->sym && nl->sym->name)
11130         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
11131       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
11132         {
11133           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
11134                      "attribute in '%s' at %L", nlsym->name,
11135                      &sym->declared_at);
11136           return FAILURE;
11137         }
11138     }
11139
11140   return SUCCESS;
11141 }
11142
11143
11144 static gfc_try
11145 resolve_fl_parameter (gfc_symbol *sym)
11146 {
11147   /* A parameter array's shape needs to be constant.  */
11148   if (sym->as != NULL 
11149       && (sym->as->type == AS_DEFERRED
11150           || is_non_constant_shape_array (sym)))
11151     {
11152       gfc_error ("Parameter array '%s' at %L cannot be automatic "
11153                  "or of deferred shape", sym->name, &sym->declared_at);
11154       return FAILURE;
11155     }
11156
11157   /* Make sure a parameter that has been implicitly typed still
11158      matches the implicit type, since PARAMETER statements can precede
11159      IMPLICIT statements.  */
11160   if (sym->attr.implicit_type
11161       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
11162                                                              sym->ns)))
11163     {
11164       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
11165                  "later IMPLICIT type", sym->name, &sym->declared_at);
11166       return FAILURE;
11167     }
11168
11169   /* Make sure the types of derived parameters are consistent.  This
11170      type checking is deferred until resolution because the type may
11171      refer to a derived type from the host.  */
11172   if (sym->ts.type == BT_DERIVED
11173       && !gfc_compare_types (&sym->ts, &sym->value->ts))
11174     {
11175       gfc_error ("Incompatible derived type in PARAMETER at %L",
11176                  &sym->value->where);
11177       return FAILURE;
11178     }
11179   return SUCCESS;
11180 }
11181
11182
11183 /* Do anything necessary to resolve a symbol.  Right now, we just
11184    assume that an otherwise unknown symbol is a variable.  This sort
11185    of thing commonly happens for symbols in module.  */
11186
11187 static void
11188 resolve_symbol (gfc_symbol *sym)
11189 {
11190   int check_constant, mp_flag;
11191   gfc_symtree *symtree;
11192   gfc_symtree *this_symtree;
11193   gfc_namespace *ns;
11194   gfc_component *c;
11195
11196   if (sym->attr.flavor == FL_UNKNOWN)
11197     {
11198
11199     /* If we find that a flavorless symbol is an interface in one of the
11200        parent namespaces, find its symtree in this namespace, free the
11201        symbol and set the symtree to point to the interface symbol.  */
11202       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
11203         {
11204           symtree = gfc_find_symtree (ns->sym_root, sym->name);
11205           if (symtree && symtree->n.sym->generic)
11206             {
11207               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
11208                                                sym->name);
11209               sym->refs--;
11210               if (!sym->refs)
11211                 gfc_free_symbol (sym);
11212               symtree->n.sym->refs++;
11213               this_symtree->n.sym = symtree->n.sym;
11214               return;
11215             }
11216         }
11217
11218       /* Otherwise give it a flavor according to such attributes as
11219          it has.  */
11220       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
11221         sym->attr.flavor = FL_VARIABLE;
11222       else
11223         {
11224           sym->attr.flavor = FL_PROCEDURE;
11225           if (sym->attr.dimension)
11226             sym->attr.function = 1;
11227         }
11228     }
11229
11230   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
11231     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
11232
11233   if (sym->attr.procedure && sym->ts.interface
11234       && sym->attr.if_source != IFSRC_DECL)
11235     {
11236       if (sym->ts.interface == sym)
11237         {
11238           gfc_error ("PROCEDURE '%s' at %L may not be used as its own "
11239                      "interface", sym->name, &sym->declared_at);
11240           return;
11241         }
11242       if (sym->ts.interface->attr.procedure)
11243         {
11244           gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared"
11245                      " in a later PROCEDURE statement", sym->ts.interface->name,
11246                      sym->name,&sym->declared_at);
11247           return;
11248         }
11249
11250       /* Get the attributes from the interface (now resolved).  */
11251       if (sym->ts.interface->attr.if_source
11252           || sym->ts.interface->attr.intrinsic)
11253         {
11254           gfc_symbol *ifc = sym->ts.interface;
11255           resolve_symbol (ifc);
11256
11257           if (ifc->attr.intrinsic)
11258             resolve_intrinsic (ifc, &ifc->declared_at);
11259
11260           if (ifc->result)
11261             sym->ts = ifc->result->ts;
11262           else   
11263             sym->ts = ifc->ts;
11264           sym->ts.interface = ifc;
11265           sym->attr.function = ifc->attr.function;
11266           sym->attr.subroutine = ifc->attr.subroutine;
11267           gfc_copy_formal_args (sym, ifc);
11268
11269           sym->attr.allocatable = ifc->attr.allocatable;
11270           sym->attr.pointer = ifc->attr.pointer;
11271           sym->attr.pure = ifc->attr.pure;
11272           sym->attr.elemental = ifc->attr.elemental;
11273           sym->attr.dimension = ifc->attr.dimension;
11274           sym->attr.recursive = ifc->attr.recursive;
11275           sym->attr.always_explicit = ifc->attr.always_explicit;
11276           sym->attr.ext_attr |= ifc->attr.ext_attr;
11277           /* Copy array spec.  */
11278           sym->as = gfc_copy_array_spec (ifc->as);
11279           if (sym->as)
11280             {
11281               int i;
11282               for (i = 0; i < sym->as->rank; i++)
11283                 {
11284                   gfc_expr_replace_symbols (sym->as->lower[i], sym);
11285                   gfc_expr_replace_symbols (sym->as->upper[i], sym);
11286                 }
11287             }
11288           /* Copy char length.  */
11289           if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
11290             {
11291               sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
11292               gfc_expr_replace_symbols (sym->ts.u.cl->length, sym);
11293             }
11294         }
11295       else if (sym->ts.interface->name[0] != '\0')
11296         {
11297           gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
11298                     sym->ts.interface->name, sym->name, &sym->declared_at);
11299           return;
11300         }
11301     }
11302
11303   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
11304     return;
11305
11306   /* Symbols that are module procedures with results (functions) have
11307      the types and array specification copied for type checking in
11308      procedures that call them, as well as for saving to a module
11309      file.  These symbols can't stand the scrutiny that their results
11310      can.  */
11311   mp_flag = (sym->result != NULL && sym->result != sym);
11312
11313
11314   /* Make sure that the intrinsic is consistent with its internal 
11315      representation. This needs to be done before assigning a default 
11316      type to avoid spurious warnings.  */
11317   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
11318       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
11319     return;
11320
11321   /* Assign default type to symbols that need one and don't have one.  */
11322   if (sym->ts.type == BT_UNKNOWN)
11323     {
11324       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
11325         gfc_set_default_type (sym, 1, NULL);
11326
11327       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
11328           && !sym->attr.function && !sym->attr.subroutine
11329           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
11330         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
11331
11332       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
11333         {
11334           /* The specific case of an external procedure should emit an error
11335              in the case that there is no implicit type.  */
11336           if (!mp_flag)
11337             gfc_set_default_type (sym, sym->attr.external, NULL);
11338           else
11339             {
11340               /* Result may be in another namespace.  */
11341               resolve_symbol (sym->result);
11342
11343               if (!sym->result->attr.proc_pointer)
11344                 {
11345                   sym->ts = sym->result->ts;
11346                   sym->as = gfc_copy_array_spec (sym->result->as);
11347                   sym->attr.dimension = sym->result->attr.dimension;
11348                   sym->attr.pointer = sym->result->attr.pointer;
11349                   sym->attr.allocatable = sym->result->attr.allocatable;
11350                 }
11351             }
11352         }
11353     }
11354
11355   /* Assumed size arrays and assumed shape arrays must be dummy
11356      arguments.  */
11357
11358   if (sym->as != NULL
11359       && ((sym->as->type == AS_ASSUMED_SIZE && !sym->as->cp_was_assumed)
11360           || sym->as->type == AS_ASSUMED_SHAPE)
11361       && sym->attr.dummy == 0)
11362     {
11363       if (sym->as->type == AS_ASSUMED_SIZE)
11364         gfc_error ("Assumed size array at %L must be a dummy argument",
11365                    &sym->declared_at);
11366       else
11367         gfc_error ("Assumed shape array at %L must be a dummy argument",
11368                    &sym->declared_at);
11369       return;
11370     }
11371
11372   /* Make sure symbols with known intent or optional are really dummy
11373      variable.  Because of ENTRY statement, this has to be deferred
11374      until resolution time.  */
11375
11376   if (!sym->attr.dummy
11377       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
11378     {
11379       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
11380       return;
11381     }
11382
11383   if (sym->attr.value && !sym->attr.dummy)
11384     {
11385       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
11386                  "it is not a dummy argument", sym->name, &sym->declared_at);
11387       return;
11388     }
11389
11390   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
11391     {
11392       gfc_charlen *cl = sym->ts.u.cl;
11393       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
11394         {
11395           gfc_error ("Character dummy variable '%s' at %L with VALUE "
11396                      "attribute must have constant length",
11397                      sym->name, &sym->declared_at);
11398           return;
11399         }
11400
11401       if (sym->ts.is_c_interop
11402           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
11403         {
11404           gfc_error ("C interoperable character dummy variable '%s' at %L "
11405                      "with VALUE attribute must have length one",
11406                      sym->name, &sym->declared_at);
11407           return;
11408         }
11409     }
11410
11411   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
11412      do this for something that was implicitly typed because that is handled
11413      in gfc_set_default_type.  Handle dummy arguments and procedure
11414      definitions separately.  Also, anything that is use associated is not
11415      handled here but instead is handled in the module it is declared in.
11416      Finally, derived type definitions are allowed to be BIND(C) since that
11417      only implies that they're interoperable, and they are checked fully for
11418      interoperability when a variable is declared of that type.  */
11419   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
11420       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
11421       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
11422     {
11423       gfc_try t = SUCCESS;
11424       
11425       /* First, make sure the variable is declared at the
11426          module-level scope (J3/04-007, Section 15.3).  */
11427       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
11428           sym->attr.in_common == 0)
11429         {
11430           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
11431                      "is neither a COMMON block nor declared at the "
11432                      "module level scope", sym->name, &(sym->declared_at));
11433           t = FAILURE;
11434         }
11435       else if (sym->common_head != NULL)
11436         {
11437           t = verify_com_block_vars_c_interop (sym->common_head);
11438         }
11439       else
11440         {
11441           /* If type() declaration, we need to verify that the components
11442              of the given type are all C interoperable, etc.  */
11443           if (sym->ts.type == BT_DERIVED &&
11444               sym->ts.u.derived->attr.is_c_interop != 1)
11445             {
11446               /* Make sure the user marked the derived type as BIND(C).  If
11447                  not, call the verify routine.  This could print an error
11448                  for the derived type more than once if multiple variables
11449                  of that type are declared.  */
11450               if (sym->ts.u.derived->attr.is_bind_c != 1)
11451                 verify_bind_c_derived_type (sym->ts.u.derived);
11452               t = FAILURE;
11453             }
11454           
11455           /* Verify the variable itself as C interoperable if it
11456              is BIND(C).  It is not possible for this to succeed if
11457              the verify_bind_c_derived_type failed, so don't have to handle
11458              any error returned by verify_bind_c_derived_type.  */
11459           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
11460                                  sym->common_block);
11461         }
11462
11463       if (t == FAILURE)
11464         {
11465           /* clear the is_bind_c flag to prevent reporting errors more than
11466              once if something failed.  */
11467           sym->attr.is_bind_c = 0;
11468           return;
11469         }
11470     }
11471
11472   /* If a derived type symbol has reached this point, without its
11473      type being declared, we have an error.  Notice that most
11474      conditions that produce undefined derived types have already
11475      been dealt with.  However, the likes of:
11476      implicit type(t) (t) ..... call foo (t) will get us here if
11477      the type is not declared in the scope of the implicit
11478      statement. Change the type to BT_UNKNOWN, both because it is so
11479      and to prevent an ICE.  */
11480   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->components == NULL
11481       && !sym->ts.u.derived->attr.zero_comp)
11482     {
11483       gfc_error ("The derived type '%s' at %L is of type '%s', "
11484                  "which has not been defined", sym->name,
11485                   &sym->declared_at, sym->ts.u.derived->name);
11486       sym->ts.type = BT_UNKNOWN;
11487       return;
11488     }
11489
11490   /* Make sure that the derived type has been resolved and that the
11491      derived type is visible in the symbol's namespace, if it is a
11492      module function and is not PRIVATE.  */
11493   if (sym->ts.type == BT_DERIVED
11494         && sym->ts.u.derived->attr.use_assoc
11495         && sym->ns->proc_name
11496         && sym->ns->proc_name->attr.flavor == FL_MODULE)
11497     {
11498       gfc_symbol *ds;
11499
11500       if (resolve_fl_derived (sym->ts.u.derived) == FAILURE)
11501         return;
11502
11503       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 1, &ds);
11504       if (!ds && sym->attr.function
11505             && gfc_check_access (sym->attr.access, sym->ns->default_access))
11506         {
11507           symtree = gfc_new_symtree (&sym->ns->sym_root,
11508                                      sym->ts.u.derived->name);
11509           symtree->n.sym = sym->ts.u.derived;
11510           sym->ts.u.derived->refs++;
11511         }
11512     }
11513
11514   /* Unless the derived-type declaration is use associated, Fortran 95
11515      does not allow public entries of private derived types.
11516      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
11517      161 in 95-006r3.  */
11518   if (sym->ts.type == BT_DERIVED
11519       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
11520       && !sym->ts.u.derived->attr.use_assoc
11521       && gfc_check_access (sym->attr.access, sym->ns->default_access)
11522       && !gfc_check_access (sym->ts.u.derived->attr.access,
11523                             sym->ts.u.derived->ns->default_access)
11524       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
11525                          "of PRIVATE derived type '%s'",
11526                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
11527                          : "variable", sym->name, &sym->declared_at,
11528                          sym->ts.u.derived->name) == FAILURE)
11529     return;
11530
11531   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
11532      default initialization is defined (5.1.2.4.4).  */
11533   if (sym->ts.type == BT_DERIVED
11534       && sym->attr.dummy
11535       && sym->attr.intent == INTENT_OUT
11536       && sym->as
11537       && sym->as->type == AS_ASSUMED_SIZE)
11538     {
11539       for (c = sym->ts.u.derived->components; c; c = c->next)
11540         {
11541           if (c->initializer)
11542             {
11543               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
11544                          "ASSUMED SIZE and so cannot have a default initializer",
11545                          sym->name, &sym->declared_at);
11546               return;
11547             }
11548         }
11549     }
11550
11551   /* F2008, C526.  */
11552   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
11553        || sym->attr.codimension)
11554       && sym->attr.result)
11555     gfc_error ("Function result '%s' at %L shall not be a coarray or have "
11556                "a coarray component", sym->name, &sym->declared_at);
11557
11558   /* F2008, C524.  */
11559   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
11560       && sym->ts.u.derived->ts.is_iso_c)
11561     gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
11562                "shall not be a coarray", sym->name, &sym->declared_at);
11563
11564   /* F2008, C525.  */
11565   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp
11566       && (sym->attr.codimension || sym->attr.pointer || sym->attr.dimension
11567           || sym->attr.allocatable))
11568     gfc_error ("Variable '%s' at %L with coarray component "
11569                "shall be a nonpointer, nonallocatable scalar",
11570                sym->name, &sym->declared_at);
11571
11572   /* F2008, C526.  The function-result case was handled above.  */
11573   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
11574        || sym->attr.codimension)
11575       && !(sym->attr.allocatable || sym->attr.dummy || sym->attr.save
11576            || sym->ns->proc_name->attr.flavor == FL_MODULE
11577            || sym->ns->proc_name->attr.is_main_program
11578            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
11579     gfc_error ("Variable '%s' at %L is a coarray or has a coarray "
11580                "component and is not ALLOCATABLE, SAVE nor a "
11581                "dummy argument", sym->name, &sym->declared_at);
11582   /* F2008, C528.  */  /* FIXME: sym->as check due to PR 43412.  */
11583   else if (sym->attr.codimension && !sym->attr.allocatable
11584       && sym->as && sym->as->cotype == AS_DEFERRED)
11585     gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
11586                 "deferred shape", sym->name, &sym->declared_at);
11587   else if (sym->attr.codimension && sym->attr.allocatable
11588       && (sym->as->type != AS_DEFERRED || sym->as->cotype != AS_DEFERRED))
11589     gfc_error ("Allocatable coarray variable '%s' at %L must have "
11590                "deferred shape", sym->name, &sym->declared_at);
11591
11592
11593   /* F2008, C541.  */
11594   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
11595        || (sym->attr.codimension && sym->attr.allocatable))
11596       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
11597     gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
11598                "allocatable coarray or have coarray components",
11599                sym->name, &sym->declared_at);
11600
11601   if (sym->attr.codimension && sym->attr.dummy
11602       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
11603     gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
11604                "procedure '%s'", sym->name, &sym->declared_at,
11605                sym->ns->proc_name->name);
11606
11607   switch (sym->attr.flavor)
11608     {
11609     case FL_VARIABLE:
11610       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
11611         return;
11612       break;
11613
11614     case FL_PROCEDURE:
11615       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
11616         return;
11617       break;
11618
11619     case FL_NAMELIST:
11620       if (resolve_fl_namelist (sym) == FAILURE)
11621         return;
11622       break;
11623
11624     case FL_PARAMETER:
11625       if (resolve_fl_parameter (sym) == FAILURE)
11626         return;
11627       break;
11628
11629     default:
11630       break;
11631     }
11632
11633   /* Resolve array specifier. Check as well some constraints
11634      on COMMON blocks.  */
11635
11636   check_constant = sym->attr.in_common && !sym->attr.pointer;
11637
11638   /* Set the formal_arg_flag so that check_conflict will not throw
11639      an error for host associated variables in the specification
11640      expression for an array_valued function.  */
11641   if (sym->attr.function && sym->as)
11642     formal_arg_flag = 1;
11643
11644   gfc_resolve_array_spec (sym->as, check_constant);
11645
11646   formal_arg_flag = 0;
11647
11648   /* Resolve formal namespaces.  */
11649   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
11650       && !sym->attr.contained && !sym->attr.intrinsic)
11651     gfc_resolve (sym->formal_ns);
11652
11653   /* Make sure the formal namespace is present.  */
11654   if (sym->formal && !sym->formal_ns)
11655     {
11656       gfc_formal_arglist *formal = sym->formal;
11657       while (formal && !formal->sym)
11658         formal = formal->next;
11659
11660       if (formal)
11661         {
11662           sym->formal_ns = formal->sym->ns;
11663           sym->formal_ns->refs++;
11664         }
11665     }
11666
11667   /* Check threadprivate restrictions.  */
11668   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
11669       && (!sym->attr.in_common
11670           && sym->module == NULL
11671           && (sym->ns->proc_name == NULL
11672               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
11673     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
11674
11675   /* If we have come this far we can apply default-initializers, as
11676      described in 14.7.5, to those variables that have not already
11677      been assigned one.  */
11678   if (sym->ts.type == BT_DERIVED
11679       && sym->attr.referenced
11680       && sym->ns == gfc_current_ns
11681       && !sym->value
11682       && !sym->attr.allocatable
11683       && !sym->attr.alloc_comp)
11684     {
11685       symbol_attribute *a = &sym->attr;
11686
11687       if ((!a->save && !a->dummy && !a->pointer
11688            && !a->in_common && !a->use_assoc
11689            && !(a->function && sym != sym->result))
11690           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
11691         apply_default_init (sym);
11692     }
11693
11694   /* If this symbol has a type-spec, check it.  */
11695   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
11696       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
11697     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
11698           == FAILURE)
11699       return;
11700 }
11701
11702
11703 /************* Resolve DATA statements *************/
11704
11705 static struct
11706 {
11707   gfc_data_value *vnode;
11708   mpz_t left;
11709 }
11710 values;
11711
11712
11713 /* Advance the values structure to point to the next value in the data list.  */
11714
11715 static gfc_try
11716 next_data_value (void)
11717 {
11718   while (mpz_cmp_ui (values.left, 0) == 0)
11719     {
11720
11721       if (values.vnode->next == NULL)
11722         return FAILURE;
11723
11724       values.vnode = values.vnode->next;
11725       mpz_set (values.left, values.vnode->repeat);
11726     }
11727
11728   return SUCCESS;
11729 }
11730
11731
11732 static gfc_try
11733 check_data_variable (gfc_data_variable *var, locus *where)
11734 {
11735   gfc_expr *e;
11736   mpz_t size;
11737   mpz_t offset;
11738   gfc_try t;
11739   ar_type mark = AR_UNKNOWN;
11740   int i;
11741   mpz_t section_index[GFC_MAX_DIMENSIONS];
11742   gfc_ref *ref;
11743   gfc_array_ref *ar;
11744   gfc_symbol *sym;
11745   int has_pointer;
11746
11747   if (gfc_resolve_expr (var->expr) == FAILURE)
11748     return FAILURE;
11749
11750   ar = NULL;
11751   mpz_init_set_si (offset, 0);
11752   e = var->expr;
11753
11754   if (e->expr_type != EXPR_VARIABLE)
11755     gfc_internal_error ("check_data_variable(): Bad expression");
11756
11757   sym = e->symtree->n.sym;
11758
11759   if (sym->ns->is_block_data && !sym->attr.in_common)
11760     {
11761       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
11762                  sym->name, &sym->declared_at);
11763     }
11764
11765   if (e->ref == NULL && sym->as)
11766     {
11767       gfc_error ("DATA array '%s' at %L must be specified in a previous"
11768                  " declaration", sym->name, where);
11769       return FAILURE;
11770     }
11771
11772   has_pointer = sym->attr.pointer;
11773
11774   for (ref = e->ref; ref; ref = ref->next)
11775     {
11776       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
11777         has_pointer = 1;
11778
11779       if (ref->type == REF_ARRAY && ref->u.ar.codimen)
11780         {
11781           gfc_error ("DATA element '%s' at %L cannot have a coindex",
11782                      sym->name, where);
11783           return FAILURE;
11784         }
11785
11786       if (has_pointer
11787             && ref->type == REF_ARRAY
11788             && ref->u.ar.type != AR_FULL)
11789           {
11790             gfc_error ("DATA element '%s' at %L is a pointer and so must "
11791                         "be a full array", sym->name, where);
11792             return FAILURE;
11793           }
11794     }
11795
11796   if (e->rank == 0 || has_pointer)
11797     {
11798       mpz_init_set_ui (size, 1);
11799       ref = NULL;
11800     }
11801   else
11802     {
11803       ref = e->ref;
11804
11805       /* Find the array section reference.  */
11806       for (ref = e->ref; ref; ref = ref->next)
11807         {
11808           if (ref->type != REF_ARRAY)
11809             continue;
11810           if (ref->u.ar.type == AR_ELEMENT)
11811             continue;
11812           break;
11813         }
11814       gcc_assert (ref);
11815
11816       /* Set marks according to the reference pattern.  */
11817       switch (ref->u.ar.type)
11818         {
11819         case AR_FULL:
11820           mark = AR_FULL;
11821           break;
11822
11823         case AR_SECTION:
11824           ar = &ref->u.ar;
11825           /* Get the start position of array section.  */
11826           gfc_get_section_index (ar, section_index, &offset);
11827           mark = AR_SECTION;
11828           break;
11829
11830         default:
11831           gcc_unreachable ();
11832         }
11833
11834       if (gfc_array_size (e, &size) == FAILURE)
11835         {
11836           gfc_error ("Nonconstant array section at %L in DATA statement",
11837                      &e->where);
11838           mpz_clear (offset);
11839           return FAILURE;
11840         }
11841     }
11842
11843   t = SUCCESS;
11844
11845   while (mpz_cmp_ui (size, 0) > 0)
11846     {
11847       if (next_data_value () == FAILURE)
11848         {
11849           gfc_error ("DATA statement at %L has more variables than values",
11850                      where);
11851           t = FAILURE;
11852           break;
11853         }
11854
11855       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
11856       if (t == FAILURE)
11857         break;
11858
11859       /* If we have more than one element left in the repeat count,
11860          and we have more than one element left in the target variable,
11861          then create a range assignment.  */
11862       /* FIXME: Only done for full arrays for now, since array sections
11863          seem tricky.  */
11864       if (mark == AR_FULL && ref && ref->next == NULL
11865           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
11866         {
11867           mpz_t range;
11868
11869           if (mpz_cmp (size, values.left) >= 0)
11870             {
11871               mpz_init_set (range, values.left);
11872               mpz_sub (size, size, values.left);
11873               mpz_set_ui (values.left, 0);
11874             }
11875           else
11876             {
11877               mpz_init_set (range, size);
11878               mpz_sub (values.left, values.left, size);
11879               mpz_set_ui (size, 0);
11880             }
11881
11882           gfc_assign_data_value_range (var->expr, values.vnode->expr,
11883                                        offset, range);
11884
11885           mpz_add (offset, offset, range);
11886           mpz_clear (range);
11887         }
11888
11889       /* Assign initial value to symbol.  */
11890       else
11891         {
11892           mpz_sub_ui (values.left, values.left, 1);
11893           mpz_sub_ui (size, size, 1);
11894
11895           t = gfc_assign_data_value (var->expr, values.vnode->expr, offset);
11896           if (t == FAILURE)
11897             break;
11898
11899           if (mark == AR_FULL)
11900             mpz_add_ui (offset, offset, 1);
11901
11902           /* Modify the array section indexes and recalculate the offset
11903              for next element.  */
11904           else if (mark == AR_SECTION)
11905             gfc_advance_section (section_index, ar, &offset);
11906         }
11907     }
11908
11909   if (mark == AR_SECTION)
11910     {
11911       for (i = 0; i < ar->dimen; i++)
11912         mpz_clear (section_index[i]);
11913     }
11914
11915   mpz_clear (size);
11916   mpz_clear (offset);
11917
11918   return t;
11919 }
11920
11921
11922 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
11923
11924 /* Iterate over a list of elements in a DATA statement.  */
11925
11926 static gfc_try
11927 traverse_data_list (gfc_data_variable *var, locus *where)
11928 {
11929   mpz_t trip;
11930   iterator_stack frame;
11931   gfc_expr *e, *start, *end, *step;
11932   gfc_try retval = SUCCESS;
11933
11934   mpz_init (frame.value);
11935
11936   start = gfc_copy_expr (var->iter.start);
11937   end = gfc_copy_expr (var->iter.end);
11938   step = gfc_copy_expr (var->iter.step);
11939
11940   if (gfc_simplify_expr (start, 1) == FAILURE
11941       || start->expr_type != EXPR_CONSTANT)
11942     {
11943       gfc_error ("iterator start at %L does not simplify", &start->where);
11944       retval = FAILURE;
11945       goto cleanup;
11946     }
11947   if (gfc_simplify_expr (end, 1) == FAILURE
11948       || end->expr_type != EXPR_CONSTANT)
11949     {
11950       gfc_error ("iterator end at %L does not simplify", &end->where);
11951       retval = FAILURE;
11952       goto cleanup;
11953     }
11954   if (gfc_simplify_expr (step, 1) == FAILURE
11955       || step->expr_type != EXPR_CONSTANT)
11956     {
11957       gfc_error ("iterator step at %L does not simplify", &step->where);
11958       retval = FAILURE;
11959       goto cleanup;
11960     }
11961
11962   mpz_init_set (trip, end->value.integer);
11963   mpz_sub (trip, trip, start->value.integer);
11964   mpz_add (trip, trip, step->value.integer);
11965
11966   mpz_div (trip, trip, step->value.integer);
11967
11968   mpz_set (frame.value, start->value.integer);
11969
11970   frame.prev = iter_stack;
11971   frame.variable = var->iter.var->symtree;
11972   iter_stack = &frame;
11973
11974   while (mpz_cmp_ui (trip, 0) > 0)
11975     {
11976       if (traverse_data_var (var->list, where) == FAILURE)
11977         {
11978           mpz_clear (trip);
11979           retval = FAILURE;
11980           goto cleanup;
11981         }
11982
11983       e = gfc_copy_expr (var->expr);
11984       if (gfc_simplify_expr (e, 1) == FAILURE)
11985         {
11986           gfc_free_expr (e);
11987           mpz_clear (trip);
11988           retval = FAILURE;
11989           goto cleanup;
11990         }
11991
11992       mpz_add (frame.value, frame.value, step->value.integer);
11993
11994       mpz_sub_ui (trip, trip, 1);
11995     }
11996
11997   mpz_clear (trip);
11998 cleanup:
11999   mpz_clear (frame.value);
12000
12001   gfc_free_expr (start);
12002   gfc_free_expr (end);
12003   gfc_free_expr (step);
12004
12005   iter_stack = frame.prev;
12006   return retval;
12007 }
12008
12009
12010 /* Type resolve variables in the variable list of a DATA statement.  */
12011
12012 static gfc_try
12013 traverse_data_var (gfc_data_variable *var, locus *where)
12014 {
12015   gfc_try t;
12016
12017   for (; var; var = var->next)
12018     {
12019       if (var->expr == NULL)
12020         t = traverse_data_list (var, where);
12021       else
12022         t = check_data_variable (var, where);
12023
12024       if (t == FAILURE)
12025         return FAILURE;
12026     }
12027
12028   return SUCCESS;
12029 }
12030
12031
12032 /* Resolve the expressions and iterators associated with a data statement.
12033    This is separate from the assignment checking because data lists should
12034    only be resolved once.  */
12035
12036 static gfc_try
12037 resolve_data_variables (gfc_data_variable *d)
12038 {
12039   for (; d; d = d->next)
12040     {
12041       if (d->list == NULL)
12042         {
12043           if (gfc_resolve_expr (d->expr) == FAILURE)
12044             return FAILURE;
12045         }
12046       else
12047         {
12048           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
12049             return FAILURE;
12050
12051           if (resolve_data_variables (d->list) == FAILURE)
12052             return FAILURE;
12053         }
12054     }
12055
12056   return SUCCESS;
12057 }
12058
12059
12060 /* Resolve a single DATA statement.  We implement this by storing a pointer to
12061    the value list into static variables, and then recursively traversing the
12062    variables list, expanding iterators and such.  */
12063
12064 static void
12065 resolve_data (gfc_data *d)
12066 {
12067
12068   if (resolve_data_variables (d->var) == FAILURE)
12069     return;
12070
12071   values.vnode = d->value;
12072   if (d->value == NULL)
12073     mpz_set_ui (values.left, 0);
12074   else
12075     mpz_set (values.left, d->value->repeat);
12076
12077   if (traverse_data_var (d->var, &d->where) == FAILURE)
12078     return;
12079
12080   /* At this point, we better not have any values left.  */
12081
12082   if (next_data_value () == SUCCESS)
12083     gfc_error ("DATA statement at %L has more values than variables",
12084                &d->where);
12085 }
12086
12087
12088 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
12089    accessed by host or use association, is a dummy argument to a pure function,
12090    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
12091    is storage associated with any such variable, shall not be used in the
12092    following contexts: (clients of this function).  */
12093
12094 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
12095    procedure.  Returns zero if assignment is OK, nonzero if there is a
12096    problem.  */
12097 int
12098 gfc_impure_variable (gfc_symbol *sym)
12099 {
12100   gfc_symbol *proc;
12101   gfc_namespace *ns;
12102
12103   if (sym->attr.use_assoc || sym->attr.in_common)
12104     return 1;
12105
12106   /* Check if the symbol's ns is inside the pure procedure.  */
12107   for (ns = gfc_current_ns; ns; ns = ns->parent)
12108     {
12109       if (ns == sym->ns)
12110         break;
12111       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
12112         return 1;
12113     }
12114
12115   proc = sym->ns->proc_name;
12116   if (sym->attr.dummy && gfc_pure (proc)
12117         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
12118                 ||
12119              proc->attr.function))
12120     return 1;
12121
12122   /* TODO: Sort out what can be storage associated, if anything, and include
12123      it here.  In principle equivalences should be scanned but it does not
12124      seem to be possible to storage associate an impure variable this way.  */
12125   return 0;
12126 }
12127
12128
12129 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
12130    current namespace is inside a pure procedure.  */
12131
12132 int
12133 gfc_pure (gfc_symbol *sym)
12134 {
12135   symbol_attribute attr;
12136   gfc_namespace *ns;
12137
12138   if (sym == NULL)
12139     {
12140       /* Check if the current namespace or one of its parents
12141         belongs to a pure procedure.  */
12142       for (ns = gfc_current_ns; ns; ns = ns->parent)
12143         {
12144           sym = ns->proc_name;
12145           if (sym == NULL)
12146             return 0;
12147           attr = sym->attr;
12148           if (attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental))
12149             return 1;
12150         }
12151       return 0;
12152     }
12153
12154   attr = sym->attr;
12155
12156   return attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental);
12157 }
12158
12159
12160 /* Test whether the current procedure is elemental or not.  */
12161
12162 int
12163 gfc_elemental (gfc_symbol *sym)
12164 {
12165   symbol_attribute attr;
12166
12167   if (sym == NULL)
12168     sym = gfc_current_ns->proc_name;
12169   if (sym == NULL)
12170     return 0;
12171   attr = sym->attr;
12172
12173   return attr.flavor == FL_PROCEDURE && attr.elemental;
12174 }
12175
12176
12177 /* Warn about unused labels.  */
12178
12179 static void
12180 warn_unused_fortran_label (gfc_st_label *label)
12181 {
12182   if (label == NULL)
12183     return;
12184
12185   warn_unused_fortran_label (label->left);
12186
12187   if (label->defined == ST_LABEL_UNKNOWN)
12188     return;
12189
12190   switch (label->referenced)
12191     {
12192     case ST_LABEL_UNKNOWN:
12193       gfc_warning ("Label %d at %L defined but not used", label->value,
12194                    &label->where);
12195       break;
12196
12197     case ST_LABEL_BAD_TARGET:
12198       gfc_warning ("Label %d at %L defined but cannot be used",
12199                    label->value, &label->where);
12200       break;
12201
12202     default:
12203       break;
12204     }
12205
12206   warn_unused_fortran_label (label->right);
12207 }
12208
12209
12210 /* Returns the sequence type of a symbol or sequence.  */
12211
12212 static seq_type
12213 sequence_type (gfc_typespec ts)
12214 {
12215   seq_type result;
12216   gfc_component *c;
12217
12218   switch (ts.type)
12219   {
12220     case BT_DERIVED:
12221
12222       if (ts.u.derived->components == NULL)
12223         return SEQ_NONDEFAULT;
12224
12225       result = sequence_type (ts.u.derived->components->ts);
12226       for (c = ts.u.derived->components->next; c; c = c->next)
12227         if (sequence_type (c->ts) != result)
12228           return SEQ_MIXED;
12229
12230       return result;
12231
12232     case BT_CHARACTER:
12233       if (ts.kind != gfc_default_character_kind)
12234           return SEQ_NONDEFAULT;
12235
12236       return SEQ_CHARACTER;
12237
12238     case BT_INTEGER:
12239       if (ts.kind != gfc_default_integer_kind)
12240           return SEQ_NONDEFAULT;
12241
12242       return SEQ_NUMERIC;
12243
12244     case BT_REAL:
12245       if (!(ts.kind == gfc_default_real_kind
12246             || ts.kind == gfc_default_double_kind))
12247           return SEQ_NONDEFAULT;
12248
12249       return SEQ_NUMERIC;
12250
12251     case BT_COMPLEX:
12252       if (ts.kind != gfc_default_complex_kind)
12253           return SEQ_NONDEFAULT;
12254
12255       return SEQ_NUMERIC;
12256
12257     case BT_LOGICAL:
12258       if (ts.kind != gfc_default_logical_kind)
12259           return SEQ_NONDEFAULT;
12260
12261       return SEQ_NUMERIC;
12262
12263     default:
12264       return SEQ_NONDEFAULT;
12265   }
12266 }
12267
12268
12269 /* Resolve derived type EQUIVALENCE object.  */
12270
12271 static gfc_try
12272 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
12273 {
12274   gfc_component *c = derived->components;
12275
12276   if (!derived)
12277     return SUCCESS;
12278
12279   /* Shall not be an object of nonsequence derived type.  */
12280   if (!derived->attr.sequence)
12281     {
12282       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
12283                  "attribute to be an EQUIVALENCE object", sym->name,
12284                  &e->where);
12285       return FAILURE;
12286     }
12287
12288   /* Shall not have allocatable components.  */
12289   if (derived->attr.alloc_comp)
12290     {
12291       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
12292                  "components to be an EQUIVALENCE object",sym->name,
12293                  &e->where);
12294       return FAILURE;
12295     }
12296
12297   if (sym->attr.in_common && has_default_initializer (sym->ts.u.derived))
12298     {
12299       gfc_error ("Derived type variable '%s' at %L with default "
12300                  "initialization cannot be in EQUIVALENCE with a variable "
12301                  "in COMMON", sym->name, &e->where);
12302       return FAILURE;
12303     }
12304
12305   for (; c ; c = c->next)
12306     {
12307       if (c->ts.type == BT_DERIVED
12308           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
12309         return FAILURE;
12310
12311       /* Shall not be an object of sequence derived type containing a pointer
12312          in the structure.  */
12313       if (c->attr.pointer)
12314         {
12315           gfc_error ("Derived type variable '%s' at %L with pointer "
12316                      "component(s) cannot be an EQUIVALENCE object",
12317                      sym->name, &e->where);
12318           return FAILURE;
12319         }
12320     }
12321   return SUCCESS;
12322 }
12323
12324
12325 /* Resolve equivalence object. 
12326    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
12327    an allocatable array, an object of nonsequence derived type, an object of
12328    sequence derived type containing a pointer at any level of component
12329    selection, an automatic object, a function name, an entry name, a result
12330    name, a named constant, a structure component, or a subobject of any of
12331    the preceding objects.  A substring shall not have length zero.  A
12332    derived type shall not have components with default initialization nor
12333    shall two objects of an equivalence group be initialized.
12334    Either all or none of the objects shall have an protected attribute.
12335    The simple constraints are done in symbol.c(check_conflict) and the rest
12336    are implemented here.  */
12337
12338 static void
12339 resolve_equivalence (gfc_equiv *eq)
12340 {
12341   gfc_symbol *sym;
12342   gfc_symbol *first_sym;
12343   gfc_expr *e;
12344   gfc_ref *r;
12345   locus *last_where = NULL;
12346   seq_type eq_type, last_eq_type;
12347   gfc_typespec *last_ts;
12348   int object, cnt_protected;
12349   const char *msg;
12350
12351   last_ts = &eq->expr->symtree->n.sym->ts;
12352
12353   first_sym = eq->expr->symtree->n.sym;
12354
12355   cnt_protected = 0;
12356
12357   for (object = 1; eq; eq = eq->eq, object++)
12358     {
12359       e = eq->expr;
12360
12361       e->ts = e->symtree->n.sym->ts;
12362       /* match_varspec might not know yet if it is seeing
12363          array reference or substring reference, as it doesn't
12364          know the types.  */
12365       if (e->ref && e->ref->type == REF_ARRAY)
12366         {
12367           gfc_ref *ref = e->ref;
12368           sym = e->symtree->n.sym;
12369
12370           if (sym->attr.dimension)
12371             {
12372               ref->u.ar.as = sym->as;
12373               ref = ref->next;
12374             }
12375
12376           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
12377           if (e->ts.type == BT_CHARACTER
12378               && ref
12379               && ref->type == REF_ARRAY
12380               && ref->u.ar.dimen == 1
12381               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
12382               && ref->u.ar.stride[0] == NULL)
12383             {
12384               gfc_expr *start = ref->u.ar.start[0];
12385               gfc_expr *end = ref->u.ar.end[0];
12386               void *mem = NULL;
12387
12388               /* Optimize away the (:) reference.  */
12389               if (start == NULL && end == NULL)
12390                 {
12391                   if (e->ref == ref)
12392                     e->ref = ref->next;
12393                   else
12394                     e->ref->next = ref->next;
12395                   mem = ref;
12396                 }
12397               else
12398                 {
12399                   ref->type = REF_SUBSTRING;
12400                   if (start == NULL)
12401                     start = gfc_int_expr (1);
12402                   ref->u.ss.start = start;
12403                   if (end == NULL && e->ts.u.cl)
12404                     end = gfc_copy_expr (e->ts.u.cl->length);
12405                   ref->u.ss.end = end;
12406                   ref->u.ss.length = e->ts.u.cl;
12407                   e->ts.u.cl = NULL;
12408                 }
12409               ref = ref->next;
12410               gfc_free (mem);
12411             }
12412
12413           /* Any further ref is an error.  */
12414           if (ref)
12415             {
12416               gcc_assert (ref->type == REF_ARRAY);
12417               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
12418                          &ref->u.ar.where);
12419               continue;
12420             }
12421         }
12422
12423       if (gfc_resolve_expr (e) == FAILURE)
12424         continue;
12425
12426       sym = e->symtree->n.sym;
12427
12428       if (sym->attr.is_protected)
12429         cnt_protected++;
12430       if (cnt_protected > 0 && cnt_protected != object)
12431         {
12432               gfc_error ("Either all or none of the objects in the "
12433                          "EQUIVALENCE set at %L shall have the "
12434                          "PROTECTED attribute",
12435                          &e->where);
12436               break;
12437         }
12438
12439       /* Shall not equivalence common block variables in a PURE procedure.  */
12440       if (sym->ns->proc_name
12441           && sym->ns->proc_name->attr.pure
12442           && sym->attr.in_common)
12443         {
12444           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
12445                      "object in the pure procedure '%s'",
12446                      sym->name, &e->where, sym->ns->proc_name->name);
12447           break;
12448         }
12449
12450       /* Shall not be a named constant.  */
12451       if (e->expr_type == EXPR_CONSTANT)
12452         {
12453           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
12454                      "object", sym->name, &e->where);
12455           continue;
12456         }
12457
12458       if (e->ts.type == BT_DERIVED
12459           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
12460         continue;
12461
12462       /* Check that the types correspond correctly:
12463          Note 5.28:
12464          A numeric sequence structure may be equivalenced to another sequence
12465          structure, an object of default integer type, default real type, double
12466          precision real type, default logical type such that components of the
12467          structure ultimately only become associated to objects of the same
12468          kind. A character sequence structure may be equivalenced to an object
12469          of default character kind or another character sequence structure.
12470          Other objects may be equivalenced only to objects of the same type and
12471          kind parameters.  */
12472
12473       /* Identical types are unconditionally OK.  */
12474       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
12475         goto identical_types;
12476
12477       last_eq_type = sequence_type (*last_ts);
12478       eq_type = sequence_type (sym->ts);
12479
12480       /* Since the pair of objects is not of the same type, mixed or
12481          non-default sequences can be rejected.  */
12482
12483       msg = "Sequence %s with mixed components in EQUIVALENCE "
12484             "statement at %L with different type objects";
12485       if ((object ==2
12486            && last_eq_type == SEQ_MIXED
12487            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
12488               == FAILURE)
12489           || (eq_type == SEQ_MIXED
12490               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12491                                  &e->where) == FAILURE))
12492         continue;
12493
12494       msg = "Non-default type object or sequence %s in EQUIVALENCE "
12495             "statement at %L with objects of different type";
12496       if ((object ==2
12497            && last_eq_type == SEQ_NONDEFAULT
12498            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
12499                               last_where) == FAILURE)
12500           || (eq_type == SEQ_NONDEFAULT
12501               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12502                                  &e->where) == FAILURE))
12503         continue;
12504
12505       msg ="Non-CHARACTER object '%s' in default CHARACTER "
12506            "EQUIVALENCE statement at %L";
12507       if (last_eq_type == SEQ_CHARACTER
12508           && eq_type != SEQ_CHARACTER
12509           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12510                              &e->where) == FAILURE)
12511                 continue;
12512
12513       msg ="Non-NUMERIC object '%s' in default NUMERIC "
12514            "EQUIVALENCE statement at %L";
12515       if (last_eq_type == SEQ_NUMERIC
12516           && eq_type != SEQ_NUMERIC
12517           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12518                              &e->where) == FAILURE)
12519                 continue;
12520
12521   identical_types:
12522       last_ts =&sym->ts;
12523       last_where = &e->where;
12524
12525       if (!e->ref)
12526         continue;
12527
12528       /* Shall not be an automatic array.  */
12529       if (e->ref->type == REF_ARRAY
12530           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
12531         {
12532           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
12533                      "an EQUIVALENCE object", sym->name, &e->where);
12534           continue;
12535         }
12536
12537       r = e->ref;
12538       while (r)
12539         {
12540           /* Shall not be a structure component.  */
12541           if (r->type == REF_COMPONENT)
12542             {
12543               gfc_error ("Structure component '%s' at %L cannot be an "
12544                          "EQUIVALENCE object",
12545                          r->u.c.component->name, &e->where);
12546               break;
12547             }
12548
12549           /* A substring shall not have length zero.  */
12550           if (r->type == REF_SUBSTRING)
12551             {
12552               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
12553                 {
12554                   gfc_error ("Substring at %L has length zero",
12555                              &r->u.ss.start->where);
12556                   break;
12557                 }
12558             }
12559           r = r->next;
12560         }
12561     }
12562 }
12563
12564
12565 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
12566
12567 static void
12568 resolve_fntype (gfc_namespace *ns)
12569 {
12570   gfc_entry_list *el;
12571   gfc_symbol *sym;
12572
12573   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
12574     return;
12575
12576   /* If there are any entries, ns->proc_name is the entry master
12577      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
12578   if (ns->entries)
12579     sym = ns->entries->sym;
12580   else
12581     sym = ns->proc_name;
12582   if (sym->result == sym
12583       && sym->ts.type == BT_UNKNOWN
12584       && gfc_set_default_type (sym, 0, NULL) == FAILURE
12585       && !sym->attr.untyped)
12586     {
12587       gfc_error ("Function '%s' at %L has no IMPLICIT type",
12588                  sym->name, &sym->declared_at);
12589       sym->attr.untyped = 1;
12590     }
12591
12592   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
12593       && !sym->attr.contained
12594       && !gfc_check_access (sym->ts.u.derived->attr.access,
12595                             sym->ts.u.derived->ns->default_access)
12596       && gfc_check_access (sym->attr.access, sym->ns->default_access))
12597     {
12598       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
12599                       "%L of PRIVATE type '%s'", sym->name,
12600                       &sym->declared_at, sym->ts.u.derived->name);
12601     }
12602
12603     if (ns->entries)
12604     for (el = ns->entries->next; el; el = el->next)
12605       {
12606         if (el->sym->result == el->sym
12607             && el->sym->ts.type == BT_UNKNOWN
12608             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
12609             && !el->sym->attr.untyped)
12610           {
12611             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
12612                        el->sym->name, &el->sym->declared_at);
12613             el->sym->attr.untyped = 1;
12614           }
12615       }
12616 }
12617
12618
12619 /* 12.3.2.1.1 Defined operators.  */
12620
12621 static gfc_try
12622 check_uop_procedure (gfc_symbol *sym, locus where)
12623 {
12624   gfc_formal_arglist *formal;
12625
12626   if (!sym->attr.function)
12627     {
12628       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
12629                  sym->name, &where);
12630       return FAILURE;
12631     }
12632
12633   if (sym->ts.type == BT_CHARACTER
12634       && !(sym->ts.u.cl && sym->ts.u.cl->length)
12635       && !(sym->result && sym->result->ts.u.cl
12636            && sym->result->ts.u.cl->length))
12637     {
12638       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
12639                  "character length", sym->name, &where);
12640       return FAILURE;
12641     }
12642
12643   formal = sym->formal;
12644   if (!formal || !formal->sym)
12645     {
12646       gfc_error ("User operator procedure '%s' at %L must have at least "
12647                  "one argument", sym->name, &where);
12648       return FAILURE;
12649     }
12650
12651   if (formal->sym->attr.intent != INTENT_IN)
12652     {
12653       gfc_error ("First argument of operator interface at %L must be "
12654                  "INTENT(IN)", &where);
12655       return FAILURE;
12656     }
12657
12658   if (formal->sym->attr.optional)
12659     {
12660       gfc_error ("First argument of operator interface at %L cannot be "
12661                  "optional", &where);
12662       return FAILURE;
12663     }
12664
12665   formal = formal->next;
12666   if (!formal || !formal->sym)
12667     return SUCCESS;
12668
12669   if (formal->sym->attr.intent != INTENT_IN)
12670     {
12671       gfc_error ("Second argument of operator interface at %L must be "
12672                  "INTENT(IN)", &where);
12673       return FAILURE;
12674     }
12675
12676   if (formal->sym->attr.optional)
12677     {
12678       gfc_error ("Second argument of operator interface at %L cannot be "
12679                  "optional", &where);
12680       return FAILURE;
12681     }
12682
12683   if (formal->next)
12684     {
12685       gfc_error ("Operator interface at %L must have, at most, two "
12686                  "arguments", &where);
12687       return FAILURE;
12688     }
12689
12690   return SUCCESS;
12691 }
12692
12693 static void
12694 gfc_resolve_uops (gfc_symtree *symtree)
12695 {
12696   gfc_interface *itr;
12697
12698   if (symtree == NULL)
12699     return;
12700
12701   gfc_resolve_uops (symtree->left);
12702   gfc_resolve_uops (symtree->right);
12703
12704   for (itr = symtree->n.uop->op; itr; itr = itr->next)
12705     check_uop_procedure (itr->sym, itr->sym->declared_at);
12706 }
12707
12708
12709 /* Examine all of the expressions associated with a program unit,
12710    assign types to all intermediate expressions, make sure that all
12711    assignments are to compatible types and figure out which names
12712    refer to which functions or subroutines.  It doesn't check code
12713    block, which is handled by resolve_code.  */
12714
12715 static void
12716 resolve_types (gfc_namespace *ns)
12717 {
12718   gfc_namespace *n;
12719   gfc_charlen *cl;
12720   gfc_data *d;
12721   gfc_equiv *eq;
12722   gfc_namespace* old_ns = gfc_current_ns;
12723
12724   /* Check that all IMPLICIT types are ok.  */
12725   if (!ns->seen_implicit_none)
12726     {
12727       unsigned letter;
12728       for (letter = 0; letter != GFC_LETTERS; ++letter)
12729         if (ns->set_flag[letter]
12730             && resolve_typespec_used (&ns->default_type[letter],
12731                                       &ns->implicit_loc[letter],
12732                                       NULL) == FAILURE)
12733           return;
12734     }
12735
12736   gfc_current_ns = ns;
12737
12738   resolve_entries (ns);
12739
12740   resolve_common_vars (ns->blank_common.head, false);
12741   resolve_common_blocks (ns->common_root);
12742
12743   resolve_contained_functions (ns);
12744
12745   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
12746
12747   for (cl = ns->cl_list; cl; cl = cl->next)
12748     resolve_charlen (cl);
12749
12750   gfc_traverse_ns (ns, resolve_symbol);
12751
12752   resolve_fntype (ns);
12753
12754   for (n = ns->contained; n; n = n->sibling)
12755     {
12756       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
12757         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
12758                    "also be PURE", n->proc_name->name,
12759                    &n->proc_name->declared_at);
12760
12761       resolve_types (n);
12762     }
12763
12764   forall_flag = 0;
12765   gfc_check_interfaces (ns);
12766
12767   gfc_traverse_ns (ns, resolve_values);
12768
12769   if (ns->save_all)
12770     gfc_save_all (ns);
12771
12772   iter_stack = NULL;
12773   for (d = ns->data; d; d = d->next)
12774     resolve_data (d);
12775
12776   iter_stack = NULL;
12777   gfc_traverse_ns (ns, gfc_formalize_init_value);
12778
12779   gfc_traverse_ns (ns, gfc_verify_binding_labels);
12780
12781   if (ns->common_root != NULL)
12782     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
12783
12784   for (eq = ns->equiv; eq; eq = eq->next)
12785     resolve_equivalence (eq);
12786
12787   /* Warn about unused labels.  */
12788   if (warn_unused_label)
12789     warn_unused_fortran_label (ns->st_labels);
12790
12791   gfc_resolve_uops (ns->uop_root);
12792
12793   gfc_current_ns = old_ns;
12794 }
12795
12796
12797 /* Call resolve_code recursively.  */
12798
12799 static void
12800 resolve_codes (gfc_namespace *ns)
12801 {
12802   gfc_namespace *n;
12803   bitmap_obstack old_obstack;
12804
12805   for (n = ns->contained; n; n = n->sibling)
12806     resolve_codes (n);
12807
12808   gfc_current_ns = ns;
12809
12810   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
12811   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
12812     cs_base = NULL;
12813
12814   /* Set to an out of range value.  */
12815   current_entry_id = -1;
12816
12817   old_obstack = labels_obstack;
12818   bitmap_obstack_initialize (&labels_obstack);
12819
12820   resolve_code (ns->code, ns);
12821
12822   bitmap_obstack_release (&labels_obstack);
12823   labels_obstack = old_obstack;
12824 }
12825
12826
12827 /* This function is called after a complete program unit has been compiled.
12828    Its purpose is to examine all of the expressions associated with a program
12829    unit, assign types to all intermediate expressions, make sure that all
12830    assignments are to compatible types and figure out which names refer to
12831    which functions or subroutines.  */
12832
12833 void
12834 gfc_resolve (gfc_namespace *ns)
12835 {
12836   gfc_namespace *old_ns;
12837   code_stack *old_cs_base;
12838
12839   if (ns->resolved)
12840     return;
12841
12842   ns->resolved = -1;
12843   old_ns = gfc_current_ns;
12844   old_cs_base = cs_base;
12845
12846   resolve_types (ns);
12847   resolve_codes (ns);
12848
12849   gfc_current_ns = old_ns;
12850   cs_base = old_cs_base;
12851   ns->resolved = 1;
12852 }