OSDN Git Service

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