OSDN Git Service

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