OSDN Git Service

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