OSDN Git Service

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