OSDN Git Service

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