OSDN Git Service

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