OSDN Git Service

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