OSDN Git Service

2006-02-18 Danny Smith <dannysmith@users.sourceforeg.net>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various stuctures.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, 
3    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 2, 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 COPYING.  If not, write to the Free
20 Software Foundation, 51 Franklin Street, Fifth Floor,Boston, MA
21 02110-1301, USA.  */
22
23
24 #include "config.h"
25 #include "system.h"
26 #include "gfortran.h"
27 #include "arith.h"  /* For gfc_compare_expr().  */
28 #include "dependency.h"
29
30 /* Types used in equivalence statements.  */
31
32 typedef enum seq_type
33 {
34   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
35 }
36 seq_type;
37
38 /* Stack to push the current if we descend into a block during
39    resolution.  See resolve_branch() and resolve_code().  */
40
41 typedef struct code_stack
42 {
43   struct gfc_code *head, *current;
44   struct code_stack *prev;
45 }
46 code_stack;
47
48 static code_stack *cs_base = NULL;
49
50
51 /* Nonzero if we're inside a FORALL block.  */
52
53 static int forall_flag;
54
55 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
56
57 static int omp_workshare_flag;
58
59 /* Nonzero if we are processing a formal arglist. The corresponding function
60    resets the flag each time that it is read.  */
61 static int formal_arg_flag = 0;
62
63 int
64 gfc_is_formal_arg (void)
65 {
66   return formal_arg_flag;
67 }
68
69 /* Resolve types of formal argument lists.  These have to be done early so that
70    the formal argument lists of module procedures can be copied to the
71    containing module before the individual procedures are resolved
72    individually.  We also resolve argument lists of procedures in interface
73    blocks because they are self-contained scoping units.
74
75    Since a dummy argument cannot be a non-dummy procedure, the only
76    resort left for untyped names are the IMPLICIT types.  */
77
78 static void
79 resolve_formal_arglist (gfc_symbol * proc)
80 {
81   gfc_formal_arglist *f;
82   gfc_symbol *sym;
83   int i;
84
85   /* TODO: Procedures whose return character length parameter is not constant
86      or assumed must also have explicit interfaces.  */
87   if (proc->result != NULL)
88     sym = proc->result;
89   else
90     sym = proc;
91
92   if (gfc_elemental (proc)
93       || sym->attr.pointer || sym->attr.allocatable
94       || (sym->as && sym->as->rank > 0))
95     proc->attr.always_explicit = 1;
96
97   formal_arg_flag = 1;
98
99   for (f = proc->formal; f; f = f->next)
100     {
101       sym = f->sym;
102
103       if (sym == NULL)
104         {
105           /* Alternate return placeholder.  */
106           if (gfc_elemental (proc))
107             gfc_error ("Alternate return specifier in elemental subroutine "
108                        "'%s' at %L is not allowed", proc->name,
109                        &proc->declared_at);
110           if (proc->attr.function)
111             gfc_error ("Alternate return specifier in function "
112                        "'%s' at %L is not allowed", proc->name,
113                        &proc->declared_at);
114           continue;
115         }
116
117       if (sym->attr.if_source != IFSRC_UNKNOWN)
118         resolve_formal_arglist (sym);
119
120       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
121         {
122           if (gfc_pure (proc) && !gfc_pure (sym))
123             {
124               gfc_error
125                 ("Dummy procedure '%s' of PURE procedure at %L must also "
126                  "be PURE", sym->name, &sym->declared_at);
127               continue;
128             }
129
130           if (gfc_elemental (proc))
131             {
132               gfc_error
133                 ("Dummy procedure at %L not allowed in ELEMENTAL procedure",
134                  &sym->declared_at);
135               continue;
136             }
137
138           continue;
139         }
140
141       if (sym->ts.type == BT_UNKNOWN)
142         {
143           if (!sym->attr.function || sym->result == sym)
144             gfc_set_default_type (sym, 1, sym->ns);
145         }
146
147       gfc_resolve_array_spec (sym->as, 0);
148
149       /* We can't tell if an array with dimension (:) is assumed or deferred
150          shape until we know if it has the pointer or allocatable attributes.
151       */
152       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
153           && !(sym->attr.pointer || sym->attr.allocatable))
154         {
155           sym->as->type = AS_ASSUMED_SHAPE;
156           for (i = 0; i < sym->as->rank; i++)
157             sym->as->lower[i] = gfc_int_expr (1);
158         }
159
160       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
161           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
162           || sym->attr.optional)
163         proc->attr.always_explicit = 1;
164
165       /* If the flavor is unknown at this point, it has to be a variable.
166          A procedure specification would have already set the type.  */
167
168       if (sym->attr.flavor == FL_UNKNOWN)
169         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
170
171       if (gfc_pure (proc))
172         {
173           if (proc->attr.function && !sym->attr.pointer
174               && sym->attr.flavor != FL_PROCEDURE
175               && sym->attr.intent != INTENT_IN)
176
177             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
178                        "INTENT(IN)", sym->name, proc->name,
179                        &sym->declared_at);
180
181           if (proc->attr.subroutine && !sym->attr.pointer
182               && sym->attr.intent == INTENT_UNKNOWN)
183
184             gfc_error
185               ("Argument '%s' of pure subroutine '%s' at %L must have "
186                "its INTENT specified", sym->name, proc->name,
187                &sym->declared_at);
188         }
189
190
191       if (gfc_elemental (proc))
192         {
193           if (sym->as != NULL)
194             {
195               gfc_error
196                 ("Argument '%s' of elemental procedure at %L must be scalar",
197                  sym->name, &sym->declared_at);
198               continue;
199             }
200
201           if (sym->attr.pointer)
202             {
203               gfc_error
204                 ("Argument '%s' of elemental procedure at %L cannot have "
205                  "the POINTER attribute", sym->name, &sym->declared_at);
206               continue;
207             }
208         }
209
210       /* Each dummy shall be specified to be scalar.  */
211       if (proc->attr.proc == PROC_ST_FUNCTION)
212         {
213           if (sym->as != NULL)
214             {
215               gfc_error
216                 ("Argument '%s' of statement function at %L must be scalar",
217                  sym->name, &sym->declared_at);
218               continue;
219             }
220
221           if (sym->ts.type == BT_CHARACTER)
222             {
223               gfc_charlen *cl = sym->ts.cl;
224               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
225                 {
226                   gfc_error
227                     ("Character-valued argument '%s' of statement function at "
228                      "%L must has constant length",
229                      sym->name, &sym->declared_at);
230                   continue;
231                 }
232             }
233         }
234     }
235   formal_arg_flag = 0;
236 }
237
238
239 /* Work function called when searching for symbols that have argument lists
240    associated with them.  */
241
242 static void
243 find_arglists (gfc_symbol * sym)
244 {
245
246   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
247     return;
248
249   resolve_formal_arglist (sym);
250 }
251
252
253 /* Given a namespace, resolve all formal argument lists within the namespace.
254  */
255
256 static void
257 resolve_formal_arglists (gfc_namespace * ns)
258 {
259
260   if (ns == NULL)
261     return;
262
263   gfc_traverse_ns (ns, find_arglists);
264 }
265
266
267 static void
268 resolve_contained_fntype (gfc_symbol * sym, gfc_namespace * ns)
269 {
270   try t;
271   
272   /* If this namespace is not a function, ignore it.  */
273   if (! sym
274       || !(sym->attr.function
275            || sym->attr.flavor == FL_VARIABLE))
276     return;
277
278   /* Try to find out of what the return type is.  */
279   if (sym->result != NULL)
280     sym = sym->result;
281
282   if (sym->ts.type == BT_UNKNOWN)
283     {
284       t = gfc_set_default_type (sym, 0, ns);
285
286       if (t == FAILURE && !sym->attr.untyped)
287         {
288           gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
289                      sym->name, &sym->declared_at); /* FIXME */
290           sym->attr.untyped = 1;
291         }
292     }
293
294   /*Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character type,
295     lists the only ways a character length value of * can be used: dummy arguments
296     of procedures, named constants, and function results in external functions.
297     Internal function results are not on that list; ergo, not permitted.  */
298
299   if (sym->ts.type == BT_CHARACTER)
300     {
301       gfc_charlen *cl = sym->ts.cl;
302       if (!cl || !cl->length)
303         gfc_error ("Character-valued internal function '%s' at %L must "
304                    "not be assumed length", sym->name, &sym->declared_at);
305     }
306 }
307
308
309 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
310    introduce duplicates.  */
311
312 static void
313 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
314 {
315   gfc_formal_arglist *f, *new_arglist;
316   gfc_symbol *new_sym;
317
318   for (; new_args != NULL; new_args = new_args->next)
319     {
320       new_sym = new_args->sym;
321       /* See if ths arg is already in the formal argument list.  */
322       for (f = proc->formal; f; f = f->next)
323         {
324           if (new_sym == f->sym)
325             break;
326         }
327
328       if (f)
329         continue;
330
331       /* Add a new argument.  Argument order is not important.  */
332       new_arglist = gfc_get_formal_arglist ();
333       new_arglist->sym = new_sym;
334       new_arglist->next = proc->formal;
335       proc->formal  = new_arglist;
336     }
337 }
338
339
340 /* Resolve alternate entry points.  If a symbol has multiple entry points we
341    create a new master symbol for the main routine, and turn the existing
342    symbol into an entry point.  */
343
344 static void
345 resolve_entries (gfc_namespace * ns)
346 {
347   gfc_namespace *old_ns;
348   gfc_code *c;
349   gfc_symbol *proc;
350   gfc_entry_list *el;
351   char name[GFC_MAX_SYMBOL_LEN + 1];
352   static int master_count = 0;
353
354   if (ns->proc_name == NULL)
355     return;
356
357   /* No need to do anything if this procedure doesn't have alternate entry
358      points.  */
359   if (!ns->entries)
360     return;
361
362   /* We may already have resolved alternate entry points.  */
363   if (ns->proc_name->attr.entry_master)
364     return;
365
366   /* If this isn't a procedure something has gone horribly wrong.  */
367   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
368   
369   /* Remember the current namespace.  */
370   old_ns = gfc_current_ns;
371
372   gfc_current_ns = ns;
373
374   /* Add the main entry point to the list of entry points.  */
375   el = gfc_get_entry_list ();
376   el->sym = ns->proc_name;
377   el->id = 0;
378   el->next = ns->entries;
379   ns->entries = el;
380   ns->proc_name->attr.entry = 1;
381
382   /* Add an entry statement for it.  */
383   c = gfc_get_code ();
384   c->op = EXEC_ENTRY;
385   c->ext.entry = el;
386   c->next = ns->code;
387   ns->code = c;
388
389   /* Create a new symbol for the master function.  */
390   /* Give the internal function a unique name (within this file).
391      Also include the function name so the user has some hope of figuring
392      out what is going on.  */
393   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
394             master_count++, ns->proc_name->name);
395   gfc_get_ha_symbol (name, &proc);
396   gcc_assert (proc != NULL);
397
398   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
399   if (ns->proc_name->attr.subroutine)
400     gfc_add_subroutine (&proc->attr, proc->name, NULL);
401   else
402     {
403       gfc_symbol *sym;
404       gfc_typespec *ts, *fts;
405
406       gfc_add_function (&proc->attr, proc->name, NULL);
407       proc->result = proc;
408       fts = &ns->entries->sym->result->ts;
409       if (fts->type == BT_UNKNOWN)
410         fts = gfc_get_default_type (ns->entries->sym->result, NULL);
411       for (el = ns->entries->next; el; el = el->next)
412         {
413           ts = &el->sym->result->ts;
414           if (ts->type == BT_UNKNOWN)
415             ts = gfc_get_default_type (el->sym->result, NULL);
416           if (! gfc_compare_types (ts, fts)
417               || (el->sym->result->attr.dimension
418                   != ns->entries->sym->result->attr.dimension)
419               || (el->sym->result->attr.pointer
420                   != ns->entries->sym->result->attr.pointer))
421             break;
422         }
423
424       if (el == NULL)
425         {
426           sym = ns->entries->sym->result;
427           /* All result types the same.  */
428           proc->ts = *fts;
429           if (sym->attr.dimension)
430             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
431           if (sym->attr.pointer)
432             gfc_add_pointer (&proc->attr, NULL);
433         }
434       else
435         {
436           /* Otherwise the result will be passed through a union by
437              reference.  */
438           proc->attr.mixed_entry_master = 1;
439           for (el = ns->entries; el; el = el->next)
440             {
441               sym = el->sym->result;
442               if (sym->attr.dimension)
443               {
444                 if (el == ns->entries)
445                   gfc_error
446                   ("FUNCTION result %s can't be an array in FUNCTION %s at %L",
447                    sym->name, ns->entries->sym->name, &sym->declared_at);
448                 else
449                   gfc_error
450                     ("ENTRY result %s can't be an array in FUNCTION %s at %L",
451                      sym->name, ns->entries->sym->name, &sym->declared_at);
452               }
453               else if (sym->attr.pointer)
454               {
455                 if (el == ns->entries)
456                   gfc_error
457                   ("FUNCTION result %s can't be a POINTER in FUNCTION %s at %L",
458                    sym->name, ns->entries->sym->name, &sym->declared_at);
459                 else
460                   gfc_error
461                     ("ENTRY result %s can't be a POINTER in FUNCTION %s at %L",
462                      sym->name, ns->entries->sym->name, &sym->declared_at);
463               }
464               else
465                 {
466                   ts = &sym->ts;
467                   if (ts->type == BT_UNKNOWN)
468                     ts = gfc_get_default_type (sym, NULL);
469                   switch (ts->type)
470                     {
471                     case BT_INTEGER:
472                       if (ts->kind == gfc_default_integer_kind)
473                         sym = NULL;
474                       break;
475                     case BT_REAL:
476                       if (ts->kind == gfc_default_real_kind
477                           || ts->kind == gfc_default_double_kind)
478                         sym = NULL;
479                       break;
480                     case BT_COMPLEX:
481                       if (ts->kind == gfc_default_complex_kind)
482                         sym = NULL;
483                       break;
484                     case BT_LOGICAL:
485                       if (ts->kind == gfc_default_logical_kind)
486                         sym = NULL;
487                       break;
488                     case BT_UNKNOWN:
489                       /* We will issue error elsewhere.  */
490                       sym = NULL;
491                       break;
492                     default:
493                       break;
494                     }
495                   if (sym)
496                   {
497                     if (el == ns->entries)
498                       gfc_error
499                         ("FUNCTION result %s can't be of type %s in FUNCTION %s at %L",
500                          sym->name, gfc_typename (ts), ns->entries->sym->name,
501                          &sym->declared_at);
502                     else
503                       gfc_error
504                         ("ENTRY result %s can't be of type %s in FUNCTION %s at %L",
505                          sym->name, gfc_typename (ts), ns->entries->sym->name,
506                          &sym->declared_at);
507                   }
508                 }
509             }
510         }
511     }
512   proc->attr.access = ACCESS_PRIVATE;
513   proc->attr.entry_master = 1;
514
515   /* Merge all the entry point arguments.  */
516   for (el = ns->entries; el; el = el->next)
517     merge_argument_lists (proc, el->sym->formal);
518
519   /* Use the master function for the function body.  */
520   ns->proc_name = proc;
521
522   /* Finalize the new symbols.  */
523   gfc_commit_symbols ();
524
525   /* Restore the original namespace.  */
526   gfc_current_ns = old_ns;
527 }
528
529
530 /* Resolve contained function types.  Because contained functions can call one
531    another, they have to be worked out before any of the contained procedures
532    can be resolved.
533
534    The good news is that if a function doesn't already have a type, the only
535    way it can get one is through an IMPLICIT type or a RESULT variable, because
536    by definition contained functions are contained namespace they're contained
537    in, not in a sibling or parent namespace.  */
538
539 static void
540 resolve_contained_functions (gfc_namespace * ns)
541 {
542   gfc_namespace *child;
543   gfc_entry_list *el;
544
545   resolve_formal_arglists (ns);
546
547   for (child = ns->contained; child; child = child->sibling)
548     {
549       /* Resolve alternate entry points first.  */
550       resolve_entries (child); 
551
552       /* Then check function return types.  */
553       resolve_contained_fntype (child->proc_name, child);
554       for (el = child->entries; el; el = el->next)
555         resolve_contained_fntype (el->sym, child);
556     }
557 }
558
559
560 /* Resolve all of the elements of a structure constructor and make sure that
561    the types are correct.  */
562
563 static try
564 resolve_structure_cons (gfc_expr * expr)
565 {
566   gfc_constructor *cons;
567   gfc_component *comp;
568   try t;
569
570   t = SUCCESS;
571   cons = expr->value.constructor;
572   /* A constructor may have references if it is the result of substituting a
573      parameter variable.  In this case we just pull out the component we
574      want.  */
575   if (expr->ref)
576     comp = expr->ref->u.c.sym->components;
577   else
578     comp = expr->ts.derived->components;
579
580   for (; comp; comp = comp->next, cons = cons->next)
581     {
582       if (! cons->expr)
583         {
584           t = FAILURE;
585           continue;
586         }
587
588       if (gfc_resolve_expr (cons->expr) == FAILURE)
589         {
590           t = FAILURE;
591           continue;
592         }
593
594       /* If we don't have the right type, try to convert it.  */
595
596       if (!gfc_compare_types (&cons->expr->ts, &comp->ts))
597         {
598           t = FAILURE;
599           if (comp->pointer && cons->expr->ts.type != BT_UNKNOWN)
600             gfc_error ("The element in the derived type constructor at %L, "
601                        "for pointer component '%s', is %s but should be %s",
602                        &cons->expr->where, comp->name,
603                        gfc_basic_typename (cons->expr->ts.type),
604                        gfc_basic_typename (comp->ts.type));
605           else
606             t = gfc_convert_type (cons->expr, &comp->ts, 1);
607         }
608     }
609
610   return t;
611 }
612
613
614
615 /****************** Expression name resolution ******************/
616
617 /* Returns 0 if a symbol was not declared with a type or
618    attribute declaration statement, nonzero otherwise.  */
619
620 static int
621 was_declared (gfc_symbol * sym)
622 {
623   symbol_attribute a;
624
625   a = sym->attr;
626
627   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
628     return 1;
629
630   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
631       || a.optional || a.pointer || a.save || a.target
632       || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN)
633     return 1;
634
635   return 0;
636 }
637
638
639 /* Determine if a symbol is generic or not.  */
640
641 static int
642 generic_sym (gfc_symbol * sym)
643 {
644   gfc_symbol *s;
645
646   if (sym->attr.generic ||
647       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
648     return 1;
649
650   if (was_declared (sym) || sym->ns->parent == NULL)
651     return 0;
652
653   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
654
655   return (s == NULL) ? 0 : generic_sym (s);
656 }
657
658
659 /* Determine if a symbol is specific or not.  */
660
661 static int
662 specific_sym (gfc_symbol * sym)
663 {
664   gfc_symbol *s;
665
666   if (sym->attr.if_source == IFSRC_IFBODY
667       || sym->attr.proc == PROC_MODULE
668       || sym->attr.proc == PROC_INTERNAL
669       || sym->attr.proc == PROC_ST_FUNCTION
670       || (sym->attr.intrinsic &&
671           gfc_specific_intrinsic (sym->name))
672       || sym->attr.external)
673     return 1;
674
675   if (was_declared (sym) || sym->ns->parent == NULL)
676     return 0;
677
678   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
679
680   return (s == NULL) ? 0 : specific_sym (s);
681 }
682
683
684 /* Figure out if the procedure is specific, generic or unknown.  */
685
686 typedef enum
687 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
688 proc_type;
689
690 static proc_type
691 procedure_kind (gfc_symbol * sym)
692 {
693
694   if (generic_sym (sym))
695     return PTYPE_GENERIC;
696
697   if (specific_sym (sym))
698     return PTYPE_SPECIFIC;
699
700   return PTYPE_UNKNOWN;
701 }
702
703 /* Check references to assumed size arrays.  The flag need_full_assumed_size
704    is non-zero when matching actual arguments.  */
705
706 static int need_full_assumed_size = 0;
707
708 static bool
709 check_assumed_size_reference (gfc_symbol * sym, gfc_expr * e)
710 {
711   gfc_ref * ref;
712   int dim;
713   int last = 1;
714
715   if (need_full_assumed_size
716         || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
717       return false;
718
719   for (ref = e->ref; ref; ref = ref->next)
720     if (ref->type == REF_ARRAY)
721       for (dim = 0; dim < ref->u.ar.as->rank; dim++)
722         last = (ref->u.ar.end[dim] == NULL) && (ref->u.ar.type == DIMEN_ELEMENT);
723
724   if (last)
725     {
726       gfc_error ("The upper bound in the last dimension must "
727                  "appear in the reference to the assumed size "
728                  "array '%s' at %L.", sym->name, &e->where);
729       return true;
730     }
731   return false;
732 }
733
734
735 /* Look for bad assumed size array references in argument expressions
736   of elemental and array valued intrinsic procedures.  Since this is
737   called from procedure resolution functions, it only recurses at
738   operators.  */
739
740 static bool
741 resolve_assumed_size_actual (gfc_expr *e)
742 {
743   if (e == NULL)
744    return false;
745
746   switch (e->expr_type)
747     {
748     case EXPR_VARIABLE:
749       if (e->symtree
750             && check_assumed_size_reference (e->symtree->n.sym, e))
751         return true;
752       break;
753
754     case EXPR_OP:
755       if (resolve_assumed_size_actual (e->value.op.op1)
756             || resolve_assumed_size_actual (e->value.op.op2))
757         return true;
758       break;
759
760     default:
761       break;
762     }
763   return false;
764 }
765
766
767 /* Resolve an actual argument list.  Most of the time, this is just
768    resolving the expressions in the list.
769    The exception is that we sometimes have to decide whether arguments
770    that look like procedure arguments are really simple variable
771    references.  */
772
773 static try
774 resolve_actual_arglist (gfc_actual_arglist * arg)
775 {
776   gfc_symbol *sym;
777   gfc_symtree *parent_st;
778   gfc_expr *e;
779
780   for (; arg; arg = arg->next)
781     {
782
783       e = arg->expr;
784       if (e == NULL)
785         {
786           /* Check the label is a valid branching target.  */
787           if (arg->label)
788             {
789               if (arg->label->defined == ST_LABEL_UNKNOWN)
790                 {
791                   gfc_error ("Label %d referenced at %L is never defined",
792                              arg->label->value, &arg->label->where);
793                   return FAILURE;
794                 }
795             }
796           continue;
797         }
798
799       if (e->ts.type != BT_PROCEDURE)
800         {
801           if (gfc_resolve_expr (e) != SUCCESS)
802             return FAILURE;
803           continue;
804         }
805
806       /* See if the expression node should really be a variable
807          reference.  */
808
809       sym = e->symtree->n.sym;
810
811       if (sym->attr.flavor == FL_PROCEDURE
812           || sym->attr.intrinsic
813           || sym->attr.external)
814         {
815
816           if (sym->attr.proc == PROC_ST_FUNCTION)
817             {
818               gfc_error ("Statement function '%s' at %L is not allowed as an "
819                          "actual argument", sym->name, &e->where);
820             }
821
822           if (sym->attr.contained && !sym->attr.use_assoc
823               && sym->ns->proc_name->attr.flavor != FL_MODULE)
824             {
825               gfc_error ("Internal procedure '%s' is not allowed as an "
826                          "actual argument at %L", sym->name, &e->where);
827             }
828
829           if (sym->attr.elemental && !sym->attr.intrinsic)
830             {
831               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
832                          "allowed as an actual argument at %L", sym->name,
833                          &e->where);
834             }
835
836           /* If the symbol is the function that names the current (or
837              parent) scope, then we really have a variable reference.  */
838
839           if (sym->attr.function && sym->result == sym
840               && (sym->ns->proc_name == sym
841                   || (sym->ns->parent != NULL
842                       && sym->ns->parent->proc_name == sym)))
843             goto got_variable;
844
845           continue;
846         }
847
848       /* See if the name is a module procedure in a parent unit.  */
849
850       if (was_declared (sym) || sym->ns->parent == NULL)
851         goto got_variable;
852
853       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
854         {
855           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
856           return FAILURE;
857         }
858
859       if (parent_st == NULL)
860         goto got_variable;
861
862       sym = parent_st->n.sym;
863       e->symtree = parent_st;           /* Point to the right thing.  */
864
865       if (sym->attr.flavor == FL_PROCEDURE
866           || sym->attr.intrinsic
867           || sym->attr.external)
868         {
869           continue;
870         }
871
872     got_variable:
873       e->expr_type = EXPR_VARIABLE;
874       e->ts = sym->ts;
875       if (sym->as != NULL)
876         {
877           e->rank = sym->as->rank;
878           e->ref = gfc_get_ref ();
879           e->ref->type = REF_ARRAY;
880           e->ref->u.ar.type = AR_FULL;
881           e->ref->u.ar.as = sym->as;
882         }
883     }
884
885   return SUCCESS;
886 }
887
888
889 /* Go through each actual argument in ACTUAL and see if it can be
890    implemented as an inlined, non-copying intrinsic.  FNSYM is the
891    function being called, or NULL if not known.  */
892
893 static void
894 find_noncopying_intrinsics (gfc_symbol * fnsym, gfc_actual_arglist * actual)
895 {
896   gfc_actual_arglist *ap;
897   gfc_expr *expr;
898
899   for (ap = actual; ap; ap = ap->next)
900     if (ap->expr
901         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
902         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual))
903       ap->expr->inline_noncopying_intrinsic = 1;
904 }
905
906 /* This function does the checking of references to global procedures
907    as defined in sections 18.1 and 14.1, respectively, of the Fortran
908    77 and 95 standards.  It checks for a gsymbol for the name, making
909    one if it does not already exist.  If it already exists, then the
910    reference being resolved must correspond to the type of gsymbol.
911    Otherwise, the new symbol is equipped with the attributes of the 
912    reference.  The corresponding code that is called in creating
913    global entities is parse.c.  */
914
915 static void
916 resolve_global_procedure (gfc_symbol *sym, locus *where, int sub)
917 {
918   gfc_gsymbol * gsym;
919   unsigned int type;
920
921   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
922
923   gsym = gfc_get_gsymbol (sym->name);
924
925   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
926     global_used (gsym, where);
927
928   if (gsym->type == GSYM_UNKNOWN)
929     {
930       gsym->type = type;
931       gsym->where = *where;
932     }
933
934   gsym->used = 1;
935 }
936
937 /************* Function resolution *************/
938
939 /* Resolve a function call known to be generic.
940    Section 14.1.2.4.1.  */
941
942 static match
943 resolve_generic_f0 (gfc_expr * expr, gfc_symbol * sym)
944 {
945   gfc_symbol *s;
946
947   if (sym->attr.generic)
948     {
949       s =
950         gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
951       if (s != NULL)
952         {
953           expr->value.function.name = s->name;
954           expr->value.function.esym = s;
955           expr->ts = s->ts;
956           if (s->as != NULL)
957             expr->rank = s->as->rank;
958           return MATCH_YES;
959         }
960
961       /* TODO: Need to search for elemental references in generic interface */
962     }
963
964   if (sym->attr.intrinsic)
965     return gfc_intrinsic_func_interface (expr, 0);
966
967   return MATCH_NO;
968 }
969
970
971 static try
972 resolve_generic_f (gfc_expr * expr)
973 {
974   gfc_symbol *sym;
975   match m;
976
977   sym = expr->symtree->n.sym;
978
979   for (;;)
980     {
981       m = resolve_generic_f0 (expr, sym);
982       if (m == MATCH_YES)
983         return SUCCESS;
984       else if (m == MATCH_ERROR)
985         return FAILURE;
986
987 generic:
988       if (sym->ns->parent == NULL)
989         break;
990       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
991
992       if (sym == NULL)
993         break;
994       if (!generic_sym (sym))
995         goto generic;
996     }
997
998   /* Last ditch attempt.  */
999
1000   if (!gfc_generic_intrinsic (expr->symtree->n.sym->name))
1001     {
1002       gfc_error ("Generic function '%s' at %L is not an intrinsic function",
1003                  expr->symtree->n.sym->name, &expr->where);
1004       return FAILURE;
1005     }
1006
1007   m = gfc_intrinsic_func_interface (expr, 0);
1008   if (m == MATCH_YES)
1009     return SUCCESS;
1010   if (m == MATCH_NO)
1011     gfc_error
1012       ("Generic function '%s' at %L is not consistent with a specific "
1013        "intrinsic interface", expr->symtree->n.sym->name, &expr->where);
1014
1015   return FAILURE;
1016 }
1017
1018
1019 /* Resolve a function call known to be specific.  */
1020
1021 static match
1022 resolve_specific_f0 (gfc_symbol * sym, gfc_expr * expr)
1023 {
1024   match m;
1025
1026   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
1027     {
1028       if (sym->attr.dummy)
1029         {
1030           sym->attr.proc = PROC_DUMMY;
1031           goto found;
1032         }
1033
1034       sym->attr.proc = PROC_EXTERNAL;
1035       goto found;
1036     }
1037
1038   if (sym->attr.proc == PROC_MODULE
1039       || sym->attr.proc == PROC_ST_FUNCTION
1040       || sym->attr.proc == PROC_INTERNAL)
1041     goto found;
1042
1043   if (sym->attr.intrinsic)
1044     {
1045       m = gfc_intrinsic_func_interface (expr, 1);
1046       if (m == MATCH_YES)
1047         return MATCH_YES;
1048       if (m == MATCH_NO)
1049         gfc_error
1050           ("Function '%s' at %L is INTRINSIC but is not compatible with "
1051            "an intrinsic", sym->name, &expr->where);
1052
1053       return MATCH_ERROR;
1054     }
1055
1056   return MATCH_NO;
1057
1058 found:
1059   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
1060
1061   expr->ts = sym->ts;
1062   expr->value.function.name = sym->name;
1063   expr->value.function.esym = sym;
1064   if (sym->as != NULL)
1065     expr->rank = sym->as->rank;
1066
1067   return MATCH_YES;
1068 }
1069
1070
1071 static try
1072 resolve_specific_f (gfc_expr * expr)
1073 {
1074   gfc_symbol *sym;
1075   match m;
1076
1077   sym = expr->symtree->n.sym;
1078
1079   for (;;)
1080     {
1081       m = resolve_specific_f0 (sym, expr);
1082       if (m == MATCH_YES)
1083         return SUCCESS;
1084       if (m == MATCH_ERROR)
1085         return FAILURE;
1086
1087       if (sym->ns->parent == NULL)
1088         break;
1089
1090       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1091
1092       if (sym == NULL)
1093         break;
1094     }
1095
1096   gfc_error ("Unable to resolve the specific function '%s' at %L",
1097              expr->symtree->n.sym->name, &expr->where);
1098
1099   return SUCCESS;
1100 }
1101
1102
1103 /* Resolve a procedure call not known to be generic nor specific.  */
1104
1105 static try
1106 resolve_unknown_f (gfc_expr * expr)
1107 {
1108   gfc_symbol *sym;
1109   gfc_typespec *ts;
1110
1111   sym = expr->symtree->n.sym;
1112
1113   if (sym->attr.dummy)
1114     {
1115       sym->attr.proc = PROC_DUMMY;
1116       expr->value.function.name = sym->name;
1117       goto set_type;
1118     }
1119
1120   /* See if we have an intrinsic function reference.  */
1121
1122   if (gfc_intrinsic_name (sym->name, 0))
1123     {
1124       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
1125         return SUCCESS;
1126       return FAILURE;
1127     }
1128
1129   /* The reference is to an external name.  */
1130
1131   sym->attr.proc = PROC_EXTERNAL;
1132   expr->value.function.name = sym->name;
1133   expr->value.function.esym = expr->symtree->n.sym;
1134
1135   if (sym->as != NULL)
1136     expr->rank = sym->as->rank;
1137
1138   /* Type of the expression is either the type of the symbol or the
1139      default type of the symbol.  */
1140
1141 set_type:
1142   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
1143
1144   if (sym->ts.type != BT_UNKNOWN)
1145     expr->ts = sym->ts;
1146   else
1147     {
1148       ts = gfc_get_default_type (sym, sym->ns);
1149
1150       if (ts->type == BT_UNKNOWN)
1151         {
1152           gfc_error ("Function '%s' at %L has no IMPLICIT type",
1153                      sym->name, &expr->where);
1154           return FAILURE;
1155         }
1156       else
1157         expr->ts = *ts;
1158     }
1159
1160   return SUCCESS;
1161 }
1162
1163
1164 /* Figure out if a function reference is pure or not.  Also set the name
1165    of the function for a potential error message.  Return nonzero if the
1166    function is PURE, zero if not.  */
1167
1168 static int
1169 pure_function (gfc_expr * e, const char **name)
1170 {
1171   int pure;
1172
1173   if (e->value.function.esym)
1174     {
1175       pure = gfc_pure (e->value.function.esym);
1176       *name = e->value.function.esym->name;
1177     }
1178   else if (e->value.function.isym)
1179     {
1180       pure = e->value.function.isym->pure
1181         || e->value.function.isym->elemental;
1182       *name = e->value.function.isym->name;
1183     }
1184   else
1185     {
1186       /* Implicit functions are not pure.  */
1187       pure = 0;
1188       *name = e->value.function.name;
1189     }
1190
1191   return pure;
1192 }
1193
1194
1195 /* Resolve a function call, which means resolving the arguments, then figuring
1196    out which entity the name refers to.  */
1197 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
1198    to INTENT(OUT) or INTENT(INOUT).  */
1199
1200 static try
1201 resolve_function (gfc_expr * expr)
1202 {
1203   gfc_actual_arglist *arg;
1204   gfc_symbol * sym;
1205   const char *name;
1206   try t;
1207   int temp;
1208
1209   sym = NULL;
1210   if (expr->symtree)
1211     sym = expr->symtree->n.sym;
1212
1213   /* If the procedure is not internal, a statement function or a module
1214      procedure,it must be external and should be checked for usage.  */
1215   if (sym && !sym->attr.dummy && !sym->attr.contained
1216         && sym->attr.proc != PROC_ST_FUNCTION
1217         && !sym->attr.use_assoc)
1218     resolve_global_procedure (sym, &expr->where, 0);
1219
1220   /* Switch off assumed size checking and do this again for certain kinds
1221      of procedure, once the procedure itself is resolved.  */
1222   need_full_assumed_size++;
1223
1224   if (resolve_actual_arglist (expr->value.function.actual) == FAILURE)
1225     return FAILURE;
1226
1227   /* Resume assumed_size checking. */
1228   need_full_assumed_size--;
1229
1230   if (sym && sym->ts.type == BT_CHARACTER
1231           && sym->ts.cl && sym->ts.cl->length == NULL)
1232     {
1233       if (sym->attr.if_source == IFSRC_IFBODY)
1234         {
1235           /* This follows from a slightly odd requirement at 5.1.1.5 in the
1236              standard that allows assumed character length functions to be
1237              declared in interfaces but not used.  Picking up the symbol here,
1238              rather than resolve_symbol, accomplishes that.  */
1239           gfc_error ("Function '%s' can be declared in an interface to "
1240                      "return CHARACTER(*) but cannot be used at %L",
1241                      sym->name, &expr->where);
1242           return FAILURE;
1243         }
1244
1245       /* Internal procedures are taken care of in resolve_contained_fntype.  */
1246       if (!sym->attr.dummy && !sym->attr.contained)
1247         {
1248           gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
1249                      "be used at %L since it is not a dummy argument",
1250                      sym->name, &expr->where);
1251           return FAILURE;
1252         }
1253     }
1254
1255 /* See if function is already resolved.  */
1256
1257   if (expr->value.function.name != NULL)
1258     {
1259       if (expr->ts.type == BT_UNKNOWN)
1260         expr->ts = sym->ts;
1261       t = SUCCESS;
1262     }
1263   else
1264     {
1265       /* Apply the rules of section 14.1.2.  */
1266
1267       switch (procedure_kind (sym))
1268         {
1269         case PTYPE_GENERIC:
1270           t = resolve_generic_f (expr);
1271           break;
1272
1273         case PTYPE_SPECIFIC:
1274           t = resolve_specific_f (expr);
1275           break;
1276
1277         case PTYPE_UNKNOWN:
1278           t = resolve_unknown_f (expr);
1279           break;
1280
1281         default:
1282           gfc_internal_error ("resolve_function(): bad function type");
1283         }
1284     }
1285
1286   /* If the expression is still a function (it might have simplified),
1287      then we check to see if we are calling an elemental function.  */
1288
1289   if (expr->expr_type != EXPR_FUNCTION)
1290     return t;
1291
1292   temp = need_full_assumed_size;
1293   need_full_assumed_size = 0;
1294
1295   if (expr->value.function.actual != NULL
1296       && ((expr->value.function.esym != NULL
1297            && expr->value.function.esym->attr.elemental)
1298           || (expr->value.function.isym != NULL
1299               && expr->value.function.isym->elemental)))
1300     {
1301       /* The rank of an elemental is the rank of its array argument(s).  */
1302       for (arg = expr->value.function.actual; arg; arg = arg->next)
1303         {
1304           if (arg->expr != NULL && arg->expr->rank > 0)
1305             {
1306               expr->rank = arg->expr->rank;
1307               break;
1308             }
1309         }
1310
1311       /* Being elemental, the last upper bound of an assumed size array
1312          argument must be present.  */
1313       for (arg = expr->value.function.actual; arg; arg = arg->next)
1314         {
1315           if (arg->expr != NULL
1316                 && arg->expr->rank > 0
1317                 && resolve_assumed_size_actual (arg->expr))
1318             return FAILURE;
1319         }
1320     }
1321   if (omp_workshare_flag
1322       && expr->value.function.esym
1323       && ! gfc_elemental (expr->value.function.esym))
1324     {
1325       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed"
1326                  " in WORKSHARE construct", expr->value.function.esym->name,
1327                  &expr->where);
1328       t = FAILURE;
1329     }
1330
1331   else if (expr->value.function.actual != NULL
1332              && expr->value.function.isym != NULL
1333              && expr->value.function.isym->generic_id != GFC_ISYM_LBOUND
1334              && expr->value.function.isym->generic_id != GFC_ISYM_LOC
1335              && expr->value.function.isym->generic_id != GFC_ISYM_PRESENT)
1336     {
1337       /* Array instrinsics must also have the last upper bound of an
1338          asumed size array argument.  UBOUND and SIZE have to be
1339          excluded from the check if the second argument is anything
1340          than a constant.  */
1341       int inquiry;
1342       inquiry = expr->value.function.isym->generic_id == GFC_ISYM_UBOUND
1343                   || expr->value.function.isym->generic_id == GFC_ISYM_SIZE;
1344             
1345       for (arg = expr->value.function.actual; arg; arg = arg->next)
1346         {
1347           if (inquiry && arg->next != NULL && arg->next->expr
1348                 && arg->next->expr->expr_type != EXPR_CONSTANT)
1349             break;
1350           
1351           if (arg->expr != NULL
1352                 && arg->expr->rank > 0
1353                 && resolve_assumed_size_actual (arg->expr))
1354             return FAILURE;
1355         }
1356     }
1357
1358   need_full_assumed_size = temp;
1359
1360   if (!pure_function (expr, &name))
1361     {
1362       if (forall_flag)
1363         {
1364           gfc_error
1365             ("Function reference to '%s' at %L is inside a FORALL block",
1366              name, &expr->where);
1367           t = FAILURE;
1368         }
1369       else if (gfc_pure (NULL))
1370         {
1371           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
1372                      "procedure within a PURE procedure", name, &expr->where);
1373           t = FAILURE;
1374         }
1375     }
1376
1377   /* Character lengths of use associated functions may contains references to
1378      symbols not referenced from the current program unit otherwise.  Make sure
1379      those symbols are marked as referenced.  */
1380
1381   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym 
1382       && expr->value.function.esym->attr.use_assoc)
1383     {
1384       gfc_expr_set_symbols_referenced (expr->ts.cl->length);
1385     }
1386
1387   if (t == SUCCESS)
1388     find_noncopying_intrinsics (expr->value.function.esym,
1389                                 expr->value.function.actual);
1390   return t;
1391 }
1392
1393
1394 /************* Subroutine resolution *************/
1395
1396 static void
1397 pure_subroutine (gfc_code * c, gfc_symbol * sym)
1398 {
1399
1400   if (gfc_pure (sym))
1401     return;
1402
1403   if (forall_flag)
1404     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
1405                sym->name, &c->loc);
1406   else if (gfc_pure (NULL))
1407     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
1408                &c->loc);
1409 }
1410
1411
1412 static match
1413 resolve_generic_s0 (gfc_code * c, gfc_symbol * sym)
1414 {
1415   gfc_symbol *s;
1416
1417   if (sym->attr.generic)
1418     {
1419       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
1420       if (s != NULL)
1421         {
1422           c->resolved_sym = s;
1423           pure_subroutine (c, s);
1424           return MATCH_YES;
1425         }
1426
1427       /* TODO: Need to search for elemental references in generic interface.  */
1428     }
1429
1430   if (sym->attr.intrinsic)
1431     return gfc_intrinsic_sub_interface (c, 0);
1432
1433   return MATCH_NO;
1434 }
1435
1436
1437 static try
1438 resolve_generic_s (gfc_code * c)
1439 {
1440   gfc_symbol *sym;
1441   match m;
1442
1443   sym = c->symtree->n.sym;
1444
1445   m = resolve_generic_s0 (c, sym);
1446   if (m == MATCH_YES)
1447     return SUCCESS;
1448   if (m == MATCH_ERROR)
1449     return FAILURE;
1450
1451   if (sym->ns->parent != NULL)
1452     {
1453       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1454       if (sym != NULL)
1455         {
1456           m = resolve_generic_s0 (c, sym);
1457           if (m == MATCH_YES)
1458             return SUCCESS;
1459           if (m == MATCH_ERROR)
1460             return FAILURE;
1461         }
1462     }
1463
1464   /* Last ditch attempt.  */
1465
1466   if (!gfc_generic_intrinsic (sym->name))
1467     {
1468       gfc_error
1469         ("Generic subroutine '%s' at %L is not an intrinsic subroutine",
1470          sym->name, &c->loc);
1471       return FAILURE;
1472     }
1473
1474   m = gfc_intrinsic_sub_interface (c, 0);
1475   if (m == MATCH_YES)
1476     return SUCCESS;
1477   if (m == MATCH_NO)
1478     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
1479                "intrinsic subroutine interface", sym->name, &c->loc);
1480
1481   return FAILURE;
1482 }
1483
1484
1485 /* Resolve a subroutine call known to be specific.  */
1486
1487 static match
1488 resolve_specific_s0 (gfc_code * c, gfc_symbol * sym)
1489 {
1490   match m;
1491
1492   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
1493     {
1494       if (sym->attr.dummy)
1495         {
1496           sym->attr.proc = PROC_DUMMY;
1497           goto found;
1498         }
1499
1500       sym->attr.proc = PROC_EXTERNAL;
1501       goto found;
1502     }
1503
1504   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
1505     goto found;
1506
1507   if (sym->attr.intrinsic)
1508     {
1509       m = gfc_intrinsic_sub_interface (c, 1);
1510       if (m == MATCH_YES)
1511         return MATCH_YES;
1512       if (m == MATCH_NO)
1513         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
1514                    "with an intrinsic", sym->name, &c->loc);
1515
1516       return MATCH_ERROR;
1517     }
1518
1519   return MATCH_NO;
1520
1521 found:
1522   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
1523
1524   c->resolved_sym = sym;
1525   pure_subroutine (c, sym);
1526
1527   return MATCH_YES;
1528 }
1529
1530
1531 static try
1532 resolve_specific_s (gfc_code * c)
1533 {
1534   gfc_symbol *sym;
1535   match m;
1536
1537   sym = c->symtree->n.sym;
1538
1539   m = resolve_specific_s0 (c, sym);
1540   if (m == MATCH_YES)
1541     return SUCCESS;
1542   if (m == MATCH_ERROR)
1543     return FAILURE;
1544
1545   gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1546
1547   if (sym != NULL)
1548     {
1549       m = resolve_specific_s0 (c, sym);
1550       if (m == MATCH_YES)
1551         return SUCCESS;
1552       if (m == MATCH_ERROR)
1553         return FAILURE;
1554     }
1555
1556   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
1557              sym->name, &c->loc);
1558
1559   return FAILURE;
1560 }
1561
1562
1563 /* Resolve a subroutine call not known to be generic nor specific.  */
1564
1565 static try
1566 resolve_unknown_s (gfc_code * c)
1567 {
1568   gfc_symbol *sym;
1569
1570   sym = c->symtree->n.sym;
1571
1572   if (sym->attr.dummy)
1573     {
1574       sym->attr.proc = PROC_DUMMY;
1575       goto found;
1576     }
1577
1578   /* See if we have an intrinsic function reference.  */
1579
1580   if (gfc_intrinsic_name (sym->name, 1))
1581     {
1582       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
1583         return SUCCESS;
1584       return FAILURE;
1585     }
1586
1587   /* The reference is to an external name.  */
1588
1589 found:
1590   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
1591
1592   c->resolved_sym = sym;
1593
1594   pure_subroutine (c, sym);
1595
1596   return SUCCESS;
1597 }
1598
1599
1600 /* Resolve a subroutine call.  Although it was tempting to use the same code
1601    for functions, subroutines and functions are stored differently and this
1602    makes things awkward.  */
1603
1604 static try
1605 resolve_call (gfc_code * c)
1606 {
1607   try t;
1608
1609   if (c->symtree && c->symtree->n.sym
1610         && c->symtree->n.sym->ts.type != BT_UNKNOWN)
1611     {
1612       gfc_error ("'%s' at %L has a type, which is not consistent with "
1613                  "the CALL at %L", c->symtree->n.sym->name,
1614                  &c->symtree->n.sym->declared_at, &c->loc);
1615       return FAILURE;
1616     }
1617
1618   /* If the procedure is not internal or module, it must be external and
1619      should be checked for usage.  */
1620   if (c->symtree && c->symtree->n.sym
1621         && !c->symtree->n.sym->attr.dummy
1622         && !c->symtree->n.sym->attr.contained
1623         && !c->symtree->n.sym->attr.use_assoc)
1624     resolve_global_procedure (c->symtree->n.sym, &c->loc, 1);
1625
1626   /* Switch off assumed size checking and do this again for certain kinds
1627      of procedure, once the procedure itself is resolved.  */
1628   need_full_assumed_size++;
1629
1630   if (resolve_actual_arglist (c->ext.actual) == FAILURE)
1631     return FAILURE;
1632
1633   /* Resume assumed_size checking. */
1634   need_full_assumed_size--;
1635
1636
1637   t = SUCCESS;
1638   if (c->resolved_sym == NULL)
1639     switch (procedure_kind (c->symtree->n.sym))
1640       {
1641       case PTYPE_GENERIC:
1642         t = resolve_generic_s (c);
1643         break;
1644
1645       case PTYPE_SPECIFIC:
1646         t = resolve_specific_s (c);
1647         break;
1648
1649       case PTYPE_UNKNOWN:
1650         t = resolve_unknown_s (c);
1651         break;
1652
1653       default:
1654         gfc_internal_error ("resolve_subroutine(): bad function type");
1655       }
1656
1657   if (c->ext.actual != NULL
1658       && c->symtree->n.sym->attr.elemental)
1659     {
1660       gfc_actual_arglist * a;
1661       /* Being elemental, the last upper bound of an assumed size array
1662          argument must be present.  */
1663       for (a = c->ext.actual; a; a = a->next)
1664         {
1665           if (a->expr != NULL
1666                 && a->expr->rank > 0
1667                 && resolve_assumed_size_actual (a->expr))
1668             return FAILURE;
1669         }
1670     }
1671
1672   if (t == SUCCESS)
1673     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
1674   return t;
1675 }
1676
1677 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
1678    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
1679    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
1680    if their shapes do not match.  If either op1->shape or op2->shape is
1681    NULL, return SUCCESS.  */
1682
1683 static try
1684 compare_shapes (gfc_expr * op1, gfc_expr * op2)
1685 {
1686   try t;
1687   int i;
1688
1689   t = SUCCESS;
1690                   
1691   if (op1->shape != NULL && op2->shape != NULL)
1692     {
1693       for (i = 0; i < op1->rank; i++)
1694         {
1695           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
1696            {
1697              gfc_error ("Shapes for operands at %L and %L are not conformable",
1698                          &op1->where, &op2->where);
1699              t = FAILURE;
1700              break;
1701            }
1702         }
1703     }
1704
1705   return t;
1706 }
1707
1708 /* Resolve an operator expression node.  This can involve replacing the
1709    operation with a user defined function call.  */
1710
1711 static try
1712 resolve_operator (gfc_expr * e)
1713 {
1714   gfc_expr *op1, *op2;
1715   char msg[200];
1716   try t;
1717
1718   /* Resolve all subnodes-- give them types.  */
1719
1720   switch (e->value.op.operator)
1721     {
1722     default:
1723       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
1724         return FAILURE;
1725
1726     /* Fall through...  */
1727
1728     case INTRINSIC_NOT:
1729     case INTRINSIC_UPLUS:
1730     case INTRINSIC_UMINUS:
1731     case INTRINSIC_PARENTHESES:
1732       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
1733         return FAILURE;
1734       break;
1735     }
1736
1737   /* Typecheck the new node.  */
1738
1739   op1 = e->value.op.op1;
1740   op2 = e->value.op.op2;
1741
1742   switch (e->value.op.operator)
1743     {
1744     case INTRINSIC_UPLUS:
1745     case INTRINSIC_UMINUS:
1746       if (op1->ts.type == BT_INTEGER
1747           || op1->ts.type == BT_REAL
1748           || op1->ts.type == BT_COMPLEX)
1749         {
1750           e->ts = op1->ts;
1751           break;
1752         }
1753
1754       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
1755                gfc_op2string (e->value.op.operator), gfc_typename (&e->ts));
1756       goto bad_op;
1757
1758     case INTRINSIC_PLUS:
1759     case INTRINSIC_MINUS:
1760     case INTRINSIC_TIMES:
1761     case INTRINSIC_DIVIDE:
1762     case INTRINSIC_POWER:
1763       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
1764         {
1765           gfc_type_convert_binary (e);
1766           break;
1767         }
1768
1769       sprintf (msg,
1770                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
1771                gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
1772                gfc_typename (&op2->ts));
1773       goto bad_op;
1774
1775     case INTRINSIC_CONCAT:
1776       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER)
1777         {
1778           e->ts.type = BT_CHARACTER;
1779           e->ts.kind = op1->ts.kind;
1780           break;
1781         }
1782
1783       sprintf (msg,
1784                _("Operands of string concatenation operator at %%L are %s/%s"),
1785                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
1786       goto bad_op;
1787
1788     case INTRINSIC_AND:
1789     case INTRINSIC_OR:
1790     case INTRINSIC_EQV:
1791     case INTRINSIC_NEQV:
1792       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
1793         {
1794           e->ts.type = BT_LOGICAL;
1795           e->ts.kind = gfc_kind_max (op1, op2);
1796           if (op1->ts.kind < e->ts.kind)
1797             gfc_convert_type (op1, &e->ts, 2);
1798           else if (op2->ts.kind < e->ts.kind)
1799             gfc_convert_type (op2, &e->ts, 2);
1800           break;
1801         }
1802
1803       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
1804                gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
1805                gfc_typename (&op2->ts));
1806
1807       goto bad_op;
1808
1809     case INTRINSIC_NOT:
1810       if (op1->ts.type == BT_LOGICAL)
1811         {
1812           e->ts.type = BT_LOGICAL;
1813           e->ts.kind = op1->ts.kind;
1814           break;
1815         }
1816
1817       sprintf (msg, _("Operand of .NOT. operator at %%L is %s"),
1818                gfc_typename (&op1->ts));
1819       goto bad_op;
1820
1821     case INTRINSIC_GT:
1822     case INTRINSIC_GE:
1823     case INTRINSIC_LT:
1824     case INTRINSIC_LE:
1825       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
1826         {
1827           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
1828           goto bad_op;
1829         }
1830
1831       /* Fall through...  */
1832
1833     case INTRINSIC_EQ:
1834     case INTRINSIC_NE:
1835       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER)
1836         {
1837           e->ts.type = BT_LOGICAL;
1838           e->ts.kind = gfc_default_logical_kind;
1839           break;
1840         }
1841
1842       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
1843         {
1844           gfc_type_convert_binary (e);
1845
1846           e->ts.type = BT_LOGICAL;
1847           e->ts.kind = gfc_default_logical_kind;
1848           break;
1849         }
1850
1851       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
1852         sprintf (msg,
1853                  _("Logicals at %%L must be compared with %s instead of %s"),
1854                  e->value.op.operator == INTRINSIC_EQ ? ".EQV." : ".NEQV.",
1855                  gfc_op2string (e->value.op.operator));
1856       else
1857         sprintf (msg,
1858                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
1859                  gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
1860                  gfc_typename (&op2->ts));
1861
1862       goto bad_op;
1863
1864     case INTRINSIC_USER:
1865       if (op2 == NULL)
1866         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
1867                  e->value.op.uop->name, gfc_typename (&op1->ts));
1868       else
1869         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
1870                  e->value.op.uop->name, gfc_typename (&op1->ts),
1871                  gfc_typename (&op2->ts));
1872
1873       goto bad_op;
1874
1875     case INTRINSIC_PARENTHESES:
1876       break;
1877
1878     default:
1879       gfc_internal_error ("resolve_operator(): Bad intrinsic");
1880     }
1881
1882   /* Deal with arrayness of an operand through an operator.  */
1883
1884   t = SUCCESS;
1885
1886   switch (e->value.op.operator)
1887     {
1888     case INTRINSIC_PLUS:
1889     case INTRINSIC_MINUS:
1890     case INTRINSIC_TIMES:
1891     case INTRINSIC_DIVIDE:
1892     case INTRINSIC_POWER:
1893     case INTRINSIC_CONCAT:
1894     case INTRINSIC_AND:
1895     case INTRINSIC_OR:
1896     case INTRINSIC_EQV:
1897     case INTRINSIC_NEQV:
1898     case INTRINSIC_EQ:
1899     case INTRINSIC_NE:
1900     case INTRINSIC_GT:
1901     case INTRINSIC_GE:
1902     case INTRINSIC_LT:
1903     case INTRINSIC_LE:
1904
1905       if (op1->rank == 0 && op2->rank == 0)
1906         e->rank = 0;
1907
1908       if (op1->rank == 0 && op2->rank != 0)
1909         {
1910           e->rank = op2->rank;
1911
1912           if (e->shape == NULL)
1913             e->shape = gfc_copy_shape (op2->shape, op2->rank);
1914         }
1915
1916       if (op1->rank != 0 && op2->rank == 0)
1917         {
1918           e->rank = op1->rank;
1919
1920           if (e->shape == NULL)
1921             e->shape = gfc_copy_shape (op1->shape, op1->rank);
1922         }
1923
1924       if (op1->rank != 0 && op2->rank != 0)
1925         {
1926           if (op1->rank == op2->rank)
1927             {
1928               e->rank = op1->rank;
1929               if (e->shape == NULL)
1930                 {
1931                   t = compare_shapes(op1, op2);
1932                   if (t == FAILURE)
1933                     e->shape = NULL;
1934                   else
1935                 e->shape = gfc_copy_shape (op1->shape, op1->rank);
1936                 }
1937             }
1938           else
1939             {
1940               gfc_error ("Inconsistent ranks for operator at %L and %L",
1941                          &op1->where, &op2->where);
1942               t = FAILURE;
1943
1944               /* Allow higher level expressions to work.  */
1945               e->rank = 0;
1946             }
1947         }
1948
1949       break;
1950
1951     case INTRINSIC_NOT:
1952     case INTRINSIC_UPLUS:
1953     case INTRINSIC_UMINUS:
1954     case INTRINSIC_PARENTHESES:
1955       e->rank = op1->rank;
1956
1957       if (e->shape == NULL)
1958         e->shape = gfc_copy_shape (op1->shape, op1->rank);
1959
1960       /* Simply copy arrayness attribute */
1961       break;
1962
1963     default:
1964       break;
1965     }
1966
1967   /* Attempt to simplify the expression.  */
1968   if (t == SUCCESS)
1969     t = gfc_simplify_expr (e, 0);
1970   return t;
1971
1972 bad_op:
1973
1974   if (gfc_extend_expr (e) == SUCCESS)
1975     return SUCCESS;
1976
1977   gfc_error (msg, &e->where);
1978
1979   return FAILURE;
1980 }
1981
1982
1983 /************** Array resolution subroutines **************/
1984
1985
1986 typedef enum
1987 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
1988 comparison;
1989
1990 /* Compare two integer expressions.  */
1991
1992 static comparison
1993 compare_bound (gfc_expr * a, gfc_expr * b)
1994 {
1995   int i;
1996
1997   if (a == NULL || a->expr_type != EXPR_CONSTANT
1998       || b == NULL || b->expr_type != EXPR_CONSTANT)
1999     return CMP_UNKNOWN;
2000
2001   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
2002     gfc_internal_error ("compare_bound(): Bad expression");
2003
2004   i = mpz_cmp (a->value.integer, b->value.integer);
2005
2006   if (i < 0)
2007     return CMP_LT;
2008   if (i > 0)
2009     return CMP_GT;
2010   return CMP_EQ;
2011 }
2012
2013
2014 /* Compare an integer expression with an integer.  */
2015
2016 static comparison
2017 compare_bound_int (gfc_expr * a, int b)
2018 {
2019   int i;
2020
2021   if (a == NULL || a->expr_type != EXPR_CONSTANT)
2022     return CMP_UNKNOWN;
2023
2024   if (a->ts.type != BT_INTEGER)
2025     gfc_internal_error ("compare_bound_int(): Bad expression");
2026
2027   i = mpz_cmp_si (a->value.integer, b);
2028
2029   if (i < 0)
2030     return CMP_LT;
2031   if (i > 0)
2032     return CMP_GT;
2033   return CMP_EQ;
2034 }
2035
2036
2037 /* Compare a single dimension of an array reference to the array
2038    specification.  */
2039
2040 static try
2041 check_dimension (int i, gfc_array_ref * ar, gfc_array_spec * as)
2042 {
2043
2044 /* Given start, end and stride values, calculate the minimum and
2045    maximum referenced indexes.  */
2046
2047   switch (ar->type)
2048     {
2049     case AR_FULL:
2050       break;
2051
2052     case AR_ELEMENT:
2053       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
2054         goto bound;
2055       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
2056         goto bound;
2057
2058       break;
2059
2060     case AR_SECTION:
2061       if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
2062         {
2063           gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
2064           return FAILURE;
2065         }
2066
2067       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
2068         goto bound;
2069       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
2070         goto bound;
2071
2072       /* TODO: Possibly, we could warn about end[i] being out-of-bound although
2073          it is legal (see 6.2.2.3.1).  */
2074
2075       break;
2076
2077     default:
2078       gfc_internal_error ("check_dimension(): Bad array reference");
2079     }
2080
2081   return SUCCESS;
2082
2083 bound:
2084   gfc_warning ("Array reference at %L is out of bounds", &ar->c_where[i]);
2085   return SUCCESS;
2086 }
2087
2088
2089 /* Compare an array reference with an array specification.  */
2090
2091 static try
2092 compare_spec_to_ref (gfc_array_ref * ar)
2093 {
2094   gfc_array_spec *as;
2095   int i;
2096
2097   as = ar->as;
2098   i = as->rank - 1;
2099   /* TODO: Full array sections are only allowed as actual parameters.  */
2100   if (as->type == AS_ASSUMED_SIZE
2101       && (/*ar->type == AR_FULL
2102           ||*/ (ar->type == AR_SECTION
2103               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
2104     {
2105       gfc_error ("Rightmost upper bound of assumed size array section"
2106                  " not specified at %L", &ar->where);
2107       return FAILURE;
2108     }
2109
2110   if (ar->type == AR_FULL)
2111     return SUCCESS;
2112
2113   if (as->rank != ar->dimen)
2114     {
2115       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
2116                  &ar->where, ar->dimen, as->rank);
2117       return FAILURE;
2118     }
2119
2120   for (i = 0; i < as->rank; i++)
2121     if (check_dimension (i, ar, as) == FAILURE)
2122       return FAILURE;
2123
2124   return SUCCESS;
2125 }
2126
2127
2128 /* Resolve one part of an array index.  */
2129
2130 try
2131 gfc_resolve_index (gfc_expr * index, int check_scalar)
2132 {
2133   gfc_typespec ts;
2134
2135   if (index == NULL)
2136     return SUCCESS;
2137
2138   if (gfc_resolve_expr (index) == FAILURE)
2139     return FAILURE;
2140
2141   if (check_scalar && index->rank != 0)
2142     {
2143       gfc_error ("Array index at %L must be scalar", &index->where);
2144       return FAILURE;
2145     }
2146
2147   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
2148     {
2149       gfc_error ("Array index at %L must be of INTEGER type",
2150                  &index->where);
2151       return FAILURE;
2152     }
2153
2154   if (index->ts.type == BT_REAL)
2155     if (gfc_notify_std (GFC_STD_GNU, "Extension: REAL array index at %L",
2156                         &index->where) == FAILURE)
2157       return FAILURE;
2158
2159   if (index->ts.kind != gfc_index_integer_kind
2160       || index->ts.type != BT_INTEGER)
2161     {
2162       gfc_clear_ts (&ts);
2163       ts.type = BT_INTEGER;
2164       ts.kind = gfc_index_integer_kind;
2165
2166       gfc_convert_type_warn (index, &ts, 2, 0);
2167     }
2168
2169   return SUCCESS;
2170 }
2171
2172 /* Resolve a dim argument to an intrinsic function.  */
2173
2174 try
2175 gfc_resolve_dim_arg (gfc_expr *dim)
2176 {
2177   if (dim == NULL)
2178     return SUCCESS;
2179
2180   if (gfc_resolve_expr (dim) == FAILURE)
2181     return FAILURE;
2182
2183   if (dim->rank != 0)
2184     {
2185       gfc_error ("Argument dim at %L must be scalar", &dim->where);
2186       return FAILURE;
2187   
2188     }
2189   if (dim->ts.type != BT_INTEGER)
2190     {
2191       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
2192       return FAILURE;
2193     }
2194   if (dim->ts.kind != gfc_index_integer_kind)
2195     {
2196       gfc_typespec ts;
2197
2198       ts.type = BT_INTEGER;
2199       ts.kind = gfc_index_integer_kind;
2200
2201       gfc_convert_type_warn (dim, &ts, 2, 0);
2202     }
2203
2204   return SUCCESS;
2205 }
2206
2207 /* Given an expression that contains array references, update those array
2208    references to point to the right array specifications.  While this is
2209    filled in during matching, this information is difficult to save and load
2210    in a module, so we take care of it here.
2211
2212    The idea here is that the original array reference comes from the
2213    base symbol.  We traverse the list of reference structures, setting
2214    the stored reference to references.  Component references can
2215    provide an additional array specification.  */
2216
2217 static void
2218 find_array_spec (gfc_expr * e)
2219 {
2220   gfc_array_spec *as;
2221   gfc_component *c;
2222   gfc_ref *ref;
2223
2224   as = e->symtree->n.sym->as;
2225
2226   for (ref = e->ref; ref; ref = ref->next)
2227     switch (ref->type)
2228       {
2229       case REF_ARRAY:
2230         if (as == NULL)
2231           gfc_internal_error ("find_array_spec(): Missing spec");
2232
2233         ref->u.ar.as = as;
2234         as = NULL;
2235         break;
2236
2237       case REF_COMPONENT:
2238         for (c = e->symtree->n.sym->ts.derived->components; c; c = c->next)
2239           if (c == ref->u.c.component)
2240             break;
2241
2242         if (c == NULL)
2243           gfc_internal_error ("find_array_spec(): Component not found");
2244
2245         if (c->dimension)
2246           {
2247             if (as != NULL)
2248               gfc_internal_error ("find_array_spec(): unused as(1)");
2249             as = c->as;
2250           }
2251
2252         break;
2253
2254       case REF_SUBSTRING:
2255         break;
2256       }
2257
2258   if (as != NULL)
2259     gfc_internal_error ("find_array_spec(): unused as(2)");
2260 }
2261
2262
2263 /* Resolve an array reference.  */
2264
2265 static try
2266 resolve_array_ref (gfc_array_ref * ar)
2267 {
2268   int i, check_scalar;
2269
2270   for (i = 0; i < ar->dimen; i++)
2271     {
2272       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
2273
2274       if (gfc_resolve_index (ar->start[i], check_scalar) == FAILURE)
2275         return FAILURE;
2276       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
2277         return FAILURE;
2278       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
2279         return FAILURE;
2280
2281       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
2282         switch (ar->start[i]->rank)
2283           {
2284           case 0:
2285             ar->dimen_type[i] = DIMEN_ELEMENT;
2286             break;
2287
2288           case 1:
2289             ar->dimen_type[i] = DIMEN_VECTOR;
2290             break;
2291
2292           default:
2293             gfc_error ("Array index at %L is an array of rank %d",
2294                        &ar->c_where[i], ar->start[i]->rank);
2295             return FAILURE;
2296           }
2297     }
2298
2299   /* If the reference type is unknown, figure out what kind it is.  */
2300
2301   if (ar->type == AR_UNKNOWN)
2302     {
2303       ar->type = AR_ELEMENT;
2304       for (i = 0; i < ar->dimen; i++)
2305         if (ar->dimen_type[i] == DIMEN_RANGE
2306             || ar->dimen_type[i] == DIMEN_VECTOR)
2307           {
2308             ar->type = AR_SECTION;
2309             break;
2310           }
2311     }
2312
2313   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
2314     return FAILURE;
2315
2316   return SUCCESS;
2317 }
2318
2319
2320 static try
2321 resolve_substring (gfc_ref * ref)
2322 {
2323
2324   if (ref->u.ss.start != NULL)
2325     {
2326       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
2327         return FAILURE;
2328
2329       if (ref->u.ss.start->ts.type != BT_INTEGER)
2330         {
2331           gfc_error ("Substring start index at %L must be of type INTEGER",
2332                      &ref->u.ss.start->where);
2333           return FAILURE;
2334         }
2335
2336       if (ref->u.ss.start->rank != 0)
2337         {
2338           gfc_error ("Substring start index at %L must be scalar",
2339                      &ref->u.ss.start->where);
2340           return FAILURE;
2341         }
2342
2343       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT)
2344         {
2345           gfc_error ("Substring start index at %L is less than one",
2346                      &ref->u.ss.start->where);
2347           return FAILURE;
2348         }
2349     }
2350
2351   if (ref->u.ss.end != NULL)
2352     {
2353       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
2354         return FAILURE;
2355
2356       if (ref->u.ss.end->ts.type != BT_INTEGER)
2357         {
2358           gfc_error ("Substring end index at %L must be of type INTEGER",
2359                      &ref->u.ss.end->where);
2360           return FAILURE;
2361         }
2362
2363       if (ref->u.ss.end->rank != 0)
2364         {
2365           gfc_error ("Substring end index at %L must be scalar",
2366                      &ref->u.ss.end->where);
2367           return FAILURE;
2368         }
2369
2370       if (ref->u.ss.length != NULL
2371           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT)
2372         {
2373           gfc_error ("Substring end index at %L is out of bounds",
2374                      &ref->u.ss.start->where);
2375           return FAILURE;
2376         }
2377     }
2378
2379   return SUCCESS;
2380 }
2381
2382
2383 /* Resolve subtype references.  */
2384
2385 static try
2386 resolve_ref (gfc_expr * expr)
2387 {
2388   int current_part_dimension, n_components, seen_part_dimension;
2389   gfc_ref *ref;
2390
2391   for (ref = expr->ref; ref; ref = ref->next)
2392     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
2393       {
2394         find_array_spec (expr);
2395         break;
2396       }
2397
2398   for (ref = expr->ref; ref; ref = ref->next)
2399     switch (ref->type)
2400       {
2401       case REF_ARRAY:
2402         if (resolve_array_ref (&ref->u.ar) == FAILURE)
2403           return FAILURE;
2404         break;
2405
2406       case REF_COMPONENT:
2407         break;
2408
2409       case REF_SUBSTRING:
2410         resolve_substring (ref);
2411         break;
2412       }
2413
2414   /* Check constraints on part references.  */
2415
2416   current_part_dimension = 0;
2417   seen_part_dimension = 0;
2418   n_components = 0;
2419
2420   for (ref = expr->ref; ref; ref = ref->next)
2421     {
2422       switch (ref->type)
2423         {
2424         case REF_ARRAY:
2425           switch (ref->u.ar.type)
2426             {
2427             case AR_FULL:
2428             case AR_SECTION:
2429               current_part_dimension = 1;
2430               break;
2431
2432             case AR_ELEMENT:
2433               current_part_dimension = 0;
2434               break;
2435
2436             case AR_UNKNOWN:
2437               gfc_internal_error ("resolve_ref(): Bad array reference");
2438             }
2439
2440           break;
2441
2442         case REF_COMPONENT:
2443           if ((current_part_dimension || seen_part_dimension)
2444               && ref->u.c.component->pointer)
2445             {
2446               gfc_error
2447                 ("Component to the right of a part reference with nonzero "
2448                  "rank must not have the POINTER attribute at %L",
2449                  &expr->where);
2450               return FAILURE;
2451             }
2452
2453           n_components++;
2454           break;
2455
2456         case REF_SUBSTRING:
2457           break;
2458         }
2459
2460       if (((ref->type == REF_COMPONENT && n_components > 1)
2461            || ref->next == NULL)
2462           && current_part_dimension
2463           && seen_part_dimension)
2464         {
2465
2466           gfc_error ("Two or more part references with nonzero rank must "
2467                      "not be specified at %L", &expr->where);
2468           return FAILURE;
2469         }
2470
2471       if (ref->type == REF_COMPONENT)
2472         {
2473           if (current_part_dimension)
2474             seen_part_dimension = 1;
2475
2476           /* reset to make sure */
2477           current_part_dimension = 0;
2478         }
2479     }
2480
2481   return SUCCESS;
2482 }
2483
2484
2485 /* Given an expression, determine its shape.  This is easier than it sounds.
2486    Leaves the shape array NULL if it is not possible to determine the shape.  */
2487
2488 static void
2489 expression_shape (gfc_expr * e)
2490 {
2491   mpz_t array[GFC_MAX_DIMENSIONS];
2492   int i;
2493
2494   if (e->rank == 0 || e->shape != NULL)
2495     return;
2496
2497   for (i = 0; i < e->rank; i++)
2498     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
2499       goto fail;
2500
2501   e->shape = gfc_get_shape (e->rank);
2502
2503   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
2504
2505   return;
2506
2507 fail:
2508   for (i--; i >= 0; i--)
2509     mpz_clear (array[i]);
2510 }
2511
2512
2513 /* Given a variable expression node, compute the rank of the expression by
2514    examining the base symbol and any reference structures it may have.  */
2515
2516 static void
2517 expression_rank (gfc_expr * e)
2518 {
2519   gfc_ref *ref;
2520   int i, rank;
2521
2522   if (e->ref == NULL)
2523     {
2524       if (e->expr_type == EXPR_ARRAY)
2525         goto done;
2526       /* Constructors can have a rank different from one via RESHAPE().  */
2527
2528       if (e->symtree == NULL)
2529         {
2530           e->rank = 0;
2531           goto done;
2532         }
2533
2534       e->rank = (e->symtree->n.sym->as == NULL)
2535                   ? 0 : e->symtree->n.sym->as->rank;
2536       goto done;
2537     }
2538
2539   rank = 0;
2540
2541   for (ref = e->ref; ref; ref = ref->next)
2542     {
2543       if (ref->type != REF_ARRAY)
2544         continue;
2545
2546       if (ref->u.ar.type == AR_FULL)
2547         {
2548           rank = ref->u.ar.as->rank;
2549           break;
2550         }
2551
2552       if (ref->u.ar.type == AR_SECTION)
2553         {
2554           /* Figure out the rank of the section.  */
2555           if (rank != 0)
2556             gfc_internal_error ("expression_rank(): Two array specs");
2557
2558           for (i = 0; i < ref->u.ar.dimen; i++)
2559             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
2560                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
2561               rank++;
2562
2563           break;
2564         }
2565     }
2566
2567   e->rank = rank;
2568
2569 done:
2570   expression_shape (e);
2571 }
2572
2573
2574 /* Resolve a variable expression.  */
2575
2576 static try
2577 resolve_variable (gfc_expr * e)
2578 {
2579   gfc_symbol *sym;
2580
2581   if (e->ref && resolve_ref (e) == FAILURE)
2582     return FAILURE;
2583
2584   if (e->symtree == NULL)
2585     return FAILURE;
2586
2587   sym = e->symtree->n.sym;
2588   if (sym->attr.flavor == FL_PROCEDURE && !sym->attr.function)
2589     {
2590       e->ts.type = BT_PROCEDURE;
2591       return SUCCESS;
2592     }
2593
2594   if (sym->ts.type != BT_UNKNOWN)
2595     gfc_variable_attr (e, &e->ts);
2596   else
2597     {
2598       /* Must be a simple variable reference.  */
2599       if (gfc_set_default_type (sym, 1, NULL) == FAILURE)
2600         return FAILURE;
2601       e->ts = sym->ts;
2602     }
2603
2604   if (check_assumed_size_reference (sym, e))
2605     return FAILURE;
2606
2607   return SUCCESS;
2608 }
2609
2610
2611 /* Resolve an expression.  That is, make sure that types of operands agree
2612    with their operators, intrinsic operators are converted to function calls
2613    for overloaded types and unresolved function references are resolved.  */
2614
2615 try
2616 gfc_resolve_expr (gfc_expr * e)
2617 {
2618   try t;
2619
2620   if (e == NULL)
2621     return SUCCESS;
2622
2623   switch (e->expr_type)
2624     {
2625     case EXPR_OP:
2626       t = resolve_operator (e);
2627       break;
2628
2629     case EXPR_FUNCTION:
2630       t = resolve_function (e);
2631       break;
2632
2633     case EXPR_VARIABLE:
2634       t = resolve_variable (e);
2635       if (t == SUCCESS)
2636         expression_rank (e);
2637       break;
2638
2639     case EXPR_SUBSTRING:
2640       t = resolve_ref (e);
2641       break;
2642
2643     case EXPR_CONSTANT:
2644     case EXPR_NULL:
2645       t = SUCCESS;
2646       break;
2647
2648     case EXPR_ARRAY:
2649       t = FAILURE;
2650       if (resolve_ref (e) == FAILURE)
2651         break;
2652
2653       t = gfc_resolve_array_constructor (e);
2654       /* Also try to expand a constructor.  */
2655       if (t == SUCCESS)
2656         {
2657           expression_rank (e);
2658           gfc_expand_constructor (e);
2659         }
2660
2661       break;
2662
2663     case EXPR_STRUCTURE:
2664       t = resolve_ref (e);
2665       if (t == FAILURE)
2666         break;
2667
2668       t = resolve_structure_cons (e);
2669       if (t == FAILURE)
2670         break;
2671
2672       t = gfc_simplify_expr (e, 0);
2673       break;
2674
2675     default:
2676       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
2677     }
2678
2679   return t;
2680 }
2681
2682
2683 /* Resolve an expression from an iterator.  They must be scalar and have
2684    INTEGER or (optionally) REAL type.  */
2685
2686 static try
2687 gfc_resolve_iterator_expr (gfc_expr * expr, bool real_ok,
2688                            const char * name_msgid)
2689 {
2690   if (gfc_resolve_expr (expr) == FAILURE)
2691     return FAILURE;
2692
2693   if (expr->rank != 0)
2694     {
2695       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
2696       return FAILURE;
2697     }
2698
2699   if (!(expr->ts.type == BT_INTEGER
2700         || (expr->ts.type == BT_REAL && real_ok)))
2701     {
2702       if (real_ok)
2703         gfc_error ("%s at %L must be INTEGER or REAL", _(name_msgid),
2704                    &expr->where);
2705       else
2706         gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
2707       return FAILURE;
2708     }
2709   return SUCCESS;
2710 }
2711
2712
2713 /* Resolve the expressions in an iterator structure.  If REAL_OK is
2714    false allow only INTEGER type iterators, otherwise allow REAL types.  */
2715
2716 try
2717 gfc_resolve_iterator (gfc_iterator * iter, bool real_ok)
2718 {
2719
2720   if (iter->var->ts.type == BT_REAL)
2721     gfc_notify_std (GFC_STD_F95_DEL,
2722                     "Obsolete: REAL DO loop iterator at %L",
2723                     &iter->var->where);
2724
2725   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
2726       == FAILURE)
2727     return FAILURE;
2728
2729   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
2730     {
2731       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
2732                  &iter->var->where);
2733       return FAILURE;
2734     }
2735
2736   if (gfc_resolve_iterator_expr (iter->start, real_ok,
2737                                  "Start expression in DO loop") == FAILURE)
2738     return FAILURE;
2739
2740   if (gfc_resolve_iterator_expr (iter->end, real_ok,
2741                                  "End expression in DO loop") == FAILURE)
2742     return FAILURE;
2743
2744   if (gfc_resolve_iterator_expr (iter->step, real_ok,
2745                                  "Step expression in DO loop") == FAILURE)
2746     return FAILURE;
2747
2748   if (iter->step->expr_type == EXPR_CONSTANT)
2749     {
2750       if ((iter->step->ts.type == BT_INTEGER
2751            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
2752           || (iter->step->ts.type == BT_REAL
2753               && mpfr_sgn (iter->step->value.real) == 0))
2754         {
2755           gfc_error ("Step expression in DO loop at %L cannot be zero",
2756                      &iter->step->where);
2757           return FAILURE;
2758         }
2759     }
2760
2761   /* Convert start, end, and step to the same type as var.  */
2762   if (iter->start->ts.kind != iter->var->ts.kind
2763       || iter->start->ts.type != iter->var->ts.type)
2764     gfc_convert_type (iter->start, &iter->var->ts, 2);
2765
2766   if (iter->end->ts.kind != iter->var->ts.kind
2767       || iter->end->ts.type != iter->var->ts.type)
2768     gfc_convert_type (iter->end, &iter->var->ts, 2);
2769
2770   if (iter->step->ts.kind != iter->var->ts.kind
2771       || iter->step->ts.type != iter->var->ts.type)
2772     gfc_convert_type (iter->step, &iter->var->ts, 2);
2773
2774   return SUCCESS;
2775 }
2776
2777
2778 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
2779    to be a scalar INTEGER variable.  The subscripts and stride are scalar
2780    INTEGERs, and if stride is a constant it must be nonzero.  */
2781
2782 static void
2783 resolve_forall_iterators (gfc_forall_iterator * iter)
2784 {
2785
2786   while (iter)
2787     {
2788       if (gfc_resolve_expr (iter->var) == SUCCESS
2789           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
2790         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
2791                    &iter->var->where);
2792
2793       if (gfc_resolve_expr (iter->start) == SUCCESS
2794           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
2795         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
2796                    &iter->start->where);
2797       if (iter->var->ts.kind != iter->start->ts.kind)
2798         gfc_convert_type (iter->start, &iter->var->ts, 2);
2799
2800       if (gfc_resolve_expr (iter->end) == SUCCESS
2801           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
2802         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
2803                    &iter->end->where);
2804       if (iter->var->ts.kind != iter->end->ts.kind)
2805         gfc_convert_type (iter->end, &iter->var->ts, 2);
2806
2807       if (gfc_resolve_expr (iter->stride) == SUCCESS)
2808         {
2809           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
2810             gfc_error ("FORALL stride expression at %L must be a scalar %s",
2811                         &iter->stride->where, "INTEGER");
2812
2813           if (iter->stride->expr_type == EXPR_CONSTANT
2814               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
2815             gfc_error ("FORALL stride expression at %L cannot be zero",
2816                        &iter->stride->where);
2817         }
2818       if (iter->var->ts.kind != iter->stride->ts.kind)
2819         gfc_convert_type (iter->stride, &iter->var->ts, 2);
2820
2821       iter = iter->next;
2822     }
2823 }
2824
2825
2826 /* Given a pointer to a symbol that is a derived type, see if any components
2827    have the POINTER attribute.  The search is recursive if necessary.
2828    Returns zero if no pointer components are found, nonzero otherwise.  */
2829
2830 static int
2831 derived_pointer (gfc_symbol * sym)
2832 {
2833   gfc_component *c;
2834
2835   for (c = sym->components; c; c = c->next)
2836     {
2837       if (c->pointer)
2838         return 1;
2839
2840       if (c->ts.type == BT_DERIVED && derived_pointer (c->ts.derived))
2841         return 1;
2842     }
2843
2844   return 0;
2845 }
2846
2847
2848 /* Given a pointer to a symbol that is a derived type, see if it's
2849    inaccessible, i.e. if it's defined in another module and the components are
2850    PRIVATE.  The search is recursive if necessary.  Returns zero if no
2851    inaccessible components are found, nonzero otherwise.  */
2852
2853 static int
2854 derived_inaccessible (gfc_symbol *sym)
2855 {
2856   gfc_component *c;
2857
2858   if (sym->attr.use_assoc && sym->component_access == ACCESS_PRIVATE)
2859     return 1;
2860
2861   for (c = sym->components; c; c = c->next)
2862     {
2863         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.derived))
2864           return 1;
2865     }
2866
2867   return 0;
2868 }
2869
2870
2871 /* Resolve the argument of a deallocate expression.  The expression must be
2872    a pointer or a full array.  */
2873
2874 static try
2875 resolve_deallocate_expr (gfc_expr * e)
2876 {
2877   symbol_attribute attr;
2878   int allocatable;
2879   gfc_ref *ref;
2880
2881   if (gfc_resolve_expr (e) == FAILURE)
2882     return FAILURE;
2883
2884   attr = gfc_expr_attr (e);
2885   if (attr.pointer)
2886     return SUCCESS;
2887
2888   if (e->expr_type != EXPR_VARIABLE)
2889     goto bad;
2890
2891   allocatable = e->symtree->n.sym->attr.allocatable;
2892   for (ref = e->ref; ref; ref = ref->next)
2893     switch (ref->type)
2894       {
2895       case REF_ARRAY:
2896         if (ref->u.ar.type != AR_FULL)
2897           allocatable = 0;
2898         break;
2899
2900       case REF_COMPONENT:
2901         allocatable = (ref->u.c.component->as != NULL
2902                        && ref->u.c.component->as->type == AS_DEFERRED);
2903         break;
2904
2905       case REF_SUBSTRING:
2906         allocatable = 0;
2907         break;
2908       }
2909
2910   if (allocatable == 0)
2911     {
2912     bad:
2913       gfc_error ("Expression in DEALLOCATE statement at %L must be "
2914                  "ALLOCATABLE or a POINTER", &e->where);
2915     }
2916
2917   return SUCCESS;
2918 }
2919
2920
2921 /* Given the expression node e for an allocatable/pointer of derived type to be
2922    allocated, get the expression node to be initialized afterwards (needed for
2923    derived types with default initializers).  */
2924
2925 static gfc_expr *
2926 expr_to_initialize (gfc_expr * e)
2927 {
2928   gfc_expr *result;
2929   gfc_ref *ref;
2930   int i;
2931
2932   result = gfc_copy_expr (e);
2933
2934   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
2935   for (ref = result->ref; ref; ref = ref->next)
2936     if (ref->type == REF_ARRAY && ref->next == NULL)
2937       {
2938         ref->u.ar.type = AR_FULL;
2939
2940         for (i = 0; i < ref->u.ar.dimen; i++)
2941           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
2942
2943         result->rank = ref->u.ar.dimen; 
2944         break;
2945       }
2946
2947   return result;
2948 }
2949
2950
2951 /* Resolve the expression in an ALLOCATE statement, doing the additional
2952    checks to see whether the expression is OK or not.  The expression must
2953    have a trailing array reference that gives the size of the array.  */
2954
2955 static try
2956 resolve_allocate_expr (gfc_expr * e, gfc_code * code)
2957 {
2958   int i, pointer, allocatable, dimension;
2959   symbol_attribute attr;
2960   gfc_ref *ref, *ref2;
2961   gfc_array_ref *ar;
2962   gfc_code *init_st;
2963   gfc_expr *init_e;
2964
2965   if (gfc_resolve_expr (e) == FAILURE)
2966     return FAILURE;
2967
2968   /* Make sure the expression is allocatable or a pointer.  If it is
2969      pointer, the next-to-last reference must be a pointer.  */
2970
2971   ref2 = NULL;
2972
2973   if (e->expr_type != EXPR_VARIABLE)
2974     {
2975       allocatable = 0;
2976
2977       attr = gfc_expr_attr (e);
2978       pointer = attr.pointer;
2979       dimension = attr.dimension;
2980
2981     }
2982   else
2983     {
2984       allocatable = e->symtree->n.sym->attr.allocatable;
2985       pointer = e->symtree->n.sym->attr.pointer;
2986       dimension = e->symtree->n.sym->attr.dimension;
2987
2988       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
2989         switch (ref->type)
2990           {
2991           case REF_ARRAY:
2992             if (ref->next != NULL)
2993               pointer = 0;
2994             break;
2995
2996           case REF_COMPONENT:
2997             allocatable = (ref->u.c.component->as != NULL
2998                            && ref->u.c.component->as->type == AS_DEFERRED);
2999
3000             pointer = ref->u.c.component->pointer;
3001             dimension = ref->u.c.component->dimension;
3002             break;
3003
3004           case REF_SUBSTRING:
3005             allocatable = 0;
3006             pointer = 0;
3007             break;
3008           }
3009     }
3010
3011   if (allocatable == 0 && pointer == 0)
3012     {
3013       gfc_error ("Expression in ALLOCATE statement at %L must be "
3014                  "ALLOCATABLE or a POINTER", &e->where);
3015       return FAILURE;
3016     }
3017
3018   /* Add default initializer for those derived types that need them.  */
3019   if (e->ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&e->ts)))
3020     {
3021         init_st = gfc_get_code ();
3022         init_st->loc = code->loc;
3023         init_st->op = EXEC_ASSIGN;
3024         init_st->expr = expr_to_initialize (e);
3025         init_st->expr2 = init_e;
3026
3027         init_st->next = code->next;
3028         code->next = init_st;
3029     }
3030
3031   if (pointer && dimension == 0)
3032     return SUCCESS;
3033
3034   /* Make sure the next-to-last reference node is an array specification.  */
3035
3036   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL)
3037     {
3038       gfc_error ("Array specification required in ALLOCATE statement "
3039                  "at %L", &e->where);
3040       return FAILURE;
3041     }
3042
3043   if (ref2->u.ar.type == AR_ELEMENT)
3044     return SUCCESS;
3045
3046   /* Make sure that the array section reference makes sense in the
3047     context of an ALLOCATE specification.  */
3048
3049   ar = &ref2->u.ar;
3050
3051   for (i = 0; i < ar->dimen; i++)
3052     switch (ar->dimen_type[i])
3053       {
3054       case DIMEN_ELEMENT:
3055         break;
3056
3057       case DIMEN_RANGE:
3058         if (ar->start[i] != NULL
3059             && ar->end[i] != NULL
3060             && ar->stride[i] == NULL)
3061           break;
3062
3063         /* Fall Through...  */
3064
3065       case DIMEN_UNKNOWN:
3066       case DIMEN_VECTOR:
3067         gfc_error ("Bad array specification in ALLOCATE statement at %L",
3068                    &e->where);
3069         return FAILURE;
3070       }
3071
3072   return SUCCESS;
3073 }
3074
3075
3076 /************ SELECT CASE resolution subroutines ************/
3077
3078 /* Callback function for our mergesort variant.  Determines interval
3079    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
3080    op1 > op2.  Assumes we're not dealing with the default case.  
3081    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
3082    There are nine situations to check.  */
3083
3084 static int
3085 compare_cases (const gfc_case * op1, const gfc_case * op2)
3086 {
3087   int retval;
3088
3089   if (op1->low == NULL) /* op1 = (:L)  */
3090     {
3091       /* op2 = (:N), so overlap.  */
3092       retval = 0;
3093       /* op2 = (M:) or (M:N),  L < M  */
3094       if (op2->low != NULL
3095           && gfc_compare_expr (op1->high, op2->low) < 0)
3096         retval = -1;
3097     }
3098   else if (op1->high == NULL) /* op1 = (K:)  */
3099     {
3100       /* op2 = (M:), so overlap.  */
3101       retval = 0;
3102       /* op2 = (:N) or (M:N), K > N  */
3103       if (op2->high != NULL
3104           && gfc_compare_expr (op1->low, op2->high) > 0)
3105         retval = 1;
3106     }
3107   else /* op1 = (K:L)  */
3108     {
3109       if (op2->low == NULL)       /* op2 = (:N), K > N  */
3110         retval = (gfc_compare_expr (op1->low, op2->high) > 0) ? 1 : 0;
3111       else if (op2->high == NULL) /* op2 = (M:), L < M  */
3112         retval = (gfc_compare_expr (op1->high, op2->low) < 0) ? -1 : 0;
3113       else                        /* op2 = (M:N)  */
3114         {
3115           retval =  0;
3116           /* L < M  */
3117           if (gfc_compare_expr (op1->high, op2->low) < 0)
3118             retval =  -1;
3119           /* K > N  */
3120           else if (gfc_compare_expr (op1->low, op2->high) > 0)
3121             retval =  1;
3122         }
3123     }
3124
3125   return retval;
3126 }
3127
3128
3129 /* Merge-sort a double linked case list, detecting overlap in the
3130    process.  LIST is the head of the double linked case list before it
3131    is sorted.  Returns the head of the sorted list if we don't see any
3132    overlap, or NULL otherwise.  */
3133
3134 static gfc_case *
3135 check_case_overlap (gfc_case * list)
3136 {
3137   gfc_case *p, *q, *e, *tail;
3138   int insize, nmerges, psize, qsize, cmp, overlap_seen;
3139
3140   /* If the passed list was empty, return immediately.  */
3141   if (!list)
3142     return NULL;
3143
3144   overlap_seen = 0;
3145   insize = 1;
3146
3147   /* Loop unconditionally.  The only exit from this loop is a return
3148      statement, when we've finished sorting the case list.  */
3149   for (;;)
3150     {
3151       p = list;
3152       list = NULL;
3153       tail = NULL;
3154
3155       /* Count the number of merges we do in this pass.  */
3156       nmerges = 0;
3157
3158       /* Loop while there exists a merge to be done.  */
3159       while (p)
3160         {
3161           int i;
3162
3163           /* Count this merge.  */
3164           nmerges++;
3165
3166           /* Cut the list in two pieces by stepping INSIZE places
3167              forward in the list, starting from P.  */
3168           psize = 0;
3169           q = p;
3170           for (i = 0; i < insize; i++)
3171             {
3172               psize++;
3173               q = q->right;
3174               if (!q)
3175                 break;
3176             }
3177           qsize = insize;
3178
3179           /* Now we have two lists.  Merge them!  */
3180           while (psize > 0 || (qsize > 0 && q != NULL))
3181             {
3182
3183               /* See from which the next case to merge comes from.  */
3184               if (psize == 0)
3185                 {
3186                   /* P is empty so the next case must come from Q.  */
3187                   e = q;
3188                   q = q->right;
3189                   qsize--;
3190                 }
3191               else if (qsize == 0 || q == NULL)
3192                 {
3193                   /* Q is empty.  */
3194                   e = p;
3195                   p = p->right;
3196                   psize--;
3197                 }
3198               else
3199                 {
3200                   cmp = compare_cases (p, q);
3201                   if (cmp < 0)
3202                     {
3203                       /* The whole case range for P is less than the
3204                          one for Q.  */
3205                       e = p;
3206                       p = p->right;
3207                       psize--;
3208                     }
3209                   else if (cmp > 0)
3210                     {
3211                       /* The whole case range for Q is greater than
3212                          the case range for P.  */
3213                       e = q;
3214                       q = q->right;
3215                       qsize--;
3216                     }
3217                   else
3218                     {
3219                       /* The cases overlap, or they are the same
3220                          element in the list.  Either way, we must
3221                          issue an error and get the next case from P.  */
3222                       /* FIXME: Sort P and Q by line number.  */
3223                       gfc_error ("CASE label at %L overlaps with CASE "
3224                                  "label at %L", &p->where, &q->where);
3225                       overlap_seen = 1;
3226                       e = p;
3227                       p = p->right;
3228                       psize--;
3229                     }
3230                 }
3231
3232                 /* Add the next element to the merged list.  */
3233               if (tail)
3234                 tail->right = e;
3235               else
3236                 list = e;
3237               e->left = tail;
3238               tail = e;
3239             }
3240
3241           /* P has now stepped INSIZE places along, and so has Q.  So
3242              they're the same.  */
3243           p = q;
3244         }
3245       tail->right = NULL;
3246
3247       /* If we have done only one merge or none at all, we've
3248          finished sorting the cases.  */
3249       if (nmerges <= 1)
3250         {
3251           if (!overlap_seen)
3252             return list;
3253           else
3254             return NULL;
3255         }
3256
3257       /* Otherwise repeat, merging lists twice the size.  */
3258       insize *= 2;
3259     }
3260 }
3261
3262
3263 /* Check to see if an expression is suitable for use in a CASE statement.
3264    Makes sure that all case expressions are scalar constants of the same
3265    type.  Return FAILURE if anything is wrong.  */
3266
3267 static try
3268 validate_case_label_expr (gfc_expr * e, gfc_expr * case_expr)
3269 {
3270   if (e == NULL) return SUCCESS;
3271
3272   if (e->ts.type != case_expr->ts.type)
3273     {
3274       gfc_error ("Expression in CASE statement at %L must be of type %s",
3275                  &e->where, gfc_basic_typename (case_expr->ts.type));
3276       return FAILURE;
3277     }
3278
3279   /* C805 (R808) For a given case-construct, each case-value shall be of
3280      the same type as case-expr.  For character type, length differences
3281      are allowed, but the kind type parameters shall be the same.  */
3282
3283   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
3284     {
3285       gfc_error("Expression in CASE statement at %L must be kind %d",
3286                 &e->where, case_expr->ts.kind);
3287       return FAILURE;
3288     }
3289
3290   /* Convert the case value kind to that of case expression kind, if needed.
3291      FIXME:  Should a warning be issued?  */
3292   if (e->ts.kind != case_expr->ts.kind)
3293     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
3294
3295   if (e->rank != 0)
3296     {
3297       gfc_error ("Expression in CASE statement at %L must be scalar",
3298                  &e->where);
3299       return FAILURE;
3300     }
3301
3302   return SUCCESS;
3303 }
3304
3305
3306 /* Given a completely parsed select statement, we:
3307
3308      - Validate all expressions and code within the SELECT.
3309      - Make sure that the selection expression is not of the wrong type.
3310      - Make sure that no case ranges overlap.
3311      - Eliminate unreachable cases and unreachable code resulting from
3312        removing case labels.
3313
3314    The standard does allow unreachable cases, e.g. CASE (5:3).  But
3315    they are a hassle for code generation, and to prevent that, we just
3316    cut them out here.  This is not necessary for overlapping cases
3317    because they are illegal and we never even try to generate code.
3318
3319    We have the additional caveat that a SELECT construct could have
3320    been a computed GOTO in the source code. Fortunately we can fairly
3321    easily work around that here: The case_expr for a "real" SELECT CASE
3322    is in code->expr1, but for a computed GOTO it is in code->expr2. All
3323    we have to do is make sure that the case_expr is a scalar integer
3324    expression.  */
3325
3326 static void
3327 resolve_select (gfc_code * code)
3328 {
3329   gfc_code *body;
3330   gfc_expr *case_expr;
3331   gfc_case *cp, *default_case, *tail, *head;
3332   int seen_unreachable;
3333   int ncases;
3334   bt type;
3335   try t;
3336
3337   if (code->expr == NULL)
3338     {
3339       /* This was actually a computed GOTO statement.  */
3340       case_expr = code->expr2;
3341       if (case_expr->ts.type != BT_INTEGER
3342           || case_expr->rank != 0)
3343         gfc_error ("Selection expression in computed GOTO statement "
3344                    "at %L must be a scalar integer expression",
3345                    &case_expr->where);
3346
3347       /* Further checking is not necessary because this SELECT was built
3348          by the compiler, so it should always be OK.  Just move the
3349          case_expr from expr2 to expr so that we can handle computed
3350          GOTOs as normal SELECTs from here on.  */
3351       code->expr = code->expr2;
3352       code->expr2 = NULL;
3353       return;
3354     }
3355
3356   case_expr = code->expr;
3357
3358   type = case_expr->ts.type;
3359   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
3360     {
3361       gfc_error ("Argument of SELECT statement at %L cannot be %s",
3362                  &case_expr->where, gfc_typename (&case_expr->ts));
3363
3364       /* Punt. Going on here just produce more garbage error messages.  */
3365       return;
3366     }
3367
3368   if (case_expr->rank != 0)
3369     {
3370       gfc_error ("Argument of SELECT statement at %L must be a scalar "
3371                  "expression", &case_expr->where);
3372
3373       /* Punt.  */
3374       return;
3375     }
3376
3377   /* PR 19168 has a long discussion concerning a mismatch of the kinds
3378      of the SELECT CASE expression and its CASE values.  Walk the lists
3379      of case values, and if we find a mismatch, promote case_expr to
3380      the appropriate kind.  */
3381
3382   if (type == BT_LOGICAL || type == BT_INTEGER)
3383     {
3384       for (body = code->block; body; body = body->block)
3385         {
3386           /* Walk the case label list.  */
3387           for (cp = body->ext.case_list; cp; cp = cp->next)
3388             {
3389               /* Intercept the DEFAULT case.  It does not have a kind.  */
3390               if (cp->low == NULL && cp->high == NULL)
3391                 continue;
3392
3393               /* Unreachable case ranges are discarded, so ignore.  */  
3394               if (cp->low != NULL && cp->high != NULL
3395                   && cp->low != cp->high
3396                   && gfc_compare_expr (cp->low, cp->high) > 0)
3397                 continue;
3398
3399               /* FIXME: Should a warning be issued?  */
3400               if (cp->low != NULL
3401                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
3402                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
3403
3404               if (cp->high != NULL
3405                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
3406                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
3407             }
3408          }
3409     }
3410
3411   /* Assume there is no DEFAULT case.  */
3412   default_case = NULL;
3413   head = tail = NULL;
3414   ncases = 0;
3415
3416   for (body = code->block; body; body = body->block)
3417     {
3418       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
3419       t = SUCCESS;
3420       seen_unreachable = 0;
3421
3422       /* Walk the case label list, making sure that all case labels
3423          are legal.  */
3424       for (cp = body->ext.case_list; cp; cp = cp->next)
3425         {
3426           /* Count the number of cases in the whole construct.  */
3427           ncases++;
3428
3429           /* Intercept the DEFAULT case.  */
3430           if (cp->low == NULL && cp->high == NULL)
3431             {
3432               if (default_case != NULL)
3433                 {
3434                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
3435                              "by a second DEFAULT CASE at %L",
3436                              &default_case->where, &cp->where);
3437                   t = FAILURE;
3438                   break;
3439                 }
3440               else
3441                 {
3442                   default_case = cp;
3443                   continue;
3444                 }
3445             }
3446
3447           /* Deal with single value cases and case ranges.  Errors are
3448              issued from the validation function.  */
3449           if(validate_case_label_expr (cp->low, case_expr) != SUCCESS
3450              || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
3451             {
3452               t = FAILURE;
3453               break;
3454             }
3455
3456           if (type == BT_LOGICAL
3457               && ((cp->low == NULL || cp->high == NULL)
3458                   || cp->low != cp->high))
3459             {
3460               gfc_error
3461                 ("Logical range in CASE statement at %L is not allowed",
3462                  &cp->low->where);
3463               t = FAILURE;
3464               break;
3465             }
3466
3467           if (cp->low != NULL && cp->high != NULL
3468               && cp->low != cp->high
3469               && gfc_compare_expr (cp->low, cp->high) > 0)
3470             {
3471               if (gfc_option.warn_surprising)
3472                 gfc_warning ("Range specification at %L can never "
3473                              "be matched", &cp->where);
3474
3475               cp->unreachable = 1;
3476               seen_unreachable = 1;
3477             }
3478           else
3479             {
3480               /* If the case range can be matched, it can also overlap with
3481                  other cases.  To make sure it does not, we put it in a
3482                  double linked list here.  We sort that with a merge sort
3483                  later on to detect any overlapping cases.  */
3484               if (!head)
3485                 {
3486                   head = tail = cp;
3487                   head->right = head->left = NULL;
3488                 }
3489               else
3490                 {
3491                   tail->right = cp;
3492                   tail->right->left = tail;
3493                   tail = tail->right;
3494                   tail->right = NULL;
3495                 }
3496             }
3497         }
3498
3499       /* It there was a failure in the previous case label, give up
3500          for this case label list.  Continue with the next block.  */
3501       if (t == FAILURE)
3502         continue;
3503
3504       /* See if any case labels that are unreachable have been seen.
3505          If so, we eliminate them.  This is a bit of a kludge because
3506          the case lists for a single case statement (label) is a
3507          single forward linked lists.  */
3508       if (seen_unreachable)
3509       {
3510         /* Advance until the first case in the list is reachable.  */
3511         while (body->ext.case_list != NULL
3512                && body->ext.case_list->unreachable)
3513           {
3514             gfc_case *n = body->ext.case_list;
3515             body->ext.case_list = body->ext.case_list->next;
3516             n->next = NULL;
3517             gfc_free_case_list (n);
3518           }
3519
3520         /* Strip all other unreachable cases.  */
3521         if (body->ext.case_list)
3522           {
3523             for (cp = body->ext.case_list; cp->next; cp = cp->next)
3524               {
3525                 if (cp->next->unreachable)
3526                   {
3527                     gfc_case *n = cp->next;
3528                     cp->next = cp->next->next;
3529                     n->next = NULL;
3530                     gfc_free_case_list (n);
3531                   }
3532               }
3533           }
3534       }
3535     }
3536
3537   /* See if there were overlapping cases.  If the check returns NULL,
3538      there was overlap.  In that case we don't do anything.  If head
3539      is non-NULL, we prepend the DEFAULT case.  The sorted list can
3540      then used during code generation for SELECT CASE constructs with
3541      a case expression of a CHARACTER type.  */
3542   if (head)
3543     {
3544       head = check_case_overlap (head);
3545
3546       /* Prepend the default_case if it is there.  */
3547       if (head != NULL && default_case)
3548         {
3549           default_case->left = NULL;
3550           default_case->right = head;
3551           head->left = default_case;
3552         }
3553     }
3554
3555   /* Eliminate dead blocks that may be the result if we've seen
3556      unreachable case labels for a block.  */
3557   for (body = code; body && body->block; body = body->block)
3558     {
3559       if (body->block->ext.case_list == NULL)
3560         {
3561           /* Cut the unreachable block from the code chain.  */
3562           gfc_code *c = body->block;
3563           body->block = c->block;
3564
3565           /* Kill the dead block, but not the blocks below it.  */
3566           c->block = NULL;
3567           gfc_free_statements (c);
3568         }
3569     }
3570
3571   /* More than two cases is legal but insane for logical selects.
3572      Issue a warning for it.  */
3573   if (gfc_option.warn_surprising && type == BT_LOGICAL
3574       && ncases > 2)
3575     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
3576                  &code->loc);
3577 }
3578
3579
3580 /* Resolve a transfer statement. This is making sure that:
3581    -- a derived type being transferred has only non-pointer components
3582    -- a derived type being transferred doesn't have private components, unless 
3583       it's being transferred from the module where the type was defined
3584    -- we're not trying to transfer a whole assumed size array.  */
3585
3586 static void
3587 resolve_transfer (gfc_code * code)
3588 {
3589   gfc_typespec *ts;
3590   gfc_symbol *sym;
3591   gfc_ref *ref;
3592   gfc_expr *exp;
3593
3594   exp = code->expr;
3595
3596   if (exp->expr_type != EXPR_VARIABLE)
3597     return;
3598
3599   sym = exp->symtree->n.sym;
3600   ts = &sym->ts;
3601
3602   /* Go to actual component transferred.  */
3603   for (ref = code->expr->ref; ref; ref = ref->next)
3604     if (ref->type == REF_COMPONENT)
3605       ts = &ref->u.c.component->ts;
3606
3607   if (ts->type == BT_DERIVED)
3608     {
3609       /* Check that transferred derived type doesn't contain POINTER
3610          components.  */
3611       if (derived_pointer (ts->derived))
3612         {
3613           gfc_error ("Data transfer element at %L cannot have "
3614                      "POINTER components", &code->loc);
3615           return;
3616         }
3617
3618       if (derived_inaccessible (ts->derived))
3619         {
3620           gfc_error ("Data transfer element at %L cannot have "
3621                      "PRIVATE components",&code->loc);
3622           return;
3623         }
3624     }
3625
3626   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
3627       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
3628     {
3629       gfc_error ("Data transfer element at %L cannot be a full reference to "
3630                  "an assumed-size array", &code->loc);
3631       return;
3632     }
3633 }
3634
3635
3636 /*********** Toplevel code resolution subroutines ***********/
3637
3638 /* Given a branch to a label and a namespace, if the branch is conforming.
3639    The code node described where the branch is located.  */
3640
3641 static void
3642 resolve_branch (gfc_st_label * label, gfc_code * code)
3643 {
3644   gfc_code *block, *found;
3645   code_stack *stack;
3646   gfc_st_label *lp;
3647
3648   if (label == NULL)
3649     return;
3650   lp = label;
3651
3652   /* Step one: is this a valid branching target?  */
3653
3654   if (lp->defined == ST_LABEL_UNKNOWN)
3655     {
3656       gfc_error ("Label %d referenced at %L is never defined", lp->value,
3657                  &lp->where);
3658       return;
3659     }
3660
3661   if (lp->defined != ST_LABEL_TARGET)
3662     {
3663       gfc_error ("Statement at %L is not a valid branch target statement "
3664                  "for the branch statement at %L", &lp->where, &code->loc);
3665       return;
3666     }
3667
3668   /* Step two: make sure this branch is not a branch to itself ;-)  */
3669
3670   if (code->here == label)
3671     {
3672       gfc_warning ("Branch at %L causes an infinite loop", &code->loc);
3673       return;
3674     }
3675
3676   /* Step three: Try to find the label in the parse tree. To do this,
3677      we traverse the tree block-by-block: first the block that
3678      contains this GOTO, then the block that it is nested in, etc.  We
3679      can ignore other blocks because branching into another block is
3680      not allowed.  */
3681
3682   found = NULL;
3683
3684   for (stack = cs_base; stack; stack = stack->prev)
3685     {
3686       for (block = stack->head; block; block = block->next)
3687         {
3688           if (block->here == label)
3689             {
3690               found = block;
3691               break;
3692             }
3693         }
3694
3695       if (found)
3696         break;
3697     }
3698
3699   if (found == NULL)
3700     {
3701       /* The label is not in an enclosing block, so illegal.  This was
3702          allowed in Fortran 66, so we allow it as extension.  We also 
3703          forego further checks if we run into this.  */
3704       gfc_notify_std (GFC_STD_LEGACY,
3705                       "Label at %L is not in the same block as the "
3706                       "GOTO statement at %L", &lp->where, &code->loc);
3707       return;
3708     }
3709
3710   /* Step four: Make sure that the branching target is legal if
3711      the statement is an END {SELECT,DO,IF}.  */
3712
3713   if (found->op == EXEC_NOP)
3714     {
3715       for (stack = cs_base; stack; stack = stack->prev)
3716         if (stack->current->next == found)
3717           break;
3718
3719       if (stack == NULL)
3720         gfc_notify_std (GFC_STD_F95_DEL,
3721                         "Obsolete: GOTO at %L jumps to END of construct at %L",
3722                         &code->loc, &found->loc);
3723     }
3724 }
3725
3726
3727 /* Check whether EXPR1 has the same shape as EXPR2.  */
3728
3729 static try
3730 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
3731 {
3732   mpz_t shape[GFC_MAX_DIMENSIONS];
3733   mpz_t shape2[GFC_MAX_DIMENSIONS];
3734   try result = FAILURE;
3735   int i;
3736
3737   /* Compare the rank.  */
3738   if (expr1->rank != expr2->rank)
3739     return result;
3740
3741   /* Compare the size of each dimension.  */
3742   for (i=0; i<expr1->rank; i++)
3743     {
3744       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
3745         goto ignore;
3746
3747       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
3748         goto ignore;
3749
3750       if (mpz_cmp (shape[i], shape2[i]))
3751         goto over;
3752     }
3753
3754   /* When either of the two expression is an assumed size array, we
3755      ignore the comparison of dimension sizes.  */
3756 ignore:
3757   result = SUCCESS;
3758
3759 over:
3760   for (i--; i>=0; i--)
3761     {
3762       mpz_clear (shape[i]);
3763       mpz_clear (shape2[i]);
3764     }
3765   return result;
3766 }
3767
3768
3769 /* Check whether a WHERE assignment target or a WHERE mask expression
3770    has the same shape as the outmost WHERE mask expression.  */
3771
3772 static void
3773 resolve_where (gfc_code *code, gfc_expr *mask)
3774 {
3775   gfc_code *cblock;
3776   gfc_code *cnext;
3777   gfc_expr *e = NULL;
3778
3779   cblock = code->block;
3780
3781   /* Store the first WHERE mask-expr of the WHERE statement or construct.
3782      In case of nested WHERE, only the outmost one is stored.  */
3783   if (mask == NULL) /* outmost WHERE */
3784     e = cblock->expr;
3785   else /* inner WHERE */
3786     e = mask;
3787
3788   while (cblock)
3789     {
3790       if (cblock->expr)
3791         {
3792           /* Check if the mask-expr has a consistent shape with the
3793              outmost WHERE mask-expr.  */
3794           if (resolve_where_shape (cblock->expr, e) == FAILURE)
3795             gfc_error ("WHERE mask at %L has inconsistent shape",
3796                        &cblock->expr->where);
3797          }
3798
3799       /* the assignment statement of a WHERE statement, or the first
3800          statement in where-body-construct of a WHERE construct */
3801       cnext = cblock->next;
3802       while (cnext)
3803         {
3804           switch (cnext->op)
3805             {
3806             /* WHERE assignment statement */
3807             case EXEC_ASSIGN:
3808
3809               /* Check shape consistent for WHERE assignment target.  */
3810               if (e && resolve_where_shape (cnext->expr, e) == FAILURE)
3811                gfc_error ("WHERE assignment target at %L has "
3812                           "inconsistent shape", &cnext->expr->where);
3813               break;
3814
3815             /* WHERE or WHERE construct is part of a where-body-construct */
3816             case EXEC_WHERE:
3817               resolve_where (cnext, e);
3818               break;
3819
3820             default:
3821               gfc_error ("Unsupported statement inside WHERE at %L",
3822                          &cnext->loc);
3823             }
3824          /* the next statement within the same where-body-construct */
3825          cnext = cnext->next;
3826        }
3827     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
3828     cblock = cblock->block;
3829   }
3830 }
3831
3832
3833 /* Check whether the FORALL index appears in the expression or not.  */
3834
3835 static try
3836 gfc_find_forall_index (gfc_expr *expr, gfc_symbol *symbol)
3837 {
3838   gfc_array_ref ar;
3839   gfc_ref *tmp;
3840   gfc_actual_arglist *args;
3841   int i;
3842
3843   switch (expr->expr_type)
3844     {
3845     case EXPR_VARIABLE:
3846       gcc_assert (expr->symtree->n.sym);
3847
3848       /* A scalar assignment  */
3849       if (!expr->ref)
3850         {
3851           if (expr->symtree->n.sym == symbol)
3852             return SUCCESS;
3853           else
3854             return FAILURE;
3855         }
3856
3857       /* the expr is array ref, substring or struct component.  */
3858       tmp = expr->ref;
3859       while (tmp != NULL)
3860         {
3861           switch (tmp->type)
3862             {
3863             case  REF_ARRAY:
3864               /* Check if the symbol appears in the array subscript.  */
3865               ar = tmp->u.ar;
3866               for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
3867                 {
3868                   if (ar.start[i])
3869                     if (gfc_find_forall_index (ar.start[i], symbol) == SUCCESS)
3870                       return SUCCESS;
3871
3872                   if (ar.end[i])
3873                     if (gfc_find_forall_index (ar.end[i], symbol) == SUCCESS)
3874                       return SUCCESS;
3875
3876                   if (ar.stride[i])
3877                     if (gfc_find_forall_index (ar.stride[i], symbol) == SUCCESS)
3878                       return SUCCESS;
3879                 }  /* end for  */
3880               break;
3881
3882             case REF_SUBSTRING:
3883               if (expr->symtree->n.sym == symbol)
3884                 return SUCCESS;
3885               tmp = expr->ref;
3886               /* Check if the symbol appears in the substring section.  */
3887               if (gfc_find_forall_index (tmp->u.ss.start, symbol) == SUCCESS)
3888                 return SUCCESS;
3889               if (gfc_find_forall_index (tmp->u.ss.end, symbol) == SUCCESS)
3890                 return SUCCESS;
3891               break;
3892
3893             case REF_COMPONENT:
3894               break;
3895
3896             default:
3897               gfc_error("expresion reference type error at %L", &expr->where);
3898             }
3899           tmp = tmp->next;
3900         }
3901       break;
3902
3903     /* If the expression is a function call, then check if the symbol
3904        appears in the actual arglist of the function.  */
3905     case EXPR_FUNCTION:
3906       for (args = expr->value.function.actual; args; args = args->next)
3907         {
3908           if (gfc_find_forall_index(args->expr,symbol) == SUCCESS)
3909             return SUCCESS;
3910         }
3911       break;
3912
3913     /* It seems not to happen.  */
3914     case EXPR_SUBSTRING:
3915       if (expr->ref)
3916         {
3917           tmp = expr->ref;
3918           gcc_assert (expr->ref->type == REF_SUBSTRING);
3919           if (gfc_find_forall_index (tmp->u.ss.start, symbol) == SUCCESS)
3920             return SUCCESS;
3921           if (gfc_find_forall_index (tmp->u.ss.end, symbol) == SUCCESS)
3922             return SUCCESS;
3923         }
3924       break;
3925
3926     /* It seems not to happen.  */
3927     case EXPR_STRUCTURE:
3928     case EXPR_ARRAY:
3929       gfc_error ("Unsupported statement while finding forall index in "
3930                  "expression");
3931       break;
3932
3933     case EXPR_OP:
3934       /* Find the FORALL index in the first operand.  */
3935       if (expr->value.op.op1)
3936         {
3937           if (gfc_find_forall_index (expr->value.op.op1, symbol) == SUCCESS)
3938             return SUCCESS;
3939         }
3940
3941       /* Find the FORALL index in the second operand.  */
3942       if (expr->value.op.op2)
3943         {
3944           if (gfc_find_forall_index (expr->value.op.op2, symbol) == SUCCESS)
3945             return SUCCESS;
3946         }
3947       break;
3948
3949     default:
3950       break;
3951     }
3952
3953   return FAILURE;
3954 }
3955
3956
3957 /* Resolve assignment in FORALL construct.
3958    NVAR is the number of FORALL index variables, and VAR_EXPR records the
3959    FORALL index variables.  */
3960
3961 static void
3962 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
3963 {
3964   int n;
3965
3966   for (n = 0; n < nvar; n++)
3967     {
3968       gfc_symbol *forall_index;
3969
3970       forall_index = var_expr[n]->symtree->n.sym;
3971
3972       /* Check whether the assignment target is one of the FORALL index
3973          variable.  */
3974       if ((code->expr->expr_type == EXPR_VARIABLE)
3975           && (code->expr->symtree->n.sym == forall_index))
3976         gfc_error ("Assignment to a FORALL index variable at %L",
3977                    &code->expr->where);
3978       else
3979         {
3980           /* If one of the FORALL index variables doesn't appear in the
3981              assignment target, then there will be a many-to-one
3982              assignment.  */
3983           if (gfc_find_forall_index (code->expr, forall_index) == FAILURE)
3984             gfc_error ("The FORALL with index '%s' cause more than one "
3985                        "assignment to this object at %L",
3986                        var_expr[n]->symtree->name, &code->expr->where);
3987         }
3988     }
3989 }
3990
3991
3992 /* Resolve WHERE statement in FORALL construct.  */
3993
3994 static void
3995 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr){
3996   gfc_code *cblock;
3997   gfc_code *cnext;
3998
3999   cblock = code->block;
4000   while (cblock)
4001     {
4002       /* the assignment statement of a WHERE statement, or the first
4003          statement in where-body-construct of a WHERE construct */
4004       cnext = cblock->next;
4005       while (cnext)
4006         {
4007           switch (cnext->op)
4008             {
4009             /* WHERE assignment statement */
4010             case EXEC_ASSIGN:
4011               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
4012               break;
4013
4014             /* WHERE or WHERE construct is part of a where-body-construct */
4015             case EXEC_WHERE:
4016               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
4017               break;
4018
4019             default:
4020               gfc_error ("Unsupported statement inside WHERE at %L",
4021                          &cnext->loc);
4022             }
4023           /* the next statement within the same where-body-construct */
4024           cnext = cnext->next;
4025         }
4026       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
4027       cblock = cblock->block;
4028     }
4029 }
4030
4031
4032 /* Traverse the FORALL body to check whether the following errors exist:
4033    1. For assignment, check if a many-to-one assignment happens.
4034    2. For WHERE statement, check the WHERE body to see if there is any
4035       many-to-one assignment.  */
4036
4037 static void
4038 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
4039 {
4040   gfc_code *c;
4041
4042   c = code->block->next;
4043   while (c)
4044     {
4045       switch (c->op)
4046         {
4047         case EXEC_ASSIGN:
4048         case EXEC_POINTER_ASSIGN:
4049           gfc_resolve_assign_in_forall (c, nvar, var_expr);
4050           break;
4051
4052         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
4053            there is no need to handle it here.  */
4054         case EXEC_FORALL:
4055           break;
4056         case EXEC_WHERE:
4057           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
4058           break;
4059         default:
4060           break;
4061         }
4062       /* The next statement in the FORALL body.  */
4063       c = c->next;
4064     }
4065 }
4066
4067
4068 /* Given a FORALL construct, first resolve the FORALL iterator, then call
4069    gfc_resolve_forall_body to resolve the FORALL body.  */
4070
4071 static void
4072 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
4073 {
4074   static gfc_expr **var_expr;
4075   static int total_var = 0;
4076   static int nvar = 0;
4077   gfc_forall_iterator *fa;
4078   gfc_symbol *forall_index;
4079   gfc_code *next;
4080   int i;
4081
4082   /* Start to resolve a FORALL construct   */
4083   if (forall_save == 0)
4084     {
4085       /* Count the total number of FORALL index in the nested FORALL
4086          construct in order to allocate the VAR_EXPR with proper size.  */
4087       next = code;
4088       while ((next != NULL) && (next->op == EXEC_FORALL))
4089         {
4090           for (fa = next->ext.forall_iterator; fa; fa = fa->next)
4091             total_var ++;
4092           next = next->block->next;
4093         }
4094
4095       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
4096       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
4097     }
4098
4099   /* The information about FORALL iterator, including FORALL index start, end
4100      and stride. The FORALL index can not appear in start, end or stride.  */
4101   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
4102     {
4103       /* Check if any outer FORALL index name is the same as the current
4104          one.  */
4105       for (i = 0; i < nvar; i++)
4106         {
4107           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
4108             {
4109               gfc_error ("An outer FORALL construct already has an index "
4110                          "with this name %L", &fa->var->where);
4111             }
4112         }
4113
4114       /* Record the current FORALL index.  */
4115       var_expr[nvar] = gfc_copy_expr (fa->var);
4116
4117       forall_index = fa->var->symtree->n.sym;
4118
4119       /* Check if the FORALL index appears in start, end or stride.  */
4120       if (gfc_find_forall_index (fa->start, forall_index) == SUCCESS)
4121         gfc_error ("A FORALL index must not appear in a limit or stride "
4122                    "expression in the same FORALL at %L", &fa->start->where);
4123       if (gfc_find_forall_index (fa->end, forall_index) == SUCCESS)
4124         gfc_error ("A FORALL index must not appear in a limit or stride "
4125                    "expression in the same FORALL at %L", &fa->end->where);
4126       if (gfc_find_forall_index (fa->stride, forall_index) == SUCCESS)
4127         gfc_error ("A FORALL index must not appear in a limit or stride "
4128                    "expression in the same FORALL at %L", &fa->stride->where);
4129       nvar++;
4130     }
4131
4132   /* Resolve the FORALL body.  */
4133   gfc_resolve_forall_body (code, nvar, var_expr);
4134
4135   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
4136   gfc_resolve_blocks (code->block, ns);
4137
4138   /* Free VAR_EXPR after the whole FORALL construct resolved.  */
4139   for (i = 0; i < total_var; i++)
4140     gfc_free_expr (var_expr[i]);
4141
4142   /* Reset the counters.  */
4143   total_var = 0;
4144   nvar = 0;
4145 }
4146
4147
4148 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL ,GOTO and
4149    DO code nodes.  */
4150
4151 static void resolve_code (gfc_code *, gfc_namespace *);
4152
4153 void
4154 gfc_resolve_blocks (gfc_code * b, gfc_namespace * ns)
4155 {
4156   try t;
4157
4158   for (; b; b = b->block)
4159     {
4160       t = gfc_resolve_expr (b->expr);
4161       if (gfc_resolve_expr (b->expr2) == FAILURE)
4162         t = FAILURE;
4163
4164       switch (b->op)
4165         {
4166         case EXEC_IF:
4167           if (t == SUCCESS && b->expr != NULL
4168               && (b->expr->ts.type != BT_LOGICAL || b->expr->rank != 0))
4169             gfc_error
4170               ("ELSE IF clause at %L requires a scalar LOGICAL expression",
4171                &b->expr->where);
4172           break;
4173
4174         case EXEC_WHERE:
4175           if (t == SUCCESS
4176               && b->expr != NULL
4177               && (b->expr->ts.type != BT_LOGICAL
4178                   || b->expr->rank == 0))
4179             gfc_error
4180               ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
4181                &b->expr->where);
4182           break;
4183
4184         case EXEC_GOTO:
4185           resolve_branch (b->label, b);
4186           break;
4187
4188         case EXEC_SELECT:
4189         case EXEC_FORALL:
4190         case EXEC_DO:
4191         case EXEC_DO_WHILE:
4192         case EXEC_READ:
4193         case EXEC_WRITE:
4194         case EXEC_IOLENGTH:
4195           break;
4196
4197         case EXEC_OMP_ATOMIC:
4198         case EXEC_OMP_CRITICAL:
4199         case EXEC_OMP_DO:
4200         case EXEC_OMP_MASTER:
4201         case EXEC_OMP_ORDERED:
4202         case EXEC_OMP_PARALLEL:
4203         case EXEC_OMP_PARALLEL_DO:
4204         case EXEC_OMP_PARALLEL_SECTIONS:
4205         case EXEC_OMP_PARALLEL_WORKSHARE:
4206         case EXEC_OMP_SECTIONS:
4207         case EXEC_OMP_SINGLE:
4208         case EXEC_OMP_WORKSHARE:
4209           break;
4210
4211         default:
4212           gfc_internal_error ("resolve_block(): Bad block type");
4213         }
4214
4215       resolve_code (b->next, ns);
4216     }
4217 }
4218
4219
4220 /* Given a block of code, recursively resolve everything pointed to by this
4221    code block.  */
4222
4223 static void
4224 resolve_code (gfc_code * code, gfc_namespace * ns)
4225 {
4226   int omp_workshare_save;
4227   code_stack frame;
4228   gfc_alloc *a;
4229   try t;
4230
4231   frame.prev = cs_base;
4232   frame.head = code;
4233   cs_base = &frame;
4234
4235   for (; code; code = code->next)
4236     {
4237       frame.current = code;
4238
4239       if (code->op == EXEC_FORALL)
4240         {
4241           int forall_save = forall_flag;
4242
4243           forall_flag = 1;
4244           gfc_resolve_forall (code, ns, forall_save);
4245           forall_flag = forall_save;
4246         }
4247       else if (code->block)
4248         {
4249           omp_workshare_save = -1;
4250           switch (code->op)
4251             {
4252             case EXEC_OMP_PARALLEL_WORKSHARE:
4253               omp_workshare_save = omp_workshare_flag;
4254               omp_workshare_flag = 1;
4255               gfc_resolve_omp_parallel_blocks (code, ns);
4256               break;
4257             case EXEC_OMP_PARALLEL:
4258             case EXEC_OMP_PARALLEL_DO:
4259             case EXEC_OMP_PARALLEL_SECTIONS:
4260               omp_workshare_save = omp_workshare_flag;
4261               omp_workshare_flag = 0;
4262               gfc_resolve_omp_parallel_blocks (code, ns);
4263               break;
4264             case EXEC_OMP_DO:
4265               gfc_resolve_omp_do_blocks (code, ns);
4266               break;
4267             case EXEC_OMP_WORKSHARE:
4268               omp_workshare_save = omp_workshare_flag;
4269               omp_workshare_flag = 1;
4270               /* FALLTHROUGH */
4271             default:
4272               gfc_resolve_blocks (code->block, ns);
4273               break;
4274             }
4275
4276           if (omp_workshare_save != -1)
4277             omp_workshare_flag = omp_workshare_save;
4278         }
4279
4280       t = gfc_resolve_expr (code->expr);
4281       if (gfc_resolve_expr (code->expr2) == FAILURE)
4282         t = FAILURE;
4283
4284       switch (code->op)
4285         {
4286         case EXEC_NOP:
4287         case EXEC_CYCLE:
4288         case EXEC_PAUSE:
4289         case EXEC_STOP:
4290         case EXEC_EXIT:
4291         case EXEC_CONTINUE:
4292         case EXEC_DT_END:
4293         case EXEC_ENTRY:
4294           break;
4295
4296         case EXEC_WHERE:
4297           resolve_where (code, NULL);
4298           break;
4299
4300         case EXEC_GOTO:
4301           if (code->expr != NULL)
4302             {
4303               if (code->expr->ts.type != BT_INTEGER)
4304                 gfc_error ("ASSIGNED GOTO statement at %L requires an INTEGER "
4305                        "variable", &code->expr->where);
4306               else if (code->expr->symtree->n.sym->attr.assign != 1)
4307                 gfc_error ("Variable '%s' has not been assigned a target label "
4308                         "at %L", code->expr->symtree->n.sym->name,
4309                         &code->expr->where);
4310             }
4311           else
4312             resolve_branch (code->label, code);
4313           break;
4314
4315         case EXEC_RETURN:
4316           if (code->expr != NULL && code->expr->ts.type != BT_INTEGER)
4317             gfc_error ("Alternate RETURN statement at %L requires an INTEGER "
4318                        "return specifier", &code->expr->where);
4319           break;
4320
4321         case EXEC_ASSIGN:
4322           if (t == FAILURE)
4323             break;
4324
4325           if (gfc_extend_assign (code, ns) == SUCCESS)
4326             {
4327               if (gfc_pure (NULL) && !gfc_pure (code->symtree->n.sym))
4328                 {
4329                   gfc_error ("Subroutine '%s' called instead of assignment at "
4330                              "%L must be PURE", code->symtree->n.sym->name,
4331                              &code->loc);
4332                   break;
4333                 }
4334               goto call;
4335             }
4336
4337           if (gfc_pure (NULL))
4338             {
4339               if (gfc_impure_variable (code->expr->symtree->n.sym))
4340                 {
4341                   gfc_error
4342                     ("Cannot assign to variable '%s' in PURE procedure at %L",
4343                      code->expr->symtree->n.sym->name, &code->expr->where);
4344                   break;
4345                 }
4346
4347               if (code->expr2->ts.type == BT_DERIVED
4348                   && derived_pointer (code->expr2->ts.derived))
4349                 {
4350                   gfc_error
4351                     ("Right side of assignment at %L is a derived type "
4352                      "containing a POINTER in a PURE procedure",
4353                      &code->expr2->where);
4354                   break;
4355                 }
4356             }
4357
4358           gfc_check_assign (code->expr, code->expr2, 1);
4359           break;
4360
4361         case EXEC_LABEL_ASSIGN:
4362           if (code->label->defined == ST_LABEL_UNKNOWN)
4363             gfc_error ("Label %d referenced at %L is never defined",
4364                        code->label->value, &code->label->where);
4365           if (t == SUCCESS
4366               && (code->expr->expr_type != EXPR_VARIABLE
4367                   || code->expr->symtree->n.sym->ts.type != BT_INTEGER
4368                   || code->expr->symtree->n.sym->ts.kind 
4369                         != gfc_default_integer_kind
4370                   || code->expr->symtree->n.sym->as != NULL))
4371             gfc_error ("ASSIGN statement at %L requires a scalar "
4372                        "default INTEGER variable", &code->expr->where);
4373           break;
4374
4375         case EXEC_POINTER_ASSIGN:
4376           if (t == FAILURE)
4377             break;
4378
4379           gfc_check_pointer_assign (code->expr, code->expr2);
4380           break;
4381
4382         case EXEC_ARITHMETIC_IF:
4383           if (t == SUCCESS
4384               && code->expr->ts.type != BT_INTEGER
4385               && code->expr->ts.type != BT_REAL)
4386             gfc_error ("Arithmetic IF statement at %L requires a numeric "
4387                        "expression", &code->expr->where);
4388
4389           resolve_branch (code->label, code);
4390           resolve_branch (code->label2, code);
4391           resolve_branch (code->label3, code);
4392           break;
4393
4394         case EXEC_IF:
4395           if (t == SUCCESS && code->expr != NULL
4396               && (code->expr->ts.type != BT_LOGICAL
4397                   || code->expr->rank != 0))
4398             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
4399                        &code->expr->where);
4400           break;
4401
4402         case EXEC_CALL:
4403         call:
4404           resolve_call (code);
4405           break;
4406
4407         case EXEC_SELECT:
4408           /* Select is complicated. Also, a SELECT construct could be
4409              a transformed computed GOTO.  */
4410           resolve_select (code);
4411           break;
4412
4413         case EXEC_DO:
4414           if (code->ext.iterator != NULL)
4415             {
4416               gfc_iterator *iter = code->ext.iterator;
4417               if (gfc_resolve_iterator (iter, true) != FAILURE)
4418                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
4419             }
4420           break;
4421
4422         case EXEC_DO_WHILE:
4423           if (code->expr == NULL)
4424             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
4425           if (t == SUCCESS
4426               && (code->expr->rank != 0
4427                   || code->expr->ts.type != BT_LOGICAL))
4428             gfc_error ("Exit condition of DO WHILE loop at %L must be "
4429                        "a scalar LOGICAL expression", &code->expr->where);
4430           break;
4431
4432         case EXEC_ALLOCATE:
4433           if (t == SUCCESS && code->expr != NULL
4434               && code->expr->ts.type != BT_INTEGER)
4435             gfc_error ("STAT tag in ALLOCATE statement at %L must be "
4436                        "of type INTEGER", &code->expr->where);
4437
4438           for (a = code->ext.alloc_list; a; a = a->next)
4439             resolve_allocate_expr (a->expr, code);
4440
4441           break;
4442
4443         case EXEC_DEALLOCATE:
4444           if (t == SUCCESS && code->expr != NULL
4445               && code->expr->ts.type != BT_INTEGER)
4446             gfc_error
4447               ("STAT tag in DEALLOCATE statement at %L must be of type "
4448                "INTEGER", &code->expr->where);
4449
4450           for (a = code->ext.alloc_list; a; a = a->next)
4451             resolve_deallocate_expr (a->expr);
4452
4453           break;
4454
4455         case EXEC_OPEN:
4456           if (gfc_resolve_open (code->ext.open) == FAILURE)
4457             break;
4458
4459           resolve_branch (code->ext.open->err, code);
4460           break;
4461
4462         case EXEC_CLOSE:
4463           if (gfc_resolve_close (code->ext.close) == FAILURE)
4464             break;
4465
4466           resolve_branch (code->ext.close->err, code);
4467           break;
4468
4469         case EXEC_BACKSPACE:
4470         case EXEC_ENDFILE:
4471         case EXEC_REWIND:
4472         case EXEC_FLUSH:
4473           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
4474             break;
4475
4476           resolve_branch (code->ext.filepos->err, code);
4477           break;
4478
4479         case EXEC_INQUIRE:
4480           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
4481               break;
4482
4483           resolve_branch (code->ext.inquire->err, code);
4484           break;
4485
4486         case EXEC_IOLENGTH:
4487           gcc_assert (code->ext.inquire != NULL);
4488           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
4489             break;
4490
4491           resolve_branch (code->ext.inquire->err, code);
4492           break;
4493
4494         case EXEC_READ:
4495         case EXEC_WRITE:
4496           if (gfc_resolve_dt (code->ext.dt) == FAILURE)
4497             break;
4498
4499           resolve_branch (code->ext.dt->err, code);
4500           resolve_branch (code->ext.dt->end, code);
4501           resolve_branch (code->ext.dt->eor, code);
4502           break;
4503
4504         case EXEC_TRANSFER:
4505           resolve_transfer (code);
4506           break;
4507
4508         case EXEC_FORALL:
4509           resolve_forall_iterators (code->ext.forall_iterator);
4510
4511           if (code->expr != NULL && code->expr->ts.type != BT_LOGICAL)
4512             gfc_error
4513               ("FORALL mask clause at %L requires a LOGICAL expression",
4514                &code->expr->where);
4515           break;
4516
4517         case EXEC_OMP_ATOMIC:
4518         case EXEC_OMP_BARRIER:
4519         case EXEC_OMP_CRITICAL:
4520         case EXEC_OMP_FLUSH:
4521         case EXEC_OMP_DO:
4522         case EXEC_OMP_MASTER:
4523         case EXEC_OMP_ORDERED:
4524         case EXEC_OMP_SECTIONS:
4525         case EXEC_OMP_SINGLE:
4526         case EXEC_OMP_WORKSHARE:
4527           gfc_resolve_omp_directive (code, ns);
4528           break;
4529
4530         case EXEC_OMP_PARALLEL:
4531         case EXEC_OMP_PARALLEL_DO:
4532         case EXEC_OMP_PARALLEL_SECTIONS:
4533         case EXEC_OMP_PARALLEL_WORKSHARE:
4534           omp_workshare_save = omp_workshare_flag;
4535           omp_workshare_flag = 0;
4536           gfc_resolve_omp_directive (code, ns);
4537           omp_workshare_flag = omp_workshare_save;
4538           break;
4539
4540         default:
4541           gfc_internal_error ("resolve_code(): Bad statement code");
4542         }
4543     }
4544
4545   cs_base = frame.prev;
4546 }
4547
4548
4549 /* Resolve initial values and make sure they are compatible with
4550    the variable.  */
4551
4552 static void
4553 resolve_values (gfc_symbol * sym)
4554 {
4555
4556   if (sym->value == NULL)
4557     return;
4558
4559   if (gfc_resolve_expr (sym->value) == FAILURE)
4560     return;
4561
4562   gfc_check_assign_symbol (sym, sym->value);
4563 }
4564
4565
4566 /* Resolve an index expression.  */
4567
4568 static try
4569 resolve_index_expr (gfc_expr * e)
4570 {
4571
4572   if (gfc_resolve_expr (e) == FAILURE)
4573     return FAILURE;
4574
4575   if (gfc_simplify_expr (e, 0) == FAILURE)
4576     return FAILURE;
4577
4578   if (gfc_specification_expr (e) == FAILURE)
4579     return FAILURE;
4580
4581   return SUCCESS;
4582 }
4583
4584 /* Resolve a charlen structure.  */
4585
4586 static try
4587 resolve_charlen (gfc_charlen *cl)
4588 {
4589   if (cl->resolved)
4590     return SUCCESS;
4591
4592   cl->resolved = 1;
4593
4594   if (resolve_index_expr (cl->length) == FAILURE)
4595     return FAILURE;
4596
4597   return SUCCESS;
4598 }
4599
4600
4601 /* Resolution of common features of flavors variable and procedure. */
4602
4603 static try
4604 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
4605 {
4606   /* Constraints on deferred shape variable.  */
4607   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
4608     {
4609       if (sym->attr.allocatable)
4610         {
4611           if (sym->attr.dimension)
4612             gfc_error ("Allocatable array '%s' at %L must have "
4613                        "a deferred shape", sym->name, &sym->declared_at);
4614           else
4615             gfc_error ("Scalar object '%s' at %L may not be ALLOCATABLE",
4616                        sym->name, &sym->declared_at);
4617             return FAILURE;
4618         }
4619
4620       if (sym->attr.pointer && sym->attr.dimension)
4621         {
4622           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
4623                      sym->name, &sym->declared_at);
4624           return FAILURE;
4625         }
4626
4627     }
4628   else
4629     {
4630       if (!mp_flag && !sym->attr.allocatable
4631              && !sym->attr.pointer && !sym->attr.dummy)
4632         {
4633           gfc_error ("Array '%s' at %L cannot have a deferred shape",
4634                      sym->name, &sym->declared_at);
4635           return FAILURE;
4636          }
4637     }
4638   return SUCCESS;
4639 }
4640
4641 /* Resolve symbols with flavor variable.  */
4642
4643 static try
4644 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
4645 {
4646   int flag;
4647   int i;
4648   gfc_expr *e;
4649   gfc_expr *constructor_expr;
4650
4651   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
4652     return FAILURE;
4653
4654   /* The shape of a main program or module array needs to be constant.  */
4655   if (sym->as != NULL
4656         && sym->ns->proc_name
4657         && (sym->ns->proc_name->attr.flavor == FL_MODULE
4658              || sym->ns->proc_name->attr.is_main_program)
4659         && !sym->attr.use_assoc
4660         && !sym->attr.allocatable
4661         && !sym->attr.pointer)
4662     {
4663       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
4664          has not been simplified; parameter array references.  Do the
4665          simplification now.  */
4666       flag = 0;
4667       for (i = 0; i < sym->as->rank; i++)
4668         {
4669           e = sym->as->lower[i];
4670           if (e && (resolve_index_expr (e) == FAILURE
4671                 || !gfc_is_constant_expr (e)))
4672             {
4673               flag = 1;
4674               break;
4675             }
4676
4677           e = sym->as->upper[i];
4678           if (e && (resolve_index_expr (e) == FAILURE
4679                 || !gfc_is_constant_expr (e)))
4680             {
4681               flag = 1;
4682               break;
4683             }
4684         }
4685
4686       if (flag)
4687         {
4688           gfc_error ("The module or main program array '%s' at %L must "
4689                      "have constant shape", sym->name, &sym->declared_at);
4690           return FAILURE;
4691         }
4692     }
4693
4694   if (sym->ts.type == BT_CHARACTER)
4695     {
4696       /* Make sure that character string variables with assumed length are
4697          dummy arguments.  */
4698       e = sym->ts.cl->length;
4699       if (e == NULL && !sym->attr.dummy && !sym->attr.result)
4700         {
4701           gfc_error ("Entity with assumed character length at %L must be a "
4702                      "dummy argument or a PARAMETER", &sym->declared_at);
4703           return FAILURE;
4704         }
4705
4706       if (!gfc_is_constant_expr (e)
4707             && !(e->expr_type == EXPR_VARIABLE
4708             && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
4709             && sym->ns->proc_name
4710             && (sym->ns->proc_name->attr.flavor == FL_MODULE
4711                   || sym->ns->proc_name->attr.is_main_program)
4712             && !sym->attr.use_assoc)
4713         {
4714           gfc_error ("'%s' at %L must have constant character length "
4715                      "in this context", sym->name, &sym->declared_at);
4716           return FAILURE;
4717         }
4718     }
4719
4720   /* Can the symbol have an initializer?  */
4721   flag = 0;
4722   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
4723         || sym->attr.intrinsic || sym->attr.result)
4724     flag = 1;
4725   else if (sym->attr.dimension && !sym->attr.pointer)
4726     {
4727       /* Don't allow initialization of automatic arrays.  */
4728       for (i = 0; i < sym->as->rank; i++)
4729         {
4730           if (sym->as->lower[i] == NULL
4731                 || sym->as->lower[i]->expr_type != EXPR_CONSTANT
4732                 || sym->as->upper[i] == NULL
4733                 || sym->as->upper[i]->expr_type != EXPR_CONSTANT)
4734             {
4735               flag = 1;
4736               break;
4737             }
4738         }
4739   }
4740
4741   /* Reject illegal initializers.  */
4742   if (sym->value && flag)
4743     {
4744       if (sym->attr.allocatable)
4745         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
4746                    sym->name, &sym->declared_at);
4747       else if (sym->attr.external)
4748         gfc_error ("External '%s' at %L cannot have an initializer",
4749                    sym->name, &sym->declared_at);
4750       else if (sym->attr.dummy)
4751         gfc_error ("Dummy '%s' at %L cannot have an initializer",
4752                    sym->name, &sym->declared_at);
4753       else if (sym->attr.intrinsic)
4754         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
4755                    sym->name, &sym->declared_at);
4756       else if (sym->attr.result)
4757         gfc_error ("Function result '%s' at %L cannot have an initializer",
4758                    sym->name, &sym->declared_at);
4759       else
4760         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
4761                    sym->name, &sym->declared_at);
4762       return FAILURE;
4763     }
4764
4765   /* 4th constraint in section 11.3:  "If an object of a type for which
4766      component-initialization is specified (R429) appears in the
4767      specification-part of a module and does not have the ALLOCATABLE
4768      or POINTER attribute, the object shall have the SAVE attribute."  */
4769
4770   constructor_expr = NULL;
4771   if (sym->ts.type == BT_DERIVED && !(sym->value || flag))
4772         constructor_expr = gfc_default_initializer (&sym->ts);
4773
4774   if (sym->ns->proc_name
4775         && sym->ns->proc_name->attr.flavor == FL_MODULE
4776         && constructor_expr
4777         && !sym->ns->save_all && !sym->attr.save
4778         && !sym->attr.pointer && !sym->attr.allocatable)
4779     {
4780       gfc_error("Object '%s' at %L must have the SAVE attribute %s",
4781                 sym->name, &sym->declared_at,
4782                 "for default initialization of a component");
4783       return FAILURE;
4784     }
4785
4786   /* Assign default initializer.  */
4787   if (sym->ts.type == BT_DERIVED && !(sym->value || flag)
4788         && !sym->attr.pointer)
4789     sym->value = gfc_default_initializer (&sym->ts);
4790
4791   return SUCCESS;
4792 }
4793
4794
4795 /* Resolve a procedure.  */
4796
4797 static try
4798 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
4799 {
4800   gfc_formal_arglist *arg;
4801
4802   if (sym->attr.function
4803         && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
4804     return FAILURE;
4805
4806   if (sym->attr.proc == PROC_ST_FUNCTION)
4807     {
4808       if (sym->ts.type == BT_CHARACTER)
4809         {
4810           gfc_charlen *cl = sym->ts.cl;
4811           if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
4812             {
4813               gfc_error ("Character-valued statement function '%s' at %L must "
4814                          "have constant length", sym->name, &sym->declared_at);
4815               return FAILURE;
4816             }
4817         }
4818     }
4819
4820   /* Ensure that derived type formal arguments of a public procedure
4821      are not of a private type.  */
4822   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
4823     {
4824       for (arg = sym->formal; arg; arg = arg->next)
4825         {
4826           if (arg->sym
4827                 && arg->sym->ts.type == BT_DERIVED
4828                 && !arg->sym->ts.derived->attr.use_assoc
4829                 && !gfc_check_access(arg->sym->ts.derived->attr.access,
4830                         arg->sym->ts.derived->ns->default_access))
4831             {
4832               gfc_error_now ("'%s' is of a PRIVATE type and cannot be "
4833                              "a dummy argument of '%s', which is "
4834                              "PUBLIC at %L", arg->sym->name, sym->name,
4835                              &sym->declared_at);
4836               /* Stop this message from recurring.  */
4837               arg->sym->ts.derived->attr.access = ACCESS_PUBLIC;
4838               return FAILURE;
4839             }
4840         }
4841     }
4842
4843   /* An external symbol may not have an intializer because it is taken to be
4844      a procedure.  */
4845   if (sym->attr.external && sym->value)
4846     {
4847       gfc_error ("External object '%s' at %L may not have an initializer",
4848                  sym->name, &sym->declared_at);
4849       return FAILURE;
4850     }
4851
4852   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
4853      char-len-param shall not be array-valued, pointer-valued, recursive
4854      or pure.  ....snip... A character value of * may only be used in the
4855      following ways: (i) Dummy arg of procedure - dummy associates with
4856      actual length; (ii) To declare a named constant; or (iii) External
4857      function - but length must be declared in calling scoping unit.  */
4858   if (sym->attr.function
4859         && sym->ts.type == BT_CHARACTER
4860         && sym->ts.cl && sym->ts.cl->length == NULL)
4861     {
4862       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
4863              || (sym->attr.recursive) || (sym->attr.pure))
4864         {
4865           if (sym->as && sym->as->rank)
4866             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
4867                        "array-valued", sym->name, &sym->declared_at);
4868
4869           if (sym->attr.pointer)
4870             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
4871                        "pointer-valued", sym->name, &sym->declared_at);
4872
4873           if (sym->attr.pure)
4874             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
4875                        "pure", sym->name, &sym->declared_at);
4876
4877           if (sym->attr.recursive)
4878             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
4879                        "recursive", sym->name, &sym->declared_at);
4880
4881           return FAILURE;
4882         }
4883
4884       /* Appendix B.2 of the standard.  Contained functions give an
4885          error anyway.  Fixed-form is likely to be F77/legacy.  */
4886       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
4887         gfc_notify_std (GFC_STD_F95_OBS, "CHARACTER(*) function "
4888                         "'%s' at %L is obsolescent in fortran 95",
4889                         sym->name, &sym->declared_at);
4890     }
4891   return SUCCESS;
4892 }
4893
4894
4895 /* Resolve the components of a derived type.  */
4896
4897 static try
4898 resolve_fl_derived (gfc_symbol *sym)
4899 {
4900   gfc_component *c;
4901   gfc_dt_list * dt_list;
4902   int i;
4903
4904   for (c = sym->components; c != NULL; c = c->next)
4905     {
4906       if (c->ts.type == BT_CHARACTER)
4907         {
4908          if (c->ts.cl->length == NULL
4909              || (resolve_charlen (c->ts.cl) == FAILURE)
4910              || !gfc_is_constant_expr (c->ts.cl->length))
4911            {
4912              gfc_error ("Character length of component '%s' needs to "
4913                         "be a constant specification expression at %L.",
4914                         c->name,
4915                         c->ts.cl->length ? &c->ts.cl->length->where : &c->loc);
4916              return FAILURE;
4917            }
4918         }
4919
4920       if (c->ts.type == BT_DERIVED
4921             && sym->component_access != ACCESS_PRIVATE
4922             && gfc_check_access(sym->attr.access, sym->ns->default_access)
4923             && !c->ts.derived->attr.use_assoc
4924             && !gfc_check_access(c->ts.derived->attr.access,
4925                                  c->ts.derived->ns->default_access))
4926         {
4927           gfc_error ("The component '%s' is a PRIVATE type and cannot be "
4928                      "a component of '%s', which is PUBLIC at %L",
4929                       c->name, sym->name, &sym->declared_at);
4930           return FAILURE;
4931         }
4932
4933       if (c->pointer || c->as == NULL)
4934         continue;
4935
4936       for (i = 0; i < c->as->rank; i++)
4937         {
4938           if (c->as->lower[i] == NULL
4939                 || !gfc_is_constant_expr (c->as->lower[i])
4940                 || (resolve_index_expr (c->as->lower[i]) == FAILURE)
4941                 || c->as->upper[i] == NULL
4942                 || (resolve_index_expr (c->as->upper[i]) == FAILURE)
4943                 || !gfc_is_constant_expr (c->as->upper[i]))
4944             {
4945               gfc_error ("Component '%s' of '%s' at %L must have "
4946                          "constant array bounds.",
4947                          c->name, sym->name, &c->loc);
4948               return FAILURE;
4949             }
4950         }
4951     }
4952     
4953   /* Add derived type to the derived type list.  */
4954   dt_list = gfc_get_dt_list ();
4955   dt_list->next = sym->ns->derived_types;
4956   dt_list->derived = sym;
4957   sym->ns->derived_types = dt_list;
4958
4959   return SUCCESS;
4960 }
4961
4962
4963 static try
4964 resolve_fl_parameter (gfc_symbol *sym)
4965 {
4966   /* A parameter array's shape needs to be constant.  */
4967   if (sym->as != NULL && !gfc_is_compile_time_shape (sym->as))
4968     {
4969       gfc_error ("Parameter array '%s' at %L cannot be automatic "
4970                  "or assumed shape", sym->name, &sym->declared_at);
4971       return FAILURE;
4972     }
4973
4974   /* Make sure a parameter that has been implicitly typed still
4975      matches the implicit type, since PARAMETER statements can precede
4976      IMPLICIT statements.  */
4977   if (sym->attr.implicit_type
4978         && !gfc_compare_types (&sym->ts,
4979                                gfc_get_default_type (sym, sym->ns)))
4980     {
4981       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
4982                  "later IMPLICIT type", sym->name, &sym->declared_at);
4983       return FAILURE;
4984     }
4985
4986   /* Make sure the types of derived parameters are consistent.  This
4987      type checking is deferred until resolution because the type may
4988      refer to a derived type from the host.  */
4989   if (sym->ts.type == BT_DERIVED
4990         && !gfc_compare_types (&sym->ts, &sym->value->ts))
4991     {
4992       gfc_error ("Incompatible derived type in PARAMETER at %L",
4993                  &sym->value->where);
4994       return FAILURE;
4995     }
4996   return SUCCESS;
4997 }
4998
4999
5000 /* Do anything necessary to resolve a symbol.  Right now, we just
5001    assume that an otherwise unknown symbol is a variable.  This sort
5002    of thing commonly happens for symbols in module.  */
5003
5004 static void
5005 resolve_symbol (gfc_symbol * sym)
5006 {
5007   /* Zero if we are checking a formal namespace.  */
5008   static int formal_ns_flag = 1;
5009   int formal_ns_save, check_constant, mp_flag;
5010   gfc_namelist *nl;
5011   gfc_symtree *symtree;
5012   gfc_symtree *this_symtree;
5013   gfc_namespace *ns;
5014   gfc_component *c;
5015
5016   if (sym->attr.flavor == FL_UNKNOWN)
5017     {
5018
5019     /* If we find that a flavorless symbol is an interface in one of the
5020        parent namespaces, find its symtree in this namespace, free the
5021        symbol and set the symtree to point to the interface symbol.  */
5022       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
5023         {
5024           symtree = gfc_find_symtree (ns->sym_root, sym->name);
5025           if (symtree && symtree->n.sym->generic)
5026             {
5027               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
5028                                                sym->name);
5029               sym->refs--;
5030               if (!sym->refs)
5031                 gfc_free_symbol (sym);
5032               symtree->n.sym->refs++;
5033               this_symtree->n.sym = symtree->n.sym;
5034               return;
5035             }
5036         }
5037
5038       /* Otherwise give it a flavor according to such attributes as
5039          it has.  */
5040       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
5041         sym->attr.flavor = FL_VARIABLE;
5042       else
5043         {
5044           sym->attr.flavor = FL_PROCEDURE;
5045           if (sym->attr.dimension)
5046             sym->attr.function = 1;
5047         }
5048     }
5049
5050   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
5051     return;
5052
5053   /* Symbols that are module procedures with results (functions) have
5054      the types and array specification copied for type checking in
5055      procedures that call them, as well as for saving to a module
5056      file.  These symbols can't stand the scrutiny that their results
5057      can.  */
5058   mp_flag = (sym->result != NULL && sym->result != sym);
5059
5060   /* Assign default type to symbols that need one and don't have one.  */
5061   if (sym->ts.type == BT_UNKNOWN)
5062     {
5063       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
5064         gfc_set_default_type (sym, 1, NULL);
5065
5066       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
5067         {
5068           /* The specific case of an external procedure should emit an error
5069              in the case that there is no implicit type.  */
5070           if (!mp_flag)
5071             gfc_set_default_type (sym, sym->attr.external, NULL);
5072           else
5073             {
5074               /* Result may be in another namespace.  */
5075               resolve_symbol (sym->result);
5076
5077               sym->ts = sym->result->ts;
5078               sym->as = gfc_copy_array_spec (sym->result->as);
5079               sym->attr.dimension = sym->result->attr.dimension;
5080               sym->attr.pointer = sym->result->attr.pointer;
5081             }
5082         }
5083     }
5084
5085   /* Assumed size arrays and assumed shape arrays must be dummy
5086      arguments.  */ 
5087
5088   if (sym->as != NULL
5089       && (sym->as->type == AS_ASSUMED_SIZE
5090           || sym->as->type == AS_ASSUMED_SHAPE)
5091       && sym->attr.dummy == 0)
5092     {
5093       if (sym->as->type == AS_ASSUMED_SIZE)
5094         gfc_error ("Assumed size array at %L must be a dummy argument",
5095                    &sym->declared_at);
5096       else
5097         gfc_error ("Assumed shape array at %L must be a dummy argument",
5098                    &sym->declared_at);
5099       return;
5100     }
5101
5102   /* Make sure symbols with known intent or optional are really dummy
5103      variable.  Because of ENTRY statement, this has to be deferred
5104      until resolution time.  */
5105
5106   if (!sym->attr.dummy
5107       && (sym->attr.optional
5108           || sym->attr.intent != INTENT_UNKNOWN))
5109     {
5110       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
5111       return;
5112     }
5113
5114   /* If a derived type symbol has reached this point, without its
5115      type being declared, we have an error.  Notice that most
5116      conditions that produce undefined derived types have already
5117      been dealt with.  However, the likes of:
5118      implicit type(t) (t) ..... call foo (t) will get us here if
5119      the type is not declared in the scope of the implicit
5120      statement. Change the type to BT_UNKNOWN, both because it is so
5121      and to prevent an ICE.  */
5122   if (sym->ts.type == BT_DERIVED
5123         && sym->ts.derived->components == NULL)
5124     {
5125       gfc_error ("The derived type '%s' at %L is of type '%s', "
5126                  "which has not been defined.", sym->name,
5127                   &sym->declared_at, sym->ts.derived->name);
5128       sym->ts.type = BT_UNKNOWN;
5129       return;
5130     }
5131
5132   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
5133      default initialization is defined (5.1.2.4.4).  */
5134   if (sym->ts.type == BT_DERIVED
5135         && sym->attr.dummy
5136         && sym->attr.intent == INTENT_OUT
5137         && sym->as
5138         && sym->as->type == AS_ASSUMED_SIZE)
5139     {
5140       for (c = sym->ts.derived->components; c; c = c->next)
5141         {
5142           if (c->initializer)
5143             {
5144               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
5145                          "ASSUMED SIZE and so cannot have a default initializer",
5146                          sym->name, &sym->declared_at);
5147               return;
5148             }
5149         }
5150     }
5151
5152   switch (sym->attr.flavor)
5153     {
5154     case FL_VARIABLE:
5155       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
5156         return;
5157       break;
5158
5159     case FL_PROCEDURE:
5160       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
5161         return;
5162       break;
5163
5164     case FL_NAMELIST:
5165       /* Reject PRIVATE objects in a PUBLIC namelist.  */
5166       if (gfc_check_access(sym->attr.access, sym->ns->default_access))
5167         {
5168           for (nl = sym->namelist; nl; nl = nl->next)
5169             {
5170               if (!nl->sym->attr.use_assoc
5171                     &&
5172                   !(sym->ns->parent == nl->sym->ns)
5173                     &&
5174                   !gfc_check_access(nl->sym->attr.access,
5175                                     nl->sym->ns->default_access))
5176                 gfc_error ("PRIVATE symbol '%s' cannot be member of "
5177                            "PUBLIC namelist at %L", nl->sym->name,
5178                            &sym->declared_at);
5179             }
5180         }
5181
5182       break;
5183
5184     case FL_PARAMETER:
5185       if (resolve_fl_parameter (sym) == FAILURE)
5186         return;
5187
5188       break;
5189
5190     default:
5191
5192       break;
5193     }
5194
5195
5196   /* Make sure that intrinsic exist */
5197   if (sym->attr.intrinsic
5198       && ! gfc_intrinsic_name(sym->name, 0)
5199       && ! gfc_intrinsic_name(sym->name, 1))
5200     gfc_error("Intrinsic at %L does not exist", &sym->declared_at);
5201
5202   /* Resolve array specifier. Check as well some constraints
5203      on COMMON blocks.  */
5204
5205   check_constant = sym->attr.in_common && !sym->attr.pointer;
5206   gfc_resolve_array_spec (sym->as, check_constant);
5207
5208   /* Resolve formal namespaces.  */
5209
5210   if (formal_ns_flag && sym != NULL && sym->formal_ns != NULL)
5211     {
5212       formal_ns_save = formal_ns_flag;
5213       formal_ns_flag = 0;
5214       gfc_resolve (sym->formal_ns);
5215       formal_ns_flag = formal_ns_save;
5216     }
5217
5218   /* Check threadprivate restrictions.  */
5219   if (sym->attr.threadprivate && !sym->attr.save
5220       && (!sym->attr.in_common
5221           && sym->module == NULL
5222           && (sym->ns->proc_name == NULL
5223               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
5224     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
5225 }
5226
5227
5228
5229 /************* Resolve DATA statements *************/
5230
5231 static struct
5232 {
5233   gfc_data_value *vnode;
5234   unsigned int left;
5235 }
5236 values;
5237
5238
5239 /* Advance the values structure to point to the next value in the data list.  */
5240
5241 static try
5242 next_data_value (void)
5243 {
5244   while (values.left == 0)
5245     {
5246       if (values.vnode->next == NULL)
5247         return FAILURE;
5248
5249       values.vnode = values.vnode->next;
5250       values.left = values.vnode->repeat;
5251     }
5252
5253   return SUCCESS;
5254 }
5255
5256
5257 static try
5258 check_data_variable (gfc_data_variable * var, locus * where)
5259 {
5260   gfc_expr *e;
5261   mpz_t size;
5262   mpz_t offset;
5263   try t;
5264   ar_type mark = AR_UNKNOWN;
5265   int i;
5266   mpz_t section_index[GFC_MAX_DIMENSIONS];
5267   gfc_ref *ref;
5268   gfc_array_ref *ar;
5269
5270   if (gfc_resolve_expr (var->expr) == FAILURE)
5271     return FAILURE;
5272
5273   ar = NULL;
5274   mpz_init_set_si (offset, 0);
5275   e = var->expr;
5276
5277   if (e->expr_type != EXPR_VARIABLE)
5278     gfc_internal_error ("check_data_variable(): Bad expression");
5279
5280   if (e->symtree->n.sym->ns->is_block_data
5281         && !e->symtree->n.sym->attr.in_common)
5282     {
5283       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
5284                  e->symtree->n.sym->name, &e->symtree->n.sym->declared_at);
5285     }
5286
5287   if (e->rank == 0)
5288     {
5289       mpz_init_set_ui (size, 1);
5290       ref = NULL;
5291     }
5292   else
5293     {
5294       ref = e->ref;
5295
5296       /* Find the array section reference.  */
5297       for (ref = e->ref; ref; ref = ref->next)
5298         {
5299           if (ref->type != REF_ARRAY)
5300             continue;
5301           if (ref->u.ar.type == AR_ELEMENT)
5302             continue;
5303           break;
5304         }
5305       gcc_assert (ref);
5306
5307       /* Set marks according to the reference pattern.  */
5308       switch (ref->u.ar.type)
5309         {
5310         case AR_FULL:
5311           mark = AR_FULL;
5312           break;
5313
5314         case AR_SECTION:
5315           ar = &ref->u.ar;
5316           /* Get the start position of array section.  */
5317           gfc_get_section_index (ar, section_index, &offset);
5318           mark = AR_SECTION;
5319           break;
5320
5321         default:
5322           gcc_unreachable ();
5323         }
5324
5325       if (gfc_array_size (e, &size) == FAILURE)
5326         {
5327           gfc_error ("Nonconstant array section at %L in DATA statement",
5328                      &e->where);
5329           mpz_clear (offset);
5330           return FAILURE;
5331         }
5332     }
5333
5334   t = SUCCESS;
5335
5336   while (mpz_cmp_ui (size, 0) > 0)
5337     {
5338       if (next_data_value () == FAILURE)
5339         {
5340           gfc_error ("DATA statement at %L has more variables than values",
5341                      where);
5342           t = FAILURE;
5343           break;
5344         }
5345
5346       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
5347       if (t == FAILURE)
5348         break;
5349
5350       /* If we have more than one element left in the repeat count,
5351          and we have more than one element left in the target variable,
5352          then create a range assignment.  */
5353       /* ??? Only done for full arrays for now, since array sections
5354          seem tricky.  */
5355       if (mark == AR_FULL && ref && ref->next == NULL
5356           && values.left > 1 && mpz_cmp_ui (size, 1) > 0)
5357         {
5358           mpz_t range;
5359
5360           if (mpz_cmp_ui (size, values.left) >= 0)
5361             {
5362               mpz_init_set_ui (range, values.left);
5363               mpz_sub_ui (size, size, values.left);
5364               values.left = 0;
5365             }
5366           else
5367             {
5368               mpz_init_set (range, size);
5369               values.left -= mpz_get_ui (size);
5370               mpz_set_ui (size, 0);
5371             }
5372
5373           gfc_assign_data_value_range (var->expr, values.vnode->expr,
5374                                        offset, range);
5375
5376           mpz_add (offset, offset, range);
5377           mpz_clear (range);
5378         }
5379
5380       /* Assign initial value to symbol.  */
5381       else
5382         {
5383           values.left -= 1;
5384           mpz_sub_ui (size, size, 1);
5385
5386           gfc_assign_data_value (var->expr, values.vnode->expr, offset);
5387
5388           if (mark == AR_FULL)
5389             mpz_add_ui (offset, offset, 1);
5390
5391           /* Modify the array section indexes and recalculate the offset
5392              for next element.  */
5393           else if (mark == AR_SECTION)
5394             gfc_advance_section (section_index, ar, &offset);
5395         }
5396     }
5397
5398   if (mark == AR_SECTION)
5399     {
5400       for (i = 0; i < ar->dimen; i++)
5401         mpz_clear (section_index[i]);
5402     }
5403
5404   mpz_clear (size);
5405   mpz_clear (offset);
5406
5407   return t;
5408 }
5409
5410
5411 static try traverse_data_var (gfc_data_variable *, locus *);
5412
5413 /* Iterate over a list of elements in a DATA statement.  */
5414
5415 static try
5416 traverse_data_list (gfc_data_variable * var, locus * where)
5417 {
5418   mpz_t trip;
5419   iterator_stack frame;
5420   gfc_expr *e;
5421
5422   mpz_init (frame.value);
5423
5424   mpz_init_set (trip, var->iter.end->value.integer);
5425   mpz_sub (trip, trip, var->iter.start->value.integer);
5426   mpz_add (trip, trip, var->iter.step->value.integer);
5427
5428   mpz_div (trip, trip, var->iter.step->value.integer);
5429
5430   mpz_set (frame.value, var->iter.start->value.integer);
5431
5432   frame.prev = iter_stack;
5433   frame.variable = var->iter.var->symtree;
5434   iter_stack = &frame;
5435
5436   while (mpz_cmp_ui (trip, 0) > 0)
5437     {
5438       if (traverse_data_var (var->list, where) == FAILURE)
5439         {
5440           mpz_clear (trip);
5441           return FAILURE;
5442         }
5443
5444       e = gfc_copy_expr (var->expr);
5445       if (gfc_simplify_expr (e, 1) == FAILURE)
5446         {
5447           gfc_free_expr (e);
5448           return FAILURE;
5449         }
5450
5451       mpz_add (frame.value, frame.value, var->iter.step->value.integer);
5452
5453       mpz_sub_ui (trip, trip, 1);
5454     }
5455
5456   mpz_clear (trip);
5457   mpz_clear (frame.value);
5458
5459   iter_stack = frame.prev;
5460   return SUCCESS;
5461 }
5462
5463
5464 /* Type resolve variables in the variable list of a DATA statement.  */
5465
5466 static try
5467 traverse_data_var (gfc_data_variable * var, locus * where)
5468 {
5469   try t;
5470
5471   for (; var; var = var->next)
5472     {
5473       if (var->expr == NULL)
5474         t = traverse_data_list (var, where);
5475       else
5476         t = check_data_variable (var, where);
5477
5478       if (t == FAILURE)
5479         return FAILURE;
5480     }
5481
5482   return SUCCESS;
5483 }
5484
5485
5486 /* Resolve the expressions and iterators associated with a data statement.
5487    This is separate from the assignment checking because data lists should
5488    only be resolved once.  */
5489
5490 static try
5491 resolve_data_variables (gfc_data_variable * d)
5492 {
5493   for (; d; d = d->next)
5494     {
5495       if (d->list == NULL)
5496         {
5497           if (gfc_resolve_expr (d->expr) == FAILURE)
5498             return FAILURE;
5499         }
5500       else
5501         {
5502           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
5503             return FAILURE;
5504
5505           if (d->iter.start->expr_type != EXPR_CONSTANT
5506               || d->iter.end->expr_type != EXPR_CONSTANT
5507               || d->iter.step->expr_type != EXPR_CONSTANT)
5508             gfc_internal_error ("resolve_data_variables(): Bad iterator");
5509
5510           if (resolve_data_variables (d->list) == FAILURE)
5511             return FAILURE;
5512         }
5513     }
5514
5515   return SUCCESS;
5516 }
5517
5518
5519 /* Resolve a single DATA statement.  We implement this by storing a pointer to
5520    the value list into static variables, and then recursively traversing the
5521    variables list, expanding iterators and such.  */
5522
5523 static void
5524 resolve_data (gfc_data * d)
5525 {
5526   if (resolve_data_variables (d->var) == FAILURE)
5527     return;
5528
5529   values.vnode = d->value;
5530   values.left = (d->value == NULL) ? 0 : d->value->repeat;
5531
5532   if (traverse_data_var (d->var, &d->where) == FAILURE)
5533     return;
5534
5535   /* At this point, we better not have any values left.  */
5536
5537   if (next_data_value () == SUCCESS)
5538     gfc_error ("DATA statement at %L has more values than variables",
5539                &d->where);
5540 }
5541
5542
5543 /* Determines if a variable is not 'pure', ie not assignable within a pure
5544    procedure.  Returns zero if assignment is OK, nonzero if there is a problem.
5545  */
5546
5547 int
5548 gfc_impure_variable (gfc_symbol * sym)
5549 {
5550   if (sym->attr.use_assoc || sym->attr.in_common)
5551     return 1;
5552
5553   if (sym->ns != gfc_current_ns)
5554     return !sym->attr.function;
5555
5556   /* TODO: Check storage association through EQUIVALENCE statements */
5557
5558   return 0;
5559 }
5560
5561
5562 /* Test whether a symbol is pure or not.  For a NULL pointer, checks the
5563    symbol of the current procedure.  */
5564
5565 int
5566 gfc_pure (gfc_symbol * sym)
5567 {
5568   symbol_attribute attr;
5569
5570   if (sym == NULL)
5571     sym = gfc_current_ns->proc_name;
5572   if (sym == NULL)
5573     return 0;
5574
5575   attr = sym->attr;
5576
5577   return attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental);
5578 }
5579
5580
5581 /* Test whether the current procedure is elemental or not.  */
5582
5583 int
5584 gfc_elemental (gfc_symbol * sym)
5585 {
5586   symbol_attribute attr;
5587
5588   if (sym == NULL)
5589     sym = gfc_current_ns->proc_name;
5590   if (sym == NULL)
5591     return 0;
5592   attr = sym->attr;
5593
5594   return attr.flavor == FL_PROCEDURE && attr.elemental;
5595 }
5596
5597
5598 /* Warn about unused labels.  */
5599
5600 static void
5601 warn_unused_label (gfc_st_label * label)
5602 {
5603   if (label == NULL)
5604     return;
5605
5606   warn_unused_label (label->left);
5607
5608   if (label->defined == ST_LABEL_UNKNOWN)
5609     return;
5610
5611   switch (label->referenced)
5612     {
5613     case ST_LABEL_UNKNOWN:
5614       gfc_warning ("Label %d at %L defined but not used", label->value,
5615                    &label->where);
5616       break;
5617
5618     case ST_LABEL_BAD_TARGET:
5619       gfc_warning ("Label %d at %L defined but cannot be used",
5620                    label->value, &label->where);
5621       break;
5622
5623     default:
5624       break;
5625     }
5626
5627   warn_unused_label (label->right);
5628 }
5629
5630
5631 /* Returns the sequence type of a symbol or sequence.  */
5632
5633 static seq_type
5634 sequence_type (gfc_typespec ts)
5635 {
5636   seq_type result;
5637   gfc_component *c;
5638
5639   switch (ts.type)
5640   {
5641     case BT_DERIVED:
5642
5643       if (ts.derived->components == NULL)
5644         return SEQ_NONDEFAULT;
5645
5646       result = sequence_type (ts.derived->components->ts);
5647       for (c = ts.derived->components->next; c; c = c->next)
5648         if (sequence_type (c->ts) != result)
5649           return SEQ_MIXED;
5650
5651       return result;
5652
5653     case BT_CHARACTER:
5654       if (ts.kind != gfc_default_character_kind)
5655           return SEQ_NONDEFAULT;
5656
5657       return SEQ_CHARACTER;
5658
5659     case BT_INTEGER:
5660       if (ts.kind != gfc_default_integer_kind)
5661           return SEQ_NONDEFAULT;
5662
5663       return SEQ_NUMERIC;
5664
5665     case BT_REAL:
5666       if (!(ts.kind == gfc_default_real_kind
5667              || ts.kind == gfc_default_double_kind))
5668           return SEQ_NONDEFAULT;
5669
5670       return SEQ_NUMERIC;
5671
5672     case BT_COMPLEX:
5673       if (ts.kind != gfc_default_complex_kind)
5674           return SEQ_NONDEFAULT;
5675
5676       return SEQ_NUMERIC;
5677
5678     case BT_LOGICAL:
5679       if (ts.kind != gfc_default_logical_kind)
5680           return SEQ_NONDEFAULT;
5681
5682       return SEQ_NUMERIC;
5683
5684     default:
5685       return SEQ_NONDEFAULT;
5686   }
5687 }
5688
5689
5690 /* Resolve derived type EQUIVALENCE object.  */
5691
5692 static try
5693 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
5694 {
5695   gfc_symbol *d;
5696   gfc_component *c = derived->components;
5697
5698   if (!derived)
5699     return SUCCESS;
5700
5701   /* Shall not be an object of nonsequence derived type.  */
5702   if (!derived->attr.sequence)
5703     {
5704       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
5705                  "attribute to be an EQUIVALENCE object", sym->name, &e->where);
5706       return FAILURE;
5707     }
5708
5709   for (; c ; c = c->next)
5710     {
5711       d = c->ts.derived;
5712       if (d && (resolve_equivalence_derived (c->ts.derived, sym, e) == FAILURE))
5713         return FAILURE;
5714         
5715       /* Shall not be an object of sequence derived type containing a pointer
5716          in the structure.  */
5717       if (c->pointer)
5718         {
5719           gfc_error ("Derived type variable '%s' at %L with pointer component(s) "
5720                      "cannot be an EQUIVALENCE object", sym->name, &e->where);
5721           return FAILURE;
5722         }
5723
5724       if (c->initializer)
5725         {
5726           gfc_error ("Derived type variable '%s' at %L with default initializer "
5727                      "cannot be an EQUIVALENCE object", sym->name, &e->where);
5728           return FAILURE;
5729         }
5730     }
5731   return SUCCESS;
5732 }
5733
5734
5735 /* Resolve equivalence object. 
5736    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
5737    an allocatable array, an object of nonsequence derived type, an object of
5738    sequence derived type containing a pointer at any level of component
5739    selection, an automatic object, a function name, an entry name, a result
5740    name, a named constant, a structure component, or a subobject of any of
5741    the preceding objects.  A substring shall not have length zero.  A
5742    derived type shall not have components with default initialization nor
5743    shall two objects of an equivalence group be initialized.
5744    The simple constraints are done in symbol.c(check_conflict) and the rest
5745    are implemented here.  */
5746
5747 static void
5748 resolve_equivalence (gfc_equiv *eq)
5749 {
5750   gfc_symbol *sym;
5751   gfc_symbol *derived;
5752   gfc_symbol *first_sym;
5753   gfc_expr *e;
5754   gfc_ref *r;
5755   locus *last_where = NULL;
5756   seq_type eq_type, last_eq_type;
5757   gfc_typespec *last_ts;
5758   int object;
5759   const char *value_name;
5760   const char *msg;
5761
5762   value_name = NULL;
5763   last_ts = &eq->expr->symtree->n.sym->ts;
5764
5765   first_sym = eq->expr->symtree->n.sym;
5766
5767   for (object = 1; eq; eq = eq->eq, object++)
5768     {
5769       e = eq->expr;
5770
5771       e->ts = e->symtree->n.sym->ts;
5772       /* match_varspec might not know yet if it is seeing
5773          array reference or substring reference, as it doesn't
5774          know the types.  */
5775       if (e->ref && e->ref->type == REF_ARRAY)
5776         {
5777           gfc_ref *ref = e->ref;
5778           sym = e->symtree->n.sym;
5779
5780           if (sym->attr.dimension)
5781             {
5782               ref->u.ar.as = sym->as;
5783               ref = ref->next;
5784             }
5785
5786           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
5787           if (e->ts.type == BT_CHARACTER
5788               && ref
5789               && ref->type == REF_ARRAY
5790               && ref->u.ar.dimen == 1
5791               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
5792               && ref->u.ar.stride[0] == NULL)
5793             {
5794               gfc_expr *start = ref->u.ar.start[0];
5795               gfc_expr *end = ref->u.ar.end[0];
5796               void *mem = NULL;
5797
5798               /* Optimize away the (:) reference.  */
5799               if (start == NULL && end == NULL)
5800                 {
5801                   if (e->ref == ref)
5802                     e->ref = ref->next;
5803                   else
5804                     e->ref->next = ref->next;
5805                   mem = ref;
5806                 }
5807               else
5808                 {
5809                   ref->type = REF_SUBSTRING;
5810                   if (start == NULL)
5811                     start = gfc_int_expr (1);
5812                   ref->u.ss.start = start;
5813                   if (end == NULL && e->ts.cl)
5814                     end = gfc_copy_expr (e->ts.cl->length);
5815                   ref->u.ss.end = end;
5816                   ref->u.ss.length = e->ts.cl;
5817                   e->ts.cl = NULL;
5818                 }
5819               ref = ref->next;
5820               gfc_free (mem);
5821             }
5822
5823           /* Any further ref is an error.  */
5824           if (ref)
5825             {
5826               gcc_assert (ref->type == REF_ARRAY);
5827               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
5828                          &ref->u.ar.where);
5829               continue;
5830             }
5831         }
5832
5833       if (gfc_resolve_expr (e) == FAILURE)
5834         continue;
5835
5836       sym = e->symtree->n.sym;
5837
5838       /* An equivalence statement cannot have more than one initialized
5839          object.  */
5840       if (sym->value)
5841         {
5842           if (value_name != NULL)
5843             {
5844               gfc_error ("Initialized objects '%s' and '%s'  cannot both "
5845                          "be in the EQUIVALENCE statement at %L",
5846                          value_name, sym->name, &e->where);
5847               continue;
5848             }
5849           else
5850             value_name = sym->name;
5851         }
5852
5853       /* Shall not equivalence common block variables in a PURE procedure.  */
5854       if (sym->ns->proc_name 
5855             && sym->ns->proc_name->attr.pure
5856             && sym->attr.in_common)
5857         {
5858           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
5859                      "object in the pure procedure '%s'",
5860                      sym->name, &e->where, sym->ns->proc_name->name);
5861           break;
5862         }
5863  
5864       /* Shall not be a named constant.  */      
5865       if (e->expr_type == EXPR_CONSTANT)
5866         {
5867           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
5868                      "object", sym->name, &e->where);
5869           continue;
5870         }
5871
5872       derived = e->ts.derived;
5873       if (derived && resolve_equivalence_derived (derived, sym, e) == FAILURE)
5874         continue;
5875
5876       /* Check that the types correspond correctly:
5877          Note 5.28:
5878          A numeric sequence structure may be equivalenced to another sequence
5879          structure, an object of default integer type, default real type, double
5880          precision real type, default logical type such that components of the
5881          structure ultimately only become associated to objects of the same
5882          kind. A character sequence structure may be equivalenced to an object
5883          of default character kind or another character sequence structure.
5884          Other objects may be equivalenced only to objects of the same type and
5885          kind parameters.  */
5886
5887       /* Identical types are unconditionally OK.  */
5888       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
5889         goto identical_types;
5890
5891       last_eq_type = sequence_type (*last_ts);
5892       eq_type = sequence_type (sym->ts);
5893
5894       /* Since the pair of objects is not of the same type, mixed or
5895          non-default sequences can be rejected.  */
5896
5897       msg = "Sequence %s with mixed components in EQUIVALENCE "
5898             "statement at %L with different type objects";
5899       if ((object ==2
5900                && last_eq_type == SEQ_MIXED
5901                && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
5902                                   last_where) == FAILURE)
5903            ||  (eq_type == SEQ_MIXED
5904                && gfc_notify_std (GFC_STD_GNU, msg,sym->name,
5905                                   &e->where) == FAILURE))
5906         continue;
5907
5908       msg = "Non-default type object or sequence %s in EQUIVALENCE "
5909             "statement at %L with objects of different type";
5910       if ((object ==2
5911                && last_eq_type == SEQ_NONDEFAULT
5912                && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
5913                                   last_where) == FAILURE)
5914            ||  (eq_type == SEQ_NONDEFAULT
5915                && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
5916                                   &e->where) == FAILURE))
5917         continue;
5918
5919       msg ="Non-CHARACTER object '%s' in default CHARACTER "
5920            "EQUIVALENCE statement at %L";
5921       if (last_eq_type == SEQ_CHARACTER
5922             && eq_type != SEQ_CHARACTER
5923             && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
5924                                   &e->where) == FAILURE)
5925                 continue;
5926
5927       msg ="Non-NUMERIC object '%s' in default NUMERIC "
5928            "EQUIVALENCE statement at %L";
5929       if (last_eq_type == SEQ_NUMERIC
5930             && eq_type != SEQ_NUMERIC
5931             && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
5932                                   &e->where) == FAILURE)
5933                 continue;
5934
5935   identical_types:
5936       last_ts =&sym->ts;
5937       last_where = &e->where;
5938
5939       if (!e->ref)
5940         continue;
5941
5942       /* Shall not be an automatic array.  */
5943       if (e->ref->type == REF_ARRAY
5944           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
5945         {
5946           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
5947                      "an EQUIVALENCE object", sym->name, &e->where);
5948           continue;
5949         }
5950
5951       r = e->ref;
5952       while (r)
5953         {
5954           /* Shall not be a structure component.  */
5955           if (r->type == REF_COMPONENT)
5956             {
5957               gfc_error ("Structure component '%s' at %L cannot be an "
5958                          "EQUIVALENCE object",
5959                          r->u.c.component->name, &e->where);
5960               break;
5961             }
5962
5963           /* A substring shall not have length zero.  */
5964           if (r->type == REF_SUBSTRING)
5965             {
5966               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
5967                 {
5968                   gfc_error ("Substring at %L has length zero",
5969                              &r->u.ss.start->where);
5970                   break;
5971                 }
5972             }
5973           r = r->next;
5974         }
5975     }    
5976 }      
5977
5978
5979 /* Resolve function and ENTRY types, issue diagnostics if needed. */
5980
5981 static void
5982 resolve_fntype (gfc_namespace * ns)
5983 {
5984   gfc_entry_list *el;
5985   gfc_symbol *sym;
5986
5987   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
5988     return;
5989
5990   /* If there are any entries, ns->proc_name is the entry master
5991      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
5992   if (ns->entries)
5993     sym = ns->entries->sym;
5994   else
5995     sym = ns->proc_name;
5996   if (sym->result == sym
5997       && sym->ts.type == BT_UNKNOWN
5998       && gfc_set_default_type (sym, 0, NULL) == FAILURE
5999       && !sym->attr.untyped)
6000     {
6001       gfc_error ("Function '%s' at %L has no IMPLICIT type",
6002                  sym->name, &sym->declared_at);
6003       sym->attr.untyped = 1;
6004     }
6005
6006   if (sym->ts.type == BT_DERIVED && !sym->ts.derived->attr.use_assoc
6007       && !gfc_check_access (sym->ts.derived->attr.access,
6008                             sym->ts.derived->ns->default_access)
6009       && gfc_check_access (sym->attr.access, sym->ns->default_access))
6010     {
6011       gfc_error ("PUBLIC function '%s' at %L cannot be of PRIVATE type '%s'",
6012                  sym->name, &sym->declared_at, sym->ts.derived->name);
6013     }
6014
6015   if (ns->entries)
6016     for (el = ns->entries->next; el; el = el->next)
6017       {
6018         if (el->sym->result == el->sym
6019             && el->sym->ts.type == BT_UNKNOWN
6020             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
6021             && !el->sym->attr.untyped)
6022           {
6023             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
6024                        el->sym->name, &el->sym->declared_at);
6025             el->sym->attr.untyped = 1;
6026           }
6027       }
6028 }
6029
6030
6031 /* Examine all of the expressions associated with a program unit,
6032    assign types to all intermediate expressions, make sure that all
6033    assignments are to compatible types and figure out which names
6034    refer to which functions or subroutines.  It doesn't check code
6035    block, which is handled by resolve_code.  */
6036
6037 static void
6038 resolve_types (gfc_namespace * ns)
6039 {
6040   gfc_namespace *n;
6041   gfc_charlen *cl;
6042   gfc_data *d;
6043   gfc_equiv *eq;
6044
6045   gfc_current_ns = ns;
6046
6047   resolve_entries (ns);
6048
6049   resolve_contained_functions (ns);
6050
6051   gfc_traverse_ns (ns, resolve_symbol);
6052
6053   resolve_fntype (ns);
6054
6055   for (n = ns->contained; n; n = n->sibling)
6056     {
6057       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
6058         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
6059                    "also be PURE", n->proc_name->name,
6060                    &n->proc_name->declared_at);
6061
6062       resolve_types (n);
6063     }
6064
6065   forall_flag = 0;
6066   gfc_check_interfaces (ns);
6067
6068   for (cl = ns->cl_list; cl; cl = cl->next)
6069     resolve_charlen (cl);
6070
6071   gfc_traverse_ns (ns, resolve_values);
6072
6073   if (ns->save_all)
6074     gfc_save_all (ns);
6075
6076   iter_stack = NULL;
6077   for (d = ns->data; d; d = d->next)
6078     resolve_data (d);
6079
6080   iter_stack = NULL;
6081   gfc_traverse_ns (ns, gfc_formalize_init_value);
6082
6083   for (eq = ns->equiv; eq; eq = eq->next)
6084     resolve_equivalence (eq);
6085
6086   /* Warn about unused labels.  */
6087   if (gfc_option.warn_unused_labels)
6088     warn_unused_label (ns->st_labels);
6089 }
6090
6091
6092 /* Call resolve_code recursively.  */
6093
6094 static void
6095 resolve_codes (gfc_namespace * ns)
6096 {
6097   gfc_namespace *n;
6098
6099   for (n = ns->contained; n; n = n->sibling)
6100     resolve_codes (n);
6101
6102   gfc_current_ns = ns;
6103   cs_base = NULL;
6104   resolve_code (ns->code, ns);
6105 }
6106
6107
6108 /* This function is called after a complete program unit has been compiled.
6109    Its purpose is to examine all of the expressions associated with a program
6110    unit, assign types to all intermediate expressions, make sure that all
6111    assignments are to compatible types and figure out which names refer to
6112    which functions or subroutines.  */
6113
6114 void
6115 gfc_resolve (gfc_namespace * ns)
6116 {
6117   gfc_namespace *old_ns;
6118
6119   old_ns = gfc_current_ns;
6120
6121   resolve_types (ns);
6122   resolve_codes (ns);
6123
6124   gfc_current_ns = old_ns;
6125 }