OSDN Git Service

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