06fa3018f4c36ecd760998097c021ef9856439cc
[platform/upstream/gcc.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various structures.
2    Copyright (C) 2001-2013 Free Software Foundation, Inc.
3    Contributed by Andy Vaught
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.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 #include "constructor.h"
33
34 /* Types used in equivalence statements.  */
35
36 typedef enum seq_type
37 {
38   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
39 }
40 seq_type;
41
42 /* Stack to keep track of the nesting of blocks as we move through the
43    code.  See resolve_branch() and resolve_code().  */
44
45 typedef struct code_stack
46 {
47   struct gfc_code *head, *current;
48   struct code_stack *prev;
49
50   /* This bitmap keeps track of the targets valid for a branch from
51      inside this block except for END {IF|SELECT}s of enclosing
52      blocks.  */
53   bitmap reachable_labels;
54 }
55 code_stack;
56
57 static code_stack *cs_base = NULL;
58
59
60 /* Nonzero if we're inside a FORALL or DO CONCURRENT block.  */
61
62 static int forall_flag;
63 static int do_concurrent_flag;
64
65 /* True when we are resolving an expression that is an actual argument to
66    a procedure.  */
67 static bool actual_arg = false;
68 /* True when we are resolving an expression that is the first actual argument
69    to a procedure.  */
70 static bool first_actual_arg = false;
71
72
73 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
74
75 static int omp_workshare_flag;
76
77 /* Nonzero if we are processing a formal arglist. The corresponding function
78    resets the flag each time that it is read.  */
79 static int formal_arg_flag = 0;
80
81 /* True if we are resolving a specification expression.  */
82 static bool specification_expr = false;
83
84 /* The id of the last entry seen.  */
85 static int current_entry_id;
86
87 /* We use bitmaps to determine if a branch target is valid.  */
88 static bitmap_obstack labels_obstack;
89
90 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
91 static bool inquiry_argument = false;
92
93
94 int
95 gfc_is_formal_arg (void)
96 {
97   return formal_arg_flag;
98 }
99
100 /* Is the symbol host associated?  */
101 static bool
102 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
103 {
104   for (ns = ns->parent; ns; ns = ns->parent)
105     {
106       if (sym->ns == ns)
107         return true;
108     }
109
110   return false;
111 }
112
113 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
114    an ABSTRACT derived-type.  If where is not NULL, an error message with that
115    locus is printed, optionally using name.  */
116
117 static bool
118 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
119 {
120   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
121     {
122       if (where)
123         {
124           if (name)
125             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
126                        name, where, ts->u.derived->name);
127           else
128             gfc_error ("ABSTRACT type '%s' used at %L",
129                        ts->u.derived->name, where);
130         }
131
132       return false;
133     }
134
135   return true;
136 }
137
138
139 static bool
140 check_proc_interface (gfc_symbol *ifc, locus *where)
141 {
142   /* Several checks for F08:C1216.  */
143   if (ifc->attr.procedure)
144     {
145       gfc_error ("Interface '%s' at %L is declared "
146                  "in a later PROCEDURE statement", ifc->name, where);
147       return false;
148     }
149   if (ifc->generic)
150     {
151       /* For generic interfaces, check if there is
152          a specific procedure with the same name.  */
153       gfc_interface *gen = ifc->generic;
154       while (gen && strcmp (gen->sym->name, ifc->name) != 0)
155         gen = gen->next;
156       if (!gen)
157         {
158           gfc_error ("Interface '%s' at %L may not be generic",
159                      ifc->name, where);
160           return false;
161         }
162     }
163   if (ifc->attr.proc == PROC_ST_FUNCTION)
164     {
165       gfc_error ("Interface '%s' at %L may not be a statement function",
166                  ifc->name, where);
167       return false;
168     }
169   if (gfc_is_intrinsic (ifc, 0, ifc->declared_at)
170       || gfc_is_intrinsic (ifc, 1, ifc->declared_at))
171     ifc->attr.intrinsic = 1;
172   if (ifc->attr.intrinsic && !gfc_intrinsic_actual_ok (ifc->name, 0))
173     {
174       gfc_error ("Intrinsic procedure '%s' not allowed in "
175                  "PROCEDURE statement at %L", ifc->name, where);
176       return false;
177     }
178   if (!ifc->attr.if_source && !ifc->attr.intrinsic && ifc->name[0] != '\0')
179     {
180       gfc_error ("Interface '%s' at %L must be explicit", ifc->name, where);
181       return false;
182     }
183   return true;
184 }
185
186
187 static void resolve_symbol (gfc_symbol *sym);
188
189
190 /* Resolve the interface for a PROCEDURE declaration or procedure pointer.  */
191
192 static bool
193 resolve_procedure_interface (gfc_symbol *sym)
194 {
195   gfc_symbol *ifc = sym->ts.interface;
196
197   if (!ifc)
198     return true;
199
200   if (ifc == sym)
201     {
202       gfc_error ("PROCEDURE '%s' at %L may not be used as its own interface",
203                  sym->name, &sym->declared_at);
204       return false;
205     }
206   if (!check_proc_interface (ifc, &sym->declared_at))
207     return false;
208
209   if (ifc->attr.if_source || ifc->attr.intrinsic)
210     {
211       /* Resolve interface and copy attributes.  */
212       resolve_symbol (ifc);
213       if (ifc->attr.intrinsic)
214         gfc_resolve_intrinsic (ifc, &ifc->declared_at);
215
216       if (ifc->result)
217         {
218           sym->ts = ifc->result->ts;
219           sym->result = sym;
220         }
221       else
222         sym->ts = ifc->ts;
223       sym->ts.interface = ifc;
224       sym->attr.function = ifc->attr.function;
225       sym->attr.subroutine = ifc->attr.subroutine;
226
227       sym->attr.allocatable = ifc->attr.allocatable;
228       sym->attr.pointer = ifc->attr.pointer;
229       sym->attr.pure = ifc->attr.pure;
230       sym->attr.elemental = ifc->attr.elemental;
231       sym->attr.dimension = ifc->attr.dimension;
232       sym->attr.contiguous = ifc->attr.contiguous;
233       sym->attr.recursive = ifc->attr.recursive;
234       sym->attr.always_explicit = ifc->attr.always_explicit;
235       sym->attr.ext_attr |= ifc->attr.ext_attr;
236       sym->attr.is_bind_c = ifc->attr.is_bind_c;
237       sym->attr.class_ok = ifc->attr.class_ok;
238       /* Copy array spec.  */
239       sym->as = gfc_copy_array_spec (ifc->as);
240       /* Copy char length.  */
241       if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
242         {
243           sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
244           if (sym->ts.u.cl->length && !sym->ts.u.cl->resolved
245               && !gfc_resolve_expr (sym->ts.u.cl->length))
246             return false;
247         }
248     }
249
250   return true;
251 }
252
253
254 /* Resolve types of formal argument lists.  These have to be done early so that
255    the formal argument lists of module procedures can be copied to the
256    containing module before the individual procedures are resolved
257    individually.  We also resolve argument lists of procedures in interface
258    blocks because they are self-contained scoping units.
259
260    Since a dummy argument cannot be a non-dummy procedure, the only
261    resort left for untyped names are the IMPLICIT types.  */
262
263 static void
264 resolve_formal_arglist (gfc_symbol *proc)
265 {
266   gfc_formal_arglist *f;
267   gfc_symbol *sym;
268   bool saved_specification_expr;
269   int i;
270
271   if (proc->result != NULL)
272     sym = proc->result;
273   else
274     sym = proc;
275
276   if (gfc_elemental (proc)
277       || sym->attr.pointer || sym->attr.allocatable
278       || (sym->as && sym->as->rank != 0))
279     {
280       proc->attr.always_explicit = 1;
281       sym->attr.always_explicit = 1;
282     }
283
284   formal_arg_flag = 1;
285
286   for (f = proc->formal; f; f = f->next)
287     {
288       gfc_array_spec *as;
289
290       sym = f->sym;
291
292       if (sym == NULL)
293         {
294           /* Alternate return placeholder.  */
295           if (gfc_elemental (proc))
296             gfc_error ("Alternate return specifier in elemental subroutine "
297                        "'%s' at %L is not allowed", proc->name,
298                        &proc->declared_at);
299           if (proc->attr.function)
300             gfc_error ("Alternate return specifier in function "
301                        "'%s' at %L is not allowed", proc->name,
302                        &proc->declared_at);
303           continue;
304         }
305       else if (sym->attr.procedure && sym->attr.if_source != IFSRC_DECL
306                && !resolve_procedure_interface (sym))
307         return;
308
309       if (sym->attr.if_source != IFSRC_UNKNOWN)
310         resolve_formal_arglist (sym);
311
312       if (sym->attr.subroutine || sym->attr.external)
313         {
314           if (sym->attr.flavor == FL_UNKNOWN)
315             gfc_add_flavor (&sym->attr, FL_PROCEDURE, sym->name, &sym->declared_at);
316         }
317       else
318         {
319           if (sym->ts.type == BT_UNKNOWN && !proc->attr.intrinsic
320               && (!sym->attr.function || sym->result == sym))
321             gfc_set_default_type (sym, 1, sym->ns);
322         }
323
324       as = sym->ts.type == BT_CLASS && sym->attr.class_ok
325            ? CLASS_DATA (sym)->as : sym->as;
326
327       saved_specification_expr = specification_expr;
328       specification_expr = true;
329       gfc_resolve_array_spec (as, 0);
330       specification_expr = saved_specification_expr;
331
332       /* We can't tell if an array with dimension (:) is assumed or deferred
333          shape until we know if it has the pointer or allocatable attributes.
334       */
335       if (as && as->rank > 0 && as->type == AS_DEFERRED
336           && ((sym->ts.type != BT_CLASS
337                && !(sym->attr.pointer || sym->attr.allocatable))
338               || (sym->ts.type == BT_CLASS
339                   && !(CLASS_DATA (sym)->attr.class_pointer
340                        || CLASS_DATA (sym)->attr.allocatable)))
341           && sym->attr.flavor != FL_PROCEDURE)
342         {
343           as->type = AS_ASSUMED_SHAPE;
344           for (i = 0; i < as->rank; i++)
345             as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
346         }
347
348       if ((as && as->rank > 0 && as->type == AS_ASSUMED_SHAPE)
349           || (as && as->type == AS_ASSUMED_RANK)
350           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
351           || (sym->ts.type == BT_CLASS && sym->attr.class_ok
352               && (CLASS_DATA (sym)->attr.class_pointer
353                   || CLASS_DATA (sym)->attr.allocatable
354                   || CLASS_DATA (sym)->attr.target))
355           || sym->attr.optional)
356         {
357           proc->attr.always_explicit = 1;
358           if (proc->result)
359             proc->result->attr.always_explicit = 1;
360         }
361
362       /* If the flavor is unknown at this point, it has to be a variable.
363          A procedure specification would have already set the type.  */
364
365       if (sym->attr.flavor == FL_UNKNOWN)
366         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
367
368       if (gfc_pure (proc))
369         {
370           if (sym->attr.flavor == FL_PROCEDURE)
371             {
372               /* F08:C1279.  */
373               if (!gfc_pure (sym))
374                 {
375                   gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
376                             "also be PURE", sym->name, &sym->declared_at);
377                   continue;
378                 }
379             }
380           else if (!sym->attr.pointer)
381             {
382               if (proc->attr.function && sym->attr.intent != INTENT_IN)
383                 {
384                   if (sym->attr.value)
385                     gfc_notify_std (GFC_STD_F2008, "Argument '%s'"
386                                     " of pure function '%s' at %L with VALUE "
387                                     "attribute but without INTENT(IN)",
388                                     sym->name, proc->name, &sym->declared_at);
389                   else
390                     gfc_error ("Argument '%s' of pure function '%s' at %L must "
391                                "be INTENT(IN) or VALUE", sym->name, proc->name,
392                                &sym->declared_at);
393                 }
394
395               if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
396                 {
397                   if (sym->attr.value)
398                     gfc_notify_std (GFC_STD_F2008, "Argument '%s'"
399                                     " of pure subroutine '%s' at %L with VALUE "
400                                     "attribute but without INTENT", sym->name,
401                                     proc->name, &sym->declared_at);
402                   else
403                     gfc_error ("Argument '%s' of pure subroutine '%s' at %L "
404                                "must have its INTENT specified or have the "
405                                "VALUE attribute", sym->name, proc->name,
406                                &sym->declared_at);
407                 }
408             }
409         }
410
411       if (proc->attr.implicit_pure)
412         {
413           if (sym->attr.flavor == FL_PROCEDURE)
414             {
415               if (!gfc_pure (sym))
416                 proc->attr.implicit_pure = 0;
417             }
418           else if (!sym->attr.pointer)
419             {
420               if (proc->attr.function && sym->attr.intent != INTENT_IN
421                   && !sym->value)
422                 proc->attr.implicit_pure = 0;
423
424               if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN
425                   && !sym->value)
426                 proc->attr.implicit_pure = 0;
427             }
428         }
429
430       if (gfc_elemental (proc))
431         {
432           /* F08:C1289.  */
433           if (sym->attr.codimension
434               || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
435                   && CLASS_DATA (sym)->attr.codimension))
436             {
437               gfc_error ("Coarray dummy argument '%s' at %L to elemental "
438                          "procedure", sym->name, &sym->declared_at);
439               continue;
440             }
441
442           if (sym->as || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
443                           && CLASS_DATA (sym)->as))
444             {
445               gfc_error ("Argument '%s' of elemental procedure at %L must "
446                          "be scalar", sym->name, &sym->declared_at);
447               continue;
448             }
449
450           if (sym->attr.allocatable
451               || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
452                   && CLASS_DATA (sym)->attr.allocatable))
453             {
454               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
455                          "have the ALLOCATABLE attribute", sym->name,
456                          &sym->declared_at);
457               continue;
458             }
459
460           if (sym->attr.pointer
461               || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
462                   && CLASS_DATA (sym)->attr.class_pointer))
463             {
464               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
465                          "have the POINTER attribute", sym->name,
466                          &sym->declared_at);
467               continue;
468             }
469
470           if (sym->attr.flavor == FL_PROCEDURE)
471             {
472               gfc_error ("Dummy procedure '%s' not allowed in elemental "
473                          "procedure '%s' at %L", sym->name, proc->name,
474                          &sym->declared_at);
475               continue;
476             }
477
478           /* Fortran 2008 Corrigendum 1, C1290a.  */
479           if (sym->attr.intent == INTENT_UNKNOWN && !sym->attr.value)
480             {
481               gfc_error ("Argument '%s' of elemental procedure '%s' at %L must "
482                          "have its INTENT specified or have the VALUE "
483                          "attribute", sym->name, proc->name,
484                          &sym->declared_at);
485               continue;
486             }
487         }
488
489       /* Each dummy shall be specified to be scalar.  */
490       if (proc->attr.proc == PROC_ST_FUNCTION)
491         {
492           if (sym->as != NULL)
493             {
494               gfc_error ("Argument '%s' of statement function at %L must "
495                          "be scalar", sym->name, &sym->declared_at);
496               continue;
497             }
498
499           if (sym->ts.type == BT_CHARACTER)
500             {
501               gfc_charlen *cl = sym->ts.u.cl;
502               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
503                 {
504                   gfc_error ("Character-valued argument '%s' of statement "
505                              "function at %L must have constant length",
506                              sym->name, &sym->declared_at);
507                   continue;
508                 }
509             }
510         }
511     }
512   formal_arg_flag = 0;
513 }
514
515
516 /* Work function called when searching for symbols that have argument lists
517    associated with them.  */
518
519 static void
520 find_arglists (gfc_symbol *sym)
521 {
522   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns
523       || sym->attr.flavor == FL_DERIVED || sym->attr.intrinsic)
524     return;
525
526   resolve_formal_arglist (sym);
527 }
528
529
530 /* Given a namespace, resolve all formal argument lists within the namespace.
531  */
532
533 static void
534 resolve_formal_arglists (gfc_namespace *ns)
535 {
536   if (ns == NULL)
537     return;
538
539   gfc_traverse_ns (ns, find_arglists);
540 }
541
542
543 static void
544 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
545 {
546   bool t;
547
548   /* If this namespace is not a function or an entry master function,
549      ignore it.  */
550   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
551       || sym->attr.entry_master)
552     return;
553
554   /* Try to find out of what the return type is.  */
555   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
556     {
557       t = gfc_set_default_type (sym->result, 0, ns);
558
559       if (!t && !sym->result->attr.untyped)
560         {
561           if (sym->result == sym)
562             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
563                        sym->name, &sym->declared_at);
564           else if (!sym->result->attr.proc_pointer)
565             gfc_error ("Result '%s' of contained function '%s' at %L has "
566                        "no IMPLICIT type", sym->result->name, sym->name,
567                        &sym->result->declared_at);
568           sym->result->attr.untyped = 1;
569         }
570     }
571
572   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character
573      type, lists the only ways a character length value of * can be used:
574      dummy arguments of procedures, named constants, and function results
575      in external functions.  Internal function results and results of module
576      procedures are not on this list, ergo, not permitted.  */
577
578   if (sym->result->ts.type == BT_CHARACTER)
579     {
580       gfc_charlen *cl = sym->result->ts.u.cl;
581       if ((!cl || !cl->length) && !sym->result->ts.deferred)
582         {
583           /* See if this is a module-procedure and adapt error message
584              accordingly.  */
585           bool module_proc;
586           gcc_assert (ns->parent && ns->parent->proc_name);
587           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
588
589           gfc_error ("Character-valued %s '%s' at %L must not be"
590                      " assumed length",
591                      module_proc ? _("module procedure")
592                                  : _("internal function"),
593                      sym->name, &sym->declared_at);
594         }
595     }
596 }
597
598
599 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
600    introduce duplicates.  */
601
602 static void
603 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
604 {
605   gfc_formal_arglist *f, *new_arglist;
606   gfc_symbol *new_sym;
607
608   for (; new_args != NULL; new_args = new_args->next)
609     {
610       new_sym = new_args->sym;
611       /* See if this arg is already in the formal argument list.  */
612       for (f = proc->formal; f; f = f->next)
613         {
614           if (new_sym == f->sym)
615             break;
616         }
617
618       if (f)
619         continue;
620
621       /* Add a new argument.  Argument order is not important.  */
622       new_arglist = gfc_get_formal_arglist ();
623       new_arglist->sym = new_sym;
624       new_arglist->next = proc->formal;
625       proc->formal  = new_arglist;
626     }
627 }
628
629
630 /* Flag the arguments that are not present in all entries.  */
631
632 static void
633 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
634 {
635   gfc_formal_arglist *f, *head;
636   head = new_args;
637
638   for (f = proc->formal; f; f = f->next)
639     {
640       if (f->sym == NULL)
641         continue;
642
643       for (new_args = head; new_args; new_args = new_args->next)
644         {
645           if (new_args->sym == f->sym)
646             break;
647         }
648
649       if (new_args)
650         continue;
651
652       f->sym->attr.not_always_present = 1;
653     }
654 }
655
656
657 /* Resolve alternate entry points.  If a symbol has multiple entry points we
658    create a new master symbol for the main routine, and turn the existing
659    symbol into an entry point.  */
660
661 static void
662 resolve_entries (gfc_namespace *ns)
663 {
664   gfc_namespace *old_ns;
665   gfc_code *c;
666   gfc_symbol *proc;
667   gfc_entry_list *el;
668   char name[GFC_MAX_SYMBOL_LEN + 1];
669   static int master_count = 0;
670
671   if (ns->proc_name == NULL)
672     return;
673
674   /* No need to do anything if this procedure doesn't have alternate entry
675      points.  */
676   if (!ns->entries)
677     return;
678
679   /* We may already have resolved alternate entry points.  */
680   if (ns->proc_name->attr.entry_master)
681     return;
682
683   /* If this isn't a procedure something has gone horribly wrong.  */
684   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
685
686   /* Remember the current namespace.  */
687   old_ns = gfc_current_ns;
688
689   gfc_current_ns = ns;
690
691   /* Add the main entry point to the list of entry points.  */
692   el = gfc_get_entry_list ();
693   el->sym = ns->proc_name;
694   el->id = 0;
695   el->next = ns->entries;
696   ns->entries = el;
697   ns->proc_name->attr.entry = 1;
698
699   /* If it is a module function, it needs to be in the right namespace
700      so that gfc_get_fake_result_decl can gather up the results. The
701      need for this arose in get_proc_name, where these beasts were
702      left in their own namespace, to keep prior references linked to
703      the entry declaration.*/
704   if (ns->proc_name->attr.function
705       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
706     el->sym->ns = ns;
707
708   /* Do the same for entries where the master is not a module
709      procedure.  These are retained in the module namespace because
710      of the module procedure declaration.  */
711   for (el = el->next; el; el = el->next)
712     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
713           && el->sym->attr.mod_proc)
714       el->sym->ns = ns;
715   el = ns->entries;
716
717   /* Add an entry statement for it.  */
718   c = gfc_get_code ();
719   c->op = EXEC_ENTRY;
720   c->ext.entry = el;
721   c->next = ns->code;
722   ns->code = c;
723
724   /* Create a new symbol for the master function.  */
725   /* Give the internal function a unique name (within this file).
726      Also include the function name so the user has some hope of figuring
727      out what is going on.  */
728   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
729             master_count++, ns->proc_name->name);
730   gfc_get_ha_symbol (name, &proc);
731   gcc_assert (proc != NULL);
732
733   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
734   if (ns->proc_name->attr.subroutine)
735     gfc_add_subroutine (&proc->attr, proc->name, NULL);
736   else
737     {
738       gfc_symbol *sym;
739       gfc_typespec *ts, *fts;
740       gfc_array_spec *as, *fas;
741       gfc_add_function (&proc->attr, proc->name, NULL);
742       proc->result = proc;
743       fas = ns->entries->sym->as;
744       fas = fas ? fas : ns->entries->sym->result->as;
745       fts = &ns->entries->sym->result->ts;
746       if (fts->type == BT_UNKNOWN)
747         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
748       for (el = ns->entries->next; el; el = el->next)
749         {
750           ts = &el->sym->result->ts;
751           as = el->sym->as;
752           as = as ? as : el->sym->result->as;
753           if (ts->type == BT_UNKNOWN)
754             ts = gfc_get_default_type (el->sym->result->name, NULL);
755
756           if (! gfc_compare_types (ts, fts)
757               || (el->sym->result->attr.dimension
758                   != ns->entries->sym->result->attr.dimension)
759               || (el->sym->result->attr.pointer
760                   != ns->entries->sym->result->attr.pointer))
761             break;
762           else if (as && fas && ns->entries->sym->result != el->sym->result
763                       && gfc_compare_array_spec (as, fas) == 0)
764             gfc_error ("Function %s at %L has entries with mismatched "
765                        "array specifications", ns->entries->sym->name,
766                        &ns->entries->sym->declared_at);
767           /* The characteristics need to match and thus both need to have
768              the same string length, i.e. both len=*, or both len=4.
769              Having both len=<variable> is also possible, but difficult to
770              check at compile time.  */
771           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
772                    && (((ts->u.cl->length && !fts->u.cl->length)
773                         ||(!ts->u.cl->length && fts->u.cl->length))
774                        || (ts->u.cl->length
775                            && ts->u.cl->length->expr_type
776                               != fts->u.cl->length->expr_type)
777                        || (ts->u.cl->length
778                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
779                            && mpz_cmp (ts->u.cl->length->value.integer,
780                                        fts->u.cl->length->value.integer) != 0)))
781             gfc_notify_std (GFC_STD_GNU, "Function %s at %L with "
782                             "entries returning variables of different "
783                             "string lengths", ns->entries->sym->name,
784                             &ns->entries->sym->declared_at);
785         }
786
787       if (el == NULL)
788         {
789           sym = ns->entries->sym->result;
790           /* All result types the same.  */
791           proc->ts = *fts;
792           if (sym->attr.dimension)
793             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
794           if (sym->attr.pointer)
795             gfc_add_pointer (&proc->attr, NULL);
796         }
797       else
798         {
799           /* Otherwise the result will be passed through a union by
800              reference.  */
801           proc->attr.mixed_entry_master = 1;
802           for (el = ns->entries; el; el = el->next)
803             {
804               sym = el->sym->result;
805               if (sym->attr.dimension)
806                 {
807                   if (el == ns->entries)
808                     gfc_error ("FUNCTION result %s can't be an array in "
809                                "FUNCTION %s at %L", sym->name,
810                                ns->entries->sym->name, &sym->declared_at);
811                   else
812                     gfc_error ("ENTRY result %s can't be an array in "
813                                "FUNCTION %s at %L", sym->name,
814                                ns->entries->sym->name, &sym->declared_at);
815                 }
816               else if (sym->attr.pointer)
817                 {
818                   if (el == ns->entries)
819                     gfc_error ("FUNCTION result %s can't be a POINTER in "
820                                "FUNCTION %s at %L", sym->name,
821                                ns->entries->sym->name, &sym->declared_at);
822                   else
823                     gfc_error ("ENTRY result %s can't be a POINTER in "
824                                "FUNCTION %s at %L", sym->name,
825                                ns->entries->sym->name, &sym->declared_at);
826                 }
827               else
828                 {
829                   ts = &sym->ts;
830                   if (ts->type == BT_UNKNOWN)
831                     ts = gfc_get_default_type (sym->name, NULL);
832                   switch (ts->type)
833                     {
834                     case BT_INTEGER:
835                       if (ts->kind == gfc_default_integer_kind)
836                         sym = NULL;
837                       break;
838                     case BT_REAL:
839                       if (ts->kind == gfc_default_real_kind
840                           || ts->kind == gfc_default_double_kind)
841                         sym = NULL;
842                       break;
843                     case BT_COMPLEX:
844                       if (ts->kind == gfc_default_complex_kind)
845                         sym = NULL;
846                       break;
847                     case BT_LOGICAL:
848                       if (ts->kind == gfc_default_logical_kind)
849                         sym = NULL;
850                       break;
851                     case BT_UNKNOWN:
852                       /* We will issue error elsewhere.  */
853                       sym = NULL;
854                       break;
855                     default:
856                       break;
857                     }
858                   if (sym)
859                     {
860                       if (el == ns->entries)
861                         gfc_error ("FUNCTION result %s can't be of type %s "
862                                    "in FUNCTION %s at %L", sym->name,
863                                    gfc_typename (ts), ns->entries->sym->name,
864                                    &sym->declared_at);
865                       else
866                         gfc_error ("ENTRY result %s can't be of type %s "
867                                    "in FUNCTION %s at %L", sym->name,
868                                    gfc_typename (ts), ns->entries->sym->name,
869                                    &sym->declared_at);
870                     }
871                 }
872             }
873         }
874     }
875   proc->attr.access = ACCESS_PRIVATE;
876   proc->attr.entry_master = 1;
877
878   /* Merge all the entry point arguments.  */
879   for (el = ns->entries; el; el = el->next)
880     merge_argument_lists (proc, el->sym->formal);
881
882   /* Check the master formal arguments for any that are not
883      present in all entry points.  */
884   for (el = ns->entries; el; el = el->next)
885     check_argument_lists (proc, el->sym->formal);
886
887   /* Use the master function for the function body.  */
888   ns->proc_name = proc;
889
890   /* Finalize the new symbols.  */
891   gfc_commit_symbols ();
892
893   /* Restore the original namespace.  */
894   gfc_current_ns = old_ns;
895 }
896
897
898 /* Resolve common variables.  */
899 static void
900 resolve_common_vars (gfc_symbol *sym, bool named_common)
901 {
902   gfc_symbol *csym = sym;
903
904   for (; csym; csym = csym->common_next)
905     {
906       if (csym->value || csym->attr.data)
907         {
908           if (!csym->ns->is_block_data)
909             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
910                             "but only in BLOCK DATA initialization is "
911                             "allowed", csym->name, &csym->declared_at);
912           else if (!named_common)
913             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
914                             "in a blank COMMON but initialization is only "
915                             "allowed in named common blocks", csym->name,
916                             &csym->declared_at);
917         }
918
919       if (UNLIMITED_POLY (csym))
920         gfc_error_now ("'%s' in cannot appear in COMMON at %L "
921                        "[F2008:C5100]", csym->name, &csym->declared_at);
922
923       if (csym->ts.type != BT_DERIVED)
924         continue;
925
926       if (!(csym->ts.u.derived->attr.sequence
927             || csym->ts.u.derived->attr.is_bind_c))
928         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
929                        "has neither the SEQUENCE nor the BIND(C) "
930                        "attribute", csym->name, &csym->declared_at);
931       if (csym->ts.u.derived->attr.alloc_comp)
932         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
933                        "has an ultimate component that is "
934                        "allocatable", csym->name, &csym->declared_at);
935       if (gfc_has_default_initializer (csym->ts.u.derived))
936         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
937                        "may not have default initializer", csym->name,
938                        &csym->declared_at);
939
940       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
941         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
942     }
943 }
944
945 /* Resolve common blocks.  */
946 static void
947 resolve_common_blocks (gfc_symtree *common_root)
948 {
949   gfc_symbol *sym;
950   gfc_gsymbol * gsym;
951
952   if (common_root == NULL)
953     return;
954
955   if (common_root->left)
956     resolve_common_blocks (common_root->left);
957   if (common_root->right)
958     resolve_common_blocks (common_root->right);
959
960   resolve_common_vars (common_root->n.common->head, true);
961
962   /* The common name is a global name - in Fortran 2003 also if it has a
963      C binding name, since Fortran 2008 only the C binding name is a global
964      identifier.  */
965   if (!common_root->n.common->binding_label
966       || gfc_notification_std (GFC_STD_F2008))
967     {
968       gsym = gfc_find_gsymbol (gfc_gsym_root,
969                                common_root->n.common->name);
970
971       if (gsym && gfc_notification_std (GFC_STD_F2008)
972           && gsym->type == GSYM_COMMON
973           && ((common_root->n.common->binding_label
974                && (!gsym->binding_label
975                    || strcmp (common_root->n.common->binding_label,
976                               gsym->binding_label) != 0))
977               || (!common_root->n.common->binding_label
978                   && gsym->binding_label)))
979         {
980           gfc_error ("In Fortran 2003 COMMON '%s' block at %L is a global "
981                      "identifier and must thus have the same binding name "
982                      "as the same-named COMMON block at %L: %s vs %s",
983                      common_root->n.common->name, &common_root->n.common->where,
984                      &gsym->where,
985                      common_root->n.common->binding_label
986                      ? common_root->n.common->binding_label : "(blank)",
987                      gsym->binding_label ? gsym->binding_label : "(blank)");
988           return;
989         }
990
991       if (gsym && gsym->type != GSYM_COMMON
992           && !common_root->n.common->binding_label)
993         {
994           gfc_error ("COMMON block '%s' at %L uses the same global identifier "
995                      "as entity at %L",
996                      common_root->n.common->name, &common_root->n.common->where,
997                      &gsym->where);
998           return;
999         }
1000       if (gsym && gsym->type != GSYM_COMMON)
1001         {
1002           gfc_error ("Fortran 2008: COMMON block '%s' with binding label at "
1003                      "%L sharing the identifier with global non-COMMON-block "
1004                      "entity at %L", common_root->n.common->name,
1005                      &common_root->n.common->where, &gsym->where);
1006           return;
1007         }
1008       if (!gsym)
1009         {
1010           gsym = gfc_get_gsymbol (common_root->n.common->name);
1011           gsym->type = GSYM_COMMON;
1012           gsym->where = common_root->n.common->where;
1013           gsym->defined = 1;
1014         }
1015       gsym->used = 1;
1016     }
1017
1018   if (common_root->n.common->binding_label)
1019     {
1020       gsym = gfc_find_gsymbol (gfc_gsym_root,
1021                                common_root->n.common->binding_label);
1022       if (gsym && gsym->type != GSYM_COMMON)
1023         {
1024           gfc_error ("COMMON block at %L with binding label %s uses the same "
1025                      "global identifier as entity at %L",
1026                      &common_root->n.common->where,
1027                      common_root->n.common->binding_label, &gsym->where);
1028           return;
1029         }
1030       if (!gsym)
1031         {
1032           gsym = gfc_get_gsymbol (common_root->n.common->binding_label);
1033           gsym->type = GSYM_COMMON;
1034           gsym->where = common_root->n.common->where;
1035           gsym->defined = 1;
1036         }
1037       gsym->used = 1;
1038     }
1039
1040   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
1041   if (sym == NULL)
1042     return;
1043
1044   if (sym->attr.flavor == FL_PARAMETER)
1045     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
1046                sym->name, &common_root->n.common->where, &sym->declared_at);
1047
1048   if (sym->attr.external)
1049     gfc_error ("COMMON block '%s' at %L can not have the EXTERNAL attribute",
1050                sym->name, &common_root->n.common->where);
1051
1052   if (sym->attr.intrinsic)
1053     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
1054                sym->name, &common_root->n.common->where);
1055   else if (sym->attr.result
1056            || gfc_is_function_return_value (sym, gfc_current_ns))
1057     gfc_notify_std (GFC_STD_F2003, "COMMON block '%s' at %L "
1058                     "that is also a function result", sym->name,
1059                     &common_root->n.common->where);
1060   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
1061            && sym->attr.proc != PROC_ST_FUNCTION)
1062     gfc_notify_std (GFC_STD_F2003, "COMMON block '%s' at %L "
1063                     "that is also a global procedure", sym->name,
1064                     &common_root->n.common->where);
1065 }
1066
1067
1068 /* Resolve contained function types.  Because contained functions can call one
1069    another, they have to be worked out before any of the contained procedures
1070    can be resolved.
1071
1072    The good news is that if a function doesn't already have a type, the only
1073    way it can get one is through an IMPLICIT type or a RESULT variable, because
1074    by definition contained functions are contained namespace they're contained
1075    in, not in a sibling or parent namespace.  */
1076
1077 static void
1078 resolve_contained_functions (gfc_namespace *ns)
1079 {
1080   gfc_namespace *child;
1081   gfc_entry_list *el;
1082
1083   resolve_formal_arglists (ns);
1084
1085   for (child = ns->contained; child; child = child->sibling)
1086     {
1087       /* Resolve alternate entry points first.  */
1088       resolve_entries (child);
1089
1090       /* Then check function return types.  */
1091       resolve_contained_fntype (child->proc_name, child);
1092       for (el = child->entries; el; el = el->next)
1093         resolve_contained_fntype (el->sym, child);
1094     }
1095 }
1096
1097
1098 static bool resolve_fl_derived0 (gfc_symbol *sym);
1099
1100
1101 /* Resolve all of the elements of a structure constructor and make sure that
1102    the types are correct. The 'init' flag indicates that the given
1103    constructor is an initializer.  */
1104
1105 static bool
1106 resolve_structure_cons (gfc_expr *expr, int init)
1107 {
1108   gfc_constructor *cons;
1109   gfc_component *comp;
1110   bool t;
1111   symbol_attribute a;
1112
1113   t = true;
1114
1115   if (expr->ts.type == BT_DERIVED)
1116     resolve_fl_derived0 (expr->ts.u.derived);
1117
1118   cons = gfc_constructor_first (expr->value.constructor);
1119
1120   /* A constructor may have references if it is the result of substituting a
1121      parameter variable.  In this case we just pull out the component we
1122      want.  */
1123   if (expr->ref)
1124     comp = expr->ref->u.c.sym->components;
1125   else
1126     comp = expr->ts.u.derived->components;
1127
1128   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
1129     {
1130       int rank;
1131
1132       if (!cons->expr)
1133         continue;
1134
1135       if (!gfc_resolve_expr (cons->expr))
1136         {
1137           t = false;
1138           continue;
1139         }
1140
1141       rank = comp->as ? comp->as->rank : 0;
1142       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
1143           && (comp->attr.allocatable || cons->expr->rank))
1144         {
1145           gfc_error ("The rank of the element in the structure "
1146                      "constructor at %L does not match that of the "
1147                      "component (%d/%d)", &cons->expr->where,
1148                      cons->expr->rank, rank);
1149           t = false;
1150         }
1151
1152       /* If we don't have the right type, try to convert it.  */
1153
1154       if (!comp->attr.proc_pointer &&
1155           !gfc_compare_types (&cons->expr->ts, &comp->ts))
1156         {
1157           if (strcmp (comp->name, "_extends") == 0)
1158             {
1159               /* Can afford to be brutal with the _extends initializer.
1160                  The derived type can get lost because it is PRIVATE
1161                  but it is not usage constrained by the standard.  */
1162               cons->expr->ts = comp->ts;
1163             }
1164           else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
1165             {
1166               gfc_error ("The element in the structure constructor at %L, "
1167                          "for pointer component '%s', is %s but should be %s",
1168                          &cons->expr->where, comp->name,
1169                          gfc_basic_typename (cons->expr->ts.type),
1170                          gfc_basic_typename (comp->ts.type));
1171               t = false;
1172             }
1173           else
1174             {
1175               bool t2 = gfc_convert_type (cons->expr, &comp->ts, 1);
1176               if (t)
1177                 t = t2;
1178             }
1179         }
1180
1181       /* For strings, the length of the constructor should be the same as
1182          the one of the structure, ensure this if the lengths are known at
1183          compile time and when we are dealing with PARAMETER or structure
1184          constructors.  */
1185       if (cons->expr->ts.type == BT_CHARACTER && comp->ts.u.cl
1186           && comp->ts.u.cl->length
1187           && comp->ts.u.cl->length->expr_type == EXPR_CONSTANT
1188           && cons->expr->ts.u.cl && cons->expr->ts.u.cl->length
1189           && cons->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
1190           && cons->expr->rank != 0
1191           && mpz_cmp (cons->expr->ts.u.cl->length->value.integer,
1192                       comp->ts.u.cl->length->value.integer) != 0)
1193         {
1194           if (cons->expr->expr_type == EXPR_VARIABLE
1195               && cons->expr->symtree->n.sym->attr.flavor == FL_PARAMETER)
1196             {
1197               /* Wrap the parameter in an array constructor (EXPR_ARRAY)
1198                  to make use of the gfc_resolve_character_array_constructor
1199                  machinery.  The expression is later simplified away to
1200                  an array of string literals.  */
1201               gfc_expr *para = cons->expr;
1202               cons->expr = gfc_get_expr ();
1203               cons->expr->ts = para->ts;
1204               cons->expr->where = para->where;
1205               cons->expr->expr_type = EXPR_ARRAY;
1206               cons->expr->rank = para->rank;
1207               cons->expr->shape = gfc_copy_shape (para->shape, para->rank);
1208               gfc_constructor_append_expr (&cons->expr->value.constructor,
1209                                            para, &cons->expr->where);
1210             }
1211           if (cons->expr->expr_type == EXPR_ARRAY)
1212             {
1213               gfc_constructor *p;
1214               p = gfc_constructor_first (cons->expr->value.constructor);
1215               if (cons->expr->ts.u.cl != p->expr->ts.u.cl)
1216                 {
1217                   gfc_charlen *cl, *cl2;
1218
1219                   cl2 = NULL;
1220                   for (cl = gfc_current_ns->cl_list; cl; cl = cl->next)
1221                     {
1222                       if (cl == cons->expr->ts.u.cl)
1223                         break;
1224                       cl2 = cl;
1225                     }
1226
1227                   gcc_assert (cl);
1228
1229                   if (cl2)
1230                     cl2->next = cl->next;
1231
1232                   gfc_free_expr (cl->length);
1233                   free (cl);
1234                 }
1235
1236               cons->expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1237               cons->expr->ts.u.cl->length_from_typespec = true;
1238               cons->expr->ts.u.cl->length = gfc_copy_expr (comp->ts.u.cl->length);
1239               gfc_resolve_character_array_constructor (cons->expr);
1240             }
1241         }
1242
1243       if (cons->expr->expr_type == EXPR_NULL
1244           && !(comp->attr.pointer || comp->attr.allocatable
1245                || comp->attr.proc_pointer || comp->ts.f90_type == BT_VOID
1246                || (comp->ts.type == BT_CLASS
1247                    && (CLASS_DATA (comp)->attr.class_pointer
1248                        || CLASS_DATA (comp)->attr.allocatable))))
1249         {
1250           t = false;
1251           gfc_error ("The NULL in the structure constructor at %L is "
1252                      "being applied to component '%s', which is neither "
1253                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
1254                      comp->name);
1255         }
1256
1257       if (comp->attr.proc_pointer && comp->ts.interface)
1258         {
1259           /* Check procedure pointer interface.  */
1260           gfc_symbol *s2 = NULL;
1261           gfc_component *c2;
1262           const char *name;
1263           char err[200];
1264
1265           c2 = gfc_get_proc_ptr_comp (cons->expr);
1266           if (c2)
1267             {
1268               s2 = c2->ts.interface;
1269               name = c2->name;
1270             }
1271           else if (cons->expr->expr_type == EXPR_FUNCTION)
1272             {
1273               s2 = cons->expr->symtree->n.sym->result;
1274               name = cons->expr->symtree->n.sym->result->name;
1275             }
1276           else if (cons->expr->expr_type != EXPR_NULL)
1277             {
1278               s2 = cons->expr->symtree->n.sym;
1279               name = cons->expr->symtree->n.sym->name;
1280             }
1281
1282           if (s2 && !gfc_compare_interfaces (comp->ts.interface, s2, name, 0, 1,
1283                                              err, sizeof (err), NULL, NULL))
1284             {
1285               gfc_error ("Interface mismatch for procedure-pointer component "
1286                          "'%s' in structure constructor at %L: %s",
1287                          comp->name, &cons->expr->where, err);
1288               return false;
1289             }
1290         }
1291
1292       if (!comp->attr.pointer || comp->attr.proc_pointer
1293           || cons->expr->expr_type == EXPR_NULL)
1294         continue;
1295
1296       a = gfc_expr_attr (cons->expr);
1297
1298       if (!a.pointer && !a.target)
1299         {
1300           t = false;
1301           gfc_error ("The element in the structure constructor at %L, "
1302                      "for pointer component '%s' should be a POINTER or "
1303                      "a TARGET", &cons->expr->where, comp->name);
1304         }
1305
1306       if (init)
1307         {
1308           /* F08:C461. Additional checks for pointer initialization.  */
1309           if (a.allocatable)
1310             {
1311               t = false;
1312               gfc_error ("Pointer initialization target at %L "
1313                          "must not be ALLOCATABLE ", &cons->expr->where);
1314             }
1315           if (!a.save)
1316             {
1317               t = false;
1318               gfc_error ("Pointer initialization target at %L "
1319                          "must have the SAVE attribute", &cons->expr->where);
1320             }
1321         }
1322
1323       /* F2003, C1272 (3).  */
1324       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
1325           && (gfc_impure_variable (cons->expr->symtree->n.sym)
1326               || gfc_is_coindexed (cons->expr)))
1327         {
1328           t = false;
1329           gfc_error ("Invalid expression in the structure constructor for "
1330                      "pointer component '%s' at %L in PURE procedure",
1331                      comp->name, &cons->expr->where);
1332         }
1333
1334       if (gfc_implicit_pure (NULL)
1335             && cons->expr->expr_type == EXPR_VARIABLE
1336             && (gfc_impure_variable (cons->expr->symtree->n.sym)
1337                 || gfc_is_coindexed (cons->expr)))
1338         gfc_current_ns->proc_name->attr.implicit_pure = 0;
1339
1340     }
1341
1342   return t;
1343 }
1344
1345
1346 /****************** Expression name resolution ******************/
1347
1348 /* Returns 0 if a symbol was not declared with a type or
1349    attribute declaration statement, nonzero otherwise.  */
1350
1351 static int
1352 was_declared (gfc_symbol *sym)
1353 {
1354   symbol_attribute a;
1355
1356   a = sym->attr;
1357
1358   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
1359     return 1;
1360
1361   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
1362       || a.optional || a.pointer || a.save || a.target || a.volatile_
1363       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
1364       || a.asynchronous || a.codimension)
1365     return 1;
1366
1367   return 0;
1368 }
1369
1370
1371 /* Determine if a symbol is generic or not.  */
1372
1373 static int
1374 generic_sym (gfc_symbol *sym)
1375 {
1376   gfc_symbol *s;
1377
1378   if (sym->attr.generic ||
1379       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
1380     return 1;
1381
1382   if (was_declared (sym) || sym->ns->parent == NULL)
1383     return 0;
1384
1385   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1386
1387   if (s != NULL)
1388     {
1389       if (s == sym)
1390         return 0;
1391       else
1392         return generic_sym (s);
1393     }
1394
1395   return 0;
1396 }
1397
1398
1399 /* Determine if a symbol is specific or not.  */
1400
1401 static int
1402 specific_sym (gfc_symbol *sym)
1403 {
1404   gfc_symbol *s;
1405
1406   if (sym->attr.if_source == IFSRC_IFBODY
1407       || sym->attr.proc == PROC_MODULE
1408       || sym->attr.proc == PROC_INTERNAL
1409       || sym->attr.proc == PROC_ST_FUNCTION
1410       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1411       || sym->attr.external)
1412     return 1;
1413
1414   if (was_declared (sym) || sym->ns->parent == NULL)
1415     return 0;
1416
1417   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1418
1419   return (s == NULL) ? 0 : specific_sym (s);
1420 }
1421
1422
1423 /* Figure out if the procedure is specific, generic or unknown.  */
1424
1425 typedef enum
1426 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1427 proc_type;
1428
1429 static proc_type
1430 procedure_kind (gfc_symbol *sym)
1431 {
1432   if (generic_sym (sym))
1433     return PTYPE_GENERIC;
1434
1435   if (specific_sym (sym))
1436     return PTYPE_SPECIFIC;
1437
1438   return PTYPE_UNKNOWN;
1439 }
1440
1441 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1442    is nonzero when matching actual arguments.  */
1443
1444 static int need_full_assumed_size = 0;
1445
1446 static bool
1447 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1448 {
1449   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1450       return false;
1451
1452   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1453      What should it be?  */
1454   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1455           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1456                && (e->ref->u.ar.type == AR_FULL))
1457     {
1458       gfc_error ("The upper bound in the last dimension must "
1459                  "appear in the reference to the assumed size "
1460                  "array '%s' at %L", sym->name, &e->where);
1461       return true;
1462     }
1463   return false;
1464 }
1465
1466
1467 /* Look for bad assumed size array references in argument expressions
1468   of elemental and array valued intrinsic procedures.  Since this is
1469   called from procedure resolution functions, it only recurses at
1470   operators.  */
1471
1472 static bool
1473 resolve_assumed_size_actual (gfc_expr *e)
1474 {
1475   if (e == NULL)
1476    return false;
1477
1478   switch (e->expr_type)
1479     {
1480     case EXPR_VARIABLE:
1481       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1482         return true;
1483       break;
1484
1485     case EXPR_OP:
1486       if (resolve_assumed_size_actual (e->value.op.op1)
1487           || resolve_assumed_size_actual (e->value.op.op2))
1488         return true;
1489       break;
1490
1491     default:
1492       break;
1493     }
1494   return false;
1495 }
1496
1497
1498 /* Check a generic procedure, passed as an actual argument, to see if
1499    there is a matching specific name.  If none, it is an error, and if
1500    more than one, the reference is ambiguous.  */
1501 static int
1502 count_specific_procs (gfc_expr *e)
1503 {
1504   int n;
1505   gfc_interface *p;
1506   gfc_symbol *sym;
1507
1508   n = 0;
1509   sym = e->symtree->n.sym;
1510
1511   for (p = sym->generic; p; p = p->next)
1512     if (strcmp (sym->name, p->sym->name) == 0)
1513       {
1514         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1515                                        sym->name);
1516         n++;
1517       }
1518
1519   if (n > 1)
1520     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1521                &e->where);
1522
1523   if (n == 0)
1524     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1525                "argument at %L", sym->name, &e->where);
1526
1527   return n;
1528 }
1529
1530
1531 /* See if a call to sym could possibly be a not allowed RECURSION because of
1532    a missing RECURSIVE declaration.  This means that either sym is the current
1533    context itself, or sym is the parent of a contained procedure calling its
1534    non-RECURSIVE containing procedure.
1535    This also works if sym is an ENTRY.  */
1536
1537 static bool
1538 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1539 {
1540   gfc_symbol* proc_sym;
1541   gfc_symbol* context_proc;
1542   gfc_namespace* real_context;
1543
1544   if (sym->attr.flavor == FL_PROGRAM
1545       || sym->attr.flavor == FL_DERIVED)
1546     return false;
1547
1548   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1549
1550   /* If we've got an ENTRY, find real procedure.  */
1551   if (sym->attr.entry && sym->ns->entries)
1552     proc_sym = sym->ns->entries->sym;
1553   else
1554     proc_sym = sym;
1555
1556   /* If sym is RECURSIVE, all is well of course.  */
1557   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1558     return false;
1559
1560   /* Find the context procedure's "real" symbol if it has entries.
1561      We look for a procedure symbol, so recurse on the parents if we don't
1562      find one (like in case of a BLOCK construct).  */
1563   for (real_context = context; ; real_context = real_context->parent)
1564     {
1565       /* We should find something, eventually!  */
1566       gcc_assert (real_context);
1567
1568       context_proc = (real_context->entries ? real_context->entries->sym
1569                                             : real_context->proc_name);
1570
1571       /* In some special cases, there may not be a proc_name, like for this
1572          invalid code:
1573          real(bad_kind()) function foo () ...
1574          when checking the call to bad_kind ().
1575          In these cases, we simply return here and assume that the
1576          call is ok.  */
1577       if (!context_proc)
1578         return false;
1579
1580       if (context_proc->attr.flavor != FL_LABEL)
1581         break;
1582     }
1583
1584   /* A call from sym's body to itself is recursion, of course.  */
1585   if (context_proc == proc_sym)
1586     return true;
1587
1588   /* The same is true if context is a contained procedure and sym the
1589      containing one.  */
1590   if (context_proc->attr.contained)
1591     {
1592       gfc_symbol* parent_proc;
1593
1594       gcc_assert (context->parent);
1595       parent_proc = (context->parent->entries ? context->parent->entries->sym
1596                                               : context->parent->proc_name);
1597
1598       if (parent_proc == proc_sym)
1599         return true;
1600     }
1601
1602   return false;
1603 }
1604
1605
1606 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1607    its typespec and formal argument list.  */
1608
1609 bool
1610 gfc_resolve_intrinsic (gfc_symbol *sym, locus *loc)
1611 {
1612   gfc_intrinsic_sym* isym = NULL;
1613   const char* symstd;
1614
1615   if (sym->formal)
1616     return true;
1617
1618   /* Already resolved.  */
1619   if (sym->from_intmod && sym->ts.type != BT_UNKNOWN)
1620     return true;
1621
1622   /* We already know this one is an intrinsic, so we don't call
1623      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1624      gfc_find_subroutine directly to check whether it is a function or
1625      subroutine.  */
1626
1627   if (sym->intmod_sym_id && sym->attr.subroutine)
1628     {
1629       gfc_isym_id id = gfc_isym_id_by_intmod_sym (sym);
1630       isym = gfc_intrinsic_subroutine_by_id (id);
1631     }
1632   else if (sym->intmod_sym_id)
1633     {
1634       gfc_isym_id id = gfc_isym_id_by_intmod_sym (sym);
1635       isym = gfc_intrinsic_function_by_id (id);
1636     }
1637   else if (!sym->attr.subroutine)
1638     isym = gfc_find_function (sym->name);
1639
1640   if (isym && !sym->attr.subroutine)
1641     {
1642       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1643           && !sym->attr.implicit_type)
1644         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1645                       " ignored", sym->name, &sym->declared_at);
1646
1647       if (!sym->attr.function &&
1648           !gfc_add_function(&sym->attr, sym->name, loc))
1649         return false;
1650
1651       sym->ts = isym->ts;
1652     }
1653   else if (isym || (isym = gfc_find_subroutine (sym->name)))
1654     {
1655       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1656         {
1657           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1658                       " specifier", sym->name, &sym->declared_at);
1659           return false;
1660         }
1661
1662       if (!sym->attr.subroutine &&
1663           !gfc_add_subroutine(&sym->attr, sym->name, loc))
1664         return false;
1665     }
1666   else
1667     {
1668       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1669                  &sym->declared_at);
1670       return false;
1671     }
1672
1673   gfc_copy_formal_args_intr (sym, isym);
1674
1675   /* Check it is actually available in the standard settings.  */
1676   if (!gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at))
1677     {
1678       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1679                  " available in the current standard settings but %s.  Use"
1680                  " an appropriate -std=* option or enable -fall-intrinsics"
1681                  " in order to use it.",
1682                  sym->name, &sym->declared_at, symstd);
1683       return false;
1684     }
1685
1686   return true;
1687 }
1688
1689
1690 /* Resolve a procedure expression, like passing it to a called procedure or as
1691    RHS for a procedure pointer assignment.  */
1692
1693 static bool
1694 resolve_procedure_expression (gfc_expr* expr)
1695 {
1696   gfc_symbol* sym;
1697
1698   if (expr->expr_type != EXPR_VARIABLE)
1699     return true;
1700   gcc_assert (expr->symtree);
1701
1702   sym = expr->symtree->n.sym;
1703
1704   if (sym->attr.intrinsic)
1705     gfc_resolve_intrinsic (sym, &expr->where);
1706
1707   if (sym->attr.flavor != FL_PROCEDURE
1708       || (sym->attr.function && sym->result == sym))
1709     return true;
1710
1711   /* A non-RECURSIVE procedure that is used as procedure expression within its
1712      own body is in danger of being called recursively.  */
1713   if (is_illegal_recursion (sym, gfc_current_ns))
1714     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1715                  " itself recursively.  Declare it RECURSIVE or use"
1716                  " -frecursive", sym->name, &expr->where);
1717
1718   return true;
1719 }
1720
1721
1722 /* Resolve an actual argument list.  Most of the time, this is just
1723    resolving the expressions in the list.
1724    The exception is that we sometimes have to decide whether arguments
1725    that look like procedure arguments are really simple variable
1726    references.  */
1727
1728 static bool
1729 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1730                         bool no_formal_args)
1731 {
1732   gfc_symbol *sym;
1733   gfc_symtree *parent_st;
1734   gfc_expr *e;
1735   int save_need_full_assumed_size;
1736   bool return_value = false;
1737   bool actual_arg_sav = actual_arg, first_actual_arg_sav = first_actual_arg;
1738
1739   actual_arg = true;
1740   first_actual_arg = true;
1741
1742   for (; arg; arg = arg->next)
1743     {
1744       e = arg->expr;
1745       if (e == NULL)
1746         {
1747           /* Check the label is a valid branching target.  */
1748           if (arg->label)
1749             {
1750               if (arg->label->defined == ST_LABEL_UNKNOWN)
1751                 {
1752                   gfc_error ("Label %d referenced at %L is never defined",
1753                              arg->label->value, &arg->label->where);
1754                   goto cleanup;
1755                 }
1756             }
1757           first_actual_arg = false;
1758           continue;
1759         }
1760
1761       if (e->expr_type == EXPR_VARIABLE
1762             && e->symtree->n.sym->attr.generic
1763             && no_formal_args
1764             && count_specific_procs (e) != 1)
1765         goto cleanup;
1766
1767       if (e->ts.type != BT_PROCEDURE)
1768         {
1769           save_need_full_assumed_size = need_full_assumed_size;
1770           if (e->expr_type != EXPR_VARIABLE)
1771             need_full_assumed_size = 0;
1772           if (!gfc_resolve_expr (e))
1773             goto cleanup;
1774           need_full_assumed_size = save_need_full_assumed_size;
1775           goto argument_list;
1776         }
1777
1778       /* See if the expression node should really be a variable reference.  */
1779
1780       sym = e->symtree->n.sym;
1781
1782       if (sym->attr.flavor == FL_PROCEDURE
1783           || sym->attr.intrinsic
1784           || sym->attr.external)
1785         {
1786           int actual_ok;
1787
1788           /* If a procedure is not already determined to be something else
1789              check if it is intrinsic.  */
1790           if (gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1791             sym->attr.intrinsic = 1;
1792
1793           if (sym->attr.proc == PROC_ST_FUNCTION)
1794             {
1795               gfc_error ("Statement function '%s' at %L is not allowed as an "
1796                          "actual argument", sym->name, &e->where);
1797             }
1798
1799           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1800                                                sym->attr.subroutine);
1801           if (sym->attr.intrinsic && actual_ok == 0)
1802             {
1803               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1804                          "actual argument", sym->name, &e->where);
1805             }
1806
1807           if (sym->attr.contained && !sym->attr.use_assoc
1808               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1809             {
1810               if (!gfc_notify_std (GFC_STD_F2008, "Internal procedure '%s' is"
1811                                    " used as actual argument at %L", 
1812                                    sym->name, &e->where))
1813                 goto cleanup;
1814             }
1815
1816           if (sym->attr.elemental && !sym->attr.intrinsic)
1817             {
1818               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1819                          "allowed as an actual argument at %L", sym->name,
1820                          &e->where);
1821             }
1822
1823           /* Check if a generic interface has a specific procedure
1824             with the same name before emitting an error.  */
1825           if (sym->attr.generic && count_specific_procs (e) != 1)
1826             goto cleanup;
1827
1828           /* Just in case a specific was found for the expression.  */
1829           sym = e->symtree->n.sym;
1830
1831           /* If the symbol is the function that names the current (or
1832              parent) scope, then we really have a variable reference.  */
1833
1834           if (gfc_is_function_return_value (sym, sym->ns))
1835             goto got_variable;
1836
1837           /* If all else fails, see if we have a specific intrinsic.  */
1838           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1839             {
1840               gfc_intrinsic_sym *isym;
1841
1842               isym = gfc_find_function (sym->name);
1843               if (isym == NULL || !isym->specific)
1844                 {
1845                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1846                              "for the reference '%s' at %L", sym->name,
1847                              &e->where);
1848                   goto cleanup;
1849                 }
1850               sym->ts = isym->ts;
1851               sym->attr.intrinsic = 1;
1852               sym->attr.function = 1;
1853             }
1854
1855           if (!gfc_resolve_expr (e))
1856             goto cleanup;
1857           goto argument_list;
1858         }
1859
1860       /* See if the name is a module procedure in a parent unit.  */
1861
1862       if (was_declared (sym) || sym->ns->parent == NULL)
1863         goto got_variable;
1864
1865       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1866         {
1867           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1868           goto cleanup;
1869         }
1870
1871       if (parent_st == NULL)
1872         goto got_variable;
1873
1874       sym = parent_st->n.sym;
1875       e->symtree = parent_st;           /* Point to the right thing.  */
1876
1877       if (sym->attr.flavor == FL_PROCEDURE
1878           || sym->attr.intrinsic
1879           || sym->attr.external)
1880         {
1881           if (!gfc_resolve_expr (e))
1882             goto cleanup;
1883           goto argument_list;
1884         }
1885
1886     got_variable:
1887       e->expr_type = EXPR_VARIABLE;
1888       e->ts = sym->ts;
1889       if ((sym->as != NULL && sym->ts.type != BT_CLASS)
1890           || (sym->ts.type == BT_CLASS && sym->attr.class_ok
1891               && CLASS_DATA (sym)->as))
1892         {
1893           e->rank = sym->ts.type == BT_CLASS
1894                     ? CLASS_DATA (sym)->as->rank : sym->as->rank;
1895           e->ref = gfc_get_ref ();
1896           e->ref->type = REF_ARRAY;
1897           e->ref->u.ar.type = AR_FULL;
1898           e->ref->u.ar.as = sym->ts.type == BT_CLASS
1899                             ? CLASS_DATA (sym)->as : sym->as;
1900         }
1901
1902       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1903          primary.c (match_actual_arg). If above code determines that it
1904          is a  variable instead, it needs to be resolved as it was not
1905          done at the beginning of this function.  */
1906       save_need_full_assumed_size = need_full_assumed_size;
1907       if (e->expr_type != EXPR_VARIABLE)
1908         need_full_assumed_size = 0;
1909       if (!gfc_resolve_expr (e))
1910         goto cleanup;
1911       need_full_assumed_size = save_need_full_assumed_size;
1912
1913     argument_list:
1914       /* Check argument list functions %VAL, %LOC and %REF.  There is
1915          nothing to do for %REF.  */
1916       if (arg->name && arg->name[0] == '%')
1917         {
1918           if (strncmp ("%VAL", arg->name, 4) == 0)
1919             {
1920               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1921                 {
1922                   gfc_error ("By-value argument at %L is not of numeric "
1923                              "type", &e->where);
1924                   goto cleanup;
1925                 }
1926
1927               if (e->rank)
1928                 {
1929                   gfc_error ("By-value argument at %L cannot be an array or "
1930                              "an array section", &e->where);
1931                   goto cleanup;
1932                 }
1933
1934               /* Intrinsics are still PROC_UNKNOWN here.  However,
1935                  since same file external procedures are not resolvable
1936                  in gfortran, it is a good deal easier to leave them to
1937                  intrinsic.c.  */
1938               if (ptype != PROC_UNKNOWN
1939                   && ptype != PROC_DUMMY
1940                   && ptype != PROC_EXTERNAL
1941                   && ptype != PROC_MODULE)
1942                 {
1943                   gfc_error ("By-value argument at %L is not allowed "
1944                              "in this context", &e->where);
1945                   goto cleanup;
1946                 }
1947             }
1948
1949           /* Statement functions have already been excluded above.  */
1950           else if (strncmp ("%LOC", arg->name, 4) == 0
1951                    && e->ts.type == BT_PROCEDURE)
1952             {
1953               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1954                 {
1955                   gfc_error ("Passing internal procedure at %L by location "
1956                              "not allowed", &e->where);
1957                   goto cleanup;
1958                 }
1959             }
1960         }
1961
1962       /* Fortran 2008, C1237.  */
1963       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1964           && gfc_has_ultimate_pointer (e))
1965         {
1966           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1967                      "component", &e->where);
1968           goto cleanup;
1969         }
1970
1971       first_actual_arg = false;
1972     }
1973
1974   return_value = true;
1975
1976 cleanup:
1977   actual_arg = actual_arg_sav;
1978   first_actual_arg = first_actual_arg_sav;
1979
1980   return return_value;
1981 }
1982
1983
1984 /* Do the checks of the actual argument list that are specific to elemental
1985    procedures.  If called with c == NULL, we have a function, otherwise if
1986    expr == NULL, we have a subroutine.  */
1987
1988 static bool
1989 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1990 {
1991   gfc_actual_arglist *arg0;
1992   gfc_actual_arglist *arg;
1993   gfc_symbol *esym = NULL;
1994   gfc_intrinsic_sym *isym = NULL;
1995   gfc_expr *e = NULL;
1996   gfc_intrinsic_arg *iformal = NULL;
1997   gfc_formal_arglist *eformal = NULL;
1998   bool formal_optional = false;
1999   bool set_by_optional = false;
2000   int i;
2001   int rank = 0;
2002
2003   /* Is this an elemental procedure?  */
2004   if (expr && expr->value.function.actual != NULL)
2005     {
2006       if (expr->value.function.esym != NULL
2007           && expr->value.function.esym->attr.elemental)
2008         {
2009           arg0 = expr->value.function.actual;
2010           esym = expr->value.function.esym;
2011         }
2012       else if (expr->value.function.isym != NULL
2013                && expr->value.function.isym->elemental)
2014         {
2015           arg0 = expr->value.function.actual;
2016           isym = expr->value.function.isym;
2017         }
2018       else
2019         return true;
2020     }
2021   else if (c && c->ext.actual != NULL)
2022     {
2023       arg0 = c->ext.actual;
2024
2025       if (c->resolved_sym)
2026         esym = c->resolved_sym;
2027       else
2028         esym = c->symtree->n.sym;
2029       gcc_assert (esym);
2030
2031       if (!esym->attr.elemental)
2032         return true;
2033     }
2034   else
2035     return true;
2036
2037   /* The rank of an elemental is the rank of its array argument(s).  */
2038   for (arg = arg0; arg; arg = arg->next)
2039     {
2040       if (arg->expr != NULL && arg->expr->rank != 0)
2041         {
2042           rank = arg->expr->rank;
2043           if (arg->expr->expr_type == EXPR_VARIABLE
2044               && arg->expr->symtree->n.sym->attr.optional)
2045             set_by_optional = true;
2046
2047           /* Function specific; set the result rank and shape.  */
2048           if (expr)
2049             {
2050               expr->rank = rank;
2051               if (!expr->shape && arg->expr->shape)
2052                 {
2053                   expr->shape = gfc_get_shape (rank);
2054                   for (i = 0; i < rank; i++)
2055                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
2056                 }
2057             }
2058           break;
2059         }
2060     }
2061
2062   /* If it is an array, it shall not be supplied as an actual argument
2063      to an elemental procedure unless an array of the same rank is supplied
2064      as an actual argument corresponding to a nonoptional dummy argument of
2065      that elemental procedure(12.4.1.5).  */
2066   formal_optional = false;
2067   if (isym)
2068     iformal = isym->formal;
2069   else
2070     eformal = esym->formal;
2071
2072   for (arg = arg0; arg; arg = arg->next)
2073     {
2074       if (eformal)
2075         {
2076           if (eformal->sym && eformal->sym->attr.optional)
2077             formal_optional = true;
2078           eformal = eformal->next;
2079         }
2080       else if (isym && iformal)
2081         {
2082           if (iformal->optional)
2083             formal_optional = true;
2084           iformal = iformal->next;
2085         }
2086       else if (isym)
2087         formal_optional = true;
2088
2089       if (pedantic && arg->expr != NULL
2090           && arg->expr->expr_type == EXPR_VARIABLE
2091           && arg->expr->symtree->n.sym->attr.optional
2092           && formal_optional
2093           && arg->expr->rank
2094           && (set_by_optional || arg->expr->rank != rank)
2095           && !(isym && isym->id == GFC_ISYM_CONVERSION))
2096         {
2097           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
2098                        "MISSING, it cannot be the actual argument of an "
2099                        "ELEMENTAL procedure unless there is a non-optional "
2100                        "argument with the same rank (12.4.1.5)",
2101                        arg->expr->symtree->n.sym->name, &arg->expr->where);
2102         }
2103     }
2104
2105   for (arg = arg0; arg; arg = arg->next)
2106     {
2107       if (arg->expr == NULL || arg->expr->rank == 0)
2108         continue;
2109
2110       /* Being elemental, the last upper bound of an assumed size array
2111          argument must be present.  */
2112       if (resolve_assumed_size_actual (arg->expr))
2113         return false;
2114
2115       /* Elemental procedure's array actual arguments must conform.  */
2116       if (e != NULL)
2117         {
2118           if (!gfc_check_conformance (arg->expr, e, "elemental procedure"))
2119             return false;
2120         }
2121       else
2122         e = arg->expr;
2123     }
2124
2125   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
2126      is an array, the intent inout/out variable needs to be also an array.  */
2127   if (rank > 0 && esym && expr == NULL)
2128     for (eformal = esym->formal, arg = arg0; arg && eformal;
2129          arg = arg->next, eformal = eformal->next)
2130       if ((eformal->sym->attr.intent == INTENT_OUT
2131            || eformal->sym->attr.intent == INTENT_INOUT)
2132           && arg->expr && arg->expr->rank == 0)
2133         {
2134           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
2135                      "ELEMENTAL subroutine '%s' is a scalar, but another "
2136                      "actual argument is an array", &arg->expr->where,
2137                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
2138                      : "INOUT", eformal->sym->name, esym->name);
2139           return false;
2140         }
2141   return true;
2142 }
2143
2144
2145 /* This function does the checking of references to global procedures
2146    as defined in sections 18.1 and 14.1, respectively, of the Fortran
2147    77 and 95 standards.  It checks for a gsymbol for the name, making
2148    one if it does not already exist.  If it already exists, then the
2149    reference being resolved must correspond to the type of gsymbol.
2150    Otherwise, the new symbol is equipped with the attributes of the
2151    reference.  The corresponding code that is called in creating
2152    global entities is parse.c.
2153
2154    In addition, for all but -std=legacy, the gsymbols are used to
2155    check the interfaces of external procedures from the same file.
2156    The namespace of the gsymbol is resolved and then, once this is
2157    done the interface is checked.  */
2158
2159
2160 static bool
2161 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
2162 {
2163   if (!gsym_ns->proc_name->attr.recursive)
2164     return true;
2165
2166   if (sym->ns == gsym_ns)
2167     return false;
2168
2169   if (sym->ns->parent && sym->ns->parent == gsym_ns)
2170     return false;
2171
2172   return true;
2173 }
2174
2175 static bool
2176 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
2177 {
2178   if (gsym_ns->entries)
2179     {
2180       gfc_entry_list *entry = gsym_ns->entries;
2181
2182       for (; entry; entry = entry->next)
2183         {
2184           if (strcmp (sym->name, entry->sym->name) == 0)
2185             {
2186               if (strcmp (gsym_ns->proc_name->name,
2187                           sym->ns->proc_name->name) == 0)
2188                 return false;
2189
2190               if (sym->ns->parent
2191                   && strcmp (gsym_ns->proc_name->name,
2192                              sym->ns->parent->proc_name->name) == 0)
2193                 return false;
2194             }
2195         }
2196     }
2197   return true;
2198 }
2199
2200
2201 /* Check for the requirement of an explicit interface. F08:12.4.2.2.  */
2202
2203 bool
2204 gfc_explicit_interface_required (gfc_symbol *sym, char *errmsg, int err_len)
2205 {
2206   gfc_formal_arglist *arg = gfc_sym_get_dummy_args (sym);
2207
2208   for ( ; arg; arg = arg->next)
2209     {
2210       if (!arg->sym)
2211         continue;
2212
2213       if (arg->sym->attr.allocatable)  /* (2a)  */
2214         {
2215           strncpy (errmsg, _("allocatable argument"), err_len);
2216           return true;
2217         }
2218       else if (arg->sym->attr.asynchronous)
2219         {
2220           strncpy (errmsg, _("asynchronous argument"), err_len);
2221           return true;
2222         }
2223       else if (arg->sym->attr.optional)
2224         {
2225           strncpy (errmsg, _("optional argument"), err_len);
2226           return true;
2227         }
2228       else if (arg->sym->attr.pointer)
2229         {
2230           strncpy (errmsg, _("pointer argument"), err_len);
2231           return true;
2232         }
2233       else if (arg->sym->attr.target)
2234         {
2235           strncpy (errmsg, _("target argument"), err_len);
2236           return true;
2237         }
2238       else if (arg->sym->attr.value)
2239         {
2240           strncpy (errmsg, _("value argument"), err_len);
2241           return true;
2242         }
2243       else if (arg->sym->attr.volatile_)
2244         {
2245           strncpy (errmsg, _("volatile argument"), err_len);
2246           return true;
2247         }
2248       else if (arg->sym->as && arg->sym->as->type == AS_ASSUMED_SHAPE)  /* (2b)  */
2249         {
2250           strncpy (errmsg, _("assumed-shape argument"), err_len);
2251           return true;
2252         }
2253       else if (arg->sym->as && arg->sym->as->type == AS_ASSUMED_RANK)  /* TS 29113, 6.2.  */
2254         {
2255           strncpy (errmsg, _("assumed-rank argument"), err_len);
2256           return true;
2257         }
2258       else if (arg->sym->attr.codimension)  /* (2c)  */
2259         {
2260           strncpy (errmsg, _("coarray argument"), err_len);
2261           return true;
2262         }
2263       else if (false)  /* (2d) TODO: parametrized derived type  */
2264         {
2265           strncpy (errmsg, _("parametrized derived type argument"), err_len);
2266           return true;
2267         }
2268       else if (arg->sym->ts.type == BT_CLASS)  /* (2e)  */
2269         {
2270           strncpy (errmsg, _("polymorphic argument"), err_len);
2271           return true;
2272         }
2273       else if (arg->sym->attr.ext_attr & (1 << EXT_ATTR_NO_ARG_CHECK))
2274         {
2275           strncpy (errmsg, _("NO_ARG_CHECK attribute"), err_len);
2276           return true;
2277         }
2278       else if (arg->sym->ts.type == BT_ASSUMED)
2279         {
2280           /* As assumed-type is unlimited polymorphic (cf. above).
2281              See also TS 29113, Note 6.1.  */
2282           strncpy (errmsg, _("assumed-type argument"), err_len);
2283           return true;
2284         }
2285     }
2286
2287   if (sym->attr.function)
2288     {
2289       gfc_symbol *res = sym->result ? sym->result : sym;
2290
2291       if (res->attr.dimension)  /* (3a)  */
2292         {
2293           strncpy (errmsg, _("array result"), err_len);
2294           return true;
2295         }
2296       else if (res->attr.pointer || res->attr.allocatable)  /* (3b)  */
2297         {
2298           strncpy (errmsg, _("pointer or allocatable result"), err_len);
2299           return true;
2300         }
2301       else if (res->ts.type == BT_CHARACTER && res->ts.u.cl
2302                && res->ts.u.cl->length
2303                && res->ts.u.cl->length->expr_type != EXPR_CONSTANT)  /* (3c)  */
2304         {
2305           strncpy (errmsg, _("result with non-constant character length"), err_len);
2306           return true;
2307         }
2308     }
2309
2310   if (sym->attr.elemental)  /* (4)  */
2311     {
2312       strncpy (errmsg, _("elemental procedure"), err_len);
2313       return true;
2314     }
2315   else if (sym->attr.is_bind_c)  /* (5)  */
2316     {
2317       strncpy (errmsg, _("bind(c) procedure"), err_len);
2318       return true;
2319     }
2320
2321   return false;
2322 }
2323
2324
2325 static void
2326 resolve_global_procedure (gfc_symbol *sym, locus *where,
2327                           gfc_actual_arglist **actual, int sub)
2328 {
2329   gfc_gsymbol * gsym;
2330   gfc_namespace *ns;
2331   enum gfc_symbol_type type;
2332   char reason[200];
2333
2334   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
2335
2336   gsym = gfc_get_gsymbol (sym->name);
2337
2338   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
2339     gfc_global_used (gsym, where);
2340
2341   if ((sym->attr.if_source == IFSRC_UNKNOWN
2342        || sym->attr.if_source == IFSRC_IFBODY)
2343       && gsym->type != GSYM_UNKNOWN
2344       && gsym->ns
2345       && gsym->ns->resolved != -1
2346       && gsym->ns->proc_name
2347       && not_in_recursive (sym, gsym->ns)
2348       && not_entry_self_reference (sym, gsym->ns))
2349     {
2350       gfc_symbol *def_sym;
2351
2352       /* Resolve the gsymbol namespace if needed.  */
2353       if (!gsym->ns->resolved)
2354         {
2355           gfc_dt_list *old_dt_list;
2356           struct gfc_omp_saved_state old_omp_state;
2357
2358           /* Stash away derived types so that the backend_decls do not
2359              get mixed up.  */
2360           old_dt_list = gfc_derived_types;
2361           gfc_derived_types = NULL;
2362           /* And stash away openmp state.  */
2363           gfc_omp_save_and_clear_state (&old_omp_state);
2364
2365           gfc_resolve (gsym->ns);
2366
2367           /* Store the new derived types with the global namespace.  */
2368           if (gfc_derived_types)
2369             gsym->ns->derived_types = gfc_derived_types;
2370
2371           /* Restore the derived types of this namespace.  */
2372           gfc_derived_types = old_dt_list;
2373           /* And openmp state.  */
2374           gfc_omp_restore_state (&old_omp_state);
2375         }
2376
2377       /* Make sure that translation for the gsymbol occurs before
2378          the procedure currently being resolved.  */
2379       ns = gfc_global_ns_list;
2380       for (; ns && ns != gsym->ns; ns = ns->sibling)
2381         {
2382           if (ns->sibling == gsym->ns)
2383             {
2384               ns->sibling = gsym->ns->sibling;
2385               gsym->ns->sibling = gfc_global_ns_list;
2386               gfc_global_ns_list = gsym->ns;
2387               break;
2388             }
2389         }
2390
2391       def_sym = gsym->ns->proc_name;
2392       if (def_sym->attr.entry_master)
2393         {
2394           gfc_entry_list *entry;
2395           for (entry = gsym->ns->entries; entry; entry = entry->next)
2396             if (strcmp (entry->sym->name, sym->name) == 0)
2397               {
2398                 def_sym = entry->sym;
2399                 break;
2400               }
2401         }
2402
2403       if (sym->attr.function && !gfc_compare_types (&sym->ts, &def_sym->ts))
2404         {
2405           gfc_error ("Return type mismatch of function '%s' at %L (%s/%s)",
2406                      sym->name, &sym->declared_at, gfc_typename (&sym->ts),
2407                      gfc_typename (&def_sym->ts));
2408           goto done;
2409         }
2410
2411       if (sym->attr.if_source == IFSRC_UNKNOWN
2412           && gfc_explicit_interface_required (def_sym, reason, sizeof(reason)))
2413         {
2414           gfc_error ("Explicit interface required for '%s' at %L: %s",
2415                      sym->name, &sym->declared_at, reason);
2416           goto done;
2417         }
2418
2419       if (!pedantic && (gfc_option.allow_std & GFC_STD_GNU))
2420         /* Turn erros into warnings with -std=gnu and -std=legacy.  */
2421         gfc_errors_to_warnings (1);
2422
2423       if (!gfc_compare_interfaces (sym, def_sym, sym->name, 0, 1,
2424                                    reason, sizeof(reason), NULL, NULL))
2425         {       
2426           gfc_error ("Interface mismatch in global procedure '%s' at %L: %s ",
2427                     sym->name, &sym->declared_at, reason);
2428           goto done;
2429         }
2430
2431       if (!pedantic
2432           || ((gfc_option.warn_std & GFC_STD_LEGACY)
2433               && !(gfc_option.warn_std & GFC_STD_GNU)))
2434         gfc_errors_to_warnings (1);
2435
2436       if (sym->attr.if_source != IFSRC_IFBODY)
2437         gfc_procedure_use (def_sym, actual, where);
2438     }
2439     
2440 done:
2441   gfc_errors_to_warnings (0);
2442
2443   if (gsym->type == GSYM_UNKNOWN)
2444     {
2445       gsym->type = type;
2446       gsym->where = *where;
2447     }
2448
2449   gsym->used = 1;
2450 }
2451
2452
2453 /************* Function resolution *************/
2454
2455 /* Resolve a function call known to be generic.
2456    Section 14.1.2.4.1.  */
2457
2458 static match
2459 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
2460 {
2461   gfc_symbol *s;
2462
2463   if (sym->attr.generic)
2464     {
2465       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
2466       if (s != NULL)
2467         {
2468           expr->value.function.name = s->name;
2469           expr->value.function.esym = s;
2470
2471           if (s->ts.type != BT_UNKNOWN)
2472             expr->ts = s->ts;
2473           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
2474             expr->ts = s->result->ts;
2475
2476           if (s->as != NULL)
2477             expr->rank = s->as->rank;
2478           else if (s->result != NULL && s->result->as != NULL)
2479             expr->rank = s->result->as->rank;
2480
2481           gfc_set_sym_referenced (expr->value.function.esym);
2482
2483           return MATCH_YES;
2484         }
2485
2486       /* TODO: Need to search for elemental references in generic
2487          interface.  */
2488     }
2489
2490   if (sym->attr.intrinsic)
2491     return gfc_intrinsic_func_interface (expr, 0);
2492
2493   return MATCH_NO;
2494 }
2495
2496
2497 static bool
2498 resolve_generic_f (gfc_expr *expr)
2499 {
2500   gfc_symbol *sym;
2501   match m;
2502   gfc_interface *intr = NULL;
2503
2504   sym = expr->symtree->n.sym;
2505
2506   for (;;)
2507     {
2508       m = resolve_generic_f0 (expr, sym);
2509       if (m == MATCH_YES)
2510         return true;
2511       else if (m == MATCH_ERROR)
2512         return false;
2513
2514 generic:
2515       if (!intr)
2516         for (intr = sym->generic; intr; intr = intr->next)
2517           if (intr->sym->attr.flavor == FL_DERIVED)
2518             break;
2519
2520       if (sym->ns->parent == NULL)
2521         break;
2522       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2523
2524       if (sym == NULL)
2525         break;
2526       if (!generic_sym (sym))
2527         goto generic;
2528     }
2529
2530   /* Last ditch attempt.  See if the reference is to an intrinsic
2531      that possesses a matching interface.  14.1.2.4  */
2532   if (sym  && !intr && !gfc_is_intrinsic (sym, 0, expr->where))
2533     {
2534       gfc_error ("There is no specific function for the generic '%s' "
2535                  "at %L", expr->symtree->n.sym->name, &expr->where);
2536       return false;
2537     }
2538
2539   if (intr)
2540     {
2541       if (!gfc_convert_to_structure_constructor (expr, intr->sym, NULL, 
2542                                                  NULL, false))
2543         return false;
2544       return resolve_structure_cons (expr, 0);
2545     }
2546
2547   m = gfc_intrinsic_func_interface (expr, 0);
2548   if (m == MATCH_YES)
2549     return true;
2550
2551   if (m == MATCH_NO)
2552     gfc_error ("Generic function '%s' at %L is not consistent with a "
2553                "specific intrinsic interface", expr->symtree->n.sym->name,
2554                &expr->where);
2555
2556   return false;
2557 }
2558
2559
2560 /* Resolve a function call known to be specific.  */
2561
2562 static match
2563 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2564 {
2565   match m;
2566
2567   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2568     {
2569       if (sym->attr.dummy)
2570         {
2571           sym->attr.proc = PROC_DUMMY;
2572           goto found;
2573         }
2574
2575       sym->attr.proc = PROC_EXTERNAL;
2576       goto found;
2577     }
2578
2579   if (sym->attr.proc == PROC_MODULE
2580       || sym->attr.proc == PROC_ST_FUNCTION
2581       || sym->attr.proc == PROC_INTERNAL)
2582     goto found;
2583
2584   if (sym->attr.intrinsic)
2585     {
2586       m = gfc_intrinsic_func_interface (expr, 1);
2587       if (m == MATCH_YES)
2588         return MATCH_YES;
2589       if (m == MATCH_NO)
2590         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2591                    "with an intrinsic", sym->name, &expr->where);
2592
2593       return MATCH_ERROR;
2594     }
2595
2596   return MATCH_NO;
2597
2598 found:
2599   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2600
2601   if (sym->result)
2602     expr->ts = sym->result->ts;
2603   else
2604     expr->ts = sym->ts;
2605   expr->value.function.name = sym->name;
2606   expr->value.function.esym = sym;
2607   if (sym->as != NULL)
2608     expr->rank = sym->as->rank;
2609
2610   return MATCH_YES;
2611 }
2612
2613
2614 static bool
2615 resolve_specific_f (gfc_expr *expr)
2616 {
2617   gfc_symbol *sym;
2618   match m;
2619
2620   sym = expr->symtree->n.sym;
2621
2622   for (;;)
2623     {
2624       m = resolve_specific_f0 (sym, expr);
2625       if (m == MATCH_YES)
2626         return true;
2627       if (m == MATCH_ERROR)
2628         return false;
2629
2630       if (sym->ns->parent == NULL)
2631         break;
2632
2633       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2634
2635       if (sym == NULL)
2636         break;
2637     }
2638
2639   gfc_error ("Unable to resolve the specific function '%s' at %L",
2640              expr->symtree->n.sym->name, &expr->where);
2641
2642   return true;
2643 }
2644
2645
2646 /* Resolve a procedure call not known to be generic nor specific.  */
2647
2648 static bool
2649 resolve_unknown_f (gfc_expr *expr)
2650 {
2651   gfc_symbol *sym;
2652   gfc_typespec *ts;
2653
2654   sym = expr->symtree->n.sym;
2655
2656   if (sym->attr.dummy)
2657     {
2658       sym->attr.proc = PROC_DUMMY;
2659       expr->value.function.name = sym->name;
2660       goto set_type;
2661     }
2662
2663   /* See if we have an intrinsic function reference.  */
2664
2665   if (gfc_is_intrinsic (sym, 0, expr->where))
2666     {
2667       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2668         return true;
2669       return false;
2670     }
2671
2672   /* The reference is to an external name.  */
2673
2674   sym->attr.proc = PROC_EXTERNAL;
2675   expr->value.function.name = sym->name;
2676   expr->value.function.esym = expr->symtree->n.sym;
2677
2678   if (sym->as != NULL)
2679     expr->rank = sym->as->rank;
2680
2681   /* Type of the expression is either the type of the symbol or the
2682      default type of the symbol.  */
2683
2684 set_type:
2685   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2686
2687   if (sym->ts.type != BT_UNKNOWN)
2688     expr->ts = sym->ts;
2689   else
2690     {
2691       ts = gfc_get_default_type (sym->name, sym->ns);
2692
2693       if (ts->type == BT_UNKNOWN)
2694         {
2695           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2696                      sym->name, &expr->where);
2697           return false;
2698         }
2699       else
2700         expr->ts = *ts;
2701     }
2702
2703   return true;
2704 }
2705
2706
2707 /* Return true, if the symbol is an external procedure.  */
2708 static bool
2709 is_external_proc (gfc_symbol *sym)
2710 {
2711   if (!sym->attr.dummy && !sym->attr.contained
2712         && !gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at)
2713         && sym->attr.proc != PROC_ST_FUNCTION
2714         && !sym->attr.proc_pointer
2715         && !sym->attr.use_assoc
2716         && sym->name)
2717     return true;
2718
2719   return false;
2720 }
2721
2722
2723 /* Figure out if a function reference is pure or not.  Also set the name
2724    of the function for a potential error message.  Return nonzero if the
2725    function is PURE, zero if not.  */
2726 static int
2727 pure_stmt_function (gfc_expr *, gfc_symbol *);
2728
2729 static int
2730 pure_function (gfc_expr *e, const char **name)
2731 {
2732   int pure;
2733
2734   *name = NULL;
2735
2736   if (e->symtree != NULL
2737         && e->symtree->n.sym != NULL
2738         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2739     return pure_stmt_function (e, e->symtree->n.sym);
2740
2741   if (e->value.function.esym)
2742     {
2743       pure = gfc_pure (e->value.function.esym);
2744       *name = e->value.function.esym->name;
2745     }
2746   else if (e->value.function.isym)
2747     {
2748       pure = e->value.function.isym->pure
2749              || e->value.function.isym->elemental;
2750       *name = e->value.function.isym->name;
2751     }
2752   else
2753     {
2754       /* Implicit functions are not pure.  */
2755       pure = 0;
2756       *name = e->value.function.name;
2757     }
2758
2759   return pure;
2760 }
2761
2762
2763 static bool
2764 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2765                  int *f ATTRIBUTE_UNUSED)
2766 {
2767   const char *name;
2768
2769   /* Don't bother recursing into other statement functions
2770      since they will be checked individually for purity.  */
2771   if (e->expr_type != EXPR_FUNCTION
2772         || !e->symtree
2773         || e->symtree->n.sym == sym
2774         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2775     return false;
2776
2777   return pure_function (e, &name) ? false : true;
2778 }
2779
2780
2781 static int
2782 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2783 {
2784   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2785 }
2786
2787
2788 /* Resolve a function call, which means resolving the arguments, then figuring
2789    out which entity the name refers to.  */
2790
2791 static bool
2792 resolve_function (gfc_expr *expr)
2793 {
2794   gfc_actual_arglist *arg;
2795   gfc_symbol *sym;
2796   const char *name;
2797   bool t;
2798   int temp;
2799   procedure_type p = PROC_INTRINSIC;
2800   bool no_formal_args;
2801
2802   sym = NULL;
2803   if (expr->symtree)
2804     sym = expr->symtree->n.sym;
2805
2806   /* If this is a procedure pointer component, it has already been resolved.  */
2807   if (gfc_is_proc_ptr_comp (expr))
2808     return true;
2809
2810   if (sym && sym->attr.intrinsic
2811       && !gfc_resolve_intrinsic (sym, &expr->where))
2812     return false;
2813
2814   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2815     {
2816       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2817       return false;
2818     }
2819
2820   /* If this ia a deferred TBP with an abstract interface (which may
2821      of course be referenced), expr->value.function.esym will be set.  */
2822   if (sym && sym->attr.abstract && !expr->value.function.esym)
2823     {
2824       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2825                  sym->name, &expr->where);
2826       return false;
2827     }
2828
2829   /* Switch off assumed size checking and do this again for certain kinds
2830      of procedure, once the procedure itself is resolved.  */
2831   need_full_assumed_size++;
2832
2833   if (expr->symtree && expr->symtree->n.sym)
2834     p = expr->symtree->n.sym->attr.proc;
2835
2836   if (expr->value.function.isym && expr->value.function.isym->inquiry)
2837     inquiry_argument = true;
2838   no_formal_args = sym && is_external_proc (sym)
2839                        && gfc_sym_get_dummy_args (sym) == NULL;
2840
2841   if (!resolve_actual_arglist (expr->value.function.actual, 
2842                                p, no_formal_args))
2843     {
2844       inquiry_argument = false;
2845       return false;
2846     }
2847
2848   inquiry_argument = false;
2849
2850   /* Resume assumed_size checking.  */
2851   need_full_assumed_size--;
2852
2853   /* If the procedure is external, check for usage.  */
2854   if (sym && is_external_proc (sym))
2855     resolve_global_procedure (sym, &expr->where,
2856                               &expr->value.function.actual, 0);
2857
2858   if (sym && sym->ts.type == BT_CHARACTER
2859       && sym->ts.u.cl
2860       && sym->ts.u.cl->length == NULL
2861       && !sym->attr.dummy
2862       && !sym->ts.deferred
2863       && expr->value.function.esym == NULL
2864       && !sym->attr.contained)
2865     {
2866       /* Internal procedures are taken care of in resolve_contained_fntype.  */
2867       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
2868                  "be used at %L since it is not a dummy argument",
2869                  sym->name, &expr->where);
2870       return false;
2871     }
2872
2873   /* See if function is already resolved.  */
2874
2875   if (expr->value.function.name != NULL)
2876     {
2877       if (expr->ts.type == BT_UNKNOWN)
2878         expr->ts = sym->ts;
2879       t = true;
2880     }
2881   else
2882     {
2883       /* Apply the rules of section 14.1.2.  */
2884
2885       switch (procedure_kind (sym))
2886         {
2887         case PTYPE_GENERIC:
2888           t = resolve_generic_f (expr);
2889           break;
2890
2891         case PTYPE_SPECIFIC:
2892           t = resolve_specific_f (expr);
2893           break;
2894
2895         case PTYPE_UNKNOWN:
2896           t = resolve_unknown_f (expr);
2897           break;
2898
2899         default:
2900           gfc_internal_error ("resolve_function(): bad function type");
2901         }
2902     }
2903
2904   /* If the expression is still a function (it might have simplified),
2905      then we check to see if we are calling an elemental function.  */
2906
2907   if (expr->expr_type != EXPR_FUNCTION)
2908     return t;
2909
2910   temp = need_full_assumed_size;
2911   need_full_assumed_size = 0;
2912
2913   if (!resolve_elemental_actual (expr, NULL))
2914     return false;
2915
2916   if (omp_workshare_flag
2917       && expr->value.function.esym
2918       && ! gfc_elemental (expr->value.function.esym))
2919     {
2920       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
2921                  "in WORKSHARE construct", expr->value.function.esym->name,
2922                  &expr->where);
2923       t = false;
2924     }
2925
2926 #define GENERIC_ID expr->value.function.isym->id
2927   else if (expr->value.function.actual != NULL
2928            && expr->value.function.isym != NULL
2929            && GENERIC_ID != GFC_ISYM_LBOUND
2930            && GENERIC_ID != GFC_ISYM_LEN
2931            && GENERIC_ID != GFC_ISYM_LOC
2932            && GENERIC_ID != GFC_ISYM_C_LOC
2933            && GENERIC_ID != GFC_ISYM_PRESENT)
2934     {
2935       /* Array intrinsics must also have the last upper bound of an
2936          assumed size array argument.  UBOUND and SIZE have to be
2937          excluded from the check if the second argument is anything
2938          than a constant.  */
2939
2940       for (arg = expr->value.function.actual; arg; arg = arg->next)
2941         {
2942           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
2943               && arg == expr->value.function.actual
2944               && arg->next != NULL && arg->next->expr)
2945             {
2946               if (arg->next->expr->expr_type != EXPR_CONSTANT)
2947                 break;
2948
2949               if (arg->next->name && strncmp (arg->next->name, "kind", 4) == 0)
2950                 break;
2951
2952               if ((int)mpz_get_si (arg->next->expr->value.integer)
2953                         < arg->expr->rank)
2954                 break;
2955             }
2956
2957           if (arg->expr != NULL
2958               && arg->expr->rank > 0
2959               && resolve_assumed_size_actual (arg->expr))
2960             return false;
2961         }
2962     }
2963 #undef GENERIC_ID
2964
2965   need_full_assumed_size = temp;
2966   name = NULL;
2967
2968   if (!pure_function (expr, &name) && name)
2969     {
2970       if (forall_flag)
2971         {
2972           gfc_error ("Reference to non-PURE function '%s' at %L inside a "
2973                      "FORALL %s", name, &expr->where,
2974                      forall_flag == 2 ? "mask" : "block");
2975           t = false;
2976         }
2977       else if (do_concurrent_flag)
2978         {
2979           gfc_error ("Reference to non-PURE function '%s' at %L inside a "
2980                      "DO CONCURRENT %s", name, &expr->where,
2981                      do_concurrent_flag == 2 ? "mask" : "block");
2982           t = false;
2983         }
2984       else if (gfc_pure (NULL))
2985         {
2986           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
2987                      "procedure within a PURE procedure", name, &expr->where);
2988           t = false;
2989         }
2990
2991       if (gfc_implicit_pure (NULL))
2992         gfc_current_ns->proc_name->attr.implicit_pure = 0;
2993     }
2994
2995   /* Functions without the RECURSIVE attribution are not allowed to
2996    * call themselves.  */
2997   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
2998     {
2999       gfc_symbol *esym;
3000       esym = expr->value.function.esym;
3001
3002       if (is_illegal_recursion (esym, gfc_current_ns))
3003       {
3004         if (esym->attr.entry && esym->ns->entries)
3005           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3006                      " function '%s' is not RECURSIVE",
3007                      esym->name, &expr->where, esym->ns->entries->sym->name);
3008         else
3009           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
3010                      " is not RECURSIVE", esym->name, &expr->where);
3011
3012         t = false;
3013       }
3014     }
3015
3016   /* Character lengths of use associated functions may contains references to
3017      symbols not referenced from the current program unit otherwise.  Make sure
3018      those symbols are marked as referenced.  */
3019
3020   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
3021       && expr->value.function.esym->attr.use_assoc)
3022     {
3023       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
3024     }
3025
3026   /* Make sure that the expression has a typespec that works.  */
3027   if (expr->ts.type == BT_UNKNOWN)
3028     {
3029       if (expr->symtree->n.sym->result
3030             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
3031             && !expr->symtree->n.sym->result->attr.proc_pointer)
3032         expr->ts = expr->symtree->n.sym->result->ts;
3033     }
3034
3035   return t;
3036 }
3037
3038
3039 /************* Subroutine resolution *************/
3040
3041 static void
3042 pure_subroutine (gfc_code *c, gfc_symbol *sym)
3043 {
3044   if (gfc_pure (sym))
3045     return;
3046
3047   if (forall_flag)
3048     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
3049                sym->name, &c->loc);
3050   else if (do_concurrent_flag)
3051     gfc_error ("Subroutine call to '%s' in DO CONCURRENT block at %L is not "
3052                "PURE", sym->name, &c->loc);
3053   else if (gfc_pure (NULL))
3054     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
3055                &c->loc);
3056
3057   if (gfc_implicit_pure (NULL))
3058     gfc_current_ns->proc_name->attr.implicit_pure = 0;
3059 }
3060
3061
3062 static match
3063 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
3064 {
3065   gfc_symbol *s;
3066
3067   if (sym->attr.generic)
3068     {
3069       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
3070       if (s != NULL)
3071         {
3072           c->resolved_sym = s;
3073           pure_subroutine (c, s);
3074           return MATCH_YES;
3075         }
3076
3077       /* TODO: Need to search for elemental references in generic interface.  */
3078     }
3079
3080   if (sym->attr.intrinsic)
3081     return gfc_intrinsic_sub_interface (c, 0);
3082
3083   return MATCH_NO;
3084 }
3085
3086
3087 static bool
3088 resolve_generic_s (gfc_code *c)
3089 {
3090   gfc_symbol *sym;
3091   match m;
3092
3093   sym = c->symtree->n.sym;
3094
3095   for (;;)
3096     {
3097       m = resolve_generic_s0 (c, sym);
3098       if (m == MATCH_YES)
3099         return true;
3100       else if (m == MATCH_ERROR)
3101         return false;
3102
3103 generic:
3104       if (sym->ns->parent == NULL)
3105         break;
3106       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3107
3108       if (sym == NULL)
3109         break;
3110       if (!generic_sym (sym))
3111         goto generic;
3112     }
3113
3114   /* Last ditch attempt.  See if the reference is to an intrinsic
3115      that possesses a matching interface.  14.1.2.4  */
3116   sym = c->symtree->n.sym;
3117
3118   if (!gfc_is_intrinsic (sym, 1, c->loc))
3119     {
3120       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
3121                  sym->name, &c->loc);
3122       return false;
3123     }
3124
3125   m = gfc_intrinsic_sub_interface (c, 0);
3126   if (m == MATCH_YES)
3127     return true;
3128   if (m == MATCH_NO)
3129     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
3130                "intrinsic subroutine interface", sym->name, &c->loc);
3131
3132   return false;
3133 }
3134
3135
3136 /* Resolve a subroutine call known to be specific.  */
3137
3138 static match
3139 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3140 {
3141   match m;
3142
3143   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3144     {
3145       if (sym->attr.dummy)
3146         {
3147           sym->attr.proc = PROC_DUMMY;
3148           goto found;
3149         }
3150
3151       sym->attr.proc = PROC_EXTERNAL;
3152       goto found;
3153     }
3154
3155   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3156     goto found;
3157
3158   if (sym->attr.intrinsic)
3159     {
3160       m = gfc_intrinsic_sub_interface (c, 1);
3161       if (m == MATCH_YES)
3162         return MATCH_YES;
3163       if (m == MATCH_NO)
3164         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3165                    "with an intrinsic", sym->name, &c->loc);
3166
3167       return MATCH_ERROR;
3168     }
3169
3170   return MATCH_NO;
3171
3172 found:
3173   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3174
3175   c->resolved_sym = sym;
3176   pure_subroutine (c, sym);
3177
3178   return MATCH_YES;
3179 }
3180
3181
3182 static bool
3183 resolve_specific_s (gfc_code *c)
3184 {
3185   gfc_symbol *sym;
3186   match m;
3187
3188   sym = c->symtree->n.sym;
3189
3190   for (;;)
3191     {
3192       m = resolve_specific_s0 (c, sym);
3193       if (m == MATCH_YES)
3194         return true;
3195       if (m == MATCH_ERROR)
3196         return false;
3197
3198       if (sym->ns->parent == NULL)
3199         break;
3200
3201       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3202
3203       if (sym == NULL)
3204         break;
3205     }
3206
3207   sym = c->symtree->n.sym;
3208   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3209              sym->name, &c->loc);
3210
3211   return false;
3212 }
3213
3214
3215 /* Resolve a subroutine call not known to be generic nor specific.  */
3216
3217 static bool
3218 resolve_unknown_s (gfc_code *c)
3219 {
3220   gfc_symbol *sym;
3221
3222   sym = c->symtree->n.sym;
3223
3224   if (sym->attr.dummy)
3225     {
3226       sym->attr.proc = PROC_DUMMY;
3227       goto found;
3228     }
3229
3230   /* See if we have an intrinsic function reference.  */
3231
3232   if (gfc_is_intrinsic (sym, 1, c->loc))
3233     {
3234       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3235         return true;
3236       return false;
3237     }
3238
3239   /* The reference is to an external name.  */
3240
3241 found:
3242   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3243
3244   c->resolved_sym = sym;
3245
3246   pure_subroutine (c, sym);
3247
3248   return true;
3249 }
3250
3251
3252 /* Resolve a subroutine call.  Although it was tempting to use the same code
3253    for functions, subroutines and functions are stored differently and this
3254    makes things awkward.  */
3255
3256 static bool
3257 resolve_call (gfc_code *c)
3258 {
3259   bool t;
3260   procedure_type ptype = PROC_INTRINSIC;
3261   gfc_symbol *csym, *sym;
3262   bool no_formal_args;
3263
3264   csym = c->symtree ? c->symtree->n.sym : NULL;
3265
3266   if (csym && csym->ts.type != BT_UNKNOWN)
3267     {
3268       gfc_error ("'%s' at %L has a type, which is not consistent with "
3269                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3270       return false;
3271     }
3272
3273   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3274     {
3275       gfc_symtree *st;
3276       gfc_find_sym_tree (c->symtree->name, gfc_current_ns, 1, &st);
3277       sym = st ? st->n.sym : NULL;
3278       if (sym && csym != sym
3279               && sym->ns == gfc_current_ns
3280               && sym->attr.flavor == FL_PROCEDURE
3281               && sym->attr.contained)
3282         {
3283           sym->refs++;
3284           if (csym->attr.generic)
3285             c->symtree->n.sym = sym;
3286           else
3287             c->symtree = st;
3288           csym = c->symtree->n.sym;
3289         }
3290     }
3291
3292   /* If this ia a deferred TBP, c->expr1 will be set.  */
3293   if (!c->expr1 && csym)
3294     {
3295       if (csym->attr.abstract)
3296         {
3297           gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3298                     csym->name, &c->loc);
3299           return false;
3300         }
3301
3302       /* Subroutines without the RECURSIVE attribution are not allowed to
3303          call themselves.  */
3304       if (is_illegal_recursion (csym, gfc_current_ns))
3305         {
3306           if (csym->attr.entry && csym->ns->entries)
3307             gfc_error ("ENTRY '%s' at %L cannot be called recursively, "
3308                        "as subroutine '%s' is not RECURSIVE",
3309                        csym->name, &c->loc, csym->ns->entries->sym->name);
3310           else
3311             gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, "
3312                        "as it is not RECURSIVE", csym->name, &c->loc);
3313
3314           t = false;
3315         }
3316     }
3317
3318   /* Switch off assumed size checking and do this again for certain kinds
3319      of procedure, once the procedure itself is resolved.  */
3320   need_full_assumed_size++;
3321
3322   if (csym)
3323     ptype = csym->attr.proc;
3324
3325   no_formal_args = csym && is_external_proc (csym)
3326                         && gfc_sym_get_dummy_args (csym) == NULL;
3327   if (!resolve_actual_arglist (c->ext.actual, ptype, no_formal_args))
3328     return false;
3329
3330   /* Resume assumed_size checking.  */
3331   need_full_assumed_size--;
3332
3333   /* If external, check for usage.  */
3334   if (csym && is_external_proc (csym))
3335     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3336
3337   t = true;
3338   if (c->resolved_sym == NULL)
3339     {
3340       c->resolved_isym = NULL;
3341       switch (procedure_kind (csym))
3342         {
3343         case PTYPE_GENERIC:
3344           t = resolve_generic_s (c);
3345           break;
3346
3347         case PTYPE_SPECIFIC:
3348           t = resolve_specific_s (c);
3349           break;
3350
3351         case PTYPE_UNKNOWN:
3352           t = resolve_unknown_s (c);
3353           break;
3354
3355         default:
3356           gfc_internal_error ("resolve_subroutine(): bad function type");
3357         }
3358     }
3359
3360   /* Some checks of elemental subroutine actual arguments.  */
3361   if (!resolve_elemental_actual (NULL, c))
3362     return false;
3363
3364   return t;
3365 }
3366
3367
3368 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3369    op1->shape and op2->shape are non-NULL return true if their shapes
3370    match.  If both op1->shape and op2->shape are non-NULL return false
3371    if their shapes do not match.  If either op1->shape or op2->shape is
3372    NULL, return true.  */
3373
3374 static bool
3375 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3376 {
3377   bool t;
3378   int i;
3379
3380   t = true;
3381
3382   if (op1->shape != NULL && op2->shape != NULL)
3383     {
3384       for (i = 0; i < op1->rank; i++)
3385         {
3386           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3387            {
3388              gfc_error ("Shapes for operands at %L and %L are not conformable",
3389                          &op1->where, &op2->where);
3390              t = false;
3391              break;
3392            }
3393         }
3394     }
3395
3396   return t;
3397 }
3398
3399
3400 /* Resolve an operator expression node.  This can involve replacing the
3401    operation with a user defined function call.  */
3402
3403 static bool
3404 resolve_operator (gfc_expr *e)
3405 {
3406   gfc_expr *op1, *op2;
3407   char msg[200];
3408   bool dual_locus_error;
3409   bool t;
3410
3411   /* Resolve all subnodes-- give them types.  */
3412
3413   switch (e->value.op.op)
3414     {
3415     default:
3416       if (!gfc_resolve_expr (e->value.op.op2))
3417         return false;
3418
3419     /* Fall through...  */
3420
3421     case INTRINSIC_NOT:
3422     case INTRINSIC_UPLUS:
3423     case INTRINSIC_UMINUS:
3424     case INTRINSIC_PARENTHESES:
3425       if (!gfc_resolve_expr (e->value.op.op1))
3426         return false;
3427       break;
3428     }
3429
3430   /* Typecheck the new node.  */
3431
3432   op1 = e->value.op.op1;
3433   op2 = e->value.op.op2;
3434   dual_locus_error = false;
3435
3436   if ((op1 && op1->expr_type == EXPR_NULL)
3437       || (op2 && op2->expr_type == EXPR_NULL))
3438     {
3439       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3440       goto bad_op;
3441     }
3442
3443   switch (e->value.op.op)
3444     {
3445     case INTRINSIC_UPLUS:
3446     case INTRINSIC_UMINUS:
3447       if (op1->ts.type == BT_INTEGER
3448           || op1->ts.type == BT_REAL
3449           || op1->ts.type == BT_COMPLEX)
3450         {
3451           e->ts = op1->ts;
3452           break;
3453         }
3454
3455       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3456                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3457       goto bad_op;
3458
3459     case INTRINSIC_PLUS:
3460     case INTRINSIC_MINUS:
3461     case INTRINSIC_TIMES:
3462     case INTRINSIC_DIVIDE:
3463     case INTRINSIC_POWER:
3464       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3465         {
3466           gfc_type_convert_binary (e, 1);
3467           break;
3468         }
3469
3470       sprintf (msg,
3471                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3472                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3473                gfc_typename (&op2->ts));
3474       goto bad_op;
3475
3476     case INTRINSIC_CONCAT:
3477       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3478           && op1->ts.kind == op2->ts.kind)
3479         {
3480           e->ts.type = BT_CHARACTER;
3481           e->ts.kind = op1->ts.kind;
3482           break;
3483         }
3484
3485       sprintf (msg,
3486                _("Operands of string concatenation operator at %%L are %s/%s"),
3487                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3488       goto bad_op;
3489
3490     case INTRINSIC_AND:
3491     case INTRINSIC_OR:
3492     case INTRINSIC_EQV:
3493     case INTRINSIC_NEQV:
3494       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3495         {
3496           e->ts.type = BT_LOGICAL;
3497           e->ts.kind = gfc_kind_max (op1, op2);
3498           if (op1->ts.kind < e->ts.kind)
3499             gfc_convert_type (op1, &e->ts, 2);
3500           else if (op2->ts.kind < e->ts.kind)
3501             gfc_convert_type (op2, &e->ts, 2);
3502           break;
3503         }
3504
3505       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3506                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3507                gfc_typename (&op2->ts));
3508
3509       goto bad_op;
3510
3511     case INTRINSIC_NOT:
3512       if (op1->ts.type == BT_LOGICAL)
3513         {
3514           e->ts.type = BT_LOGICAL;
3515           e->ts.kind = op1->ts.kind;
3516           break;
3517         }
3518
3519       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3520                gfc_typename (&op1->ts));
3521       goto bad_op;
3522
3523     case INTRINSIC_GT:
3524     case INTRINSIC_GT_OS:
3525     case INTRINSIC_GE:
3526     case INTRINSIC_GE_OS:
3527     case INTRINSIC_LT:
3528     case INTRINSIC_LT_OS:
3529     case INTRINSIC_LE:
3530     case INTRINSIC_LE_OS:
3531       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3532         {
3533           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3534           goto bad_op;
3535         }
3536
3537       /* Fall through...  */
3538
3539     case INTRINSIC_EQ:
3540     case INTRINSIC_EQ_OS:
3541     case INTRINSIC_NE:
3542     case INTRINSIC_NE_OS:
3543       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3544           && op1->ts.kind == op2->ts.kind)
3545         {
3546           e->ts.type = BT_LOGICAL;
3547           e->ts.kind = gfc_default_logical_kind;
3548           break;
3549         }
3550
3551       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3552         {
3553           gfc_type_convert_binary (e, 1);
3554
3555           e->ts.type = BT_LOGICAL;
3556           e->ts.kind = gfc_default_logical_kind;
3557
3558           if (gfc_option.warn_compare_reals)
3559             {
3560               gfc_intrinsic_op op = e->value.op.op;
3561
3562               /* Type conversion has made sure that the types of op1 and op2
3563                  agree, so it is only necessary to check the first one.   */
3564               if ((op1->ts.type == BT_REAL || op1->ts.type == BT_COMPLEX)
3565                   && (op == INTRINSIC_EQ || op == INTRINSIC_EQ_OS
3566                       || op == INTRINSIC_NE || op == INTRINSIC_NE_OS))
3567                 {
3568                   const char *msg;
3569
3570                   if (op == INTRINSIC_EQ || op == INTRINSIC_EQ_OS)
3571                     msg = "Equality comparison for %s at %L";
3572                   else
3573                     msg = "Inequality comparison for %s at %L";
3574
3575                   gfc_warning (msg, gfc_typename (&op1->ts), &op1->where);
3576                 }
3577             }
3578
3579           break;
3580         }
3581
3582       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3583         sprintf (msg,
3584                  _("Logicals at %%L must be compared with %s instead of %s"),
3585                  (e->value.op.op == INTRINSIC_EQ
3586                   || e->value.op.op == INTRINSIC_EQ_OS)
3587                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3588       else
3589         sprintf (msg,
3590                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3591                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3592                  gfc_typename (&op2->ts));
3593
3594       goto bad_op;
3595
3596     case INTRINSIC_USER:
3597       if (e->value.op.uop->op == NULL)
3598         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3599       else if (op2 == NULL)
3600         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3601                  e->value.op.uop->name, gfc_typename (&op1->ts));
3602       else
3603         {
3604           sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3605                    e->value.op.uop->name, gfc_typename (&op1->ts),
3606                    gfc_typename (&op2->ts));
3607           e->value.op.uop->op->sym->attr.referenced = 1;
3608         }
3609
3610       goto bad_op;
3611
3612     case INTRINSIC_PARENTHESES:
3613       e->ts = op1->ts;
3614       if (e->ts.type == BT_CHARACTER)
3615         e->ts.u.cl = op1->ts.u.cl;
3616       break;
3617
3618     default:
3619       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3620     }
3621
3622   /* Deal with arrayness of an operand through an operator.  */
3623
3624   t = true;
3625
3626   switch (e->value.op.op)
3627     {
3628     case INTRINSIC_PLUS:
3629     case INTRINSIC_MINUS:
3630     case INTRINSIC_TIMES:
3631     case INTRINSIC_DIVIDE:
3632     case INTRINSIC_POWER:
3633     case INTRINSIC_CONCAT:
3634     case INTRINSIC_AND:
3635     case INTRINSIC_OR:
3636     case INTRINSIC_EQV:
3637     case INTRINSIC_NEQV:
3638     case INTRINSIC_EQ:
3639     case INTRINSIC_EQ_OS:
3640     case INTRINSIC_NE:
3641     case INTRINSIC_NE_OS:
3642     case INTRINSIC_GT:
3643     case INTRINSIC_GT_OS:
3644     case INTRINSIC_GE:
3645     case INTRINSIC_GE_OS:
3646     case INTRINSIC_LT:
3647     case INTRINSIC_LT_OS:
3648     case INTRINSIC_LE:
3649     case INTRINSIC_LE_OS:
3650
3651       if (op1->rank == 0 && op2->rank == 0)
3652         e->rank = 0;
3653
3654       if (op1->rank == 0 && op2->rank != 0)
3655         {
3656           e->rank = op2->rank;
3657
3658           if (e->shape == NULL)
3659             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3660         }
3661
3662       if (op1->rank != 0 && op2->rank == 0)
3663         {
3664           e->rank = op1->rank;
3665
3666           if (e->shape == NULL)
3667             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3668         }
3669
3670       if (op1->rank != 0 && op2->rank != 0)
3671         {
3672           if (op1->rank == op2->rank)
3673             {
3674               e->rank = op1->rank;
3675               if (e->shape == NULL)
3676                 {
3677                   t = compare_shapes (op1, op2);
3678                   if (!t)
3679                     e->shape = NULL;
3680                   else
3681                     e->shape = gfc_copy_shape (op1->shape, op1->rank);
3682                 }
3683             }
3684           else
3685             {
3686               /* Allow higher level expressions to work.  */
3687               e->rank = 0;
3688
3689               /* Try user-defined operators, and otherwise throw an error.  */
3690               dual_locus_error = true;
3691               sprintf (msg,
3692                        _("Inconsistent ranks for operator at %%L and %%L"));
3693               goto bad_op;
3694             }
3695         }
3696
3697       break;
3698
3699     case INTRINSIC_PARENTHESES:
3700     case INTRINSIC_NOT:
3701     case INTRINSIC_UPLUS:
3702     case INTRINSIC_UMINUS:
3703       /* Simply copy arrayness attribute */
3704       e->rank = op1->rank;
3705
3706       if (e->shape == NULL)
3707         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3708
3709       break;
3710
3711     default:
3712       break;
3713     }
3714
3715   /* Attempt to simplify the expression.  */
3716   if (t)
3717     {
3718       t = gfc_simplify_expr (e, 0);
3719       /* Some calls do not succeed in simplification and return false
3720          even though there is no error; e.g. variable references to
3721          PARAMETER arrays.  */
3722       if (!gfc_is_constant_expr (e))
3723         t = true;
3724     }
3725   return t;
3726
3727 bad_op:
3728
3729   {
3730     match m = gfc_extend_expr (e);
3731     if (m == MATCH_YES)
3732       return true;
3733     if (m == MATCH_ERROR)
3734       return false;
3735   }
3736
3737   if (dual_locus_error)
3738     gfc_error (msg, &op1->where, &op2->where);
3739   else
3740     gfc_error (msg, &e->where);
3741
3742   return false;
3743 }
3744
3745
3746 /************** Array resolution subroutines **************/
3747
3748 typedef enum
3749 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
3750 comparison;
3751
3752 /* Compare two integer expressions.  */
3753
3754 static comparison
3755 compare_bound (gfc_expr *a, gfc_expr *b)
3756 {
3757   int i;
3758
3759   if (a == NULL || a->expr_type != EXPR_CONSTANT
3760       || b == NULL || b->expr_type != EXPR_CONSTANT)
3761     return CMP_UNKNOWN;
3762
3763   /* If either of the types isn't INTEGER, we must have
3764      raised an error earlier.  */
3765
3766   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
3767     return CMP_UNKNOWN;
3768
3769   i = mpz_cmp (a->value.integer, b->value.integer);
3770
3771   if (i < 0)
3772     return CMP_LT;
3773   if (i > 0)
3774     return CMP_GT;
3775   return CMP_EQ;
3776 }
3777
3778
3779 /* Compare an integer expression with an integer.  */
3780
3781 static comparison
3782 compare_bound_int (gfc_expr *a, int b)
3783 {
3784   int i;
3785
3786   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3787     return CMP_UNKNOWN;
3788
3789   if (a->ts.type != BT_INTEGER)
3790     gfc_internal_error ("compare_bound_int(): Bad expression");
3791
3792   i = mpz_cmp_si (a->value.integer, b);
3793
3794   if (i < 0)
3795     return CMP_LT;
3796   if (i > 0)
3797     return CMP_GT;
3798   return CMP_EQ;
3799 }
3800
3801
3802 /* Compare an integer expression with a mpz_t.  */
3803
3804 static comparison
3805 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
3806 {
3807   int i;
3808
3809   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3810     return CMP_UNKNOWN;
3811
3812   if (a->ts.type != BT_INTEGER)
3813     gfc_internal_error ("compare_bound_int(): Bad expression");
3814
3815   i = mpz_cmp (a->value.integer, b);
3816
3817   if (i < 0)
3818     return CMP_LT;
3819   if (i > 0)
3820     return CMP_GT;
3821   return CMP_EQ;
3822 }
3823
3824
3825 /* Compute the last value of a sequence given by a triplet.
3826    Return 0 if it wasn't able to compute the last value, or if the
3827    sequence if empty, and 1 otherwise.  */
3828
3829 static int
3830 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
3831                                 gfc_expr *stride, mpz_t last)
3832 {
3833   mpz_t rem;
3834
3835   if (start == NULL || start->expr_type != EXPR_CONSTANT
3836       || end == NULL || end->expr_type != EXPR_CONSTANT
3837       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
3838     return 0;
3839
3840   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
3841       || (stride != NULL && stride->ts.type != BT_INTEGER))
3842     return 0;
3843
3844   if (stride == NULL || compare_bound_int (stride, 1) == CMP_EQ)
3845     {
3846       if (compare_bound (start, end) == CMP_GT)
3847         return 0;
3848       mpz_set (last, end->value.integer);
3849       return 1;
3850     }
3851
3852   if (compare_bound_int (stride, 0) == CMP_GT)
3853     {
3854       /* Stride is positive */
3855       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
3856         return 0;
3857     }
3858   else
3859     {
3860       /* Stride is negative */
3861       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
3862         return 0;
3863     }
3864
3865   mpz_init (rem);
3866   mpz_sub (rem, end->value.integer, start->value.integer);
3867   mpz_tdiv_r (rem, rem, stride->value.integer);
3868   mpz_sub (last, end->value.integer, rem);
3869   mpz_clear (rem);
3870
3871   return 1;
3872 }
3873
3874
3875 /* Compare a single dimension of an array reference to the array
3876    specification.  */
3877
3878 static bool
3879 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
3880 {
3881   mpz_t last_value;
3882
3883   if (ar->dimen_type[i] == DIMEN_STAR)
3884     {
3885       gcc_assert (ar->stride[i] == NULL);
3886       /* This implies [*] as [*:] and [*:3] are not possible.  */
3887       if (ar->start[i] == NULL)
3888         {
3889           gcc_assert (ar->end[i] == NULL);
3890           return true;
3891         }
3892     }
3893
3894 /* Given start, end and stride values, calculate the minimum and
3895    maximum referenced indexes.  */
3896
3897   switch (ar->dimen_type[i])
3898     {
3899     case DIMEN_VECTOR:
3900     case DIMEN_THIS_IMAGE:
3901       break;
3902
3903     case DIMEN_STAR:
3904     case DIMEN_ELEMENT:
3905       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
3906         {
3907           if (i < as->rank)
3908             gfc_warning ("Array reference at %L is out of bounds "
3909                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
3910                          mpz_get_si (ar->start[i]->value.integer),
3911                          mpz_get_si (as->lower[i]->value.integer), i+1);
3912           else
3913             gfc_warning ("Array reference at %L is out of bounds "
3914                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
3915                          mpz_get_si (ar->start[i]->value.integer),
3916                          mpz_get_si (as->lower[i]->value.integer),
3917                          i + 1 - as->rank);
3918           return true;
3919         }
3920       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
3921         {
3922           if (i < as->rank)
3923             gfc_warning ("Array reference at %L is out of bounds "
3924                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
3925                          mpz_get_si (ar->start[i]->value.integer),
3926                          mpz_get_si (as->upper[i]->value.integer), i+1);
3927           else
3928             gfc_warning ("Array reference at %L is out of bounds "
3929                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
3930                          mpz_get_si (ar->start[i]->value.integer),
3931                          mpz_get_si (as->upper[i]->value.integer),
3932                          i + 1 - as->rank);
3933           return true;
3934         }
3935
3936       break;
3937
3938     case DIMEN_RANGE:
3939       {
3940 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
3941 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
3942
3943         comparison comp_start_end = compare_bound (AR_START, AR_END);
3944
3945         /* Check for zero stride, which is not allowed.  */
3946         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
3947           {
3948             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
3949             return false;
3950           }
3951
3952         /* if start == len || (stride > 0 && start < len)
3953                            || (stride < 0 && start > len),
3954            then the array section contains at least one element.  In this
3955            case, there is an out-of-bounds access if
3956            (start < lower || start > upper).  */
3957         if (compare_bound (AR_START, AR_END) == CMP_EQ
3958             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
3959                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
3960             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
3961                 && comp_start_end == CMP_GT))
3962           {
3963             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
3964               {
3965                 gfc_warning ("Lower array reference at %L is out of bounds "
3966                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3967                        mpz_get_si (AR_START->value.integer),
3968                        mpz_get_si (as->lower[i]->value.integer), i+1);
3969                 return true;
3970               }
3971             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
3972               {
3973                 gfc_warning ("Lower array reference at %L is out of bounds "
3974                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3975                        mpz_get_si (AR_START->value.integer),
3976                        mpz_get_si (as->upper[i]->value.integer), i+1);
3977                 return true;
3978               }
3979           }
3980
3981         /* If we can compute the highest index of the array section,
3982            then it also has to be between lower and upper.  */
3983         mpz_init (last_value);
3984         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
3985                                             last_value))
3986           {
3987             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
3988               {
3989                 gfc_warning ("Upper array reference at %L is out of bounds "
3990                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3991                        mpz_get_si (last_value),
3992                        mpz_get_si (as->lower[i]->value.integer), i+1);
3993                 mpz_clear (last_value);
3994                 return true;
3995               }
3996             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
3997               {
3998                 gfc_warning ("Upper array reference at %L is out of bounds "
3999                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4000                        mpz_get_si (last_value),
4001                        mpz_get_si (as->upper[i]->value.integer), i+1);
4002                 mpz_clear (last_value);
4003                 return true;
4004               }
4005           }
4006         mpz_clear (last_value);
4007
4008 #undef AR_START
4009 #undef AR_END
4010       }
4011       break;
4012
4013     default:
4014       gfc_internal_error ("check_dimension(): Bad array reference");
4015     }
4016
4017   return true;
4018 }
4019
4020
4021 /* Compare an array reference with an array specification.  */
4022
4023 static bool
4024 compare_spec_to_ref (gfc_array_ref *ar)
4025 {
4026   gfc_array_spec *as;
4027   int i;
4028
4029   as = ar->as;
4030   i = as->rank - 1;
4031   /* TODO: Full array sections are only allowed as actual parameters.  */
4032   if (as->type == AS_ASSUMED_SIZE
4033       && (/*ar->type == AR_FULL
4034           ||*/ (ar->type == AR_SECTION
4035               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
4036     {
4037       gfc_error ("Rightmost upper bound of assumed size array section "
4038                  "not specified at %L", &ar->where);
4039       return false;
4040     }
4041
4042   if (ar->type == AR_FULL)
4043     return true;
4044
4045   if (as->rank != ar->dimen)
4046     {
4047       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
4048                  &ar->where, ar->dimen, as->rank);
4049       return false;
4050     }
4051
4052   /* ar->codimen == 0 is a local array.  */
4053   if (as->corank != ar->codimen && ar->codimen != 0)
4054     {
4055       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
4056                  &ar->where, ar->codimen, as->corank);
4057       return false;
4058     }
4059
4060   for (i = 0; i < as->rank; i++)
4061     if (!check_dimension (i, ar, as))
4062       return false;
4063
4064   /* Local access has no coarray spec.  */
4065   if (ar->codimen != 0)
4066     for (i = as->rank; i < as->rank + as->corank; i++)
4067       {
4068         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate
4069             && ar->dimen_type[i] != DIMEN_THIS_IMAGE)
4070           {
4071             gfc_error ("Coindex of codimension %d must be a scalar at %L",
4072                        i + 1 - as->rank, &ar->where);
4073             return false;
4074           }
4075         if (!check_dimension (i, ar, as))
4076           return false;
4077       }
4078
4079   return true;
4080 }
4081
4082
4083 /* Resolve one part of an array index.  */
4084
4085 static bool
4086 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
4087                      int force_index_integer_kind)
4088 {
4089   gfc_typespec ts;
4090
4091   if (index == NULL)
4092     return true;
4093
4094   if (!gfc_resolve_expr (index))
4095     return false;
4096
4097   if (check_scalar && index->rank != 0)
4098     {
4099       gfc_error ("Array index at %L must be scalar", &index->where);
4100       return false;
4101     }
4102
4103   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4104     {
4105       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4106                  &index->where, gfc_basic_typename (index->ts.type));
4107       return false;
4108     }
4109
4110   if (index->ts.type == BT_REAL)
4111     if (!gfc_notify_std (GFC_STD_LEGACY, "REAL array index at %L", 
4112                          &index->where))
4113       return false;
4114
4115   if ((index->ts.kind != gfc_index_integer_kind
4116        && force_index_integer_kind)
4117       || index->ts.type != BT_INTEGER)
4118     {
4119       gfc_clear_ts (&ts);
4120       ts.type = BT_INTEGER;
4121       ts.kind = gfc_index_integer_kind;
4122
4123       gfc_convert_type_warn (index, &ts, 2, 0);
4124     }
4125
4126   return true;
4127 }
4128
4129 /* Resolve one part of an array index.  */
4130
4131 bool
4132 gfc_resolve_index (gfc_expr *index, int check_scalar)
4133 {
4134   return gfc_resolve_index_1 (index, check_scalar, 1);
4135 }
4136
4137 /* Resolve a dim argument to an intrinsic function.  */
4138
4139 bool
4140 gfc_resolve_dim_arg (gfc_expr *dim)
4141 {
4142   if (dim == NULL)
4143     return true;
4144
4145   if (!gfc_resolve_expr (dim))
4146     return false;
4147
4148   if (dim->rank != 0)
4149     {
4150       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4151       return false;
4152
4153     }
4154
4155   if (dim->ts.type != BT_INTEGER)
4156     {
4157       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4158       return false;
4159     }
4160
4161   if (dim->ts.kind != gfc_index_integer_kind)
4162     {
4163       gfc_typespec ts;
4164
4165       gfc_clear_ts (&ts);
4166       ts.type = BT_INTEGER;
4167       ts.kind = gfc_index_integer_kind;
4168
4169       gfc_convert_type_warn (dim, &ts, 2, 0);
4170     }
4171
4172   return true;
4173 }
4174
4175 /* Given an expression that contains array references, update those array
4176    references to point to the right array specifications.  While this is
4177    filled in during matching, this information is difficult to save and load
4178    in a module, so we take care of it here.
4179
4180    The idea here is that the original array reference comes from the
4181    base symbol.  We traverse the list of reference structures, setting
4182    the stored reference to references.  Component references can
4183    provide an additional array specification.  */
4184
4185 static void
4186 find_array_spec (gfc_expr *e)
4187 {
4188   gfc_array_spec *as;
4189   gfc_component *c;
4190   gfc_ref *ref;
4191
4192   if (e->symtree->n.sym->ts.type == BT_CLASS)
4193     as = CLASS_DATA (e->symtree->n.sym)->as;
4194   else
4195     as = e->symtree->n.sym->as;
4196
4197   for (ref = e->ref; ref; ref = ref->next)
4198     switch (ref->type)
4199       {
4200       case REF_ARRAY:
4201         if (as == NULL)
4202           gfc_internal_error ("find_array_spec(): Missing spec");
4203
4204         ref->u.ar.as = as;
4205         as = NULL;
4206         break;
4207
4208       case REF_COMPONENT:
4209         c = ref->u.c.component;
4210         if (c->attr.dimension)
4211           {
4212             if (as != NULL)
4213               gfc_internal_error ("find_array_spec(): unused as(1)");
4214             as = c->as;
4215           }
4216
4217         break;
4218
4219       case REF_SUBSTRING:
4220         break;
4221       }
4222
4223   if (as != NULL)
4224     gfc_internal_error ("find_array_spec(): unused as(2)");
4225 }
4226
4227
4228 /* Resolve an array reference.  */
4229
4230 static bool
4231 resolve_array_ref (gfc_array_ref *ar)
4232 {
4233   int i, check_scalar;
4234   gfc_expr *e;
4235
4236   for (i = 0; i < ar->dimen + ar->codimen; i++)
4237     {
4238       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4239
4240       /* Do not force gfc_index_integer_kind for the start.  We can
4241          do fine with any integer kind.  This avoids temporary arrays
4242          created for indexing with a vector.  */
4243       if (!gfc_resolve_index_1 (ar->start[i], check_scalar, 0))
4244         return false;
4245       if (!gfc_resolve_index (ar->end[i], check_scalar))
4246         return false;
4247       if (!gfc_resolve_index (ar->stride[i], check_scalar))
4248         return false;
4249
4250       e = ar->start[i];
4251
4252       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4253         switch (e->rank)
4254           {
4255           case 0:
4256             ar->dimen_type[i] = DIMEN_ELEMENT;
4257             break;
4258
4259           case 1:
4260             ar->dimen_type[i] = DIMEN_VECTOR;
4261             if (e->expr_type == EXPR_VARIABLE
4262                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4263               ar->start[i] = gfc_get_parentheses (e);
4264             break;
4265
4266           default:
4267             gfc_error ("Array index at %L is an array of rank %d",
4268                        &ar->c_where[i], e->rank);
4269             return false;
4270           }
4271
4272       /* Fill in the upper bound, which may be lower than the
4273          specified one for something like a(2:10:5), which is
4274          identical to a(2:7:5).  Only relevant for strides not equal
4275          to one.  Don't try a division by zero.  */
4276       if (ar->dimen_type[i] == DIMEN_RANGE
4277           && ar->stride[i] != NULL && ar->stride[i]->expr_type == EXPR_CONSTANT
4278           && mpz_cmp_si (ar->stride[i]->value.integer, 1L) != 0
4279           && mpz_cmp_si (ar->stride[i]->value.integer, 0L) != 0)
4280         {
4281           mpz_t size, end;
4282
4283           if (gfc_ref_dimen_size (ar, i, &size, &end))
4284             {
4285               if (ar->end[i] == NULL)
4286                 {
4287                   ar->end[i] =
4288                     gfc_get_constant_expr (BT_INTEGER, gfc_index_integer_kind,
4289                                            &ar->where);
4290                   mpz_set (ar->end[i]->value.integer, end);
4291                 }
4292               else if (ar->end[i]->ts.type == BT_INTEGER
4293                        && ar->end[i]->expr_type == EXPR_CONSTANT)
4294                 {
4295                   mpz_set (ar->end[i]->value.integer, end);
4296                 }
4297               else
4298                 gcc_unreachable ();
4299
4300               mpz_clear (size);
4301               mpz_clear (end);
4302             }
4303         }
4304     }
4305
4306   if (ar->type == AR_FULL)
4307     {
4308       if (ar->as->rank == 0)
4309         ar->type = AR_ELEMENT;
4310
4311       /* Make sure array is the same as array(:,:), this way
4312          we don't need to special case all the time.  */
4313       ar->dimen = ar->as->rank;
4314       for (i = 0; i < ar->dimen; i++)
4315         {
4316           ar->dimen_type[i] = DIMEN_RANGE;
4317
4318           gcc_assert (ar->start[i] == NULL);
4319           gcc_assert (ar->end[i] == NULL);
4320           gcc_assert (ar->stride[i] == NULL);
4321         }
4322     }
4323
4324   /* If the reference type is unknown, figure out what kind it is.  */
4325
4326   if (ar->type == AR_UNKNOWN)
4327     {
4328       ar->type = AR_ELEMENT;
4329       for (i = 0; i < ar->dimen; i++)
4330         if (ar->dimen_type[i] == DIMEN_RANGE
4331             || ar->dimen_type[i] == DIMEN_VECTOR)
4332           {
4333             ar->type = AR_SECTION;
4334             break;
4335           }
4336     }
4337
4338   if (!ar->as->cray_pointee && !compare_spec_to_ref (ar))
4339     return false;
4340
4341   if (ar->as->corank && ar->codimen == 0)
4342     {
4343       int n;
4344       ar->codimen = ar->as->corank;
4345       for (n = ar->dimen; n < ar->dimen + ar->codimen; n++)
4346         ar->dimen_type[n] = DIMEN_THIS_IMAGE;
4347     }
4348
4349   return true;
4350 }
4351
4352
4353 static bool
4354 resolve_substring (gfc_ref *ref)
4355 {
4356   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4357
4358   if (ref->u.ss.start != NULL)
4359     {
4360       if (!gfc_resolve_expr (ref->u.ss.start))
4361         return false;
4362
4363       if (ref->u.ss.start->ts.type != BT_INTEGER)
4364         {
4365           gfc_error ("Substring start index at %L must be of type INTEGER",
4366                      &ref->u.ss.start->where);
4367           return false;
4368         }
4369
4370       if (ref->u.ss.start->rank != 0)
4371         {
4372           gfc_error ("Substring start index at %L must be scalar",
4373                      &ref->u.ss.start->where);
4374           return false;
4375         }
4376
4377       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4378           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4379               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4380         {
4381           gfc_error ("Substring start index at %L is less than one",
4382                      &ref->u.ss.start->where);
4383           return false;
4384         }
4385     }
4386
4387   if (ref->u.ss.end != NULL)
4388     {
4389       if (!gfc_resolve_expr (ref->u.ss.end))
4390         return false;
4391
4392       if (ref->u.ss.end->ts.type != BT_INTEGER)
4393         {
4394           gfc_error ("Substring end index at %L must be of type INTEGER",
4395                      &ref->u.ss.end->where);
4396           return false;
4397         }
4398
4399       if (ref->u.ss.end->rank != 0)
4400         {
4401           gfc_error ("Substring end index at %L must be scalar",
4402                      &ref->u.ss.end->where);
4403           return false;
4404         }
4405
4406       if (ref->u.ss.length != NULL
4407           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4408           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4409               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4410         {
4411           gfc_error ("Substring end index at %L exceeds the string length",
4412                      &ref->u.ss.start->where);
4413           return false;
4414         }
4415
4416       if (compare_bound_mpz_t (ref->u.ss.end,
4417                                gfc_integer_kinds[k].huge) == CMP_GT
4418           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4419               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4420         {
4421           gfc_error ("Substring end index at %L is too large",
4422                      &ref->u.ss.end->where);
4423           return false;
4424         }
4425     }
4426
4427   return true;
4428 }
4429
4430
4431 /* This function supplies missing substring charlens.  */
4432
4433 void
4434 gfc_resolve_substring_charlen (gfc_expr *e)
4435 {
4436   gfc_ref *char_ref;
4437   gfc_expr *start, *end;
4438
4439   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4440     if (char_ref->type == REF_SUBSTRING)
4441       break;
4442
4443   if (!char_ref)
4444     return;
4445
4446   gcc_assert (char_ref->next == NULL);
4447
4448   if (e->ts.u.cl)
4449     {
4450       if (e->ts.u.cl->length)
4451         gfc_free_expr (e->ts.u.cl->length);
4452       else if (e->expr_type == EXPR_VARIABLE
4453                  && e->symtree->n.sym->attr.dummy)
4454         return;
4455     }
4456
4457   e->ts.type = BT_CHARACTER;
4458   e->ts.kind = gfc_default_character_kind;
4459
4460   if (!e->ts.u.cl)
4461     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4462
4463   if (char_ref->u.ss.start)
4464     start = gfc_copy_expr (char_ref->u.ss.start);
4465   else
4466     start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
4467
4468   if (char_ref->u.ss.end)
4469     end = gfc_copy_expr (char_ref->u.ss.end);
4470   else if (e->expr_type == EXPR_VARIABLE)
4471     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4472   else
4473     end = NULL;
4474
4475   if (!start || !end)
4476     {
4477       gfc_free_expr (start);
4478       gfc_free_expr (end);
4479       return;
4480     }
4481
4482   /* Length = (end - start +1).  */
4483   e->ts.u.cl->length = gfc_subtract (end, start);
4484   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
4485                                 gfc_get_int_expr (gfc_default_integer_kind,
4486                                                   NULL, 1));
4487
4488   e->ts.u.cl->length->ts.type = BT_INTEGER;
4489   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4490
4491   /* Make sure that the length is simplified.  */
4492   gfc_simplify_expr (e->ts.u.cl->length, 1);
4493   gfc_resolve_expr (e->ts.u.cl->length);
4494 }
4495
4496
4497 /* Resolve subtype references.  */
4498
4499 static bool
4500 resolve_ref (gfc_expr *expr)
4501 {
4502   int current_part_dimension, n_components, seen_part_dimension;
4503   gfc_ref *ref;
4504
4505   for (ref = expr->ref; ref; ref = ref->next)
4506     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4507       {
4508         find_array_spec (expr);
4509         break;
4510       }
4511
4512   for (ref = expr->ref; ref; ref = ref->next)
4513     switch (ref->type)
4514       {
4515       case REF_ARRAY:
4516         if (!resolve_array_ref (&ref->u.ar))
4517           return false;
4518         break;
4519
4520       case REF_COMPONENT:
4521         break;
4522
4523       case REF_SUBSTRING:
4524         if (!resolve_substring (ref))
4525           return false;
4526         break;
4527       }
4528
4529   /* Check constraints on part references.  */
4530
4531   current_part_dimension = 0;
4532   seen_part_dimension = 0;
4533   n_components = 0;
4534
4535   for (ref = expr->ref; ref; ref = ref->next)
4536     {
4537       switch (ref->type)
4538         {
4539         case REF_ARRAY:
4540           switch (ref->u.ar.type)
4541             {
4542             case AR_FULL:
4543               /* Coarray scalar.  */
4544               if (ref->u.ar.as->rank == 0)
4545                 {
4546                   current_part_dimension = 0;
4547                   break;
4548                 }
4549               /* Fall through.  */
4550             case AR_SECTION:
4551               current_part_dimension = 1;
4552               break;
4553
4554             case AR_ELEMENT:
4555               current_part_dimension = 0;
4556               break;
4557
4558             case AR_UNKNOWN:
4559               gfc_internal_error ("resolve_ref(): Bad array reference");
4560             }
4561
4562           break;
4563
4564         case REF_COMPONENT:
4565           if (current_part_dimension || seen_part_dimension)
4566             {
4567               /* F03:C614.  */
4568               if (ref->u.c.component->attr.pointer
4569                   || ref->u.c.component->attr.proc_pointer
4570                   || (ref->u.c.component->ts.type == BT_CLASS
4571                         && CLASS_DATA (ref->u.c.component)->attr.pointer))
4572                 {
4573                   gfc_error ("Component to the right of a part reference "
4574                              "with nonzero rank must not have the POINTER "
4575                              "attribute at %L", &expr->where);
4576                   return false;
4577                 }
4578               else if (ref->u.c.component->attr.allocatable
4579                         || (ref->u.c.component->ts.type == BT_CLASS
4580                             && CLASS_DATA (ref->u.c.component)->attr.allocatable))
4581
4582                 {
4583                   gfc_error ("Component to the right of a part reference "
4584                              "with nonzero rank must not have the ALLOCATABLE "
4585                              "attribute at %L", &expr->where);
4586                   return false;
4587                 }
4588             }
4589
4590           n_components++;
4591           break;
4592
4593         case REF_SUBSTRING:
4594           break;
4595         }
4596
4597       if (((ref->type == REF_COMPONENT && n_components > 1)
4598            || ref->next == NULL)
4599           && current_part_dimension
4600           && seen_part_dimension)
4601         {
4602           gfc_error ("Two or more part references with nonzero rank must "
4603                      "not be specified at %L", &expr->where);
4604           return false;
4605         }
4606
4607       if (ref->type == REF_COMPONENT)
4608         {
4609           if (current_part_dimension)
4610             seen_part_dimension = 1;
4611
4612           /* reset to make sure */
4613           current_part_dimension = 0;
4614         }
4615     }
4616
4617   return true;
4618 }
4619
4620
4621 /* Given an expression, determine its shape.  This is easier than it sounds.
4622    Leaves the shape array NULL if it is not possible to determine the shape.  */
4623
4624 static void
4625 expression_shape (gfc_expr *e)
4626 {
4627   mpz_t array[GFC_MAX_DIMENSIONS];
4628   int i;
4629
4630   if (e->rank <= 0 || e->shape != NULL)
4631     return;
4632
4633   for (i = 0; i < e->rank; i++)
4634     if (!gfc_array_dimen_size (e, i, &array[i]))
4635       goto fail;
4636
4637   e->shape = gfc_get_shape (e->rank);
4638
4639   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4640
4641   return;
4642
4643 fail:
4644   for (i--; i >= 0; i--)
4645     mpz_clear (array[i]);
4646 }
4647
4648
4649 /* Given a variable expression node, compute the rank of the expression by
4650    examining the base symbol and any reference structures it may have.  */
4651
4652 static void
4653 expression_rank (gfc_expr *e)
4654 {
4655   gfc_ref *ref;
4656   int i, rank;
4657
4658   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4659      could lead to serious confusion...  */
4660   gcc_assert (e->expr_type != EXPR_COMPCALL);
4661
4662   if (e->ref == NULL)
4663     {
4664       if (e->expr_type == EXPR_ARRAY)
4665         goto done;
4666       /* Constructors can have a rank different from one via RESHAPE().  */
4667
4668       if (e->symtree == NULL)
4669         {
4670           e->rank = 0;
4671           goto done;
4672         }
4673
4674       e->rank = (e->symtree->n.sym->as == NULL)
4675                 ? 0 : e->symtree->n.sym->as->rank;
4676       goto done;
4677     }
4678
4679   rank = 0;
4680
4681   for (ref = e->ref; ref; ref = ref->next)
4682     {
4683       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.proc_pointer
4684           && ref->u.c.component->attr.function && !ref->next)
4685         rank = ref->u.c.component->as ? ref->u.c.component->as->rank : 0;
4686
4687       if (ref->type != REF_ARRAY)
4688         continue;
4689
4690       if (ref->u.ar.type == AR_FULL)
4691         {
4692           rank = ref->u.ar.as->rank;
4693           break;
4694         }
4695
4696       if (ref->u.ar.type == AR_SECTION)
4697         {
4698           /* Figure out the rank of the section.  */
4699           if (rank != 0)
4700             gfc_internal_error ("expression_rank(): Two array specs");
4701
4702           for (i = 0; i < ref->u.ar.dimen; i++)
4703             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4704                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4705               rank++;
4706
4707           break;
4708         }
4709     }
4710
4711   e->rank = rank;
4712
4713 done:
4714   expression_shape (e);
4715 }
4716
4717
4718 /* Resolve a variable expression.  */
4719
4720 static bool
4721 resolve_variable (gfc_expr *e)
4722 {
4723   gfc_symbol *sym;
4724   bool t;
4725
4726   t = true;
4727
4728   if (e->symtree == NULL)
4729     return false;
4730   sym = e->symtree->n.sym;
4731
4732   /* Use same check as for TYPE(*) below; this check has to be before TYPE(*)
4733      as ts.type is set to BT_ASSUMED in resolve_symbol.  */
4734   if (sym->attr.ext_attr & (1 << EXT_ATTR_NO_ARG_CHECK))
4735     {
4736       if (!actual_arg || inquiry_argument)
4737         {
4738           gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute may only "
4739                      "be used as actual argument", sym->name, &e->where);
4740           return false;
4741         }
4742     }
4743   /* TS 29113, 407b.  */
4744   else if (e->ts.type == BT_ASSUMED)
4745     {
4746       if (!actual_arg)
4747         {
4748           gfc_error ("Assumed-type variable %s at %L may only be used "
4749                      "as actual argument", sym->name, &e->where);
4750           return false;
4751         }
4752       else if (inquiry_argument && !first_actual_arg)
4753         {
4754           /* FIXME: It doesn't work reliably as inquiry_argument is not set
4755              for all inquiry functions in resolve_function; the reason is
4756              that the function-name resolution happens too late in that
4757              function.  */
4758           gfc_error ("Assumed-type variable %s at %L as actual argument to "
4759                      "an inquiry function shall be the first argument",
4760                      sym->name, &e->where);
4761           return false;
4762         }
4763     }
4764   /* TS 29113, C535b.  */
4765   else if ((sym->ts.type == BT_CLASS && sym->attr.class_ok
4766             && CLASS_DATA (sym)->as
4767             && CLASS_DATA (sym)->as->type == AS_ASSUMED_RANK)
4768            || (sym->ts.type != BT_CLASS && sym->as
4769                && sym->as->type == AS_ASSUMED_RANK))
4770     {
4771       if (!actual_arg)
4772         {
4773           gfc_error ("Assumed-rank variable %s at %L may only be used as "
4774                      "actual argument", sym->name, &e->where);
4775           return false;
4776         }
4777       else if (inquiry_argument && !first_actual_arg)
4778         {
4779           /* FIXME: It doesn't work reliably as inquiry_argument is not set
4780              for all inquiry functions in resolve_function; the reason is
4781              that the function-name resolution happens too late in that
4782              function.  */
4783           gfc_error ("Assumed-rank variable %s at %L as actual argument "
4784                      "to an inquiry function shall be the first argument",
4785                      sym->name, &e->where);
4786           return false;
4787         }
4788     }
4789
4790   if ((sym->attr.ext_attr & (1 << EXT_ATTR_NO_ARG_CHECK)) && e->ref
4791       && !(e->ref->type == REF_ARRAY && e->ref->u.ar.type == AR_FULL
4792            && e->ref->next == NULL))
4793     {
4794       gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute shall not have "
4795                  "a subobject reference", sym->name, &e->ref->u.ar.where);
4796       return false;
4797     }
4798   /* TS 29113, 407b.  */
4799   else if (e->ts.type == BT_ASSUMED && e->ref
4800            && !(e->ref->type == REF_ARRAY && e->ref->u.ar.type == AR_FULL
4801                 && e->ref->next == NULL))
4802     {
4803       gfc_error ("Assumed-type variable %s at %L shall not have a subobject "
4804                  "reference", sym->name, &e->ref->u.ar.where);
4805       return false;
4806     }
4807
4808   /* TS 29113, C535b.  */
4809   if (((sym->ts.type == BT_CLASS && sym->attr.class_ok
4810         && CLASS_DATA (sym)->as
4811         && CLASS_DATA (sym)->as->type == AS_ASSUMED_RANK)
4812        || (sym->ts.type != BT_CLASS && sym->as
4813            && sym->as->type == AS_ASSUMED_RANK))
4814       && e->ref
4815       && !(e->ref->type == REF_ARRAY && e->ref->u.ar.type == AR_FULL
4816            && e->ref->next == NULL))
4817     {
4818       gfc_error ("Assumed-rank variable %s at %L shall not have a subobject "
4819                  "reference", sym->name, &e->ref->u.ar.where);
4820       return false;
4821     }
4822
4823
4824   /* If this is an associate-name, it may be parsed with an array reference
4825      in error even though the target is scalar.  Fail directly in this case.
4826      TODO Understand why class scalar expressions must be excluded.  */
4827   if (sym->assoc && !(sym->ts.type == BT_CLASS && e->rank == 0))
4828     {
4829       if (sym->ts.type == BT_CLASS)
4830         gfc_fix_class_refs (e);
4831       if (!sym->attr.dimension && e->ref && e->ref->type == REF_ARRAY)
4832         return false;
4833     }
4834
4835   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.generic)
4836     sym->ts.u.derived = gfc_find_dt_in_generic (sym->ts.u.derived);
4837
4838   /* On the other hand, the parser may not have known this is an array;
4839      in this case, we have to add a FULL reference.  */
4840   if (sym->assoc && sym->attr.dimension && !e->ref)
4841     {
4842       e->ref = gfc_get_ref ();
4843       e->ref->type = REF_ARRAY;
4844       e->ref->u.ar.type = AR_FULL;
4845       e->ref->u.ar.dimen = 0;
4846     }
4847
4848   if (e->ref && !resolve_ref (e))
4849     return false;
4850
4851   if (sym->attr.flavor == FL_PROCEDURE
4852       && (!sym->attr.function
4853           || (sym->attr.function && sym->result
4854               && sym->result->attr.proc_pointer
4855               && !sym->result->attr.function)))
4856     {
4857       e->ts.type = BT_PROCEDURE;
4858       goto resolve_procedure;
4859     }
4860
4861   if (sym->ts.type != BT_UNKNOWN)
4862     gfc_variable_attr (e, &e->ts);
4863   else
4864     {
4865       /* Must be a simple variable reference.  */
4866       if (!gfc_set_default_type (sym, 1, sym->ns))
4867         return false;
4868       e->ts = sym->ts;
4869     }
4870
4871   if (check_assumed_size_reference (sym, e))
4872     return false;
4873
4874   /* Deal with forward references to entries during resolve_code, to
4875      satisfy, at least partially, 12.5.2.5.  */
4876   if (gfc_current_ns->entries
4877       && current_entry_id == sym->entry_id
4878       && cs_base
4879       && cs_base->current
4880       && cs_base->current->op != EXEC_ENTRY)
4881     {
4882       gfc_entry_list *entry;
4883       gfc_formal_arglist *formal;
4884       int n;
4885       bool seen, saved_specification_expr;
4886
4887       /* If the symbol is a dummy...  */
4888       if (sym->attr.dummy && sym->ns == gfc_current_ns)
4889         {
4890           entry = gfc_current_ns->entries;
4891           seen = false;
4892
4893           /* ...test if the symbol is a parameter of previous entries.  */
4894           for (; entry && entry->id <= current_entry_id; entry = entry->next)
4895             for (formal = entry->sym->formal; formal; formal = formal->next)
4896               {
4897                 if (formal->sym && sym->name == formal->sym->name)
4898                   seen = true;
4899               }
4900
4901           /*  If it has not been seen as a dummy, this is an error.  */
4902           if (!seen)
4903             {
4904               if (specification_expr)
4905                 gfc_error ("Variable '%s', used in a specification expression"
4906                            ", is referenced at %L before the ENTRY statement "
4907                            "in which it is a parameter",
4908                            sym->name, &cs_base->current->loc);
4909               else
4910                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
4911                            "statement in which it is a parameter",
4912                            sym->name, &cs_base->current->loc);
4913               t = false;
4914             }
4915         }
4916
4917       /* Now do the same check on the specification expressions.  */
4918       saved_specification_expr = specification_expr;
4919       specification_expr = true;
4920       if (sym->ts.type == BT_CHARACTER
4921           && !gfc_resolve_expr (sym->ts.u.cl->length))
4922         t = false;
4923
4924       if (sym->as)
4925         for (n = 0; n < sym->as->rank; n++)
4926           {
4927              if (!gfc_resolve_expr (sym->as->lower[n]))
4928                t = false;
4929              if (!gfc_resolve_expr (sym->as->upper[n]))
4930                t = false;
4931           }
4932       specification_expr = saved_specification_expr;
4933
4934       if (t)
4935         /* Update the symbol's entry level.  */
4936         sym->entry_id = current_entry_id + 1;
4937     }
4938
4939   /* If a symbol has been host_associated mark it.  This is used latter,
4940      to identify if aliasing is possible via host association.  */
4941   if (sym->attr.flavor == FL_VARIABLE
4942         && gfc_current_ns->parent
4943         && (gfc_current_ns->parent == sym->ns
4944               || (gfc_current_ns->parent->parent
4945                     && gfc_current_ns->parent->parent == sym->ns)))
4946     sym->attr.host_assoc = 1;
4947
4948 resolve_procedure:
4949   if (t && !resolve_procedure_expression (e))
4950     t = false;
4951
4952   /* F2008, C617 and C1229.  */
4953   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
4954       && gfc_is_coindexed (e))
4955     {
4956       gfc_ref *ref, *ref2 = NULL;
4957
4958       for (ref = e->ref; ref; ref = ref->next)
4959         {
4960           if (ref->type == REF_COMPONENT)
4961             ref2 = ref;
4962           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
4963             break;
4964         }
4965
4966       for ( ; ref; ref = ref->next)
4967         if (ref->type == REF_COMPONENT)
4968           break;
4969
4970       /* Expression itself is not coindexed object.  */
4971       if (ref && e->ts.type == BT_CLASS)
4972         {
4973           gfc_error ("Polymorphic subobject of coindexed object at %L",
4974                      &e->where);
4975           t = false;
4976         }
4977
4978       /* Expression itself is coindexed object.  */
4979       if (ref == NULL)
4980         {
4981           gfc_component *c;
4982           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
4983           for ( ; c; c = c->next)
4984             if (c->attr.allocatable && c->ts.type == BT_CLASS)
4985               {
4986                 gfc_error ("Coindexed object with polymorphic allocatable "
4987                          "subcomponent at %L", &e->where);
4988                 t = false;
4989                 break;
4990               }
4991         }
4992     }
4993
4994   return t;
4995 }
4996
4997
4998 /* Checks to see that the correct symbol has been host associated.
4999    The only situation where this arises is that in which a twice
5000    contained function is parsed after the host association is made.
5001    Therefore, on detecting this, change the symbol in the expression
5002    and convert the array reference into an actual arglist if the old
5003    symbol is a variable.  */
5004 static bool
5005 check_host_association (gfc_expr *e)
5006 {
5007   gfc_symbol *sym, *old_sym;
5008   gfc_symtree *st;
5009   int n;
5010   gfc_ref *ref;
5011   gfc_actual_arglist *arg, *tail = NULL;
5012   bool retval = e->expr_type == EXPR_FUNCTION;
5013
5014   /*  If the expression is the result of substitution in
5015       interface.c(gfc_extend_expr) because there is no way in
5016       which the host association can be wrong.  */
5017   if (e->symtree == NULL
5018         || e->symtree->n.sym == NULL
5019         || e->user_operator)
5020     return retval;
5021
5022   old_sym = e->symtree->n.sym;
5023
5024   if (gfc_current_ns->parent
5025         && old_sym->ns != gfc_current_ns)
5026     {
5027       /* Use the 'USE' name so that renamed module symbols are
5028          correctly handled.  */
5029       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
5030
5031       if (sym && old_sym != sym
5032               && sym->ts.type == old_sym->ts.type
5033               && sym->attr.flavor == FL_PROCEDURE
5034               && sym->attr.contained)
5035         {
5036           /* Clear the shape, since it might not be valid.  */
5037           gfc_free_shape (&e->shape, e->rank);
5038
5039           /* Give the expression the right symtree!  */
5040           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
5041           gcc_assert (st != NULL);
5042
5043           if (old_sym->attr.flavor == FL_PROCEDURE
5044                 || e->expr_type == EXPR_FUNCTION)
5045             {
5046               /* Original was function so point to the new symbol, since
5047                  the actual argument list is already attached to the
5048                  expression. */
5049               e->value.function.esym = NULL;
5050               e->symtree = st;
5051             }
5052           else
5053             {
5054               /* Original was variable so convert array references into
5055                  an actual arglist. This does not need any checking now
5056                  since resolve_function will take care of it.  */
5057               e->value.function.actual = NULL;
5058               e->expr_type = EXPR_FUNCTION;
5059               e->symtree = st;
5060
5061               /* Ambiguity will not arise if the array reference is not
5062                  the last reference.  */
5063               for (ref = e->ref; ref; ref = ref->next)
5064                 if (ref->type == REF_ARRAY && ref->next == NULL)
5065                   break;
5066
5067               gcc_assert (ref->type == REF_ARRAY);
5068
5069               /* Grab the start expressions from the array ref and
5070                  copy them into actual arguments.  */
5071               for (n = 0; n < ref->u.ar.dimen; n++)
5072                 {
5073                   arg = gfc_get_actual_arglist ();
5074                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
5075                   if (e->value.function.actual == NULL)
5076                     tail = e->value.function.actual = arg;
5077                   else
5078                     {
5079                       tail->next = arg;
5080                       tail = arg;
5081                     }
5082                 }
5083
5084               /* Dump the reference list and set the rank.  */
5085               gfc_free_ref_list (e->ref);
5086               e->ref = NULL;
5087               e->rank = sym->as ? sym->as->rank : 0;
5088             }
5089
5090           gfc_resolve_expr (e);
5091           sym->refs++;
5092         }
5093     }
5094   /* This might have changed!  */
5095   return e->expr_type == EXPR_FUNCTION;
5096 }
5097
5098
5099 static void
5100 gfc_resolve_character_operator (gfc_expr *e)
5101 {
5102   gfc_expr *op1 = e->value.op.op1;
5103   gfc_expr *op2 = e->value.op.op2;
5104   gfc_expr *e1 = NULL;
5105   gfc_expr *e2 = NULL;
5106
5107   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
5108
5109   if (op1->ts.u.cl && op1->ts.u.cl->length)
5110     e1 = gfc_copy_expr (op1->ts.u.cl->length);
5111   else if (op1->expr_type == EXPR_CONSTANT)
5112     e1 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5113                            op1->value.character.length);
5114
5115   if (op2->ts.u.cl && op2->ts.u.cl->length)
5116     e2 = gfc_copy_expr (op2->ts.u.cl->length);
5117   else if (op2->expr_type == EXPR_CONSTANT)
5118     e2 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5119                            op2->value.character.length);
5120
5121   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5122
5123   if (!e1 || !e2)
5124     {
5125       gfc_free_expr (e1);
5126       gfc_free_expr (e2);
5127
5128       return;
5129     }
5130
5131   e->ts.u.cl->length = gfc_add (e1, e2);
5132   e->ts.u.cl->length->ts.type = BT_INTEGER;
5133   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5134   gfc_simplify_expr (e->ts.u.cl->length, 0);
5135   gfc_resolve_expr (e->ts.u.cl->length);
5136
5137   return;
5138 }
5139
5140
5141 /*  Ensure that an character expression has a charlen and, if possible, a
5142     length expression.  */
5143
5144 static void
5145 fixup_charlen (gfc_expr *e)
5146 {
5147   /* The cases fall through so that changes in expression type and the need
5148      for multiple fixes are picked up.  In all circumstances, a charlen should
5149      be available for the middle end to hang a backend_decl on.  */
5150   switch (e->expr_type)
5151     {
5152     case EXPR_OP:
5153       gfc_resolve_character_operator (e);
5154
5155     case EXPR_ARRAY:
5156       if (e->expr_type == EXPR_ARRAY)
5157         gfc_resolve_character_array_constructor (e);
5158
5159     case EXPR_SUBSTRING:
5160       if (!e->ts.u.cl && e->ref)
5161         gfc_resolve_substring_charlen (e);
5162
5163     default:
5164       if (!e->ts.u.cl)
5165         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5166
5167       break;
5168     }
5169 }
5170
5171
5172 /* Update an actual argument to include the passed-object for type-bound
5173    procedures at the right position.  */
5174
5175 static gfc_actual_arglist*
5176 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
5177                      const char *name)
5178 {
5179   gcc_assert (argpos > 0);
5180
5181   if (argpos == 1)
5182     {
5183       gfc_actual_arglist* result;
5184
5185       result = gfc_get_actual_arglist ();
5186       result->expr = po;
5187       result->next = lst;
5188       if (name)
5189         result->name = name;
5190
5191       return result;
5192     }
5193
5194   if (lst)
5195     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
5196   else
5197     lst = update_arglist_pass (NULL, po, argpos - 1, name);
5198   return lst;
5199 }
5200
5201
5202 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
5203
5204 static gfc_expr*
5205 extract_compcall_passed_object (gfc_expr* e)
5206 {
5207   gfc_expr* po;
5208
5209   gcc_assert (e->expr_type == EXPR_COMPCALL);
5210
5211   if (e->value.compcall.base_object)
5212     po = gfc_copy_expr (e->value.compcall.base_object);
5213   else
5214     {
5215       po = gfc_get_expr ();
5216       po->expr_type = EXPR_VARIABLE;
5217       po->symtree = e->symtree;
5218       po->ref = gfc_copy_ref (e->ref);
5219       po->where = e->where;
5220     }
5221
5222   if (!gfc_resolve_expr (po))
5223     return NULL;
5224
5225   return po;
5226 }
5227
5228
5229 /* Update the arglist of an EXPR_COMPCALL expression to include the
5230    passed-object.  */
5231
5232 static bool
5233 update_compcall_arglist (gfc_expr* e)
5234 {
5235   gfc_expr* po;
5236   gfc_typebound_proc* tbp;
5237
5238   tbp = e->value.compcall.tbp;
5239
5240   if (tbp->error)
5241     return false;
5242
5243   po = extract_compcall_passed_object (e);
5244   if (!po)
5245     return false;
5246
5247   if (tbp->nopass || e->value.compcall.ignore_pass)
5248     {
5249       gfc_free_expr (po);
5250       return true;
5251     }
5252
5253   gcc_assert (tbp->pass_arg_num > 0);
5254   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5255                                                   tbp->pass_arg_num,
5256                                                   tbp->pass_arg);
5257
5258   return true;
5259 }
5260
5261
5262 /* Extract the passed object from a PPC call (a copy of it).  */
5263
5264 static gfc_expr*
5265 extract_ppc_passed_object (gfc_expr *e)
5266 {
5267   gfc_expr *po;
5268   gfc_ref **ref;
5269
5270   po = gfc_get_expr ();
5271   po->expr_type = EXPR_VARIABLE;
5272   po->symtree = e->symtree;
5273   po->ref = gfc_copy_ref (e->ref);
5274   po->where = e->where;
5275
5276   /* Remove PPC reference.  */
5277   ref = &po->ref;
5278   while ((*ref)->next)
5279     ref = &(*ref)->next;
5280   gfc_free_ref_list (*ref);
5281   *ref = NULL;
5282
5283   if (!gfc_resolve_expr (po))
5284     return NULL;
5285
5286   return po;
5287 }
5288
5289
5290 /* Update the actual arglist of a procedure pointer component to include the
5291    passed-object.  */
5292
5293 static bool
5294 update_ppc_arglist (gfc_expr* e)
5295 {
5296   gfc_expr* po;
5297   gfc_component *ppc;
5298   gfc_typebound_proc* tb;
5299
5300   ppc = gfc_get_proc_ptr_comp (e);
5301   if (!ppc)
5302     return false;
5303
5304   tb = ppc->tb;
5305
5306   if (tb->error)
5307     return false;
5308   else if (tb->nopass)
5309     return true;
5310
5311   po = extract_ppc_passed_object (e);
5312   if (!po)
5313     return false;
5314
5315   /* F08:R739.  */
5316   if (po->rank != 0)
5317     {
5318       gfc_error ("Passed-object at %L must be scalar", &e->where);
5319       return false;
5320     }
5321
5322   /* F08:C611.  */
5323   if (po->ts.type == BT_DERIVED && po->ts.u.derived->attr.abstract)
5324     {
5325       gfc_error ("Base object for procedure-pointer component call at %L is of"
5326                  " ABSTRACT type '%s'", &e->where, po->ts.u.derived->name);
5327       return false;
5328     }
5329
5330   gcc_assert (tb->pass_arg_num > 0);
5331   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5332                                                   tb->pass_arg_num,
5333                                                   tb->pass_arg);
5334
5335   return true;
5336 }
5337
5338
5339 /* Check that the object a TBP is called on is valid, i.e. it must not be
5340    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5341
5342 static bool
5343 check_typebound_baseobject (gfc_expr* e)
5344 {
5345   gfc_expr* base;
5346   bool return_value = false;
5347
5348   base = extract_compcall_passed_object (e);
5349   if (!base)
5350     return false;
5351
5352   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5353
5354   if (base->ts.type == BT_CLASS && !gfc_expr_attr (base).class_ok)
5355     return false;
5356
5357   /* F08:C611.  */
5358   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5359     {
5360       gfc_error ("Base object for type-bound procedure call at %L is of"
5361                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5362       goto cleanup;
5363     }
5364
5365   /* F08:C1230. If the procedure called is NOPASS,
5366      the base object must be scalar.  */
5367   if (e->value.compcall.tbp->nopass && base->rank != 0)
5368     {
5369       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5370                  " be scalar", &e->where);
5371       goto cleanup;
5372     }
5373
5374   return_value = true;
5375
5376 cleanup:
5377   gfc_free_expr (base);
5378   return return_value;
5379 }
5380
5381
5382 /* Resolve a call to a type-bound procedure, either function or subroutine,
5383    statically from the data in an EXPR_COMPCALL expression.  The adapted
5384    arglist and the target-procedure symtree are returned.  */
5385
5386 static bool
5387 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5388                           gfc_actual_arglist** actual)
5389 {
5390   gcc_assert (e->expr_type == EXPR_COMPCALL);
5391   gcc_assert (!e->value.compcall.tbp->is_generic);
5392
5393   /* Update the actual arglist for PASS.  */
5394   if (!update_compcall_arglist (e))
5395     return false;
5396
5397   *actual = e->value.compcall.actual;
5398   *target = e->value.compcall.tbp->u.specific;
5399
5400   gfc_free_ref_list (e->ref);
5401   e->ref = NULL;
5402   e->value.compcall.actual = NULL;
5403
5404   /* If we find a deferred typebound procedure, check for derived types
5405      that an overriding typebound procedure has not been missed.  */
5406   if (e->value.compcall.name
5407       && !e->value.compcall.tbp->non_overridable
5408       && e->value.compcall.base_object
5409       && e->value.compcall.base_object->ts.type == BT_DERIVED)
5410     {
5411       gfc_symtree *st;
5412       gfc_symbol *derived;
5413
5414       /* Use the derived type of the base_object.  */
5415       derived = e->value.compcall.base_object->ts.u.derived;
5416       st = NULL;
5417
5418       /* If necessary, go through the inheritance chain.  */
5419       while (!st && derived)
5420         {
5421           /* Look for the typebound procedure 'name'.  */
5422           if (derived->f2k_derived && derived->f2k_derived->tb_sym_root)
5423             st = gfc_find_symtree (derived->f2k_derived->tb_sym_root,
5424                                    e->value.compcall.name);
5425           if (!st)
5426             derived = gfc_get_derived_super_type (derived);
5427         }
5428
5429       /* Now find the specific name in the derived type namespace.  */
5430       if (st && st->n.tb && st->n.tb->u.specific)
5431         gfc_find_sym_tree (st->n.tb->u.specific->name,
5432                            derived->ns, 1, &st);
5433       if (st)
5434         *target = st;
5435     }
5436   return true;
5437 }
5438
5439
5440 /* Get the ultimate declared type from an expression.  In addition,
5441    return the last class/derived type reference and the copy of the
5442    reference list.  If check_types is set true, derived types are
5443    identified as well as class references.  */
5444 static gfc_symbol*
5445 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5446                         gfc_expr *e, bool check_types)
5447 {
5448   gfc_symbol *declared;
5449   gfc_ref *ref;
5450
5451   declared = NULL;
5452   if (class_ref)
5453     *class_ref = NULL;
5454   if (new_ref)
5455     *new_ref = gfc_copy_ref (e->ref);
5456
5457   for (ref = e->ref; ref; ref = ref->next)
5458     {
5459       if (ref->type != REF_COMPONENT)
5460         continue;
5461
5462       if ((ref->u.c.component->ts.type == BT_CLASS
5463              || (check_types && ref->u.c.component->ts.type == BT_DERIVED))
5464           && ref->u.c.component->attr.flavor != FL_PROCEDURE)
5465         {
5466           declared = ref->u.c.component->ts.u.derived;
5467           if (class_ref)
5468             *class_ref = ref;
5469         }
5470     }
5471
5472   if (declared == NULL)
5473     declared = e->symtree->n.sym->ts.u.derived;
5474
5475   return declared;
5476 }
5477
5478
5479 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5480    which of the specific bindings (if any) matches the arglist and transform
5481    the expression into a call of that binding.  */
5482
5483 static bool
5484 resolve_typebound_generic_call (gfc_expr* e, const char **name)
5485 {
5486   gfc_typebound_proc* genproc;
5487   const char* genname;
5488   gfc_symtree *st;
5489   gfc_symbol *derived;
5490
5491   gcc_assert (e->expr_type == EXPR_COMPCALL);
5492   genname = e->value.compcall.name;
5493   genproc = e->value.compcall.tbp;
5494
5495   if (!genproc->is_generic)
5496     return true;
5497
5498   /* Try the bindings on this type and in the inheritance hierarchy.  */
5499   for (; genproc; genproc = genproc->overridden)
5500     {
5501       gfc_tbp_generic* g;
5502
5503       gcc_assert (genproc->is_generic);
5504       for (g = genproc->u.generic; g; g = g->next)
5505         {
5506           gfc_symbol* target;
5507           gfc_actual_arglist* args;
5508           bool matches;
5509
5510           gcc_assert (g->specific);
5511
5512           if (g->specific->error)
5513             continue;
5514
5515           target = g->specific->u.specific->n.sym;
5516
5517           /* Get the right arglist by handling PASS/NOPASS.  */
5518           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5519           if (!g->specific->nopass)
5520             {
5521               gfc_expr* po;
5522               po = extract_compcall_passed_object (e);
5523               if (!po)
5524                 {
5525                   gfc_free_actual_arglist (args);
5526                   return false;
5527                 }
5528
5529               gcc_assert (g->specific->pass_arg_num > 0);
5530               gcc_assert (!g->specific->error);
5531               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5532                                           g->specific->pass_arg);
5533             }
5534           resolve_actual_arglist (args, target->attr.proc,
5535                                   is_external_proc (target)
5536                                   && gfc_sym_get_dummy_args (target) == NULL);
5537
5538           /* Check if this arglist matches the formal.  */
5539           matches = gfc_arglist_matches_symbol (&args, target);
5540
5541           /* Clean up and break out of the loop if we've found it.  */
5542           gfc_free_actual_arglist (args);
5543           if (matches)
5544             {
5545               e->value.compcall.tbp = g->specific;
5546               genname = g->specific_st->name;
5547               /* Pass along the name for CLASS methods, where the vtab
5548                  procedure pointer component has to be referenced.  */
5549               if (name)
5550                 *name = genname;
5551               goto success;
5552             }
5553         }
5554     }
5555
5556   /* Nothing matching found!  */
5557   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5558              " '%s' at %L", genname, &e->where);
5559   return false;
5560
5561 success:
5562   /* Make sure that we have the right specific instance for the name.  */
5563   derived = get_declared_from_expr (NULL, NULL, e, true);
5564
5565   st = gfc_find_typebound_proc (derived, NULL, genname, true, &e->where);
5566   if (st)
5567     e->value.compcall.tbp = st->n.tb;
5568
5569   return true;
5570 }
5571
5572
5573 /* Resolve a call to a type-bound subroutine.  */
5574
5575 static bool
5576 resolve_typebound_call (gfc_code* c, const char **name)
5577 {
5578   gfc_actual_arglist* newactual;
5579   gfc_symtree* target;
5580
5581   /* Check that's really a SUBROUTINE.  */
5582   if (!c->expr1->value.compcall.tbp->subroutine)
5583     {
5584       gfc_error ("'%s' at %L should be a SUBROUTINE",
5585                  c->expr1->value.compcall.name, &c->loc);
5586       return false;
5587     }
5588
5589   if (!check_typebound_baseobject (c->expr1))
5590     return false;
5591
5592   /* Pass along the name for CLASS methods, where the vtab
5593      procedure pointer component has to be referenced.  */
5594   if (name)
5595     *name = c->expr1->value.compcall.name;
5596
5597   if (!resolve_typebound_generic_call (c->expr1, name))
5598     return false;
5599
5600   /* Transform into an ordinary EXEC_CALL for now.  */
5601
5602   if (!resolve_typebound_static (c->expr1, &target, &newactual))
5603     return false;
5604
5605   c->ext.actual = newactual;
5606   c->symtree = target;
5607   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5608
5609   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5610
5611   gfc_free_expr (c->expr1);
5612   c->expr1 = gfc_get_expr ();
5613   c->expr1->expr_type = EXPR_FUNCTION;
5614   c->expr1->symtree = target;
5615   c->expr1->where = c->loc;
5616
5617   return resolve_call (c);
5618 }
5619
5620
5621 /* Resolve a component-call expression.  */
5622 static bool
5623 resolve_compcall (gfc_expr* e, const char **name)
5624 {
5625   gfc_actual_arglist* newactual;
5626   gfc_symtree* target;
5627
5628   /* Check that's really a FUNCTION.  */
5629   if (!e->value.compcall.tbp->function)
5630     {
5631       gfc_error ("'%s' at %L should be a FUNCTION",
5632                  e->value.compcall.name, &e->where);
5633       return false;
5634     }
5635
5636   /* These must not be assign-calls!  */
5637   gcc_assert (!e->value.compcall.assign);
5638
5639   if (!check_typebound_baseobject (e))
5640     return false;
5641
5642   /* Pass along the name for CLASS methods, where the vtab
5643      procedure pointer component has to be referenced.  */
5644   if (name)
5645     *name = e->value.compcall.name;
5646
5647   if (!resolve_typebound_generic_call (e, name))
5648     return false;
5649   gcc_assert (!e->value.compcall.tbp->is_generic);
5650
5651   /* Take the rank from the function's symbol.  */
5652   if (e->value.compcall.tbp->u.specific->n.sym->as)
5653     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5654
5655   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5656      arglist to the TBP's binding target.  */
5657
5658   if (!resolve_typebound_static (e, &target, &newactual))
5659     return false;
5660
5661   e->value.function.actual = newactual;
5662   e->value.function.name = NULL;
5663   e->value.function.esym = target->n.sym;
5664   e->value.function.isym = NULL;
5665   e->symtree = target;
5666   e->ts = target->n.sym->ts;
5667   e->expr_type = EXPR_FUNCTION;
5668
5669   /* Resolution is not necessary if this is a class subroutine; this
5670      function only has to identify the specific proc. Resolution of
5671      the call will be done next in resolve_typebound_call.  */
5672   return gfc_resolve_expr (e);
5673 }
5674
5675
5676
5677 /* Resolve a typebound function, or 'method'. First separate all
5678    the non-CLASS references by calling resolve_compcall directly.  */
5679
5680 static bool
5681 resolve_typebound_function (gfc_expr* e)
5682 {
5683   gfc_symbol *declared;
5684   gfc_component *c;
5685   gfc_ref *new_ref;
5686   gfc_ref *class_ref;
5687   gfc_symtree *st;
5688   const char *name;
5689   gfc_typespec ts;
5690   gfc_expr *expr;
5691   bool overridable;
5692
5693   st = e->symtree;
5694
5695   /* Deal with typebound operators for CLASS objects.  */
5696   expr = e->value.compcall.base_object;
5697   overridable = !e->value.compcall.tbp->non_overridable;
5698   if (expr && expr->ts.type == BT_CLASS && e->value.compcall.name)
5699     {
5700       /* If the base_object is not a variable, the corresponding actual
5701          argument expression must be stored in e->base_expression so
5702          that the corresponding tree temporary can be used as the base
5703          object in gfc_conv_procedure_call.  */
5704       if (expr->expr_type != EXPR_VARIABLE)
5705         {
5706           gfc_actual_arglist *args;
5707
5708           for (args= e->value.function.actual; args; args = args->next)
5709             {
5710               if (expr == args->expr)
5711                 expr = args->expr;
5712             }
5713         }
5714
5715       /* Since the typebound operators are generic, we have to ensure
5716          that any delays in resolution are corrected and that the vtab
5717          is present.  */
5718       ts = expr->ts;
5719       declared = ts.u.derived;
5720       c = gfc_find_component (declared, "_vptr", true, true);
5721       if (c->ts.u.derived == NULL)
5722         c->ts.u.derived = gfc_find_derived_vtab (declared);
5723
5724       if (!resolve_compcall (e, &name))
5725         return false;
5726
5727       /* Use the generic name if it is there.  */
5728       name = name ? name : e->value.function.esym->name;
5729       e->symtree = expr->symtree;
5730       e->ref = gfc_copy_ref (expr->ref);
5731       get_declared_from_expr (&class_ref, NULL, e, false);
5732
5733       /* Trim away the extraneous references that emerge from nested
5734          use of interface.c (extend_expr).  */
5735       if (class_ref && class_ref->next)
5736         {
5737           gfc_free_ref_list (class_ref->next);
5738           class_ref->next = NULL;
5739         }
5740       else if (e->ref && !class_ref)
5741         {
5742           gfc_free_ref_list (e->ref);
5743           e->ref = NULL;
5744         }
5745
5746       gfc_add_vptr_component (e);
5747       gfc_add_component_ref (e, name);
5748       e->value.function.esym = NULL;
5749       if (expr->expr_type != EXPR_VARIABLE)
5750         e->base_expr = expr;
5751       return true;
5752     }
5753
5754   if (st == NULL)
5755     return resolve_compcall (e, NULL);
5756
5757   if (!resolve_ref (e))
5758     return false;
5759
5760   /* Get the CLASS declared type.  */
5761   declared = get_declared_from_expr (&class_ref, &new_ref, e, true);
5762
5763   /* Weed out cases of the ultimate component being a derived type.  */
5764   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5765          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5766     {
5767       gfc_free_ref_list (new_ref);
5768       return resolve_compcall (e, NULL);
5769     }
5770
5771   c = gfc_find_component (declared, "_data", true, true);
5772   declared = c->ts.u.derived;
5773
5774   /* Treat the call as if it is a typebound procedure, in order to roll
5775      out the correct name for the specific function.  */
5776   if (!resolve_compcall (e, &name))
5777     {
5778       gfc_free_ref_list (new_ref);
5779       return false;
5780     }
5781   ts = e->ts;
5782
5783   if (overridable)
5784     {
5785       /* Convert the expression to a procedure pointer component call.  */
5786       e->value.function.esym = NULL;
5787       e->symtree = st;
5788
5789       if (new_ref)
5790         e->ref = new_ref;
5791
5792       /* '_vptr' points to the vtab, which contains the procedure pointers.  */
5793       gfc_add_vptr_component (e);
5794       gfc_add_component_ref (e, name);
5795
5796       /* Recover the typespec for the expression.  This is really only
5797         necessary for generic procedures, where the additional call
5798         to gfc_add_component_ref seems to throw the collection of the
5799         correct typespec.  */
5800       e->ts = ts;
5801     }
5802   else if (new_ref)
5803     gfc_free_ref_list (new_ref);
5804
5805   return true;
5806 }
5807
5808 /* Resolve a typebound subroutine, or 'method'. First separate all
5809    the non-CLASS references by calling resolve_typebound_call
5810    directly.  */
5811
5812 static bool
5813 resolve_typebound_subroutine (gfc_code *code)
5814 {
5815   gfc_symbol *declared;
5816   gfc_component *c;
5817   gfc_ref *new_ref;
5818   gfc_ref *class_ref;
5819   gfc_symtree *st;
5820   const char *name;
5821   gfc_typespec ts;
5822   gfc_expr *expr;
5823   bool overridable;
5824
5825   st = code->expr1->symtree;
5826
5827   /* Deal with typebound operators for CLASS objects.  */
5828   expr = code->expr1->value.compcall.base_object;
5829   overridable = !code->expr1->value.compcall.tbp->non_overridable;
5830   if (expr && expr->ts.type == BT_CLASS && code->expr1->value.compcall.name)
5831     {
5832       /* If the base_object is not a variable, the corresponding actual
5833          argument expression must be stored in e->base_expression so
5834          that the corresponding tree temporary can be used as the base
5835          object in gfc_conv_procedure_call.  */
5836       if (expr->expr_type != EXPR_VARIABLE)
5837         {
5838           gfc_actual_arglist *args;
5839
5840           args= code->expr1->value.function.actual;
5841           for (; args; args = args->next)
5842             if (expr == args->expr)
5843               expr = args->expr;
5844         }
5845
5846       /* Since the typebound operators are generic, we have to ensure
5847          that any delays in resolution are corrected and that the vtab
5848          is present.  */
5849       declared = expr->ts.u.derived;
5850       c = gfc_find_component (declared, "_vptr", true, true);
5851       if (c->ts.u.derived == NULL)
5852         c->ts.u.derived = gfc_find_derived_vtab (declared);
5853
5854       if (!resolve_typebound_call (code, &name))
5855         return false;
5856
5857       /* Use the generic name if it is there.  */
5858       name = name ? name : code->expr1->value.function.esym->name;
5859       code->expr1->symtree = expr->symtree;
5860       code->expr1->ref = gfc_copy_ref (expr->ref);
5861
5862       /* Trim away the extraneous references that emerge from nested
5863          use of interface.c (extend_expr).  */
5864       get_declared_from_expr (&class_ref, NULL, code->expr1, false);
5865       if (class_ref && class_ref->next)
5866         {
5867           gfc_free_ref_list (class_ref->next);
5868           class_ref->next = NULL;
5869         }
5870       else if (code->expr1->ref && !class_ref)
5871         {
5872           gfc_free_ref_list (code->expr1->ref);
5873           code->expr1->ref = NULL;
5874         }
5875
5876       /* Now use the procedure in the vtable.  */
5877       gfc_add_vptr_component (code->expr1);
5878       gfc_add_component_ref (code->expr1, name);
5879       code->expr1->value.function.esym = NULL;
5880       if (expr->expr_type != EXPR_VARIABLE)
5881         code->expr1->base_expr = expr;
5882       return true;
5883     }
5884
5885   if (st == NULL)
5886     return resolve_typebound_call (code, NULL);
5887
5888   if (!resolve_ref (code->expr1))
5889     return false;
5890
5891   /* Get the CLASS declared type.  */
5892   get_declared_from_expr (&class_ref, &new_ref, code->expr1, true);
5893
5894   /* Weed out cases of the ultimate component being a derived type.  */
5895   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5896          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5897     {
5898       gfc_free_ref_list (new_ref);
5899       return resolve_typebound_call (code, NULL);
5900     }
5901
5902   if (!resolve_typebound_call (code, &name))
5903     {
5904       gfc_free_ref_list (new_ref);
5905       return false;
5906     }
5907   ts = code->expr1->ts;
5908
5909   if (overridable)
5910     {
5911       /* Convert the expression to a procedure pointer component call.  */
5912       code->expr1->value.function.esym = NULL;
5913       code->expr1->symtree = st;
5914
5915       if (new_ref)
5916         code->expr1->ref = new_ref;
5917
5918       /* '_vptr' points to the vtab, which contains the procedure pointers.  */
5919       gfc_add_vptr_component (code->expr1);
5920       gfc_add_component_ref (code->expr1, name);
5921
5922       /* Recover the typespec for the expression.  This is really only
5923         necessary for generic procedures, where the additional call
5924         to gfc_add_component_ref seems to throw the collection of the
5925         correct typespec.  */
5926       code->expr1->ts = ts;
5927     }
5928   else if (new_ref)
5929     gfc_free_ref_list (new_ref);
5930
5931   return true;
5932 }
5933
5934
5935 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
5936
5937 static bool
5938 resolve_ppc_call (gfc_code* c)
5939 {
5940   gfc_component *comp;
5941
5942   comp = gfc_get_proc_ptr_comp (c->expr1);
5943   gcc_assert (comp != NULL);
5944
5945   c->resolved_sym = c->expr1->symtree->n.sym;
5946   c->expr1->expr_type = EXPR_VARIABLE;
5947
5948   if (!comp->attr.subroutine)
5949     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
5950
5951   if (!resolve_ref (c->expr1))
5952     return false;
5953
5954   if (!update_ppc_arglist (c->expr1))
5955     return false;
5956
5957   c->ext.actual = c->expr1->value.compcall.actual;
5958
5959   if (!resolve_actual_arglist (c->ext.actual, comp->attr.proc, 
5960                                !(comp->ts.interface 
5961                                  && comp->ts.interface->formal)))
5962     return false;
5963
5964   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
5965
5966   return true;
5967 }
5968
5969
5970 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
5971
5972 static bool
5973 resolve_expr_ppc (gfc_expr* e)
5974 {
5975   gfc_component *comp;
5976
5977   comp = gfc_get_proc_ptr_comp (e);
5978   gcc_assert (comp != NULL);
5979
5980   /* Convert to EXPR_FUNCTION.  */
5981   e->expr_type = EXPR_FUNCTION;
5982   e->value.function.isym = NULL;
5983   e->value.function.actual = e->value.compcall.actual;
5984   e->ts = comp->ts;
5985   if (comp->as != NULL)
5986     e->rank = comp->as->rank;
5987
5988   if (!comp->attr.function)
5989     gfc_add_function (&comp->attr, comp->name, &e->where);
5990
5991   if (!resolve_ref (e))
5992     return false;
5993
5994   if (!resolve_actual_arglist (e->value.function.actual, comp->attr.proc, 
5995                                !(comp->ts.interface 
5996                                  && comp->ts.interface->formal)))
5997     return false;
5998
5999   if (!update_ppc_arglist (e))
6000     return false;
6001
6002   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
6003
6004   return true;
6005 }
6006
6007
6008 static bool
6009 gfc_is_expandable_expr (gfc_expr *e)
6010 {
6011   gfc_constructor *con;
6012
6013   if (e->expr_type == EXPR_ARRAY)
6014     {
6015       /* Traverse the constructor looking for variables that are flavor
6016          parameter.  Parameters must be expanded since they are fully used at
6017          compile time.  */
6018       con = gfc_constructor_first (e->value.constructor);
6019       for (; con; con = gfc_constructor_next (con))
6020         {
6021           if (con->expr->expr_type == EXPR_VARIABLE
6022               && con->expr->symtree
6023               && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
6024               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
6025             return true;
6026           if (con->expr->expr_type == EXPR_ARRAY
6027               && gfc_is_expandable_expr (con->expr))
6028             return true;
6029         }
6030     }
6031
6032   return false;
6033 }
6034
6035 /* Resolve an expression.  That is, make sure that types of operands agree
6036    with their operators, intrinsic operators are converted to function calls
6037    for overloaded types and unresolved function references are resolved.  */
6038
6039 bool
6040 gfc_resolve_expr (gfc_expr *e)
6041 {
6042   bool t;
6043   bool inquiry_save, actual_arg_save, first_actual_arg_save;
6044
6045   if (e == NULL)
6046     return true;
6047
6048   /* inquiry_argument only applies to variables.  */
6049   inquiry_save = inquiry_argument;
6050   actual_arg_save = actual_arg;
6051   first_actual_arg_save = first_actual_arg;
6052
6053   if (e->expr_type != EXPR_VARIABLE)
6054     {
6055       inquiry_argument = false;
6056       actual_arg = false;
6057       first_actual_arg = false;
6058     }
6059
6060   switch (e->expr_type)
6061     {
6062     case EXPR_OP:
6063       t = resolve_operator (e);
6064       break;
6065
6066     case EXPR_FUNCTION:
6067     case EXPR_VARIABLE:
6068
6069       if (check_host_association (e))
6070         t = resolve_function (e);
6071       else
6072         {
6073           t = resolve_variable (e);
6074           if (t)
6075             expression_rank (e);
6076         }
6077
6078       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
6079           && e->ref->type != REF_SUBSTRING)
6080         gfc_resolve_substring_charlen (e);
6081
6082       break;
6083
6084     case EXPR_COMPCALL:
6085       t = resolve_typebound_function (e);
6086       break;
6087
6088     case EXPR_SUBSTRING:
6089       t = resolve_ref (e);
6090       break;
6091
6092     case EXPR_CONSTANT:
6093     case EXPR_NULL:
6094       t = true;
6095       break;
6096
6097     case EXPR_PPC:
6098       t = resolve_expr_ppc (e);
6099       break;
6100
6101     case EXPR_ARRAY:
6102       t = false;
6103       if (!resolve_ref (e))
6104         break;
6105
6106       t = gfc_resolve_array_constructor (e);
6107       /* Also try to expand a constructor.  */
6108       if (t)
6109         {
6110           expression_rank (e);
6111           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
6112             gfc_expand_constructor (e, false);
6113         }
6114
6115       /* This provides the opportunity for the length of constructors with
6116          character valued function elements to propagate the string length
6117          to the expression.  */
6118       if (t && e->ts.type == BT_CHARACTER)
6119         {
6120           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
6121              here rather then add a duplicate test for it above.  */
6122           gfc_expand_constructor (e, false);
6123           t = gfc_resolve_character_array_constructor (e);
6124         }
6125
6126       break;
6127
6128     case EXPR_STRUCTURE:
6129       t = resolve_ref (e);
6130       if (!t)
6131         break;
6132
6133       t = resolve_structure_cons (e, 0);
6134       if (!t)
6135         break;
6136
6137       t = gfc_simplify_expr (e, 0);
6138       break;
6139
6140     default:
6141       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
6142     }
6143
6144   if (e->ts.type == BT_CHARACTER && t && !e->ts.u.cl)
6145     fixup_charlen (e);
6146
6147   inquiry_argument = inquiry_save;
6148   actual_arg = actual_arg_save;
6149   first_actual_arg = first_actual_arg_save;
6150
6151   return t;
6152 }
6153
6154
6155 /* Resolve an expression from an iterator.  They must be scalar and have
6156    INTEGER or (optionally) REAL type.  */
6157
6158 static bool
6159 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
6160                            const char *name_msgid)
6161 {
6162   if (!gfc_resolve_expr (expr))
6163     return false;
6164
6165   if (expr->rank != 0)
6166     {
6167       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
6168       return false;
6169     }
6170
6171   if (expr->ts.type != BT_INTEGER)
6172     {
6173       if (expr->ts.type == BT_REAL)
6174         {
6175           if (real_ok)
6176             return gfc_notify_std (GFC_STD_F95_DEL,
6177                                    "%s at %L must be integer",
6178                                    _(name_msgid), &expr->where);
6179           else
6180             {
6181               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
6182                          &expr->where);
6183               return false;
6184             }
6185         }
6186       else
6187         {
6188           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
6189           return false;
6190         }
6191     }
6192   return true;
6193 }
6194
6195
6196 /* Resolve the expressions in an iterator structure.  If REAL_OK is
6197    false allow only INTEGER type iterators, otherwise allow REAL types.
6198    Set own_scope to true for ac-implied-do and data-implied-do as those
6199    have a separate scope such that, e.g., a INTENT(IN) doesn't apply.  */
6200
6201 bool
6202 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok, bool own_scope)
6203 {
6204   if (!gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable"))
6205     return false;
6206
6207   if (!gfc_check_vardef_context (iter->var, false, false, own_scope, 
6208                                  _("iterator variable")))
6209     return false;
6210
6211   if (!gfc_resolve_iterator_expr (iter->start, real_ok, 
6212                                   "Start expression in DO loop"))
6213     return false;
6214
6215   if (!gfc_resolve_iterator_expr (iter->end, real_ok, 
6216                                   "End expression in DO loop"))
6217     return false;
6218
6219   if (!gfc_resolve_iterator_expr (iter->step, real_ok, 
6220                                   "Step expression in DO loop"))
6221     return false;
6222
6223   if (iter->step->expr_type == EXPR_CONSTANT)
6224     {
6225       if ((iter->step->ts.type == BT_INTEGER
6226            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
6227           || (iter->step->ts.type == BT_REAL
6228               && mpfr_sgn (iter->step->value.real) == 0))
6229         {
6230           gfc_error ("Step expression in DO loop at %L cannot be zero",
6231                      &iter->step->where);
6232           return false;
6233         }
6234     }
6235
6236   /* Convert start, end, and step to the same type as var.  */
6237   if (iter->start->ts.kind != iter->var->ts.kind
6238       || iter->start->ts.type != iter->var->ts.type)
6239     gfc_convert_type (iter->start, &iter->var->ts, 2);
6240
6241   if (iter->end->ts.kind != iter->var->ts.kind
6242       || iter->end->ts.type != iter->var->ts.type)
6243     gfc_convert_type (iter->end, &iter->var->ts, 2);
6244
6245   if (iter->step->ts.kind != iter->var->ts.kind
6246       || iter->step->ts.type != iter->var->ts.type)
6247     gfc_convert_type (iter->step, &iter->var->ts, 2);
6248
6249   if (iter->start->expr_type == EXPR_CONSTANT
6250       && iter->end->expr_type == EXPR_CONSTANT
6251       && iter->step->expr_type == EXPR_CONSTANT)
6252     {
6253       int sgn, cmp;
6254       if (iter->start->ts.type == BT_INTEGER)
6255         {
6256           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
6257           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
6258         }
6259       else
6260         {
6261           sgn = mpfr_sgn (iter->step->value.real);
6262           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
6263         }
6264       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
6265         gfc_warning ("DO loop at %L will be executed zero times",
6266                      &iter->step->where);
6267     }
6268
6269   return true;
6270 }
6271
6272
6273 /* Traversal function for find_forall_index.  f == 2 signals that
6274    that variable itself is not to be checked - only the references.  */
6275
6276 static bool
6277 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
6278 {
6279   if (expr->expr_type != EXPR_VARIABLE)
6280     return false;
6281
6282   /* A scalar assignment  */
6283   if (!expr->ref || *f == 1)
6284     {
6285       if (expr->symtree->n.sym == sym)
6286         return true;
6287       else
6288         return false;
6289     }
6290
6291   if (*f == 2)
6292     *f = 1;
6293   return false;
6294 }
6295
6296
6297 /* Check whether the FORALL index appears in the expression or not.
6298    Returns true if SYM is found in EXPR.  */
6299
6300 bool
6301 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
6302 {
6303   if (gfc_traverse_expr (expr, sym, forall_index, f))
6304     return true;
6305   else
6306     return false;
6307 }
6308
6309
6310 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
6311    to be a scalar INTEGER variable.  The subscripts and stride are scalar
6312    INTEGERs, and if stride is a constant it must be nonzero.
6313    Furthermore "A subscript or stride in a forall-triplet-spec shall
6314    not contain a reference to any index-name in the
6315    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
6316
6317 static void
6318 resolve_forall_iterators (gfc_forall_iterator *it)
6319 {
6320   gfc_forall_iterator *iter, *iter2;
6321
6322   for (iter = it; iter; iter = iter->next)
6323     {
6324       if (gfc_resolve_expr (iter->var)
6325           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
6326         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
6327                    &iter->var->where);
6328
6329       if (gfc_resolve_expr (iter->start)
6330           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
6331         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
6332                    &iter->start->where);
6333       if (iter->var->ts.kind != iter->start->ts.kind)
6334         gfc_convert_type (iter->start, &iter->var->ts, 1);
6335
6336       if (gfc_resolve_expr (iter->end)
6337           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
6338         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
6339                    &iter->end->where);
6340       if (iter->var->ts.kind != iter->end->ts.kind)
6341         gfc_convert_type (iter->end, &iter->var->ts, 1);
6342
6343       if (gfc_resolve_expr (iter->stride))
6344         {
6345           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
6346             gfc_error ("FORALL stride expression at %L must be a scalar %s",
6347                        &iter->stride->where, "INTEGER");
6348
6349           if (iter->stride->expr_type == EXPR_CONSTANT
6350               && mpz_cmp_ui (iter->stride->value.integer, 0) == 0)
6351             gfc_error ("FORALL stride expression at %L cannot be zero",
6352                        &iter->stride->where);
6353         }
6354       if (iter->var->ts.kind != iter->stride->ts.kind)
6355         gfc_convert_type (iter->stride, &iter->var->ts, 1);
6356     }
6357
6358   for (iter = it; iter; iter = iter->next)
6359     for (iter2 = iter; iter2; iter2 = iter2->next)
6360       {
6361         if (find_forall_index (iter2->start, iter->var->symtree->n.sym, 0)
6362             || find_forall_index (iter2->end, iter->var->symtree->n.sym, 0)
6363             || find_forall_index (iter2->stride, iter->var->symtree->n.sym, 0))
6364           gfc_error ("FORALL index '%s' may not appear in triplet "
6365                      "specification at %L", iter->var->symtree->name,
6366                      &iter2->start->where);
6367       }
6368 }
6369
6370
6371 /* Given a pointer to a symbol that is a derived type, see if it's
6372    inaccessible, i.e. if it's defined in another module and the components are
6373    PRIVATE.  The search is recursive if necessary.  Returns zero if no
6374    inaccessible components are found, nonzero otherwise.  */
6375
6376 static int
6377 derived_inaccessible (gfc_symbol *sym)
6378 {
6379   gfc_component *c;
6380
6381   if (sym->attr.use_assoc && sym->attr.private_comp)
6382     return 1;
6383
6384   for (c = sym->components; c; c = c->next)
6385     {
6386         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
6387           return 1;
6388     }
6389
6390   return 0;
6391 }
6392
6393
6394 /* Resolve the argument of a deallocate expression.  The expression must be
6395    a pointer or a full array.  */
6396
6397 static bool
6398 resolve_deallocate_expr (gfc_expr *e)
6399 {
6400   symbol_attribute attr;
6401   int allocatable, pointer;
6402   gfc_ref *ref;
6403   gfc_symbol *sym;
6404   gfc_component *c;
6405   bool unlimited;
6406
6407   if (!gfc_resolve_expr (e))
6408     return false;
6409
6410   if (e->expr_type != EXPR_VARIABLE)
6411     goto bad;
6412
6413   sym = e->symtree->n.sym;
6414   unlimited = UNLIMITED_POLY(sym);
6415
6416   if (sym->ts.type == BT_CLASS)
6417     {
6418       allocatable = CLASS_DATA (sym)->attr.allocatable;
6419       pointer = CLASS_DATA (sym)->attr.class_pointer;
6420     }
6421   else
6422     {
6423       allocatable = sym->attr.allocatable;
6424       pointer = sym->attr.pointer;
6425     }
6426   for (ref = e->ref; ref; ref = ref->next)
6427     {
6428       switch (ref->type)
6429         {
6430         case REF_ARRAY:
6431           if (ref->u.ar.type != AR_FULL
6432               && !(ref->u.ar.type == AR_ELEMENT && ref->u.ar.as->rank == 0
6433                    && ref->u.ar.codimen && gfc_ref_this_image (ref)))
6434             allocatable = 0;
6435           break;
6436
6437         case REF_COMPONENT:
6438           c = ref->u.c.component;
6439           if (c->ts.type == BT_CLASS)
6440             {
6441               allocatable = CLASS_DATA (c)->attr.allocatable;
6442               pointer = CLASS_DATA (c)->attr.class_pointer;
6443             }
6444           else
6445             {
6446               allocatable = c->attr.allocatable;
6447               pointer = c->attr.pointer;
6448             }
6449           break;
6450
6451         case REF_SUBSTRING:
6452           allocatable = 0;
6453           break;
6454         }
6455     }
6456
6457   attr = gfc_expr_attr (e);
6458
6459   if (allocatable == 0 && attr.pointer == 0 && !unlimited)
6460     {
6461     bad:
6462       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6463                  &e->where);
6464       return false;
6465     }
6466
6467   /* F2008, C644.  */
6468   if (gfc_is_coindexed (e))
6469     {
6470       gfc_error ("Coindexed allocatable object at %L", &e->where);
6471       return false;
6472     }
6473
6474   if (pointer
6475       && !gfc_check_vardef_context (e, true, true, false, 
6476                                     _("DEALLOCATE object")))
6477     return false;
6478   if (!gfc_check_vardef_context (e, false, true, false, 
6479                                  _("DEALLOCATE object")))
6480     return false;
6481
6482   return true;
6483 }
6484
6485
6486 /* Returns true if the expression e contains a reference to the symbol sym.  */
6487 static bool
6488 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6489 {
6490   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6491     return true;
6492
6493   return false;
6494 }
6495
6496 bool
6497 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6498 {
6499   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6500 }
6501
6502
6503 /* Given the expression node e for an allocatable/pointer of derived type to be
6504    allocated, get the expression node to be initialized afterwards (needed for
6505    derived types with default initializers, and derived types with allocatable
6506    components that need nullification.)  */
6507
6508 gfc_expr *
6509 gfc_expr_to_initialize (gfc_expr *e)
6510 {
6511   gfc_expr *result;
6512   gfc_ref *ref;
6513   int i;
6514
6515   result = gfc_copy_expr (e);
6516
6517   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6518   for (ref = result->ref; ref; ref = ref->next)
6519     if (ref->type == REF_ARRAY && ref->next == NULL)
6520       {
6521         ref->u.ar.type = AR_FULL;
6522
6523         for (i = 0; i < ref->u.ar.dimen; i++)
6524           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6525
6526         break;
6527       }
6528
6529   gfc_free_shape (&result->shape, result->rank);
6530
6531   /* Recalculate rank, shape, etc.  */
6532   gfc_resolve_expr (result);
6533   return result;
6534 }
6535
6536
6537 /* If the last ref of an expression is an array ref, return a copy of the
6538    expression with that one removed.  Otherwise, a copy of the original
6539    expression.  This is used for allocate-expressions and pointer assignment
6540    LHS, where there may be an array specification that needs to be stripped
6541    off when using gfc_check_vardef_context.  */
6542
6543 static gfc_expr*
6544 remove_last_array_ref (gfc_expr* e)
6545 {
6546   gfc_expr* e2;
6547   gfc_ref** r;
6548
6549   e2 = gfc_copy_expr (e);
6550   for (r = &e2->ref; *r; r = &(*r)->next)
6551     if ((*r)->type == REF_ARRAY && !(*r)->next)
6552       {
6553         gfc_free_ref_list (*r);
6554         *r = NULL;
6555         break;
6556       }
6557
6558   return e2;
6559 }
6560
6561
6562 /* Used in resolve_allocate_expr to check that a allocation-object and
6563    a source-expr are conformable.  This does not catch all possible
6564    cases; in particular a runtime checking is needed.  */
6565
6566 static bool
6567 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6568 {
6569   gfc_ref *tail;
6570   for (tail = e2->ref; tail && tail->next; tail = tail->next);
6571
6572   /* First compare rank.  */
6573   if (tail && e1->rank != tail->u.ar.as->rank)
6574     {
6575       gfc_error ("Source-expr at %L must be scalar or have the "
6576                  "same rank as the allocate-object at %L",
6577                  &e1->where, &e2->where);
6578       return false;
6579     }
6580
6581   if (e1->shape)
6582     {
6583       int i;
6584       mpz_t s;
6585
6586       mpz_init (s);
6587
6588       for (i = 0; i < e1->rank; i++)
6589         {
6590           if (tail->u.ar.start[i] == NULL)
6591             break;
6592
6593           if (tail->u.ar.end[i])
6594             {
6595               mpz_set (s, tail->u.ar.end[i]->value.integer);
6596               mpz_sub (s, s, tail->u.ar.start[i]->value.integer);
6597               mpz_add_ui (s, s, 1);
6598             }
6599           else
6600             {
6601               mpz_set (s, tail->u.ar.start[i]->value.integer);
6602             }
6603
6604           if (mpz_cmp (e1->shape[i], s) != 0)
6605             {
6606               gfc_error ("Source-expr at %L and allocate-object at %L must "
6607                          "have the same shape", &e1->where, &e2->where);
6608               mpz_clear (s);
6609               return false;
6610             }
6611         }
6612
6613       mpz_clear (s);
6614     }
6615
6616   return true;
6617 }
6618
6619
6620 /* Resolve the expression in an ALLOCATE statement, doing the additional
6621    checks to see whether the expression is OK or not.  The expression must
6622    have a trailing array reference that gives the size of the array.  */
6623
6624 static bool
6625 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6626 {
6627   int i, pointer, allocatable, dimension, is_abstract;
6628   int codimension;
6629   bool coindexed;
6630   bool unlimited;
6631   symbol_attribute attr;
6632   gfc_ref *ref, *ref2;
6633   gfc_expr *e2;
6634   gfc_array_ref *ar;
6635   gfc_symbol *sym = NULL;
6636   gfc_alloc *a;
6637   gfc_component *c;
6638   bool t;
6639
6640   /* Mark the utmost array component as being in allocate to allow DIMEN_STAR
6641      checking of coarrays.  */
6642   for (ref = e->ref; ref; ref = ref->next)
6643     if (ref->next == NULL)
6644       break;
6645
6646   if (ref && ref->type == REF_ARRAY)
6647     ref->u.ar.in_allocate = true;
6648
6649   if (!gfc_resolve_expr (e))
6650     goto failure;
6651
6652   /* Make sure the expression is allocatable or a pointer.  If it is
6653      pointer, the next-to-last reference must be a pointer.  */
6654
6655   ref2 = NULL;
6656   if (e->symtree)
6657     sym = e->symtree->n.sym;
6658
6659   /* Check whether ultimate component is abstract and CLASS.  */
6660   is_abstract = 0;
6661
6662   /* Is the allocate-object unlimited polymorphic?  */
6663   unlimited = UNLIMITED_POLY(e);
6664
6665   if (e->expr_type != EXPR_VARIABLE)
6666     {
6667       allocatable = 0;
6668       attr = gfc_expr_attr (e);
6669       pointer = attr.pointer;
6670       dimension = attr.dimension;
6671       codimension = attr.codimension;
6672     }
6673   else
6674     {
6675       if (sym->ts.type == BT_CLASS && CLASS_DATA (sym))
6676         {
6677           allocatable = CLASS_DATA (sym)->attr.allocatable;
6678           pointer = CLASS_DATA (sym)->attr.class_pointer;
6679           dimension = CLASS_DATA (sym)->attr.dimension;
6680           codimension = CLASS_DATA (sym)->attr.codimension;
6681           is_abstract = CLASS_DATA (sym)->attr.abstract;
6682         }
6683       else
6684         {
6685           allocatable = sym->attr.allocatable;
6686           pointer = sym->attr.pointer;
6687           dimension = sym->attr.dimension;
6688           codimension = sym->attr.codimension;
6689         }
6690
6691       coindexed = false;
6692
6693       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6694         {
6695           switch (ref->type)
6696             {
6697               case REF_ARRAY:
6698                 if (ref->u.ar.codimen > 0)
6699                   {
6700                     int n;
6701                     for (n = ref->u.ar.dimen;
6702                          n < ref->u.ar.dimen + ref->u.ar.codimen; n++)
6703                       if (ref->u.ar.dimen_type[n] != DIMEN_THIS_IMAGE)
6704                         {
6705                           coindexed = true;
6706                           break;
6707                         }
6708                    }
6709
6710                 if (ref->next != NULL)
6711                   pointer = 0;
6712                 break;
6713
6714               case REF_COMPONENT:
6715                 /* F2008, C644.  */
6716                 if (coindexed)
6717                   {
6718                     gfc_error ("Coindexed allocatable object at %L",
6719                                &e->where);
6720                     goto failure;
6721                   }
6722
6723                 c = ref->u.c.component;
6724                 if (c->ts.type == BT_CLASS)
6725                   {
6726                     allocatable = CLASS_DATA (c)->attr.allocatable;
6727                     pointer = CLASS_DATA (c)->attr.class_pointer;
6728                     dimension = CLASS_DATA (c)->attr.dimension;
6729                     codimension = CLASS_DATA (c)->attr.codimension;
6730                     is_abstract = CLASS_DATA (c)->attr.abstract;
6731                   }
6732                 else
6733                   {
6734                     allocatable = c->attr.allocatable;
6735                     pointer = c->attr.pointer;
6736                     dimension = c->attr.dimension;
6737                     codimension = c->attr.codimension;
6738                     is_abstract = c->attr.abstract;
6739                   }
6740                 break;
6741
6742               case REF_SUBSTRING:
6743                 allocatable = 0;
6744                 pointer = 0;
6745                 break;
6746             }
6747         }
6748     }
6749
6750   /* Check for F08:C628.  */
6751   if (allocatable == 0 && pointer == 0 && !unlimited)
6752     {
6753       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6754                  &e->where);
6755       goto failure;
6756     }
6757
6758   /* Some checks for the SOURCE tag.  */
6759   if (code->expr3)
6760     {
6761       /* Check F03:C631.  */
6762       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6763         {
6764           gfc_error ("Type of entity at %L is type incompatible with "
6765                       "source-expr at %L", &e->where, &code->expr3->where);
6766           goto failure;
6767         }
6768
6769       /* Check F03:C632 and restriction following Note 6.18.  */
6770       if (code->expr3->rank > 0 && !unlimited
6771           && !conformable_arrays (code->expr3, e))
6772         goto failure;
6773
6774       /* Check F03:C633.  */
6775       if (code->expr3->ts.kind != e->ts.kind && !unlimited)
6776         {
6777           gfc_error ("The allocate-object at %L and the source-expr at %L "
6778                       "shall have the same kind type parameter",
6779                       &e->where, &code->expr3->where);
6780           goto failure;
6781         }
6782
6783       /* Check F2008, C642.  */
6784       if (code->expr3->ts.type == BT_DERIVED
6785           && ((codimension && gfc_expr_attr (code->expr3).lock_comp)
6786               || (code->expr3->ts.u.derived->from_intmod
6787                      == INTMOD_ISO_FORTRAN_ENV
6788                   && code->expr3->ts.u.derived->intmod_sym_id
6789                      == ISOFORTRAN_LOCK_TYPE)))
6790         {
6791           gfc_error ("The source-expr at %L shall neither be of type "
6792                      "LOCK_TYPE nor have a LOCK_TYPE component if "
6793                       "allocate-object at %L is a coarray",
6794                       &code->expr3->where, &e->where);
6795           goto failure;
6796         }
6797     }
6798
6799   /* Check F08:C629.  */
6800   if (is_abstract && code->ext.alloc.ts.type == BT_UNKNOWN
6801       && !code->expr3)
6802     {
6803       gcc_assert (e->ts.type == BT_CLASS);
6804       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6805                  "type-spec or source-expr", sym->name, &e->where);
6806       goto failure;
6807     }
6808
6809   if (code->ext.alloc.ts.type == BT_CHARACTER && !e->ts.deferred)
6810     {
6811       int cmp = gfc_dep_compare_expr (e->ts.u.cl->length,
6812                                       code->ext.alloc.ts.u.cl->length);
6813       if (cmp == 1 || cmp == -1 || cmp == -3)
6814         {
6815           gfc_error ("Allocating %s at %L with type-spec requires the same "
6816                      "character-length parameter as in the declaration",
6817                      sym->name, &e->where);
6818           goto failure;
6819         }
6820     }
6821
6822   /* In the variable definition context checks, gfc_expr_attr is used
6823      on the expression.  This is fooled by the array specification
6824      present in e, thus we have to eliminate that one temporarily.  */
6825   e2 = remove_last_array_ref (e);
6826   t = true;
6827   if (t && pointer)
6828     t = gfc_check_vardef_context (e2, true, true, false, 
6829                                   _("ALLOCATE object"));
6830   if (t)
6831     t = gfc_check_vardef_context (e2, false, true, false, 
6832                                   _("ALLOCATE object"));
6833   gfc_free_expr (e2);
6834   if (!t)
6835     goto failure;
6836
6837   if (e->ts.type == BT_CLASS && CLASS_DATA (e)->attr.dimension
6838         && !code->expr3 && code->ext.alloc.ts.type == BT_DERIVED)
6839     {
6840       /* For class arrays, the initialization with SOURCE is done
6841          using _copy and trans_call. It is convenient to exploit that
6842          when the allocated type is different from the declared type but
6843          no SOURCE exists by setting expr3.  */
6844       code->expr3 = gfc_default_initializer (&code->ext.alloc.ts);
6845     }
6846   else if (!code->expr3)
6847     {
6848       /* Set up default initializer if needed.  */
6849       gfc_typespec ts;
6850       gfc_expr *init_e;
6851
6852       if (code->ext.alloc.ts.type == BT_DERIVED)
6853         ts = code->ext.alloc.ts;
6854       else
6855         ts = e->ts;
6856
6857       if (ts.type == BT_CLASS)
6858         ts = ts.u.derived->components->ts;
6859
6860       if (ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&ts)))
6861         {
6862           gfc_code *init_st = gfc_get_code ();
6863           init_st->loc = code->loc;
6864           init_st->op = EXEC_INIT_ASSIGN;
6865           init_st->expr1 = gfc_expr_to_initialize (e);
6866           init_st->expr2 = init_e;
6867           init_st->next = code->next;
6868           code->next = init_st;
6869         }
6870     }
6871   else if (code->expr3->mold && code->expr3->ts.type == BT_DERIVED)
6872     {
6873       /* Default initialization via MOLD (non-polymorphic).  */
6874       gfc_expr *rhs = gfc_default_initializer (&code->expr3->ts);
6875       gfc_resolve_expr (rhs);
6876       gfc_free_expr (code->expr3);
6877       code->expr3 = rhs;
6878     }
6879
6880   if (e->ts.type == BT_CLASS && !unlimited && !UNLIMITED_POLY (code->expr3))
6881     {
6882       /* Make sure the vtab symbol is present when
6883          the module variables are generated.  */
6884       gfc_typespec ts = e->ts;
6885       if (code->expr3)
6886         ts = code->expr3->ts;
6887       else if (code->ext.alloc.ts.type == BT_DERIVED)
6888         ts = code->ext.alloc.ts;
6889
6890       gfc_find_derived_vtab (ts.u.derived);
6891
6892       if (dimension)
6893         e = gfc_expr_to_initialize (e);
6894     }
6895   else if (unlimited && !UNLIMITED_POLY (code->expr3))
6896     {
6897       /* Again, make sure the vtab symbol is present when
6898          the module variables are generated.  */
6899       gfc_typespec *ts = NULL;
6900       if (code->expr3)
6901         ts = &code->expr3->ts;
6902       else
6903         ts = &code->ext.alloc.ts;
6904
6905       gcc_assert (ts);
6906
6907       if (ts->type == BT_CLASS || ts->type == BT_DERIVED)
6908         gfc_find_derived_vtab (ts->u.derived);
6909       else
6910         gfc_find_intrinsic_vtab (ts);
6911
6912       if (dimension)
6913         e = gfc_expr_to_initialize (e);
6914     }
6915
6916   if (dimension == 0 && codimension == 0)
6917     goto success;
6918
6919   /* Make sure the last reference node is an array specification.  */
6920
6921   if (!ref2 || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
6922       || (dimension && ref2->u.ar.dimen == 0))
6923     {
6924       gfc_error ("Array specification required in ALLOCATE statement "
6925                  "at %L", &e->where);
6926       goto failure;
6927     }
6928
6929   /* Make sure that the array section reference makes sense in the
6930     context of an ALLOCATE specification.  */
6931
6932   ar = &ref2->u.ar;
6933
6934   if (codimension)
6935     for (i = ar->dimen; i < ar->dimen + ar->codimen; i++)
6936       if (ar->dimen_type[i] == DIMEN_THIS_IMAGE)
6937         {
6938           gfc_error ("Coarray specification required in ALLOCATE statement "
6939                      "at %L", &e->where);
6940           goto failure;
6941         }
6942
6943   for (i = 0; i < ar->dimen; i++)
6944     {
6945       if (ref2->u.ar.type == AR_ELEMENT)
6946         goto check_symbols;
6947
6948       switch (ar->dimen_type[i])
6949         {
6950         case DIMEN_ELEMENT:
6951           break;
6952
6953         case DIMEN_RANGE:
6954           if (ar->start[i] != NULL
6955               && ar->end[i] != NULL
6956               && ar->stride[i] == NULL)
6957             break;
6958
6959           /* Fall Through...  */
6960
6961         case DIMEN_UNKNOWN:
6962         case DIMEN_VECTOR:
6963         case DIMEN_STAR:
6964         case DIMEN_THIS_IMAGE:
6965           gfc_error ("Bad array specification in ALLOCATE statement at %L",
6966                      &e->where);
6967           goto failure;
6968         }
6969
6970 check_symbols:
6971       for (a = code->ext.alloc.list; a; a = a->next)
6972         {
6973           sym = a->expr->symtree->n.sym;
6974
6975           /* TODO - check derived type components.  */
6976           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
6977             continue;
6978
6979           if ((ar->start[i] != NULL
6980                && gfc_find_sym_in_expr (sym, ar->start[i]))
6981               || (ar->end[i] != NULL
6982                   && gfc_find_sym_in_expr (sym, ar->end[i])))
6983             {
6984               gfc_error ("'%s' must not appear in the array specification at "
6985                          "%L in the same ALLOCATE statement where it is "
6986                          "itself allocated", sym->name, &ar->where);
6987               goto failure;
6988             }
6989         }
6990     }
6991
6992   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
6993     {
6994       if (ar->dimen_type[i] == DIMEN_ELEMENT
6995           || ar->dimen_type[i] == DIMEN_RANGE)
6996         {
6997           if (i == (ar->dimen + ar->codimen - 1))
6998             {
6999               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
7000                          "statement at %L", &e->where);
7001               goto failure;
7002             }
7003           continue;
7004         }
7005
7006       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
7007           && ar->stride[i] == NULL)
7008         break;
7009
7010       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
7011                  &e->where);
7012       goto failure;
7013     }
7014
7015 success:
7016   return true;
7017
7018 failure:
7019   return false;
7020 }
7021
7022 static void
7023 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
7024 {
7025   gfc_expr *stat, *errmsg, *pe, *qe;
7026   gfc_alloc *a, *p, *q;
7027
7028   stat = code->expr1;
7029   errmsg = code->expr2;
7030
7031   /* Check the stat variable.  */
7032   if (stat)
7033     {
7034       gfc_check_vardef_context (stat, false, false, false, 
7035                                 _("STAT variable"));
7036
7037       if ((stat->ts.type != BT_INTEGER
7038            && !(stat->ref && (stat->ref->type == REF_ARRAY
7039                               || stat->ref->type == REF_COMPONENT)))
7040           || stat->rank > 0)
7041         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
7042                    "variable", &stat->where);
7043
7044       for (p = code->ext.alloc.list; p; p = p->next)
7045         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
7046           {
7047             gfc_ref *ref1, *ref2;
7048             bool found = true;
7049
7050             for (ref1 = p->expr->ref, ref2 = stat->ref; ref1 && ref2;
7051                  ref1 = ref1->next, ref2 = ref2->next)
7052               {
7053                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7054                   continue;
7055                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7056                   {
7057                     found = false;
7058                     break;
7059                   }
7060               }
7061
7062             if (found)
7063               {
7064                 gfc_error ("Stat-variable at %L shall not be %sd within "
7065                            "the same %s statement", &stat->where, fcn, fcn);
7066                 break;
7067               }
7068           }
7069     }
7070
7071   /* Check the errmsg variable.  */
7072   if (errmsg)
7073     {
7074       if (!stat)
7075         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
7076                      &errmsg->where);
7077
7078       gfc_check_vardef_context (errmsg, false, false, false,
7079                                 _("ERRMSG variable"));
7080
7081       if ((errmsg->ts.type != BT_CHARACTER
7082            && !(errmsg->ref
7083                 && (errmsg->ref->type == REF_ARRAY
7084                     || errmsg->ref->type == REF_COMPONENT)))
7085           || errmsg->rank > 0 )
7086         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
7087                    "variable", &errmsg->where);
7088
7089       for (p = code->ext.alloc.list; p; p = p->next)
7090         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
7091           {
7092             gfc_ref *ref1, *ref2;
7093             bool found = true;
7094
7095             for (ref1 = p->expr->ref, ref2 = errmsg->ref; ref1 && ref2;
7096                  ref1 = ref1->next, ref2 = ref2->next)
7097               {
7098                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7099                   continue;
7100                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7101                   {
7102                     found = false;
7103                     break;
7104                   }
7105               }
7106
7107             if (found)
7108               {
7109                 gfc_error ("Errmsg-variable at %L shall not be %sd within "
7110                            "the same %s statement", &errmsg->where, fcn, fcn);
7111                 break;
7112               }
7113           }
7114     }
7115
7116   /* Check that an allocate-object appears only once in the statement.  */
7117
7118   for (p = code->ext.alloc.list; p; p = p->next)
7119     {
7120       pe = p->expr;
7121       for (q = p->next; q; q = q->next)
7122         {
7123           qe = q->expr;
7124           if (pe->symtree->n.sym->name == qe->symtree->n.sym->name)
7125             {
7126               /* This is a potential collision.  */
7127               gfc_ref *pr = pe->ref;
7128               gfc_ref *qr = qe->ref;
7129
7130               /* Follow the references  until
7131                  a) They start to differ, in which case there is no error;
7132                  you can deallocate a%b and a%c in a single statement
7133                  b) Both of them stop, which is an error
7134                  c) One of them stops, which is also an error.  */
7135               while (1)
7136                 {
7137                   if (pr == NULL && qr == NULL)
7138                     {
7139                       gfc_error ("Allocate-object at %L also appears at %L",
7140                                  &pe->where, &qe->where);
7141                       break;
7142                     }
7143                   else if (pr != NULL && qr == NULL)
7144                     {
7145                       gfc_error ("Allocate-object at %L is subobject of"
7146                                  " object at %L", &pe->where, &qe->where);
7147                       break;
7148                     }
7149                   else if (pr == NULL && qr != NULL)
7150                     {
7151                       gfc_error ("Allocate-object at %L is subobject of"
7152                                  " object at %L", &qe->where, &pe->where);
7153                       break;
7154                     }
7155                   /* Here, pr != NULL && qr != NULL  */
7156                   gcc_assert(pr->type == qr->type);
7157                   if (pr->type == REF_ARRAY)
7158                     {
7159                       /* Handle cases like allocate(v(3)%x(3), v(2)%x(3)),
7160                          which are legal.  */
7161                       gcc_assert (qr->type == REF_ARRAY);
7162
7163                       if (pr->next && qr->next)
7164                         {
7165                           int i;
7166                           gfc_array_ref *par = &(pr->u.ar);
7167                           gfc_array_ref *qar = &(qr->u.ar);
7168
7169                           for (i=0; i<par->dimen; i++)
7170                             {
7171                               if ((par->start[i] != NULL
7172                                    || qar->start[i] != NULL)
7173                                   && gfc_dep_compare_expr (par->start[i],
7174                                                            qar->start[i]) != 0)
7175                                 goto break_label;
7176                             }
7177                         }
7178                     }
7179                   else
7180                     {
7181                       if (pr->u.c.component->name != qr->u.c.component->name)
7182                         break;
7183                     }
7184
7185                   pr = pr->next;
7186                   qr = qr->next;
7187                 }
7188             break_label:
7189               ;
7190             }
7191         }
7192     }
7193
7194   if (strcmp (fcn, "ALLOCATE") == 0)
7195     {
7196       for (a = code->ext.alloc.list; a; a = a->next)
7197         resolve_allocate_expr (a->expr, code);
7198     }
7199   else
7200     {
7201       for (a = code->ext.alloc.list; a; a = a->next)
7202         resolve_deallocate_expr (a->expr);
7203     }
7204 }
7205
7206
7207 /************ SELECT CASE resolution subroutines ************/
7208
7209 /* Callback function for our mergesort variant.  Determines interval
7210    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
7211    op1 > op2.  Assumes we're not dealing with the default case.
7212    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
7213    There are nine situations to check.  */
7214
7215 static int
7216 compare_cases (const gfc_case *op1, const gfc_case *op2)
7217 {
7218   int retval;
7219
7220   if (op1->low == NULL) /* op1 = (:L)  */
7221     {
7222       /* op2 = (:N), so overlap.  */
7223       retval = 0;
7224       /* op2 = (M:) or (M:N),  L < M  */
7225       if (op2->low != NULL
7226           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7227         retval = -1;
7228     }
7229   else if (op1->high == NULL) /* op1 = (K:)  */
7230     {
7231       /* op2 = (M:), so overlap.  */
7232       retval = 0;
7233       /* op2 = (:N) or (M:N), K > N  */
7234       if (op2->high != NULL
7235           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7236         retval = 1;
7237     }
7238   else /* op1 = (K:L)  */
7239     {
7240       if (op2->low == NULL)       /* op2 = (:N), K > N  */
7241         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7242                  ? 1 : 0;
7243       else if (op2->high == NULL) /* op2 = (M:), L < M  */
7244         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7245                  ? -1 : 0;
7246       else                      /* op2 = (M:N)  */
7247         {
7248           retval =  0;
7249           /* L < M  */
7250           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7251             retval =  -1;
7252           /* K > N  */
7253           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7254             retval =  1;
7255         }
7256     }
7257
7258   return retval;
7259 }
7260
7261
7262 /* Merge-sort a double linked case list, detecting overlap in the
7263    process.  LIST is the head of the double linked case list before it
7264    is sorted.  Returns the head of the sorted list if we don't see any
7265    overlap, or NULL otherwise.  */
7266
7267 static gfc_case *
7268 check_case_overlap (gfc_case *list)
7269 {
7270   gfc_case *p, *q, *e, *tail;
7271   int insize, nmerges, psize, qsize, cmp, overlap_seen;
7272
7273   /* If the passed list was empty, return immediately.  */
7274   if (!list)
7275     return NULL;
7276
7277   overlap_seen = 0;
7278   insize = 1;
7279
7280   /* Loop unconditionally.  The only exit from this loop is a return
7281      statement, when we've finished sorting the case list.  */
7282   for (;;)
7283     {
7284       p = list;
7285       list = NULL;
7286       tail = NULL;
7287
7288       /* Count the number of merges we do in this pass.  */
7289       nmerges = 0;
7290
7291       /* Loop while there exists a merge to be done.  */
7292       while (p)
7293         {
7294           int i;
7295
7296           /* Count this merge.  */
7297           nmerges++;
7298
7299           /* Cut the list in two pieces by stepping INSIZE places
7300              forward in the list, starting from P.  */
7301           psize = 0;
7302           q = p;
7303           for (i = 0; i < insize; i++)
7304             {
7305               psize++;
7306               q = q->right;
7307               if (!q)
7308                 break;
7309             }
7310           qsize = insize;
7311
7312           /* Now we have two lists.  Merge them!  */
7313           while (psize > 0 || (qsize > 0 && q != NULL))
7314             {
7315               /* See from which the next case to merge comes from.  */
7316               if (psize == 0)
7317                 {
7318                   /* P is empty so the next case must come from Q.  */
7319                   e = q;
7320                   q = q->right;
7321                   qsize--;
7322                 }
7323               else if (qsize == 0 || q == NULL)
7324                 {
7325                   /* Q is empty.  */
7326                   e = p;
7327                   p = p->right;
7328                   psize--;
7329                 }
7330               else
7331                 {
7332                   cmp = compare_cases (p, q);
7333                   if (cmp < 0)
7334                     {
7335                       /* The whole case range for P is less than the
7336                          one for Q.  */
7337                       e = p;
7338                       p = p->right;
7339                       psize--;
7340                     }
7341                   else if (cmp > 0)
7342                     {
7343                       /* The whole case range for Q is greater than
7344                          the case range for P.  */
7345                       e = q;
7346                       q = q->right;
7347                       qsize--;
7348                     }
7349                   else
7350                     {
7351                       /* The cases overlap, or they are the same
7352                          element in the list.  Either way, we must
7353                          issue an error and get the next case from P.  */
7354                       /* FIXME: Sort P and Q by line number.  */
7355                       gfc_error ("CASE label at %L overlaps with CASE "
7356                                  "label at %L", &p->where, &q->where);
7357                       overlap_seen = 1;
7358                       e = p;
7359                       p = p->right;
7360                       psize--;
7361                     }
7362                 }
7363
7364                 /* Add the next element to the merged list.  */
7365               if (tail)
7366                 tail->right = e;
7367               else
7368                 list = e;
7369               e->left = tail;
7370               tail = e;
7371             }
7372
7373           /* P has now stepped INSIZE places along, and so has Q.  So
7374              they're the same.  */
7375           p = q;
7376         }
7377       tail->right = NULL;
7378
7379       /* If we have done only one merge or none at all, we've
7380          finished sorting the cases.  */
7381       if (nmerges <= 1)
7382         {
7383           if (!overlap_seen)
7384             return list;
7385           else
7386             return NULL;
7387         }
7388
7389       /* Otherwise repeat, merging lists twice the size.  */
7390       insize *= 2;
7391     }
7392 }
7393
7394
7395 /* Check to see if an expression is suitable for use in a CASE statement.
7396    Makes sure that all case expressions are scalar constants of the same
7397    type.  Return false if anything is wrong.  */
7398
7399 static bool
7400 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
7401 {
7402   if (e == NULL) return true;
7403
7404   if (e->ts.type != case_expr->ts.type)
7405     {
7406       gfc_error ("Expression in CASE statement at %L must be of type %s",
7407                  &e->where, gfc_basic_typename (case_expr->ts.type));
7408       return false;
7409     }
7410
7411   /* C805 (R808) For a given case-construct, each case-value shall be of
7412      the same type as case-expr.  For character type, length differences
7413      are allowed, but the kind type parameters shall be the same.  */
7414
7415   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
7416     {
7417       gfc_error ("Expression in CASE statement at %L must be of kind %d",
7418                  &e->where, case_expr->ts.kind);
7419       return false;
7420     }
7421
7422   /* Convert the case value kind to that of case expression kind,
7423      if needed */
7424
7425   if (e->ts.kind != case_expr->ts.kind)
7426     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
7427
7428   if (e->rank != 0)
7429     {
7430       gfc_error ("Expression in CASE statement at %L must be scalar",
7431                  &e->where);
7432       return false;
7433     }
7434
7435   return true;
7436 }
7437
7438
7439 /* Given a completely parsed select statement, we:
7440
7441      - Validate all expressions and code within the SELECT.
7442      - Make sure that the selection expression is not of the wrong type.
7443      - Make sure that no case ranges overlap.
7444      - Eliminate unreachable cases and unreachable code resulting from
7445        removing case labels.
7446
7447    The standard does allow unreachable cases, e.g. CASE (5:3).  But
7448    they are a hassle for code generation, and to prevent that, we just
7449    cut them out here.  This is not necessary for overlapping cases
7450    because they are illegal and we never even try to generate code.
7451
7452    We have the additional caveat that a SELECT construct could have
7453    been a computed GOTO in the source code. Fortunately we can fairly
7454    easily work around that here: The case_expr for a "real" SELECT CASE
7455    is in code->expr1, but for a computed GOTO it is in code->expr2. All
7456    we have to do is make sure that the case_expr is a scalar integer
7457    expression.  */
7458
7459 static void
7460 resolve_select (gfc_code *code, bool select_type)
7461 {
7462   gfc_code *body;
7463   gfc_expr *case_expr;
7464   gfc_case *cp, *default_case, *tail, *head;
7465   int seen_unreachable;
7466   int seen_logical;
7467   int ncases;
7468   bt type;
7469   bool t;
7470
7471   if (code->expr1 == NULL)
7472     {
7473       /* This was actually a computed GOTO statement.  */
7474       case_expr = code->expr2;
7475       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
7476         gfc_error ("Selection expression in computed GOTO statement "
7477                    "at %L must be a scalar integer expression",
7478                    &case_expr->where);
7479
7480       /* Further checking is not necessary because this SELECT was built
7481          by the compiler, so it should always be OK.  Just move the
7482          case_expr from expr2 to expr so that we can handle computed
7483          GOTOs as normal SELECTs from here on.  */
7484       code->expr1 = code->expr2;
7485       code->expr2 = NULL;
7486       return;
7487     }
7488
7489   case_expr = code->expr1;
7490   type = case_expr->ts.type;
7491
7492   /* F08:C830.  */
7493   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
7494     {
7495       gfc_error ("Argument of SELECT statement at %L cannot be %s",
7496                  &case_expr->where, gfc_typename (&case_expr->ts));
7497
7498       /* Punt. Going on here just produce more garbage error messages.  */
7499       return;
7500     }
7501
7502   /* F08:R842.  */
7503   if (!select_type && case_expr->rank != 0)
7504     {
7505       gfc_error ("Argument of SELECT statement at %L must be a scalar "
7506                  "expression", &case_expr->where);
7507
7508       /* Punt.  */
7509       return;
7510     }
7511
7512   /* Raise a warning if an INTEGER case value exceeds the range of
7513      the case-expr. Later, all expressions will be promoted to the
7514      largest kind of all case-labels.  */
7515
7516   if (type == BT_INTEGER)
7517     for (body = code->block; body; body = body->block)
7518       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7519         {
7520           if (cp->low
7521               && gfc_check_integer_range (cp->low->value.integer,
7522                                           case_expr->ts.kind) != ARITH_OK)
7523             gfc_warning ("Expression in CASE statement at %L is "
7524                          "not in the range of %s", &cp->low->where,
7525                          gfc_typename (&case_expr->ts));
7526
7527           if (cp->high
7528               && cp->low != cp->high
7529               && gfc_check_integer_range (cp->high->value.integer,
7530                                           case_expr->ts.kind) != ARITH_OK)
7531             gfc_warning ("Expression in CASE statement at %L is "
7532                          "not in the range of %s", &cp->high->where,
7533                          gfc_typename (&case_expr->ts));
7534         }
7535
7536   /* PR 19168 has a long discussion concerning a mismatch of the kinds
7537      of the SELECT CASE expression and its CASE values.  Walk the lists
7538      of case values, and if we find a mismatch, promote case_expr to
7539      the appropriate kind.  */
7540
7541   if (type == BT_LOGICAL || type == BT_INTEGER)
7542     {
7543       for (body = code->block; body; body = body->block)
7544         {
7545           /* Walk the case label list.  */
7546           for (cp = body->ext.block.case_list; cp; cp = cp->next)
7547             {
7548               /* Intercept the DEFAULT case.  It does not have a kind.  */
7549               if (cp->low == NULL && cp->high == NULL)
7550                 continue;
7551
7552               /* Unreachable case ranges are discarded, so ignore.  */
7553               if (cp->low != NULL && cp->high != NULL
7554                   && cp->low != cp->high
7555                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7556                 continue;
7557
7558               if (cp->low != NULL
7559                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
7560                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
7561
7562               if (cp->high != NULL
7563                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
7564                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
7565             }
7566          }
7567     }
7568
7569   /* Assume there is no DEFAULT case.  */
7570   default_case = NULL;
7571   head = tail = NULL;
7572   ncases = 0;
7573   seen_logical = 0;
7574
7575   for (body = code->block; body; body = body->block)
7576     {
7577       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
7578       t = true;
7579       seen_unreachable = 0;
7580
7581       /* Walk the case label list, making sure that all case labels
7582          are legal.  */
7583       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7584         {
7585           /* Count the number of cases in the whole construct.  */
7586           ncases++;
7587
7588           /* Intercept the DEFAULT case.  */
7589           if (cp->low == NULL && cp->high == NULL)
7590             {
7591               if (default_case != NULL)
7592                 {
7593                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
7594                              "by a second DEFAULT CASE at %L",
7595                              &default_case->where, &cp->where);
7596                   t = false;
7597                   break;
7598                 }
7599               else
7600                 {
7601                   default_case = cp;
7602                   continue;
7603                 }
7604             }
7605
7606           /* Deal with single value cases and case ranges.  Errors are
7607              issued from the validation function.  */
7608           if (!validate_case_label_expr (cp->low, case_expr)
7609               || !validate_case_label_expr (cp->high, case_expr))
7610             {
7611               t = false;
7612               break;
7613             }
7614
7615           if (type == BT_LOGICAL
7616               && ((cp->low == NULL || cp->high == NULL)
7617                   || cp->low != cp->high))
7618             {
7619               gfc_error ("Logical range in CASE statement at %L is not "
7620                          "allowed", &cp->low->where);
7621               t = false;
7622               break;
7623             }
7624
7625           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
7626             {
7627               int value;
7628               value = cp->low->value.logical == 0 ? 2 : 1;
7629               if (value & seen_logical)
7630                 {
7631                   gfc_error ("Constant logical value in CASE statement "
7632                              "is repeated at %L",
7633                              &cp->low->where);
7634                   t = false;
7635                   break;
7636                 }
7637               seen_logical |= value;
7638             }
7639
7640           if (cp->low != NULL && cp->high != NULL
7641               && cp->low != cp->high
7642               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7643             {
7644               if (gfc_option.warn_surprising)
7645                 gfc_warning ("Range specification at %L can never "
7646                              "be matched", &cp->where);
7647
7648               cp->unreachable = 1;
7649               seen_unreachable = 1;
7650             }
7651           else
7652             {
7653               /* If the case range can be matched, it can also overlap with
7654                  other cases.  To make sure it does not, we put it in a
7655                  double linked list here.  We sort that with a merge sort
7656                  later on to detect any overlapping cases.  */
7657               if (!head)
7658                 {
7659                   head = tail = cp;
7660                   head->right = head->left = NULL;
7661                 }
7662               else
7663                 {
7664                   tail->right = cp;
7665                   tail->right->left = tail;
7666                   tail = tail->right;
7667                   tail->right = NULL;
7668                 }
7669             }
7670         }
7671
7672       /* It there was a failure in the previous case label, give up
7673          for this case label list.  Continue with the next block.  */
7674       if (!t)
7675         continue;
7676
7677       /* See if any case labels that are unreachable have been seen.
7678          If so, we eliminate them.  This is a bit of a kludge because
7679          the case lists for a single case statement (label) is a
7680          single forward linked lists.  */
7681       if (seen_unreachable)
7682       {
7683         /* Advance until the first case in the list is reachable.  */
7684         while (body->ext.block.case_list != NULL
7685                && body->ext.block.case_list->unreachable)
7686           {
7687             gfc_case *n = body->ext.block.case_list;
7688             body->ext.block.case_list = body->ext.block.case_list->next;
7689             n->next = NULL;
7690             gfc_free_case_list (n);
7691           }
7692
7693         /* Strip all other unreachable cases.  */
7694         if (body->ext.block.case_list)
7695           {
7696             for (cp = body->ext.block.case_list; cp->next; cp = cp->next)
7697               {
7698                 if (cp->next->unreachable)
7699                   {
7700                     gfc_case *n = cp->next;
7701                     cp->next = cp->next->next;
7702                     n->next = NULL;
7703                     gfc_free_case_list (n);
7704                   }
7705               }
7706           }
7707       }
7708     }
7709
7710   /* See if there were overlapping cases.  If the check returns NULL,
7711      there was overlap.  In that case we don't do anything.  If head
7712      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7713      then used during code generation for SELECT CASE constructs with
7714      a case expression of a CHARACTER type.  */
7715   if (head)
7716     {
7717       head = check_case_overlap (head);
7718
7719       /* Prepend the default_case if it is there.  */
7720       if (head != NULL && default_case)
7721         {
7722           default_case->left = NULL;
7723           default_case->right = head;
7724           head->left = default_case;
7725         }
7726     }
7727
7728   /* Eliminate dead blocks that may be the result if we've seen
7729      unreachable case labels for a block.  */
7730   for (body = code; body && body->block; body = body->block)
7731     {
7732       if (body->block->ext.block.case_list == NULL)
7733         {
7734           /* Cut the unreachable block from the code chain.  */
7735           gfc_code *c = body->block;
7736           body->block = c->block;
7737
7738           /* Kill the dead block, but not the blocks below it.  */
7739           c->block = NULL;
7740           gfc_free_statements (c);
7741         }
7742     }
7743
7744   /* More than two cases is legal but insane for logical selects.
7745      Issue a warning for it.  */
7746   if (gfc_option.warn_surprising && type == BT_LOGICAL
7747       && ncases > 2)
7748     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7749                  &code->loc);
7750 }
7751
7752
7753 /* Check if a derived type is extensible.  */
7754
7755 bool
7756 gfc_type_is_extensible (gfc_symbol *sym)
7757 {
7758   return !(sym->attr.is_bind_c || sym->attr.sequence
7759            || (sym->attr.is_class
7760                && sym->components->ts.u.derived->attr.unlimited_polymorphic));
7761 }
7762
7763
7764 /* Resolve an associate-name:  Resolve target and ensure the type-spec is
7765    correct as well as possibly the array-spec.  */
7766
7767 static void
7768 resolve_assoc_var (gfc_symbol* sym, bool resolve_target)
7769 {
7770   gfc_expr* target;
7771
7772   gcc_assert (sym->assoc);
7773   gcc_assert (sym->attr.flavor == FL_VARIABLE);
7774
7775   /* If this is for SELECT TYPE, the target may not yet be set.  In that
7776      case, return.  Resolution will be called later manually again when
7777      this is done.  */
7778   target = sym->assoc->target;
7779   if (!target)
7780     return;
7781   gcc_assert (!sym->assoc->dangling);
7782
7783   if (resolve_target && !gfc_resolve_expr (target))
7784     return;
7785
7786   /* For variable targets, we get some attributes from the target.  */
7787   if (target->expr_type == EXPR_VARIABLE)
7788     {
7789       gfc_symbol* tsym;
7790
7791       gcc_assert (target->symtree);
7792       tsym = target->symtree->n.sym;
7793
7794       sym->attr.asynchronous = tsym->attr.asynchronous;
7795       sym->attr.volatile_ = tsym->attr.volatile_;
7796
7797       sym->attr.target = tsym->attr.target
7798                          || gfc_expr_attr (target).pointer;
7799     }
7800
7801   /* Get type if this was not already set.  Note that it can be
7802      some other type than the target in case this is a SELECT TYPE
7803      selector!  So we must not update when the type is already there.  */
7804   if (sym->ts.type == BT_UNKNOWN)
7805     sym->ts = target->ts;
7806   gcc_assert (sym->ts.type != BT_UNKNOWN);
7807
7808   /* See if this is a valid association-to-variable.  */
7809   sym->assoc->variable = (target->expr_type == EXPR_VARIABLE
7810                           && !gfc_has_vector_subscript (target));
7811
7812   /* Finally resolve if this is an array or not.  */
7813   if (sym->attr.dimension && target->rank == 0)
7814     {
7815       gfc_error ("Associate-name '%s' at %L is used as array",
7816                  sym->name, &sym->declared_at);
7817       sym->attr.dimension = 0;
7818       return;
7819     }
7820
7821   /* We cannot deal with class selectors that need temporaries.  */
7822   if (target->ts.type == BT_CLASS
7823         && gfc_ref_needs_temporary_p (target->ref))
7824     {
7825       gfc_error ("CLASS selector at %L needs a temporary which is not "
7826                  "yet implemented", &target->where);
7827       return;
7828     }
7829
7830   if (target->ts.type != BT_CLASS && target->rank > 0)
7831     sym->attr.dimension = 1;
7832   else if (target->ts.type == BT_CLASS)
7833     gfc_fix_class_refs (target);
7834
7835   /* The associate-name will have a correct type by now. Make absolutely
7836      sure that it has not picked up a dimension attribute.  */
7837   if (sym->ts.type == BT_CLASS)
7838     sym->attr.dimension = 0;
7839
7840   if (sym->attr.dimension)
7841     {
7842       sym->as = gfc_get_array_spec ();
7843       sym->as->rank = target->rank;
7844       sym->as->type = AS_DEFERRED;
7845
7846       /* Target must not be coindexed, thus the associate-variable
7847          has no corank.  */
7848       sym->as->corank = 0;
7849     }
7850
7851   /* Mark this as an associate variable.  */
7852   sym->attr.associate_var = 1;
7853
7854   /* If the target is a good class object, so is the associate variable.  */
7855   if (sym->ts.type == BT_CLASS && gfc_expr_attr (target).class_ok)
7856     sym->attr.class_ok = 1;
7857 }
7858
7859
7860 /* Resolve a SELECT TYPE statement.  */
7861
7862 static void
7863 resolve_select_type (gfc_code *code, gfc_namespace *old_ns)
7864 {
7865   gfc_symbol *selector_type;
7866   gfc_code *body, *new_st, *if_st, *tail;
7867   gfc_code *class_is = NULL, *default_case = NULL;
7868   gfc_case *c;
7869   gfc_symtree *st;
7870   char name[GFC_MAX_SYMBOL_LEN];
7871   gfc_namespace *ns;
7872   int error = 0;
7873   int charlen = 0;
7874
7875   ns = code->ext.block.ns;
7876   gfc_resolve (ns);
7877
7878   /* Check for F03:C813.  */
7879   if (code->expr1->ts.type != BT_CLASS
7880       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
7881     {
7882       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
7883                  "at %L", &code->loc);
7884       return;
7885     }
7886
7887   if (!code->expr1->symtree->n.sym->attr.class_ok)
7888     return;
7889
7890   if (code->expr2)
7891     {
7892       if (code->expr1->symtree->n.sym->attr.untyped)
7893         code->expr1->symtree->n.sym->ts = code->expr2->ts;
7894       selector_type = CLASS_DATA (code->expr2)->ts.u.derived;
7895
7896       /* F2008: C803 The selector expression must not be coindexed.  */
7897       if (gfc_is_coindexed (code->expr2))
7898         {
7899           gfc_error ("Selector at %L must not be coindexed",
7900                      &code->expr2->where);
7901           return;
7902         }
7903
7904     }
7905   else
7906     {
7907       selector_type = CLASS_DATA (code->expr1)->ts.u.derived;
7908
7909       if (gfc_is_coindexed (code->expr1))
7910         {
7911           gfc_error ("Selector at %L must not be coindexed",
7912                      &code->expr1->where);
7913           return;
7914         }
7915     }
7916
7917   /* Loop over TYPE IS / CLASS IS cases.  */
7918   for (body = code->block; body; body = body->block)
7919     {
7920       c = body->ext.block.case_list;
7921
7922       /* Check F03:C815.  */
7923       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7924           && !selector_type->attr.unlimited_polymorphic
7925           && !gfc_type_is_extensible (c->ts.u.derived))
7926         {
7927           gfc_error ("Derived type '%s' at %L must be extensible",
7928                      c->ts.u.derived->name, &c->where);
7929           error++;
7930           continue;
7931         }
7932
7933       /* Check F03:C816.  */
7934       if (c->ts.type != BT_UNKNOWN && !selector_type->attr.unlimited_polymorphic
7935           && ((c->ts.type != BT_DERIVED && c->ts.type != BT_CLASS)
7936               || !gfc_type_is_extension_of (selector_type, c->ts.u.derived)))
7937         {
7938           if (c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7939             gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
7940                        c->ts.u.derived->name, &c->where, selector_type->name);
7941           else
7942             gfc_error ("Unexpected intrinsic type '%s' at %L",
7943                        gfc_basic_typename (c->ts.type), &c->where);
7944           error++;
7945           continue;
7946         }
7947
7948       /* Check F03:C814.  */
7949       if (c->ts.type == BT_CHARACTER && c->ts.u.cl->length != NULL)
7950         {
7951           gfc_error ("The type-spec at %L shall specify that each length "
7952                      "type parameter is assumed", &c->where);
7953           error++;
7954           continue;
7955         }
7956
7957       /* Intercept the DEFAULT case.  */
7958       if (c->ts.type == BT_UNKNOWN)
7959         {
7960           /* Check F03:C818.  */
7961           if (default_case)
7962             {
7963               gfc_error ("The DEFAULT CASE at %L cannot be followed "
7964                          "by a second DEFAULT CASE at %L",
7965                          &default_case->ext.block.case_list->where, &c->where);
7966               error++;
7967               continue;
7968             }
7969
7970           default_case = body;
7971         }
7972     }
7973
7974   if (error > 0)
7975     return;
7976
7977   /* Transform SELECT TYPE statement to BLOCK and associate selector to
7978      target if present.  If there are any EXIT statements referring to the
7979      SELECT TYPE construct, this is no problem because the gfc_code
7980      reference stays the same and EXIT is equally possible from the BLOCK
7981      it is changed to.  */
7982   code->op = EXEC_BLOCK;
7983   if (code->expr2)
7984     {
7985       gfc_association_list* assoc;
7986
7987       assoc = gfc_get_association_list ();
7988       assoc->st = code->expr1->symtree;
7989       assoc->target = gfc_copy_expr (code->expr2);
7990       assoc->target->where = code->expr2->where;
7991       /* assoc->variable will be set by resolve_assoc_var.  */
7992
7993       code->ext.block.assoc = assoc;
7994       code->expr1->symtree->n.sym->assoc = assoc;
7995
7996       resolve_assoc_var (code->expr1->symtree->n.sym, false);
7997     }
7998   else
7999     code->ext.block.assoc = NULL;
8000
8001   /* Add EXEC_SELECT to switch on type.  */
8002   new_st = gfc_get_code ();
8003   new_st->op = code->op;
8004   new_st->expr1 = code->expr1;
8005   new_st->expr2 = code->expr2;
8006   new_st->block = code->block;
8007   code->expr1 = code->expr2 =  NULL;
8008   code->block = NULL;
8009   if (!ns->code)
8010     ns->code = new_st;
8011   else
8012     ns->code->next = new_st;
8013   code = new_st;
8014   code->op = EXEC_SELECT;
8015
8016   gfc_add_vptr_component (code->expr1);
8017   gfc_add_hash_component (code->expr1);
8018
8019   /* Loop over TYPE IS / CLASS IS cases.  */
8020   for (body = code->block; body; body = body->block)
8021     {
8022       c = body->ext.block.case_list;
8023
8024       if (c->ts.type == BT_DERIVED)
8025         c->low = c->high = gfc_get_int_expr (gfc_default_integer_kind, NULL,
8026                                              c->ts.u.derived->hash_value);
8027       else if (c->ts.type != BT_CLASS && c->ts.type != BT_UNKNOWN)
8028         {
8029           gfc_symbol *ivtab;
8030           gfc_expr *e;
8031
8032           ivtab = gfc_find_intrinsic_vtab (&c->ts);
8033           gcc_assert (ivtab && CLASS_DATA (ivtab)->initializer);
8034           e = CLASS_DATA (ivtab)->initializer;
8035           c->low = c->high = gfc_copy_expr (e);
8036         }
8037
8038       else if (c->ts.type == BT_UNKNOWN)
8039         continue;
8040
8041       /* Associate temporary to selector.  This should only be done
8042          when this case is actually true, so build a new ASSOCIATE
8043          that does precisely this here (instead of using the
8044          'global' one).  */
8045
8046       if (c->ts.type == BT_CLASS)
8047         sprintf (name, "__tmp_class_%s", c->ts.u.derived->name);
8048       else if (c->ts.type == BT_DERIVED)
8049         sprintf (name, "__tmp_type_%s", c->ts.u.derived->name);
8050       else if (c->ts.type == BT_CHARACTER)
8051         {
8052           if (c->ts.u.cl && c->ts.u.cl->length
8053               && c->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8054             charlen = mpz_get_si (c->ts.u.cl->length->value.integer);
8055           sprintf (name, "__tmp_%s_%d_%d", gfc_basic_typename (c->ts.type),
8056                    charlen, c->ts.kind);
8057         }
8058       else
8059         sprintf (name, "__tmp_%s_%d", gfc_basic_typename (c->ts.type),
8060                  c->ts.kind);
8061
8062       st = gfc_find_symtree (ns->sym_root, name);
8063       gcc_assert (st->n.sym->assoc);
8064       st->n.sym->assoc->target = gfc_get_variable_expr (code->expr1->symtree);
8065       st->n.sym->assoc->target->where = code->expr1->where;
8066       if (c->ts.type != BT_CLASS && c->ts.type != BT_UNKNOWN)
8067         gfc_add_data_component (st->n.sym->assoc->target);
8068
8069       new_st = gfc_get_code ();
8070       new_st->op = EXEC_BLOCK;
8071       new_st->ext.block.ns = gfc_build_block_ns (ns);
8072       new_st->ext.block.ns->code = body->next;
8073       body->next = new_st;
8074
8075       /* Chain in the new list only if it is marked as dangling.  Otherwise
8076          there is a CASE label overlap and this is already used.  Just ignore,
8077          the error is diagnosed elsewhere.  */
8078       if (st->n.sym->assoc->dangling)
8079         {
8080           new_st->ext.block.assoc = st->n.sym->assoc;
8081           st->n.sym->assoc->dangling = 0;
8082         }
8083
8084       resolve_assoc_var (st->n.sym, false);
8085     }
8086
8087   /* Take out CLASS IS cases for separate treatment.  */
8088   body = code;
8089   while (body && body->block)
8090     {
8091       if (body->block->ext.block.case_list->ts.type == BT_CLASS)
8092         {
8093           /* Add to class_is list.  */
8094           if (class_is == NULL)
8095             {
8096               class_is = body->block;
8097               tail = class_is;
8098             }
8099           else
8100             {
8101               for (tail = class_is; tail->block; tail = tail->block) ;
8102               tail->block = body->block;
8103               tail = tail->block;
8104             }
8105           /* Remove from EXEC_SELECT list.  */
8106           body->block = body->block->block;
8107           tail->block = NULL;
8108         }
8109       else
8110         body = body->block;
8111     }
8112
8113   if (class_is)
8114     {
8115       gfc_symbol *vtab;
8116
8117       if (!default_case)
8118         {
8119           /* Add a default case to hold the CLASS IS cases.  */
8120           for (tail = code; tail->block; tail = tail->block) ;
8121           tail->block = gfc_get_code ();
8122           tail = tail->block;
8123           tail->op = EXEC_SELECT_TYPE;
8124           tail->ext.block.case_list = gfc_get_case ();
8125           tail->ext.block.case_list->ts.type = BT_UNKNOWN;
8126           tail->next = NULL;
8127           default_case = tail;
8128         }
8129
8130       /* More than one CLASS IS block?  */
8131       if (class_is->block)
8132         {
8133           gfc_code **c1,*c2;
8134           bool swapped;
8135           /* Sort CLASS IS blocks by extension level.  */
8136           do
8137             {
8138               swapped = false;
8139               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
8140                 {
8141                   c2 = (*c1)->block;
8142                   /* F03:C817 (check for doubles).  */
8143                   if ((*c1)->ext.block.case_list->ts.u.derived->hash_value
8144                       == c2->ext.block.case_list->ts.u.derived->hash_value)
8145                     {
8146                       gfc_error ("Double CLASS IS block in SELECT TYPE "
8147                                  "statement at %L",
8148                                  &c2->ext.block.case_list->where);
8149                       return;
8150                     }
8151                   if ((*c1)->ext.block.case_list->ts.u.derived->attr.extension
8152                       < c2->ext.block.case_list->ts.u.derived->attr.extension)
8153                     {
8154                       /* Swap.  */
8155                       (*c1)->block = c2->block;
8156                       c2->block = *c1;
8157                       *c1 = c2;
8158                       swapped = true;
8159                     }
8160                 }
8161             }
8162           while (swapped);
8163         }
8164
8165       /* Generate IF chain.  */
8166       if_st = gfc_get_code ();
8167       if_st->op = EXEC_IF;
8168       new_st = if_st;
8169       for (body = class_is; body; body = body->block)
8170         {
8171           new_st->block = gfc_get_code ();
8172           new_st = new_st->block;
8173           new_st->op = EXEC_IF;
8174           /* Set up IF condition: Call _gfortran_is_extension_of.  */
8175           new_st->expr1 = gfc_get_expr ();
8176           new_st->expr1->expr_type = EXPR_FUNCTION;
8177           new_st->expr1->ts.type = BT_LOGICAL;
8178           new_st->expr1->ts.kind = 4;
8179           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
8180           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
8181           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
8182           /* Set up arguments.  */
8183           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
8184           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
8185           new_st->expr1->value.function.actual->expr->where = code->loc;
8186           gfc_add_vptr_component (new_st->expr1->value.function.actual->expr);
8187           vtab = gfc_find_derived_vtab (body->ext.block.case_list->ts.u.derived);
8188           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
8189           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
8190           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
8191           new_st->next = body->next;
8192         }
8193         if (default_case->next)
8194           {
8195             new_st->block = gfc_get_code ();
8196             new_st = new_st->block;
8197             new_st->op = EXEC_IF;
8198             new_st->next = default_case->next;
8199           }
8200
8201         /* Replace CLASS DEFAULT code by the IF chain.  */
8202         default_case->next = if_st;
8203     }
8204
8205   /* Resolve the internal code.  This can not be done earlier because
8206      it requires that the sym->assoc of selectors is set already.  */
8207   gfc_current_ns = ns;
8208   gfc_resolve_blocks (code->block, gfc_current_ns);
8209   gfc_current_ns = old_ns;
8210
8211   resolve_select (code, true);
8212 }
8213
8214
8215 /* Resolve a transfer statement. This is making sure that:
8216    -- a derived type being transferred has only non-pointer components
8217    -- a derived type being transferred doesn't have private components, unless
8218       it's being transferred from the module where the type was defined
8219    -- we're not trying to transfer a whole assumed size array.  */
8220
8221 static void
8222 resolve_transfer (gfc_code *code)
8223 {
8224   gfc_typespec *ts;
8225   gfc_symbol *sym;
8226   gfc_ref *ref;
8227   gfc_expr *exp;
8228
8229   exp = code->expr1;
8230
8231   while (exp != NULL && exp->expr_type == EXPR_OP
8232          && exp->value.op.op == INTRINSIC_PARENTHESES)
8233     exp = exp->value.op.op1;
8234
8235   if (exp && exp->expr_type == EXPR_NULL && exp->ts.type == BT_UNKNOWN)
8236     {
8237       gfc_error ("NULL intrinsic at %L in data transfer statement requires "
8238                  "MOLD=", &exp->where);
8239       return;
8240     }
8241
8242   if (exp == NULL || (exp->expr_type != EXPR_VARIABLE
8243                       && exp->expr_type != EXPR_FUNCTION))
8244     return;
8245
8246   /* If we are reading, the variable will be changed.  Note that
8247      code->ext.dt may be NULL if the TRANSFER is related to
8248      an INQUIRE statement -- but in this case, we are not reading, either.  */
8249   if (code->ext.dt && code->ext.dt->dt_io_kind->value.iokind == M_READ
8250       && !gfc_check_vardef_context (exp, false, false, false, 
8251                                     _("item in READ")))
8252     return;
8253
8254   sym = exp->symtree->n.sym;
8255   ts = &sym->ts;
8256
8257   /* Go to actual component transferred.  */
8258   for (ref = exp->ref; ref; ref = ref->next)
8259     if (ref->type == REF_COMPONENT)
8260       ts = &ref->u.c.component->ts;
8261
8262   if (ts->type == BT_CLASS)
8263     {
8264       /* FIXME: Test for defined input/output.  */
8265       gfc_error ("Data transfer element at %L cannot be polymorphic unless "
8266                 "it is processed by a defined input/output procedure",
8267                 &code->loc);
8268       return;
8269     }
8270
8271   if (ts->type == BT_DERIVED)
8272     {
8273       /* Check that transferred derived type doesn't contain POINTER
8274          components.  */
8275       if (ts->u.derived->attr.pointer_comp)
8276         {
8277           gfc_error ("Data transfer element at %L cannot have POINTER "
8278                      "components unless it is processed by a defined "
8279                      "input/output procedure", &code->loc);
8280           return;
8281         }
8282
8283       /* F08:C935.  */
8284       if (ts->u.derived->attr.proc_pointer_comp)
8285         {
8286           gfc_error ("Data transfer element at %L cannot have "
8287                      "procedure pointer components", &code->loc);
8288           return;
8289         }
8290
8291       if (ts->u.derived->attr.alloc_comp)
8292         {
8293           gfc_error ("Data transfer element at %L cannot have ALLOCATABLE "
8294                      "components unless it is processed by a defined "
8295                      "input/output procedure", &code->loc);
8296           return;
8297         }
8298
8299       /* C_PTR and C_FUNPTR have private components which means they can not
8300          be printed.  However, if -std=gnu and not -pedantic, allow
8301          the component to be printed to help debugging.  */
8302       if (ts->u.derived->ts.f90_type == BT_VOID)
8303         {
8304           if (!gfc_notify_std (GFC_STD_GNU, "Data transfer element at %L "
8305                                "cannot have PRIVATE components", &code->loc))
8306             return;
8307         }
8308       else if (derived_inaccessible (ts->u.derived))
8309         {
8310           gfc_error ("Data transfer element at %L cannot have "
8311                      "PRIVATE components",&code->loc);
8312           return;
8313         }
8314     }
8315
8316   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE && exp->ref
8317       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
8318     {
8319       gfc_error ("Data transfer element at %L cannot be a full reference to "
8320                  "an assumed-size array", &code->loc);
8321       return;
8322     }
8323 }
8324
8325
8326 /*********** Toplevel code resolution subroutines ***********/
8327
8328 /* Find the set of labels that are reachable from this block.  We also
8329    record the last statement in each block.  */
8330
8331 static void
8332 find_reachable_labels (gfc_code *block)
8333 {
8334   gfc_code *c;
8335
8336   if (!block)
8337     return;
8338
8339   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
8340
8341   /* Collect labels in this block.  We don't keep those corresponding
8342      to END {IF|SELECT}, these are checked in resolve_branch by going
8343      up through the code_stack.  */
8344   for (c = block; c; c = c->next)
8345     {
8346       if (c->here && c->op != EXEC_END_NESTED_BLOCK)
8347         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
8348     }
8349
8350   /* Merge with labels from parent block.  */
8351   if (cs_base->prev)
8352     {
8353       gcc_assert (cs_base->prev->reachable_labels);
8354       bitmap_ior_into (cs_base->reachable_labels,
8355                        cs_base->prev->reachable_labels);
8356     }
8357 }
8358
8359
8360 static void
8361 resolve_lock_unlock (gfc_code *code)
8362 {
8363   if (code->expr1->ts.type != BT_DERIVED
8364       || code->expr1->expr_type != EXPR_VARIABLE
8365       || code->expr1->ts.u.derived->from_intmod != INTMOD_ISO_FORTRAN_ENV
8366       || code->expr1->ts.u.derived->intmod_sym_id != ISOFORTRAN_LOCK_TYPE
8367       || code->expr1->rank != 0
8368       || (!gfc_is_coarray (code->expr1) && !gfc_is_coindexed (code->expr1)))
8369     gfc_error ("Lock variable at %L must be a scalar of type LOCK_TYPE",
8370                &code->expr1->where);
8371
8372   /* Check STAT.  */
8373   if (code->expr2
8374       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8375           || code->expr2->expr_type != EXPR_VARIABLE))
8376     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8377                &code->expr2->where);
8378
8379   if (code->expr2
8380       && !gfc_check_vardef_context (code->expr2, false, false, false, 
8381                                     _("STAT variable")))
8382     return;
8383
8384   /* Check ERRMSG.  */
8385   if (code->expr3
8386       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8387           || code->expr3->expr_type != EXPR_VARIABLE))
8388     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8389                &code->expr3->where);
8390
8391   if (code->expr3
8392       && !gfc_check_vardef_context (code->expr3, false, false, false, 
8393                                     _("ERRMSG variable")))
8394     return;
8395
8396   /* Check ACQUIRED_LOCK.  */
8397   if (code->expr4
8398       && (code->expr4->ts.type != BT_LOGICAL || code->expr4->rank != 0
8399           || code->expr4->expr_type != EXPR_VARIABLE))
8400     gfc_error ("ACQUIRED_LOCK= argument at %L must be a scalar LOGICAL "
8401                "variable", &code->expr4->where);
8402
8403   if (code->expr4
8404       && !gfc_check_vardef_context (code->expr4, false, false, false, 
8405                                     _("ACQUIRED_LOCK variable")))
8406     return;
8407 }
8408
8409
8410 static void
8411 resolve_sync (gfc_code *code)
8412 {
8413   /* Check imageset. The * case matches expr1 == NULL.  */
8414   if (code->expr1)
8415     {
8416       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
8417         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
8418                    "INTEGER expression", &code->expr1->where);
8419       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
8420           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
8421         gfc_error ("Imageset argument at %L must between 1 and num_images()",
8422                    &code->expr1->where);
8423       else if (code->expr1->expr_type == EXPR_ARRAY
8424                && gfc_simplify_expr (code->expr1, 0))
8425         {
8426            gfc_constructor *cons;
8427            cons = gfc_constructor_first (code->expr1->value.constructor);
8428            for (; cons; cons = gfc_constructor_next (cons))
8429              if (cons->expr->expr_type == EXPR_CONSTANT
8430                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
8431                gfc_error ("Imageset argument at %L must between 1 and "
8432                           "num_images()", &cons->expr->where);
8433         }
8434     }
8435
8436   /* Check STAT.  */
8437   if (code->expr2
8438       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8439           || code->expr2->expr_type != EXPR_VARIABLE))
8440     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8441                &code->expr2->where);
8442
8443   /* Check ERRMSG.  */
8444   if (code->expr3
8445       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8446           || code->expr3->expr_type != EXPR_VARIABLE))
8447     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8448                &code->expr3->where);
8449 }
8450
8451
8452 /* Given a branch to a label, see if the branch is conforming.
8453    The code node describes where the branch is located.  */
8454
8455 static void
8456 resolve_branch (gfc_st_label *label, gfc_code *code)
8457 {
8458   code_stack *stack;
8459
8460   if (label == NULL)
8461     return;
8462
8463   /* Step one: is this a valid branching target?  */
8464
8465   if (label->defined == ST_LABEL_UNKNOWN)
8466     {
8467       gfc_error ("Label %d referenced at %L is never defined", label->value,
8468                  &label->where);
8469       return;
8470     }
8471
8472   if (label->defined != ST_LABEL_TARGET && label->defined != ST_LABEL_DO_TARGET)
8473     {
8474       gfc_error ("Statement at %L is not a valid branch target statement "
8475                  "for the branch statement at %L", &label->where, &code->loc);
8476       return;
8477     }
8478
8479   /* Step two: make sure this branch is not a branch to itself ;-)  */
8480
8481   if (code->here == label)
8482     {
8483       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
8484       return;
8485     }
8486
8487   /* Step three:  See if the label is in the same block as the
8488      branching statement.  The hard work has been done by setting up
8489      the bitmap reachable_labels.  */
8490
8491   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
8492     {
8493       /* Check now whether there is a CRITICAL construct; if so, check
8494          whether the label is still visible outside of the CRITICAL block,
8495          which is invalid.  */
8496       for (stack = cs_base; stack; stack = stack->prev)
8497         {
8498           if (stack->current->op == EXEC_CRITICAL
8499               && bitmap_bit_p (stack->reachable_labels, label->value))
8500             gfc_error ("GOTO statement at %L leaves CRITICAL construct for "
8501                       "label at %L", &code->loc, &label->where);
8502           else if (stack->current->op == EXEC_DO_CONCURRENT
8503                    && bitmap_bit_p (stack->reachable_labels, label->value))
8504             gfc_error ("GOTO statement at %L leaves DO CONCURRENT construct "
8505                       "for label at %L", &code->loc, &label->where);
8506         }
8507
8508       return;
8509     }
8510
8511   /* Step four:  If we haven't found the label in the bitmap, it may
8512     still be the label of the END of the enclosing block, in which
8513     case we find it by going up the code_stack.  */
8514
8515   for (stack = cs_base; stack; stack = stack->prev)
8516     {
8517       if (stack->current->next && stack->current->next->here == label)
8518         break;
8519       if (stack->current->op == EXEC_CRITICAL)
8520         {
8521           /* Note: A label at END CRITICAL does not leave the CRITICAL
8522              construct as END CRITICAL is still part of it.  */
8523           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8524                       " at %L", &code->loc, &label->where);
8525           return;
8526         }
8527       else if (stack->current->op == EXEC_DO_CONCURRENT)
8528         {
8529           gfc_error ("GOTO statement at %L leaves DO CONCURRENT construct for "
8530                      "label at %L", &code->loc, &label->where);
8531           return;
8532         }
8533     }
8534
8535   if (stack)
8536     {
8537       gcc_assert (stack->current->next->op == EXEC_END_NESTED_BLOCK);
8538       return;
8539     }
8540
8541   /* The label is not in an enclosing block, so illegal.  This was
8542      allowed in Fortran 66, so we allow it as extension.  No
8543      further checks are necessary in this case.  */
8544   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
8545                   "as the GOTO statement at %L", &label->where,
8546                   &code->loc);
8547   return;
8548 }
8549
8550
8551 /* Check whether EXPR1 has the same shape as EXPR2.  */
8552
8553 static bool
8554 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
8555 {
8556   mpz_t shape[GFC_MAX_DIMENSIONS];
8557   mpz_t shape2[GFC_MAX_DIMENSIONS];
8558   bool result = false;
8559   int i;
8560
8561   /* Compare the rank.  */
8562   if (expr1->rank != expr2->rank)
8563     return result;
8564
8565   /* Compare the size of each dimension.  */
8566   for (i=0; i<expr1->rank; i++)
8567     {
8568       if (!gfc_array_dimen_size (expr1, i, &shape[i]))
8569         goto ignore;
8570
8571       if (!gfc_array_dimen_size (expr2, i, &shape2[i]))
8572         goto ignore;
8573
8574       if (mpz_cmp (shape[i], shape2[i]))
8575         goto over;
8576     }
8577
8578   /* When either of the two expression is an assumed size array, we
8579      ignore the comparison of dimension sizes.  */
8580 ignore:
8581   result = true;
8582
8583 over:
8584   gfc_clear_shape (shape, i);
8585   gfc_clear_shape (shape2, i);
8586   return result;
8587 }
8588
8589
8590 /* Check whether a WHERE assignment target or a WHERE mask expression
8591    has the same shape as the outmost WHERE mask expression.  */
8592
8593 static void
8594 resolve_where (gfc_code *code, gfc_expr *mask)
8595 {
8596   gfc_code *cblock;
8597   gfc_code *cnext;
8598   gfc_expr *e = NULL;
8599
8600   cblock = code->block;
8601
8602   /* Store the first WHERE mask-expr of the WHERE statement or construct.
8603      In case of nested WHERE, only the outmost one is stored.  */
8604   if (mask == NULL) /* outmost WHERE */
8605     e = cblock->expr1;
8606   else /* inner WHERE */
8607     e = mask;
8608
8609   while (cblock)
8610     {
8611       if (cblock->expr1)
8612         {
8613           /* Check if the mask-expr has a consistent shape with the
8614              outmost WHERE mask-expr.  */
8615           if (!resolve_where_shape (cblock->expr1, e))
8616             gfc_error ("WHERE mask at %L has inconsistent shape",
8617                        &cblock->expr1->where);
8618          }
8619
8620       /* the assignment statement of a WHERE statement, or the first
8621          statement in where-body-construct of a WHERE construct */
8622       cnext = cblock->next;
8623       while (cnext)
8624         {
8625           switch (cnext->op)
8626             {
8627             /* WHERE assignment statement */
8628             case EXEC_ASSIGN:
8629
8630               /* Check shape consistent for WHERE assignment target.  */
8631               if (e && !resolve_where_shape (cnext->expr1, e))
8632                gfc_error ("WHERE assignment target at %L has "
8633                           "inconsistent shape", &cnext->expr1->where);
8634               break;
8635
8636
8637             case EXEC_ASSIGN_CALL:
8638               resolve_call (cnext);
8639               if (!cnext->resolved_sym->attr.elemental)
8640                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8641                           &cnext->ext.actual->expr->where);
8642               break;
8643
8644             /* WHERE or WHERE construct is part of a where-body-construct */
8645             case EXEC_WHERE:
8646               resolve_where (cnext, e);
8647               break;
8648
8649             default:
8650               gfc_error ("Unsupported statement inside WHERE at %L",
8651                          &cnext->loc);
8652             }
8653          /* the next statement within the same where-body-construct */
8654          cnext = cnext->next;
8655        }
8656     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8657     cblock = cblock->block;
8658   }
8659 }
8660
8661
8662 /* Resolve assignment in FORALL construct.
8663    NVAR is the number of FORALL index variables, and VAR_EXPR records the
8664    FORALL index variables.  */
8665
8666 static void
8667 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
8668 {
8669   int n;
8670
8671   for (n = 0; n < nvar; n++)
8672     {
8673       gfc_symbol *forall_index;
8674
8675       forall_index = var_expr[n]->symtree->n.sym;
8676
8677       /* Check whether the assignment target is one of the FORALL index
8678          variable.  */
8679       if ((code->expr1->expr_type == EXPR_VARIABLE)
8680           && (code->expr1->symtree->n.sym == forall_index))
8681         gfc_error ("Assignment to a FORALL index variable at %L",
8682                    &code->expr1->where);
8683       else
8684         {
8685           /* If one of the FORALL index variables doesn't appear in the
8686              assignment variable, then there could be a many-to-one
8687              assignment.  Emit a warning rather than an error because the
8688              mask could be resolving this problem.  */
8689           if (!find_forall_index (code->expr1, forall_index, 0))
8690             gfc_warning ("The FORALL with index '%s' is not used on the "
8691                          "left side of the assignment at %L and so might "
8692                          "cause multiple assignment to this object",
8693                          var_expr[n]->symtree->name, &code->expr1->where);
8694         }
8695     }
8696 }
8697
8698
8699 /* Resolve WHERE statement in FORALL construct.  */
8700
8701 static void
8702 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
8703                                   gfc_expr **var_expr)
8704 {
8705   gfc_code *cblock;
8706   gfc_code *cnext;
8707
8708   cblock = code->block;
8709   while (cblock)
8710     {
8711       /* the assignment statement of a WHERE statement, or the first
8712          statement in where-body-construct of a WHERE construct */
8713       cnext = cblock->next;
8714       while (cnext)
8715         {
8716           switch (cnext->op)
8717             {
8718             /* WHERE assignment statement */
8719             case EXEC_ASSIGN:
8720               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
8721               break;
8722
8723             /* WHERE operator assignment statement */
8724             case EXEC_ASSIGN_CALL:
8725               resolve_call (cnext);
8726               if (!cnext->resolved_sym->attr.elemental)
8727                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8728                           &cnext->ext.actual->expr->where);
8729               break;
8730
8731             /* WHERE or WHERE construct is part of a where-body-construct */
8732             case EXEC_WHERE:
8733               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
8734               break;
8735
8736             default:
8737               gfc_error ("Unsupported statement inside WHERE at %L",
8738                          &cnext->loc);
8739             }
8740           /* the next statement within the same where-body-construct */
8741           cnext = cnext->next;
8742         }
8743       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8744       cblock = cblock->block;
8745     }
8746 }
8747
8748
8749 /* Traverse the FORALL body to check whether the following errors exist:
8750    1. For assignment, check if a many-to-one assignment happens.
8751    2. For WHERE statement, check the WHERE body to see if there is any
8752       many-to-one assignment.  */
8753
8754 static void
8755 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
8756 {
8757   gfc_code *c;
8758
8759   c = code->block->next;
8760   while (c)
8761     {
8762       switch (c->op)
8763         {
8764         case EXEC_ASSIGN:
8765         case EXEC_POINTER_ASSIGN:
8766           gfc_resolve_assign_in_forall (c, nvar, var_expr);
8767           break;
8768
8769         case EXEC_ASSIGN_CALL:
8770           resolve_call (c);
8771           break;
8772
8773         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
8774            there is no need to handle it here.  */
8775         case EXEC_FORALL:
8776           break;
8777         case EXEC_WHERE:
8778           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
8779           break;
8780         default:
8781           break;
8782         }
8783       /* The next statement in the FORALL body.  */
8784       c = c->next;
8785     }
8786 }
8787
8788
8789 /* Counts the number of iterators needed inside a forall construct, including
8790    nested forall constructs. This is used to allocate the needed memory
8791    in gfc_resolve_forall.  */
8792
8793 static int
8794 gfc_count_forall_iterators (gfc_code *code)
8795 {
8796   int max_iters, sub_iters, current_iters;
8797   gfc_forall_iterator *fa;
8798
8799   gcc_assert(code->op == EXEC_FORALL);
8800   max_iters = 0;
8801   current_iters = 0;
8802
8803   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8804     current_iters ++;
8805
8806   code = code->block->next;
8807
8808   while (code)
8809     {
8810       if (code->op == EXEC_FORALL)
8811         {
8812           sub_iters = gfc_count_forall_iterators (code);
8813           if (sub_iters > max_iters)
8814             max_iters = sub_iters;
8815         }
8816       code = code->next;
8817     }
8818
8819   return current_iters + max_iters;
8820 }
8821
8822
8823 /* Given a FORALL construct, first resolve the FORALL iterator, then call
8824    gfc_resolve_forall_body to resolve the FORALL body.  */
8825
8826 static void
8827 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
8828 {
8829   static gfc_expr **var_expr;
8830   static int total_var = 0;
8831   static int nvar = 0;
8832   int old_nvar, tmp;
8833   gfc_forall_iterator *fa;
8834   int i;
8835
8836   old_nvar = nvar;
8837
8838   /* Start to resolve a FORALL construct   */
8839   if (forall_save == 0)
8840     {
8841       /* Count the total number of FORALL index in the nested FORALL
8842          construct in order to allocate the VAR_EXPR with proper size.  */
8843       total_var = gfc_count_forall_iterators (code);
8844
8845       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
8846       var_expr = XCNEWVEC (gfc_expr *, total_var);
8847     }
8848
8849   /* The information about FORALL iterator, including FORALL index start, end
8850      and stride. The FORALL index can not appear in start, end or stride.  */
8851   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8852     {
8853       /* Check if any outer FORALL index name is the same as the current
8854          one.  */
8855       for (i = 0; i < nvar; i++)
8856         {
8857           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
8858             {
8859               gfc_error ("An outer FORALL construct already has an index "
8860                          "with this name %L", &fa->var->where);
8861             }
8862         }
8863
8864       /* Record the current FORALL index.  */
8865       var_expr[nvar] = gfc_copy_expr (fa->var);
8866
8867       nvar++;
8868
8869       /* No memory leak.  */
8870       gcc_assert (nvar <= total_var);
8871     }
8872
8873   /* Resolve the FORALL body.  */
8874   gfc_resolve_forall_body (code, nvar, var_expr);
8875
8876   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
8877   gfc_resolve_blocks (code->block, ns);
8878
8879   tmp = nvar;
8880   nvar = old_nvar;
8881   /* Free only the VAR_EXPRs allocated in this frame.  */
8882   for (i = nvar; i < tmp; i++)
8883      gfc_free_expr (var_expr[i]);
8884
8885   if (nvar == 0)
8886     {
8887       /* We are in the outermost FORALL construct.  */
8888       gcc_assert (forall_save == 0);
8889
8890       /* VAR_EXPR is not needed any more.  */
8891       free (var_expr);
8892       total_var = 0;
8893     }
8894 }
8895
8896
8897 /* Resolve a BLOCK construct statement.  */
8898
8899 static void
8900 resolve_block_construct (gfc_code* code)
8901 {
8902   /* Resolve the BLOCK's namespace.  */
8903   gfc_resolve (code->ext.block.ns);
8904
8905   /* For an ASSOCIATE block, the associations (and their targets) are already
8906      resolved during resolve_symbol.  */
8907 }
8908
8909
8910 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
8911    DO code nodes.  */
8912
8913 static void resolve_code (gfc_code *, gfc_namespace *);
8914
8915 void
8916 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
8917 {
8918   bool t;
8919
8920   for (; b; b = b->block)
8921     {
8922       t = gfc_resolve_expr (b->expr1);
8923       if (!gfc_resolve_expr (b->expr2))
8924         t = false;
8925
8926       switch (b->op)
8927         {
8928         case EXEC_IF:
8929           if (t && b->expr1 != NULL
8930               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
8931             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8932                        &b->expr1->where);
8933           break;
8934
8935         case EXEC_WHERE:
8936           if (t
8937               && b->expr1 != NULL
8938               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
8939             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
8940                        &b->expr1->where);
8941           break;
8942
8943         case EXEC_GOTO:
8944           resolve_branch (b->label1, b);
8945           break;
8946
8947         case EXEC_BLOCK:
8948           resolve_block_construct (b);
8949           break;
8950
8951         case EXEC_SELECT:
8952         case EXEC_SELECT_TYPE:
8953         case EXEC_FORALL:
8954         case EXEC_DO:
8955         case EXEC_DO_WHILE:
8956         case EXEC_DO_CONCURRENT:
8957         case EXEC_CRITICAL:
8958         case EXEC_READ:
8959         case EXEC_WRITE:
8960         case EXEC_IOLENGTH:
8961         case EXEC_WAIT:
8962           break;
8963
8964         case EXEC_OMP_ATOMIC:
8965         case EXEC_OMP_CRITICAL:
8966         case EXEC_OMP_DO:
8967         case EXEC_OMP_MASTER:
8968         case EXEC_OMP_ORDERED:
8969         case EXEC_OMP_PARALLEL:
8970         case EXEC_OMP_PARALLEL_DO:
8971         case EXEC_OMP_PARALLEL_SECTIONS:
8972         case EXEC_OMP_PARALLEL_WORKSHARE:
8973         case EXEC_OMP_SECTIONS:
8974         case EXEC_OMP_SINGLE:
8975         case EXEC_OMP_TASK:
8976         case EXEC_OMP_TASKWAIT:
8977         case EXEC_OMP_TASKYIELD:
8978         case EXEC_OMP_WORKSHARE:
8979           break;
8980
8981         default:
8982           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
8983         }
8984
8985       resolve_code (b->next, ns);
8986     }
8987 }
8988
8989
8990 /* Does everything to resolve an ordinary assignment.  Returns true
8991    if this is an interface assignment.  */
8992 static bool
8993 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
8994 {
8995   bool rval = false;
8996   gfc_expr *lhs;
8997   gfc_expr *rhs;
8998   int llen = 0;
8999   int rlen = 0;
9000   int n;
9001   gfc_ref *ref;
9002
9003   if (gfc_extend_assign (code, ns))
9004     {
9005       gfc_expr** rhsptr;
9006
9007       if (code->op == EXEC_ASSIGN_CALL)
9008         {
9009           lhs = code->ext.actual->expr;
9010           rhsptr = &code->ext.actual->next->expr;
9011         }
9012       else
9013         {
9014           gfc_actual_arglist* args;
9015           gfc_typebound_proc* tbp;
9016
9017           gcc_assert (code->op == EXEC_COMPCALL);
9018
9019           args = code->expr1->value.compcall.actual;
9020           lhs = args->expr;
9021           rhsptr = &args->next->expr;
9022
9023           tbp = code->expr1->value.compcall.tbp;
9024           gcc_assert (!tbp->is_generic);
9025         }
9026
9027       /* Make a temporary rhs when there is a default initializer
9028          and rhs is the same symbol as the lhs.  */
9029       if ((*rhsptr)->expr_type == EXPR_VARIABLE
9030             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
9031             && gfc_has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
9032             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
9033         *rhsptr = gfc_get_parentheses (*rhsptr);
9034
9035       return true;
9036     }
9037
9038   lhs = code->expr1;
9039   rhs = code->expr2;
9040
9041   if (rhs->is_boz
9042       && !gfc_notify_std (GFC_STD_GNU, "BOZ literal at %L outside "
9043                           "a DATA statement and outside INT/REAL/DBLE/CMPLX", 
9044                           &code->loc))
9045     return false;
9046
9047   /* Handle the case of a BOZ literal on the RHS.  */
9048   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
9049     {
9050       int rc;
9051       if (gfc_option.warn_surprising)
9052         gfc_warning ("BOZ literal at %L is bitwise transferred "
9053                      "non-integer symbol '%s'", &code->loc,
9054                      lhs->symtree->n.sym->name);
9055
9056       if (!gfc_convert_boz (rhs, &lhs->ts))
9057         return false;
9058       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
9059         {
9060           if (rc == ARITH_UNDERFLOW)
9061             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
9062                        ". This check can be disabled with the option "
9063                        "-fno-range-check", &rhs->where);
9064           else if (rc == ARITH_OVERFLOW)
9065             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
9066                        ". This check can be disabled with the option "
9067                        "-fno-range-check", &rhs->where);
9068           else if (rc == ARITH_NAN)
9069             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
9070                        ". This check can be disabled with the option "
9071                        "-fno-range-check", &rhs->where);
9072           return false;
9073         }
9074     }
9075
9076   if (lhs->ts.type == BT_CHARACTER
9077         && gfc_option.warn_character_truncation)
9078     {
9079       if (lhs->ts.u.cl != NULL
9080             && lhs->ts.u.cl->length != NULL
9081             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9082         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
9083
9084       if (rhs->expr_type == EXPR_CONSTANT)
9085         rlen = rhs->value.character.length;
9086
9087       else if (rhs->ts.u.cl != NULL
9088                  && rhs->ts.u.cl->length != NULL
9089                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9090         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
9091
9092       if (rlen && llen && rlen > llen)
9093         gfc_warning_now ("CHARACTER expression will be truncated "
9094                          "in assignment (%d/%d) at %L",
9095                          llen, rlen, &code->loc);
9096     }
9097
9098   /* Ensure that a vector index expression for the lvalue is evaluated
9099      to a temporary if the lvalue symbol is referenced in it.  */
9100   if (lhs->rank)
9101     {
9102       for (ref = lhs->ref; ref; ref= ref->next)
9103         if (ref->type == REF_ARRAY)
9104           {
9105             for (n = 0; n < ref->u.ar.dimen; n++)
9106               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
9107                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
9108                                            ref->u.ar.start[n]))
9109                 ref->u.ar.start[n]
9110                         = gfc_get_parentheses (ref->u.ar.start[n]);
9111           }
9112     }
9113
9114   if (gfc_pure (NULL))
9115     {
9116       if (lhs->ts.type == BT_DERIVED
9117             && lhs->expr_type == EXPR_VARIABLE
9118             && lhs->ts.u.derived->attr.pointer_comp
9119             && rhs->expr_type == EXPR_VARIABLE
9120             && (gfc_impure_variable (rhs->symtree->n.sym)
9121                 || gfc_is_coindexed (rhs)))
9122         {
9123           /* F2008, C1283.  */
9124           if (gfc_is_coindexed (rhs))
9125             gfc_error ("Coindexed expression at %L is assigned to "
9126                         "a derived type variable with a POINTER "
9127                         "component in a PURE procedure",
9128                         &rhs->where);
9129           else
9130             gfc_error ("The impure variable at %L is assigned to "
9131                         "a derived type variable with a POINTER "
9132                         "component in a PURE procedure (12.6)",
9133                         &rhs->where);
9134           return rval;
9135         }
9136
9137       /* Fortran 2008, C1283.  */
9138       if (gfc_is_coindexed (lhs))
9139         {
9140           gfc_error ("Assignment to coindexed variable at %L in a PURE "
9141                      "procedure", &rhs->where);
9142           return rval;
9143         }
9144     }
9145
9146   if (gfc_implicit_pure (NULL))
9147     {
9148       if (lhs->expr_type == EXPR_VARIABLE
9149             && lhs->symtree->n.sym != gfc_current_ns->proc_name
9150             && lhs->symtree->n.sym->ns != gfc_current_ns)
9151         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9152
9153       if (lhs->ts.type == BT_DERIVED
9154             && lhs->expr_type == EXPR_VARIABLE
9155             && lhs->ts.u.derived->attr.pointer_comp
9156             && rhs->expr_type == EXPR_VARIABLE
9157             && (gfc_impure_variable (rhs->symtree->n.sym)
9158                 || gfc_is_coindexed (rhs)))
9159         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9160
9161       /* Fortran 2008, C1283.  */
9162       if (gfc_is_coindexed (lhs))
9163         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9164     }
9165
9166   /* F03:7.4.1.2.  */
9167   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
9168      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
9169   if (lhs->ts.type == BT_CLASS)
9170     {
9171       gfc_error ("Variable must not be polymorphic in intrinsic assignment at "
9172                  "%L - check that there is a matching specific subroutine "
9173                  "for '=' operator", &lhs->where);
9174       return false;
9175     }
9176
9177   /* F2008, Section 7.2.1.2.  */
9178   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
9179     {
9180       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
9181                  "component in assignment at %L", &lhs->where);
9182       return false;
9183     }
9184
9185   gfc_check_assign (lhs, rhs, 1);
9186   return false;
9187 }
9188
9189
9190 /* Add a component reference onto an expression.  */
9191
9192 static void
9193 add_comp_ref (gfc_expr *e, gfc_component *c)
9194 {
9195   gfc_ref **ref;
9196   ref = &(e->ref);
9197   while (*ref)
9198     ref = &((*ref)->next);
9199   *ref = gfc_get_ref ();
9200   (*ref)->type = REF_COMPONENT;
9201   (*ref)->u.c.sym = e->ts.u.derived;
9202   (*ref)->u.c.component = c;
9203   e->ts = c->ts;
9204
9205   /* Add a full array ref, as necessary.  */
9206   if (c->as)
9207     {
9208       gfc_add_full_array_ref (e, c->as);
9209       e->rank = c->as->rank;
9210     }
9211 }
9212
9213
9214 /* Build an assignment.  Keep the argument 'op' for future use, so that
9215    pointer assignments can be made.  */
9216
9217 static gfc_code *
9218 build_assignment (gfc_exec_op op, gfc_expr *expr1, gfc_expr *expr2,
9219                   gfc_component *comp1, gfc_component *comp2, locus loc)
9220 {
9221   gfc_code *this_code;
9222
9223   this_code = gfc_get_code ();
9224   this_code->op = op;
9225   this_code->next = NULL;
9226   this_code->expr1 = gfc_copy_expr (expr1);
9227   this_code->expr2 = gfc_copy_expr (expr2);
9228   this_code->loc = loc;
9229   if (comp1 && comp2)
9230     {
9231       add_comp_ref (this_code->expr1, comp1);
9232       add_comp_ref (this_code->expr2, comp2);
9233     }
9234
9235   return this_code;
9236 }
9237
9238
9239 /* Makes a temporary variable expression based on the characteristics of
9240    a given variable expression.  */
9241
9242 static gfc_expr*
9243 get_temp_from_expr (gfc_expr *e, gfc_namespace *ns)
9244 {
9245   static int serial = 0;
9246   char name[GFC_MAX_SYMBOL_LEN];
9247   gfc_symtree *tmp;
9248   gfc_array_spec *as;
9249   gfc_array_ref *aref;
9250   gfc_ref *ref;
9251
9252   sprintf (name, "DA@%d", serial++);
9253   gfc_get_sym_tree (name, ns, &tmp, false);
9254   gfc_add_type (tmp->n.sym, &e->ts, NULL);
9255
9256   as = NULL;
9257   ref = NULL;
9258   aref = NULL;
9259
9260   /* This function could be expanded to support other expression type
9261      but this is not needed here.  */
9262   gcc_assert (e->expr_type == EXPR_VARIABLE);
9263
9264   /* Obtain the arrayspec for the temporary.  */
9265   if (e->rank)
9266     {
9267       aref = gfc_find_array_ref (e);
9268       if (e->expr_type == EXPR_VARIABLE
9269           && e->symtree->n.sym->as == aref->as)
9270         as = aref->as;
9271       else
9272         {
9273           for (ref = e->ref; ref; ref = ref->next)
9274             if (ref->type == REF_COMPONENT
9275                 && ref->u.c.component->as == aref->as)
9276               {
9277                 as = aref->as;
9278                 break;
9279               }
9280         }
9281     }
9282
9283   /* Add the attributes and the arrayspec to the temporary.  */
9284   tmp->n.sym->attr = gfc_expr_attr (e);
9285   if (as)
9286     {
9287       tmp->n.sym->as = gfc_copy_array_spec (as);
9288       if (!ref)
9289         ref = e->ref;
9290       if (as->type == AS_DEFERRED)
9291         tmp->n.sym->attr.allocatable = 1;
9292     }
9293   else
9294     tmp->n.sym->attr.dimension = 0;
9295
9296   gfc_set_sym_referenced (tmp->n.sym);
9297   gfc_add_flavor (&tmp->n.sym->attr, FL_VARIABLE, name, NULL);
9298   e = gfc_lval_expr_from_sym (tmp->n.sym);
9299
9300   /* Should the lhs be a section, use its array ref for the
9301      temporary expression.  */
9302   if (aref && aref->type != AR_FULL)
9303     {
9304       gfc_free_ref_list (e->ref);
9305       e->ref = gfc_copy_ref (ref);
9306     }
9307   return e;
9308 }
9309
9310
9311 /* Add one line of code to the code chain, making sure that 'head' and
9312    'tail' are appropriately updated.  */
9313
9314 static void
9315 add_code_to_chain (gfc_code **this_code, gfc_code **head, gfc_code **tail)
9316 {
9317   gcc_assert (this_code);
9318   if (*head == NULL)
9319     *head = *tail = *this_code;
9320   else
9321     *tail = gfc_append_code (*tail, *this_code);
9322   *this_code = NULL;
9323 }
9324
9325
9326 /* Counts the potential number of part array references that would
9327    result from resolution of typebound defined assignments.  */
9328
9329 static int
9330 nonscalar_typebound_assign (gfc_symbol *derived, int depth)
9331 {
9332   gfc_component *c;
9333   int c_depth = 0, t_depth;
9334
9335   for (c= derived->components; c; c = c->next)
9336     {
9337       if ((c->ts.type != BT_DERIVED
9338             || c->attr.pointer
9339             || c->attr.allocatable
9340             || c->attr.proc_pointer_comp
9341             || c->attr.class_pointer
9342             || c->attr.proc_pointer)
9343           && !c->attr.defined_assign_comp)
9344         continue;
9345
9346       if (c->as && c_depth == 0)
9347         c_depth = 1;
9348
9349       if (c->ts.u.derived->attr.defined_assign_comp)
9350         t_depth = nonscalar_typebound_assign (c->ts.u.derived,
9351                                               c->as ? 1 : 0);
9352       else
9353         t_depth = 0;
9354
9355       c_depth = t_depth > c_depth ? t_depth : c_depth;
9356     }
9357   return depth + c_depth;
9358 }
9359
9360
9361 /* Implement 7.2.1.3 of the F08 standard:
9362    "An intrinsic assignment where the variable is of derived type is
9363    performed as if each component of the variable were assigned from the
9364    corresponding component of expr using pointer assignment (7.2.2) for
9365    each pointer component, defined assignment for each nonpointer
9366    nonallocatable component of a type that has a type-bound defined
9367    assignment consistent with the component, intrinsic assignment for
9368    each other nonpointer nonallocatable component, ..."
9369
9370    The pointer assignments are taken care of by the intrinsic
9371    assignment of the structure itself.  This function recursively adds
9372    defined assignments where required.  The recursion is accomplished
9373    by calling resolve_code.
9374
9375    When the lhs in a defined assignment has intent INOUT, we need a
9376    temporary for the lhs.  In pseudo-code:
9377
9378    ! Only call function lhs once.
9379       if (lhs is not a constant or an variable)
9380           temp_x = expr2
9381           expr2 => temp_x
9382    ! Do the intrinsic assignment
9383       expr1 = expr2
9384    ! Now do the defined assignments
9385       do over components with typebound defined assignment [%cmp]
9386         #if one component's assignment procedure is INOUT
9387           t1 = expr1
9388           #if expr2 non-variable
9389             temp_x = expr2
9390             expr2 => temp_x
9391           # endif
9392           expr1 = expr2
9393           # for each cmp
9394             t1%cmp {defined=} expr2%cmp
9395             expr1%cmp = t1%cmp
9396         #else
9397           expr1 = expr2
9398
9399         # for each cmp
9400           expr1%cmp {defined=} expr2%cmp
9401         #endif
9402    */
9403
9404 /* The temporary assignments have to be put on top of the additional
9405    code to avoid the result being changed by the intrinsic assignment.
9406    */
9407 static int component_assignment_level = 0;
9408 static gfc_code *tmp_head = NULL, *tmp_tail = NULL;
9409
9410 static void
9411 generate_component_assignments (gfc_code **code, gfc_namespace *ns)
9412 {
9413   gfc_component *comp1, *comp2;
9414   gfc_code *this_code = NULL, *head = NULL, *tail = NULL;
9415   gfc_expr *t1;
9416   int error_count, depth;
9417
9418   gfc_get_errors (NULL, &error_count);
9419
9420   /* Filter out continuing processing after an error.  */
9421   if (error_count
9422       || (*code)->expr1->ts.type != BT_DERIVED
9423       || (*code)->expr2->ts.type != BT_DERIVED)
9424     return;
9425
9426   /* TODO: Handle more than one part array reference in assignments.  */
9427   depth = nonscalar_typebound_assign ((*code)->expr1->ts.u.derived,
9428                                       (*code)->expr1->rank ? 1 : 0);
9429   if (depth > 1)
9430     {
9431       gfc_warning ("TODO: type-bound defined assignment(s) at %L not "
9432                    "done because multiple part array references would "
9433                    "occur in intermediate expressions.", &(*code)->loc);
9434       return;
9435     }
9436
9437   component_assignment_level++;
9438
9439   /* Create a temporary so that functions get called only once.  */
9440   if ((*code)->expr2->expr_type != EXPR_VARIABLE
9441       && (*code)->expr2->expr_type != EXPR_CONSTANT)
9442     {
9443       gfc_expr *tmp_expr;
9444
9445       /* Assign the rhs to the temporary.  */
9446       tmp_expr = get_temp_from_expr ((*code)->expr1, ns);
9447       this_code = build_assignment (EXEC_ASSIGN,
9448                                     tmp_expr, (*code)->expr2,
9449                                     NULL, NULL, (*code)->loc);
9450       /* Add the code and substitute the rhs expression.  */
9451       add_code_to_chain (&this_code, &tmp_head, &tmp_tail);
9452       gfc_free_expr ((*code)->expr2);
9453       (*code)->expr2 = tmp_expr;
9454     }
9455
9456   /* Do the intrinsic assignment.  This is not needed if the lhs is one
9457      of the temporaries generated here, since the intrinsic assignment
9458      to the final result already does this.  */
9459   if ((*code)->expr1->symtree->n.sym->name[2] != '@')
9460     {
9461       this_code = build_assignment (EXEC_ASSIGN,
9462                                     (*code)->expr1, (*code)->expr2,
9463                                     NULL, NULL, (*code)->loc);
9464       add_code_to_chain (&this_code, &head, &tail);
9465     }
9466
9467   comp1 = (*code)->expr1->ts.u.derived->components;
9468   comp2 = (*code)->expr2->ts.u.derived->components;
9469
9470   t1 = NULL;
9471   for (; comp1; comp1 = comp1->next, comp2 = comp2->next)
9472     {
9473       bool inout = false;
9474
9475       /* The intrinsic assignment does the right thing for pointers
9476          of all kinds and allocatable components.  */
9477       if (comp1->ts.type != BT_DERIVED
9478           || comp1->attr.pointer
9479           || comp1->attr.allocatable
9480           || comp1->attr.proc_pointer_comp
9481           || comp1->attr.class_pointer
9482           || comp1->attr.proc_pointer)
9483         continue;
9484
9485       /* Make an assigment for this component.  */
9486       this_code = build_assignment (EXEC_ASSIGN,
9487                                     (*code)->expr1, (*code)->expr2,
9488                                     comp1, comp2, (*code)->loc);
9489
9490       /* Convert the assignment if there is a defined assignment for
9491          this type.  Otherwise, using the call from resolve_code,
9492          recurse into its components.  */
9493       resolve_code (this_code, ns);
9494
9495       if (this_code->op == EXEC_ASSIGN_CALL)
9496         {
9497           gfc_formal_arglist *dummy_args;
9498           gfc_symbol *rsym;
9499           /* Check that there is a typebound defined assignment.  If not,
9500              then this must be a module defined assignment.  We cannot
9501              use the defined_assign_comp attribute here because it must
9502              be this derived type that has the defined assignment and not
9503              a parent type.  */
9504           if (!(comp1->ts.u.derived->f2k_derived
9505                 && comp1->ts.u.derived->f2k_derived
9506                                         ->tb_op[INTRINSIC_ASSIGN]))
9507             {
9508               gfc_free_statements (this_code);
9509               this_code = NULL;
9510               continue;
9511             }
9512
9513           /* If the first argument of the subroutine has intent INOUT
9514              a temporary must be generated and used instead.  */
9515           rsym = this_code->resolved_sym;
9516           dummy_args = gfc_sym_get_dummy_args (rsym);
9517           if (dummy_args
9518               && dummy_args->sym->attr.intent == INTENT_INOUT)
9519             {
9520               gfc_code *temp_code;
9521               inout = true;
9522
9523               /* Build the temporary required for the assignment and put
9524                  it at the head of the generated code.  */
9525               if (!t1)
9526                 {
9527                   t1 = get_temp_from_expr ((*code)->expr1, ns);
9528                   temp_code = build_assignment (EXEC_ASSIGN,
9529                                                 t1, (*code)->expr1,
9530                                 NULL, NULL, (*code)->loc);
9531                   add_code_to_chain (&temp_code, &tmp_head, &tmp_tail);
9532                 }
9533
9534               /* Replace the first actual arg with the component of the
9535                  temporary.  */
9536               gfc_free_expr (this_code->ext.actual->expr);
9537               this_code->ext.actual->expr = gfc_copy_expr (t1);
9538               add_comp_ref (this_code->ext.actual->expr, comp1);
9539             }
9540           }
9541       else if (this_code->op == EXEC_ASSIGN && !this_code->next)
9542         {
9543           /* Don't add intrinsic assignments since they are already
9544              effected by the intrinsic assignment of the structure.  */
9545           gfc_free_statements (this_code);
9546           this_code = NULL;
9547           continue;
9548         }
9549
9550       add_code_to_chain (&this_code, &head, &tail);
9551
9552       if (t1 && inout)
9553         {
9554           /* Transfer the value to the final result.  */
9555           this_code = build_assignment (EXEC_ASSIGN,
9556                                         (*code)->expr1, t1,
9557                                         comp1, comp2, (*code)->loc);
9558           add_code_to_chain (&this_code, &head, &tail);
9559         }
9560     }
9561
9562   /* This is probably not necessary.  */
9563   if (this_code)
9564     {
9565       gfc_free_statements (this_code);
9566       this_code = NULL;
9567     }
9568
9569   /* Put the temporary assignments at the top of the generated code.  */
9570   if (tmp_head && component_assignment_level == 1)
9571     {
9572       gfc_append_code (tmp_head, head);
9573       head = tmp_head;
9574       tmp_head = tmp_tail = NULL;
9575     }
9576
9577   /* Now attach the remaining code chain to the input code.  Step on
9578      to the end of the new code since resolution is complete.  */
9579   gcc_assert ((*code)->op == EXEC_ASSIGN);
9580   tail->next = (*code)->next;
9581   /* Overwrite 'code' because this would place the intrinsic assignment
9582      before the temporary for the lhs is created.  */
9583   gfc_free_expr ((*code)->expr1);
9584   gfc_free_expr ((*code)->expr2);
9585   **code = *head;
9586   free (head);
9587   *code = tail;
9588
9589   component_assignment_level--;
9590 }
9591
9592
9593 /* Given a block of code, recursively resolve everything pointed to by this
9594    code block.  */
9595
9596 static void
9597 resolve_code (gfc_code *code, gfc_namespace *ns)
9598 {
9599   int omp_workshare_save;
9600   int forall_save, do_concurrent_save;
9601   code_stack frame;
9602   bool t;
9603
9604   frame.prev = cs_base;
9605   frame.head = code;
9606   cs_base = &frame;
9607
9608   find_reachable_labels (code);
9609
9610   for (; code; code = code->next)
9611     {
9612       frame.current = code;
9613       forall_save = forall_flag;
9614       do_concurrent_save = do_concurrent_flag;
9615
9616       if (code->op == EXEC_FORALL)
9617         {
9618           forall_flag = 1;
9619           gfc_resolve_forall (code, ns, forall_save);
9620           forall_flag = 2;
9621         }
9622       else if (code->block)
9623         {
9624           omp_workshare_save = -1;
9625           switch (code->op)
9626             {
9627             case EXEC_OMP_PARALLEL_WORKSHARE:
9628               omp_workshare_save = omp_workshare_flag;
9629               omp_workshare_flag = 1;
9630               gfc_resolve_omp_parallel_blocks (code, ns);
9631               break;
9632             case EXEC_OMP_PARALLEL:
9633             case EXEC_OMP_PARALLEL_DO:
9634             case EXEC_OMP_PARALLEL_SECTIONS:
9635             case EXEC_OMP_TASK:
9636               omp_workshare_save = omp_workshare_flag;
9637               omp_workshare_flag = 0;
9638               gfc_resolve_omp_parallel_blocks (code, ns);
9639               break;
9640             case EXEC_OMP_DO:
9641               gfc_resolve_omp_do_blocks (code, ns);
9642               break;
9643             case EXEC_SELECT_TYPE:
9644               /* Blocks are handled in resolve_select_type because we have
9645                  to transform the SELECT TYPE into ASSOCIATE first.  */
9646               break;
9647             case EXEC_DO_CONCURRENT:
9648               do_concurrent_flag = 1;
9649               gfc_resolve_blocks (code->block, ns);
9650               do_concurrent_flag = 2;
9651               break;
9652             case EXEC_OMP_WORKSHARE:
9653               omp_workshare_save = omp_workshare_flag;
9654               omp_workshare_flag = 1;
9655               /* FALL THROUGH */
9656             default:
9657               gfc_resolve_blocks (code->block, ns);
9658               break;
9659             }
9660
9661           if (omp_workshare_save != -1)
9662             omp_workshare_flag = omp_workshare_save;
9663         }
9664
9665       t = true;
9666       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
9667         t = gfc_resolve_expr (code->expr1);
9668       forall_flag = forall_save;
9669       do_concurrent_flag = do_concurrent_save;
9670
9671       if (!gfc_resolve_expr (code->expr2))
9672         t = false;
9673
9674       if (code->op == EXEC_ALLOCATE
9675           && !gfc_resolve_expr (code->expr3))
9676         t = false;
9677
9678       switch (code->op)
9679         {
9680         case EXEC_NOP:
9681         case EXEC_END_BLOCK:
9682         case EXEC_END_NESTED_BLOCK:
9683         case EXEC_CYCLE:
9684         case EXEC_PAUSE:
9685         case EXEC_STOP:
9686         case EXEC_ERROR_STOP:
9687         case EXEC_EXIT:
9688         case EXEC_CONTINUE:
9689         case EXEC_DT_END:
9690         case EXEC_ASSIGN_CALL:
9691         case EXEC_CRITICAL:
9692           break;
9693
9694         case EXEC_SYNC_ALL:
9695         case EXEC_SYNC_IMAGES:
9696         case EXEC_SYNC_MEMORY:
9697           resolve_sync (code);
9698           break;
9699
9700         case EXEC_LOCK:
9701         case EXEC_UNLOCK:
9702           resolve_lock_unlock (code);
9703           break;
9704
9705         case EXEC_ENTRY:
9706           /* Keep track of which entry we are up to.  */
9707           current_entry_id = code->ext.entry->id;
9708           break;
9709
9710         case EXEC_WHERE:
9711           resolve_where (code, NULL);
9712           break;
9713
9714         case EXEC_GOTO:
9715           if (code->expr1 != NULL)
9716             {
9717               if (code->expr1->ts.type != BT_INTEGER)
9718                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
9719                            "INTEGER variable", &code->expr1->where);
9720               else if (code->expr1->symtree->n.sym->attr.assign != 1)
9721                 gfc_error ("Variable '%s' has not been assigned a target "
9722                            "label at %L", code->expr1->symtree->n.sym->name,
9723                            &code->expr1->where);
9724             }
9725           else
9726             resolve_branch (code->label1, code);
9727           break;
9728
9729         case EXEC_RETURN:
9730           if (code->expr1 != NULL
9731                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
9732             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
9733                        "INTEGER return specifier", &code->expr1->where);
9734           break;
9735
9736         case EXEC_INIT_ASSIGN:
9737         case EXEC_END_PROCEDURE:
9738           break;
9739
9740         case EXEC_ASSIGN:
9741           if (!t)
9742             break;
9743
9744           if (!gfc_check_vardef_context (code->expr1, false, false, false, 
9745                                          _("assignment")))
9746             break;
9747
9748           if (resolve_ordinary_assign (code, ns))
9749             {
9750               if (code->op == EXEC_COMPCALL)
9751                 goto compcall;
9752               else
9753                 goto call;
9754             }
9755
9756           /* F03 7.4.1.3 for non-allocatable, non-pointer components.  */
9757           if (code->expr1->ts.type == BT_DERIVED
9758               && code->expr1->ts.u.derived->attr.defined_assign_comp)
9759             generate_component_assignments (&code, ns);
9760
9761           break;
9762
9763         case EXEC_LABEL_ASSIGN:
9764           if (code->label1->defined == ST_LABEL_UNKNOWN)
9765             gfc_error ("Label %d referenced at %L is never defined",
9766                        code->label1->value, &code->label1->where);
9767           if (t
9768               && (code->expr1->expr_type != EXPR_VARIABLE
9769                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
9770                   || code->expr1->symtree->n.sym->ts.kind
9771                      != gfc_default_integer_kind
9772                   || code->expr1->symtree->n.sym->as != NULL))
9773             gfc_error ("ASSIGN statement at %L requires a scalar "
9774                        "default INTEGER variable", &code->expr1->where);
9775           break;
9776
9777         case EXEC_POINTER_ASSIGN:
9778           {
9779             gfc_expr* e;
9780
9781             if (!t)
9782               break;
9783
9784             /* This is both a variable definition and pointer assignment
9785                context, so check both of them.  For rank remapping, a final
9786                array ref may be present on the LHS and fool gfc_expr_attr
9787                used in gfc_check_vardef_context.  Remove it.  */
9788             e = remove_last_array_ref (code->expr1);
9789             t = gfc_check_vardef_context (e, true, false, false,
9790                                           _("pointer assignment"));
9791             if (t)
9792               t = gfc_check_vardef_context (e, false, false, false,
9793                                             _("pointer assignment"));
9794             gfc_free_expr (e);
9795             if (!t)
9796               break;
9797
9798             gfc_check_pointer_assign (code->expr1, code->expr2);
9799             break;
9800           }
9801
9802         case EXEC_ARITHMETIC_IF:
9803           if (t
9804               && code->expr1->ts.type != BT_INTEGER
9805               && code->expr1->ts.type != BT_REAL)
9806             gfc_error ("Arithmetic IF statement at %L requires a numeric "
9807                        "expression", &code->expr1->where);
9808
9809           resolve_branch (code->label1, code);
9810           resolve_branch (code->label2, code);
9811           resolve_branch (code->label3, code);
9812           break;
9813
9814         case EXEC_IF:
9815           if (t && code->expr1 != NULL
9816               && (code->expr1->ts.type != BT_LOGICAL
9817                   || code->expr1->rank != 0))
9818             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
9819                        &code->expr1->where);
9820           break;
9821
9822         case EXEC_CALL:
9823         call:
9824           resolve_call (code);
9825           break;
9826
9827         case EXEC_COMPCALL:
9828         compcall:
9829           resolve_typebound_subroutine (code);
9830           break;
9831
9832         case EXEC_CALL_PPC:
9833           resolve_ppc_call (code);
9834           break;
9835
9836         case EXEC_SELECT:
9837           /* Select is complicated. Also, a SELECT construct could be
9838              a transformed computed GOTO.  */
9839           resolve_select (code, false);
9840           break;
9841
9842         case EXEC_SELECT_TYPE:
9843           resolve_select_type (code, ns);
9844           break;
9845
9846         case EXEC_BLOCK:
9847           resolve_block_construct (code);
9848           break;
9849
9850         case EXEC_DO:
9851           if (code->ext.iterator != NULL)
9852             {
9853               gfc_iterator *iter = code->ext.iterator;
9854               if (gfc_resolve_iterator (iter, true, false))
9855                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
9856             }
9857           break;
9858
9859         case EXEC_DO_WHILE:
9860           if (code->expr1 == NULL)
9861             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
9862           if (t
9863               && (code->expr1->rank != 0
9864                   || code->expr1->ts.type != BT_LOGICAL))
9865             gfc_error ("Exit condition of DO WHILE loop at %L must be "
9866                        "a scalar LOGICAL expression", &code->expr1->where);
9867           break;
9868
9869         case EXEC_ALLOCATE:
9870           if (t)
9871             resolve_allocate_deallocate (code, "ALLOCATE");
9872
9873           break;
9874
9875         case EXEC_DEALLOCATE:
9876           if (t)
9877             resolve_allocate_deallocate (code, "DEALLOCATE");
9878
9879           break;
9880
9881         case EXEC_OPEN:
9882           if (!gfc_resolve_open (code->ext.open))
9883             break;
9884
9885           resolve_branch (code->ext.open->err, code);
9886           break;
9887
9888         case EXEC_CLOSE:
9889           if (!gfc_resolve_close (code->ext.close))
9890             break;
9891
9892           resolve_branch (code->ext.close->err, code);
9893           break;
9894
9895         case EXEC_BACKSPACE:
9896         case EXEC_ENDFILE:
9897         case EXEC_REWIND:
9898         case EXEC_FLUSH:
9899           if (!gfc_resolve_filepos (code->ext.filepos))
9900             break;
9901
9902           resolve_branch (code->ext.filepos->err, code);
9903           break;
9904
9905         case EXEC_INQUIRE:
9906           if (!gfc_resolve_inquire (code->ext.inquire))
9907               break;
9908
9909           resolve_branch (code->ext.inquire->err, code);
9910           break;
9911
9912         case EXEC_IOLENGTH:
9913           gcc_assert (code->ext.inquire != NULL);
9914           if (!gfc_resolve_inquire (code->ext.inquire))
9915             break;
9916
9917           resolve_branch (code->ext.inquire->err, code);
9918           break;
9919
9920         case EXEC_WAIT:
9921           if (!gfc_resolve_wait (code->ext.wait))
9922             break;
9923
9924           resolve_branch (code->ext.wait->err, code);
9925           resolve_branch (code->ext.wait->end, code);
9926           resolve_branch (code->ext.wait->eor, code);
9927           break;
9928
9929         case EXEC_READ:
9930         case EXEC_WRITE:
9931           if (!gfc_resolve_dt (code->ext.dt, &code->loc))
9932             break;
9933
9934           resolve_branch (code->ext.dt->err, code);
9935           resolve_branch (code->ext.dt->end, code);
9936           resolve_branch (code->ext.dt->eor, code);
9937           break;
9938
9939         case EXEC_TRANSFER:
9940           resolve_transfer (code);
9941           break;
9942
9943         case EXEC_DO_CONCURRENT:
9944         case EXEC_FORALL:
9945           resolve_forall_iterators (code->ext.forall_iterator);
9946
9947           if (code->expr1 != NULL
9948               && (code->expr1->ts.type != BT_LOGICAL || code->expr1->rank))
9949             gfc_error ("FORALL mask clause at %L requires a scalar LOGICAL "
9950                        "expression", &code->expr1->where);
9951           break;
9952
9953         case EXEC_OMP_ATOMIC:
9954         case EXEC_OMP_BARRIER:
9955         case EXEC_OMP_CRITICAL:
9956         case EXEC_OMP_FLUSH:
9957         case EXEC_OMP_DO:
9958         case EXEC_OMP_MASTER:
9959         case EXEC_OMP_ORDERED:
9960         case EXEC_OMP_SECTIONS:
9961         case EXEC_OMP_SINGLE:
9962         case EXEC_OMP_TASKWAIT:
9963         case EXEC_OMP_TASKYIELD:
9964         case EXEC_OMP_WORKSHARE:
9965           gfc_resolve_omp_directive (code, ns);
9966           break;
9967
9968         case EXEC_OMP_PARALLEL:
9969         case EXEC_OMP_PARALLEL_DO:
9970         case EXEC_OMP_PARALLEL_SECTIONS:
9971         case EXEC_OMP_PARALLEL_WORKSHARE:
9972         case EXEC_OMP_TASK:
9973           omp_workshare_save = omp_workshare_flag;
9974           omp_workshare_flag = 0;
9975           gfc_resolve_omp_directive (code, ns);
9976           omp_workshare_flag = omp_workshare_save;
9977           break;
9978
9979         default:
9980           gfc_internal_error ("resolve_code(): Bad statement code");
9981         }
9982     }
9983
9984   cs_base = frame.prev;
9985 }
9986
9987
9988 /* Resolve initial values and make sure they are compatible with
9989    the variable.  */
9990
9991 static void
9992 resolve_values (gfc_symbol *sym)
9993 {
9994   bool t;
9995
9996   if (sym->value == NULL)
9997     return;
9998
9999   if (sym->value->expr_type == EXPR_STRUCTURE)
10000     t= resolve_structure_cons (sym->value, 1);
10001   else
10002     t = gfc_resolve_expr (sym->value);
10003
10004   if (!t)
10005     return;
10006
10007   gfc_check_assign_symbol (sym, NULL, sym->value);
10008 }
10009
10010
10011 /* Verify any BIND(C) derived types in the namespace so we can report errors
10012    for them once, rather than for each variable declared of that type.  */
10013
10014 static void
10015 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
10016 {
10017   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
10018       && derived_sym->attr.is_bind_c == 1)
10019     verify_bind_c_derived_type (derived_sym);
10020
10021   return;
10022 }
10023
10024
10025 /* Verify that any binding labels used in a given namespace do not collide
10026    with the names or binding labels of any global symbols.  */
10027
10028 static void
10029 gfc_verify_binding_labels (gfc_symbol *sym)
10030 {
10031   int has_error = 0;
10032
10033   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0
10034       && sym->attr.flavor != FL_DERIVED && sym->binding_label)
10035     {
10036       gfc_gsymbol *bind_c_sym;
10037
10038       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
10039       if (bind_c_sym != NULL
10040           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
10041         {
10042           if (sym->attr.if_source == IFSRC_DECL
10043               && (bind_c_sym->type != GSYM_SUBROUTINE
10044                   && bind_c_sym->type != GSYM_FUNCTION)
10045               && ((sym->attr.contained == 1
10046                    && strcmp (bind_c_sym->sym_name, sym->name) != 0)
10047                   || (sym->attr.use_assoc == 1
10048                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
10049             {
10050               /* Make sure global procedures don't collide with anything.  */
10051               gfc_error ("Binding label '%s' at %L collides with the global "
10052                          "entity '%s' at %L", sym->binding_label,
10053                          &(sym->declared_at), bind_c_sym->name,
10054                          &(bind_c_sym->where));
10055               has_error = 1;
10056             }
10057           else if (sym->attr.contained == 0
10058                    && (sym->attr.if_source == IFSRC_IFBODY
10059                        && sym->attr.flavor == FL_PROCEDURE)
10060                    && (bind_c_sym->sym_name != NULL
10061                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
10062             {
10063               /* Make sure procedures in interface bodies don't collide.  */
10064               gfc_error ("Binding label '%s' in interface body at %L collides "
10065                          "with the global entity '%s' at %L",
10066                          sym->binding_label,
10067                          &(sym->declared_at), bind_c_sym->name,
10068                          &(bind_c_sym->where));
10069               has_error = 1;
10070             }
10071           else if (sym->attr.contained == 0
10072                    && sym->attr.if_source == IFSRC_UNKNOWN)
10073             if ((sym->attr.use_assoc && bind_c_sym->mod_name
10074                  && strcmp (bind_c_sym->mod_name, sym->module) != 0)
10075                 || sym->attr.use_assoc == 0)
10076               {
10077                 gfc_error ("Binding label '%s' at %L collides with global "
10078                            "entity '%s' at %L", sym->binding_label,
10079                            &(sym->declared_at), bind_c_sym->name,
10080                            &(bind_c_sym->where));
10081                 has_error = 1;
10082               }
10083
10084           if (has_error != 0)
10085             /* Clear the binding label to prevent checking multiple times.  */
10086             sym->binding_label = NULL;
10087         }
10088       else if (bind_c_sym == NULL)
10089         {
10090           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
10091           bind_c_sym->where = sym->declared_at;
10092           bind_c_sym->sym_name = sym->name;
10093
10094           if (sym->attr.use_assoc == 1)
10095             bind_c_sym->mod_name = sym->module;
10096           else
10097             if (sym->ns->proc_name != NULL)
10098               bind_c_sym->mod_name = sym->ns->proc_name->name;
10099
10100           if (sym->attr.contained == 0)
10101             {
10102               if (sym->attr.subroutine)
10103                 bind_c_sym->type = GSYM_SUBROUTINE;
10104               else if (sym->attr.function)
10105                 bind_c_sym->type = GSYM_FUNCTION;
10106             }
10107         }
10108     }
10109   return;
10110 }
10111
10112
10113 /* Resolve an index expression.  */
10114
10115 static bool
10116 resolve_index_expr (gfc_expr *e)
10117 {
10118   if (!gfc_resolve_expr (e))
10119     return false;
10120
10121   if (!gfc_simplify_expr (e, 0))
10122     return false;
10123
10124   if (!gfc_specification_expr (e))
10125     return false;
10126
10127   return true;
10128 }
10129
10130
10131 /* Resolve a charlen structure.  */
10132
10133 static bool
10134 resolve_charlen (gfc_charlen *cl)
10135 {
10136   int i, k;
10137   bool saved_specification_expr;
10138
10139   if (cl->resolved)
10140     return true;
10141
10142   cl->resolved = 1;
10143   saved_specification_expr = specification_expr;
10144   specification_expr = true;
10145
10146   if (cl->length_from_typespec)
10147     {
10148       if (!gfc_resolve_expr (cl->length))
10149         {
10150           specification_expr = saved_specification_expr;
10151           return false;
10152         }
10153
10154       if (!gfc_simplify_expr (cl->length, 0))
10155         {
10156           specification_expr = saved_specification_expr;
10157           return false;
10158         }
10159     }
10160   else
10161     {
10162
10163       if (!resolve_index_expr (cl->length))
10164         {
10165           specification_expr = saved_specification_expr;
10166           return false;
10167         }
10168     }
10169
10170   /* "If the character length parameter value evaluates to a negative
10171      value, the length of character entities declared is zero."  */
10172   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
10173     {
10174       if (gfc_option.warn_surprising)
10175         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
10176                          " the length has been set to zero",
10177                          &cl->length->where, i);
10178       gfc_replace_expr (cl->length,
10179                         gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
10180     }
10181
10182   /* Check that the character length is not too large.  */
10183   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
10184   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
10185       && cl->length->ts.type == BT_INTEGER
10186       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
10187     {
10188       gfc_error ("String length at %L is too large", &cl->length->where);
10189       specification_expr = saved_specification_expr;
10190       return false;
10191     }
10192
10193   specification_expr = saved_specification_expr;
10194   return true;
10195 }
10196
10197
10198 /* Test for non-constant shape arrays.  */
10199
10200 static bool
10201 is_non_constant_shape_array (gfc_symbol *sym)
10202 {
10203   gfc_expr *e;
10204   int i;
10205   bool not_constant;
10206
10207   not_constant = false;
10208   if (sym->as != NULL)
10209     {
10210       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
10211          has not been simplified; parameter array references.  Do the
10212          simplification now.  */
10213       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
10214         {
10215           e = sym->as->lower[i];
10216           if (e && (!resolve_index_expr(e)
10217                     || !gfc_is_constant_expr (e)))
10218             not_constant = true;
10219           e = sym->as->upper[i];
10220           if (e && (!resolve_index_expr(e)
10221                     || !gfc_is_constant_expr (e)))
10222             not_constant = true;
10223         }
10224     }
10225   return not_constant;
10226 }
10227
10228 /* Given a symbol and an initialization expression, add code to initialize
10229    the symbol to the function entry.  */
10230 static void
10231 build_init_assign (gfc_symbol *sym, gfc_expr *init)
10232 {
10233   gfc_expr *lval;
10234   gfc_code *init_st;
10235   gfc_namespace *ns = sym->ns;
10236
10237   /* Search for the function namespace if this is a contained
10238      function without an explicit result.  */
10239   if (sym->attr.function && sym == sym->result
10240       && sym->name != sym->ns->proc_name->name)
10241     {
10242       ns = ns->contained;
10243       for (;ns; ns = ns->sibling)
10244         if (strcmp (ns->proc_name->name, sym->name) == 0)
10245           break;
10246     }
10247
10248   if (ns == NULL)
10249     {
10250       gfc_free_expr (init);
10251       return;
10252     }
10253
10254   /* Build an l-value expression for the result.  */
10255   lval = gfc_lval_expr_from_sym (sym);
10256
10257   /* Add the code at scope entry.  */
10258   init_st = gfc_get_code ();
10259   init_st->next = ns->code;
10260   ns->code = init_st;
10261
10262   /* Assign the default initializer to the l-value.  */
10263   init_st->loc = sym->declared_at;
10264   init_st->op = EXEC_INIT_ASSIGN;
10265   init_st->expr1 = lval;
10266   init_st->expr2 = init;
10267 }
10268
10269 /* Assign the default initializer to a derived type variable or result.  */
10270
10271 static void
10272 apply_default_init (gfc_symbol *sym)
10273 {
10274   gfc_expr *init = NULL;
10275
10276   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
10277     return;
10278
10279   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
10280     init = gfc_default_initializer (&sym->ts);
10281
10282   if (init == NULL && sym->ts.type != BT_CLASS)
10283     return;
10284
10285   build_init_assign (sym, init);
10286   sym->attr.referenced = 1;
10287 }
10288
10289 /* Build an initializer for a local integer, real, complex, logical, or
10290    character variable, based on the command line flags finit-local-zero,
10291    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns
10292    null if the symbol should not have a default initialization.  */
10293 static gfc_expr *
10294 build_default_init_expr (gfc_symbol *sym)
10295 {
10296   int char_len;
10297   gfc_expr *init_expr;
10298   int i;
10299
10300   /* These symbols should never have a default initialization.  */
10301   if (sym->attr.allocatable
10302       || sym->attr.external
10303       || sym->attr.dummy
10304       || sym->attr.pointer
10305       || sym->attr.in_equivalence
10306       || sym->attr.in_common
10307       || sym->attr.data
10308       || sym->module
10309       || sym->attr.cray_pointee
10310       || sym->attr.cray_pointer
10311       || sym->assoc)
10312     return NULL;
10313
10314   /* Now we'll try to build an initializer expression.  */
10315   init_expr = gfc_get_constant_expr (sym->ts.type, sym->ts.kind,
10316                                      &sym->declared_at);
10317
10318   /* We will only initialize integers, reals, complex, logicals, and
10319      characters, and only if the corresponding command-line flags
10320      were set.  Otherwise, we free init_expr and return null.  */
10321   switch (sym->ts.type)
10322     {
10323     case BT_INTEGER:
10324       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
10325         mpz_set_si (init_expr->value.integer,
10326                          gfc_option.flag_init_integer_value);
10327       else
10328         {
10329           gfc_free_expr (init_expr);
10330           init_expr = NULL;
10331         }
10332       break;
10333
10334     case BT_REAL:
10335       switch (gfc_option.flag_init_real)
10336         {
10337         case GFC_INIT_REAL_SNAN:
10338           init_expr->is_snan = 1;
10339           /* Fall through.  */
10340         case GFC_INIT_REAL_NAN:
10341           mpfr_set_nan (init_expr->value.real);
10342           break;
10343
10344         case GFC_INIT_REAL_INF:
10345           mpfr_set_inf (init_expr->value.real, 1);
10346           break;
10347
10348         case GFC_INIT_REAL_NEG_INF:
10349           mpfr_set_inf (init_expr->value.real, -1);
10350           break;
10351
10352         case GFC_INIT_REAL_ZERO:
10353           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
10354           break;
10355
10356         default:
10357           gfc_free_expr (init_expr);
10358           init_expr = NULL;
10359           break;
10360         }
10361       break;
10362
10363     case BT_COMPLEX:
10364       switch (gfc_option.flag_init_real)
10365         {
10366         case GFC_INIT_REAL_SNAN:
10367           init_expr->is_snan = 1;
10368           /* Fall through.  */
10369         case GFC_INIT_REAL_NAN:
10370           mpfr_set_nan (mpc_realref (init_expr->value.complex));
10371           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
10372           break;
10373
10374         case GFC_INIT_REAL_INF:
10375           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
10376           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
10377           break;
10378
10379         case GFC_INIT_REAL_NEG_INF:
10380           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
10381           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
10382           break;
10383
10384         case GFC_INIT_REAL_ZERO:
10385           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
10386           break;
10387
10388         default:
10389           gfc_free_expr (init_expr);
10390           init_expr = NULL;
10391           break;
10392         }
10393       break;
10394
10395     case BT_LOGICAL:
10396       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
10397         init_expr->value.logical = 0;
10398       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
10399         init_expr->value.logical = 1;
10400       else
10401         {
10402           gfc_free_expr (init_expr);
10403           init_expr = NULL;
10404         }
10405       break;
10406
10407     case BT_CHARACTER:
10408       /* For characters, the length must be constant in order to
10409          create a default initializer.  */
10410       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
10411           && sym->ts.u.cl->length
10412           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
10413         {
10414           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
10415           init_expr->value.character.length = char_len;
10416           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
10417           for (i = 0; i < char_len; i++)
10418             init_expr->value.character.string[i]
10419               = (unsigned char) gfc_option.flag_init_character_value;
10420         }
10421       else
10422         {
10423           gfc_free_expr (init_expr);
10424           init_expr = NULL;
10425         }
10426       if (!init_expr && gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
10427           && sym->ts.u.cl->length)
10428         {
10429           gfc_actual_arglist *arg;
10430           init_expr = gfc_get_expr ();
10431           init_expr->where = sym->declared_at;
10432           init_expr->ts = sym->ts;
10433           init_expr->expr_type = EXPR_FUNCTION;
10434           init_expr->value.function.isym =
10435                 gfc_intrinsic_function_by_id (GFC_ISYM_REPEAT);
10436           init_expr->value.function.name = "repeat";
10437           arg = gfc_get_actual_arglist ();
10438           arg->expr = gfc_get_character_expr (sym->ts.kind, &sym->declared_at,
10439                                               NULL, 1);
10440           arg->expr->value.character.string[0]
10441                 = gfc_option.flag_init_character_value;
10442           arg->next = gfc_get_actual_arglist ();
10443           arg->next->expr = gfc_copy_expr (sym->ts.u.cl->length);
10444           init_expr->value.function.actual = arg;
10445         }
10446       break;
10447
10448     default:
10449      gfc_free_expr (init_expr);
10450      init_expr = NULL;
10451     }
10452   return init_expr;
10453 }
10454
10455 /* Add an initialization expression to a local variable.  */
10456 static void
10457 apply_default_init_local (gfc_symbol *sym)
10458 {
10459   gfc_expr *init = NULL;
10460
10461   /* The symbol should be a variable or a function return value.  */
10462   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
10463       || (sym->attr.function && sym->result != sym))
10464     return;
10465
10466   /* Try to build the initializer expression.  If we can't initialize
10467      this symbol, then init will be NULL.  */
10468   init = build_default_init_expr (sym);
10469   if (init == NULL)
10470     return;
10471
10472   /* For saved variables, we don't want to add an initializer at function
10473      entry, so we just add a static initializer. Note that automatic variables
10474      are stack allocated even with -fno-automatic; we have also to exclude
10475      result variable, which are also nonstatic.  */
10476   if (sym->attr.save || sym->ns->save_all
10477       || (gfc_option.flag_max_stack_var_size == 0 && !sym->attr.result
10478           && (!sym->attr.dimension || !is_non_constant_shape_array (sym))))
10479     {
10480       /* Don't clobber an existing initializer!  */
10481       gcc_assert (sym->value == NULL);
10482       sym->value = init;
10483       return;
10484     }
10485
10486   build_init_assign (sym, init);
10487 }
10488
10489
10490 /* Resolution of common features of flavors variable and procedure.  */
10491
10492 static bool
10493 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
10494 {
10495   gfc_array_spec *as;
10496
10497   if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
10498     as = CLASS_DATA (sym)->as;
10499   else
10500     as = sym->as;
10501
10502   /* Constraints on deferred shape variable.  */
10503   if (as == NULL || as->type != AS_DEFERRED)
10504     {
10505       bool pointer, allocatable, dimension;
10506
10507       if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
10508         {
10509           pointer = CLASS_DATA (sym)->attr.class_pointer;
10510           allocatable = CLASS_DATA (sym)->attr.allocatable;
10511           dimension = CLASS_DATA (sym)->attr.dimension;
10512         }
10513       else
10514         {
10515           pointer = sym->attr.pointer && !sym->attr.select_type_temporary;
10516           allocatable = sym->attr.allocatable;
10517           dimension = sym->attr.dimension;
10518         }
10519
10520       if (allocatable)
10521         {
10522           if (dimension && as->type != AS_ASSUMED_RANK)
10523             {
10524               gfc_error ("Allocatable array '%s' at %L must have a deferred "
10525                          "shape or assumed rank", sym->name, &sym->declared_at);
10526               return false;
10527             }
10528           else if (!gfc_notify_std (GFC_STD_F2003, "Scalar object "
10529                                     "'%s' at %L may not be ALLOCATABLE", 
10530                                     sym->name, &sym->declared_at))
10531             return false;
10532         }
10533
10534       if (pointer && dimension && as->type != AS_ASSUMED_RANK)
10535         {
10536           gfc_error ("Array pointer '%s' at %L must have a deferred shape or "
10537                      "assumed rank", sym->name, &sym->declared_at);
10538           return false;
10539         }
10540     }
10541   else
10542     {
10543       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
10544           && sym->ts.type != BT_CLASS && !sym->assoc)
10545         {
10546           gfc_error ("Array '%s' at %L cannot have a deferred shape",
10547                      sym->name, &sym->declared_at);
10548           return false;
10549          }
10550     }
10551
10552   /* Constraints on polymorphic variables.  */
10553   if (sym->ts.type == BT_CLASS && !(sym->result && sym->result != sym))
10554     {
10555       /* F03:C502.  */
10556       if (sym->attr.class_ok
10557           && !sym->attr.select_type_temporary
10558           && !UNLIMITED_POLY (sym)
10559           && !gfc_type_is_extensible (CLASS_DATA (sym)->ts.u.derived))
10560         {
10561           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
10562                      CLASS_DATA (sym)->ts.u.derived->name, sym->name,
10563                      &sym->declared_at);
10564           return false;
10565         }
10566
10567       /* F03:C509.  */
10568       /* Assume that use associated symbols were checked in the module ns.
10569          Class-variables that are associate-names are also something special
10570          and excepted from the test.  */
10571       if (!sym->attr.class_ok && !sym->attr.use_assoc && !sym->assoc)
10572         {
10573           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
10574                      "or pointer", sym->name, &sym->declared_at);
10575           return false;
10576         }
10577     }
10578
10579   return true;
10580 }
10581
10582
10583 /* Additional checks for symbols with flavor variable and derived
10584    type.  To be called from resolve_fl_variable.  */
10585
10586 static bool
10587 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
10588 {
10589   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
10590
10591   /* Check to see if a derived type is blocked from being host
10592      associated by the presence of another class I symbol in the same
10593      namespace.  14.6.1.3 of the standard and the discussion on
10594      comp.lang.fortran.  */
10595   if (sym->ns != sym->ts.u.derived->ns
10596       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
10597     {
10598       gfc_symbol *s;
10599       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
10600       if (s && s->attr.generic)
10601         s = gfc_find_dt_in_generic (s);
10602       if (s && s->attr.flavor != FL_DERIVED)
10603         {
10604           gfc_error ("The type '%s' cannot be host associated at %L "
10605                      "because it is blocked by an incompatible object "
10606                      "of the same name declared at %L",
10607                      sym->ts.u.derived->name, &sym->declared_at,
10608                      &s->declared_at);
10609           return false;
10610         }
10611     }
10612
10613   /* 4th constraint in section 11.3: "If an object of a type for which
10614      component-initialization is specified (R429) appears in the
10615      specification-part of a module and does not have the ALLOCATABLE
10616      or POINTER attribute, the object shall have the SAVE attribute."
10617
10618      The check for initializers is performed with
10619      gfc_has_default_initializer because gfc_default_initializer generates
10620      a hidden default for allocatable components.  */
10621   if (!(sym->value || no_init_flag) && sym->ns->proc_name
10622       && sym->ns->proc_name->attr.flavor == FL_MODULE
10623       && !sym->ns->save_all && !sym->attr.save
10624       && !sym->attr.pointer && !sym->attr.allocatable
10625       && gfc_has_default_initializer (sym->ts.u.derived)
10626       && !gfc_notify_std (GFC_STD_F2008, "Implied SAVE for module variable "
10627                           "'%s' at %L, needed due to the default "
10628                           "initialization", sym->name, &sym->declared_at))
10629     return false;
10630
10631   /* Assign default initializer.  */
10632   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
10633       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
10634     {
10635       sym->value = gfc_default_initializer (&sym->ts);
10636     }
10637
10638   return true;
10639 }
10640
10641
10642 /* Resolve symbols with flavor variable.  */
10643
10644 static bool
10645 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
10646 {
10647   int no_init_flag, automatic_flag;
10648   gfc_expr *e;
10649   const char *auto_save_msg;
10650   bool saved_specification_expr;
10651
10652   auto_save_msg = "Automatic object '%s' at %L cannot have the "
10653                   "SAVE attribute";
10654
10655   if (!resolve_fl_var_and_proc (sym, mp_flag))
10656     return false;
10657
10658   /* Set this flag to check that variables are parameters of all entries.
10659      This check is effected by the call to gfc_resolve_expr through
10660      is_non_constant_shape_array.  */
10661   saved_specification_expr = specification_expr;
10662   specification_expr = true;
10663
10664   if (sym->ns->proc_name
10665       && (sym->ns->proc_name->attr.flavor == FL_MODULE
10666           || sym->ns->proc_name->attr.is_main_program)
10667       && !sym->attr.use_assoc
10668       && !sym->attr.allocatable
10669       && !sym->attr.pointer
10670       && is_non_constant_shape_array (sym))
10671     {
10672       /* The shape of a main program or module array needs to be
10673          constant.  */
10674       gfc_error ("The module or main program array '%s' at %L must "
10675                  "have constant shape", sym->name, &sym->declared_at);
10676       specification_expr = saved_specification_expr;
10677       return false;
10678     }
10679
10680   /* Constraints on deferred type parameter.  */
10681   if (sym->ts.deferred && !(sym->attr.pointer || sym->attr.allocatable))
10682     {
10683       gfc_error ("Entity '%s' at %L has a deferred type parameter and "
10684                  "requires either the pointer or allocatable attribute",
10685                      sym->name, &sym->declared_at);
10686       specification_expr = saved_specification_expr;
10687       return false;
10688     }
10689
10690   if (sym->ts.type == BT_CHARACTER)
10691     {
10692       /* Make sure that character string variables with assumed length are
10693          dummy arguments.  */
10694       e = sym->ts.u.cl->length;
10695       if (e == NULL && !sym->attr.dummy && !sym->attr.result
10696           && !sym->ts.deferred && !sym->attr.select_type_temporary)
10697         {
10698           gfc_error ("Entity with assumed character length at %L must be a "
10699                      "dummy argument or a PARAMETER", &sym->declared_at);
10700           specification_expr = saved_specification_expr;
10701           return false;
10702         }
10703
10704       if (e && sym->attr.save == SAVE_EXPLICIT && !gfc_is_constant_expr (e))
10705         {
10706           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10707           specification_expr = saved_specification_expr;
10708           return false;
10709         }
10710
10711       if (!gfc_is_constant_expr (e)
10712           && !(e->expr_type == EXPR_VARIABLE
10713                && e->symtree->n.sym->attr.flavor == FL_PARAMETER))
10714         {
10715           if (!sym->attr.use_assoc && sym->ns->proc_name
10716               && (sym->ns->proc_name->attr.flavor == FL_MODULE
10717                   || sym->ns->proc_name->attr.is_main_program))
10718             {
10719               gfc_error ("'%s' at %L must have constant character length "
10720                         "in this context", sym->name, &sym->declared_at);
10721               specification_expr = saved_specification_expr;
10722               return false;
10723             }
10724           if (sym->attr.in_common)
10725             {
10726               gfc_error ("COMMON variable '%s' at %L must have constant "
10727                          "character length", sym->name, &sym->declared_at);
10728               specification_expr = saved_specification_expr;
10729               return false;
10730             }
10731         }
10732     }
10733
10734   if (sym->value == NULL && sym->attr.referenced)
10735     apply_default_init_local (sym); /* Try to apply a default initialization.  */
10736
10737   /* Determine if the symbol may not have an initializer.  */
10738   no_init_flag = automatic_flag = 0;
10739   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
10740       || sym->attr.intrinsic || sym->attr.result)
10741     no_init_flag = 1;
10742   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
10743            && is_non_constant_shape_array (sym))
10744     {
10745       no_init_flag = automatic_flag = 1;
10746
10747       /* Also, they must not have the SAVE attribute.
10748          SAVE_IMPLICIT is checked below.  */
10749       if (sym->as && sym->attr.codimension)
10750         {
10751           int corank = sym->as->corank;
10752           sym->as->corank = 0;
10753           no_init_flag = automatic_flag = is_non_constant_shape_array (sym);
10754           sym->as->corank = corank;
10755         }
10756       if (automatic_flag && sym->attr.save == SAVE_EXPLICIT)
10757         {
10758           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10759           specification_expr = saved_specification_expr;
10760           return false;
10761         }
10762     }
10763
10764   /* Ensure that any initializer is simplified.  */
10765   if (sym->value)
10766     gfc_simplify_expr (sym->value, 1);
10767
10768   /* Reject illegal initializers.  */
10769   if (!sym->mark && sym->value)
10770     {
10771       if (sym->attr.allocatable || (sym->ts.type == BT_CLASS
10772                                     && CLASS_DATA (sym)->attr.allocatable))
10773         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
10774                    sym->name, &sym->declared_at);
10775       else if (sym->attr.external)
10776         gfc_error ("External '%s' at %L cannot have an initializer",
10777                    sym->name, &sym->declared_at);
10778       else if (sym->attr.dummy
10779         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
10780         gfc_error ("Dummy '%s' at %L cannot have an initializer",
10781                    sym->name, &sym->declared_at);
10782       else if (sym->attr.intrinsic)
10783         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
10784                    sym->name, &sym->declared_at);
10785       else if (sym->attr.result)
10786         gfc_error ("Function result '%s' at %L cannot have an initializer",
10787                    sym->name, &sym->declared_at);
10788       else if (automatic_flag)
10789         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
10790                    sym->name, &sym->declared_at);
10791       else
10792         goto no_init_error;
10793       specification_expr = saved_specification_expr;
10794       return false;
10795     }
10796
10797 no_init_error:
10798   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
10799     {
10800       bool res = resolve_fl_variable_derived (sym, no_init_flag);
10801       specification_expr = saved_specification_expr;
10802       return res;
10803     }
10804
10805   specification_expr = saved_specification_expr;
10806   return true;
10807 }
10808
10809
10810 /* Resolve a procedure.  */
10811
10812 static bool
10813 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
10814 {
10815   gfc_formal_arglist *arg;
10816
10817   if (sym->attr.function
10818       && !resolve_fl_var_and_proc (sym, mp_flag))
10819     return false;
10820
10821   if (sym->ts.type == BT_CHARACTER)
10822     {
10823       gfc_charlen *cl = sym->ts.u.cl;
10824
10825       if (cl && cl->length && gfc_is_constant_expr (cl->length)
10826              && !resolve_charlen (cl))
10827         return false;
10828
10829       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
10830           && sym->attr.proc == PROC_ST_FUNCTION)
10831         {
10832           gfc_error ("Character-valued statement function '%s' at %L must "
10833                      "have constant length", sym->name, &sym->declared_at);
10834           return false;
10835         }
10836     }
10837
10838   /* Ensure that derived type for are not of a private type.  Internal
10839      module procedures are excluded by 2.2.3.3 - i.e., they are not
10840      externally accessible and can access all the objects accessible in
10841      the host.  */
10842   if (!(sym->ns->parent
10843         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
10844       && gfc_check_symbol_access (sym))
10845     {
10846       gfc_interface *iface;
10847
10848       for (arg = gfc_sym_get_dummy_args (sym); arg; arg = arg->next)
10849         {
10850           if (arg->sym
10851               && arg->sym->ts.type == BT_DERIVED
10852               && !arg->sym->ts.u.derived->attr.use_assoc
10853               && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10854               && !gfc_notify_std (GFC_STD_F2003, "'%s' is of a PRIVATE type "
10855                                   "and cannot be a dummy argument"
10856                                   " of '%s', which is PUBLIC at %L", 
10857                                   arg->sym->name, sym->name, 
10858                                   &sym->declared_at))
10859             {
10860               /* Stop this message from recurring.  */
10861               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10862               return false;
10863             }
10864         }
10865
10866       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10867          PRIVATE to the containing module.  */
10868       for (iface = sym->generic; iface; iface = iface->next)
10869         {
10870           for (arg = gfc_sym_get_dummy_args (iface->sym); arg; arg = arg->next)
10871             {
10872               if (arg->sym
10873                   && arg->sym->ts.type == BT_DERIVED
10874                   && !arg->sym->ts.u.derived->attr.use_assoc
10875                   && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10876                   && !gfc_notify_std (GFC_STD_F2003, "Procedure '%s' in "
10877                                       "PUBLIC interface '%s' at %L "
10878                                       "takes dummy arguments of '%s' which "
10879                                       "is PRIVATE", iface->sym->name, 
10880                                       sym->name, &iface->sym->declared_at, 
10881                                       gfc_typename(&arg->sym->ts)))
10882                 {
10883                   /* Stop this message from recurring.  */
10884                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10885                   return false;
10886                 }
10887              }
10888         }
10889
10890       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10891          PRIVATE to the containing module.  */
10892       for (iface = sym->generic; iface; iface = iface->next)
10893         {
10894           for (arg = gfc_sym_get_dummy_args (iface->sym); arg; arg = arg->next)
10895             {
10896               if (arg->sym
10897                   && arg->sym->ts.type == BT_DERIVED
10898                   && !arg->sym->ts.u.derived->attr.use_assoc
10899                   && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10900                   && !gfc_notify_std (GFC_STD_F2003, "Procedure '%s' in "
10901                                       "PUBLIC interface '%s' at %L takes "
10902                                       "dummy arguments of '%s' which is "
10903                                       "PRIVATE", iface->sym->name, 
10904                                       sym->name, &iface->sym->declared_at, 
10905                                       gfc_typename(&arg->sym->ts)))
10906                 {
10907                   /* Stop this message from recurring.  */
10908                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10909                   return false;
10910                 }
10911              }
10912         }
10913     }
10914
10915   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
10916       && !sym->attr.proc_pointer)
10917     {
10918       gfc_error ("Function '%s' at %L cannot have an initializer",
10919                  sym->name, &sym->declared_at);
10920       return false;
10921     }
10922
10923   /* An external symbol may not have an initializer because it is taken to be
10924      a procedure. Exception: Procedure Pointers.  */
10925   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
10926     {
10927       gfc_error ("External object '%s' at %L may not have an initializer",
10928                  sym->name, &sym->declared_at);
10929       return false;
10930     }
10931
10932   /* An elemental function is required to return a scalar 12.7.1  */
10933   if (sym->attr.elemental && sym->attr.function && sym->as)
10934     {
10935       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
10936                  "result", sym->name, &sym->declared_at);
10937       /* Reset so that the error only occurs once.  */
10938       sym->attr.elemental = 0;
10939       return false;
10940     }
10941
10942   if (sym->attr.proc == PROC_ST_FUNCTION
10943       && (sym->attr.allocatable || sym->attr.pointer))
10944     {
10945       gfc_error ("Statement function '%s' at %L may not have pointer or "
10946                  "allocatable attribute", sym->name, &sym->declared_at);
10947       return false;
10948     }
10949
10950   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
10951      char-len-param shall not be array-valued, pointer-valued, recursive
10952      or pure.  ....snip... A character value of * may only be used in the
10953      following ways: (i) Dummy arg of procedure - dummy associates with
10954      actual length; (ii) To declare a named constant; or (iii) External
10955      function - but length must be declared in calling scoping unit.  */
10956   if (sym->attr.function
10957       && sym->ts.type == BT_CHARACTER && !sym->ts.deferred
10958       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
10959     {
10960       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
10961           || (sym->attr.recursive) || (sym->attr.pure))
10962         {
10963           if (sym->as && sym->as->rank)
10964             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10965                        "array-valued", sym->name, &sym->declared_at);
10966
10967           if (sym->attr.pointer)
10968             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10969                        "pointer-valued", sym->name, &sym->declared_at);
10970
10971           if (sym->attr.pure)
10972             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10973                        "pure", sym->name, &sym->declared_at);
10974
10975           if (sym->attr.recursive)
10976             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10977                        "recursive", sym->name, &sym->declared_at);
10978
10979           return false;
10980         }
10981
10982       /* Appendix B.2 of the standard.  Contained functions give an
10983          error anyway.  Fixed-form is likely to be F77/legacy. Deferred
10984          character length is an F2003 feature.  */
10985       if (!sym->attr.contained
10986             && gfc_current_form != FORM_FIXED
10987             && !sym->ts.deferred)
10988         gfc_notify_std (GFC_STD_F95_OBS,
10989                         "CHARACTER(*) function '%s' at %L",
10990                         sym->name, &sym->declared_at);
10991     }
10992
10993   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
10994     {
10995       gfc_formal_arglist *curr_arg;
10996       int has_non_interop_arg = 0;
10997
10998       if (!verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common, 
10999                               sym->common_block))
11000         {
11001           /* Clear these to prevent looking at them again if there was an
11002              error.  */
11003           sym->attr.is_bind_c = 0;
11004           sym->attr.is_c_interop = 0;
11005           sym->ts.is_c_interop = 0;
11006         }
11007       else
11008         {
11009           /* So far, no errors have been found.  */
11010           sym->attr.is_c_interop = 1;
11011           sym->ts.is_c_interop = 1;
11012         }
11013
11014       curr_arg = gfc_sym_get_dummy_args (sym);
11015       while (curr_arg != NULL)
11016         {
11017           /* Skip implicitly typed dummy args here.  */
11018           if (curr_arg->sym->attr.implicit_type == 0)
11019             if (!gfc_verify_c_interop_param (curr_arg->sym))
11020               /* If something is found to fail, record the fact so we
11021                  can mark the symbol for the procedure as not being
11022                  BIND(C) to try and prevent multiple errors being
11023                  reported.  */
11024               has_non_interop_arg = 1;
11025
11026           curr_arg = curr_arg->next;
11027         }
11028
11029       /* See if any of the arguments were not interoperable and if so, clear
11030          the procedure symbol to prevent duplicate error messages.  */
11031       if (has_non_interop_arg != 0)
11032         {
11033           sym->attr.is_c_interop = 0;
11034           sym->ts.is_c_interop = 0;
11035           sym->attr.is_bind_c = 0;
11036         }
11037     }
11038
11039   if (!sym->attr.proc_pointer)
11040     {
11041       if (sym->attr.save == SAVE_EXPLICIT)
11042         {
11043           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
11044                      "in '%s' at %L", sym->name, &sym->declared_at);
11045           return false;
11046         }
11047       if (sym->attr.intent)
11048         {
11049           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
11050                      "in '%s' at %L", sym->name, &sym->declared_at);
11051           return false;
11052         }
11053       if (sym->attr.subroutine && sym->attr.result)
11054         {
11055           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
11056                      "in '%s' at %L", sym->name, &sym->declared_at);
11057           return false;
11058         }
11059       if (sym->attr.external && sym->attr.function
11060           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
11061               || sym->attr.contained))
11062         {
11063           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
11064                      "in '%s' at %L", sym->name, &sym->declared_at);
11065           return false;
11066         }
11067       if (strcmp ("ppr@", sym->name) == 0)
11068         {
11069           gfc_error ("Procedure pointer result '%s' at %L "
11070                      "is missing the pointer attribute",
11071                      sym->ns->proc_name->name, &sym->declared_at);
11072           return false;
11073         }
11074     }
11075
11076   return true;
11077 }
11078
11079
11080 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
11081    been defined and we now know their defined arguments, check that they fulfill
11082    the requirements of the standard for procedures used as finalizers.  */
11083
11084 static bool
11085 gfc_resolve_finalizers (gfc_symbol* derived)
11086 {
11087   gfc_finalizer* list;
11088   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
11089   bool result = true;
11090   bool seen_scalar = false;
11091
11092   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
11093     return true;
11094
11095   /* Walk over the list of finalizer-procedures, check them, and if any one
11096      does not fit in with the standard's definition, print an error and remove
11097      it from the list.  */
11098   prev_link = &derived->f2k_derived->finalizers;
11099   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
11100     {
11101       gfc_formal_arglist *dummy_args;
11102       gfc_symbol* arg;
11103       gfc_finalizer* i;
11104       int my_rank;
11105
11106       /* Skip this finalizer if we already resolved it.  */
11107       if (list->proc_tree)
11108         {
11109           prev_link = &(list->next);
11110           continue;
11111         }
11112
11113       /* Check this exists and is a SUBROUTINE.  */
11114       if (!list->proc_sym->attr.subroutine)
11115         {
11116           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
11117                      list->proc_sym->name, &list->where);
11118           goto error;
11119         }
11120
11121       /* We should have exactly one argument.  */
11122       dummy_args = gfc_sym_get_dummy_args (list->proc_sym);
11123       if (!dummy_args || dummy_args->next)
11124         {
11125           gfc_error ("FINAL procedure at %L must have exactly one argument",
11126                      &list->where);
11127           goto error;
11128         }
11129       arg = dummy_args->sym;
11130
11131       /* This argument must be of our type.  */
11132       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
11133         {
11134           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
11135                      &arg->declared_at, derived->name);
11136           goto error;
11137         }
11138
11139       /* It must neither be a pointer nor allocatable nor optional.  */
11140       if (arg->attr.pointer)
11141         {
11142           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
11143                      &arg->declared_at);
11144           goto error;
11145         }
11146       if (arg->attr.allocatable)
11147         {
11148           gfc_error ("Argument of FINAL procedure at %L must not be"
11149                      " ALLOCATABLE", &arg->declared_at);
11150           goto error;
11151         }
11152       if (arg->attr.optional)
11153         {
11154           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
11155                      &arg->declared_at);
11156           goto error;
11157         }
11158
11159       /* It must not be INTENT(OUT).  */
11160       if (arg->attr.intent == INTENT_OUT)
11161         {
11162           gfc_error ("Argument of FINAL procedure at %L must not be"
11163                      " INTENT(OUT)", &arg->declared_at);
11164           goto error;
11165         }
11166
11167       /* Warn if the procedure is non-scalar and not assumed shape.  */
11168       if (gfc_option.warn_surprising && arg->as && arg->as->rank != 0
11169           && arg->as->type != AS_ASSUMED_SHAPE)
11170         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
11171                      " shape argument", &arg->declared_at);
11172
11173       /* Check that it does not match in kind and rank with a FINAL procedure
11174          defined earlier.  To really loop over the *earlier* declarations,
11175          we need to walk the tail of the list as new ones were pushed at the
11176          front.  */
11177       /* TODO: Handle kind parameters once they are implemented.  */
11178       my_rank = (arg->as ? arg->as->rank : 0);
11179       for (i = list->next; i; i = i->next)
11180         {
11181           gfc_formal_arglist *dummy_args;
11182
11183           /* Argument list might be empty; that is an error signalled earlier,
11184              but we nevertheless continued resolving.  */
11185           dummy_args = gfc_sym_get_dummy_args (i->proc_sym);
11186           if (dummy_args)
11187             {
11188               gfc_symbol* i_arg = dummy_args->sym;
11189               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
11190               if (i_rank == my_rank)
11191                 {
11192                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
11193                              " rank (%d) as '%s'",
11194                              list->proc_sym->name, &list->where, my_rank,
11195                              i->proc_sym->name);
11196                   goto error;
11197                 }
11198             }
11199         }
11200
11201         /* Is this the/a scalar finalizer procedure?  */
11202         if (!arg->as || arg->as->rank == 0)
11203           seen_scalar = true;
11204
11205         /* Find the symtree for this procedure.  */
11206         gcc_assert (!list->proc_tree);
11207         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
11208
11209         prev_link = &list->next;
11210         continue;
11211
11212         /* Remove wrong nodes immediately from the list so we don't risk any
11213            troubles in the future when they might fail later expectations.  */
11214 error:
11215         result = false;
11216         i = list;
11217         *prev_link = list->next;
11218         gfc_free_finalizer (i);
11219     }
11220
11221   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
11222      were nodes in the list, must have been for arrays.  It is surely a good
11223      idea to have a scalar version there if there's something to finalize.  */
11224   if (gfc_option.warn_surprising && result && !seen_scalar)
11225     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
11226                  " defined at %L, suggest also scalar one",
11227                  derived->name, &derived->declared_at);
11228
11229   /* TODO:  Remove this error when finalization is finished.  */
11230   gfc_error ("Finalization at %L is not yet implemented",
11231              &derived->declared_at);
11232
11233   gfc_find_derived_vtab (derived);
11234   return result;
11235 }
11236
11237
11238 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
11239
11240 static bool
11241 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
11242                              const char* generic_name, locus where)
11243 {
11244   gfc_symbol *sym1, *sym2;
11245   const char *pass1, *pass2;
11246
11247   gcc_assert (t1->specific && t2->specific);
11248   gcc_assert (!t1->specific->is_generic);
11249   gcc_assert (!t2->specific->is_generic);
11250   gcc_assert (t1->is_operator == t2->is_operator);
11251
11252   sym1 = t1->specific->u.specific->n.sym;
11253   sym2 = t2->specific->u.specific->n.sym;
11254
11255   if (sym1 == sym2)
11256     return true;
11257
11258   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
11259   if (sym1->attr.subroutine != sym2->attr.subroutine
11260       || sym1->attr.function != sym2->attr.function)
11261     {
11262       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
11263                  " GENERIC '%s' at %L",
11264                  sym1->name, sym2->name, generic_name, &where);
11265       return false;
11266     }
11267
11268   /* Compare the interfaces.  */
11269   if (t1->specific->nopass)
11270     pass1 = NULL;
11271   else if (t1->specific->pass_arg)
11272     pass1 = t1->specific->pass_arg;
11273   else
11274     pass1 = gfc_sym_get_dummy_args (t1->specific->u.specific->n.sym)->sym->name;
11275   if (t2->specific->nopass)
11276     pass2 = NULL;
11277   else if (t2->specific->pass_arg)
11278     pass2 = t2->specific->pass_arg;
11279   else
11280     pass2 = gfc_sym_get_dummy_args (t2->specific->u.specific->n.sym)->sym->name;
11281   if (gfc_compare_interfaces (sym1, sym2, sym2->name, !t1->is_operator, 0,
11282                               NULL, 0, pass1, pass2))
11283     {
11284       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
11285                  sym1->name, sym2->name, generic_name, &where);
11286       return false;
11287     }
11288
11289   return true;
11290 }
11291
11292
11293 /* Worker function for resolving a generic procedure binding; this is used to
11294    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
11295
11296    The difference between those cases is finding possible inherited bindings
11297    that are overridden, as one has to look for them in tb_sym_root,
11298    tb_uop_root or tb_op, respectively.  Thus the caller must already find
11299    the super-type and set p->overridden correctly.  */
11300
11301 static bool
11302 resolve_tb_generic_targets (gfc_symbol* super_type,
11303                             gfc_typebound_proc* p, const char* name)
11304 {
11305   gfc_tbp_generic* target;
11306   gfc_symtree* first_target;
11307   gfc_symtree* inherited;
11308
11309   gcc_assert (p && p->is_generic);
11310
11311   /* Try to find the specific bindings for the symtrees in our target-list.  */
11312   gcc_assert (p->u.generic);
11313   for (target = p->u.generic; target; target = target->next)
11314     if (!target->specific)
11315       {
11316         gfc_typebound_proc* overridden_tbp;
11317         gfc_tbp_generic* g;
11318         const char* target_name;
11319
11320         target_name = target->specific_st->name;
11321
11322         /* Defined for this type directly.  */
11323         if (target->specific_st->n.tb && !target->specific_st->n.tb->error)
11324           {
11325             target->specific = target->specific_st->n.tb;
11326             goto specific_found;
11327           }
11328
11329         /* Look for an inherited specific binding.  */
11330         if (super_type)
11331           {
11332             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
11333                                                  true, NULL);
11334
11335             if (inherited)
11336               {
11337                 gcc_assert (inherited->n.tb);
11338                 target->specific = inherited->n.tb;
11339                 goto specific_found;
11340               }
11341           }
11342
11343         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
11344                    " at %L", target_name, name, &p->where);
11345         return false;
11346
11347         /* Once we've found the specific binding, check it is not ambiguous with
11348            other specifics already found or inherited for the same GENERIC.  */
11349 specific_found:
11350         gcc_assert (target->specific);
11351
11352         /* This must really be a specific binding!  */
11353         if (target->specific->is_generic)
11354           {
11355             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
11356                        " '%s' is GENERIC, too", name, &p->where, target_name);
11357             return false;
11358           }
11359
11360         /* Check those already resolved on this type directly.  */
11361         for (g = p->u.generic; g; g = g->next)
11362           if (g != target && g->specific
11363               && !check_generic_tbp_ambiguity (target, g, name, p->where))
11364             return false;
11365
11366         /* Check for ambiguity with inherited specific targets.  */
11367         for (overridden_tbp = p->overridden; overridden_tbp;
11368              overridden_tbp = overridden_tbp->overridden)
11369           if (overridden_tbp->is_generic)
11370             {
11371               for (g = overridden_tbp->u.generic; g; g = g->next)
11372                 {
11373                   gcc_assert (g->specific);
11374                   if (!check_generic_tbp_ambiguity (target, g, name, p->where))
11375                     return false;
11376                 }
11377             }
11378       }
11379
11380   /* If we attempt to "overwrite" a specific binding, this is an error.  */
11381   if (p->overridden && !p->overridden->is_generic)
11382     {
11383       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
11384                  " the same name", name, &p->where);
11385       return false;
11386     }
11387
11388   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
11389      all must have the same attributes here.  */
11390   first_target = p->u.generic->specific->u.specific;
11391   gcc_assert (first_target);
11392   p->subroutine = first_target->n.sym->attr.subroutine;
11393   p->function = first_target->n.sym->attr.function;
11394
11395   return true;
11396 }
11397
11398
11399 /* Resolve a GENERIC procedure binding for a derived type.  */
11400
11401 static bool
11402 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
11403 {
11404   gfc_symbol* super_type;
11405
11406   /* Find the overridden binding if any.  */
11407   st->n.tb->overridden = NULL;
11408   super_type = gfc_get_derived_super_type (derived);
11409   if (super_type)
11410     {
11411       gfc_symtree* overridden;
11412       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
11413                                             true, NULL);
11414
11415       if (overridden && overridden->n.tb)
11416         st->n.tb->overridden = overridden->n.tb;
11417     }
11418
11419   /* Resolve using worker function.  */
11420   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
11421 }
11422
11423
11424 /* Retrieve the target-procedure of an operator binding and do some checks in
11425    common for intrinsic and user-defined type-bound operators.  */
11426
11427 static gfc_symbol*
11428 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
11429 {
11430   gfc_symbol* target_proc;
11431
11432   gcc_assert (target->specific && !target->specific->is_generic);
11433   target_proc = target->specific->u.specific->n.sym;
11434   gcc_assert (target_proc);
11435
11436   /* F08:C468. All operator bindings must have a passed-object dummy argument.  */
11437   if (target->specific->nopass)
11438     {
11439       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
11440       return NULL;
11441     }
11442
11443   return target_proc;
11444 }
11445
11446
11447 /* Resolve a type-bound intrinsic operator.  */
11448
11449 static bool
11450 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
11451                                 gfc_typebound_proc* p)
11452 {
11453   gfc_symbol* super_type;
11454   gfc_tbp_generic* target;
11455
11456   /* If there's already an error here, do nothing (but don't fail again).  */
11457   if (p->error)
11458     return true;
11459
11460   /* Operators should always be GENERIC bindings.  */
11461   gcc_assert (p->is_generic);
11462
11463   /* Look for an overridden binding.  */
11464   super_type = gfc_get_derived_super_type (derived);
11465   if (super_type && super_type->f2k_derived)
11466     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
11467                                                      op, true, NULL);
11468   else
11469     p->overridden = NULL;
11470
11471   /* Resolve general GENERIC properties using worker function.  */
11472   if (!resolve_tb_generic_targets (super_type, p, gfc_op2string(op)))
11473     goto error;
11474
11475   /* Check the targets to be procedures of correct interface.  */
11476   for (target = p->u.generic; target; target = target->next)
11477     {
11478       gfc_symbol* target_proc;
11479
11480       target_proc = get_checked_tb_operator_target (target, p->where);
11481       if (!target_proc)
11482         goto error;
11483
11484       if (!gfc_check_operator_interface (target_proc, op, p->where))
11485         goto error;
11486
11487       /* Add target to non-typebound operator list.  */
11488       if (!target->specific->deferred && !derived->attr.use_assoc
11489           && p->access != ACCESS_PRIVATE && derived->ns == gfc_current_ns)
11490         {
11491           gfc_interface *head, *intr;
11492           if (!gfc_check_new_interface (derived->ns->op[op], target_proc, p->where))
11493             return false;
11494           head = derived->ns->op[op];
11495           intr = gfc_get_interface ();
11496           intr->sym = target_proc;
11497           intr->where = p->where;
11498           intr->next = head;
11499           derived->ns->op[op] = intr;
11500         }
11501     }
11502
11503   return true;
11504
11505 error:
11506   p->error = 1;
11507   return false;
11508 }
11509
11510
11511 /* Resolve a type-bound user operator (tree-walker callback).  */
11512
11513 static gfc_symbol* resolve_bindings_derived;
11514 static bool resolve_bindings_result;
11515
11516 static bool check_uop_procedure (gfc_symbol* sym, locus where);
11517
11518 static void
11519 resolve_typebound_user_op (gfc_symtree* stree)
11520 {
11521   gfc_symbol* super_type;
11522   gfc_tbp_generic* target;
11523
11524   gcc_assert (stree && stree->n.tb);
11525
11526   if (stree->n.tb->error)
11527     return;
11528
11529   /* Operators should always be GENERIC bindings.  */
11530   gcc_assert (stree->n.tb->is_generic);
11531
11532   /* Find overridden procedure, if any.  */
11533   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
11534   if (super_type && super_type->f2k_derived)
11535     {
11536       gfc_symtree* overridden;
11537       overridden = gfc_find_typebound_user_op (super_type, NULL,
11538                                                stree->name, true, NULL);
11539
11540       if (overridden && overridden->n.tb)
11541         stree->n.tb->overridden = overridden->n.tb;
11542     }
11543   else
11544     stree->n.tb->overridden = NULL;
11545
11546   /* Resolve basically using worker function.  */
11547   if (!resolve_tb_generic_targets (super_type, stree->n.tb, stree->name))
11548     goto error;
11549
11550   /* Check the targets to be functions of correct interface.  */
11551   for (target = stree->n.tb->u.generic; target; target = target->next)
11552     {
11553       gfc_symbol* target_proc;
11554
11555       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
11556       if (!target_proc)
11557         goto error;
11558
11559       if (!check_uop_procedure (target_proc, stree->n.tb->where))
11560         goto error;
11561     }
11562
11563   return;
11564
11565 error:
11566   resolve_bindings_result = false;
11567   stree->n.tb->error = 1;
11568 }
11569
11570
11571 /* Resolve the type-bound procedures for a derived type.  */
11572
11573 static void
11574 resolve_typebound_procedure (gfc_symtree* stree)
11575 {
11576   gfc_symbol* proc;
11577   locus where;
11578   gfc_symbol* me_arg;
11579   gfc_symbol* super_type;
11580   gfc_component* comp;
11581
11582   gcc_assert (stree);
11583
11584   /* Undefined specific symbol from GENERIC target definition.  */
11585   if (!stree->n.tb)
11586     return;
11587
11588   if (stree->n.tb->error)
11589     return;
11590
11591   /* If this is a GENERIC binding, use that routine.  */
11592   if (stree->n.tb->is_generic)
11593     {
11594       if (!resolve_typebound_generic (resolve_bindings_derived, stree))
11595         goto error;
11596       return;
11597     }
11598
11599   /* Get the target-procedure to check it.  */
11600   gcc_assert (!stree->n.tb->is_generic);
11601   gcc_assert (stree->n.tb->u.specific);
11602   proc = stree->n.tb->u.specific->n.sym;
11603   where = stree->n.tb->where;
11604
11605   /* Default access should already be resolved from the parser.  */
11606   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
11607
11608   if (stree->n.tb->deferred)
11609     {
11610       if (!check_proc_interface (proc, &where))
11611         goto error;
11612     }
11613   else
11614     {
11615       /* Check for F08:C465.  */
11616       if ((!proc->attr.subroutine && !proc->attr.function)
11617           || (proc->attr.proc != PROC_MODULE
11618               && proc->attr.if_source != IFSRC_IFBODY)
11619           || proc->attr.abstract)
11620         {
11621           gfc_error ("'%s' must be a module procedure or an external procedure with"
11622                     " an explicit interface at %L", proc->name, &where);
11623           goto error;
11624         }
11625     }
11626
11627   stree->n.tb->subroutine = proc->attr.subroutine;
11628   stree->n.tb->function = proc->attr.function;
11629
11630   /* Find the super-type of the current derived type.  We could do this once and
11631      store in a global if speed is needed, but as long as not I believe this is
11632      more readable and clearer.  */
11633   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
11634
11635   /* If PASS, resolve and check arguments if not already resolved / loaded
11636      from a .mod file.  */
11637   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
11638     {
11639       gfc_formal_arglist *dummy_args;
11640
11641       dummy_args = gfc_sym_get_dummy_args (proc);
11642       if (stree->n.tb->pass_arg)
11643         {
11644           gfc_formal_arglist *i;
11645
11646           /* If an explicit passing argument name is given, walk the arg-list
11647              and look for it.  */
11648
11649           me_arg = NULL;
11650           stree->n.tb->pass_arg_num = 1;
11651           for (i = dummy_args; i; i = i->next)
11652             {
11653               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
11654                 {
11655                   me_arg = i->sym;
11656                   break;
11657                 }
11658               ++stree->n.tb->pass_arg_num;
11659             }
11660
11661           if (!me_arg)
11662             {
11663               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
11664                          " argument '%s'",
11665                          proc->name, stree->n.tb->pass_arg, &where,
11666                          stree->n.tb->pass_arg);
11667               goto error;
11668             }
11669         }
11670       else
11671         {
11672           /* Otherwise, take the first one; there should in fact be at least
11673              one.  */
11674           stree->n.tb->pass_arg_num = 1;
11675           if (!dummy_args)
11676             {
11677               gfc_error ("Procedure '%s' with PASS at %L must have at"
11678                          " least one argument", proc->name, &where);
11679               goto error;
11680             }
11681           me_arg = dummy_args->sym;
11682         }
11683
11684       /* Now check that the argument-type matches and the passed-object
11685          dummy argument is generally fine.  */
11686
11687       gcc_assert (me_arg);
11688
11689       if (me_arg->ts.type != BT_CLASS)
11690         {
11691           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11692                      " at %L", proc->name, &where);
11693           goto error;
11694         }
11695
11696       if (CLASS_DATA (me_arg)->ts.u.derived
11697           != resolve_bindings_derived)
11698         {
11699           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11700                      " the derived-type '%s'", me_arg->name, proc->name,
11701                      me_arg->name, &where, resolve_bindings_derived->name);
11702           goto error;
11703         }
11704
11705       gcc_assert (me_arg->ts.type == BT_CLASS);
11706       if (CLASS_DATA (me_arg)->as && CLASS_DATA (me_arg)->as->rank != 0)
11707         {
11708           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
11709                      " scalar", proc->name, &where);
11710           goto error;
11711         }
11712       if (CLASS_DATA (me_arg)->attr.allocatable)
11713         {
11714           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11715                      " be ALLOCATABLE", proc->name, &where);
11716           goto error;
11717         }
11718       if (CLASS_DATA (me_arg)->attr.class_pointer)
11719         {
11720           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11721                      " be POINTER", proc->name, &where);
11722           goto error;
11723         }
11724     }
11725
11726   /* If we are extending some type, check that we don't override a procedure
11727      flagged NON_OVERRIDABLE.  */
11728   stree->n.tb->overridden = NULL;
11729   if (super_type)
11730     {
11731       gfc_symtree* overridden;
11732       overridden = gfc_find_typebound_proc (super_type, NULL,
11733                                             stree->name, true, NULL);
11734
11735       if (overridden)
11736         {
11737           if (overridden->n.tb)
11738             stree->n.tb->overridden = overridden->n.tb;
11739
11740           if (!gfc_check_typebound_override (stree, overridden))
11741             goto error;
11742         }
11743     }
11744
11745   /* See if there's a name collision with a component directly in this type.  */
11746   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
11747     if (!strcmp (comp->name, stree->name))
11748       {
11749         gfc_error ("Procedure '%s' at %L has the same name as a component of"
11750                    " '%s'",
11751                    stree->name, &where, resolve_bindings_derived->name);
11752         goto error;
11753       }
11754
11755   /* Try to find a name collision with an inherited component.  */
11756   if (super_type && gfc_find_component (super_type, stree->name, true, true))
11757     {
11758       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
11759                  " component of '%s'",
11760                  stree->name, &where, resolve_bindings_derived->name);
11761       goto error;
11762     }
11763
11764   stree->n.tb->error = 0;
11765   return;
11766
11767 error:
11768   resolve_bindings_result = false;
11769   stree->n.tb->error = 1;
11770 }
11771
11772
11773 static bool
11774 resolve_typebound_procedures (gfc_symbol* derived)
11775 {
11776   int op;
11777   gfc_symbol* super_type;
11778
11779   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
11780     return true;
11781
11782   super_type = gfc_get_derived_super_type (derived);
11783   if (super_type)
11784     resolve_symbol (super_type);
11785
11786   resolve_bindings_derived = derived;
11787   resolve_bindings_result = true;
11788
11789   /* Make sure the vtab has been generated.  */
11790   gfc_find_derived_vtab (derived);
11791
11792   if (derived->f2k_derived->tb_sym_root)
11793     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
11794                           &resolve_typebound_procedure);
11795
11796   if (derived->f2k_derived->tb_uop_root)
11797     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
11798                           &resolve_typebound_user_op);
11799
11800   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
11801     {
11802       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
11803       if (p && !resolve_typebound_intrinsic_op (derived, 
11804                                                 (gfc_intrinsic_op)op, p))
11805         resolve_bindings_result = false;
11806     }
11807
11808   return resolve_bindings_result;
11809 }
11810
11811
11812 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
11813    to give all identical derived types the same backend_decl.  */
11814 static void
11815 add_dt_to_dt_list (gfc_symbol *derived)
11816 {
11817   gfc_dt_list *dt_list;
11818
11819   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
11820     if (derived == dt_list->derived)
11821       return;
11822
11823   dt_list = gfc_get_dt_list ();
11824   dt_list->next = gfc_derived_types;
11825   dt_list->derived = derived;
11826   gfc_derived_types = dt_list;
11827 }
11828
11829
11830 /* Ensure that a derived-type is really not abstract, meaning that every
11831    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
11832
11833 static bool
11834 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
11835 {
11836   if (!st)
11837     return true;
11838
11839   if (!ensure_not_abstract_walker (sub, st->left))
11840     return false;
11841   if (!ensure_not_abstract_walker (sub, st->right))
11842     return false;
11843
11844   if (st->n.tb && st->n.tb->deferred)
11845     {
11846       gfc_symtree* overriding;
11847       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
11848       if (!overriding)
11849         return false;
11850       gcc_assert (overriding->n.tb);
11851       if (overriding->n.tb->deferred)
11852         {
11853           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
11854                      " '%s' is DEFERRED and not overridden",
11855                      sub->name, &sub->declared_at, st->name);
11856           return false;
11857         }
11858     }
11859
11860   return true;
11861 }
11862
11863 static bool
11864 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
11865 {
11866   /* The algorithm used here is to recursively travel up the ancestry of sub
11867      and for each ancestor-type, check all bindings.  If any of them is
11868      DEFERRED, look it up starting from sub and see if the found (overriding)
11869      binding is not DEFERRED.
11870      This is not the most efficient way to do this, but it should be ok and is
11871      clearer than something sophisticated.  */
11872
11873   gcc_assert (ancestor && !sub->attr.abstract);
11874
11875   if (!ancestor->attr.abstract)
11876     return true;
11877
11878   /* Walk bindings of this ancestor.  */
11879   if (ancestor->f2k_derived)
11880     {
11881       bool t;
11882       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
11883       if (!t)
11884         return false;
11885     }
11886
11887   /* Find next ancestor type and recurse on it.  */
11888   ancestor = gfc_get_derived_super_type (ancestor);
11889   if (ancestor)
11890     return ensure_not_abstract (sub, ancestor);
11891
11892   return true;
11893 }
11894
11895
11896 /* This check for typebound defined assignments is done recursively
11897    since the order in which derived types are resolved is not always in
11898    order of the declarations.  */
11899
11900 static void
11901 check_defined_assignments (gfc_symbol *derived)
11902 {
11903   gfc_component *c;
11904
11905   for (c = derived->components; c; c = c->next)
11906     {
11907       if (c->ts.type != BT_DERIVED
11908           || c->attr.pointer
11909           || c->attr.allocatable
11910           || c->attr.proc_pointer_comp
11911           || c->attr.class_pointer
11912           || c->attr.proc_pointer)
11913         continue;
11914
11915       if (c->ts.u.derived->attr.defined_assign_comp
11916           || (c->ts.u.derived->f2k_derived
11917              && c->ts.u.derived->f2k_derived->tb_op[INTRINSIC_ASSIGN]))
11918         {
11919           derived->attr.defined_assign_comp = 1;
11920           return;
11921         }
11922
11923       check_defined_assignments (c->ts.u.derived);
11924       if (c->ts.u.derived->attr.defined_assign_comp)
11925         {
11926           derived->attr.defined_assign_comp = 1;
11927           return;
11928         }
11929     }
11930 }
11931
11932
11933 /* Resolve the components of a derived type. This does not have to wait until
11934    resolution stage, but can be done as soon as the dt declaration has been
11935    parsed.  */
11936
11937 static bool
11938 resolve_fl_derived0 (gfc_symbol *sym)
11939 {
11940   gfc_symbol* super_type;
11941   gfc_component *c;
11942
11943   if (sym->attr.unlimited_polymorphic)
11944     return true;
11945
11946   super_type = gfc_get_derived_super_type (sym);
11947
11948   /* F2008, C432. */
11949   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
11950     {
11951       gfc_error ("As extending type '%s' at %L has a coarray component, "
11952                  "parent type '%s' shall also have one", sym->name,
11953                  &sym->declared_at, super_type->name);
11954       return false;
11955     }
11956
11957   /* Ensure the extended type gets resolved before we do.  */
11958   if (super_type && !resolve_fl_derived0 (super_type))
11959     return false;
11960
11961   /* An ABSTRACT type must be extensible.  */
11962   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
11963     {
11964       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
11965                  sym->name, &sym->declared_at);
11966       return false;
11967     }
11968
11969   c = (sym->attr.is_class) ? sym->components->ts.u.derived->components
11970                            : sym->components;
11971
11972   for ( ; c != NULL; c = c->next)
11973     {
11974       if (c->attr.artificial)
11975         continue;
11976
11977       /* See PRs 51550, 47545, 48654, 49050, 51075 - and 45170.  */
11978       if (c->ts.type == BT_CHARACTER && c->ts.deferred && !c->attr.function)
11979         {
11980           gfc_error ("Deferred-length character component '%s' at %L is not "
11981                      "yet supported", c->name, &c->loc);
11982           return false;
11983         }
11984
11985       /* F2008, C442.  */
11986       if ((!sym->attr.is_class || c != sym->components)
11987           && c->attr.codimension
11988           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
11989         {
11990           gfc_error ("Coarray component '%s' at %L must be allocatable with "
11991                      "deferred shape", c->name, &c->loc);
11992           return false;
11993         }
11994
11995       /* F2008, C443.  */
11996       if (c->attr.codimension && c->ts.type == BT_DERIVED
11997           && c->ts.u.derived->ts.is_iso_c)
11998         {
11999           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
12000                      "shall not be a coarray", c->name, &c->loc);
12001           return false;
12002         }
12003
12004       /* F2008, C444.  */
12005       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
12006           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
12007               || c->attr.allocatable))
12008         {
12009           gfc_error ("Component '%s' at %L with coarray component "
12010                      "shall be a nonpointer, nonallocatable scalar",
12011                      c->name, &c->loc);
12012           return false;
12013         }
12014
12015       /* F2008, C448.  */
12016       if (c->attr.contiguous && (!c->attr.dimension || !c->attr.pointer))
12017         {
12018           gfc_error ("Component '%s' at %L has the CONTIGUOUS attribute but "
12019                      "is not an array pointer", c->name, &c->loc);
12020           return false;
12021         }
12022
12023       if (c->attr.proc_pointer && c->ts.interface)
12024         {
12025           gfc_symbol *ifc = c->ts.interface;
12026
12027           if (!sym->attr.vtype
12028               && !check_proc_interface (ifc, &c->loc))
12029             return false;
12030
12031           if (ifc->attr.if_source || ifc->attr.intrinsic)
12032             {
12033               /* Resolve interface and copy attributes.  */
12034               if (ifc->formal && !ifc->formal_ns)
12035                 resolve_symbol (ifc);
12036               if (ifc->attr.intrinsic)
12037                 gfc_resolve_intrinsic (ifc, &ifc->declared_at);
12038
12039               if (ifc->result)
12040                 {
12041                   c->ts = ifc->result->ts;
12042                   c->attr.allocatable = ifc->result->attr.allocatable;
12043                   c->attr.pointer = ifc->result->attr.pointer;
12044                   c->attr.dimension = ifc->result->attr.dimension;
12045                   c->as = gfc_copy_array_spec (ifc->result->as);
12046                   c->attr.class_ok = ifc->result->attr.class_ok;
12047                 }
12048               else
12049                 {
12050                   c->ts = ifc->ts;
12051                   c->attr.allocatable = ifc->attr.allocatable;
12052                   c->attr.pointer = ifc->attr.pointer;
12053                   c->attr.dimension = ifc->attr.dimension;
12054                   c->as = gfc_copy_array_spec (ifc->as);
12055                   c->attr.class_ok = ifc->attr.class_ok;
12056                 }
12057               c->ts.interface = ifc;
12058               c->attr.function = ifc->attr.function;
12059               c->attr.subroutine = ifc->attr.subroutine;
12060
12061               c->attr.pure = ifc->attr.pure;
12062               c->attr.elemental = ifc->attr.elemental;
12063               c->attr.recursive = ifc->attr.recursive;
12064               c->attr.always_explicit = ifc->attr.always_explicit;
12065               c->attr.ext_attr |= ifc->attr.ext_attr;
12066               /* Copy char length.  */
12067               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
12068                 {
12069                   gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
12070                   if (cl->length && !cl->resolved
12071                       && !gfc_resolve_expr (cl->length))
12072                     return false;
12073                   c->ts.u.cl = cl;
12074                 }
12075             }
12076         }
12077       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
12078         {
12079           /* Since PPCs are not implicitly typed, a PPC without an explicit
12080              interface must be a subroutine.  */
12081           gfc_add_subroutine (&c->attr, c->name, &c->loc);
12082         }
12083
12084       /* Procedure pointer components: Check PASS arg.  */
12085       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
12086           && !sym->attr.vtype)
12087         {
12088           gfc_symbol* me_arg;
12089
12090           if (c->tb->pass_arg)
12091             {
12092               gfc_formal_arglist* i;
12093
12094               /* If an explicit passing argument name is given, walk the arg-list
12095                 and look for it.  */
12096
12097               me_arg = NULL;
12098               c->tb->pass_arg_num = 1;
12099               for (i = c->ts.interface->formal; i; i = i->next)
12100                 {
12101                   if (!strcmp (i->sym->name, c->tb->pass_arg))
12102                     {
12103                       me_arg = i->sym;
12104                       break;
12105                     }
12106                   c->tb->pass_arg_num++;
12107                 }
12108
12109               if (!me_arg)
12110                 {
12111                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
12112                              "at %L has no argument '%s'", c->name,
12113                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
12114                   c->tb->error = 1;
12115                   return false;
12116                 }
12117             }
12118           else
12119             {
12120               /* Otherwise, take the first one; there should in fact be at least
12121                 one.  */
12122               c->tb->pass_arg_num = 1;
12123               if (!c->ts.interface->formal)
12124                 {
12125                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
12126                              "must have at least one argument",
12127                              c->name, &c->loc);
12128                   c->tb->error = 1;
12129                   return false;
12130                 }
12131               me_arg = c->ts.interface->formal->sym;
12132             }
12133
12134           /* Now check that the argument-type matches.  */
12135           gcc_assert (me_arg);
12136           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
12137               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
12138               || (me_arg->ts.type == BT_CLASS
12139                   && CLASS_DATA (me_arg)->ts.u.derived != sym))
12140             {
12141               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
12142                          " the derived type '%s'", me_arg->name, c->name,
12143                          me_arg->name, &c->loc, sym->name);
12144               c->tb->error = 1;
12145               return false;
12146             }
12147
12148           /* Check for C453.  */
12149           if (me_arg->attr.dimension)
12150             {
12151               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
12152                          "must be scalar", me_arg->name, c->name, me_arg->name,
12153                          &c->loc);
12154               c->tb->error = 1;
12155               return false;
12156             }
12157
12158           if (me_arg->attr.pointer)
12159             {
12160               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
12161                          "may not have the POINTER attribute", me_arg->name,
12162                          c->name, me_arg->name, &c->loc);
12163               c->tb->error = 1;
12164               return false;
12165             }
12166
12167           if (me_arg->attr.allocatable)
12168             {
12169               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
12170                          "may not be ALLOCATABLE", me_arg->name, c->name,
12171                          me_arg->name, &c->loc);
12172               c->tb->error = 1;
12173               return false;
12174             }
12175
12176           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
12177             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
12178                        " at %L", c->name, &c->loc);
12179
12180         }
12181
12182       /* Check type-spec if this is not the parent-type component.  */
12183       if (((sym->attr.is_class
12184             && (!sym->components->ts.u.derived->attr.extension
12185                 || c != sym->components->ts.u.derived->components))
12186            || (!sym->attr.is_class
12187                && (!sym->attr.extension || c != sym->components)))
12188           && !sym->attr.vtype
12189           && !resolve_typespec_used (&c->ts, &c->loc, c->name))
12190         return false;
12191
12192       /* If this type is an extension, set the accessibility of the parent
12193          component.  */
12194       if (super_type
12195           && ((sym->attr.is_class
12196                && c == sym->components->ts.u.derived->components)
12197               || (!sym->attr.is_class && c == sym->components))
12198           && strcmp (super_type->name, c->name) == 0)
12199         c->attr.access = super_type->attr.access;
12200
12201       /* If this type is an extension, see if this component has the same name
12202          as an inherited type-bound procedure.  */
12203       if (super_type && !sym->attr.is_class
12204           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
12205         {
12206           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
12207                      " inherited type-bound procedure",
12208                      c->name, sym->name, &c->loc);
12209           return false;
12210         }
12211
12212       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer
12213             && !c->ts.deferred)
12214         {
12215          if (c->ts.u.cl->length == NULL
12216              || (!resolve_charlen(c->ts.u.cl))
12217              || !gfc_is_constant_expr (c->ts.u.cl->length))
12218            {
12219              gfc_error ("Character length of component '%s' needs to "
12220                         "be a constant specification expression at %L",
12221                         c->name,
12222                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
12223              return false;
12224            }
12225         }
12226
12227       if (c->ts.type == BT_CHARACTER && c->ts.deferred
12228           && !c->attr.pointer && !c->attr.allocatable)
12229         {
12230           gfc_error ("Character component '%s' of '%s' at %L with deferred "
12231                      "length must be a POINTER or ALLOCATABLE",
12232                      c->name, sym->name, &c->loc);
12233           return false;
12234         }
12235
12236       if (c->ts.type == BT_DERIVED
12237           && sym->component_access != ACCESS_PRIVATE
12238           && gfc_check_symbol_access (sym)
12239           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
12240           && !c->ts.u.derived->attr.use_assoc
12241           && !gfc_check_symbol_access (c->ts.u.derived)
12242           && !gfc_notify_std (GFC_STD_F2003, "the component '%s' is a "
12243                               "PRIVATE type and cannot be a component of "
12244                               "'%s', which is PUBLIC at %L", c->name, 
12245                               sym->name, &sym->declared_at))
12246         return false;
12247
12248       if ((sym->attr.sequence || sym->attr.is_bind_c) && c->ts.type == BT_CLASS)
12249         {
12250           gfc_error ("Polymorphic component %s at %L in SEQUENCE or BIND(C) "
12251                      "type %s", c->name, &c->loc, sym->name);
12252           return false;
12253         }
12254
12255       if (sym->attr.sequence)
12256         {
12257           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
12258             {
12259               gfc_error ("Component %s of SEQUENCE type declared at %L does "
12260                          "not have the SEQUENCE attribute",
12261                          c->ts.u.derived->name, &sym->declared_at);
12262               return false;
12263             }
12264         }
12265
12266       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.generic)
12267         c->ts.u.derived = gfc_find_dt_in_generic (c->ts.u.derived);
12268       else if (c->ts.type == BT_CLASS && c->attr.class_ok
12269                && CLASS_DATA (c)->ts.u.derived->attr.generic)
12270         CLASS_DATA (c)->ts.u.derived
12271                         = gfc_find_dt_in_generic (CLASS_DATA (c)->ts.u.derived);
12272
12273       if (!sym->attr.is_class && c->ts.type == BT_DERIVED && !sym->attr.vtype
12274           && c->attr.pointer && c->ts.u.derived->components == NULL
12275           && !c->ts.u.derived->attr.zero_comp)
12276         {
12277           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
12278                      "that has not been declared", c->name, sym->name,
12279                      &c->loc);
12280           return false;
12281         }
12282
12283       if (c->ts.type == BT_CLASS && c->attr.class_ok
12284           && CLASS_DATA (c)->attr.class_pointer
12285           && CLASS_DATA (c)->ts.u.derived->components == NULL
12286           && !CLASS_DATA (c)->ts.u.derived->attr.zero_comp
12287           && !UNLIMITED_POLY (c))
12288         {
12289           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
12290                      "that has not been declared", c->name, sym->name,
12291                      &c->loc);
12292           return false;
12293         }
12294
12295       /* C437.  */
12296       if (c->ts.type == BT_CLASS && c->attr.flavor != FL_PROCEDURE
12297           && (!c->attr.class_ok
12298               || !(CLASS_DATA (c)->attr.class_pointer
12299                    || CLASS_DATA (c)->attr.allocatable)))
12300         {
12301           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
12302                      "or pointer", c->name, &c->loc);
12303           /* Prevent a recurrence of the error.  */
12304           c->ts.type = BT_UNKNOWN;
12305           return false;
12306         }
12307
12308       /* Ensure that all the derived type components are put on the
12309          derived type list; even in formal namespaces, where derived type
12310          pointer components might not have been declared.  */
12311       if (c->ts.type == BT_DERIVED
12312             && c->ts.u.derived
12313             && c->ts.u.derived->components
12314             && c->attr.pointer
12315             && sym != c->ts.u.derived)
12316         add_dt_to_dt_list (c->ts.u.derived);
12317
12318       if (!gfc_resolve_array_spec (c->as, 
12319                                    !(c->attr.pointer || c->attr.proc_pointer 
12320                                      || c->attr.allocatable)))
12321         return false;
12322
12323       if (c->initializer && !sym->attr.vtype
12324           && !gfc_check_assign_symbol (sym, c, c->initializer))
12325         return false;
12326     }
12327
12328   check_defined_assignments (sym);
12329
12330   if (!sym->attr.defined_assign_comp && super_type)
12331     sym->attr.defined_assign_comp
12332                         = super_type->attr.defined_assign_comp;
12333
12334   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
12335      all DEFERRED bindings are overridden.  */
12336   if (super_type && super_type->attr.abstract && !sym->attr.abstract
12337       && !sym->attr.is_class
12338       && !ensure_not_abstract (sym, super_type))
12339     return false;
12340
12341   /* Add derived type to the derived type list.  */
12342   add_dt_to_dt_list (sym);
12343
12344   /* Check if the type is finalizable. This is done in order to ensure that the
12345      finalization wrapper is generated early enough.  */
12346   gfc_is_finalizable (sym, NULL);
12347
12348   return true;
12349 }
12350
12351
12352 /* The following procedure does the full resolution of a derived type,
12353    including resolution of all type-bound procedures (if present). In contrast
12354    to 'resolve_fl_derived0' this can only be done after the module has been
12355    parsed completely.  */
12356
12357 static bool
12358 resolve_fl_derived (gfc_symbol *sym)
12359 {
12360   gfc_symbol *gen_dt = NULL;
12361
12362   if (sym->attr.unlimited_polymorphic)
12363     return true;
12364
12365   if (!sym->attr.is_class)
12366     gfc_find_symbol (sym->name, sym->ns, 0, &gen_dt);
12367   if (gen_dt && gen_dt->generic && gen_dt->generic->next
12368       && (!gen_dt->generic->sym->attr.use_assoc
12369           || gen_dt->generic->sym->module != gen_dt->generic->next->sym->module)
12370       && !gfc_notify_std (GFC_STD_F2003, "Generic name '%s' of function "
12371                           "'%s' at %L being the same name as derived "
12372                           "type at %L", sym->name, 
12373                           gen_dt->generic->sym == sym 
12374                           ? gen_dt->generic->next->sym->name 
12375                           : gen_dt->generic->sym->name, 
12376                           gen_dt->generic->sym == sym 
12377                           ? &gen_dt->generic->next->sym->declared_at 
12378                           : &gen_dt->generic->sym->declared_at, 
12379                           &sym->declared_at))
12380     return false;
12381
12382   /* Resolve the finalizer procedures.  */
12383   if (!gfc_resolve_finalizers (sym))
12384     return false;
12385
12386   if (sym->attr.is_class && sym->ts.u.derived == NULL)
12387     {
12388       /* Fix up incomplete CLASS symbols.  */
12389       gfc_component *data = gfc_find_component (sym, "_data", true, true);
12390       gfc_component *vptr = gfc_find_component (sym, "_vptr", true, true);
12391
12392       /* Nothing more to do for unlimited polymorphic entities.  */
12393       if (data->ts.u.derived->attr.unlimited_polymorphic)
12394         return true;
12395       else if (vptr->ts.u.derived == NULL)
12396         {
12397           gfc_symbol *vtab = gfc_find_derived_vtab (data->ts.u.derived);
12398           gcc_assert (vtab);
12399           vptr->ts.u.derived = vtab->ts.u.derived;
12400         }
12401     }
12402
12403   if (!resolve_fl_derived0 (sym))
12404     return false;
12405
12406   /* Resolve the type-bound procedures.  */
12407   if (!resolve_typebound_procedures (sym))
12408     return false;
12409
12410   return true;
12411 }
12412
12413
12414 static bool
12415 resolve_fl_namelist (gfc_symbol *sym)
12416 {
12417   gfc_namelist *nl;
12418   gfc_symbol *nlsym;
12419
12420   for (nl = sym->namelist; nl; nl = nl->next)
12421     {
12422       /* Check again, the check in match only works if NAMELIST comes
12423          after the decl.  */
12424       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SIZE)
12425         {
12426           gfc_error ("Assumed size array '%s' in namelist '%s' at %L is not "
12427                      "allowed", nl->sym->name, sym->name, &sym->declared_at);
12428           return false;
12429         }
12430
12431       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
12432           && !gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
12433                               "with assumed shape in namelist '%s' at %L", 
12434                               nl->sym->name, sym->name, &sym->declared_at))
12435         return false;
12436
12437       if (is_non_constant_shape_array (nl->sym)
12438           && !gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
12439                               "with nonconstant shape in namelist '%s' at %L", 
12440                               nl->sym->name, sym->name, &sym->declared_at))
12441         return false;
12442
12443       if (nl->sym->ts.type == BT_CHARACTER
12444           && (nl->sym->ts.u.cl->length == NULL
12445               || !gfc_is_constant_expr (nl->sym->ts.u.cl->length))
12446           && !gfc_notify_std (GFC_STD_F2003, "NAMELIST object '%s' with "
12447                               "nonconstant character length in "
12448                               "namelist '%s' at %L", nl->sym->name, 
12449                               sym->name, &sym->declared_at))
12450         return false;
12451
12452       /* FIXME: Once UDDTIO is implemented, the following can be
12453          removed.  */
12454       if (nl->sym->ts.type == BT_CLASS)
12455         {
12456           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L is "
12457                      "polymorphic and requires a defined input/output "
12458                      "procedure", nl->sym->name, sym->name, &sym->declared_at);
12459           return false;
12460         }
12461
12462       if (nl->sym->ts.type == BT_DERIVED
12463           && (nl->sym->ts.u.derived->attr.alloc_comp
12464               || nl->sym->ts.u.derived->attr.pointer_comp))
12465         {
12466           if (!gfc_notify_std (GFC_STD_F2003, "NAMELIST object '%s' in "
12467                                "namelist '%s' at %L with ALLOCATABLE "
12468                                "or POINTER components", nl->sym->name, 
12469                                sym->name, &sym->declared_at))
12470             return false;
12471
12472          /* FIXME: Once UDDTIO is implemented, the following can be
12473             removed.  */
12474           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L has "
12475                      "ALLOCATABLE or POINTER components and thus requires "
12476                      "a defined input/output procedure", nl->sym->name,
12477                      sym->name, &sym->declared_at);
12478           return false;
12479         }
12480     }
12481
12482   /* Reject PRIVATE objects in a PUBLIC namelist.  */
12483   if (gfc_check_symbol_access (sym))
12484     {
12485       for (nl = sym->namelist; nl; nl = nl->next)
12486         {
12487           if (!nl->sym->attr.use_assoc
12488               && !is_sym_host_assoc (nl->sym, sym->ns)
12489               && !gfc_check_symbol_access (nl->sym))
12490             {
12491               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
12492                          "cannot be member of PUBLIC namelist '%s' at %L",
12493                          nl->sym->name, sym->name, &sym->declared_at);
12494               return false;
12495             }
12496
12497           /* Types with private components that came here by USE-association.  */
12498           if (nl->sym->ts.type == BT_DERIVED
12499               && derived_inaccessible (nl->sym->ts.u.derived))
12500             {
12501               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
12502                          "components and cannot be member of namelist '%s' at %L",
12503                          nl->sym->name, sym->name, &sym->declared_at);
12504               return false;
12505             }
12506
12507           /* Types with private components that are defined in the same module.  */
12508           if (nl->sym->ts.type == BT_DERIVED
12509               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
12510               && nl->sym->ts.u.derived->attr.private_comp)
12511             {
12512               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
12513                          "cannot be a member of PUBLIC namelist '%s' at %L",
12514                          nl->sym->name, sym->name, &sym->declared_at);
12515               return false;
12516             }
12517         }
12518     }
12519
12520
12521   /* 14.1.2 A module or internal procedure represent local entities
12522      of the same type as a namelist member and so are not allowed.  */
12523   for (nl = sym->namelist; nl; nl = nl->next)
12524     {
12525       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
12526         continue;
12527
12528       if (nl->sym->attr.function && nl->sym == nl->sym->result)
12529         if ((nl->sym == sym->ns->proc_name)
12530                ||
12531             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
12532           continue;
12533
12534       nlsym = NULL;
12535       if (nl->sym->name)
12536         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
12537       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
12538         {
12539           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
12540                      "attribute in '%s' at %L", nlsym->name,
12541                      &sym->declared_at);
12542           return false;
12543         }
12544     }
12545
12546   return true;
12547 }
12548
12549
12550 static bool
12551 resolve_fl_parameter (gfc_symbol *sym)
12552 {
12553   /* A parameter array's shape needs to be constant.  */
12554   if (sym->as != NULL
12555       && (sym->as->type == AS_DEFERRED
12556           || is_non_constant_shape_array (sym)))
12557     {
12558       gfc_error ("Parameter array '%s' at %L cannot be automatic "
12559                  "or of deferred shape", sym->name, &sym->declared_at);
12560       return false;
12561     }
12562
12563   /* Make sure a parameter that has been implicitly typed still
12564      matches the implicit type, since PARAMETER statements can precede
12565      IMPLICIT statements.  */
12566   if (sym->attr.implicit_type
12567       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
12568                                                              sym->ns)))
12569     {
12570       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
12571                  "later IMPLICIT type", sym->name, &sym->declared_at);
12572       return false;
12573     }
12574
12575   /* Make sure the types of derived parameters are consistent.  This
12576      type checking is deferred until resolution because the type may
12577      refer to a derived type from the host.  */
12578   if (sym->ts.type == BT_DERIVED
12579       && !gfc_compare_types (&sym->ts, &sym->value->ts))
12580     {
12581       gfc_error ("Incompatible derived type in PARAMETER at %L",
12582                  &sym->value->where);
12583       return false;
12584     }
12585   return true;
12586 }
12587
12588
12589 /* Do anything necessary to resolve a symbol.  Right now, we just
12590    assume that an otherwise unknown symbol is a variable.  This sort
12591    of thing commonly happens for symbols in module.  */
12592
12593 static void
12594 resolve_symbol (gfc_symbol *sym)
12595 {
12596   int check_constant, mp_flag;
12597   gfc_symtree *symtree;
12598   gfc_symtree *this_symtree;
12599   gfc_namespace *ns;
12600   gfc_component *c;
12601   symbol_attribute class_attr;
12602   gfc_array_spec *as;
12603   bool saved_specification_expr;
12604
12605   if (sym->resolved)
12606     return;
12607   sym->resolved = 1;
12608
12609   if (sym->attr.artificial)
12610     return;
12611
12612   if (sym->attr.unlimited_polymorphic)
12613     return;
12614
12615   if (sym->attr.flavor == FL_UNKNOWN
12616       || (sym->attr.flavor == FL_PROCEDURE && !sym->attr.intrinsic
12617           && !sym->attr.generic && !sym->attr.external
12618           && sym->attr.if_source == IFSRC_UNKNOWN))
12619     {
12620
12621     /* If we find that a flavorless symbol is an interface in one of the
12622        parent namespaces, find its symtree in this namespace, free the
12623        symbol and set the symtree to point to the interface symbol.  */
12624       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
12625         {
12626           symtree = gfc_find_symtree (ns->sym_root, sym->name);
12627           if (symtree && (symtree->n.sym->generic ||
12628                           (symtree->n.sym->attr.flavor == FL_PROCEDURE
12629                            && sym->ns->construct_entities)))
12630             {
12631               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
12632                                                sym->name);
12633               gfc_release_symbol (sym);
12634               symtree->n.sym->refs++;
12635               this_symtree->n.sym = symtree->n.sym;
12636               return;
12637             }
12638         }
12639
12640       /* Otherwise give it a flavor according to such attributes as
12641          it has.  */
12642       if (sym->attr.flavor == FL_UNKNOWN && sym->attr.external == 0
12643           && sym->attr.intrinsic == 0)
12644         sym->attr.flavor = FL_VARIABLE;
12645       else if (sym->attr.flavor == FL_UNKNOWN)
12646         {
12647           sym->attr.flavor = FL_PROCEDURE;
12648           if (sym->attr.dimension)
12649             sym->attr.function = 1;
12650         }
12651     }
12652
12653   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
12654     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
12655
12656   if (sym->attr.procedure && sym->attr.if_source != IFSRC_DECL
12657       && !resolve_procedure_interface (sym))
12658     return;
12659
12660   if (sym->attr.is_protected && !sym->attr.proc_pointer
12661       && (sym->attr.procedure || sym->attr.external))
12662     {
12663       if (sym->attr.external)
12664         gfc_error ("PROTECTED attribute conflicts with EXTERNAL attribute "
12665                    "at %L", &sym->declared_at);
12666       else
12667         gfc_error ("PROCEDURE attribute conflicts with PROTECTED attribute "
12668                    "at %L", &sym->declared_at);
12669
12670       return;
12671     }
12672
12673   if (sym->attr.flavor == FL_DERIVED && !resolve_fl_derived (sym))
12674     return;
12675
12676   /* Symbols that are module procedures with results (functions) have
12677      the types and array specification copied for type checking in
12678      procedures that call them, as well as for saving to a module
12679      file.  These symbols can't stand the scrutiny that their results
12680      can.  */
12681   mp_flag = (sym->result != NULL && sym->result != sym);
12682
12683   /* Make sure that the intrinsic is consistent with its internal
12684      representation. This needs to be done before assigning a default
12685      type to avoid spurious warnings.  */
12686   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
12687       && !gfc_resolve_intrinsic (sym, &sym->declared_at))
12688     return;
12689
12690   /* Resolve associate names.  */
12691   if (sym->assoc)
12692     resolve_assoc_var (sym, true);
12693
12694   /* Assign default type to symbols that need one and don't have one.  */
12695   if (sym->ts.type == BT_UNKNOWN)
12696     {
12697       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
12698         {
12699           gfc_set_default_type (sym, 1, NULL);
12700         }
12701
12702       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
12703           && !sym->attr.function && !sym->attr.subroutine
12704           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
12705         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
12706
12707       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
12708         {
12709           /* The specific case of an external procedure should emit an error
12710              in the case that there is no implicit type.  */
12711           if (!mp_flag)
12712             gfc_set_default_type (sym, sym->attr.external, NULL);
12713           else
12714             {
12715               /* Result may be in another namespace.  */
12716               resolve_symbol (sym->result);
12717
12718               if (!sym->result->attr.proc_pointer)
12719                 {
12720                   sym->ts = sym->result->ts;
12721                   sym->as = gfc_copy_array_spec (sym->result->as);
12722                   sym->attr.dimension = sym->result->attr.dimension;
12723                   sym->attr.pointer = sym->result->attr.pointer;
12724                   sym->attr.allocatable = sym->result->attr.allocatable;
12725                   sym->attr.contiguous = sym->result->attr.contiguous;
12726                 }
12727             }
12728         }
12729     }
12730   else if (mp_flag && sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
12731     {
12732       bool saved_specification_expr = specification_expr;
12733       specification_expr = true;
12734       gfc_resolve_array_spec (sym->result->as, false);
12735       specification_expr = saved_specification_expr;
12736     }
12737
12738   if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
12739     {
12740       as = CLASS_DATA (sym)->as;
12741       class_attr = CLASS_DATA (sym)->attr;
12742       class_attr.pointer = class_attr.class_pointer;
12743     }
12744   else
12745     {
12746       class_attr = sym->attr;
12747       as = sym->as;
12748     }
12749
12750   /* F2008, C530. */
12751   if (sym->attr.contiguous
12752       && (!class_attr.dimension
12753           || (as->type != AS_ASSUMED_SHAPE && as->type != AS_ASSUMED_RANK
12754               && !class_attr.pointer)))
12755     {
12756       gfc_error ("'%s' at %L has the CONTIGUOUS attribute but is not an "
12757                  "array pointer or an assumed-shape or assumed-rank array",
12758                  sym->name, &sym->declared_at);
12759       return;
12760     }
12761
12762   /* Assumed size arrays and assumed shape arrays must be dummy
12763      arguments.  Array-spec's of implied-shape should have been resolved to
12764      AS_EXPLICIT already.  */
12765
12766   if (as)
12767     {
12768       gcc_assert (as->type != AS_IMPLIED_SHAPE);
12769       if (((as->type == AS_ASSUMED_SIZE && !as->cp_was_assumed)
12770            || as->type == AS_ASSUMED_SHAPE)
12771           && !sym->attr.dummy && !sym->attr.select_type_temporary)
12772         {
12773           if (as->type == AS_ASSUMED_SIZE)
12774             gfc_error ("Assumed size array at %L must be a dummy argument",
12775                        &sym->declared_at);
12776           else
12777             gfc_error ("Assumed shape array at %L must be a dummy argument",
12778                        &sym->declared_at);
12779           return;
12780         }
12781       /* TS 29113, C535a.  */
12782       if (as->type == AS_ASSUMED_RANK && !sym->attr.dummy
12783           && !sym->attr.select_type_temporary)
12784         {
12785           gfc_error ("Assumed-rank array at %L must be a dummy argument",
12786                      &sym->declared_at);
12787           return;
12788         }
12789       if (as->type == AS_ASSUMED_RANK
12790           && (sym->attr.codimension || sym->attr.value))
12791         {
12792           gfc_error ("Assumed-rank array at %L may not have the VALUE or "
12793                      "CODIMENSION attribute", &sym->declared_at);
12794           return;
12795         }
12796     }
12797
12798   /* Make sure symbols with known intent or optional are really dummy
12799      variable.  Because of ENTRY statement, this has to be deferred
12800      until resolution time.  */
12801
12802   if (!sym->attr.dummy
12803       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
12804     {
12805       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
12806       return;
12807     }
12808
12809   if (sym->attr.value && !sym->attr.dummy)
12810     {
12811       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
12812                  "it is not a dummy argument", sym->name, &sym->declared_at);
12813       return;
12814     }
12815
12816   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
12817     {
12818       gfc_charlen *cl = sym->ts.u.cl;
12819       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
12820         {
12821           gfc_error ("Character dummy variable '%s' at %L with VALUE "
12822                      "attribute must have constant length",
12823                      sym->name, &sym->declared_at);
12824           return;
12825         }
12826
12827       if (sym->ts.is_c_interop
12828           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
12829         {
12830           gfc_error ("C interoperable character dummy variable '%s' at %L "
12831                      "with VALUE attribute must have length one",
12832                      sym->name, &sym->declared_at);
12833           return;
12834         }
12835     }
12836
12837   if (sym->ts.type == BT_DERIVED && !sym->attr.is_iso_c
12838       && sym->ts.u.derived->attr.generic)
12839     {
12840       sym->ts.u.derived = gfc_find_dt_in_generic (sym->ts.u.derived);
12841       if (!sym->ts.u.derived)
12842         {
12843           gfc_error ("The derived type '%s' at %L is of type '%s', "
12844                      "which has not been defined", sym->name,
12845                      &sym->declared_at, sym->ts.u.derived->name);
12846           sym->ts.type = BT_UNKNOWN;
12847           return;
12848         }
12849     }
12850
12851     /* Use the same constraints as TYPE(*), except for the type check
12852        and that only scalars and assumed-size arrays are permitted.  */
12853     if (sym->attr.ext_attr & (1 << EXT_ATTR_NO_ARG_CHECK))
12854       {
12855         if (!sym->attr.dummy)
12856           {
12857             gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute shall be "
12858                        "a dummy argument", sym->name, &sym->declared_at);
12859             return;
12860           }
12861
12862         if (sym->ts.type != BT_ASSUMED && sym->ts.type != BT_INTEGER
12863             && sym->ts.type != BT_REAL && sym->ts.type != BT_LOGICAL
12864             && sym->ts.type != BT_COMPLEX)
12865           {
12866             gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute shall be "
12867                        "of type TYPE(*) or of an numeric intrinsic type",
12868                        sym->name, &sym->declared_at);
12869             return;
12870           }
12871
12872       if (sym->attr.allocatable || sym->attr.codimension
12873           || sym->attr.pointer || sym->attr.value)
12874         {
12875           gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute may not "
12876                      "have the ALLOCATABLE, CODIMENSION, POINTER or VALUE "
12877                      "attribute", sym->name, &sym->declared_at);
12878           return;
12879         }
12880
12881       if (sym->attr.intent == INTENT_OUT)
12882         {
12883           gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute may not "
12884                      "have the INTENT(OUT) attribute",
12885                      sym->name, &sym->declared_at);
12886           return;
12887         }
12888       if (sym->attr.dimension && sym->as->type != AS_ASSUMED_SIZE)
12889         {
12890           gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute shall "
12891                      "either be a scalar or an assumed-size array",
12892                      sym->name, &sym->declared_at);
12893           return;
12894         }
12895
12896       /* Set the type to TYPE(*) and add a dimension(*) to ensure
12897          NO_ARG_CHECK is correctly handled in trans*.c, e.g. with
12898          packing.  */
12899       sym->ts.type = BT_ASSUMED;
12900       sym->as = gfc_get_array_spec ();
12901       sym->as->type = AS_ASSUMED_SIZE;
12902       sym->as->rank = 1;
12903       sym->as->lower[0] = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
12904     }
12905   else if (sym->ts.type == BT_ASSUMED)
12906     {
12907       /* TS 29113, C407a.  */
12908       if (!sym->attr.dummy)
12909         {
12910           gfc_error ("Assumed type of variable %s at %L is only permitted "
12911                      "for dummy variables", sym->name, &sym->declared_at);
12912           return;
12913         }
12914       if (sym->attr.allocatable || sym->attr.codimension
12915           || sym->attr.pointer || sym->attr.value)
12916         {
12917           gfc_error ("Assumed-type variable %s at %L may not have the "
12918                      "ALLOCATABLE, CODIMENSION, POINTER or VALUE attribute",
12919                      sym->name, &sym->declared_at);
12920           return;
12921         }
12922       if (sym->attr.intent == INTENT_OUT)
12923         {
12924           gfc_error ("Assumed-type variable %s at %L may not have the "
12925                      "INTENT(OUT) attribute",
12926                      sym->name, &sym->declared_at);
12927           return;
12928         }
12929       if (sym->attr.dimension && sym->as->type == AS_EXPLICIT)
12930         {
12931           gfc_error ("Assumed-type variable %s at %L shall not be an "
12932                      "explicit-shape array", sym->name, &sym->declared_at);
12933           return;
12934         }
12935     }
12936
12937   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
12938      do this for something that was implicitly typed because that is handled
12939      in gfc_set_default_type.  Handle dummy arguments and procedure
12940      definitions separately.  Also, anything that is use associated is not
12941      handled here but instead is handled in the module it is declared in.
12942      Finally, derived type definitions are allowed to be BIND(C) since that
12943      only implies that they're interoperable, and they are checked fully for
12944      interoperability when a variable is declared of that type.  */
12945   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
12946       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
12947       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
12948     {
12949       bool t = true;
12950
12951       /* First, make sure the variable is declared at the
12952          module-level scope (J3/04-007, Section 15.3).  */
12953       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
12954           sym->attr.in_common == 0)
12955         {
12956           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
12957                      "is neither a COMMON block nor declared at the "
12958                      "module level scope", sym->name, &(sym->declared_at));
12959           t = false;
12960         }
12961       else if (sym->common_head != NULL)
12962         {
12963           t = verify_com_block_vars_c_interop (sym->common_head);
12964         }
12965       else
12966         {
12967           /* If type() declaration, we need to verify that the components
12968              of the given type are all C interoperable, etc.  */
12969           if (sym->ts.type == BT_DERIVED &&
12970               sym->ts.u.derived->attr.is_c_interop != 1)
12971             {
12972               /* Make sure the user marked the derived type as BIND(C).  If
12973                  not, call the verify routine.  This could print an error
12974                  for the derived type more than once if multiple variables
12975                  of that type are declared.  */
12976               if (sym->ts.u.derived->attr.is_bind_c != 1)
12977                 verify_bind_c_derived_type (sym->ts.u.derived);
12978               t = false;
12979             }
12980
12981           /* Verify the variable itself as C interoperable if it
12982              is BIND(C).  It is not possible for this to succeed if
12983              the verify_bind_c_derived_type failed, so don't have to handle
12984              any error returned by verify_bind_c_derived_type.  */
12985           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
12986                                  sym->common_block);
12987         }
12988
12989       if (!t)
12990         {
12991           /* clear the is_bind_c flag to prevent reporting errors more than
12992              once if something failed.  */
12993           sym->attr.is_bind_c = 0;
12994           return;
12995         }
12996     }
12997
12998   /* If a derived type symbol has reached this point, without its
12999      type being declared, we have an error.  Notice that most
13000      conditions that produce undefined derived types have already
13001      been dealt with.  However, the likes of:
13002      implicit type(t) (t) ..... call foo (t) will get us here if
13003      the type is not declared in the scope of the implicit
13004      statement. Change the type to BT_UNKNOWN, both because it is so
13005      and to prevent an ICE.  */
13006   if (sym->ts.type == BT_DERIVED && !sym->attr.is_iso_c
13007       && sym->ts.u.derived->components == NULL
13008       && !sym->ts.u.derived->attr.zero_comp)
13009     {
13010       gfc_error ("The derived type '%s' at %L is of type '%s', "
13011                  "which has not been defined", sym->name,
13012                   &sym->declared_at, sym->ts.u.derived->name);
13013       sym->ts.type = BT_UNKNOWN;
13014       return;
13015     }
13016
13017   /* Make sure that the derived type has been resolved and that the
13018      derived type is visible in the symbol's namespace, if it is a
13019      module function and is not PRIVATE.  */
13020   if (sym->ts.type == BT_DERIVED
13021         && sym->ts.u.derived->attr.use_assoc
13022         && sym->ns->proc_name
13023         && sym->ns->proc_name->attr.flavor == FL_MODULE
13024         && !resolve_fl_derived (sym->ts.u.derived))
13025     return;
13026
13027   /* Unless the derived-type declaration is use associated, Fortran 95
13028      does not allow public entries of private derived types.
13029      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
13030      161 in 95-006r3.  */
13031   if (sym->ts.type == BT_DERIVED
13032       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
13033       && !sym->ts.u.derived->attr.use_assoc
13034       && gfc_check_symbol_access (sym)
13035       && !gfc_check_symbol_access (sym->ts.u.derived)
13036       && !gfc_notify_std (GFC_STD_F2003, "PUBLIC %s '%s' at %L of PRIVATE "
13037                           "derived type '%s'", 
13038                           (sym->attr.flavor == FL_PARAMETER) 
13039                           ? "parameter" : "variable", 
13040                           sym->name, &sym->declared_at, 
13041                           sym->ts.u.derived->name))
13042     return;
13043
13044   /* F2008, C1302.  */
13045   if (sym->ts.type == BT_DERIVED
13046       && ((sym->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
13047            && sym->ts.u.derived->intmod_sym_id == ISOFORTRAN_LOCK_TYPE)
13048           || sym->ts.u.derived->attr.lock_comp)
13049       && !sym->attr.codimension && !sym->ts.u.derived->attr.coarray_comp)
13050     {
13051       gfc_error ("Variable %s at %L of type LOCK_TYPE or with subcomponent of "
13052                  "type LOCK_TYPE must be a coarray", sym->name,
13053                  &sym->declared_at);
13054       return;
13055     }
13056
13057   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
13058      default initialization is defined (5.1.2.4.4).  */
13059   if (sym->ts.type == BT_DERIVED
13060       && sym->attr.dummy
13061       && sym->attr.intent == INTENT_OUT
13062       && sym->as
13063       && sym->as->type == AS_ASSUMED_SIZE)
13064     {
13065       for (c = sym->ts.u.derived->components; c; c = c->next)
13066         {
13067           if (c->initializer)
13068             {
13069               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
13070                          "ASSUMED SIZE and so cannot have a default initializer",
13071                          sym->name, &sym->declared_at);
13072               return;
13073             }
13074         }
13075     }
13076
13077   /* F2008, C542.  */
13078   if (sym->ts.type == BT_DERIVED && sym->attr.dummy
13079       && sym->attr.intent == INTENT_OUT && sym->attr.lock_comp)
13080     {
13081       gfc_error ("Dummy argument '%s' at %L of LOCK_TYPE shall not be "
13082                  "INTENT(OUT)", sym->name, &sym->declared_at);
13083       return;
13084     }
13085
13086   /* F2008, C525.  */
13087   if ((((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
13088          || (sym->ts.type == BT_CLASS && sym->attr.class_ok
13089              && CLASS_DATA (sym)->attr.coarray_comp))
13090        || class_attr.codimension)
13091       && (sym->attr.result || sym->result == sym))
13092     {
13093       gfc_error ("Function result '%s' at %L shall not be a coarray or have "
13094                  "a coarray component", sym->name, &sym->declared_at);
13095       return;
13096     }
13097
13098   /* F2008, C524.  */
13099   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
13100       && sym->ts.u.derived->ts.is_iso_c)
13101     {
13102       gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
13103                  "shall not be a coarray", sym->name, &sym->declared_at);
13104       return;
13105     }
13106
13107   /* F2008, C525.  */
13108   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
13109         || (sym->ts.type == BT_CLASS && sym->attr.class_ok
13110             && CLASS_DATA (sym)->attr.coarray_comp))
13111       && (class_attr.codimension || class_attr.pointer || class_attr.dimension
13112           || class_attr.allocatable))
13113     {
13114       gfc_error ("Variable '%s' at %L with coarray component "
13115                  "shall be a nonpointer, nonallocatable scalar",
13116                  sym->name, &sym->declared_at);
13117       return;
13118     }
13119
13120   /* F2008, C526.  The function-result case was handled above.  */
13121   if (class_attr.codimension
13122       && !(class_attr.allocatable || sym->attr.dummy || sym->attr.save
13123            || sym->attr.select_type_temporary
13124            || sym->ns->save_all
13125            || sym->ns->proc_name->attr.flavor == FL_MODULE
13126            || sym->ns->proc_name->attr.is_main_program
13127            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
13128     {
13129       gfc_error ("Variable '%s' at %L is a coarray and is not ALLOCATABLE, SAVE "
13130                  "nor a dummy argument", sym->name, &sym->declared_at);
13131       return;
13132     }
13133   /* F2008, C528.  */
13134   else if (class_attr.codimension && !sym->attr.select_type_temporary
13135            && !class_attr.allocatable && as && as->cotype == AS_DEFERRED)
13136     {
13137       gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
13138                  "deferred shape", sym->name, &sym->declared_at);
13139       return;
13140     }
13141   else if (class_attr.codimension && class_attr.allocatable && as
13142            && (as->cotype != AS_DEFERRED || as->type != AS_DEFERRED))
13143     {
13144       gfc_error ("Allocatable coarray variable '%s' at %L must have "
13145                  "deferred shape", sym->name, &sym->declared_at);
13146       return;
13147     }
13148
13149   /* F2008, C541.  */
13150   if ((((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
13151         || (sym->ts.type == BT_CLASS && sym->attr.class_ok
13152             && CLASS_DATA (sym)->attr.coarray_comp))
13153        || (class_attr.codimension && class_attr.allocatable))
13154       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
13155     {
13156       gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
13157                  "allocatable coarray or have coarray components",
13158                  sym->name, &sym->declared_at);
13159       return;
13160     }
13161
13162   if (class_attr.codimension && sym->attr.dummy
13163       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
13164     {
13165       gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
13166                  "procedure '%s'", sym->name, &sym->declared_at,
13167                  sym->ns->proc_name->name);
13168       return;
13169     }
13170
13171   if (sym->ts.type == BT_LOGICAL
13172       && ((sym->attr.function && sym->attr.is_bind_c && sym->result == sym)
13173           || ((sym->attr.dummy || sym->attr.result) && sym->ns->proc_name
13174               && sym->ns->proc_name->attr.is_bind_c)))
13175     {
13176       int i;
13177       for (i = 0; gfc_logical_kinds[i].kind; i++)
13178         if (gfc_logical_kinds[i].kind == sym->ts.kind)
13179           break;
13180       if (!gfc_logical_kinds[i].c_bool && sym->attr.dummy
13181           && !gfc_notify_std (GFC_STD_GNU, "LOGICAL dummy argument '%s' at "
13182                               "%L with non-C_Bool kind in BIND(C) procedure "
13183                               "'%s'", sym->name, &sym->declared_at, 
13184                               sym->ns->proc_name->name))
13185         return;
13186       else if (!gfc_logical_kinds[i].c_bool
13187                && !gfc_notify_std (GFC_STD_GNU, "LOGICAL result variable "
13188                                    "'%s' at %L with non-C_Bool kind in "
13189                                    "BIND(C) procedure '%s'", sym->name, 
13190                                    &sym->declared_at, 
13191                                    sym->attr.function ? sym->name 
13192                                    : sym->ns->proc_name->name))
13193         return;
13194     }
13195
13196   switch (sym->attr.flavor)
13197     {
13198     case FL_VARIABLE:
13199       if (!resolve_fl_variable (sym, mp_flag))
13200         return;
13201       break;
13202
13203     case FL_PROCEDURE:
13204       if (!resolve_fl_procedure (sym, mp_flag))
13205         return;
13206       break;
13207
13208     case FL_NAMELIST:
13209       if (!resolve_fl_namelist (sym))
13210         return;
13211       break;
13212
13213     case FL_PARAMETER:
13214       if (!resolve_fl_parameter (sym))
13215         return;
13216       break;
13217
13218     default:
13219       break;
13220     }
13221
13222   /* Resolve array specifier. Check as well some constraints
13223      on COMMON blocks.  */
13224
13225   check_constant = sym->attr.in_common && !sym->attr.pointer;
13226
13227   /* Set the formal_arg_flag so that check_conflict will not throw
13228      an error for host associated variables in the specification
13229      expression for an array_valued function.  */
13230   if (sym->attr.function && sym->as)
13231     formal_arg_flag = 1;
13232
13233   saved_specification_expr = specification_expr;
13234   specification_expr = true;
13235   gfc_resolve_array_spec (sym->as, check_constant);
13236   specification_expr = saved_specification_expr;
13237
13238   formal_arg_flag = 0;
13239
13240   /* Resolve formal namespaces.  */
13241   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
13242       && !sym->attr.contained && !sym->attr.intrinsic)
13243     gfc_resolve (sym->formal_ns);
13244
13245   /* Make sure the formal namespace is present.  */
13246   if (sym->formal && !sym->formal_ns)
13247     {
13248       gfc_formal_arglist *formal = sym->formal;
13249       while (formal && !formal->sym)
13250         formal = formal->next;
13251
13252       if (formal)
13253         {
13254           sym->formal_ns = formal->sym->ns;
13255           if (sym->ns != formal->sym->ns)
13256             sym->formal_ns->refs++;
13257         }
13258     }
13259
13260   /* Check threadprivate restrictions.  */
13261   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
13262       && (!sym->attr.in_common
13263           && sym->module == NULL
13264           && (sym->ns->proc_name == NULL
13265               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
13266     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
13267
13268   /* If we have come this far we can apply default-initializers, as
13269      described in 14.7.5, to those variables that have not already
13270      been assigned one.  */
13271   if (sym->ts.type == BT_DERIVED
13272       && !sym->value
13273       && !sym->attr.allocatable
13274       && !sym->attr.alloc_comp)
13275     {
13276       symbol_attribute *a = &sym->attr;
13277
13278       if ((!a->save && !a->dummy && !a->pointer
13279            && !a->in_common && !a->use_assoc
13280            && (a->referenced || a->result)
13281            && !(a->function && sym != sym->result))
13282           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
13283         apply_default_init (sym);
13284     }
13285
13286   if (sym->ts.type == BT_CLASS && sym->ns == gfc_current_ns
13287       && sym->attr.dummy && sym->attr.intent == INTENT_OUT
13288       && !CLASS_DATA (sym)->attr.class_pointer
13289       && !CLASS_DATA (sym)->attr.allocatable)
13290     apply_default_init (sym);
13291
13292   /* If this symbol has a type-spec, check it.  */
13293   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
13294       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
13295     if (!resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name))
13296       return;
13297 }
13298
13299
13300 /************* Resolve DATA statements *************/
13301
13302 static struct
13303 {
13304   gfc_data_value *vnode;
13305   mpz_t left;
13306 }
13307 values;
13308
13309
13310 /* Advance the values structure to point to the next value in the data list.  */
13311
13312 static bool
13313 next_data_value (void)
13314 {
13315   while (mpz_cmp_ui (values.left, 0) == 0)
13316     {
13317
13318       if (values.vnode->next == NULL)
13319         return false;
13320
13321       values.vnode = values.vnode->next;
13322       mpz_set (values.left, values.vnode->repeat);
13323     }
13324
13325   return true;
13326 }
13327
13328
13329 static bool
13330 check_data_variable (gfc_data_variable *var, locus *where)
13331 {
13332   gfc_expr *e;
13333   mpz_t size;
13334   mpz_t offset;
13335   bool t;
13336   ar_type mark = AR_UNKNOWN;
13337   int i;
13338   mpz_t section_index[GFC_MAX_DIMENSIONS];
13339   gfc_ref *ref;
13340   gfc_array_ref *ar;
13341   gfc_symbol *sym;
13342   int has_pointer;
13343
13344   if (!gfc_resolve_expr (var->expr))
13345     return false;
13346
13347   ar = NULL;
13348   mpz_init_set_si (offset, 0);
13349   e = var->expr;
13350
13351   if (e->expr_type != EXPR_VARIABLE)
13352     gfc_internal_error ("check_data_variable(): Bad expression");
13353
13354   sym = e->symtree->n.sym;
13355
13356   if (sym->ns->is_block_data && !sym->attr.in_common)
13357     {
13358       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
13359                  sym->name, &sym->declared_at);
13360     }
13361
13362   if (e->ref == NULL && sym->as)
13363     {
13364       gfc_error ("DATA array '%s' at %L must be specified in a previous"
13365                  " declaration", sym->name, where);
13366       return false;
13367     }
13368
13369   has_pointer = sym->attr.pointer;
13370
13371   if (gfc_is_coindexed (e))
13372     {
13373       gfc_error ("DATA element '%s' at %L cannot have a coindex", sym->name,
13374                  where);
13375       return false;
13376     }
13377
13378   for (ref = e->ref; ref; ref = ref->next)
13379     {
13380       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
13381         has_pointer = 1;
13382
13383       if (has_pointer
13384             && ref->type == REF_ARRAY
13385             && ref->u.ar.type != AR_FULL)
13386           {
13387             gfc_error ("DATA element '%s' at %L is a pointer and so must "
13388                         "be a full array", sym->name, where);
13389             return false;
13390           }
13391     }
13392
13393   if (e->rank == 0 || has_pointer)
13394     {
13395       mpz_init_set_ui (size, 1);
13396       ref = NULL;
13397     }
13398   else
13399     {
13400       ref = e->ref;
13401
13402       /* Find the array section reference.  */
13403       for (ref = e->ref; ref; ref = ref->next)
13404         {
13405           if (ref->type != REF_ARRAY)
13406             continue;
13407           if (ref->u.ar.type == AR_ELEMENT)
13408             continue;
13409           break;
13410         }
13411       gcc_assert (ref);
13412
13413       /* Set marks according to the reference pattern.  */
13414       switch (ref->u.ar.type)
13415         {
13416         case AR_FULL:
13417           mark = AR_FULL;
13418           break;
13419
13420         case AR_SECTION:
13421           ar = &ref->u.ar;
13422           /* Get the start position of array section.  */
13423           gfc_get_section_index (ar, section_index, &offset);
13424           mark = AR_SECTION;
13425           break;
13426
13427         default:
13428           gcc_unreachable ();
13429         }
13430
13431       if (!gfc_array_size (e, &size))
13432         {
13433           gfc_error ("Nonconstant array section at %L in DATA statement",
13434                      &e->where);
13435           mpz_clear (offset);
13436           return false;
13437         }
13438     }
13439
13440   t = true;
13441
13442   while (mpz_cmp_ui (size, 0) > 0)
13443     {
13444       if (!next_data_value ())
13445         {
13446           gfc_error ("DATA statement at %L has more variables than values",
13447                      where);
13448           t = false;
13449           break;
13450         }
13451
13452       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
13453       if (!t)
13454         break;
13455
13456       /* If we have more than one element left in the repeat count,
13457          and we have more than one element left in the target variable,
13458          then create a range assignment.  */
13459       /* FIXME: Only done for full arrays for now, since array sections
13460          seem tricky.  */
13461       if (mark == AR_FULL && ref && ref->next == NULL
13462           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
13463         {
13464           mpz_t range;
13465
13466           if (mpz_cmp (size, values.left) >= 0)
13467             {
13468               mpz_init_set (range, values.left);
13469               mpz_sub (size, size, values.left);
13470               mpz_set_ui (values.left, 0);
13471             }
13472           else
13473             {
13474               mpz_init_set (range, size);
13475               mpz_sub (values.left, values.left, size);
13476               mpz_set_ui (size, 0);
13477             }
13478
13479           t = gfc_assign_data_value (var->expr, values.vnode->expr,
13480                                      offset, &range);
13481
13482           mpz_add (offset, offset, range);
13483           mpz_clear (range);
13484
13485           if (!t)
13486             break;
13487         }
13488
13489       /* Assign initial value to symbol.  */
13490       else
13491         {
13492           mpz_sub_ui (values.left, values.left, 1);
13493           mpz_sub_ui (size, size, 1);
13494
13495           t = gfc_assign_data_value (var->expr, values.vnode->expr,
13496                                      offset, NULL);
13497           if (!t)
13498             break;
13499
13500           if (mark == AR_FULL)
13501             mpz_add_ui (offset, offset, 1);
13502
13503           /* Modify the array section indexes and recalculate the offset
13504              for next element.  */
13505           else if (mark == AR_SECTION)
13506             gfc_advance_section (section_index, ar, &offset);
13507         }
13508     }
13509
13510   if (mark == AR_SECTION)
13511     {
13512       for (i = 0; i < ar->dimen; i++)
13513         mpz_clear (section_index[i]);
13514     }
13515
13516   mpz_clear (size);
13517   mpz_clear (offset);
13518
13519   return t;
13520 }
13521
13522
13523 static bool traverse_data_var (gfc_data_variable *, locus *);
13524
13525 /* Iterate over a list of elements in a DATA statement.  */
13526
13527 static bool
13528 traverse_data_list (gfc_data_variable *var, locus *where)
13529 {
13530   mpz_t trip;
13531   iterator_stack frame;
13532   gfc_expr *e, *start, *end, *step;
13533   bool retval = true;
13534
13535   mpz_init (frame.value);
13536   mpz_init (trip);
13537
13538   start = gfc_copy_expr (var->iter.start);
13539   end = gfc_copy_expr (var->iter.end);
13540   step = gfc_copy_expr (var->iter.step);
13541
13542   if (!gfc_simplify_expr (start, 1)
13543       || start->expr_type != EXPR_CONSTANT)
13544     {
13545       gfc_error ("start of implied-do loop at %L could not be "
13546                  "simplified to a constant value", &start->where);
13547       retval = false;
13548       goto cleanup;
13549     }
13550   if (!gfc_simplify_expr (end, 1)
13551       || end->expr_type != EXPR_CONSTANT)
13552     {
13553       gfc_error ("end of implied-do loop at %L could not be "
13554                  "simplified to a constant value", &start->where);
13555       retval = false;
13556       goto cleanup;
13557     }
13558   if (!gfc_simplify_expr (step, 1)
13559       || step->expr_type != EXPR_CONSTANT)
13560     {
13561       gfc_error ("step of implied-do loop at %L could not be "
13562                  "simplified to a constant value", &start->where);
13563       retval = false;
13564       goto cleanup;
13565     }
13566
13567   mpz_set (trip, end->value.integer);
13568   mpz_sub (trip, trip, start->value.integer);
13569   mpz_add (trip, trip, step->value.integer);
13570
13571   mpz_div (trip, trip, step->value.integer);
13572
13573   mpz_set (frame.value, start->value.integer);
13574
13575   frame.prev = iter_stack;
13576   frame.variable = var->iter.var->symtree;
13577   iter_stack = &frame;
13578
13579   while (mpz_cmp_ui (trip, 0) > 0)
13580     {
13581       if (!traverse_data_var (var->list, where))
13582         {
13583           retval = false;
13584           goto cleanup;
13585         }
13586
13587       e = gfc_copy_expr (var->expr);
13588       if (!gfc_simplify_expr (e, 1))
13589         {
13590           gfc_free_expr (e);
13591           retval = false;
13592           goto cleanup;
13593         }
13594
13595       mpz_add (frame.value, frame.value, step->value.integer);
13596
13597       mpz_sub_ui (trip, trip, 1);
13598     }
13599
13600 cleanup:
13601   mpz_clear (frame.value);
13602   mpz_clear (trip);
13603
13604   gfc_free_expr (start);
13605   gfc_free_expr (end);
13606   gfc_free_expr (step);
13607
13608   iter_stack = frame.prev;
13609   return retval;
13610 }
13611
13612
13613 /* Type resolve variables in the variable list of a DATA statement.  */
13614
13615 static bool
13616 traverse_data_var (gfc_data_variable *var, locus *where)
13617 {
13618   bool t;
13619
13620   for (; var; var = var->next)
13621     {
13622       if (var->expr == NULL)
13623         t = traverse_data_list (var, where);
13624       else
13625         t = check_data_variable (var, where);
13626
13627       if (!t)
13628         return false;
13629     }
13630
13631   return true;
13632 }
13633
13634
13635 /* Resolve the expressions and iterators associated with a data statement.
13636    This is separate from the assignment checking because data lists should
13637    only be resolved once.  */
13638
13639 static bool
13640 resolve_data_variables (gfc_data_variable *d)
13641 {
13642   for (; d; d = d->next)
13643     {
13644       if (d->list == NULL)
13645         {
13646           if (!gfc_resolve_expr (d->expr))
13647             return false;
13648         }
13649       else
13650         {
13651           if (!gfc_resolve_iterator (&d->iter, false, true))
13652             return false;
13653
13654           if (!resolve_data_variables (d->list))
13655             return false;
13656         }
13657     }
13658
13659   return true;
13660 }
13661
13662
13663 /* Resolve a single DATA statement.  We implement this by storing a pointer to
13664    the value list into static variables, and then recursively traversing the
13665    variables list, expanding iterators and such.  */
13666
13667 static void
13668 resolve_data (gfc_data *d)
13669 {
13670
13671   if (!resolve_data_variables (d->var))
13672     return;
13673
13674   values.vnode = d->value;
13675   if (d->value == NULL)
13676     mpz_set_ui (values.left, 0);
13677   else
13678     mpz_set (values.left, d->value->repeat);
13679
13680   if (!traverse_data_var (d->var, &d->where))
13681     return;
13682
13683   /* At this point, we better not have any values left.  */
13684
13685   if (next_data_value ())
13686     gfc_error ("DATA statement at %L has more values than variables",
13687                &d->where);
13688 }
13689
13690
13691 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
13692    accessed by host or use association, is a dummy argument to a pure function,
13693    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
13694    is storage associated with any such variable, shall not be used in the
13695    following contexts: (clients of this function).  */
13696
13697 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
13698    procedure.  Returns zero if assignment is OK, nonzero if there is a
13699    problem.  */
13700 int
13701 gfc_impure_variable (gfc_symbol *sym)
13702 {
13703   gfc_symbol *proc;
13704   gfc_namespace *ns;
13705
13706   if (sym->attr.use_assoc || sym->attr.in_common)
13707     return 1;
13708
13709   /* Check if the symbol's ns is inside the pure procedure.  */
13710   for (ns = gfc_current_ns; ns; ns = ns->parent)
13711     {
13712       if (ns == sym->ns)
13713         break;
13714       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
13715         return 1;
13716     }
13717
13718   proc = sym->ns->proc_name;
13719   if (sym->attr.dummy
13720       && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
13721           || proc->attr.function))
13722     return 1;
13723
13724   /* TODO: Sort out what can be storage associated, if anything, and include
13725      it here.  In principle equivalences should be scanned but it does not
13726      seem to be possible to storage associate an impure variable this way.  */
13727   return 0;
13728 }
13729
13730
13731 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
13732    current namespace is inside a pure procedure.  */
13733
13734 int
13735 gfc_pure (gfc_symbol *sym)
13736 {
13737   symbol_attribute attr;
13738   gfc_namespace *ns;
13739
13740   if (sym == NULL)
13741     {
13742       /* Check if the current namespace or one of its parents
13743         belongs to a pure procedure.  */
13744       for (ns = gfc_current_ns; ns; ns = ns->parent)
13745         {
13746           sym = ns->proc_name;
13747           if (sym == NULL)
13748             return 0;
13749           attr = sym->attr;
13750           if (attr.flavor == FL_PROCEDURE && attr.pure)
13751             return 1;
13752         }
13753       return 0;
13754     }
13755
13756   attr = sym->attr;
13757
13758   return attr.flavor == FL_PROCEDURE && attr.pure;
13759 }
13760
13761
13762 /* Test whether a symbol is implicitly pure or not.  For a NULL pointer,
13763    checks if the current namespace is implicitly pure.  Note that this
13764    function returns false for a PURE procedure.  */
13765
13766 int
13767 gfc_implicit_pure (gfc_symbol *sym)
13768 {
13769   gfc_namespace *ns;
13770
13771   if (sym == NULL)
13772     {
13773       /* Check if the current procedure is implicit_pure.  Walk up
13774          the procedure list until we find a procedure.  */
13775       for (ns = gfc_current_ns; ns; ns = ns->parent)
13776         {
13777           sym = ns->proc_name;
13778           if (sym == NULL)
13779             return 0;
13780
13781           if (sym->attr.flavor == FL_PROCEDURE)
13782             break;
13783         }
13784     }
13785
13786   return sym->attr.flavor == FL_PROCEDURE && sym->attr.implicit_pure
13787     && !sym->attr.pure;
13788 }
13789
13790
13791 /* Test whether the current procedure is elemental or not.  */
13792
13793 int
13794 gfc_elemental (gfc_symbol *sym)
13795 {
13796   symbol_attribute attr;
13797
13798   if (sym == NULL)
13799     sym = gfc_current_ns->proc_name;
13800   if (sym == NULL)
13801     return 0;
13802   attr = sym->attr;
13803
13804   return attr.flavor == FL_PROCEDURE && attr.elemental;
13805 }
13806
13807
13808 /* Warn about unused labels.  */
13809
13810 static void
13811 warn_unused_fortran_label (gfc_st_label *label)
13812 {
13813   if (label == NULL)
13814     return;
13815
13816   warn_unused_fortran_label (label->left);
13817
13818   if (label->defined == ST_LABEL_UNKNOWN)
13819     return;
13820
13821   switch (label->referenced)
13822     {
13823     case ST_LABEL_UNKNOWN:
13824       gfc_warning ("Label %d at %L defined but not used", label->value,
13825                    &label->where);
13826       break;
13827
13828     case ST_LABEL_BAD_TARGET:
13829       gfc_warning ("Label %d at %L defined but cannot be used",
13830                    label->value, &label->where);
13831       break;
13832
13833     default:
13834       break;
13835     }
13836
13837   warn_unused_fortran_label (label->right);
13838 }
13839
13840
13841 /* Returns the sequence type of a symbol or sequence.  */
13842
13843 static seq_type
13844 sequence_type (gfc_typespec ts)
13845 {
13846   seq_type result;
13847   gfc_component *c;
13848
13849   switch (ts.type)
13850   {
13851     case BT_DERIVED:
13852
13853       if (ts.u.derived->components == NULL)
13854         return SEQ_NONDEFAULT;
13855
13856       result = sequence_type (ts.u.derived->components->ts);
13857       for (c = ts.u.derived->components->next; c; c = c->next)
13858         if (sequence_type (c->ts) != result)
13859           return SEQ_MIXED;
13860
13861       return result;
13862
13863     case BT_CHARACTER:
13864       if (ts.kind != gfc_default_character_kind)
13865           return SEQ_NONDEFAULT;
13866
13867       return SEQ_CHARACTER;
13868
13869     case BT_INTEGER:
13870       if (ts.kind != gfc_default_integer_kind)
13871           return SEQ_NONDEFAULT;
13872
13873       return SEQ_NUMERIC;
13874
13875     case BT_REAL:
13876       if (!(ts.kind == gfc_default_real_kind
13877             || ts.kind == gfc_default_double_kind))
13878           return SEQ_NONDEFAULT;
13879
13880       return SEQ_NUMERIC;
13881
13882     case BT_COMPLEX:
13883       if (ts.kind != gfc_default_complex_kind)
13884           return SEQ_NONDEFAULT;
13885
13886       return SEQ_NUMERIC;
13887
13888     case BT_LOGICAL:
13889       if (ts.kind != gfc_default_logical_kind)
13890           return SEQ_NONDEFAULT;
13891
13892       return SEQ_NUMERIC;
13893
13894     default:
13895       return SEQ_NONDEFAULT;
13896   }
13897 }
13898
13899
13900 /* Resolve derived type EQUIVALENCE object.  */
13901
13902 static bool
13903 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
13904 {
13905   gfc_component *c = derived->components;
13906
13907   if (!derived)
13908     return true;
13909
13910   /* Shall not be an object of nonsequence derived type.  */
13911   if (!derived->attr.sequence)
13912     {
13913       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
13914                  "attribute to be an EQUIVALENCE object", sym->name,
13915                  &e->where);
13916       return false;
13917     }
13918
13919   /* Shall not have allocatable components.  */
13920   if (derived->attr.alloc_comp)
13921     {
13922       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
13923                  "components to be an EQUIVALENCE object",sym->name,
13924                  &e->where);
13925       return false;
13926     }
13927
13928   if (sym->attr.in_common && gfc_has_default_initializer (sym->ts.u.derived))
13929     {
13930       gfc_error ("Derived type variable '%s' at %L with default "
13931                  "initialization cannot be in EQUIVALENCE with a variable "
13932                  "in COMMON", sym->name, &e->where);
13933       return false;
13934     }
13935
13936   for (; c ; c = c->next)
13937     {
13938       if (c->ts.type == BT_DERIVED
13939           && (!resolve_equivalence_derived(c->ts.u.derived, sym, e)))
13940         return false;
13941
13942       /* Shall not be an object of sequence derived type containing a pointer
13943          in the structure.  */
13944       if (c->attr.pointer)
13945         {
13946           gfc_error ("Derived type variable '%s' at %L with pointer "
13947                      "component(s) cannot be an EQUIVALENCE object",
13948                      sym->name, &e->where);
13949           return false;
13950         }
13951     }
13952   return true;
13953 }
13954
13955
13956 /* Resolve equivalence object.
13957    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
13958    an allocatable array, an object of nonsequence derived type, an object of
13959    sequence derived type containing a pointer at any level of component
13960    selection, an automatic object, a function name, an entry name, a result
13961    name, a named constant, a structure component, or a subobject of any of
13962    the preceding objects.  A substring shall not have length zero.  A
13963    derived type shall not have components with default initialization nor
13964    shall two objects of an equivalence group be initialized.
13965    Either all or none of the objects shall have an protected attribute.
13966    The simple constraints are done in symbol.c(check_conflict) and the rest
13967    are implemented here.  */
13968
13969 static void
13970 resolve_equivalence (gfc_equiv *eq)
13971 {
13972   gfc_symbol *sym;
13973   gfc_symbol *first_sym;
13974   gfc_expr *e;
13975   gfc_ref *r;
13976   locus *last_where = NULL;
13977   seq_type eq_type, last_eq_type;
13978   gfc_typespec *last_ts;
13979   int object, cnt_protected;
13980   const char *msg;
13981
13982   last_ts = &eq->expr->symtree->n.sym->ts;
13983
13984   first_sym = eq->expr->symtree->n.sym;
13985
13986   cnt_protected = 0;
13987
13988   for (object = 1; eq; eq = eq->eq, object++)
13989     {
13990       e = eq->expr;
13991
13992       e->ts = e->symtree->n.sym->ts;
13993       /* match_varspec might not know yet if it is seeing
13994          array reference or substring reference, as it doesn't
13995          know the types.  */
13996       if (e->ref && e->ref->type == REF_ARRAY)
13997         {
13998           gfc_ref *ref = e->ref;
13999           sym = e->symtree->n.sym;
14000
14001           if (sym->attr.dimension)
14002             {
14003               ref->u.ar.as = sym->as;
14004               ref = ref->next;
14005             }
14006
14007           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
14008           if (e->ts.type == BT_CHARACTER
14009               && ref
14010               && ref->type == REF_ARRAY
14011               && ref->u.ar.dimen == 1
14012               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
14013               && ref->u.ar.stride[0] == NULL)
14014             {
14015               gfc_expr *start = ref->u.ar.start[0];
14016               gfc_expr *end = ref->u.ar.end[0];
14017               void *mem = NULL;
14018
14019               /* Optimize away the (:) reference.  */
14020               if (start == NULL && end == NULL)
14021                 {
14022                   if (e->ref == ref)
14023                     e->ref = ref->next;
14024                   else
14025                     e->ref->next = ref->next;
14026                   mem = ref;
14027                 }
14028               else
14029                 {
14030                   ref->type = REF_SUBSTRING;
14031                   if (start == NULL)
14032                     start = gfc_get_int_expr (gfc_default_integer_kind,
14033                                               NULL, 1);
14034                   ref->u.ss.start = start;
14035                   if (end == NULL && e->ts.u.cl)
14036                     end = gfc_copy_expr (e->ts.u.cl->length);
14037                   ref->u.ss.end = end;
14038                   ref->u.ss.length = e->ts.u.cl;
14039                   e->ts.u.cl = NULL;
14040                 }
14041               ref = ref->next;
14042               free (mem);
14043             }
14044
14045           /* Any further ref is an error.  */
14046           if (ref)
14047             {
14048               gcc_assert (ref->type == REF_ARRAY);
14049               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
14050                          &ref->u.ar.where);
14051               continue;
14052             }
14053         }
14054
14055       if (!gfc_resolve_expr (e))
14056         continue;
14057
14058       sym = e->symtree->n.sym;
14059
14060       if (sym->attr.is_protected)
14061         cnt_protected++;
14062       if (cnt_protected > 0 && cnt_protected != object)
14063         {
14064               gfc_error ("Either all or none of the objects in the "
14065                          "EQUIVALENCE set at %L shall have the "
14066                          "PROTECTED attribute",
14067                          &e->where);
14068               break;
14069         }
14070
14071       /* Shall not equivalence common block variables in a PURE procedure.  */
14072       if (sym->ns->proc_name
14073           && sym->ns->proc_name->attr.pure
14074           && sym->attr.in_common)
14075         {
14076           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
14077                      "object in the pure procedure '%s'",
14078                      sym->name, &e->where, sym->ns->proc_name->name);
14079           break;
14080         }
14081
14082       /* Shall not be a named constant.  */
14083       if (e->expr_type == EXPR_CONSTANT)
14084         {
14085           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
14086                      "object", sym->name, &e->where);
14087           continue;
14088         }
14089
14090       if (e->ts.type == BT_DERIVED
14091           && !resolve_equivalence_derived (e->ts.u.derived, sym, e))
14092         continue;
14093
14094       /* Check that the types correspond correctly:
14095          Note 5.28:
14096          A numeric sequence structure may be equivalenced to another sequence
14097          structure, an object of default integer type, default real type, double
14098          precision real type, default logical type such that components of the
14099          structure ultimately only become associated to objects of the same
14100          kind. A character sequence structure may be equivalenced to an object
14101          of default character kind or another character sequence structure.
14102          Other objects may be equivalenced only to objects of the same type and
14103          kind parameters.  */
14104
14105       /* Identical types are unconditionally OK.  */
14106       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
14107         goto identical_types;
14108
14109       last_eq_type = sequence_type (*last_ts);
14110       eq_type = sequence_type (sym->ts);
14111
14112       /* Since the pair of objects is not of the same type, mixed or
14113          non-default sequences can be rejected.  */
14114
14115       msg = "Sequence %s with mixed components in EQUIVALENCE "
14116             "statement at %L with different type objects";
14117       if ((object ==2
14118            && last_eq_type == SEQ_MIXED
14119            && !gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where))
14120           || (eq_type == SEQ_MIXED
14121               && !gfc_notify_std (GFC_STD_GNU, msg, sym->name, &e->where)))
14122         continue;
14123
14124       msg = "Non-default type object or sequence %s in EQUIVALENCE "
14125             "statement at %L with objects of different type";
14126       if ((object ==2
14127            && last_eq_type == SEQ_NONDEFAULT
14128            && !gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where))
14129           || (eq_type == SEQ_NONDEFAULT
14130               && !gfc_notify_std (GFC_STD_GNU, msg, sym->name, &e->where)))
14131         continue;
14132
14133       msg ="Non-CHARACTER object '%s' in default CHARACTER "
14134            "EQUIVALENCE statement at %L";
14135       if (last_eq_type == SEQ_CHARACTER
14136           && eq_type != SEQ_CHARACTER
14137           && !gfc_notify_std (GFC_STD_GNU, msg, sym->name, &e->where))
14138                 continue;
14139
14140       msg ="Non-NUMERIC object '%s' in default NUMERIC "
14141            "EQUIVALENCE statement at %L";
14142       if (last_eq_type == SEQ_NUMERIC
14143           && eq_type != SEQ_NUMERIC
14144           && !gfc_notify_std (GFC_STD_GNU, msg, sym->name, &e->where))
14145                 continue;
14146
14147   identical_types:
14148       last_ts =&sym->ts;
14149       last_where = &e->where;
14150
14151       if (!e->ref)
14152         continue;
14153
14154       /* Shall not be an automatic array.  */
14155       if (e->ref->type == REF_ARRAY
14156           && !gfc_resolve_array_spec (e->ref->u.ar.as, 1))
14157         {
14158           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
14159                      "an EQUIVALENCE object", sym->name, &e->where);
14160           continue;
14161         }
14162
14163       r = e->ref;
14164       while (r)
14165         {
14166           /* Shall not be a structure component.  */
14167           if (r->type == REF_COMPONENT)
14168             {
14169               gfc_error ("Structure component '%s' at %L cannot be an "
14170                          "EQUIVALENCE object",
14171                          r->u.c.component->name, &e->where);
14172               break;
14173             }
14174
14175           /* A substring shall not have length zero.  */
14176           if (r->type == REF_SUBSTRING)
14177             {
14178               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
14179                 {
14180                   gfc_error ("Substring at %L has length zero",
14181                              &r->u.ss.start->where);
14182                   break;
14183                 }
14184             }
14185           r = r->next;
14186         }
14187     }
14188 }
14189
14190
14191 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
14192
14193 static void
14194 resolve_fntype (gfc_namespace *ns)
14195 {
14196   gfc_entry_list *el;
14197   gfc_symbol *sym;
14198
14199   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
14200     return;
14201
14202   /* If there are any entries, ns->proc_name is the entry master
14203      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
14204   if (ns->entries)
14205     sym = ns->entries->sym;
14206   else
14207     sym = ns->proc_name;
14208   if (sym->result == sym
14209       && sym->ts.type == BT_UNKNOWN
14210       && !gfc_set_default_type (sym, 0, NULL)
14211       && !sym->attr.untyped)
14212     {
14213       gfc_error ("Function '%s' at %L has no IMPLICIT type",
14214                  sym->name, &sym->declared_at);
14215       sym->attr.untyped = 1;
14216     }
14217
14218   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
14219       && !sym->attr.contained
14220       && !gfc_check_symbol_access (sym->ts.u.derived)
14221       && gfc_check_symbol_access (sym))
14222     {
14223       gfc_notify_std (GFC_STD_F2003, "PUBLIC function '%s' at "
14224                       "%L of PRIVATE type '%s'", sym->name,
14225                       &sym->declared_at, sym->ts.u.derived->name);
14226     }
14227
14228     if (ns->entries)
14229     for (el = ns->entries->next; el; el = el->next)
14230       {
14231         if (el->sym->result == el->sym
14232             && el->sym->ts.type == BT_UNKNOWN
14233             && !gfc_set_default_type (el->sym, 0, NULL)
14234             && !el->sym->attr.untyped)
14235           {
14236             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
14237                        el->sym->name, &el->sym->declared_at);
14238             el->sym->attr.untyped = 1;
14239           }
14240       }
14241 }
14242
14243
14244 /* 12.3.2.1.1 Defined operators.  */
14245
14246 static bool
14247 check_uop_procedure (gfc_symbol *sym, locus where)
14248 {
14249   gfc_formal_arglist *formal;
14250
14251   if (!sym->attr.function)
14252     {
14253       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
14254                  sym->name, &where);
14255       return false;
14256     }
14257
14258   if (sym->ts.type == BT_CHARACTER
14259       && !(sym->ts.u.cl && sym->ts.u.cl->length)
14260       && !(sym->result && sym->result->ts.u.cl
14261            && sym->result->ts.u.cl->length))
14262     {
14263       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
14264                  "character length", sym->name, &where);
14265       return false;
14266     }
14267
14268   formal = gfc_sym_get_dummy_args (sym);
14269   if (!formal || !formal->sym)
14270     {
14271       gfc_error ("User operator procedure '%s' at %L must have at least "
14272                  "one argument", sym->name, &where);
14273       return false;
14274     }
14275
14276   if (formal->sym->attr.intent != INTENT_IN)
14277     {
14278       gfc_error ("First argument of operator interface at %L must be "
14279                  "INTENT(IN)", &where);
14280       return false;
14281     }
14282
14283   if (formal->sym->attr.optional)
14284     {
14285       gfc_error ("First argument of operator interface at %L cannot be "
14286                  "optional", &where);
14287       return false;
14288     }
14289
14290   formal = formal->next;
14291   if (!formal || !formal->sym)
14292     return true;
14293
14294   if (formal->sym->attr.intent != INTENT_IN)
14295     {
14296       gfc_error ("Second argument of operator interface at %L must be "
14297                  "INTENT(IN)", &where);
14298       return false;
14299     }
14300
14301   if (formal->sym->attr.optional)
14302     {
14303       gfc_error ("Second argument of operator interface at %L cannot be "
14304                  "optional", &where);
14305       return false;
14306     }
14307
14308   if (formal->next)
14309     {
14310       gfc_error ("Operator interface at %L must have, at most, two "
14311                  "arguments", &where);
14312       return false;
14313     }
14314
14315   return true;
14316 }
14317
14318 static void
14319 gfc_resolve_uops (gfc_symtree *symtree)
14320 {
14321   gfc_interface *itr;
14322
14323   if (symtree == NULL)
14324     return;
14325
14326   gfc_resolve_uops (symtree->left);
14327   gfc_resolve_uops (symtree->right);
14328
14329   for (itr = symtree->n.uop->op; itr; itr = itr->next)
14330     check_uop_procedure (itr->sym, itr->sym->declared_at);
14331 }
14332
14333
14334 /* Examine all of the expressions associated with a program unit,
14335    assign types to all intermediate expressions, make sure that all
14336    assignments are to compatible types and figure out which names
14337    refer to which functions or subroutines.  It doesn't check code
14338    block, which is handled by resolve_code.  */
14339
14340 static void
14341 resolve_types (gfc_namespace *ns)
14342 {
14343   gfc_namespace *n;
14344   gfc_charlen *cl;
14345   gfc_data *d;
14346   gfc_equiv *eq;
14347   gfc_namespace* old_ns = gfc_current_ns;
14348
14349   /* Check that all IMPLICIT types are ok.  */
14350   if (!ns->seen_implicit_none)
14351     {
14352       unsigned letter;
14353       for (letter = 0; letter != GFC_LETTERS; ++letter)
14354         if (ns->set_flag[letter]
14355             && !resolve_typespec_used (&ns->default_type[letter], 
14356                                        &ns->implicit_loc[letter], NULL))
14357           return;
14358     }
14359
14360   gfc_current_ns = ns;
14361
14362   resolve_entries (ns);
14363
14364   resolve_common_vars (ns->blank_common.head, false);
14365   resolve_common_blocks (ns->common_root);
14366
14367   resolve_contained_functions (ns);
14368
14369   if (ns->proc_name && ns->proc_name->attr.flavor == FL_PROCEDURE
14370       && ns->proc_name->attr.if_source == IFSRC_IFBODY)
14371     resolve_formal_arglist (ns->proc_name);
14372
14373   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
14374
14375   for (cl = ns->cl_list; cl; cl = cl->next)
14376     resolve_charlen (cl);
14377
14378   gfc_traverse_ns (ns, resolve_symbol);
14379
14380   resolve_fntype (ns);
14381
14382   for (n = ns->contained; n; n = n->sibling)
14383     {
14384       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
14385         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
14386                    "also be PURE", n->proc_name->name,
14387                    &n->proc_name->declared_at);
14388
14389       resolve_types (n);
14390     }
14391
14392   forall_flag = 0;
14393   do_concurrent_flag = 0;
14394   gfc_check_interfaces (ns);
14395
14396   gfc_traverse_ns (ns, resolve_values);
14397
14398   if (ns->save_all)
14399     gfc_save_all (ns);
14400
14401   iter_stack = NULL;
14402   for (d = ns->data; d; d = d->next)
14403     resolve_data (d);
14404
14405   iter_stack = NULL;
14406   gfc_traverse_ns (ns, gfc_formalize_init_value);
14407
14408   gfc_traverse_ns (ns, gfc_verify_binding_labels);
14409
14410   for (eq = ns->equiv; eq; eq = eq->next)
14411     resolve_equivalence (eq);
14412
14413   /* Warn about unused labels.  */
14414   if (warn_unused_label)
14415     warn_unused_fortran_label (ns->st_labels);
14416
14417   gfc_resolve_uops (ns->uop_root);
14418
14419   gfc_current_ns = old_ns;
14420 }
14421
14422
14423 /* Call resolve_code recursively.  */
14424
14425 static void
14426 resolve_codes (gfc_namespace *ns)
14427 {
14428   gfc_namespace *n;
14429   bitmap_obstack old_obstack;
14430
14431   if (ns->resolved == 1)
14432     return;
14433
14434   for (n = ns->contained; n; n = n->sibling)
14435     resolve_codes (n);
14436
14437   gfc_current_ns = ns;
14438
14439   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
14440   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
14441     cs_base = NULL;
14442
14443   /* Set to an out of range value.  */
14444   current_entry_id = -1;
14445
14446   old_obstack = labels_obstack;
14447   bitmap_obstack_initialize (&labels_obstack);
14448
14449   resolve_code (ns->code, ns);
14450
14451   bitmap_obstack_release (&labels_obstack);
14452   labels_obstack = old_obstack;
14453 }
14454
14455
14456 /* This function is called after a complete program unit has been compiled.
14457    Its purpose is to examine all of the expressions associated with a program
14458    unit, assign types to all intermediate expressions, make sure that all
14459    assignments are to compatible types and figure out which names refer to
14460    which functions or subroutines.  */
14461
14462 void
14463 gfc_resolve (gfc_namespace *ns)
14464 {
14465   gfc_namespace *old_ns;
14466   code_stack *old_cs_base;
14467
14468   if (ns->resolved)
14469     return;
14470
14471   ns->resolved = -1;
14472   old_ns = gfc_current_ns;
14473   old_cs_base = cs_base;
14474
14475   resolve_types (ns);
14476   component_assignment_level = 0;
14477   resolve_codes (ns);
14478
14479   gfc_current_ns = old_ns;
14480   cs_base = old_cs_base;
14481   ns->resolved = 1;
14482
14483   gfc_run_passes (ns);
14484 }