OSDN Git Service

2ffa9fc2af7c36bf09cfaa378e08c9735f0558e5
[pf3gnuchains/gcc-fork.git] / gcc / fortran / trans-expr.c
1 /* Expression translation
2    Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
3    2011, 2012
4    Free Software Foundation, Inc.
5    Contributed by Paul Brook <paul@nowt.org>
6    and Steven Bosscher <s.bosscher@student.tudelft.nl>
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
14
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18 for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* trans-expr.c-- generate GENERIC trees for gfc_expr.  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tree.h"
30 #include "diagnostic-core.h"    /* For fatal_error.  */
31 #include "langhooks.h"
32 #include "flags.h"
33 #include "gfortran.h"
34 #include "arith.h"
35 #include "constructor.h"
36 #include "trans.h"
37 #include "trans-const.h"
38 #include "trans-types.h"
39 #include "trans-array.h"
40 /* Only for gfc_trans_assign and gfc_trans_pointer_assign.  */
41 #include "trans-stmt.h"
42 #include "dependency.h"
43
44
45 /* This is the seed for an eventual trans-class.c
46
47    The following parameters should not be used directly since they might
48    in future implementations.  Use the corresponding APIs.  */
49 #define CLASS_DATA_FIELD 0
50 #define CLASS_VPTR_FIELD 1
51 #define VTABLE_HASH_FIELD 0
52 #define VTABLE_SIZE_FIELD 1
53 #define VTABLE_EXTENDS_FIELD 2
54 #define VTABLE_DEF_INIT_FIELD 3
55 #define VTABLE_COPY_FIELD 4
56
57
58 tree
59 gfc_class_data_get (tree decl)
60 {
61   tree data;
62   if (POINTER_TYPE_P (TREE_TYPE (decl)))
63     decl = build_fold_indirect_ref_loc (input_location, decl);
64   data = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
65                             CLASS_DATA_FIELD);
66   return fold_build3_loc (input_location, COMPONENT_REF,
67                           TREE_TYPE (data), decl, data,
68                           NULL_TREE);
69 }
70
71
72 tree
73 gfc_class_vptr_get (tree decl)
74 {
75   tree vptr;
76   if (POINTER_TYPE_P (TREE_TYPE (decl)))
77     decl = build_fold_indirect_ref_loc (input_location, decl);
78   vptr = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
79                             CLASS_VPTR_FIELD);
80   return fold_build3_loc (input_location, COMPONENT_REF,
81                           TREE_TYPE (vptr), decl, vptr,
82                           NULL_TREE);
83 }
84
85
86 static tree
87 gfc_vtable_field_get (tree decl, int field)
88 {
89   tree size;
90   tree vptr;
91   vptr = gfc_class_vptr_get (decl);
92   vptr = build_fold_indirect_ref_loc (input_location, vptr);
93   size = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (vptr)),
94                             field);
95   size = fold_build3_loc (input_location, COMPONENT_REF,
96                           TREE_TYPE (size), vptr, size,
97                           NULL_TREE);
98   /* Always return size as an array index type.  */
99   if (field == VTABLE_SIZE_FIELD)
100     size = fold_convert (gfc_array_index_type, size);
101   gcc_assert (size);
102   return size;
103 }
104
105
106 tree
107 gfc_vtable_hash_get (tree decl)
108 {
109   return gfc_vtable_field_get (decl, VTABLE_HASH_FIELD);
110 }
111
112
113 tree
114 gfc_vtable_size_get (tree decl)
115 {
116   return gfc_vtable_field_get (decl, VTABLE_SIZE_FIELD);
117 }
118
119
120 tree
121 gfc_vtable_extends_get (tree decl)
122 {
123   return gfc_vtable_field_get (decl, VTABLE_EXTENDS_FIELD);
124 }
125
126
127 tree
128 gfc_vtable_def_init_get (tree decl)
129 {
130   return gfc_vtable_field_get (decl, VTABLE_DEF_INIT_FIELD);
131 }
132
133
134 tree
135 gfc_vtable_copy_get (tree decl)
136 {
137   return gfc_vtable_field_get (decl, VTABLE_COPY_FIELD);
138 }
139
140
141 #undef CLASS_DATA_FIELD
142 #undef CLASS_VPTR_FIELD
143 #undef VTABLE_HASH_FIELD
144 #undef VTABLE_SIZE_FIELD
145 #undef VTABLE_EXTENDS_FIELD
146 #undef VTABLE_DEF_INIT_FIELD
147 #undef VTABLE_COPY_FIELD
148
149
150 /* Takes a derived type expression and returns the address of a temporary
151    class object of the 'declared' type.  */ 
152 static void
153 gfc_conv_derived_to_class (gfc_se *parmse, gfc_expr *e,
154                            gfc_typespec class_ts)
155 {
156   gfc_symbol *vtab;
157   gfc_ss *ss;
158   tree ctree;
159   tree var;
160   tree tmp;
161
162   /* The derived type needs to be converted to a temporary
163      CLASS object.  */
164   tmp = gfc_typenode_for_spec (&class_ts);
165   var = gfc_create_var (tmp, "class");
166
167   /* Set the vptr.  */
168   ctree =  gfc_class_vptr_get (var);
169
170   /* Remember the vtab corresponds to the derived type
171      not to the class declared type.  */
172   vtab = gfc_find_derived_vtab (e->ts.u.derived);
173   gcc_assert (vtab);
174   tmp = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtab));
175   gfc_add_modify (&parmse->pre, ctree,
176                   fold_convert (TREE_TYPE (ctree), tmp));
177
178   /* Now set the data field.  */
179   ctree =  gfc_class_data_get (var);
180
181   if (parmse->ss && parmse->ss->info->useflags)
182     {
183       /* For an array reference in an elemental procedure call we need
184          to retain the ss to provide the scalarized array reference.  */
185       gfc_conv_expr_reference (parmse, e);
186       tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
187       gfc_add_modify (&parmse->pre, ctree, tmp);
188     }
189   else
190     {
191       ss = gfc_walk_expr (e);
192       if (ss == gfc_ss_terminator)
193         {
194           parmse->ss = NULL;
195           gfc_conv_expr_reference (parmse, e);
196           tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
197           gfc_add_modify (&parmse->pre, ctree, tmp);
198         }
199       else
200         {
201           parmse->ss = ss;
202           gfc_conv_expr_descriptor (parmse, e, ss);
203           gfc_add_modify (&parmse->pre, ctree, parmse->expr);
204         }
205     }
206
207   /* Pass the address of the class object.  */
208   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
209 }
210
211
212 /* Takes a scalarized class array expression and returns the
213    address of a temporary scalar class object of the 'declared'
214    type.  
215    OOP-TODO: This could be improved by adding code that branched on
216    the dynamic type being the same as the declared type. In this case
217    the original class expression can be passed directly.  */ 
218 static void
219 gfc_conv_class_to_class (gfc_se *parmse, gfc_expr *e,
220                          gfc_typespec class_ts, bool elemental)
221 {
222   tree ctree;
223   tree var;
224   tree tmp;
225   tree vptr;
226   gfc_ref *ref;
227   gfc_ref *class_ref;
228   bool full_array = false;
229
230   class_ref = NULL;
231   for (ref = e->ref; ref; ref = ref->next)
232     {
233       if (ref->type == REF_COMPONENT
234             && ref->u.c.component->ts.type == BT_CLASS)
235         class_ref = ref;
236
237       if (ref->next == NULL)
238         break;
239     }
240
241   if (ref == NULL || class_ref == ref)
242     return;
243
244   /* Test for FULL_ARRAY.  */
245   gfc_is_class_array_ref (e, &full_array);
246
247   /* The derived type needs to be converted to a temporary
248      CLASS object.  */
249   tmp = gfc_typenode_for_spec (&class_ts);
250   var = gfc_create_var (tmp, "class");
251
252   /* Set the data.  */
253   ctree = gfc_class_data_get (var);
254   gfc_add_modify (&parmse->pre, ctree, parmse->expr);
255
256   /* Return the data component, except in the case of scalarized array
257      references, where nullification of the cannot occur and so there
258      is no need.  */
259   if (!elemental && full_array)
260     gfc_add_modify (&parmse->post, parmse->expr, ctree);
261
262   /* Set the vptr.  */
263   ctree = gfc_class_vptr_get (var);
264
265   /* The vptr is the second field of the actual argument.
266      First we have to find the corresponding class reference. */
267
268   tmp = NULL_TREE;
269   if (class_ref == NULL
270         && e->symtree && e->symtree->n.sym->ts.type == BT_CLASS) 
271     tmp = e->symtree->n.sym->backend_decl;
272   else
273     {
274       /* Remove everything after the last class reference, convert the
275          expression and then recover its tailend once more.  */
276       gfc_se tmpse;
277       ref = class_ref->next;
278       class_ref->next = NULL;
279       gfc_init_se (&tmpse, NULL);
280       gfc_conv_expr (&tmpse, e);
281       class_ref->next = ref;
282       tmp = tmpse.expr;
283     }
284
285   gcc_assert (tmp != NULL_TREE);
286
287   /* Dereference if needs be.  */
288   if (TREE_CODE (TREE_TYPE (tmp)) == REFERENCE_TYPE)
289     tmp = build_fold_indirect_ref_loc (input_location, tmp);
290
291   vptr = gfc_class_vptr_get (tmp);
292   gfc_add_modify (&parmse->pre, ctree,
293                   fold_convert (TREE_TYPE (ctree), vptr));
294
295   /* Return the vptr component, except in the case of scalarized array
296      references, where the dynamic type cannot change.  */
297   if (!elemental && full_array)
298     gfc_add_modify (&parmse->post, vptr,
299                     fold_convert (TREE_TYPE (vptr), ctree));
300
301   /* Pass the address of the class object.  */
302   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
303 }
304
305
306 static tree
307 gfc_trans_class_array_init_assign (gfc_expr *rhs, gfc_expr *lhs, gfc_expr *obj)
308 {
309   gfc_actual_arglist *actual;
310   gfc_expr *ppc;
311   gfc_code *ppc_code;
312   tree res;
313
314   actual = gfc_get_actual_arglist ();
315   actual->expr = gfc_copy_expr (rhs);
316   actual->next = gfc_get_actual_arglist ();
317   actual->next->expr = gfc_copy_expr (lhs);
318   ppc = gfc_copy_expr (obj);
319   gfc_add_vptr_component (ppc);
320   gfc_add_component_ref (ppc, "_copy");
321   ppc_code = gfc_get_code ();
322   ppc_code->resolved_sym = ppc->symtree->n.sym;
323   /* Although '_copy' is set to be elemental in class.c, it is
324      not staying that way.  Find out why, sometime....  */
325   ppc_code->resolved_sym->attr.elemental = 1;
326   ppc_code->ext.actual = actual;
327   ppc_code->expr1 = ppc;
328   ppc_code->op = EXEC_CALL;
329   /* Since '_copy' is elemental, the scalarizer will take care
330      of arrays in gfc_trans_call.  */
331   res = gfc_trans_call (ppc_code, false, NULL, NULL, false);
332   gfc_free_statements (ppc_code);
333   return res;
334 }
335
336 /* Special case for initializing a polymorphic dummy with INTENT(OUT).
337    A MEMCPY is needed to copy the full data from the default initializer
338    of the dynamic type.  */
339
340 tree
341 gfc_trans_class_init_assign (gfc_code *code)
342 {
343   stmtblock_t block;
344   tree tmp;
345   gfc_se dst,src,memsz;
346   gfc_expr *lhs, *rhs, *sz;
347
348   gfc_start_block (&block);
349
350   lhs = gfc_copy_expr (code->expr1);
351   gfc_add_data_component (lhs);
352
353   rhs = gfc_copy_expr (code->expr1);
354   gfc_add_vptr_component (rhs);
355
356   /* Make sure that the component backend_decls have been built, which
357      will not have happened if the derived types concerned have not
358      been referenced.  */
359   gfc_get_derived_type (rhs->ts.u.derived);
360   gfc_add_def_init_component (rhs);
361
362   if (code->expr1->ts.type == BT_CLASS
363         && CLASS_DATA (code->expr1)->attr.dimension)
364     tmp = gfc_trans_class_array_init_assign (rhs, lhs, code->expr1);
365   else
366     {
367       sz = gfc_copy_expr (code->expr1);
368       gfc_add_vptr_component (sz);
369       gfc_add_size_component (sz);
370
371       gfc_init_se (&dst, NULL);
372       gfc_init_se (&src, NULL);
373       gfc_init_se (&memsz, NULL);
374       gfc_conv_expr (&dst, lhs);
375       gfc_conv_expr (&src, rhs);
376       gfc_conv_expr (&memsz, sz);
377       gfc_add_block_to_block (&block, &src.pre);
378       tmp = gfc_build_memcpy_call (dst.expr, src.expr, memsz.expr);
379     }
380   gfc_add_expr_to_block (&block, tmp);
381   
382   return gfc_finish_block (&block);
383 }
384
385
386 /* Translate an assignment to a CLASS object
387    (pointer or ordinary assignment).  */
388
389 tree
390 gfc_trans_class_assign (gfc_expr *expr1, gfc_expr *expr2, gfc_exec_op op)
391 {
392   stmtblock_t block;
393   tree tmp;
394   gfc_expr *lhs;
395   gfc_expr *rhs;
396   gfc_ref *ref;
397
398   gfc_start_block (&block);
399
400   ref = expr1->ref;
401   while (ref && ref->next)
402      ref = ref->next;
403
404   /* Class valued proc_pointer assignments do not need any further
405      preparation.  */
406   if (ref && ref->type == REF_COMPONENT
407         && ref->u.c.component->attr.proc_pointer
408         && expr2->expr_type == EXPR_VARIABLE
409         && expr2->symtree->n.sym->attr.flavor == FL_PROCEDURE
410         && op == EXEC_POINTER_ASSIGN)
411     goto assign;
412
413   if (expr2->ts.type != BT_CLASS)
414     {
415       /* Insert an additional assignment which sets the '_vptr' field.  */
416       gfc_symbol *vtab = NULL;
417       gfc_symtree *st;
418
419       lhs = gfc_copy_expr (expr1);
420       gfc_add_vptr_component (lhs);
421
422       if (expr2->ts.type == BT_DERIVED)
423         vtab = gfc_find_derived_vtab (expr2->ts.u.derived);
424       else if (expr2->expr_type == EXPR_NULL)
425         vtab = gfc_find_derived_vtab (expr1->ts.u.derived);
426       gcc_assert (vtab);
427
428       rhs = gfc_get_expr ();
429       rhs->expr_type = EXPR_VARIABLE;
430       gfc_find_sym_tree (vtab->name, vtab->ns, 1, &st);
431       rhs->symtree = st;
432       rhs->ts = vtab->ts;
433
434       tmp = gfc_trans_pointer_assignment (lhs, rhs);
435       gfc_add_expr_to_block (&block, tmp);
436
437       gfc_free_expr (lhs);
438       gfc_free_expr (rhs);
439     }
440   else if (CLASS_DATA (expr2)->attr.dimension)
441     {
442       /* Insert an additional assignment which sets the '_vptr' field.  */
443       lhs = gfc_copy_expr (expr1);
444       gfc_add_vptr_component (lhs);
445
446       rhs = gfc_copy_expr (expr2);
447       gfc_add_vptr_component (rhs);
448
449       tmp = gfc_trans_pointer_assignment (lhs, rhs);
450       gfc_add_expr_to_block (&block, tmp);
451
452       gfc_free_expr (lhs);
453       gfc_free_expr (rhs);
454     }
455
456   /* Do the actual CLASS assignment.  */
457   if (expr2->ts.type == BT_CLASS
458         && !CLASS_DATA (expr2)->attr.dimension)
459     op = EXEC_ASSIGN;
460   else
461     gfc_add_data_component (expr1);
462
463 assign:
464
465   if (op == EXEC_ASSIGN)
466     tmp = gfc_trans_assignment (expr1, expr2, false, true);
467   else if (op == EXEC_POINTER_ASSIGN)
468     tmp = gfc_trans_pointer_assignment (expr1, expr2);
469   else
470     gcc_unreachable();
471
472   gfc_add_expr_to_block (&block, tmp);
473
474   return gfc_finish_block (&block);
475 }
476
477
478 /* End of prototype trans-class.c  */
479
480
481 static tree gfc_trans_structure_assign (tree dest, gfc_expr * expr);
482 static void gfc_apply_interface_mapping_to_expr (gfc_interface_mapping *,
483                                                  gfc_expr *);
484
485 /* Copy the scalarization loop variables.  */
486
487 static void
488 gfc_copy_se_loopvars (gfc_se * dest, gfc_se * src)
489 {
490   dest->ss = src->ss;
491   dest->loop = src->loop;
492 }
493
494
495 /* Initialize a simple expression holder.
496
497    Care must be taken when multiple se are created with the same parent.
498    The child se must be kept in sync.  The easiest way is to delay creation
499    of a child se until after after the previous se has been translated.  */
500
501 void
502 gfc_init_se (gfc_se * se, gfc_se * parent)
503 {
504   memset (se, 0, sizeof (gfc_se));
505   gfc_init_block (&se->pre);
506   gfc_init_block (&se->post);
507
508   se->parent = parent;
509
510   if (parent)
511     gfc_copy_se_loopvars (se, parent);
512 }
513
514
515 /* Advances to the next SS in the chain.  Use this rather than setting
516    se->ss = se->ss->next because all the parents needs to be kept in sync.
517    See gfc_init_se.  */
518
519 void
520 gfc_advance_se_ss_chain (gfc_se * se)
521 {
522   gfc_se *p;
523   gfc_ss *ss;
524
525   gcc_assert (se != NULL && se->ss != NULL && se->ss != gfc_ss_terminator);
526
527   p = se;
528   /* Walk down the parent chain.  */
529   while (p != NULL)
530     {
531       /* Simple consistency check.  */
532       gcc_assert (p->parent == NULL || p->parent->ss == p->ss
533                   || p->parent->ss->nested_ss == p->ss);
534
535       /* If we were in a nested loop, the next scalarized expression can be
536          on the parent ss' next pointer.  Thus we should not take the next
537          pointer blindly, but rather go up one nest level as long as next
538          is the end of chain.  */
539       ss = p->ss;
540       while (ss->next == gfc_ss_terminator && ss->parent != NULL)
541         ss = ss->parent;
542
543       p->ss = ss->next;
544
545       p = p->parent;
546     }
547 }
548
549
550 /* Ensures the result of the expression as either a temporary variable
551    or a constant so that it can be used repeatedly.  */
552
553 void
554 gfc_make_safe_expr (gfc_se * se)
555 {
556   tree var;
557
558   if (CONSTANT_CLASS_P (se->expr))
559     return;
560
561   /* We need a temporary for this result.  */
562   var = gfc_create_var (TREE_TYPE (se->expr), NULL);
563   gfc_add_modify (&se->pre, var, se->expr);
564   se->expr = var;
565 }
566
567
568 /* Return an expression which determines if a dummy parameter is present.
569    Also used for arguments to procedures with multiple entry points.  */
570
571 tree
572 gfc_conv_expr_present (gfc_symbol * sym)
573 {
574   tree decl, cond;
575
576   gcc_assert (sym->attr.dummy);
577
578   decl = gfc_get_symbol_decl (sym);
579   if (TREE_CODE (decl) != PARM_DECL)
580     {
581       /* Array parameters use a temporary descriptor, we want the real
582          parameter.  */
583       gcc_assert (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (decl))
584              || GFC_ARRAY_TYPE_P (TREE_TYPE (decl)));
585       decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
586     }
587
588   cond = fold_build2_loc (input_location, NE_EXPR, boolean_type_node, decl,
589                           fold_convert (TREE_TYPE (decl), null_pointer_node));
590
591   /* Fortran 2008 allows to pass null pointers and non-associated pointers
592      as actual argument to denote absent dummies. For array descriptors,
593      we thus also need to check the array descriptor.  */
594   if (!sym->attr.pointer && !sym->attr.allocatable
595       && sym->as && sym->as->type == AS_ASSUMED_SHAPE
596       && (gfc_option.allow_std & GFC_STD_F2008) != 0)
597     {
598       tree tmp;
599       tmp = build_fold_indirect_ref_loc (input_location, decl);
600       tmp = gfc_conv_array_data (tmp);
601       tmp = fold_build2_loc (input_location, NE_EXPR, boolean_type_node, tmp,
602                              fold_convert (TREE_TYPE (tmp), null_pointer_node));
603       cond = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
604                               boolean_type_node, cond, tmp);
605     }
606
607   return cond;
608 }
609
610
611 /* Converts a missing, dummy argument into a null or zero.  */
612
613 void
614 gfc_conv_missing_dummy (gfc_se * se, gfc_expr * arg, gfc_typespec ts, int kind)
615 {
616   tree present;
617   tree tmp;
618
619   present = gfc_conv_expr_present (arg->symtree->n.sym);
620
621   if (kind > 0)
622     {
623       /* Create a temporary and convert it to the correct type.  */
624       tmp = gfc_get_int_type (kind);
625       tmp = fold_convert (tmp, build_fold_indirect_ref_loc (input_location,
626                                                         se->expr));
627     
628       /* Test for a NULL value.  */
629       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp), present,
630                         tmp, fold_convert (TREE_TYPE (tmp), integer_one_node));
631       tmp = gfc_evaluate_now (tmp, &se->pre);
632       se->expr = gfc_build_addr_expr (NULL_TREE, tmp);
633     }
634   else
635     {
636       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (se->expr),
637                         present, se->expr,
638                         build_zero_cst (TREE_TYPE (se->expr)));
639       tmp = gfc_evaluate_now (tmp, &se->pre);
640       se->expr = tmp;
641     }
642
643   if (ts.type == BT_CHARACTER)
644     {
645       tmp = build_int_cst (gfc_charlen_type_node, 0);
646       tmp = fold_build3_loc (input_location, COND_EXPR, gfc_charlen_type_node,
647                              present, se->string_length, tmp);
648       tmp = gfc_evaluate_now (tmp, &se->pre);
649       se->string_length = tmp;
650     }
651   return;
652 }
653
654
655 /* Get the character length of an expression, looking through gfc_refs
656    if necessary.  */
657
658 tree
659 gfc_get_expr_charlen (gfc_expr *e)
660 {
661   gfc_ref *r;
662   tree length;
663
664   gcc_assert (e->expr_type == EXPR_VARIABLE 
665               && e->ts.type == BT_CHARACTER);
666   
667   length = NULL; /* To silence compiler warning.  */
668
669   if (is_subref_array (e) && e->ts.u.cl->length)
670     {
671       gfc_se tmpse;
672       gfc_init_se (&tmpse, NULL);
673       gfc_conv_expr_type (&tmpse, e->ts.u.cl->length, gfc_charlen_type_node);
674       e->ts.u.cl->backend_decl = tmpse.expr;
675       return tmpse.expr;
676     }
677
678   /* First candidate: if the variable is of type CHARACTER, the
679      expression's length could be the length of the character
680      variable.  */
681   if (e->symtree->n.sym->ts.type == BT_CHARACTER)
682     length = e->symtree->n.sym->ts.u.cl->backend_decl;
683
684   /* Look through the reference chain for component references.  */
685   for (r = e->ref; r; r = r->next)
686     {
687       switch (r->type)
688         {
689         case REF_COMPONENT:
690           if (r->u.c.component->ts.type == BT_CHARACTER)
691             length = r->u.c.component->ts.u.cl->backend_decl;
692           break;
693
694         case REF_ARRAY:
695           /* Do nothing.  */
696           break;
697
698         default:
699           /* We should never got substring references here.  These will be
700              broken down by the scalarizer.  */
701           gcc_unreachable ();
702           break;
703         }
704     }
705
706   gcc_assert (length != NULL);
707   return length;
708 }
709
710
711 /* Return for an expression the backend decl of the coarray.  */
712
713 static tree
714 get_tree_for_caf_expr (gfc_expr *expr)
715 {
716    tree caf_decl = NULL_TREE;
717    gfc_ref *ref;
718
719    gcc_assert (expr && expr->expr_type == EXPR_VARIABLE);
720    if (expr->symtree->n.sym->attr.codimension)
721      caf_decl = expr->symtree->n.sym->backend_decl;
722
723    for (ref = expr->ref; ref; ref = ref->next)
724      if (ref->type == REF_COMPONENT)
725        {
726         gfc_component *comp = ref->u.c.component;
727         if (comp->attr.pointer || comp->attr.allocatable)
728           caf_decl = NULL_TREE;
729         if (comp->attr.codimension)
730           caf_decl = comp->backend_decl;
731        }
732
733    gcc_assert (caf_decl != NULL_TREE);
734    return caf_decl;
735 }
736
737
738 /* For each character array constructor subexpression without a ts.u.cl->length,
739    replace it by its first element (if there aren't any elements, the length
740    should already be set to zero).  */
741
742 static void
743 flatten_array_ctors_without_strlen (gfc_expr* e)
744 {
745   gfc_actual_arglist* arg;
746   gfc_constructor* c;
747
748   if (!e)
749     return;
750
751   switch (e->expr_type)
752     {
753
754     case EXPR_OP:
755       flatten_array_ctors_without_strlen (e->value.op.op1); 
756       flatten_array_ctors_without_strlen (e->value.op.op2); 
757       break;
758
759     case EXPR_COMPCALL:
760       /* TODO: Implement as with EXPR_FUNCTION when needed.  */
761       gcc_unreachable ();
762
763     case EXPR_FUNCTION:
764       for (arg = e->value.function.actual; arg; arg = arg->next)
765         flatten_array_ctors_without_strlen (arg->expr);
766       break;
767
768     case EXPR_ARRAY:
769
770       /* We've found what we're looking for.  */
771       if (e->ts.type == BT_CHARACTER && !e->ts.u.cl->length)
772         {
773           gfc_constructor *c;
774           gfc_expr* new_expr;
775
776           gcc_assert (e->value.constructor);
777
778           c = gfc_constructor_first (e->value.constructor);
779           new_expr = c->expr;
780           c->expr = NULL;
781
782           flatten_array_ctors_without_strlen (new_expr);
783           gfc_replace_expr (e, new_expr);
784           break;
785         }
786
787       /* Otherwise, fall through to handle constructor elements.  */
788     case EXPR_STRUCTURE:
789       for (c = gfc_constructor_first (e->value.constructor);
790            c; c = gfc_constructor_next (c))
791         flatten_array_ctors_without_strlen (c->expr);
792       break;
793
794     default:
795       break;
796
797     }
798 }
799
800
801 /* Generate code to initialize a string length variable. Returns the
802    value.  For array constructors, cl->length might be NULL and in this case,
803    the first element of the constructor is needed.  expr is the original
804    expression so we can access it but can be NULL if this is not needed.  */
805
806 void
807 gfc_conv_string_length (gfc_charlen * cl, gfc_expr * expr, stmtblock_t * pblock)
808 {
809   gfc_se se;
810
811   gfc_init_se (&se, NULL);
812
813   if (!cl->length
814         && cl->backend_decl
815         && TREE_CODE (cl->backend_decl) == VAR_DECL)
816     return;
817
818   /* If cl->length is NULL, use gfc_conv_expr to obtain the string length but
819      "flatten" array constructors by taking their first element; all elements
820      should be the same length or a cl->length should be present.  */
821   if (!cl->length)
822     {
823       gfc_expr* expr_flat;
824       gcc_assert (expr);
825       expr_flat = gfc_copy_expr (expr);
826       flatten_array_ctors_without_strlen (expr_flat);
827       gfc_resolve_expr (expr_flat);
828
829       gfc_conv_expr (&se, expr_flat);
830       gfc_add_block_to_block (pblock, &se.pre);
831       cl->backend_decl = convert (gfc_charlen_type_node, se.string_length);
832
833       gfc_free_expr (expr_flat);
834       return;
835     }
836
837   /* Convert cl->length.  */
838
839   gcc_assert (cl->length);
840
841   gfc_conv_expr_type (&se, cl->length, gfc_charlen_type_node);
842   se.expr = fold_build2_loc (input_location, MAX_EXPR, gfc_charlen_type_node,
843                              se.expr, build_int_cst (gfc_charlen_type_node, 0));
844   gfc_add_block_to_block (pblock, &se.pre);
845
846   if (cl->backend_decl)
847     gfc_add_modify (pblock, cl->backend_decl, se.expr);
848   else
849     cl->backend_decl = gfc_evaluate_now (se.expr, pblock);
850 }
851
852
853 static void
854 gfc_conv_substring (gfc_se * se, gfc_ref * ref, int kind,
855                     const char *name, locus *where)
856 {
857   tree tmp;
858   tree type;
859   tree fault;
860   gfc_se start;
861   gfc_se end;
862   char *msg;
863
864   type = gfc_get_character_type (kind, ref->u.ss.length);
865   type = build_pointer_type (type);
866
867   gfc_init_se (&start, se);
868   gfc_conv_expr_type (&start, ref->u.ss.start, gfc_charlen_type_node);
869   gfc_add_block_to_block (&se->pre, &start.pre);
870
871   if (integer_onep (start.expr))
872     gfc_conv_string_parameter (se);
873   else
874     {
875       tmp = start.expr;
876       STRIP_NOPS (tmp);
877       /* Avoid multiple evaluation of substring start.  */
878       if (!CONSTANT_CLASS_P (tmp) && !DECL_P (tmp))
879         start.expr = gfc_evaluate_now (start.expr, &se->pre);
880
881       /* Change the start of the string.  */
882       if (TYPE_STRING_FLAG (TREE_TYPE (se->expr)))
883         tmp = se->expr;
884       else
885         tmp = build_fold_indirect_ref_loc (input_location,
886                                        se->expr);
887       tmp = gfc_build_array_ref (tmp, start.expr, NULL);
888       se->expr = gfc_build_addr_expr (type, tmp);
889     }
890
891   /* Length = end + 1 - start.  */
892   gfc_init_se (&end, se);
893   if (ref->u.ss.end == NULL)
894     end.expr = se->string_length;
895   else
896     {
897       gfc_conv_expr_type (&end, ref->u.ss.end, gfc_charlen_type_node);
898       gfc_add_block_to_block (&se->pre, &end.pre);
899     }
900   tmp = end.expr;
901   STRIP_NOPS (tmp);
902   if (!CONSTANT_CLASS_P (tmp) && !DECL_P (tmp))
903     end.expr = gfc_evaluate_now (end.expr, &se->pre);
904
905   if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
906     {
907       tree nonempty = fold_build2_loc (input_location, LE_EXPR,
908                                        boolean_type_node, start.expr,
909                                        end.expr);
910
911       /* Check lower bound.  */
912       fault = fold_build2_loc (input_location, LT_EXPR, boolean_type_node,
913                                start.expr,
914                                build_int_cst (gfc_charlen_type_node, 1));
915       fault = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
916                                boolean_type_node, nonempty, fault);
917       if (name)
918         asprintf (&msg, "Substring out of bounds: lower bound (%%ld) of '%s' "
919                   "is less than one", name);
920       else
921         asprintf (&msg, "Substring out of bounds: lower bound (%%ld)"
922                   "is less than one");
923       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
924                                fold_convert (long_integer_type_node,
925                                              start.expr));
926       free (msg);
927
928       /* Check upper bound.  */
929       fault = fold_build2_loc (input_location, GT_EXPR, boolean_type_node,
930                                end.expr, se->string_length);
931       fault = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
932                                boolean_type_node, nonempty, fault);
933       if (name)
934         asprintf (&msg, "Substring out of bounds: upper bound (%%ld) of '%s' "
935                   "exceeds string length (%%ld)", name);
936       else
937         asprintf (&msg, "Substring out of bounds: upper bound (%%ld) "
938                   "exceeds string length (%%ld)");
939       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
940                                fold_convert (long_integer_type_node, end.expr),
941                                fold_convert (long_integer_type_node,
942                                              se->string_length));
943       free (msg);
944     }
945
946   /* If the start and end expressions are equal, the length is one.  */
947   if (ref->u.ss.end
948       && gfc_dep_compare_expr (ref->u.ss.start, ref->u.ss.end) == 0)
949     tmp = build_int_cst (gfc_charlen_type_node, 1);
950   else
951     {
952       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_charlen_type_node,
953                              end.expr, start.expr);
954       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_charlen_type_node,
955                              build_int_cst (gfc_charlen_type_node, 1), tmp);
956       tmp = fold_build2_loc (input_location, MAX_EXPR, gfc_charlen_type_node,
957                              tmp, build_int_cst (gfc_charlen_type_node, 0));
958     }
959
960   se->string_length = tmp;
961 }
962
963
964 /* Convert a derived type component reference.  */
965
966 static void
967 gfc_conv_component_ref (gfc_se * se, gfc_ref * ref)
968 {
969   gfc_component *c;
970   tree tmp;
971   tree decl;
972   tree field;
973
974   c = ref->u.c.component;
975
976   gcc_assert (c->backend_decl);
977
978   field = c->backend_decl;
979   gcc_assert (TREE_CODE (field) == FIELD_DECL);
980   decl = se->expr;
981
982   /* Components can correspond to fields of different containing
983      types, as components are created without context, whereas
984      a concrete use of a component has the type of decl as context.
985      So, if the type doesn't match, we search the corresponding
986      FIELD_DECL in the parent type.  To not waste too much time
987      we cache this result in norestrict_decl.  */
988
989   if (DECL_FIELD_CONTEXT (field) != TREE_TYPE (decl))
990     {
991       tree f2 = c->norestrict_decl;
992       if (!f2 || DECL_FIELD_CONTEXT (f2) != TREE_TYPE (decl))
993         for (f2 = TYPE_FIELDS (TREE_TYPE (decl)); f2; f2 = DECL_CHAIN (f2))
994           if (TREE_CODE (f2) == FIELD_DECL
995               && DECL_NAME (f2) == DECL_NAME (field))
996             break;
997       gcc_assert (f2);
998       c->norestrict_decl = f2;
999       field = f2;
1000     }
1001   tmp = fold_build3_loc (input_location, COMPONENT_REF, TREE_TYPE (field),
1002                          decl, field, NULL_TREE);
1003
1004   se->expr = tmp;
1005
1006   if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer)
1007     {
1008       tmp = c->ts.u.cl->backend_decl;
1009       /* Components must always be constant length.  */
1010       gcc_assert (tmp && INTEGER_CST_P (tmp));
1011       se->string_length = tmp;
1012     }
1013
1014   if (((c->attr.pointer || c->attr.allocatable)
1015        && (!c->attr.dimension && !c->attr.codimension)
1016        && c->ts.type != BT_CHARACTER)
1017       || c->attr.proc_pointer)
1018     se->expr = build_fold_indirect_ref_loc (input_location,
1019                                         se->expr);
1020 }
1021
1022
1023 /* This function deals with component references to components of the
1024    parent type for derived type extensons.  */
1025 static void
1026 conv_parent_component_references (gfc_se * se, gfc_ref * ref)
1027 {
1028   gfc_component *c;
1029   gfc_component *cmp;
1030   gfc_symbol *dt;
1031   gfc_ref parent;
1032
1033   dt = ref->u.c.sym;
1034   c = ref->u.c.component;
1035
1036   /* Return if the component is not in the parent type.  */
1037   for (cmp = dt->components; cmp; cmp = cmp->next)
1038     if (strcmp (c->name, cmp->name) == 0)
1039       return;
1040
1041   /* Build a gfc_ref to recursively call gfc_conv_component_ref.  */
1042   parent.type = REF_COMPONENT;
1043   parent.next = NULL;
1044   parent.u.c.sym = dt;
1045   parent.u.c.component = dt->components;
1046
1047   if (dt->backend_decl == NULL)
1048     gfc_get_derived_type (dt);
1049
1050   /* Build the reference and call self.  */
1051   gfc_conv_component_ref (se, &parent);
1052   parent.u.c.sym = dt->components->ts.u.derived;
1053   parent.u.c.component = c;
1054   conv_parent_component_references (se, &parent);
1055 }
1056
1057 /* Return the contents of a variable. Also handles reference/pointer
1058    variables (all Fortran pointer references are implicit).  */
1059
1060 static void
1061 gfc_conv_variable (gfc_se * se, gfc_expr * expr)
1062 {
1063   gfc_ss *ss;
1064   gfc_ref *ref;
1065   gfc_symbol *sym;
1066   tree parent_decl = NULL_TREE;
1067   int parent_flag;
1068   bool return_value;
1069   bool alternate_entry;
1070   bool entry_master;
1071
1072   sym = expr->symtree->n.sym;
1073   ss = se->ss;
1074   if (ss != NULL)
1075     {
1076       gfc_ss_info *ss_info = ss->info;
1077
1078       /* Check that something hasn't gone horribly wrong.  */
1079       gcc_assert (ss != gfc_ss_terminator);
1080       gcc_assert (ss_info->expr == expr);
1081
1082       /* A scalarized term.  We already know the descriptor.  */
1083       se->expr = ss_info->data.array.descriptor;
1084       se->string_length = ss_info->string_length;
1085       for (ref = ss_info->data.array.ref; ref; ref = ref->next)
1086         if (ref->type == REF_ARRAY && ref->u.ar.type != AR_ELEMENT)
1087           break;
1088     }
1089   else
1090     {
1091       tree se_expr = NULL_TREE;
1092
1093       se->expr = gfc_get_symbol_decl (sym);
1094
1095       /* Deal with references to a parent results or entries by storing
1096          the current_function_decl and moving to the parent_decl.  */
1097       return_value = sym->attr.function && sym->result == sym;
1098       alternate_entry = sym->attr.function && sym->attr.entry
1099                         && sym->result == sym;
1100       entry_master = sym->attr.result
1101                      && sym->ns->proc_name->attr.entry_master
1102                      && !gfc_return_by_reference (sym->ns->proc_name);
1103       if (current_function_decl)
1104         parent_decl = DECL_CONTEXT (current_function_decl);
1105
1106       if ((se->expr == parent_decl && return_value)
1107            || (sym->ns && sym->ns->proc_name
1108                && parent_decl
1109                && sym->ns->proc_name->backend_decl == parent_decl
1110                && (alternate_entry || entry_master)))
1111         parent_flag = 1;
1112       else
1113         parent_flag = 0;
1114
1115       /* Special case for assigning the return value of a function.
1116          Self recursive functions must have an explicit return value.  */
1117       if (return_value && (se->expr == current_function_decl || parent_flag))
1118         se_expr = gfc_get_fake_result_decl (sym, parent_flag);
1119
1120       /* Similarly for alternate entry points.  */
1121       else if (alternate_entry 
1122                && (sym->ns->proc_name->backend_decl == current_function_decl
1123                    || parent_flag))
1124         {
1125           gfc_entry_list *el = NULL;
1126
1127           for (el = sym->ns->entries; el; el = el->next)
1128             if (sym == el->sym)
1129               {
1130                 se_expr = gfc_get_fake_result_decl (sym, parent_flag);
1131                 break;
1132               }
1133         }
1134
1135       else if (entry_master
1136                && (sym->ns->proc_name->backend_decl == current_function_decl
1137                    || parent_flag))
1138         se_expr = gfc_get_fake_result_decl (sym, parent_flag);
1139
1140       if (se_expr)
1141         se->expr = se_expr;
1142
1143       /* Procedure actual arguments.  */
1144       else if (sym->attr.flavor == FL_PROCEDURE
1145                && se->expr != current_function_decl)
1146         {
1147           if (!sym->attr.dummy && !sym->attr.proc_pointer)
1148             {
1149               gcc_assert (TREE_CODE (se->expr) == FUNCTION_DECL);
1150               se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
1151             }
1152           return;
1153         }
1154
1155
1156       /* Dereference the expression, where needed. Since characters
1157          are entirely different from other types, they are treated 
1158          separately.  */
1159       if (sym->ts.type == BT_CHARACTER)
1160         {
1161           /* Dereference character pointer dummy arguments
1162              or results.  */
1163           if ((sym->attr.pointer || sym->attr.allocatable)
1164               && (sym->attr.dummy
1165                   || sym->attr.function
1166                   || sym->attr.result))
1167             se->expr = build_fold_indirect_ref_loc (input_location,
1168                                                 se->expr);
1169
1170         }
1171       else if (!sym->attr.value)
1172         {
1173           /* Dereference non-character scalar dummy arguments.  */
1174           if (sym->attr.dummy && !sym->attr.dimension
1175               && !(sym->attr.codimension && sym->attr.allocatable))
1176             se->expr = build_fold_indirect_ref_loc (input_location,
1177                                                 se->expr);
1178
1179           /* Dereference scalar hidden result.  */
1180           if (gfc_option.flag_f2c && sym->ts.type == BT_COMPLEX
1181               && (sym->attr.function || sym->attr.result)
1182               && !sym->attr.dimension && !sym->attr.pointer
1183               && !sym->attr.always_explicit)
1184             se->expr = build_fold_indirect_ref_loc (input_location,
1185                                                 se->expr);
1186
1187           /* Dereference non-character pointer variables. 
1188              These must be dummies, results, or scalars.  */
1189           if ((sym->attr.pointer || sym->attr.allocatable
1190                || gfc_is_associate_pointer (sym))
1191               && (sym->attr.dummy
1192                   || sym->attr.function
1193                   || sym->attr.result
1194                   || (!sym->attr.dimension
1195                       && (!sym->attr.codimension || !sym->attr.allocatable))))
1196             se->expr = build_fold_indirect_ref_loc (input_location,
1197                                                 se->expr);
1198         }
1199
1200       ref = expr->ref;
1201     }
1202
1203   /* For character variables, also get the length.  */
1204   if (sym->ts.type == BT_CHARACTER)
1205     {
1206       /* If the character length of an entry isn't set, get the length from
1207          the master function instead.  */
1208       if (sym->attr.entry && !sym->ts.u.cl->backend_decl)
1209         se->string_length = sym->ns->proc_name->ts.u.cl->backend_decl;
1210       else
1211         se->string_length = sym->ts.u.cl->backend_decl;
1212       gcc_assert (se->string_length);
1213     }
1214
1215   while (ref)
1216     {
1217       switch (ref->type)
1218         {
1219         case REF_ARRAY:
1220           /* Return the descriptor if that's what we want and this is an array
1221              section reference.  */
1222           if (se->descriptor_only && ref->u.ar.type != AR_ELEMENT)
1223             return;
1224 /* TODO: Pointers to single elements of array sections, eg elemental subs.  */
1225           /* Return the descriptor for array pointers and allocations.  */
1226           if (se->want_pointer
1227               && ref->next == NULL && (se->descriptor_only))
1228             return;
1229
1230           gfc_conv_array_ref (se, &ref->u.ar, sym, &expr->where);
1231           /* Return a pointer to an element.  */
1232           break;
1233
1234         case REF_COMPONENT:
1235           if (ref->u.c.sym->attr.extension)
1236             conv_parent_component_references (se, ref);
1237
1238           gfc_conv_component_ref (se, ref);
1239
1240           break;
1241
1242         case REF_SUBSTRING:
1243           gfc_conv_substring (se, ref, expr->ts.kind,
1244                               expr->symtree->name, &expr->where);
1245           break;
1246
1247         default:
1248           gcc_unreachable ();
1249           break;
1250         }
1251       ref = ref->next;
1252     }
1253   /* Pointer assignment, allocation or pass by reference.  Arrays are handled
1254      separately.  */
1255   if (se->want_pointer)
1256     {
1257       if (expr->ts.type == BT_CHARACTER && !gfc_is_proc_ptr_comp (expr, NULL))
1258         gfc_conv_string_parameter (se);
1259       else 
1260         se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
1261     }
1262 }
1263
1264
1265 /* Unary ops are easy... Or they would be if ! was a valid op.  */
1266
1267 static void
1268 gfc_conv_unary_op (enum tree_code code, gfc_se * se, gfc_expr * expr)
1269 {
1270   gfc_se operand;
1271   tree type;
1272
1273   gcc_assert (expr->ts.type != BT_CHARACTER);
1274   /* Initialize the operand.  */
1275   gfc_init_se (&operand, se);
1276   gfc_conv_expr_val (&operand, expr->value.op.op1);
1277   gfc_add_block_to_block (&se->pre, &operand.pre);
1278
1279   type = gfc_typenode_for_spec (&expr->ts);
1280
1281   /* TRUTH_NOT_EXPR is not a "true" unary operator in GCC.
1282      We must convert it to a compare to 0 (e.g. EQ_EXPR (op1, 0)).
1283      All other unary operators have an equivalent GIMPLE unary operator.  */
1284   if (code == TRUTH_NOT_EXPR)
1285     se->expr = fold_build2_loc (input_location, EQ_EXPR, type, operand.expr,
1286                                 build_int_cst (type, 0));
1287   else
1288     se->expr = fold_build1_loc (input_location, code, type, operand.expr);
1289
1290 }
1291
1292 /* Expand power operator to optimal multiplications when a value is raised
1293    to a constant integer n. See section 4.6.3, "Evaluation of Powers" of
1294    Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art of Computer
1295    Programming", 3rd Edition, 1998.  */
1296
1297 /* This code is mostly duplicated from expand_powi in the backend.
1298    We establish the "optimal power tree" lookup table with the defined size.
1299    The items in the table are the exponents used to calculate the index
1300    exponents. Any integer n less than the value can get an "addition chain",
1301    with the first node being one.  */
1302 #define POWI_TABLE_SIZE 256
1303
1304 /* The table is from builtins.c.  */
1305 static const unsigned char powi_table[POWI_TABLE_SIZE] =
1306   {
1307       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
1308       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
1309       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
1310      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
1311      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
1312      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
1313      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
1314      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
1315      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
1316      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
1317      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
1318      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
1319      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
1320      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
1321      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
1322      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
1323      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
1324      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
1325      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
1326      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
1327      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
1328      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
1329      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
1330      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
1331      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
1332     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
1333     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
1334     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
1335     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
1336     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
1337     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
1338     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
1339   };
1340
1341 /* If n is larger than lookup table's max index, we use the "window 
1342    method".  */
1343 #define POWI_WINDOW_SIZE 3
1344
1345 /* Recursive function to expand the power operator. The temporary 
1346    values are put in tmpvar. The function returns tmpvar[1] ** n.  */
1347 static tree
1348 gfc_conv_powi (gfc_se * se, unsigned HOST_WIDE_INT n, tree * tmpvar)
1349 {
1350   tree op0;
1351   tree op1;
1352   tree tmp;
1353   int digit;
1354
1355   if (n < POWI_TABLE_SIZE)
1356     {
1357       if (tmpvar[n])
1358         return tmpvar[n];
1359
1360       op0 = gfc_conv_powi (se, n - powi_table[n], tmpvar);
1361       op1 = gfc_conv_powi (se, powi_table[n], tmpvar);
1362     }
1363   else if (n & 1)
1364     {
1365       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
1366       op0 = gfc_conv_powi (se, n - digit, tmpvar);
1367       op1 = gfc_conv_powi (se, digit, tmpvar);
1368     }
1369   else
1370     {
1371       op0 = gfc_conv_powi (se, n >> 1, tmpvar);
1372       op1 = op0;
1373     }
1374
1375   tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (op0), op0, op1);
1376   tmp = gfc_evaluate_now (tmp, &se->pre);
1377
1378   if (n < POWI_TABLE_SIZE)
1379     tmpvar[n] = tmp;
1380
1381   return tmp;
1382 }
1383
1384
1385 /* Expand lhs ** rhs. rhs is a constant integer. If it expands successfully,
1386    return 1. Else return 0 and a call to runtime library functions
1387    will have to be built.  */
1388 static int
1389 gfc_conv_cst_int_power (gfc_se * se, tree lhs, tree rhs)
1390 {
1391   tree cond;
1392   tree tmp;
1393   tree type;
1394   tree vartmp[POWI_TABLE_SIZE];
1395   HOST_WIDE_INT m;
1396   unsigned HOST_WIDE_INT n;
1397   int sgn;
1398
1399   /* If exponent is too large, we won't expand it anyway, so don't bother
1400      with large integer values.  */
1401   if (!double_int_fits_in_shwi_p (TREE_INT_CST (rhs)))
1402     return 0;
1403
1404   m = double_int_to_shwi (TREE_INT_CST (rhs));
1405   /* There's no ABS for HOST_WIDE_INT, so here we go. It also takes care
1406      of the asymmetric range of the integer type.  */
1407   n = (unsigned HOST_WIDE_INT) (m < 0 ? -m : m);
1408   
1409   type = TREE_TYPE (lhs);
1410   sgn = tree_int_cst_sgn (rhs);
1411
1412   if (((FLOAT_TYPE_P (type) && !flag_unsafe_math_optimizations)
1413        || optimize_size) && (m > 2 || m < -1))
1414     return 0;
1415
1416   /* rhs == 0  */
1417   if (sgn == 0)
1418     {
1419       se->expr = gfc_build_const (type, integer_one_node);
1420       return 1;
1421     }
1422
1423   /* If rhs < 0 and lhs is an integer, the result is -1, 0 or 1.  */
1424   if ((sgn == -1) && (TREE_CODE (type) == INTEGER_TYPE))
1425     {
1426       tmp = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
1427                              lhs, build_int_cst (TREE_TYPE (lhs), -1));
1428       cond = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
1429                               lhs, build_int_cst (TREE_TYPE (lhs), 1));
1430
1431       /* If rhs is even,
1432          result = (lhs == 1 || lhs == -1) ? 1 : 0.  */
1433       if ((n & 1) == 0)
1434         {
1435           tmp = fold_build2_loc (input_location, TRUTH_OR_EXPR,
1436                                  boolean_type_node, tmp, cond);
1437           se->expr = fold_build3_loc (input_location, COND_EXPR, type,
1438                                       tmp, build_int_cst (type, 1),
1439                                       build_int_cst (type, 0));
1440           return 1;
1441         }
1442       /* If rhs is odd,
1443          result = (lhs == 1) ? 1 : (lhs == -1) ? -1 : 0.  */
1444       tmp = fold_build3_loc (input_location, COND_EXPR, type, tmp,
1445                              build_int_cst (type, -1),
1446                              build_int_cst (type, 0));
1447       se->expr = fold_build3_loc (input_location, COND_EXPR, type,
1448                                   cond, build_int_cst (type, 1), tmp);
1449       return 1;
1450     }
1451
1452   memset (vartmp, 0, sizeof (vartmp));
1453   vartmp[1] = lhs;
1454   if (sgn == -1)
1455     {
1456       tmp = gfc_build_const (type, integer_one_node);
1457       vartmp[1] = fold_build2_loc (input_location, RDIV_EXPR, type, tmp,
1458                                    vartmp[1]);
1459     }
1460
1461   se->expr = gfc_conv_powi (se, n, vartmp);
1462
1463   return 1;
1464 }
1465
1466
1467 /* Power op (**).  Constant integer exponent has special handling.  */
1468
1469 static void
1470 gfc_conv_power_op (gfc_se * se, gfc_expr * expr)
1471 {
1472   tree gfc_int4_type_node;
1473   int kind;
1474   int ikind;
1475   int res_ikind_1, res_ikind_2;
1476   gfc_se lse;
1477   gfc_se rse;
1478   tree fndecl = NULL;
1479
1480   gfc_init_se (&lse, se);
1481   gfc_conv_expr_val (&lse, expr->value.op.op1);
1482   lse.expr = gfc_evaluate_now (lse.expr, &lse.pre);
1483   gfc_add_block_to_block (&se->pre, &lse.pre);
1484
1485   gfc_init_se (&rse, se);
1486   gfc_conv_expr_val (&rse, expr->value.op.op2);
1487   gfc_add_block_to_block (&se->pre, &rse.pre);
1488
1489   if (expr->value.op.op2->ts.type == BT_INTEGER
1490       && expr->value.op.op2->expr_type == EXPR_CONSTANT)
1491     if (gfc_conv_cst_int_power (se, lse.expr, rse.expr))
1492       return;
1493
1494   gfc_int4_type_node = gfc_get_int_type (4);
1495
1496   /* In case of integer operands with kinds 1 or 2, we call the integer kind 4
1497      library routine.  But in the end, we have to convert the result back
1498      if this case applies -- with res_ikind_K, we keep track whether operand K
1499      falls into this case.  */
1500   res_ikind_1 = -1;
1501   res_ikind_2 = -1;
1502
1503   kind = expr->value.op.op1->ts.kind;
1504   switch (expr->value.op.op2->ts.type)
1505     {
1506     case BT_INTEGER:
1507       ikind = expr->value.op.op2->ts.kind;
1508       switch (ikind)
1509         {
1510         case 1:
1511         case 2:
1512           rse.expr = convert (gfc_int4_type_node, rse.expr);
1513           res_ikind_2 = ikind;
1514           /* Fall through.  */
1515
1516         case 4:
1517           ikind = 0;
1518           break;
1519           
1520         case 8:
1521           ikind = 1;
1522           break;
1523
1524         case 16:
1525           ikind = 2;
1526           break;
1527
1528         default:
1529           gcc_unreachable ();
1530         }
1531       switch (kind)
1532         {
1533         case 1:
1534         case 2:
1535           if (expr->value.op.op1->ts.type == BT_INTEGER)
1536             {
1537               lse.expr = convert (gfc_int4_type_node, lse.expr);
1538               res_ikind_1 = kind;
1539             }
1540           else
1541             gcc_unreachable ();
1542           /* Fall through.  */
1543
1544         case 4:
1545           kind = 0;
1546           break;
1547           
1548         case 8:
1549           kind = 1;
1550           break;
1551
1552         case 10:
1553           kind = 2;
1554           break;
1555
1556         case 16:
1557           kind = 3;
1558           break;
1559
1560         default:
1561           gcc_unreachable ();
1562         }
1563       
1564       switch (expr->value.op.op1->ts.type)
1565         {
1566         case BT_INTEGER:
1567           if (kind == 3) /* Case 16 was not handled properly above.  */
1568             kind = 2;
1569           fndecl = gfor_fndecl_math_powi[kind][ikind].integer;
1570           break;
1571
1572         case BT_REAL:
1573           /* Use builtins for real ** int4.  */
1574           if (ikind == 0)
1575             {
1576               switch (kind)
1577                 {
1578                 case 0:
1579                   fndecl = builtin_decl_explicit (BUILT_IN_POWIF);
1580                   break;
1581                 
1582                 case 1:
1583                   fndecl = builtin_decl_explicit (BUILT_IN_POWI);
1584                   break;
1585
1586                 case 2:
1587                   fndecl = builtin_decl_explicit (BUILT_IN_POWIL);
1588                   break;
1589
1590                 case 3:
1591                   /* Use the __builtin_powil() only if real(kind=16) is 
1592                      actually the C long double type.  */
1593                   if (!gfc_real16_is_float128)
1594                     fndecl = builtin_decl_explicit (BUILT_IN_POWIL);
1595                   break;
1596
1597                 default:
1598                   gcc_unreachable ();
1599                 }
1600             }
1601
1602           /* If we don't have a good builtin for this, go for the 
1603              library function.  */
1604           if (!fndecl)
1605             fndecl = gfor_fndecl_math_powi[kind][ikind].real;
1606           break;
1607
1608         case BT_COMPLEX:
1609           fndecl = gfor_fndecl_math_powi[kind][ikind].cmplx;
1610           break;
1611
1612         default:
1613           gcc_unreachable ();
1614         }
1615       break;
1616
1617     case BT_REAL:
1618       fndecl = gfc_builtin_decl_for_float_kind (BUILT_IN_POW, kind);
1619       break;
1620
1621     case BT_COMPLEX:
1622       fndecl = gfc_builtin_decl_for_float_kind (BUILT_IN_CPOW, kind);
1623       break;
1624
1625     default:
1626       gcc_unreachable ();
1627       break;
1628     }
1629
1630   se->expr = build_call_expr_loc (input_location,
1631                               fndecl, 2, lse.expr, rse.expr);
1632
1633   /* Convert the result back if it is of wrong integer kind.  */
1634   if (res_ikind_1 != -1 && res_ikind_2 != -1)
1635     {
1636       /* We want the maximum of both operand kinds as result.  */
1637       if (res_ikind_1 < res_ikind_2)
1638         res_ikind_1 = res_ikind_2;
1639       se->expr = convert (gfc_get_int_type (res_ikind_1), se->expr);
1640     }
1641 }
1642
1643
1644 /* Generate code to allocate a string temporary.  */
1645
1646 tree
1647 gfc_conv_string_tmp (gfc_se * se, tree type, tree len)
1648 {
1649   tree var;
1650   tree tmp;
1651
1652   if (gfc_can_put_var_on_stack (len))
1653     {
1654       /* Create a temporary variable to hold the result.  */
1655       tmp = fold_build2_loc (input_location, MINUS_EXPR,
1656                              gfc_charlen_type_node, len,
1657                              build_int_cst (gfc_charlen_type_node, 1));
1658       tmp = build_range_type (gfc_array_index_type, gfc_index_zero_node, tmp);
1659
1660       if (TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE)
1661         tmp = build_array_type (TREE_TYPE (TREE_TYPE (type)), tmp);
1662       else
1663         tmp = build_array_type (TREE_TYPE (type), tmp);
1664
1665       var = gfc_create_var (tmp, "str");
1666       var = gfc_build_addr_expr (type, var);
1667     }
1668   else
1669     {
1670       /* Allocate a temporary to hold the result.  */
1671       var = gfc_create_var (type, "pstr");
1672       tmp = gfc_call_malloc (&se->pre, type,
1673                              fold_build2_loc (input_location, MULT_EXPR,
1674                                               TREE_TYPE (len), len,
1675                                               fold_convert (TREE_TYPE (len),
1676                                                             TYPE_SIZE (type))));
1677       gfc_add_modify (&se->pre, var, tmp);
1678
1679       /* Free the temporary afterwards.  */
1680       tmp = gfc_call_free (convert (pvoid_type_node, var));
1681       gfc_add_expr_to_block (&se->post, tmp);
1682     }
1683
1684   return var;
1685 }
1686
1687
1688 /* Handle a string concatenation operation.  A temporary will be allocated to
1689    hold the result.  */
1690
1691 static void
1692 gfc_conv_concat_op (gfc_se * se, gfc_expr * expr)
1693 {
1694   gfc_se lse, rse;
1695   tree len, type, var, tmp, fndecl;
1696
1697   gcc_assert (expr->value.op.op1->ts.type == BT_CHARACTER
1698               && expr->value.op.op2->ts.type == BT_CHARACTER);
1699   gcc_assert (expr->value.op.op1->ts.kind == expr->value.op.op2->ts.kind);
1700
1701   gfc_init_se (&lse, se);
1702   gfc_conv_expr (&lse, expr->value.op.op1);
1703   gfc_conv_string_parameter (&lse);
1704   gfc_init_se (&rse, se);
1705   gfc_conv_expr (&rse, expr->value.op.op2);
1706   gfc_conv_string_parameter (&rse);
1707
1708   gfc_add_block_to_block (&se->pre, &lse.pre);
1709   gfc_add_block_to_block (&se->pre, &rse.pre);
1710
1711   type = gfc_get_character_type (expr->ts.kind, expr->ts.u.cl);
1712   len = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
1713   if (len == NULL_TREE)
1714     {
1715       len = fold_build2_loc (input_location, PLUS_EXPR,
1716                              TREE_TYPE (lse.string_length),
1717                              lse.string_length, rse.string_length);
1718     }
1719
1720   type = build_pointer_type (type);
1721
1722   var = gfc_conv_string_tmp (se, type, len);
1723
1724   /* Do the actual concatenation.  */
1725   if (expr->ts.kind == 1)
1726     fndecl = gfor_fndecl_concat_string;
1727   else if (expr->ts.kind == 4)
1728     fndecl = gfor_fndecl_concat_string_char4;
1729   else
1730     gcc_unreachable ();
1731
1732   tmp = build_call_expr_loc (input_location,
1733                          fndecl, 6, len, var, lse.string_length, lse.expr,
1734                          rse.string_length, rse.expr);
1735   gfc_add_expr_to_block (&se->pre, tmp);
1736
1737   /* Add the cleanup for the operands.  */
1738   gfc_add_block_to_block (&se->pre, &rse.post);
1739   gfc_add_block_to_block (&se->pre, &lse.post);
1740
1741   se->expr = var;
1742   se->string_length = len;
1743 }
1744
1745 /* Translates an op expression. Common (binary) cases are handled by this
1746    function, others are passed on. Recursion is used in either case.
1747    We use the fact that (op1.ts == op2.ts) (except for the power
1748    operator **).
1749    Operators need no special handling for scalarized expressions as long as
1750    they call gfc_conv_simple_val to get their operands.
1751    Character strings get special handling.  */
1752
1753 static void
1754 gfc_conv_expr_op (gfc_se * se, gfc_expr * expr)
1755 {
1756   enum tree_code code;
1757   gfc_se lse;
1758   gfc_se rse;
1759   tree tmp, type;
1760   int lop;
1761   int checkstring;
1762
1763   checkstring = 0;
1764   lop = 0;
1765   switch (expr->value.op.op)
1766     {
1767     case INTRINSIC_PARENTHESES:
1768       if ((expr->ts.type == BT_REAL
1769            || expr->ts.type == BT_COMPLEX)
1770           && gfc_option.flag_protect_parens)
1771         {
1772           gfc_conv_unary_op (PAREN_EXPR, se, expr);
1773           gcc_assert (FLOAT_TYPE_P (TREE_TYPE (se->expr)));
1774           return;
1775         }
1776
1777       /* Fallthrough.  */
1778     case INTRINSIC_UPLUS:
1779       gfc_conv_expr (se, expr->value.op.op1);
1780       return;
1781
1782     case INTRINSIC_UMINUS:
1783       gfc_conv_unary_op (NEGATE_EXPR, se, expr);
1784       return;
1785
1786     case INTRINSIC_NOT:
1787       gfc_conv_unary_op (TRUTH_NOT_EXPR, se, expr);
1788       return;
1789
1790     case INTRINSIC_PLUS:
1791       code = PLUS_EXPR;
1792       break;
1793
1794     case INTRINSIC_MINUS:
1795       code = MINUS_EXPR;
1796       break;
1797
1798     case INTRINSIC_TIMES:
1799       code = MULT_EXPR;
1800       break;
1801
1802     case INTRINSIC_DIVIDE:
1803       /* If expr is a real or complex expr, use an RDIV_EXPR. If op1 is
1804          an integer, we must round towards zero, so we use a
1805          TRUNC_DIV_EXPR.  */
1806       if (expr->ts.type == BT_INTEGER)
1807         code = TRUNC_DIV_EXPR;
1808       else
1809         code = RDIV_EXPR;
1810       break;
1811
1812     case INTRINSIC_POWER:
1813       gfc_conv_power_op (se, expr);
1814       return;
1815
1816     case INTRINSIC_CONCAT:
1817       gfc_conv_concat_op (se, expr);
1818       return;
1819
1820     case INTRINSIC_AND:
1821       code = TRUTH_ANDIF_EXPR;
1822       lop = 1;
1823       break;
1824
1825     case INTRINSIC_OR:
1826       code = TRUTH_ORIF_EXPR;
1827       lop = 1;
1828       break;
1829
1830       /* EQV and NEQV only work on logicals, but since we represent them
1831          as integers, we can use EQ_EXPR and NE_EXPR for them in GIMPLE.  */
1832     case INTRINSIC_EQ:
1833     case INTRINSIC_EQ_OS:
1834     case INTRINSIC_EQV:
1835       code = EQ_EXPR;
1836       checkstring = 1;
1837       lop = 1;
1838       break;
1839
1840     case INTRINSIC_NE:
1841     case INTRINSIC_NE_OS:
1842     case INTRINSIC_NEQV:
1843       code = NE_EXPR;
1844       checkstring = 1;
1845       lop = 1;
1846       break;
1847
1848     case INTRINSIC_GT:
1849     case INTRINSIC_GT_OS:
1850       code = GT_EXPR;
1851       checkstring = 1;
1852       lop = 1;
1853       break;
1854
1855     case INTRINSIC_GE:
1856     case INTRINSIC_GE_OS:
1857       code = GE_EXPR;
1858       checkstring = 1;
1859       lop = 1;
1860       break;
1861
1862     case INTRINSIC_LT:
1863     case INTRINSIC_LT_OS:
1864       code = LT_EXPR;
1865       checkstring = 1;
1866       lop = 1;
1867       break;
1868
1869     case INTRINSIC_LE:
1870     case INTRINSIC_LE_OS:
1871       code = LE_EXPR;
1872       checkstring = 1;
1873       lop = 1;
1874       break;
1875
1876     case INTRINSIC_USER:
1877     case INTRINSIC_ASSIGN:
1878       /* These should be converted into function calls by the frontend.  */
1879       gcc_unreachable ();
1880
1881     default:
1882       fatal_error ("Unknown intrinsic op");
1883       return;
1884     }
1885
1886   /* The only exception to this is **, which is handled separately anyway.  */
1887   gcc_assert (expr->value.op.op1->ts.type == expr->value.op.op2->ts.type);
1888
1889   if (checkstring && expr->value.op.op1->ts.type != BT_CHARACTER)
1890     checkstring = 0;
1891
1892   /* lhs */
1893   gfc_init_se (&lse, se);
1894   gfc_conv_expr (&lse, expr->value.op.op1);
1895   gfc_add_block_to_block (&se->pre, &lse.pre);
1896
1897   /* rhs */
1898   gfc_init_se (&rse, se);
1899   gfc_conv_expr (&rse, expr->value.op.op2);
1900   gfc_add_block_to_block (&se->pre, &rse.pre);
1901
1902   if (checkstring)
1903     {
1904       gfc_conv_string_parameter (&lse);
1905       gfc_conv_string_parameter (&rse);
1906
1907       lse.expr = gfc_build_compare_string (lse.string_length, lse.expr,
1908                                            rse.string_length, rse.expr,
1909                                            expr->value.op.op1->ts.kind,
1910                                            code);
1911       rse.expr = build_int_cst (TREE_TYPE (lse.expr), 0);
1912       gfc_add_block_to_block (&lse.post, &rse.post);
1913     }
1914
1915   type = gfc_typenode_for_spec (&expr->ts);
1916
1917   if (lop)
1918     {
1919       /* The result of logical ops is always boolean_type_node.  */
1920       tmp = fold_build2_loc (input_location, code, boolean_type_node,
1921                              lse.expr, rse.expr);
1922       se->expr = convert (type, tmp);
1923     }
1924   else
1925     se->expr = fold_build2_loc (input_location, code, type, lse.expr, rse.expr);
1926
1927   /* Add the post blocks.  */
1928   gfc_add_block_to_block (&se->post, &rse.post);
1929   gfc_add_block_to_block (&se->post, &lse.post);
1930 }
1931
1932 /* If a string's length is one, we convert it to a single character.  */
1933
1934 tree
1935 gfc_string_to_single_character (tree len, tree str, int kind)
1936 {
1937
1938   if (!INTEGER_CST_P (len) || TREE_INT_CST_HIGH (len) != 0
1939       || !POINTER_TYPE_P (TREE_TYPE (str)))
1940     return NULL_TREE;
1941
1942   if (TREE_INT_CST_LOW (len) == 1)
1943     {
1944       str = fold_convert (gfc_get_pchar_type (kind), str);
1945       return build_fold_indirect_ref_loc (input_location, str);
1946     }
1947
1948   if (kind == 1
1949       && TREE_CODE (str) == ADDR_EXPR
1950       && TREE_CODE (TREE_OPERAND (str, 0)) == ARRAY_REF
1951       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (str, 0), 0)) == STRING_CST
1952       && array_ref_low_bound (TREE_OPERAND (str, 0))
1953          == TREE_OPERAND (TREE_OPERAND (str, 0), 1)
1954       && TREE_INT_CST_LOW (len) > 1
1955       && TREE_INT_CST_LOW (len)
1956          == (unsigned HOST_WIDE_INT)
1957             TREE_STRING_LENGTH (TREE_OPERAND (TREE_OPERAND (str, 0), 0)))
1958     {
1959       tree ret = fold_convert (gfc_get_pchar_type (kind), str);
1960       ret = build_fold_indirect_ref_loc (input_location, ret);
1961       if (TREE_CODE (ret) == INTEGER_CST)
1962         {
1963           tree string_cst = TREE_OPERAND (TREE_OPERAND (str, 0), 0);
1964           int i, length = TREE_STRING_LENGTH (string_cst);
1965           const char *ptr = TREE_STRING_POINTER (string_cst);
1966
1967           for (i = 1; i < length; i++)
1968             if (ptr[i] != ' ')
1969               return NULL_TREE;
1970
1971           return ret;
1972         }
1973     }
1974
1975   return NULL_TREE;
1976 }
1977
1978
1979 void
1980 gfc_conv_scalar_char_value (gfc_symbol *sym, gfc_se *se, gfc_expr **expr)
1981 {
1982
1983   if (sym->backend_decl)
1984     {
1985       /* This becomes the nominal_type in
1986          function.c:assign_parm_find_data_types.  */
1987       TREE_TYPE (sym->backend_decl) = unsigned_char_type_node;
1988       /* This becomes the passed_type in
1989          function.c:assign_parm_find_data_types.  C promotes char to
1990          integer for argument passing.  */
1991       DECL_ARG_TYPE (sym->backend_decl) = unsigned_type_node;
1992
1993       DECL_BY_REFERENCE (sym->backend_decl) = 0;
1994     }
1995
1996   if (expr != NULL)
1997     {
1998       /* If we have a constant character expression, make it into an
1999          integer.  */
2000       if ((*expr)->expr_type == EXPR_CONSTANT)
2001         {
2002           gfc_typespec ts;
2003           gfc_clear_ts (&ts);
2004
2005           *expr = gfc_get_int_expr (gfc_default_integer_kind, NULL,
2006                                     (int)(*expr)->value.character.string[0]);
2007           if ((*expr)->ts.kind != gfc_c_int_kind)
2008             {
2009               /* The expr needs to be compatible with a C int.  If the 
2010                  conversion fails, then the 2 causes an ICE.  */
2011               ts.type = BT_INTEGER;
2012               ts.kind = gfc_c_int_kind;
2013               gfc_convert_type (*expr, &ts, 2);
2014             }
2015         }
2016       else if (se != NULL && (*expr)->expr_type == EXPR_VARIABLE)
2017         {
2018           if ((*expr)->ref == NULL)
2019             {
2020               se->expr = gfc_string_to_single_character
2021                 (build_int_cst (integer_type_node, 1),
2022                  gfc_build_addr_expr (gfc_get_pchar_type ((*expr)->ts.kind),
2023                                       gfc_get_symbol_decl
2024                                       ((*expr)->symtree->n.sym)),
2025                  (*expr)->ts.kind);
2026             }
2027           else
2028             {
2029               gfc_conv_variable (se, *expr);
2030               se->expr = gfc_string_to_single_character
2031                 (build_int_cst (integer_type_node, 1),
2032                  gfc_build_addr_expr (gfc_get_pchar_type ((*expr)->ts.kind),
2033                                       se->expr),
2034                  (*expr)->ts.kind);
2035             }
2036         }
2037     }
2038 }
2039
2040 /* Helper function for gfc_build_compare_string.  Return LEN_TRIM value
2041    if STR is a string literal, otherwise return -1.  */
2042
2043 static int
2044 gfc_optimize_len_trim (tree len, tree str, int kind)
2045 {
2046   if (kind == 1
2047       && TREE_CODE (str) == ADDR_EXPR
2048       && TREE_CODE (TREE_OPERAND (str, 0)) == ARRAY_REF
2049       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (str, 0), 0)) == STRING_CST
2050       && array_ref_low_bound (TREE_OPERAND (str, 0))
2051          == TREE_OPERAND (TREE_OPERAND (str, 0), 1)
2052       && TREE_INT_CST_LOW (len) >= 1
2053       && TREE_INT_CST_LOW (len)
2054          == (unsigned HOST_WIDE_INT)
2055             TREE_STRING_LENGTH (TREE_OPERAND (TREE_OPERAND (str, 0), 0)))
2056     {
2057       tree folded = fold_convert (gfc_get_pchar_type (kind), str);
2058       folded = build_fold_indirect_ref_loc (input_location, folded);
2059       if (TREE_CODE (folded) == INTEGER_CST)
2060         {
2061           tree string_cst = TREE_OPERAND (TREE_OPERAND (str, 0), 0);
2062           int length = TREE_STRING_LENGTH (string_cst);
2063           const char *ptr = TREE_STRING_POINTER (string_cst);
2064
2065           for (; length > 0; length--)
2066             if (ptr[length - 1] != ' ')
2067               break;
2068
2069           return length;
2070         }
2071     }
2072   return -1;
2073 }
2074
2075 /* Compare two strings. If they are all single characters, the result is the
2076    subtraction of them. Otherwise, we build a library call.  */
2077
2078 tree
2079 gfc_build_compare_string (tree len1, tree str1, tree len2, tree str2, int kind,
2080                           enum tree_code code)
2081 {
2082   tree sc1;
2083   tree sc2;
2084   tree fndecl;
2085
2086   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str1)));
2087   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str2)));
2088
2089   sc1 = gfc_string_to_single_character (len1, str1, kind);
2090   sc2 = gfc_string_to_single_character (len2, str2, kind);
2091
2092   if (sc1 != NULL_TREE && sc2 != NULL_TREE)
2093     {
2094       /* Deal with single character specially.  */
2095       sc1 = fold_convert (integer_type_node, sc1);
2096       sc2 = fold_convert (integer_type_node, sc2);
2097       return fold_build2_loc (input_location, MINUS_EXPR, integer_type_node,
2098                               sc1, sc2);
2099     }
2100
2101   if ((code == EQ_EXPR || code == NE_EXPR)
2102       && optimize
2103       && INTEGER_CST_P (len1) && INTEGER_CST_P (len2))
2104     {
2105       /* If one string is a string literal with LEN_TRIM longer
2106          than the length of the second string, the strings
2107          compare unequal.  */
2108       int len = gfc_optimize_len_trim (len1, str1, kind);
2109       if (len > 0 && compare_tree_int (len2, len) < 0)
2110         return integer_one_node;
2111       len = gfc_optimize_len_trim (len2, str2, kind);
2112       if (len > 0 && compare_tree_int (len1, len) < 0)
2113         return integer_one_node;
2114     }
2115
2116   /* Build a call for the comparison.  */
2117   if (kind == 1)
2118     fndecl = gfor_fndecl_compare_string;
2119   else if (kind == 4)
2120     fndecl = gfor_fndecl_compare_string_char4;
2121   else
2122     gcc_unreachable ();
2123
2124   return build_call_expr_loc (input_location, fndecl, 4,
2125                               len1, str1, len2, str2);
2126 }
2127
2128
2129 /* Return the backend_decl for a procedure pointer component.  */
2130
2131 static tree
2132 get_proc_ptr_comp (gfc_expr *e)
2133 {
2134   gfc_se comp_se;
2135   gfc_expr *e2;
2136   expr_t old_type;
2137
2138   gfc_init_se (&comp_se, NULL);
2139   e2 = gfc_copy_expr (e);
2140   /* We have to restore the expr type later so that gfc_free_expr frees
2141      the exact same thing that was allocated.
2142      TODO: This is ugly.  */
2143   old_type = e2->expr_type;
2144   e2->expr_type = EXPR_VARIABLE;
2145   gfc_conv_expr (&comp_se, e2);
2146   e2->expr_type = old_type;
2147   gfc_free_expr (e2);
2148   return build_fold_addr_expr_loc (input_location, comp_se.expr);
2149 }
2150
2151
2152 /* Convert a typebound function reference from a class object.  */
2153 static void
2154 conv_base_obj_fcn_val (gfc_se * se, tree base_object, gfc_expr * expr)
2155 {
2156   gfc_ref *ref;
2157   tree var;
2158
2159   if (TREE_CODE (base_object) != VAR_DECL)
2160     {
2161       var = gfc_create_var (TREE_TYPE (base_object), NULL);
2162       gfc_add_modify (&se->pre, var, base_object);
2163     }
2164   se->expr = gfc_class_vptr_get (base_object);
2165   se->expr = build_fold_indirect_ref_loc (input_location, se->expr);
2166   ref = expr->ref;
2167   while (ref && ref->next)
2168     ref = ref->next;
2169   gcc_assert (ref && ref->type == REF_COMPONENT);
2170   if (ref->u.c.sym->attr.extension)
2171     conv_parent_component_references (se, ref);
2172   gfc_conv_component_ref (se, ref);
2173   se->expr = build_fold_addr_expr_loc (input_location, se->expr);
2174 }
2175
2176
2177 static void
2178 conv_function_val (gfc_se * se, gfc_symbol * sym, gfc_expr * expr)
2179 {
2180   tree tmp;
2181
2182   if (gfc_is_proc_ptr_comp (expr, NULL))
2183     tmp = get_proc_ptr_comp (expr);
2184   else if (sym->attr.dummy)
2185     {
2186       tmp = gfc_get_symbol_decl (sym);
2187       if (sym->attr.proc_pointer)
2188         tmp = build_fold_indirect_ref_loc (input_location,
2189                                        tmp);
2190       gcc_assert (TREE_CODE (TREE_TYPE (tmp)) == POINTER_TYPE
2191               && TREE_CODE (TREE_TYPE (TREE_TYPE (tmp))) == FUNCTION_TYPE);
2192     }
2193   else
2194     {
2195       if (!sym->backend_decl)
2196         sym->backend_decl = gfc_get_extern_function_decl (sym);
2197
2198       tmp = sym->backend_decl;
2199
2200       if (sym->attr.cray_pointee)
2201         {
2202           /* TODO - make the cray pointee a pointer to a procedure,
2203              assign the pointer to it and use it for the call.  This
2204              will do for now!  */
2205           tmp = convert (build_pointer_type (TREE_TYPE (tmp)),
2206                          gfc_get_symbol_decl (sym->cp_pointer));
2207           tmp = gfc_evaluate_now (tmp, &se->pre);
2208         }
2209
2210       if (!POINTER_TYPE_P (TREE_TYPE (tmp)))
2211         {
2212           gcc_assert (TREE_CODE (tmp) == FUNCTION_DECL);
2213           tmp = gfc_build_addr_expr (NULL_TREE, tmp);
2214         }
2215     }
2216   se->expr = tmp;
2217 }
2218
2219
2220 /* Initialize MAPPING.  */
2221
2222 void
2223 gfc_init_interface_mapping (gfc_interface_mapping * mapping)
2224 {
2225   mapping->syms = NULL;
2226   mapping->charlens = NULL;
2227 }
2228
2229
2230 /* Free all memory held by MAPPING (but not MAPPING itself).  */
2231
2232 void
2233 gfc_free_interface_mapping (gfc_interface_mapping * mapping)
2234 {
2235   gfc_interface_sym_mapping *sym;
2236   gfc_interface_sym_mapping *nextsym;
2237   gfc_charlen *cl;
2238   gfc_charlen *nextcl;
2239
2240   for (sym = mapping->syms; sym; sym = nextsym)
2241     {
2242       nextsym = sym->next;
2243       sym->new_sym->n.sym->formal = NULL;
2244       gfc_free_symbol (sym->new_sym->n.sym);
2245       gfc_free_expr (sym->expr);
2246       free (sym->new_sym);
2247       free (sym);
2248     }
2249   for (cl = mapping->charlens; cl; cl = nextcl)
2250     {
2251       nextcl = cl->next;
2252       gfc_free_expr (cl->length);
2253       free (cl);
2254     }
2255 }
2256
2257
2258 /* Return a copy of gfc_charlen CL.  Add the returned structure to
2259    MAPPING so that it will be freed by gfc_free_interface_mapping.  */
2260
2261 static gfc_charlen *
2262 gfc_get_interface_mapping_charlen (gfc_interface_mapping * mapping,
2263                                    gfc_charlen * cl)
2264 {
2265   gfc_charlen *new_charlen;
2266
2267   new_charlen = gfc_get_charlen ();
2268   new_charlen->next = mapping->charlens;
2269   new_charlen->length = gfc_copy_expr (cl->length);
2270
2271   mapping->charlens = new_charlen;
2272   return new_charlen;
2273 }
2274
2275
2276 /* A subroutine of gfc_add_interface_mapping.  Return a descriptorless
2277    array variable that can be used as the actual argument for dummy
2278    argument SYM.  Add any initialization code to BLOCK.  PACKED is as
2279    for gfc_get_nodesc_array_type and DATA points to the first element
2280    in the passed array.  */
2281
2282 static tree
2283 gfc_get_interface_mapping_array (stmtblock_t * block, gfc_symbol * sym,
2284                                  gfc_packed packed, tree data)
2285 {
2286   tree type;
2287   tree var;
2288
2289   type = gfc_typenode_for_spec (&sym->ts);
2290   type = gfc_get_nodesc_array_type (type, sym->as, packed,
2291                                     !sym->attr.target && !sym->attr.pointer
2292                                     && !sym->attr.proc_pointer);
2293
2294   var = gfc_create_var (type, "ifm");
2295   gfc_add_modify (block, var, fold_convert (type, data));
2296
2297   return var;
2298 }
2299
2300
2301 /* A subroutine of gfc_add_interface_mapping.  Set the stride, upper bounds
2302    and offset of descriptorless array type TYPE given that it has the same
2303    size as DESC.  Add any set-up code to BLOCK.  */
2304
2305 static void
2306 gfc_set_interface_mapping_bounds (stmtblock_t * block, tree type, tree desc)
2307 {
2308   int n;
2309   tree dim;
2310   tree offset;
2311   tree tmp;
2312
2313   offset = gfc_index_zero_node;
2314   for (n = 0; n < GFC_TYPE_ARRAY_RANK (type); n++)
2315     {
2316       dim = gfc_rank_cst[n];
2317       GFC_TYPE_ARRAY_STRIDE (type, n) = gfc_conv_array_stride (desc, n);
2318       if (GFC_TYPE_ARRAY_LBOUND (type, n) == NULL_TREE)
2319         {
2320           GFC_TYPE_ARRAY_LBOUND (type, n)
2321                 = gfc_conv_descriptor_lbound_get (desc, dim);
2322           GFC_TYPE_ARRAY_UBOUND (type, n)
2323                 = gfc_conv_descriptor_ubound_get (desc, dim);
2324         }
2325       else if (GFC_TYPE_ARRAY_UBOUND (type, n) == NULL_TREE)
2326         {
2327           tmp = fold_build2_loc (input_location, MINUS_EXPR,
2328                                  gfc_array_index_type,
2329                                  gfc_conv_descriptor_ubound_get (desc, dim),
2330                                  gfc_conv_descriptor_lbound_get (desc, dim));
2331           tmp = fold_build2_loc (input_location, PLUS_EXPR,
2332                                  gfc_array_index_type,
2333                                  GFC_TYPE_ARRAY_LBOUND (type, n), tmp);
2334           tmp = gfc_evaluate_now (tmp, block);
2335           GFC_TYPE_ARRAY_UBOUND (type, n) = tmp;
2336         }
2337       tmp = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
2338                              GFC_TYPE_ARRAY_LBOUND (type, n),
2339                              GFC_TYPE_ARRAY_STRIDE (type, n));
2340       offset = fold_build2_loc (input_location, MINUS_EXPR,
2341                                 gfc_array_index_type, offset, tmp);
2342     }
2343   offset = gfc_evaluate_now (offset, block);
2344   GFC_TYPE_ARRAY_OFFSET (type) = offset;
2345 }
2346
2347
2348 /* Extend MAPPING so that it maps dummy argument SYM to the value stored
2349    in SE.  The caller may still use se->expr and se->string_length after
2350    calling this function.  */
2351
2352 void
2353 gfc_add_interface_mapping (gfc_interface_mapping * mapping,
2354                            gfc_symbol * sym, gfc_se * se,
2355                            gfc_expr *expr)
2356 {
2357   gfc_interface_sym_mapping *sm;
2358   tree desc;
2359   tree tmp;
2360   tree value;
2361   gfc_symbol *new_sym;
2362   gfc_symtree *root;
2363   gfc_symtree *new_symtree;
2364
2365   /* Create a new symbol to represent the actual argument.  */
2366   new_sym = gfc_new_symbol (sym->name, NULL);
2367   new_sym->ts = sym->ts;
2368   new_sym->as = gfc_copy_array_spec (sym->as);
2369   new_sym->attr.referenced = 1;
2370   new_sym->attr.dimension = sym->attr.dimension;
2371   new_sym->attr.contiguous = sym->attr.contiguous;
2372   new_sym->attr.codimension = sym->attr.codimension;
2373   new_sym->attr.pointer = sym->attr.pointer;
2374   new_sym->attr.allocatable = sym->attr.allocatable;
2375   new_sym->attr.flavor = sym->attr.flavor;
2376   new_sym->attr.function = sym->attr.function;
2377
2378   /* Ensure that the interface is available and that
2379      descriptors are passed for array actual arguments.  */
2380   if (sym->attr.flavor == FL_PROCEDURE)
2381     {
2382       new_sym->formal = expr->symtree->n.sym->formal;
2383       new_sym->attr.always_explicit
2384             = expr->symtree->n.sym->attr.always_explicit;
2385     }
2386
2387   /* Create a fake symtree for it.  */
2388   root = NULL;
2389   new_symtree = gfc_new_symtree (&root, sym->name);
2390   new_symtree->n.sym = new_sym;
2391   gcc_assert (new_symtree == root);
2392
2393   /* Create a dummy->actual mapping.  */
2394   sm = XCNEW (gfc_interface_sym_mapping);
2395   sm->next = mapping->syms;
2396   sm->old = sym;
2397   sm->new_sym = new_symtree;
2398   sm->expr = gfc_copy_expr (expr);
2399   mapping->syms = sm;
2400
2401   /* Stabilize the argument's value.  */
2402   if (!sym->attr.function && se)
2403     se->expr = gfc_evaluate_now (se->expr, &se->pre);
2404
2405   if (sym->ts.type == BT_CHARACTER)
2406     {
2407       /* Create a copy of the dummy argument's length.  */
2408       new_sym->ts.u.cl = gfc_get_interface_mapping_charlen (mapping, sym->ts.u.cl);
2409       sm->expr->ts.u.cl = new_sym->ts.u.cl;
2410
2411       /* If the length is specified as "*", record the length that
2412          the caller is passing.  We should use the callee's length
2413          in all other cases.  */
2414       if (!new_sym->ts.u.cl->length && se)
2415         {
2416           se->string_length = gfc_evaluate_now (se->string_length, &se->pre);
2417           new_sym->ts.u.cl->backend_decl = se->string_length;
2418         }
2419     }
2420
2421   if (!se)
2422     return;
2423
2424   /* Use the passed value as-is if the argument is a function.  */
2425   if (sym->attr.flavor == FL_PROCEDURE)
2426     value = se->expr;
2427
2428   /* If the argument is either a string or a pointer to a string,
2429      convert it to a boundless character type.  */
2430   else if (!sym->attr.dimension && sym->ts.type == BT_CHARACTER)
2431     {
2432       tmp = gfc_get_character_type_len (sym->ts.kind, NULL);
2433       tmp = build_pointer_type (tmp);
2434       if (sym->attr.pointer)
2435         value = build_fold_indirect_ref_loc (input_location,
2436                                          se->expr);
2437       else
2438         value = se->expr;
2439       value = fold_convert (tmp, value);
2440     }
2441
2442   /* If the argument is a scalar, a pointer to an array or an allocatable,
2443      dereference it.  */
2444   else if (!sym->attr.dimension || sym->attr.pointer || sym->attr.allocatable)
2445     value = build_fold_indirect_ref_loc (input_location,
2446                                      se->expr);
2447   
2448   /* For character(*), use the actual argument's descriptor.  */  
2449   else if (sym->ts.type == BT_CHARACTER && !new_sym->ts.u.cl->length)
2450     value = build_fold_indirect_ref_loc (input_location,
2451                                      se->expr);
2452
2453   /* If the argument is an array descriptor, use it to determine
2454      information about the actual argument's shape.  */
2455   else if (POINTER_TYPE_P (TREE_TYPE (se->expr))
2456            && GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (TREE_TYPE (se->expr))))
2457     {
2458       /* Get the actual argument's descriptor.  */
2459       desc = build_fold_indirect_ref_loc (input_location,
2460                                       se->expr);
2461
2462       /* Create the replacement variable.  */
2463       tmp = gfc_conv_descriptor_data_get (desc);
2464       value = gfc_get_interface_mapping_array (&se->pre, sym,
2465                                                PACKED_NO, tmp);
2466
2467       /* Use DESC to work out the upper bounds, strides and offset.  */
2468       gfc_set_interface_mapping_bounds (&se->pre, TREE_TYPE (value), desc);
2469     }
2470   else
2471     /* Otherwise we have a packed array.  */
2472     value = gfc_get_interface_mapping_array (&se->pre, sym,
2473                                              PACKED_FULL, se->expr);
2474
2475   new_sym->backend_decl = value;
2476 }
2477
2478
2479 /* Called once all dummy argument mappings have been added to MAPPING,
2480    but before the mapping is used to evaluate expressions.  Pre-evaluate
2481    the length of each argument, adding any initialization code to PRE and
2482    any finalization code to POST.  */
2483
2484 void
2485 gfc_finish_interface_mapping (gfc_interface_mapping * mapping,
2486                               stmtblock_t * pre, stmtblock_t * post)
2487 {
2488   gfc_interface_sym_mapping *sym;
2489   gfc_expr *expr;
2490   gfc_se se;
2491
2492   for (sym = mapping->syms; sym; sym = sym->next)
2493     if (sym->new_sym->n.sym->ts.type == BT_CHARACTER
2494         && !sym->new_sym->n.sym->ts.u.cl->backend_decl)
2495       {
2496         expr = sym->new_sym->n.sym->ts.u.cl->length;
2497         gfc_apply_interface_mapping_to_expr (mapping, expr);
2498         gfc_init_se (&se, NULL);
2499         gfc_conv_expr (&se, expr);
2500         se.expr = fold_convert (gfc_charlen_type_node, se.expr);
2501         se.expr = gfc_evaluate_now (se.expr, &se.pre);
2502         gfc_add_block_to_block (pre, &se.pre);
2503         gfc_add_block_to_block (post, &se.post);
2504
2505         sym->new_sym->n.sym->ts.u.cl->backend_decl = se.expr;
2506       }
2507 }
2508
2509
2510 /* Like gfc_apply_interface_mapping_to_expr, but applied to
2511    constructor C.  */
2512
2513 static void
2514 gfc_apply_interface_mapping_to_cons (gfc_interface_mapping * mapping,
2515                                      gfc_constructor_base base)
2516 {
2517   gfc_constructor *c;
2518   for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
2519     {
2520       gfc_apply_interface_mapping_to_expr (mapping, c->expr);
2521       if (c->iterator)
2522         {
2523           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->start);
2524           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->end);
2525           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->step);
2526         }
2527     }
2528 }
2529
2530
2531 /* Like gfc_apply_interface_mapping_to_expr, but applied to
2532    reference REF.  */
2533
2534 static void
2535 gfc_apply_interface_mapping_to_ref (gfc_interface_mapping * mapping,
2536                                     gfc_ref * ref)
2537 {
2538   int n;
2539
2540   for (; ref; ref = ref->next)
2541     switch (ref->type)
2542       {
2543       case REF_ARRAY:
2544         for (n = 0; n < ref->u.ar.dimen; n++)
2545           {
2546             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.start[n]);
2547             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.end[n]);
2548             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.stride[n]);
2549           }
2550         gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.offset);
2551         break;
2552
2553       case REF_COMPONENT:
2554         break;
2555
2556       case REF_SUBSTRING:
2557         gfc_apply_interface_mapping_to_expr (mapping, ref->u.ss.start);
2558         gfc_apply_interface_mapping_to_expr (mapping, ref->u.ss.end);
2559         break;
2560       }
2561 }
2562
2563
2564 /* Convert intrinsic function calls into result expressions.  */
2565
2566 static bool
2567 gfc_map_intrinsic_function (gfc_expr *expr, gfc_interface_mapping *mapping)
2568 {
2569   gfc_symbol *sym;
2570   gfc_expr *new_expr;
2571   gfc_expr *arg1;
2572   gfc_expr *arg2;
2573   int d, dup;
2574
2575   arg1 = expr->value.function.actual->expr;
2576   if (expr->value.function.actual->next)
2577     arg2 = expr->value.function.actual->next->expr;
2578   else
2579     arg2 = NULL;
2580
2581   sym = arg1->symtree->n.sym;
2582
2583   if (sym->attr.dummy)
2584     return false;
2585
2586   new_expr = NULL;
2587
2588   switch (expr->value.function.isym->id)
2589     {
2590     case GFC_ISYM_LEN:
2591       /* TODO figure out why this condition is necessary.  */
2592       if (sym->attr.function
2593           && (arg1->ts.u.cl->length == NULL
2594               || (arg1->ts.u.cl->length->expr_type != EXPR_CONSTANT
2595                   && arg1->ts.u.cl->length->expr_type != EXPR_VARIABLE)))
2596         return false;
2597
2598       new_expr = gfc_copy_expr (arg1->ts.u.cl->length);
2599       break;
2600
2601     case GFC_ISYM_SIZE:
2602       if (!sym->as || sym->as->rank == 0)
2603         return false;
2604
2605       if (arg2 && arg2->expr_type == EXPR_CONSTANT)
2606         {
2607           dup = mpz_get_si (arg2->value.integer);
2608           d = dup - 1;
2609         }
2610       else
2611         {
2612           dup = sym->as->rank;
2613           d = 0;
2614         }
2615
2616       for (; d < dup; d++)
2617         {
2618           gfc_expr *tmp;
2619
2620           if (!sym->as->upper[d] || !sym->as->lower[d])
2621             {
2622               gfc_free_expr (new_expr);
2623               return false;
2624             }
2625
2626           tmp = gfc_add (gfc_copy_expr (sym->as->upper[d]),
2627                                         gfc_get_int_expr (gfc_default_integer_kind,
2628                                                           NULL, 1));
2629           tmp = gfc_subtract (tmp, gfc_copy_expr (sym->as->lower[d]));
2630           if (new_expr)
2631             new_expr = gfc_multiply (new_expr, tmp);
2632           else
2633             new_expr = tmp;
2634         }
2635       break;
2636
2637     case GFC_ISYM_LBOUND:
2638     case GFC_ISYM_UBOUND:
2639         /* TODO These implementations of lbound and ubound do not limit if
2640            the size < 0, according to F95's 13.14.53 and 13.14.113.  */
2641
2642       if (!sym->as || sym->as->rank == 0)
2643         return false;
2644
2645       if (arg2 && arg2->expr_type == EXPR_CONSTANT)
2646         d = mpz_get_si (arg2->value.integer) - 1;
2647       else
2648         /* TODO: If the need arises, this could produce an array of
2649            ubound/lbounds.  */
2650         gcc_unreachable ();
2651
2652       if (expr->value.function.isym->id == GFC_ISYM_LBOUND)
2653         {
2654           if (sym->as->lower[d])
2655             new_expr = gfc_copy_expr (sym->as->lower[d]);
2656         }
2657       else
2658         {
2659           if (sym->as->upper[d])
2660             new_expr = gfc_copy_expr (sym->as->upper[d]);
2661         }
2662       break;
2663
2664     default:
2665       break;
2666     }
2667
2668   gfc_apply_interface_mapping_to_expr (mapping, new_expr);
2669   if (!new_expr)
2670     return false;
2671
2672   gfc_replace_expr (expr, new_expr);
2673   return true;
2674 }
2675
2676
2677 static void
2678 gfc_map_fcn_formal_to_actual (gfc_expr *expr, gfc_expr *map_expr,
2679                               gfc_interface_mapping * mapping)
2680 {
2681   gfc_formal_arglist *f;
2682   gfc_actual_arglist *actual;
2683
2684   actual = expr->value.function.actual;
2685   f = map_expr->symtree->n.sym->formal;
2686
2687   for (; f && actual; f = f->next, actual = actual->next)
2688     {
2689       if (!actual->expr)
2690         continue;
2691
2692       gfc_add_interface_mapping (mapping, f->sym, NULL, actual->expr);
2693     }
2694
2695   if (map_expr->symtree->n.sym->attr.dimension)
2696     {
2697       int d;
2698       gfc_array_spec *as;
2699
2700       as = gfc_copy_array_spec (map_expr->symtree->n.sym->as);
2701
2702       for (d = 0; d < as->rank; d++)
2703         {
2704           gfc_apply_interface_mapping_to_expr (mapping, as->lower[d]);
2705           gfc_apply_interface_mapping_to_expr (mapping, as->upper[d]);
2706         }
2707
2708       expr->value.function.esym->as = as;
2709     }
2710
2711   if (map_expr->symtree->n.sym->ts.type == BT_CHARACTER)
2712     {
2713       expr->value.function.esym->ts.u.cl->length
2714         = gfc_copy_expr (map_expr->symtree->n.sym->ts.u.cl->length);
2715
2716       gfc_apply_interface_mapping_to_expr (mapping,
2717                         expr->value.function.esym->ts.u.cl->length);
2718     }
2719 }
2720
2721
2722 /* EXPR is a copy of an expression that appeared in the interface
2723    associated with MAPPING.  Walk it recursively looking for references to
2724    dummy arguments that MAPPING maps to actual arguments.  Replace each such
2725    reference with a reference to the associated actual argument.  */
2726
2727 static void
2728 gfc_apply_interface_mapping_to_expr (gfc_interface_mapping * mapping,
2729                                      gfc_expr * expr)
2730 {
2731   gfc_interface_sym_mapping *sym;
2732   gfc_actual_arglist *actual;
2733
2734   if (!expr)
2735     return;
2736
2737   /* Copying an expression does not copy its length, so do that here.  */
2738   if (expr->ts.type == BT_CHARACTER && expr->ts.u.cl)
2739     {
2740       expr->ts.u.cl = gfc_get_interface_mapping_charlen (mapping, expr->ts.u.cl);
2741       gfc_apply_interface_mapping_to_expr (mapping, expr->ts.u.cl->length);
2742     }
2743
2744   /* Apply the mapping to any references.  */
2745   gfc_apply_interface_mapping_to_ref (mapping, expr->ref);
2746
2747   /* ...and to the expression's symbol, if it has one.  */
2748   /* TODO Find out why the condition on expr->symtree had to be moved into
2749      the loop rather than being outside it, as originally.  */
2750   for (sym = mapping->syms; sym; sym = sym->next)
2751     if (expr->symtree && sym->old == expr->symtree->n.sym)
2752       {
2753         if (sym->new_sym->n.sym->backend_decl)
2754           expr->symtree = sym->new_sym;
2755         else if (sym->expr)
2756           gfc_replace_expr (expr, gfc_copy_expr (sym->expr));
2757         /* Replace base type for polymorphic arguments.  */
2758         if (expr->ref && expr->ref->type == REF_COMPONENT
2759             && sym->expr && sym->expr->ts.type == BT_CLASS)
2760           expr->ref->u.c.sym = sym->expr->ts.u.derived;
2761       }
2762
2763       /* ...and to subexpressions in expr->value.  */
2764   switch (expr->expr_type)
2765     {
2766     case EXPR_VARIABLE:
2767     case EXPR_CONSTANT:
2768     case EXPR_NULL:
2769     case EXPR_SUBSTRING:
2770       break;
2771
2772     case EXPR_OP:
2773       gfc_apply_interface_mapping_to_expr (mapping, expr->value.op.op1);
2774       gfc_apply_interface_mapping_to_expr (mapping, expr->value.op.op2);
2775       break;
2776
2777     case EXPR_FUNCTION:
2778       for (actual = expr->value.function.actual; actual; actual = actual->next)
2779         gfc_apply_interface_mapping_to_expr (mapping, actual->expr);
2780
2781       if (expr->value.function.esym == NULL
2782             && expr->value.function.isym != NULL
2783             && expr->value.function.actual->expr->symtree
2784             && gfc_map_intrinsic_function (expr, mapping))
2785         break;
2786
2787       for (sym = mapping->syms; sym; sym = sym->next)
2788         if (sym->old == expr->value.function.esym)
2789           {
2790             expr->value.function.esym = sym->new_sym->n.sym;
2791             gfc_map_fcn_formal_to_actual (expr, sym->expr, mapping);
2792             expr->value.function.esym->result = sym->new_sym->n.sym;
2793           }
2794       break;
2795
2796     case EXPR_ARRAY:
2797     case EXPR_STRUCTURE:
2798       gfc_apply_interface_mapping_to_cons (mapping, expr->value.constructor);
2799       break;
2800
2801     case EXPR_COMPCALL:
2802     case EXPR_PPC:
2803       gcc_unreachable ();
2804       break;
2805     }
2806
2807   return;
2808 }
2809
2810
2811 /* Evaluate interface expression EXPR using MAPPING.  Store the result
2812    in SE.  */
2813
2814 void
2815 gfc_apply_interface_mapping (gfc_interface_mapping * mapping,
2816                              gfc_se * se, gfc_expr * expr)
2817 {
2818   expr = gfc_copy_expr (expr);
2819   gfc_apply_interface_mapping_to_expr (mapping, expr);
2820   gfc_conv_expr (se, expr);
2821   se->expr = gfc_evaluate_now (se->expr, &se->pre);
2822   gfc_free_expr (expr);
2823 }
2824
2825
2826 /* Returns a reference to a temporary array into which a component of
2827    an actual argument derived type array is copied and then returned
2828    after the function call.  */
2829 void
2830 gfc_conv_subref_array_arg (gfc_se * parmse, gfc_expr * expr, int g77,
2831                            sym_intent intent, bool formal_ptr)
2832 {
2833   gfc_se lse;
2834   gfc_se rse;
2835   gfc_ss *lss;
2836   gfc_ss *rss;
2837   gfc_loopinfo loop;
2838   gfc_loopinfo loop2;
2839   gfc_array_info *info;
2840   tree offset;
2841   tree tmp_index;
2842   tree tmp;
2843   tree base_type;
2844   tree size;
2845   stmtblock_t body;
2846   int n;
2847   int dimen;
2848
2849   gcc_assert (expr->expr_type == EXPR_VARIABLE);
2850
2851   gfc_init_se (&lse, NULL);
2852   gfc_init_se (&rse, NULL);
2853
2854   /* Walk the argument expression.  */
2855   rss = gfc_walk_expr (expr);
2856
2857   gcc_assert (rss != gfc_ss_terminator);
2858  
2859   /* Initialize the scalarizer.  */
2860   gfc_init_loopinfo (&loop);
2861   gfc_add_ss_to_loop (&loop, rss);
2862
2863   /* Calculate the bounds of the scalarization.  */
2864   gfc_conv_ss_startstride (&loop);
2865
2866   /* Build an ss for the temporary.  */
2867   if (expr->ts.type == BT_CHARACTER && !expr->ts.u.cl->backend_decl)
2868     gfc_conv_string_length (expr->ts.u.cl, expr, &parmse->pre);
2869
2870   base_type = gfc_typenode_for_spec (&expr->ts);
2871   if (GFC_ARRAY_TYPE_P (base_type)
2872                 || GFC_DESCRIPTOR_TYPE_P (base_type))
2873     base_type = gfc_get_element_type (base_type);
2874
2875   if (expr->ts.type == BT_CLASS)
2876     base_type = gfc_typenode_for_spec (&CLASS_DATA (expr)->ts);
2877
2878   loop.temp_ss = gfc_get_temp_ss (base_type, ((expr->ts.type == BT_CHARACTER)
2879                                               ? expr->ts.u.cl->backend_decl
2880                                               : NULL),
2881                                   loop.dimen);
2882
2883   parmse->string_length = loop.temp_ss->info->string_length;
2884
2885   /* Associate the SS with the loop.  */
2886   gfc_add_ss_to_loop (&loop, loop.temp_ss);
2887
2888   /* Setup the scalarizing loops.  */
2889   gfc_conv_loop_setup (&loop, &expr->where);
2890
2891   /* Pass the temporary descriptor back to the caller.  */
2892   info = &loop.temp_ss->info->data.array;
2893   parmse->expr = info->descriptor;
2894
2895   /* Setup the gfc_se structures.  */
2896   gfc_copy_loopinfo_to_se (&lse, &loop);
2897   gfc_copy_loopinfo_to_se (&rse, &loop);
2898
2899   rse.ss = rss;
2900   lse.ss = loop.temp_ss;
2901   gfc_mark_ss_chain_used (rss, 1);
2902   gfc_mark_ss_chain_used (loop.temp_ss, 1);
2903
2904   /* Start the scalarized loop body.  */
2905   gfc_start_scalarized_body (&loop, &body);
2906
2907   /* Translate the expression.  */
2908   gfc_conv_expr (&rse, expr);
2909
2910   gfc_conv_tmp_array_ref (&lse);
2911
2912   if (intent != INTENT_OUT)
2913     {
2914       tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, true, false, true);
2915       gfc_add_expr_to_block (&body, tmp);
2916       gcc_assert (rse.ss == gfc_ss_terminator);
2917       gfc_trans_scalarizing_loops (&loop, &body);
2918     }
2919   else
2920     {
2921       /* Make sure that the temporary declaration survives by merging
2922        all the loop declarations into the current context.  */
2923       for (n = 0; n < loop.dimen; n++)
2924         {
2925           gfc_merge_block_scope (&body);
2926           body = loop.code[loop.order[n]];
2927         }
2928       gfc_merge_block_scope (&body);
2929     }
2930
2931   /* Add the post block after the second loop, so that any
2932      freeing of allocated memory is done at the right time.  */
2933   gfc_add_block_to_block (&parmse->pre, &loop.pre);
2934
2935   /**********Copy the temporary back again.*********/
2936
2937   gfc_init_se (&lse, NULL);
2938   gfc_init_se (&rse, NULL);
2939
2940   /* Walk the argument expression.  */
2941   lss = gfc_walk_expr (expr);
2942   rse.ss = loop.temp_ss;
2943   lse.ss = lss;
2944
2945   /* Initialize the scalarizer.  */
2946   gfc_init_loopinfo (&loop2);
2947   gfc_add_ss_to_loop (&loop2, lss);
2948
2949   /* Calculate the bounds of the scalarization.  */
2950   gfc_conv_ss_startstride (&loop2);
2951
2952   /* Setup the scalarizing loops.  */
2953   gfc_conv_loop_setup (&loop2, &expr->where);
2954
2955   gfc_copy_loopinfo_to_se (&lse, &loop2);
2956   gfc_copy_loopinfo_to_se (&rse, &loop2);
2957
2958   gfc_mark_ss_chain_used (lss, 1);
2959   gfc_mark_ss_chain_used (loop.temp_ss, 1);
2960
2961   /* Declare the variable to hold the temporary offset and start the
2962      scalarized loop body.  */
2963   offset = gfc_create_var (gfc_array_index_type, NULL);
2964   gfc_start_scalarized_body (&loop2, &body);
2965
2966   /* Build the offsets for the temporary from the loop variables.  The
2967      temporary array has lbounds of zero and strides of one in all
2968      dimensions, so this is very simple.  The offset is only computed
2969      outside the innermost loop, so the overall transfer could be
2970      optimized further.  */
2971   info = &rse.ss->info->data.array;
2972   dimen = rse.ss->dimen;
2973
2974   tmp_index = gfc_index_zero_node;
2975   for (n = dimen - 1; n > 0; n--)
2976     {
2977       tree tmp_str;
2978       tmp = rse.loop->loopvar[n];
2979       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
2980                              tmp, rse.loop->from[n]);
2981       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
2982                              tmp, tmp_index);
2983
2984       tmp_str = fold_build2_loc (input_location, MINUS_EXPR,
2985                                  gfc_array_index_type,
2986                                  rse.loop->to[n-1], rse.loop->from[n-1]);
2987       tmp_str = fold_build2_loc (input_location, PLUS_EXPR,
2988                                  gfc_array_index_type,
2989                                  tmp_str, gfc_index_one_node);
2990
2991       tmp_index = fold_build2_loc (input_location, MULT_EXPR,
2992                                    gfc_array_index_type, tmp, tmp_str);
2993     }
2994
2995   tmp_index = fold_build2_loc (input_location, MINUS_EXPR,
2996                                gfc_array_index_type,
2997                                tmp_index, rse.loop->from[0]);
2998   gfc_add_modify (&rse.loop->code[0], offset, tmp_index);
2999
3000   tmp_index = fold_build2_loc (input_location, PLUS_EXPR,
3001                                gfc_array_index_type,
3002                                rse.loop->loopvar[0], offset);
3003
3004   /* Now use the offset for the reference.  */
3005   tmp = build_fold_indirect_ref_loc (input_location,
3006                                  info->data);
3007   rse.expr = gfc_build_array_ref (tmp, tmp_index, NULL);
3008
3009   if (expr->ts.type == BT_CHARACTER)
3010     rse.string_length = expr->ts.u.cl->backend_decl;
3011
3012   gfc_conv_expr (&lse, expr);
3013
3014   gcc_assert (lse.ss == gfc_ss_terminator);
3015
3016   tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, false, false, true);
3017   gfc_add_expr_to_block (&body, tmp);
3018   
3019   /* Generate the copying loops.  */
3020   gfc_trans_scalarizing_loops (&loop2, &body);
3021
3022   /* Wrap the whole thing up by adding the second loop to the post-block
3023      and following it by the post-block of the first loop.  In this way,
3024      if the temporary needs freeing, it is done after use!  */
3025   if (intent != INTENT_IN)
3026     {
3027       gfc_add_block_to_block (&parmse->post, &loop2.pre);
3028       gfc_add_block_to_block (&parmse->post, &loop2.post);
3029     }
3030
3031   gfc_add_block_to_block (&parmse->post, &loop.post);
3032
3033   gfc_cleanup_loop (&loop);
3034   gfc_cleanup_loop (&loop2);
3035
3036   /* Pass the string length to the argument expression.  */
3037   if (expr->ts.type == BT_CHARACTER)
3038     parmse->string_length = expr->ts.u.cl->backend_decl;
3039
3040   /* Determine the offset for pointer formal arguments and set the
3041      lbounds to one.  */
3042   if (formal_ptr)
3043     {
3044       size = gfc_index_one_node;
3045       offset = gfc_index_zero_node;  
3046       for (n = 0; n < dimen; n++)
3047         {
3048           tmp = gfc_conv_descriptor_ubound_get (parmse->expr,
3049                                                 gfc_rank_cst[n]);
3050           tmp = fold_build2_loc (input_location, PLUS_EXPR,
3051                                  gfc_array_index_type, tmp,
3052                                  gfc_index_one_node);
3053           gfc_conv_descriptor_ubound_set (&parmse->pre,
3054                                           parmse->expr,
3055                                           gfc_rank_cst[n],
3056                                           tmp);
3057           gfc_conv_descriptor_lbound_set (&parmse->pre,
3058                                           parmse->expr,
3059                                           gfc_rank_cst[n],
3060                                           gfc_index_one_node);
3061           size = gfc_evaluate_now (size, &parmse->pre);
3062           offset = fold_build2_loc (input_location, MINUS_EXPR,
3063                                     gfc_array_index_type,
3064                                     offset, size);
3065           offset = gfc_evaluate_now (offset, &parmse->pre);
3066           tmp = fold_build2_loc (input_location, MINUS_EXPR,
3067                                  gfc_array_index_type,
3068                                  rse.loop->to[n], rse.loop->from[n]);
3069           tmp = fold_build2_loc (input_location, PLUS_EXPR,
3070                                  gfc_array_index_type,
3071                                  tmp, gfc_index_one_node);
3072           size = fold_build2_loc (input_location, MULT_EXPR,
3073                                   gfc_array_index_type, size, tmp);
3074         }
3075
3076       gfc_conv_descriptor_offset_set (&parmse->pre, parmse->expr,
3077                                       offset);
3078     }
3079
3080   /* We want either the address for the data or the address of the descriptor,
3081      depending on the mode of passing array arguments.  */
3082   if (g77)
3083     parmse->expr = gfc_conv_descriptor_data_get (parmse->expr);
3084   else
3085     parmse->expr = gfc_build_addr_expr (NULL_TREE, parmse->expr);
3086
3087   return;
3088 }
3089
3090
3091 /* Generate the code for argument list functions.  */
3092
3093 static void
3094 conv_arglist_function (gfc_se *se, gfc_expr *expr, const char *name)
3095 {
3096   /* Pass by value for g77 %VAL(arg), pass the address
3097      indirectly for %LOC, else by reference.  Thus %REF
3098      is a "do-nothing" and %LOC is the same as an F95
3099      pointer.  */
3100   if (strncmp (name, "%VAL", 4) == 0)
3101     gfc_conv_expr (se, expr);
3102   else if (strncmp (name, "%LOC", 4) == 0)
3103     {
3104       gfc_conv_expr_reference (se, expr);
3105       se->expr = gfc_build_addr_expr (NULL, se->expr);
3106     }
3107   else if (strncmp (name, "%REF", 4) == 0)
3108     gfc_conv_expr_reference (se, expr);
3109   else
3110     gfc_error ("Unknown argument list function at %L", &expr->where);
3111 }
3112
3113
3114 /* The following routine generates code for the intrinsic
3115    procedures from the ISO_C_BINDING module:
3116     * C_LOC           (function)
3117     * C_FUNLOC        (function)
3118     * C_F_POINTER     (subroutine)
3119     * C_F_PROCPOINTER (subroutine)
3120     * C_ASSOCIATED    (function)
3121    One exception which is not handled here is C_F_POINTER with non-scalar
3122    arguments. Returns 1 if the call was replaced by inline code (else: 0).  */
3123
3124 static int
3125 conv_isocbinding_procedure (gfc_se * se, gfc_symbol * sym,
3126                             gfc_actual_arglist * arg)
3127 {
3128   gfc_symbol *fsym;
3129   gfc_ss *argss;
3130     
3131   if (sym->intmod_sym_id == ISOCBINDING_LOC)
3132     {
3133       if (arg->expr->rank == 0)
3134         gfc_conv_expr_reference (se, arg->expr);
3135       else
3136         {
3137           int f;
3138           /* This is really the actual arg because no formal arglist is
3139              created for C_LOC.  */
3140           fsym = arg->expr->symtree->n.sym;
3141
3142           /* We should want it to do g77 calling convention.  */
3143           f = (fsym != NULL)
3144             && !(fsym->attr.pointer || fsym->attr.allocatable)
3145             && fsym->as->type != AS_ASSUMED_SHAPE;
3146           f = f || !sym->attr.always_explicit;
3147       
3148           argss = gfc_walk_expr (arg->expr);
3149           gfc_conv_array_parameter (se, arg->expr, argss, f,
3150                                     NULL, NULL, NULL);
3151         }
3152
3153       /* TODO -- the following two lines shouldn't be necessary, but if
3154          they're removed, a bug is exposed later in the code path.
3155          This workaround was thus introduced, but will have to be
3156          removed; please see PR 35150 for details about the issue.  */
3157       se->expr = convert (pvoid_type_node, se->expr);
3158       se->expr = gfc_evaluate_now (se->expr, &se->pre);
3159
3160       return 1;
3161     }
3162   else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
3163     {
3164       arg->expr->ts.type = sym->ts.u.derived->ts.type;
3165       arg->expr->ts.f90_type = sym->ts.u.derived->ts.f90_type;
3166       arg->expr->ts.kind = sym->ts.u.derived->ts.kind;
3167       gfc_conv_expr_reference (se, arg->expr);
3168   
3169       return 1;
3170     }
3171   else if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER
3172             && arg->next->expr->rank == 0)
3173            || sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER)
3174     {
3175       /* Convert c_f_pointer if fptr is a scalar
3176          and convert c_f_procpointer.  */
3177       gfc_se cptrse;
3178       gfc_se fptrse;
3179
3180       gfc_init_se (&cptrse, NULL);
3181       gfc_conv_expr (&cptrse, arg->expr);
3182       gfc_add_block_to_block (&se->pre, &cptrse.pre);
3183       gfc_add_block_to_block (&se->post, &cptrse.post);
3184
3185       gfc_init_se (&fptrse, NULL);
3186       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER
3187           || gfc_is_proc_ptr_comp (arg->next->expr, NULL))
3188         fptrse.want_pointer = 1;
3189
3190       gfc_conv_expr (&fptrse, arg->next->expr);
3191       gfc_add_block_to_block (&se->pre, &fptrse.pre);
3192       gfc_add_block_to_block (&se->post, &fptrse.post);
3193       
3194       if (arg->next->expr->symtree->n.sym->attr.proc_pointer
3195           && arg->next->expr->symtree->n.sym->attr.dummy)
3196         fptrse.expr = build_fold_indirect_ref_loc (input_location,
3197                                                    fptrse.expr);
3198       
3199       se->expr = fold_build2_loc (input_location, MODIFY_EXPR,
3200                                   TREE_TYPE (fptrse.expr),
3201                                   fptrse.expr,
3202                                   fold_convert (TREE_TYPE (fptrse.expr),
3203                                                 cptrse.expr));
3204
3205       return 1;
3206     }
3207   else if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
3208     {
3209       gfc_se arg1se;
3210       gfc_se arg2se;
3211
3212       /* Build the addr_expr for the first argument.  The argument is
3213          already an *address* so we don't need to set want_pointer in
3214          the gfc_se.  */
3215       gfc_init_se (&arg1se, NULL);
3216       gfc_conv_expr (&arg1se, arg->expr);
3217       gfc_add_block_to_block (&se->pre, &arg1se.pre);
3218       gfc_add_block_to_block (&se->post, &arg1se.post);
3219
3220       /* See if we were given two arguments.  */
3221       if (arg->next == NULL)
3222         /* Only given one arg so generate a null and do a
3223            not-equal comparison against the first arg.  */
3224         se->expr = fold_build2_loc (input_location, NE_EXPR, boolean_type_node,
3225                                     arg1se.expr,
3226                                     fold_convert (TREE_TYPE (arg1se.expr),
3227                                                   null_pointer_node));
3228       else
3229         {
3230           tree eq_expr;
3231           tree not_null_expr;
3232           
3233           /* Given two arguments so build the arg2se from second arg.  */
3234           gfc_init_se (&arg2se, NULL);
3235           gfc_conv_expr (&arg2se, arg->next->expr);
3236           gfc_add_block_to_block (&se->pre, &arg2se.pre);
3237           gfc_add_block_to_block (&se->post, &arg2se.post);
3238
3239           /* Generate test to compare that the two args are equal.  */
3240           eq_expr = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
3241                                      arg1se.expr, arg2se.expr);
3242           /* Generate test to ensure that the first arg is not null.  */
3243           not_null_expr = fold_build2_loc (input_location, NE_EXPR,
3244                                            boolean_type_node,
3245                                            arg1se.expr, null_pointer_node);
3246
3247           /* Finally, the generated test must check that both arg1 is not
3248              NULL and that it is equal to the second arg.  */
3249           se->expr = fold_build2_loc (input_location, TRUTH_AND_EXPR,
3250                                       boolean_type_node,
3251                                       not_null_expr, eq_expr);
3252         }
3253
3254       return 1;
3255     }
3256     
3257   /* Nothing was done.  */
3258   return 0;
3259 }
3260
3261
3262 /* Generate code for a procedure call.  Note can return se->post != NULL.
3263    If se->direct_byref is set then se->expr contains the return parameter.
3264    Return nonzero, if the call has alternate specifiers.
3265    'expr' is only needed for procedure pointer components.  */
3266
3267 int
3268 gfc_conv_procedure_call (gfc_se * se, gfc_symbol * sym,
3269                          gfc_actual_arglist * args, gfc_expr * expr,
3270                          VEC(tree,gc) *append_args)
3271 {
3272   gfc_interface_mapping mapping;
3273   VEC(tree,gc) *arglist;
3274   VEC(tree,gc) *retargs;
3275   tree tmp;
3276   tree fntype;
3277   gfc_se parmse;
3278   gfc_ss *argss;
3279   gfc_array_info *info;
3280   int byref;
3281   int parm_kind;
3282   tree type;
3283   tree var;
3284   tree len;
3285   tree base_object;
3286   VEC(tree,gc) *stringargs;
3287   tree result = NULL;
3288   gfc_formal_arglist *formal;
3289   gfc_actual_arglist *arg;
3290   int has_alternate_specifier = 0;
3291   bool need_interface_mapping;
3292   bool callee_alloc;
3293   gfc_typespec ts;
3294   gfc_charlen cl;
3295   gfc_expr *e;
3296   gfc_symbol *fsym;
3297   stmtblock_t post;
3298   enum {MISSING = 0, ELEMENTAL, SCALAR, SCALAR_POINTER, ARRAY};
3299   gfc_component *comp = NULL;
3300   int arglen;
3301
3302   arglist = NULL;
3303   retargs = NULL;
3304   stringargs = NULL;
3305   var = NULL_TREE;
3306   len = NULL_TREE;
3307   gfc_clear_ts (&ts);
3308
3309   if (sym->from_intmod == INTMOD_ISO_C_BINDING
3310       && conv_isocbinding_procedure (se, sym, args))
3311     return 0;
3312
3313   gfc_is_proc_ptr_comp (expr, &comp);
3314
3315   if (se->ss != NULL)
3316     {
3317       if (!sym->attr.elemental && !(comp && comp->attr.elemental))
3318         {
3319           gcc_assert (se->ss->info->type == GFC_SS_FUNCTION);
3320           if (se->ss->info->useflags)
3321             {
3322               gcc_assert ((!comp && gfc_return_by_reference (sym)
3323                            && sym->result->attr.dimension)
3324                           || (comp && comp->attr.dimension));
3325               gcc_assert (se->loop != NULL);
3326
3327               /* Access the previously obtained result.  */
3328               gfc_conv_tmp_array_ref (se);
3329               return 0;
3330             }
3331         }
3332       info = &se->ss->info->data.array;
3333     }
3334   else
3335     info = NULL;
3336
3337   gfc_init_block (&post);
3338   gfc_init_interface_mapping (&mapping);
3339   if (!comp)
3340     {
3341       formal = sym->formal;
3342       need_interface_mapping = sym->attr.dimension ||
3343                                (sym->ts.type == BT_CHARACTER
3344                                 && sym->ts.u.cl->length
3345                                 && sym->ts.u.cl->length->expr_type
3346                                    != EXPR_CONSTANT);
3347     }
3348   else
3349     {
3350       formal = comp->formal;
3351       need_interface_mapping = comp->attr.dimension ||
3352                                (comp->ts.type == BT_CHARACTER
3353                                 && comp->ts.u.cl->length
3354                                 && comp->ts.u.cl->length->expr_type
3355                                    != EXPR_CONSTANT);
3356     }
3357
3358   base_object = NULL_TREE;
3359
3360   /* Evaluate the arguments.  */
3361   for (arg = args; arg != NULL;
3362        arg = arg->next, formal = formal ? formal->next : NULL)
3363     {
3364       e = arg->expr;
3365       fsym = formal ? formal->sym : NULL;
3366       parm_kind = MISSING;
3367
3368       /* Class array expressions are sometimes coming completely unadorned
3369          with either arrayspec or _data component.  Correct that here.
3370          OOP-TODO: Move this to the frontend.  */
3371       if (e && e->expr_type == EXPR_VARIABLE
3372             && !e->ref
3373             && e->ts.type == BT_CLASS
3374             && CLASS_DATA (e)->attr.dimension)
3375         {
3376           gfc_typespec temp_ts = e->ts;
3377           gfc_add_class_array_ref (e);
3378           e->ts = temp_ts;
3379         }
3380
3381       if (e == NULL)
3382         {
3383           if (se->ignore_optional)
3384             {
3385               /* Some intrinsics have already been resolved to the correct
3386                  parameters.  */
3387               continue;
3388             }
3389           else if (arg->label)
3390             {
3391               has_alternate_specifier = 1;
3392               continue;
3393             }
3394           else
3395             {
3396               /* Pass a NULL pointer for an absent arg.  */
3397               gfc_init_se (&parmse, NULL);
3398               parmse.expr = null_pointer_node;
3399               if (arg->missing_arg_type == BT_CHARACTER)
3400                 parmse.string_length = build_int_cst (gfc_charlen_type_node, 0);
3401             }
3402         }
3403       else if (arg->expr->expr_type == EXPR_NULL && fsym && !fsym->attr.pointer)
3404         {
3405           /* Pass a NULL pointer to denote an absent arg.  */
3406           gcc_assert (fsym->attr.optional && !fsym->attr.allocatable);
3407           gfc_init_se (&parmse, NULL);
3408           parmse.expr = null_pointer_node;
3409           if (arg->missing_arg_type == BT_CHARACTER)
3410             parmse.string_length = build_int_cst (gfc_charlen_type_node, 0);
3411         }
3412       else if (fsym && fsym->ts.type == BT_CLASS
3413                  && e->ts.type == BT_DERIVED)
3414         {
3415           /* The derived type needs to be converted to a temporary
3416              CLASS object.  */
3417           gfc_init_se (&parmse, se);
3418           gfc_conv_derived_to_class (&parmse, e, fsym->ts);
3419         }
3420       else if (se->ss && se->ss->info->useflags)
3421         {
3422           /* An elemental function inside a scalarized loop.  */
3423           gfc_init_se (&parmse, se);
3424           parm_kind = ELEMENTAL;
3425
3426           if (se->ss->dimen > 0
3427               && se->ss->info->data.array.ref == NULL)
3428             {
3429               gfc_conv_tmp_array_ref (&parmse);
3430               if (e->ts.type == BT_CHARACTER)
3431                 gfc_conv_string_parameter (&parmse);
3432               else
3433                 parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
3434             }
3435           else
3436             gfc_conv_expr_reference (&parmse, e);
3437
3438           /* The scalarizer does not repackage the reference to a class
3439              array - instead it returns a pointer to the data element.  */
3440           if (fsym && fsym->ts.type == BT_CLASS && e->ts.type == BT_CLASS)
3441             gfc_conv_class_to_class (&parmse, e, fsym->ts, true);
3442         }
3443       else
3444         {
3445           /* A scalar or transformational function.  */
3446           gfc_init_se (&parmse, NULL);
3447           argss = gfc_walk_expr (e);
3448
3449           if (argss == gfc_ss_terminator)
3450             {
3451               if (e->expr_type == EXPR_VARIABLE
3452                     && e->symtree->n.sym->attr.cray_pointee
3453                     && fsym && fsym->attr.flavor == FL_PROCEDURE)
3454                 {
3455                     /* The Cray pointer needs to be converted to a pointer to
3456                        a type given by the expression.  */
3457                     gfc_conv_expr (&parmse, e);
3458                     type = build_pointer_type (TREE_TYPE (parmse.expr));
3459                     tmp = gfc_get_symbol_decl (e->symtree->n.sym->cp_pointer);
3460                     parmse.expr = convert (type, tmp);
3461                 }
3462               else if (fsym && fsym->attr.value)
3463                 {
3464                   if (fsym->ts.type == BT_CHARACTER
3465                       && fsym->ts.is_c_interop
3466                       && fsym->ns->proc_name != NULL
3467                       && fsym->ns->proc_name->attr.is_bind_c)
3468                     {
3469                       parmse.expr = NULL;
3470                       gfc_conv_scalar_char_value (fsym, &parmse, &e);
3471                       if (parmse.expr == NULL)
3472                         gfc_conv_expr (&parmse, e);
3473                     }
3474                   else
3475                     gfc_conv_expr (&parmse, e);
3476                 }
3477               else if (arg->name && arg->name[0] == '%')
3478                 /* Argument list functions %VAL, %LOC and %REF are signalled
3479                    through arg->name.  */
3480                 conv_arglist_function (&parmse, arg->expr, arg->name);
3481               else if ((e->expr_type == EXPR_FUNCTION)
3482                         && ((e->value.function.esym
3483                              && e->value.function.esym->result->attr.pointer)
3484                             || (!e->value.function.esym
3485                                 && e->symtree->n.sym->attr.pointer))
3486                         && fsym && fsym->attr.target)
3487                 {
3488                   gfc_conv_expr (&parmse, e);
3489                   parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
3490                 }
3491               else if (e->expr_type == EXPR_FUNCTION
3492                        && e->symtree->n.sym->result
3493                        && e->symtree->n.sym->result != e->symtree->n.sym
3494                        && e->symtree->n.sym->result->attr.proc_pointer)
3495                 {
3496                   /* Functions returning procedure pointers.  */
3497                   gfc_conv_expr (&parmse, e);
3498                   if (fsym && fsym->attr.proc_pointer)
3499                     parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
3500                 }
3501               else
3502                 {
3503                   gfc_conv_expr_reference (&parmse, e);
3504
3505                   /* Catch base objects that are not variables.  */
3506                   if (e->ts.type == BT_CLASS
3507                         && e->expr_type != EXPR_VARIABLE
3508                         && expr && e == expr->base_expr)
3509                     base_object = build_fold_indirect_ref_loc (input_location,
3510                                                                parmse.expr);
3511
3512                   /* A class array element needs converting back to be a
3513                      class object, if the formal argument is a class object.  */
3514                   if (fsym && fsym->ts.type == BT_CLASS
3515                         && e->ts.type == BT_CLASS
3516                         && CLASS_DATA (e)->attr.dimension)
3517                     gfc_conv_class_to_class (&parmse, e, fsym->ts, false);
3518
3519                   /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is 
3520                      allocated on entry, it must be deallocated.  */
3521                   if (fsym && fsym->attr.allocatable
3522                       && fsym->attr.intent == INTENT_OUT)
3523                     {
3524                       stmtblock_t block;
3525
3526                       gfc_init_block  (&block);
3527                       tmp = gfc_deallocate_with_status (parmse.expr, NULL_TREE,
3528                                                         true, NULL);
3529                       gfc_add_expr_to_block (&block, tmp);
3530                       tmp = fold_build2_loc (input_location, MODIFY_EXPR,
3531                                              void_type_node, parmse.expr,
3532                                              null_pointer_node);
3533                       gfc_add_expr_to_block (&block, tmp);
3534
3535                       if (fsym->attr.optional
3536                           && e->expr_type == EXPR_VARIABLE
3537                           && e->symtree->n.sym->attr.optional)
3538                         {
3539                           tmp = fold_build3_loc (input_location, COND_EXPR,
3540                                      void_type_node,
3541                                      gfc_conv_expr_present (e->symtree->n.sym),
3542                                             gfc_finish_block (&block),
3543                                             build_empty_stmt (input_location));
3544                         }
3545                       else
3546                         tmp = gfc_finish_block (&block);
3547
3548                       gfc_add_expr_to_block (&se->pre, tmp);
3549                     }
3550
3551                   if (fsym && e->expr_type != EXPR_NULL
3552                       && ((fsym->attr.pointer
3553                            && fsym->attr.flavor != FL_PROCEDURE)
3554                           || (fsym->attr.proc_pointer
3555                               && !(e->expr_type == EXPR_VARIABLE
3556                                    && e->symtree->n.sym->attr.dummy))
3557                           || (fsym->attr.proc_pointer
3558                               && e->expr_type == EXPR_VARIABLE
3559                               && gfc_is_proc_ptr_comp (e, NULL))
3560                           || fsym->attr.allocatable))
3561                     {
3562                       /* Scalar pointer dummy args require an extra level of
3563                          indirection. The null pointer already contains
3564                          this level of indirection.  */
3565                       parm_kind = SCALAR_POINTER;
3566                       parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
3567                     }
3568                 }
3569             }
3570           else if (e->ts.type == BT_CLASS
3571                     && fsym && fsym->ts.type == BT_CLASS
3572                     && CLASS_DATA (fsym)->attr.dimension)
3573             {
3574               /* Pass a class array.  */
3575               gfc_init_se (&parmse, se);
3576               gfc_conv_expr_descriptor (&parmse, e, argss);
3577               /* The conversion does not repackage the reference to a class
3578                  array - _data descriptor.  */
3579               gfc_conv_class_to_class (&parmse, e, fsym->ts, false);
3580             }
3581           else
3582             {
3583               /* If the procedure requires an explicit interface, the actual
3584                  argument is passed according to the corresponding formal
3585                  argument.  If the corresponding formal argument is a POINTER,
3586                  ALLOCATABLE or assumed shape, we do not use g77's calling
3587                  convention, and pass the address of the array descriptor
3588                  instead. Otherwise we use g77's calling convention.  */
3589               bool f;
3590               f = (fsym != NULL)
3591                   && !(fsym->attr.pointer || fsym->attr.allocatable)
3592                   && fsym->as && fsym->as->type != AS_ASSUMED_SHAPE;
3593               if (comp)
3594                 f = f || !comp->attr.always_explicit;
3595               else
3596                 f = f || !sym->attr.always_explicit;
3597
3598               /* If the argument is a function call that may not create
3599                  a temporary for the result, we have to check that we
3600                  can do it, i.e. that there is no alias between this 
3601                  argument and another one.  */
3602               if (gfc_get_noncopying_intrinsic_argument (e) != NULL)
3603                 {
3604                   gfc_expr *iarg;
3605                   sym_intent intent;
3606
3607                   if (fsym != NULL)
3608                     intent = fsym->attr.intent;
3609                   else
3610                     intent = INTENT_UNKNOWN;
3611
3612                   if (gfc_check_fncall_dependency (e, intent, sym, args,
3613                                                    NOT_ELEMENTAL))
3614                     parmse.force_tmp = 1;
3615
3616                   iarg = e->value.function.actual->expr;
3617
3618                   /* Temporary needed if aliasing due to host association.  */
3619                   if (sym->attr.contained
3620                         && !sym->attr.pure
3621                         && !sym->attr.implicit_pure
3622                         && !sym->attr.use_assoc
3623                         && iarg->expr_type == EXPR_VARIABLE
3624                         && sym->ns == iarg->symtree->n.sym->ns)
3625                     parmse.force_tmp = 1;
3626
3627                   /* Ditto within module.  */
3628                   if (sym->attr.use_assoc
3629                         && !sym->attr.pure
3630                         && !sym->attr.implicit_pure
3631                         && iarg->expr_type == EXPR_VARIABLE
3632                         && sym->module == iarg->symtree->n.sym->module)
3633                     parmse.force_tmp = 1;
3634                 }
3635
3636               if (e->expr_type == EXPR_VARIABLE
3637                     && is_subref_array (e))
3638                 /* The actual argument is a component reference to an
3639                    array of derived types.  In this case, the argument
3640                    is converted to a temporary, which is passed and then
3641                    written back after the procedure call.  */
3642                 gfc_conv_subref_array_arg (&parmse, e, f,
3643                                 fsym ? fsym->attr.intent : INTENT_INOUT,
3644                                 fsym && fsym->attr.pointer);
3645               else if (gfc_is_class_array_ref (e, NULL)
3646                          && fsym && fsym->ts.type == BT_DERIVED)
3647                 /* The actual argument is a component reference to an
3648                    array of derived types.  In this case, the argument
3649                    is converted to a temporary, which is passed and then
3650                    written back after the procedure call.
3651                    OOP-TODO: Insert code so that if the dynamic type is
3652                    the same as the declared type, copy-in/copy-out does
3653                    not occur.  */
3654                 gfc_conv_subref_array_arg (&parmse, e, f,
3655                                 fsym ? fsym->attr.intent : INTENT_INOUT,
3656                                 fsym && fsym->attr.pointer);
3657               else
3658                 gfc_conv_array_parameter (&parmse, e, argss, f, fsym,
3659                                           sym->name, NULL);
3660
3661               /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is 
3662                  allocated on entry, it must be deallocated.  */
3663               if (fsym && fsym->attr.allocatable
3664                   && fsym->attr.intent == INTENT_OUT)
3665                 {
3666                   tmp = build_fold_indirect_ref_loc (input_location,
3667                                                      parmse.expr);
3668                   tmp = gfc_trans_dealloc_allocated (tmp);
3669                   if (fsym->attr.optional
3670                       && e->expr_type == EXPR_VARIABLE
3671                       && e->symtree->n.sym->attr.optional)
3672                     tmp = fold_build3_loc (input_location, COND_EXPR,
3673                                      void_type_node,
3674                                      gfc_conv_expr_present (e->symtree->n.sym),
3675                                        tmp, build_empty_stmt (input_location));
3676                   gfc_add_expr_to_block (&se->pre, tmp);
3677                 }
3678             } 
3679         }
3680
3681       /* The case with fsym->attr.optional is that of a user subroutine
3682          with an interface indicating an optional argument.  When we call
3683          an intrinsic subroutine, however, fsym is NULL, but we might still
3684          have an optional argument, so we proceed to the substitution
3685          just in case.  */
3686       if (e && (fsym == NULL || fsym->attr.optional))
3687         {
3688           /* If an optional argument is itself an optional dummy argument,
3689              check its presence and substitute a null if absent.  This is
3690              only needed when passing an array to an elemental procedure
3691              as then array elements are accessed - or no NULL pointer is
3692              allowed and a "1" or "0" should be passed if not present.
3693              When passing a non-array-descriptor full array to a
3694              non-array-descriptor dummy, no check is needed. For
3695              array-descriptor actual to array-descriptor dummy, see
3696              PR 41911 for why a check has to be inserted.
3697              fsym == NULL is checked as intrinsics required the descriptor
3698              but do not always set fsym.  */
3699           if (e->expr_type == EXPR_VARIABLE
3700               && e->symtree->n.sym->attr.optional
3701               && ((e->rank > 0 && sym->attr.elemental)
3702                   || e->representation.length || e->ts.type == BT_CHARACTER
3703                   || (e->rank > 0
3704                       && (fsym == NULL 
3705                           || (fsym-> as
3706                               && (fsym->as->type == AS_ASSUMED_SHAPE
3707                                   || fsym->as->type == AS_DEFERRED))))))
3708             gfc_conv_missing_dummy (&parmse, e, fsym ? fsym->ts : e->ts,
3709                                     e->representation.length);
3710         }
3711
3712       if (fsym && e)
3713         {
3714           /* Obtain the character length of an assumed character length
3715              length procedure from the typespec.  */
3716           if (fsym->ts.type == BT_CHARACTER
3717               && parmse.string_length == NULL_TREE
3718               && e->ts.type == BT_PROCEDURE
3719               && e->symtree->n.sym->ts.type == BT_CHARACTER
3720               && e->symtree->n.sym->ts.u.cl->length != NULL
3721               && e->symtree->n.sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
3722             {
3723               gfc_conv_const_charlen (e->symtree->n.sym->ts.u.cl);
3724               parmse.string_length = e->symtree->n.sym->ts.u.cl->backend_decl;
3725             }
3726         }
3727
3728       if (fsym && need_interface_mapping && e)
3729         gfc_add_interface_mapping (&mapping, fsym, &parmse, e);
3730
3731       gfc_add_block_to_block (&se->pre, &parmse.pre);
3732       gfc_add_block_to_block (&post, &parmse.post);
3733
3734       /* Allocated allocatable components of derived types must be
3735          deallocated for non-variable scalars.  Non-variable arrays are
3736          dealt with in trans-array.c(gfc_conv_array_parameter).  */
3737       if (e && e->ts.type == BT_DERIVED
3738             && e->ts.u.derived->attr.alloc_comp
3739             && !(e->symtree && e->symtree->n.sym->attr.pointer)
3740             && (e->expr_type != EXPR_VARIABLE && !e->rank))
3741         {
3742           int parm_rank;
3743           tmp = build_fold_indirect_ref_loc (input_location,
3744                                          parmse.expr);
3745           parm_rank = e->rank;
3746           switch (parm_kind)
3747             {
3748             case (ELEMENTAL):
3749             case (SCALAR):
3750               parm_rank = 0;
3751               break;
3752
3753             case (SCALAR_POINTER):
3754               tmp = build_fold_indirect_ref_loc (input_location,
3755                                              tmp);
3756               break;
3757             }
3758
3759           if (e->expr_type == EXPR_OP
3760                 && e->value.op.op == INTRINSIC_PARENTHESES
3761                 && e->value.op.op1->expr_type == EXPR_VARIABLE)
3762             {
3763               tree local_tmp;
3764               local_tmp = gfc_evaluate_now (tmp, &se->pre);
3765               local_tmp = gfc_copy_alloc_comp (e->ts.u.derived, local_tmp, tmp, parm_rank);
3766               gfc_add_expr_to_block (&se->post, local_tmp);
3767             }
3768
3769           tmp = gfc_deallocate_alloc_comp (e->ts.u.derived, tmp, parm_rank);
3770
3771           gfc_add_expr_to_block (&se->post, tmp);
3772         }
3773
3774       /* Add argument checking of passing an unallocated/NULL actual to
3775          a nonallocatable/nonpointer dummy.  */
3776
3777       if (gfc_option.rtcheck & GFC_RTCHECK_POINTER && e != NULL)
3778         {
3779           symbol_attribute attr;
3780           char *msg;
3781           tree cond;
3782
3783           if (e->expr_type == EXPR_VARIABLE || e->expr_type == EXPR_FUNCTION)
3784             attr = gfc_expr_attr (e);
3785           else
3786             goto end_pointer_check;
3787
3788           /*  In Fortran 2008 it's allowed to pass a NULL pointer/nonallocated
3789               allocatable to an optional dummy, cf. 12.5.2.12.  */
3790           if (fsym != NULL && fsym->attr.optional && !attr.proc_pointer
3791               && (gfc_option.allow_std & GFC_STD_F2008) != 0)
3792             goto end_pointer_check;
3793
3794           if (attr.optional)
3795             {
3796               /* If the actual argument is an optional pointer/allocatable and
3797                  the formal argument takes an nonpointer optional value,
3798                  it is invalid to pass a non-present argument on, even
3799                  though there is no technical reason for this in gfortran.
3800                  See Fortran 2003, Section 12.4.1.6 item (7)+(8).  */
3801               tree present, null_ptr, type;
3802
3803               if (attr.allocatable
3804                   && (fsym == NULL || !fsym->attr.allocatable))
3805                 asprintf (&msg, "Allocatable actual argument '%s' is not "
3806                           "allocated or not present", e->symtree->n.sym->name);
3807               else if (attr.pointer
3808                        && (fsym == NULL || !fsym->attr.pointer))
3809                 asprintf (&msg, "Pointer actual argument '%s' is not "
3810                           "associated or not present",
3811                           e->symtree->n.sym->name);
3812               else if (attr.proc_pointer
3813                        && (fsym == NULL || !fsym->attr.proc_pointer))
3814                 asprintf (&msg, "Proc-pointer actual argument '%s' is not "
3815                           "associated or not present",
3816                           e->symtree->n.sym->name);
3817               else
3818                 goto end_pointer_check;
3819
3820               present = gfc_conv_expr_present (e->symtree->n.sym);
3821               type = TREE_TYPE (present);
3822               present = fold_build2_loc (input_location, EQ_EXPR,
3823                                          boolean_type_node, present,
3824                                          fold_convert (type,
3825                                                        null_pointer_node));
3826               type = TREE_TYPE (parmse.expr);
3827               null_ptr = fold_build2_loc (input_location, EQ_EXPR,
3828                                           boolean_type_node, parmse.expr,
3829                                           fold_convert (type,
3830                                                         null_pointer_node));
3831               cond = fold_build2_loc (input_location, TRUTH_ORIF_EXPR,
3832                                       boolean_type_node, present, null_ptr);
3833             }
3834           else
3835             {
3836               if (attr.allocatable
3837                   && (fsym == NULL || !fsym->attr.allocatable))
3838                 asprintf (&msg, "Allocatable actual argument '%s' is not "
3839                       "allocated", e->symtree->n.sym->name);
3840               else if (attr.pointer
3841                        && (fsym == NULL || !fsym->attr.pointer))
3842                 asprintf (&msg, "Pointer actual argument '%s' is not "
3843                       "associated", e->symtree->n.sym->name);
3844               else if (attr.proc_pointer
3845                        && (fsym == NULL || !fsym->attr.proc_pointer))
3846                 asprintf (&msg, "Proc-pointer actual argument '%s' is not "
3847                       "associated", e->symtree->n.sym->name);
3848               else
3849                 goto end_pointer_check;
3850
3851               tmp = parmse.expr;
3852
3853               /* If the argument is passed by value, we need to strip the
3854                  INDIRECT_REF.  */
3855               if (!POINTER_TYPE_P (TREE_TYPE (parmse.expr)))
3856                 tmp = gfc_build_addr_expr (NULL_TREE, tmp);
3857
3858               cond = fold_build2_loc (input_location, EQ_EXPR,
3859                                       boolean_type_node, tmp,
3860                                       fold_convert (TREE_TYPE (tmp),
3861                                                     null_pointer_node));
3862             }
3863  
3864           gfc_trans_runtime_check (true, false, cond, &se->pre, &e->where,
3865                                    msg);
3866           free (msg);
3867         }
3868       end_pointer_check:
3869
3870       /* Deferred length dummies pass the character length by reference
3871          so that the value can be returned.  */
3872       if (parmse.string_length && fsym && fsym->ts.deferred)
3873         {
3874           tmp = parmse.string_length;
3875           if (TREE_CODE (tmp) != VAR_DECL)
3876             tmp = gfc_evaluate_now (parmse.string_length, &se->pre);
3877           parmse.string_length = gfc_build_addr_expr (NULL_TREE, tmp);
3878         }
3879
3880       /* Character strings are passed as two parameters, a length and a
3881          pointer - except for Bind(c) which only passes the pointer.  */
3882       if (parmse.string_length != NULL_TREE && !sym->attr.is_bind_c)
3883         VEC_safe_push (tree, gc, stringargs, parmse.string_length);
3884
3885       /* For descriptorless coarrays and assumed-shape coarray dummies, we
3886          pass the token and the offset as additional arguments.  */
3887       if (fsym && fsym->attr.codimension
3888           && gfc_option.coarray == GFC_FCOARRAY_LIB
3889           && !fsym->attr.allocatable
3890           && e == NULL)
3891         {
3892           /* Token and offset. */
3893           VEC_safe_push (tree, gc, stringargs, null_pointer_node);
3894           VEC_safe_push (tree, gc, stringargs,
3895                          build_int_cst (gfc_array_index_type, 0));
3896           gcc_assert (fsym->attr.optional);
3897         }
3898       else if (fsym && fsym->attr.codimension
3899                && !fsym->attr.allocatable
3900                && gfc_option.coarray == GFC_FCOARRAY_LIB)
3901         {
3902           tree caf_decl, caf_type;
3903           tree offset, tmp2;
3904
3905           caf_decl = get_tree_for_caf_expr (e);
3906           caf_type = TREE_TYPE (caf_decl);
3907
3908           if (GFC_DESCRIPTOR_TYPE_P (caf_type)
3909               && GFC_TYPE_ARRAY_AKIND (caf_type) == GFC_ARRAY_ALLOCATABLE)
3910             tmp = gfc_conv_descriptor_token (caf_decl);
3911           else if (DECL_LANG_SPECIFIC (caf_decl)
3912                    && GFC_DECL_TOKEN (caf_decl) != NULL_TREE)
3913             tmp = GFC_DECL_TOKEN (caf_decl);
3914           else
3915             {
3916               gcc_assert (GFC_ARRAY_TYPE_P (caf_type)
3917                           && GFC_TYPE_ARRAY_CAF_TOKEN (caf_type) != NULL_TREE);
3918               tmp = GFC_TYPE_ARRAY_CAF_TOKEN (caf_type);
3919             }
3920           
3921           VEC_safe_push (tree, gc, stringargs, tmp);
3922
3923           if (GFC_DESCRIPTOR_TYPE_P (caf_type)
3924               && GFC_TYPE_ARRAY_AKIND (caf_type) == GFC_ARRAY_ALLOCATABLE)
3925             offset = build_int_cst (gfc_array_index_type, 0);
3926           else if (DECL_LANG_SPECIFIC (caf_decl)
3927                    && GFC_DECL_CAF_OFFSET (caf_decl) != NULL_TREE)
3928             offset = GFC_DECL_CAF_OFFSET (caf_decl);
3929           else if (GFC_TYPE_ARRAY_CAF_OFFSET (caf_type) != NULL_TREE)
3930             offset = GFC_TYPE_ARRAY_CAF_OFFSET (caf_type);
3931           else
3932             offset = build_int_cst (gfc_array_index_type, 0);
3933
3934           if (GFC_DESCRIPTOR_TYPE_P (caf_type))
3935             tmp = gfc_conv_descriptor_data_get (caf_decl);
3936           else
3937             {
3938               gcc_assert (POINTER_TYPE_P (caf_type));
3939               tmp = caf_decl;
3940             }
3941
3942           if (fsym->as->type == AS_ASSUMED_SHAPE)
3943             {
3944               gcc_assert (POINTER_TYPE_P (TREE_TYPE (parmse.expr)));
3945               gcc_assert (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE
3946                                                    (TREE_TYPE (parmse.expr))));
3947               tmp2 = build_fold_indirect_ref_loc (input_location, parmse.expr);
3948               tmp2 = gfc_conv_descriptor_data_get (tmp2);
3949             }
3950           else if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (parmse.expr)))
3951             tmp2 = gfc_conv_descriptor_data_get (parmse.expr);
3952           else
3953             {
3954               gcc_assert (POINTER_TYPE_P (TREE_TYPE (parmse.expr)));
3955               tmp2 = parmse.expr;
3956             }
3957
3958           tmp = fold_build2_loc (input_location, MINUS_EXPR,
3959                                  gfc_array_index_type,
3960                                  fold_convert (gfc_array_index_type, tmp2),
3961                                  fold_convert (gfc_array_index_type, tmp));
3962           offset = fold_build2_loc (input_location, PLUS_EXPR,
3963                                     gfc_array_index_type, offset, tmp);
3964
3965           VEC_safe_push (tree, gc, stringargs, offset);
3966         }
3967
3968       VEC_safe_push (tree, gc, arglist, parmse.expr);
3969     }
3970   gfc_finish_interface_mapping (&mapping, &se->pre, &se->post);
3971
3972   if (comp)
3973     ts = comp->ts;
3974   else
3975    ts = sym->ts;
3976
3977   if (ts.type == BT_CHARACTER && sym->attr.is_bind_c)
3978     se->string_length = build_int_cst (gfc_charlen_type_node, 1);
3979   else if (ts.type == BT_CHARACTER)
3980     {
3981       if (ts.u.cl->length == NULL)
3982         {
3983           /* Assumed character length results are not allowed by 5.1.1.5 of the
3984              standard and are trapped in resolve.c; except in the case of SPREAD
3985              (and other intrinsics?) and dummy functions.  In the case of SPREAD,
3986              we take the character length of the first argument for the result.
3987              For dummies, we have to look through the formal argument list for
3988              this function and use the character length found there.*/
3989           if (ts.deferred && (sym->attr.allocatable || sym->attr.pointer))
3990             cl.backend_decl = gfc_create_var (gfc_charlen_type_node, "slen");
3991           else if (!sym->attr.dummy)
3992             cl.backend_decl = VEC_index (tree, stringargs, 0);
3993           else
3994             {
3995               formal = sym->ns->proc_name->formal;
3996               for (; formal; formal = formal->next)
3997                 if (strcmp (formal->sym->name, sym->name) == 0)
3998                   cl.backend_decl = formal->sym->ts.u.cl->backend_decl;
3999             }
4000         }
4001       else
4002         {
4003           tree tmp;
4004
4005           /* Calculate the length of the returned string.  */
4006           gfc_init_se (&parmse, NULL);
4007           if (need_interface_mapping)
4008             gfc_apply_interface_mapping (&mapping, &parmse, ts.u.cl->length);
4009           else
4010             gfc_conv_expr (&parmse, ts.u.cl->length);
4011           gfc_add_block_to_block (&se->pre, &parmse.pre);
4012           gfc_add_block_to_block (&se->post, &parmse.post);
4013           
4014           tmp = fold_convert (gfc_charlen_type_node, parmse.expr);
4015           tmp = fold_build2_loc (input_location, MAX_EXPR,
4016                                  gfc_charlen_type_node, tmp,
4017                                  build_int_cst (gfc_charlen_type_node, 0));
4018           cl.backend_decl = tmp;
4019         }
4020
4021       /* Set up a charlen structure for it.  */
4022       cl.next = NULL;
4023       cl.length = NULL;
4024       ts.u.cl = &cl;
4025
4026       len = cl.backend_decl;
4027     }
4028
4029   byref = (comp && (comp->attr.dimension || comp->ts.type == BT_CHARACTER))
4030           || (!comp && gfc_return_by_reference (sym));
4031   if (byref)
4032     {
4033       if (se->direct_byref)
4034         {
4035           /* Sometimes, too much indirection can be applied; e.g. for
4036              function_result = array_valued_recursive_function.  */
4037           if (TREE_TYPE (TREE_TYPE (se->expr))
4038                 && TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr)))
4039                 && GFC_DESCRIPTOR_TYPE_P
4040                         (TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr)))))
4041             se->expr = build_fold_indirect_ref_loc (input_location,
4042                                                 se->expr);
4043
4044           /* If the lhs of an assignment x = f(..) is allocatable and
4045              f2003 is allowed, we must do the automatic reallocation.
4046              TODO - deal with intrinsics, without using a temporary.  */
4047           if (gfc_option.flag_realloc_lhs
4048                 && se->ss && se->ss->loop_chain
4049                 && se->ss->loop_chain->is_alloc_lhs
4050                 && !expr->value.function.isym
4051                 && sym->result->as != NULL)
4052             {
4053               /* Evaluate the bounds of the result, if known.  */
4054               gfc_set_loop_bounds_from_array_spec (&mapping, se,
4055                                                    sym->result->as);
4056
4057               /* Perform the automatic reallocation.  */
4058               tmp = gfc_alloc_allocatable_for_assignment (se->loop,
4059                                                           expr, NULL);
4060               gfc_add_expr_to_block (&se->pre, tmp);
4061
4062               /* Pass the temporary as the first argument.  */
4063               result = info->descriptor;
4064             }
4065           else
4066             result = build_fold_indirect_ref_loc (input_location,
4067                                                   se->expr);
4068           VEC_safe_push (tree, gc, retargs, se->expr);
4069         }
4070       else if (comp && comp->attr.dimension)
4071         {
4072           gcc_assert (se->loop && info);
4073
4074           /* Set the type of the array.  */
4075           tmp = gfc_typenode_for_spec (&comp->ts);
4076           gcc_assert (se->ss->dimen == se->loop->dimen);
4077
4078           /* Evaluate the bounds of the result, if known.  */
4079           gfc_set_loop_bounds_from_array_spec (&mapping, se, comp->as);
4080
4081           /* If the lhs of an assignment x = f(..) is allocatable and
4082              f2003 is allowed, we must not generate the function call
4083              here but should just send back the results of the mapping.
4084              This is signalled by the function ss being flagged.  */
4085           if (gfc_option.flag_realloc_lhs
4086                 && se->ss && se->ss->is_alloc_lhs)
4087             {
4088               gfc_free_interface_mapping (&mapping);
4089               return has_alternate_specifier;
4090             }
4091
4092           /* Create a temporary to store the result.  In case the function
4093              returns a pointer, the temporary will be a shallow copy and
4094              mustn't be deallocated.  */
4095           callee_alloc = comp->attr.allocatable || comp->attr.pointer;
4096           gfc_trans_create_temp_array (&se->pre, &se->post, se->ss,
4097                                        tmp, NULL_TREE, false,
4098                                        !comp->attr.pointer, callee_alloc,
4099                                        &se->ss->info->expr->where);
4100
4101           /* Pass the temporary as the first argument.  */
4102           result = info->descriptor;
4103           tmp = gfc_build_addr_expr (NULL_TREE, result);
4104           VEC_safe_push (tree, gc, retargs, tmp);
4105         }
4106       else if (!comp && sym->result->attr.dimension)
4107         {
4108           gcc_assert (se->loop && info);
4109
4110           /* Set the type of the array.  */
4111           tmp = gfc_typenode_for_spec (&ts);
4112           gcc_assert (se->ss->dimen == se->loop->dimen);
4113
4114           /* Evaluate the bounds of the result, if known.  */
4115           gfc_set_loop_bounds_from_array_spec (&mapping, se, sym->result->as);
4116
4117           /* If the lhs of an assignment x = f(..) is allocatable and
4118              f2003 is allowed, we must not generate the function call
4119              here but should just send back the results of the mapping.
4120              This is signalled by the function ss being flagged.  */
4121           if (gfc_option.flag_realloc_lhs
4122                 && se->ss && se->ss->is_alloc_lhs)
4123             {
4124               gfc_free_interface_mapping (&mapping);
4125               return has_alternate_specifier;
4126             }
4127
4128           /* Create a temporary to store the result.  In case the function
4129              returns a pointer, the temporary will be a shallow copy and
4130              mustn't be deallocated.  */
4131           callee_alloc = sym->attr.allocatable || sym->attr.pointer;
4132           gfc_trans_create_temp_array (&se->pre, &se->post, se->ss,
4133                                        tmp, NULL_TREE, false,
4134                                        !sym->attr.pointer, callee_alloc,
4135                                        &se->ss->info->expr->where);
4136
4137           /* Pass the temporary as the first argument.  */
4138           result = info->descriptor;
4139           tmp = gfc_build_addr_expr (NULL_TREE, result);
4140           VEC_safe_push (tree, gc, retargs, tmp);
4141         }
4142       else if (ts.type == BT_CHARACTER)
4143         {
4144           /* Pass the string length.  */
4145           type = gfc_get_character_type (ts.kind, ts.u.cl);
4146           type = build_pointer_type (type);
4147
4148           /* Return an address to a char[0:len-1]* temporary for
4149              character pointers.  */
4150           if ((!comp && (sym->attr.pointer || sym->attr.allocatable))
4151                || (comp && (comp->attr.pointer || comp->attr.allocatable)))
4152             {
4153               var = gfc_create_var (type, "pstr");
4154
4155               if ((!comp && sym->attr.allocatable)
4156                   || (comp && comp->attr.allocatable))
4157                 gfc_add_modify (&se->pre, var,
4158                                 fold_convert (TREE_TYPE (var),
4159                                               null_pointer_node));
4160
4161               /* Provide an address expression for the function arguments.  */
4162               var = gfc_build_addr_expr (NULL_TREE, var);
4163             }
4164           else
4165             var = gfc_conv_string_tmp (se, type, len);
4166
4167           VEC_safe_push (tree, gc, retargs, var);
4168         }
4169       else
4170         {
4171           gcc_assert (gfc_option.flag_f2c && ts.type == BT_COMPLEX);
4172
4173           type = gfc_get_complex_type (ts.kind);
4174           var = gfc_build_addr_expr (NULL_TREE, gfc_create_var (type, "cmplx"));
4175           VEC_safe_push (tree, gc, retargs, var);
4176         }
4177
4178       if (ts.type == BT_CHARACTER && ts.deferred
4179             && (sym->attr.allocatable || sym->attr.pointer))
4180         {
4181           tmp = len;
4182           if (TREE_CODE (tmp) != VAR_DECL)
4183             tmp = gfc_evaluate_now (len, &se->pre);
4184           len = gfc_build_addr_expr (NULL_TREE, tmp);
4185         }
4186
4187       /* Add the string length to the argument list.  */
4188       if (ts.type == BT_CHARACTER)
4189         VEC_safe_push (tree, gc, retargs, len);
4190     }
4191   gfc_free_interface_mapping (&mapping);
4192
4193   /* We need to glom RETARGS + ARGLIST + STRINGARGS + APPEND_ARGS.  */
4194   arglen = (VEC_length (tree, arglist)
4195             + VEC_length (tree, stringargs) + VEC_length (tree, append_args));
4196   VEC_reserve_exact (tree, gc, retargs, arglen);
4197
4198   /* Add the return arguments.  */
4199   VEC_splice (tree, retargs, arglist);
4200
4201   /* Add the hidden string length parameters to the arguments.  */
4202   VEC_splice (tree, retargs, stringargs);
4203
4204   /* We may want to append extra arguments here.  This is used e.g. for
4205      calls to libgfortran_matmul_??, which need extra information.  */
4206   if (!VEC_empty (tree, append_args))
4207     VEC_splice (tree, retargs, append_args);
4208   arglist = retargs;
4209
4210   /* Generate the actual call.  */
4211   if (base_object == NULL_TREE)
4212     conv_function_val (se, sym, expr);
4213   else
4214     conv_base_obj_fcn_val (se, base_object, expr);
4215
4216   /* If there are alternate return labels, function type should be
4217      integer.  Can't modify the type in place though, since it can be shared
4218      with other functions.  For dummy arguments, the typing is done to
4219      this result, even if it has to be repeated for each call.  */
4220   if (has_alternate_specifier
4221       && TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr))) != integer_type_node)
4222     {
4223       if (!sym->attr.dummy)
4224         {
4225           TREE_TYPE (sym->backend_decl)
4226                 = build_function_type (integer_type_node,
4227                       TYPE_ARG_TYPES (TREE_TYPE (sym->backend_decl)));
4228           se->expr = gfc_build_addr_expr (NULL_TREE, sym->backend_decl);
4229         }
4230       else
4231         TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr))) = integer_type_node;
4232     }
4233
4234   fntype = TREE_TYPE (TREE_TYPE (se->expr));
4235   se->expr = build_call_vec (TREE_TYPE (fntype), se->expr, arglist);
4236
4237   /* If we have a pointer function, but we don't want a pointer, e.g.
4238      something like
4239         x = f()
4240      where f is pointer valued, we have to dereference the result.  */
4241   if (!se->want_pointer && !byref
4242       && ((!comp && (sym->attr.pointer || sym->attr.allocatable))
4243           || (comp && (comp->attr.pointer || comp->attr.allocatable))))
4244     se->expr = build_fold_indirect_ref_loc (input_location, se->expr);
4245
4246   /* f2c calling conventions require a scalar default real function to
4247      return a double precision result.  Convert this back to default
4248      real.  We only care about the cases that can happen in Fortran 77.
4249   */
4250   if (gfc_option.flag_f2c && sym->ts.type == BT_REAL
4251       && sym->ts.kind == gfc_default_real_kind
4252       && !sym->attr.always_explicit)
4253     se->expr = fold_convert (gfc_get_real_type (sym->ts.kind), se->expr);
4254
4255   /* A pure function may still have side-effects - it may modify its
4256      parameters.  */
4257   TREE_SIDE_EFFECTS (se->expr) = 1;
4258 #if 0
4259   if (!sym->attr.pure)
4260     TREE_SIDE_EFFECTS (se->expr) = 1;
4261 #endif
4262
4263   if (byref)
4264     {
4265       /* Add the function call to the pre chain.  There is no expression.  */
4266       gfc_add_expr_to_block (&se->pre, se->expr);
4267       se->expr = NULL_TREE;
4268
4269       if (!se->direct_byref)
4270         {
4271           if ((sym->attr.dimension && !comp) || (comp && comp->attr.dimension))
4272             {
4273               if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
4274                 {
4275                   /* Check the data pointer hasn't been modified.  This would
4276                      happen in a function returning a pointer.  */
4277                   tmp = gfc_conv_descriptor_data_get (info->descriptor);
4278                   tmp = fold_build2_loc (input_location, NE_EXPR,
4279                                          boolean_type_node,
4280                                          tmp, info->data);
4281                   gfc_trans_runtime_check (true, false, tmp, &se->pre, NULL,
4282                                            gfc_msg_fault);
4283                 }
4284               se->expr = info->descriptor;
4285               /* Bundle in the string length.  */
4286               se->string_length = len;
4287             }
4288           else if (ts.type == BT_CHARACTER)
4289             {
4290               /* Dereference for character pointer results.  */
4291               if ((!comp && (sym->attr.pointer || sym->attr.allocatable))
4292                   || (comp && (comp->attr.pointer || comp->attr.allocatable)))
4293                 se->expr = build_fold_indirect_ref_loc (input_location, var);
4294               else
4295                 se->expr = var;
4296
4297               if (!ts.deferred)
4298                 se->string_length = len;
4299               else if (sym->attr.allocatable || sym->attr.pointer)
4300                 se->string_length = cl.backend_decl;
4301             }
4302           else
4303             {
4304               gcc_assert (ts.type == BT_COMPLEX && gfc_option.flag_f2c);
4305               se->expr = build_fold_indirect_ref_loc (input_location, var);
4306             }
4307         }
4308     }
4309
4310   /* Follow the function call with the argument post block.  */
4311   if (byref)
4312     {
4313       gfc_add_block_to_block (&se->pre, &post);
4314
4315       /* Transformational functions of derived types with allocatable
4316          components must have the result allocatable components copied.  */
4317       arg = expr->value.function.actual;
4318       if (result && arg && expr->rank
4319             && expr->value.function.isym
4320             && expr->value.function.isym->transformational
4321             && arg->expr->ts.type == BT_DERIVED
4322             && arg->expr->ts.u.derived->attr.alloc_comp)
4323         {
4324           tree tmp2;
4325           /* Copy the allocatable components.  We have to use a
4326              temporary here to prevent source allocatable components
4327              from being corrupted.  */
4328           tmp2 = gfc_evaluate_now (result, &se->pre);
4329           tmp = gfc_copy_alloc_comp (arg->expr->ts.u.derived,
4330                                      result, tmp2, expr->rank);
4331           gfc_add_expr_to_block (&se->pre, tmp);
4332           tmp = gfc_copy_allocatable_data (result, tmp2, TREE_TYPE(tmp2),
4333                                            expr->rank);
4334           gfc_add_expr_to_block (&se->pre, tmp);
4335
4336           /* Finally free the temporary's data field.  */
4337           tmp = gfc_conv_descriptor_data_get (tmp2);
4338           tmp = gfc_deallocate_with_status (tmp, NULL_TREE, true, NULL);
4339           gfc_add_expr_to_block (&se->pre, tmp);
4340         }
4341     }
4342   else
4343     gfc_add_block_to_block (&se->post, &post);
4344
4345   return has_alternate_specifier;
4346 }
4347
4348
4349 /* Fill a character string with spaces.  */
4350
4351 static tree
4352 fill_with_spaces (tree start, tree type, tree size)
4353 {
4354   stmtblock_t block, loop;
4355   tree i, el, exit_label, cond, tmp;
4356
4357   /* For a simple char type, we can call memset().  */
4358   if (compare_tree_int (TYPE_SIZE_UNIT (type), 1) == 0)
4359     return build_call_expr_loc (input_location,
4360                             builtin_decl_explicit (BUILT_IN_MEMSET),
4361                             3, start,
4362                             build_int_cst (gfc_get_int_type (gfc_c_int_kind),
4363                                            lang_hooks.to_target_charset (' ')),
4364                             size);
4365
4366   /* Otherwise, we use a loop:
4367         for (el = start, i = size; i > 0; el--, i+= TYPE_SIZE_UNIT (type))
4368           *el = (type) ' ';
4369    */
4370
4371   /* Initialize variables.  */
4372   gfc_init_block (&block);
4373   i = gfc_create_var (sizetype, "i");
4374   gfc_add_modify (&block, i, fold_convert (sizetype, size));
4375   el = gfc_create_var (build_pointer_type (type), "el");
4376   gfc_add_modify (&block, el, fold_convert (TREE_TYPE (el), start));
4377   exit_label = gfc_build_label_decl (NULL_TREE);
4378   TREE_USED (exit_label) = 1;
4379
4380
4381   /* Loop body.  */
4382   gfc_init_block (&loop);
4383
4384   /* Exit condition.  */
4385   cond = fold_build2_loc (input_location, LE_EXPR, boolean_type_node, i,
4386                           build_zero_cst (sizetype));
4387   tmp = build1_v (GOTO_EXPR, exit_label);
4388   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, tmp,
4389                          build_empty_stmt (input_location));
4390   gfc_add_expr_to_block (&loop, tmp);
4391
4392   /* Assignment.  */
4393   gfc_add_modify (&loop,
4394                   fold_build1_loc (input_location, INDIRECT_REF, type, el),
4395                   build_int_cst (type, lang_hooks.to_target_charset (' ')));
4396
4397   /* Increment loop variables.  */
4398   gfc_add_modify (&loop, i,
4399                   fold_build2_loc (input_location, MINUS_EXPR, sizetype, i,
4400                                    TYPE_SIZE_UNIT (type)));
4401   gfc_add_modify (&loop, el,
4402                   fold_build_pointer_plus_loc (input_location,
4403                                                el, TYPE_SIZE_UNIT (type)));
4404
4405   /* Making the loop... actually loop!  */
4406   tmp = gfc_finish_block (&loop);
4407   tmp = build1_v (LOOP_EXPR, tmp);
4408   gfc_add_expr_to_block (&block, tmp);
4409
4410   /* The exit label.  */
4411   tmp = build1_v (LABEL_EXPR, exit_label);
4412   gfc_add_expr_to_block (&block, tmp);
4413
4414
4415   return gfc_finish_block (&block);
4416 }
4417
4418
4419 /* Generate code to copy a string.  */
4420
4421 void
4422 gfc_trans_string_copy (stmtblock_t * block, tree dlength, tree dest,
4423                        int dkind, tree slength, tree src, int skind)
4424 {
4425   tree tmp, dlen, slen;
4426   tree dsc;
4427   tree ssc;
4428   tree cond;
4429   tree cond2;
4430   tree tmp2;
4431   tree tmp3;
4432   tree tmp4;
4433   tree chartype;
4434   stmtblock_t tempblock;
4435
4436   gcc_assert (dkind == skind);
4437
4438   if (slength != NULL_TREE)
4439     {
4440       slen = fold_convert (size_type_node, gfc_evaluate_now (slength, block));
4441       ssc = gfc_string_to_single_character (slen, src, skind);
4442     }
4443   else
4444     {
4445       slen = build_int_cst (size_type_node, 1);
4446       ssc =  src;
4447     }
4448
4449   if (dlength != NULL_TREE)
4450     {
4451       dlen = fold_convert (size_type_node, gfc_evaluate_now (dlength, block));
4452       dsc = gfc_string_to_single_character (dlen, dest, dkind);
4453     }
4454   else
4455     {
4456       dlen = build_int_cst (size_type_node, 1);
4457       dsc =  dest;
4458     }
4459
4460   /* Assign directly if the types are compatible.  */
4461   if (dsc != NULL_TREE && ssc != NULL_TREE
4462       && TREE_TYPE (dsc) == TREE_TYPE (ssc))
4463     {
4464       gfc_add_modify (block, dsc, ssc);
4465       return;
4466     }
4467
4468   /* Do nothing if the destination length is zero.  */
4469   cond = fold_build2_loc (input_location, GT_EXPR, boolean_type_node, dlen,
4470                           build_int_cst (size_type_node, 0));
4471
4472   /* The following code was previously in _gfortran_copy_string:
4473
4474        // The two strings may overlap so we use memmove.
4475        void
4476        copy_string (GFC_INTEGER_4 destlen, char * dest,
4477                     GFC_INTEGER_4 srclen, const char * src)
4478        {
4479          if (srclen >= destlen)
4480            {
4481              // This will truncate if too long.
4482              memmove (dest, src, destlen);
4483            }
4484          else
4485            {
4486              memmove (dest, src, srclen);
4487              // Pad with spaces.
4488              memset (&dest[srclen], ' ', destlen - srclen);
4489            }
4490        }
4491
4492      We're now doing it here for better optimization, but the logic
4493      is the same.  */
4494
4495   /* For non-default character kinds, we have to multiply the string
4496      length by the base type size.  */
4497   chartype = gfc_get_char_type (dkind);
4498   slen = fold_build2_loc (input_location, MULT_EXPR, size_type_node,
4499                           fold_convert (size_type_node, slen),
4500                           fold_convert (size_type_node,
4501                                         TYPE_SIZE_UNIT (chartype)));
4502   dlen = fold_build2_loc (input_location, MULT_EXPR, size_type_node,
4503                           fold_convert (size_type_node, dlen),
4504                           fold_convert (size_type_node,
4505                                         TYPE_SIZE_UNIT (chartype)));
4506
4507   if (dlength && POINTER_TYPE_P (TREE_TYPE (dest)))
4508     dest = fold_convert (pvoid_type_node, dest);
4509   else
4510     dest = gfc_build_addr_expr (pvoid_type_node, dest);
4511
4512   if (slength && POINTER_TYPE_P (TREE_TYPE (src)))
4513     src = fold_convert (pvoid_type_node, src);
4514   else
4515     src = gfc_build_addr_expr (pvoid_type_node, src);
4516
4517   /* Truncate string if source is too long.  */
4518   cond2 = fold_build2_loc (input_location, GE_EXPR, boolean_type_node, slen,
4519                            dlen);
4520   tmp2 = build_call_expr_loc (input_location,
4521                               builtin_decl_explicit (BUILT_IN_MEMMOVE),
4522                               3, dest, src, dlen);
4523
4524   /* Else copy and pad with spaces.  */
4525   tmp3 = build_call_expr_loc (input_location,
4526                               builtin_decl_explicit (BUILT_IN_MEMMOVE),
4527                               3, dest, src, slen);
4528
4529   tmp4 = fold_build_pointer_plus_loc (input_location, dest, slen);
4530   tmp4 = fill_with_spaces (tmp4, chartype,
4531                            fold_build2_loc (input_location, MINUS_EXPR,
4532                                             TREE_TYPE(dlen), dlen, slen));
4533
4534   gfc_init_block (&tempblock);
4535   gfc_add_expr_to_block (&tempblock, tmp3);
4536   gfc_add_expr_to_block (&tempblock, tmp4);
4537   tmp3 = gfc_finish_block (&tempblock);
4538
4539   /* The whole copy_string function is there.  */
4540   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond2,
4541                          tmp2, tmp3);
4542   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, tmp,
4543                          build_empty_stmt (input_location));
4544   gfc_add_expr_to_block (block, tmp);
4545 }
4546
4547
4548 /* Translate a statement function.
4549    The value of a statement function reference is obtained by evaluating the
4550    expression using the values of the actual arguments for the values of the
4551    corresponding dummy arguments.  */
4552
4553 static void
4554 gfc_conv_statement_function (gfc_se * se, gfc_expr * expr)
4555 {
4556   gfc_symbol *sym;
4557   gfc_symbol *fsym;
4558   gfc_formal_arglist *fargs;
4559   gfc_actual_arglist *args;
4560   gfc_se lse;
4561   gfc_se rse;
4562   gfc_saved_var *saved_vars;
4563   tree *temp_vars;
4564   tree type;
4565   tree tmp;
4566   int n;
4567
4568   sym = expr->symtree->n.sym;
4569   args = expr->value.function.actual;
4570   gfc_init_se (&lse, NULL);
4571   gfc_init_se (&rse, NULL);
4572
4573   n = 0;
4574   for (fargs = sym->formal; fargs; fargs = fargs->next)
4575     n++;
4576   saved_vars = XCNEWVEC (gfc_saved_var, n);
4577   temp_vars = XCNEWVEC (tree, n);
4578
4579   for (fargs = sym->formal, n = 0; fargs; fargs = fargs->next, n++)
4580     {
4581       /* Each dummy shall be specified, explicitly or implicitly, to be
4582          scalar.  */
4583       gcc_assert (fargs->sym->attr.dimension == 0);
4584       fsym = fargs->sym;
4585
4586       if (fsym->ts.type == BT_CHARACTER)
4587         {
4588           /* Copy string arguments.  */
4589           tree arglen;
4590
4591           gcc_assert (fsym->ts.u.cl && fsym->ts.u.cl->length
4592                       && fsym->ts.u.cl->length->expr_type == EXPR_CONSTANT);
4593
4594           /* Create a temporary to hold the value.  */
4595           if (fsym->ts.u.cl->backend_decl == NULL_TREE)
4596              fsym->ts.u.cl->backend_decl
4597                 = gfc_conv_constant_to_tree (fsym->ts.u.cl->length);
4598
4599           type = gfc_get_character_type (fsym->ts.kind, fsym->ts.u.cl);
4600           temp_vars[n] = gfc_create_var (type, fsym->name);
4601
4602           arglen = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
4603
4604           gfc_conv_expr (&rse, args->expr);
4605           gfc_conv_string_parameter (&rse);
4606           gfc_add_block_to_block (&se->pre, &lse.pre);
4607           gfc_add_block_to_block (&se->pre, &rse.pre);
4608
4609           gfc_trans_string_copy (&se->pre, arglen, temp_vars[n], fsym->ts.kind,
4610                                  rse.string_length, rse.expr, fsym->ts.kind);
4611           gfc_add_block_to_block (&se->pre, &lse.post);
4612           gfc_add_block_to_block (&se->pre, &rse.post);
4613         }
4614       else
4615         {
4616           /* For everything else, just evaluate the expression.  */
4617
4618           /* Create a temporary to hold the value.  */
4619           type = gfc_typenode_for_spec (&fsym->ts);
4620           temp_vars[n] = gfc_create_var (type, fsym->name);
4621
4622           gfc_conv_expr (&lse, args->expr);
4623
4624           gfc_add_block_to_block (&se->pre, &lse.pre);
4625           gfc_add_modify (&se->pre, temp_vars[n], lse.expr);
4626           gfc_add_block_to_block (&se->pre, &lse.post);
4627         }
4628
4629       args = args->next;
4630     }
4631
4632   /* Use the temporary variables in place of the real ones.  */
4633   for (fargs = sym->formal, n = 0; fargs; fargs = fargs->next, n++)
4634     gfc_shadow_sym (fargs->sym, temp_vars[n], &saved_vars[n]);
4635
4636   gfc_conv_expr (se, sym->value);
4637
4638   if (sym->ts.type == BT_CHARACTER)
4639     {
4640       gfc_conv_const_charlen (sym->ts.u.cl);
4641
4642       /* Force the expression to the correct length.  */
4643       if (!INTEGER_CST_P (se->string_length)
4644           || tree_int_cst_lt (se->string_length,
4645                               sym->ts.u.cl->backend_decl))
4646         {
4647           type = gfc_get_character_type (sym->ts.kind, sym->ts.u.cl);
4648           tmp = gfc_create_var (type, sym->name);
4649           tmp = gfc_build_addr_expr (build_pointer_type (type), tmp);
4650           gfc_trans_string_copy (&se->pre, sym->ts.u.cl->backend_decl, tmp,
4651                                  sym->ts.kind, se->string_length, se->expr,
4652                                  sym->ts.kind);
4653           se->expr = tmp;
4654         }
4655       se->string_length = sym->ts.u.cl->backend_decl;
4656     }
4657
4658   /* Restore the original variables.  */
4659   for (fargs = sym->formal, n = 0; fargs; fargs = fargs->next, n++)
4660     gfc_restore_sym (fargs->sym, &saved_vars[n]);
4661   free (saved_vars);
4662 }
4663
4664
4665 /* Translate a function expression.  */
4666
4667 static void
4668 gfc_conv_function_expr (gfc_se * se, gfc_expr * expr)
4669 {
4670   gfc_symbol *sym;
4671
4672   if (expr->value.function.isym)
4673     {
4674       gfc_conv_intrinsic_function (se, expr);
4675       return;
4676     }
4677
4678   /* We distinguish statement functions from general functions to improve
4679      runtime performance.  */
4680   if (expr->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
4681     {
4682       gfc_conv_statement_function (se, expr);
4683       return;
4684     }
4685
4686   /* expr.value.function.esym is the resolved (specific) function symbol for
4687      most functions.  However this isn't set for dummy procedures.  */
4688   sym = expr->value.function.esym;
4689   if (!sym)
4690     sym = expr->symtree->n.sym;
4691
4692   gfc_conv_procedure_call (se, sym, expr->value.function.actual, expr, NULL);
4693 }
4694
4695
4696 /* Determine whether the given EXPR_CONSTANT is a zero initializer.  */
4697
4698 static bool
4699 is_zero_initializer_p (gfc_expr * expr)
4700 {
4701   if (expr->expr_type != EXPR_CONSTANT)
4702     return false;
4703
4704   /* We ignore constants with prescribed memory representations for now.  */
4705   if (expr->representation.string)
4706     return false;
4707
4708   switch (expr->ts.type)
4709     {
4710     case BT_INTEGER:
4711       return mpz_cmp_si (expr->value.integer, 0) == 0;
4712
4713     case BT_REAL:
4714       return mpfr_zero_p (expr->value.real)
4715              && MPFR_SIGN (expr->value.real) >= 0;
4716
4717     case BT_LOGICAL:
4718       return expr->value.logical == 0;
4719
4720     case BT_COMPLEX:
4721       return mpfr_zero_p (mpc_realref (expr->value.complex))
4722              && MPFR_SIGN (mpc_realref (expr->value.complex)) >= 0
4723              && mpfr_zero_p (mpc_imagref (expr->value.complex))
4724              && MPFR_SIGN (mpc_imagref (expr->value.complex)) >= 0;
4725
4726     default:
4727       break;
4728     }
4729   return false;
4730 }
4731
4732
4733 static void
4734 gfc_conv_array_constructor_expr (gfc_se * se, gfc_expr * expr)
4735 {
4736   gfc_ss *ss;
4737
4738   ss = se->ss;
4739   gcc_assert (ss != NULL && ss != gfc_ss_terminator);
4740   gcc_assert (ss->info->expr == expr && ss->info->type == GFC_SS_CONSTRUCTOR);
4741
4742   gfc_conv_tmp_array_ref (se);
4743 }
4744
4745
4746 /* Build a static initializer.  EXPR is the expression for the initial value.
4747    The other parameters describe the variable of the component being 
4748    initialized. EXPR may be null.  */
4749
4750 tree
4751 gfc_conv_initializer (gfc_expr * expr, gfc_typespec * ts, tree type,
4752                       bool array, bool pointer, bool procptr)
4753 {
4754   gfc_se se;
4755
4756   if (!(expr || pointer || procptr))
4757     return NULL_TREE;
4758
4759   /* Check if we have ISOCBINDING_NULL_PTR or ISOCBINDING_NULL_FUNPTR
4760      (these are the only two iso_c_binding derived types that can be
4761      used as initialization expressions).  If so, we need to modify
4762      the 'expr' to be that for a (void *).  */
4763   if (expr != NULL && expr->ts.type == BT_DERIVED
4764       && expr->ts.is_iso_c && expr->ts.u.derived)
4765     {
4766       gfc_symbol *derived = expr->ts.u.derived;
4767
4768       /* The derived symbol has already been converted to a (void *).  Use
4769          its kind.  */
4770       expr = gfc_get_int_expr (derived->ts.kind, NULL, 0);
4771       expr->ts.f90_type = derived->ts.f90_type;
4772
4773       gfc_init_se (&se, NULL);
4774       gfc_conv_constant (&se, expr);
4775       gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
4776       return se.expr;
4777     }
4778   
4779   if (array && !procptr)
4780     {
4781       tree ctor;
4782       /* Arrays need special handling.  */
4783       if (pointer)
4784         ctor = gfc_build_null_descriptor (type);
4785       /* Special case assigning an array to zero.  */
4786       else if (is_zero_initializer_p (expr))
4787         ctor = build_constructor (type, NULL);
4788       else
4789         ctor = gfc_conv_array_initializer (type, expr);
4790       TREE_STATIC (ctor) = 1;
4791       return ctor;
4792     }
4793   else if (pointer || procptr)
4794     {
4795       if (!expr || expr->expr_type == EXPR_NULL)
4796         return fold_convert (type, null_pointer_node);
4797       else
4798         {
4799           gfc_init_se (&se, NULL);
4800           se.want_pointer = 1;
4801           gfc_conv_expr (&se, expr);
4802           gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
4803           return se.expr;
4804         }
4805     }
4806   else
4807     {
4808       switch (ts->type)
4809         {
4810         case BT_DERIVED:
4811         case BT_CLASS:
4812           gfc_init_se (&se, NULL);
4813           if (ts->type == BT_CLASS && expr->expr_type == EXPR_NULL)
4814             gfc_conv_structure (&se, gfc_class_null_initializer(ts), 1);
4815           else
4816             gfc_conv_structure (&se, expr, 1);
4817           gcc_assert (TREE_CODE (se.expr) == CONSTRUCTOR);
4818           TREE_STATIC (se.expr) = 1;
4819           return se.expr;
4820
4821         case BT_CHARACTER:
4822           {
4823             tree ctor = gfc_conv_string_init (ts->u.cl->backend_decl,expr);
4824             TREE_STATIC (ctor) = 1;
4825             return ctor;
4826           }
4827
4828         default:
4829           gfc_init_se (&se, NULL);
4830           gfc_conv_constant (&se, expr);
4831           gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
4832           return se.expr;
4833         }
4834     }
4835 }
4836   
4837 static tree
4838 gfc_trans_subarray_assign (tree dest, gfc_component * cm, gfc_expr * expr)
4839 {
4840   gfc_se rse;
4841   gfc_se lse;
4842   gfc_ss *rss;
4843   gfc_ss *lss;
4844   gfc_array_info *lss_array;
4845   stmtblock_t body;
4846   stmtblock_t block;
4847   gfc_loopinfo loop;
4848   int n;
4849   tree tmp;
4850
4851   gfc_start_block (&block);
4852
4853   /* Initialize the scalarizer.  */
4854   gfc_init_loopinfo (&loop);
4855
4856   gfc_init_se (&lse, NULL);
4857   gfc_init_se (&rse, NULL);
4858
4859   /* Walk the rhs.  */
4860   rss = gfc_walk_expr (expr);
4861   if (rss == gfc_ss_terminator)
4862     /* The rhs is scalar.  Add a ss for the expression.  */
4863     rss = gfc_get_scalar_ss (gfc_ss_terminator, expr);
4864
4865   /* Create a SS for the destination.  */
4866   lss = gfc_get_array_ss (gfc_ss_terminator, NULL, cm->as->rank,
4867                           GFC_SS_COMPONENT);
4868   lss_array = &lss->info->data.array;
4869   lss_array->shape = gfc_get_shape (cm->as->rank);
4870   lss_array->descriptor = dest;
4871   lss_array->data = gfc_conv_array_data (dest);
4872   lss_array->offset = gfc_conv_array_offset (dest);
4873   for (n = 0; n < cm->as->rank; n++)
4874     {
4875       lss_array->start[n] = gfc_conv_array_lbound (dest, n);
4876       lss_array->stride[n] = gfc_index_one_node;
4877
4878       mpz_init (lss_array->shape[n]);
4879       mpz_sub (lss_array->shape[n], cm->as->upper[n]->value.integer,
4880                cm->as->lower[n]->value.integer);
4881       mpz_add_ui (lss_array->shape[n], lss_array->shape[n], 1);
4882     }
4883   
4884   /* Associate the SS with the loop.  */
4885   gfc_add_ss_to_loop (&loop, lss);
4886   gfc_add_ss_to_loop (&loop, rss);
4887
4888   /* Calculate the bounds of the scalarization.  */
4889   gfc_conv_ss_startstride (&loop);
4890
4891   /* Setup the scalarizing loops.  */
4892   gfc_conv_loop_setup (&loop, &expr->where);
4893
4894   /* Setup the gfc_se structures.  */
4895   gfc_copy_loopinfo_to_se (&lse, &loop);
4896   gfc_copy_loopinfo_to_se (&rse, &loop);
4897
4898   rse.ss = rss;
4899   gfc_mark_ss_chain_used (rss, 1);
4900   lse.ss = lss;
4901   gfc_mark_ss_chain_used (lss, 1);
4902
4903   /* Start the scalarized loop body.  */
4904   gfc_start_scalarized_body (&loop, &body);
4905
4906   gfc_conv_tmp_array_ref (&lse);
4907   if (cm->ts.type == BT_CHARACTER)
4908     lse.string_length = cm->ts.u.cl->backend_decl;
4909
4910   gfc_conv_expr (&rse, expr);
4911
4912   tmp = gfc_trans_scalar_assign (&lse, &rse, cm->ts, true, false, true);
4913   gfc_add_expr_to_block (&body, tmp);
4914
4915   gcc_assert (rse.ss == gfc_ss_terminator);
4916
4917   /* Generate the copying loops.  */
4918   gfc_trans_scalarizing_loops (&loop, &body);
4919
4920   /* Wrap the whole thing up.  */
4921   gfc_add_block_to_block (&block, &loop.pre);
4922   gfc_add_block_to_block (&block, &loop.post);
4923
4924   gcc_assert (lss_array->shape != NULL);
4925   gfc_free_shape (&lss_array->shape, cm->as->rank);
4926   gfc_cleanup_loop (&loop);
4927
4928   return gfc_finish_block (&block);
4929 }
4930
4931
4932 static tree
4933 gfc_trans_alloc_subarray_assign (tree dest, gfc_component * cm,
4934                                  gfc_expr * expr)
4935 {
4936   gfc_se se;
4937   gfc_ss *rss;
4938   stmtblock_t block;
4939   tree offset;
4940   int n;
4941   tree tmp;
4942   tree tmp2;
4943   gfc_array_spec *as;
4944   gfc_expr *arg = NULL;
4945
4946   gfc_start_block (&block);
4947   gfc_init_se (&se, NULL);
4948
4949   /* Get the descriptor for the expressions.  */ 
4950   rss = gfc_walk_expr (expr);
4951   se.want_pointer = 0;
4952   gfc_conv_expr_descriptor (&se, expr, rss);
4953   gfc_add_block_to_block (&block, &se.pre);
4954   gfc_add_modify (&block, dest, se.expr);
4955
4956   /* Deal with arrays of derived types with allocatable components.  */
4957   if (cm->ts.type == BT_DERIVED
4958         && cm->ts.u.derived->attr.alloc_comp)
4959     tmp = gfc_copy_alloc_comp (cm->ts.u.derived,
4960                                se.expr, dest,
4961                                cm->as->rank);
4962   else
4963     tmp = gfc_duplicate_allocatable (dest, se.expr,
4964                                      TREE_TYPE(cm->backend_decl),
4965                                      cm->as->rank);
4966
4967   gfc_add_expr_to_block (&block, tmp);
4968   gfc_add_block_to_block (&block, &se.post);
4969
4970   if (expr->expr_type != EXPR_VARIABLE)
4971     gfc_conv_descriptor_data_set (&block, se.expr,
4972                                   null_pointer_node);
4973
4974   /* We need to know if the argument of a conversion function is a
4975      variable, so that the correct lower bound can be used.  */
4976   if (expr->expr_type == EXPR_FUNCTION
4977         && expr->value.function.isym
4978         && expr->value.function.isym->conversion
4979         && expr->value.function.actual->expr
4980         && expr->value.function.actual->expr->expr_type == EXPR_VARIABLE)
4981     arg = expr->value.function.actual->expr;
4982
4983   /* Obtain the array spec of full array references.  */
4984   if (arg)
4985     as = gfc_get_full_arrayspec_from_expr (arg);
4986   else
4987     as = gfc_get_full_arrayspec_from_expr (expr);
4988
4989   /* Shift the lbound and ubound of temporaries to being unity,
4990      rather than zero, based. Always calculate the offset.  */
4991   offset = gfc_conv_descriptor_offset_get (dest);
4992   gfc_add_modify (&block, offset, gfc_index_zero_node);
4993   tmp2 =gfc_create_var (gfc_array_index_type, NULL);
4994
4995   for (n = 0; n < expr->rank; n++)
4996     {
4997       tree span;
4998       tree lbound;
4999
5000       /* Obtain the correct lbound - ISO/IEC TR 15581:2001 page 9.
5001          TODO It looks as if gfc_conv_expr_descriptor should return
5002          the correct bounds and that the following should not be
5003          necessary.  This would simplify gfc_conv_intrinsic_bound
5004          as well.  */
5005       if (as && as->lower[n])
5006         {
5007           gfc_se lbse;
5008           gfc_init_se (&lbse, NULL);
5009           gfc_conv_expr (&lbse, as->lower[n]);
5010           gfc_add_block_to_block (&block, &lbse.pre);
5011           lbound = gfc_evaluate_now (lbse.expr, &block);
5012         }
5013       else if (as && arg)
5014         {
5015           tmp = gfc_get_symbol_decl (arg->symtree->n.sym);
5016           lbound = gfc_conv_descriptor_lbound_get (tmp,
5017                                         gfc_rank_cst[n]);
5018         }
5019       else if (as)
5020         lbound = gfc_conv_descriptor_lbound_get (dest,
5021                                                 gfc_rank_cst[n]);
5022       else
5023         lbound = gfc_index_one_node;
5024
5025       lbound = fold_convert (gfc_array_index_type, lbound);
5026
5027       /* Shift the bounds and set the offset accordingly.  */
5028       tmp = gfc_conv_descriptor_ubound_get (dest, gfc_rank_cst[n]);
5029       span = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
5030                 tmp, gfc_conv_descriptor_lbound_get (dest, gfc_rank_cst[n]));
5031       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
5032                              span, lbound);
5033       gfc_conv_descriptor_ubound_set (&block, dest,
5034                                       gfc_rank_cst[n], tmp);
5035       gfc_conv_descriptor_lbound_set (&block, dest,
5036                                       gfc_rank_cst[n], lbound);
5037
5038       tmp = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
5039                          gfc_conv_descriptor_lbound_get (dest,
5040                                                          gfc_rank_cst[n]),
5041                          gfc_conv_descriptor_stride_get (dest,
5042                                                          gfc_rank_cst[n]));
5043       gfc_add_modify (&block, tmp2, tmp);
5044       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
5045                              offset, tmp2);
5046       gfc_conv_descriptor_offset_set (&block, dest, tmp);
5047     }
5048
5049   if (arg)
5050     {
5051       /* If a conversion expression has a null data pointer
5052          argument, nullify the allocatable component.  */
5053       tree non_null_expr;
5054       tree null_expr;
5055
5056       if (arg->symtree->n.sym->attr.allocatable
5057             || arg->symtree->n.sym->attr.pointer)
5058         {
5059           non_null_expr = gfc_finish_block (&block);
5060           gfc_start_block (&block);
5061           gfc_conv_descriptor_data_set (&block, dest,
5062                                         null_pointer_node);
5063           null_expr = gfc_finish_block (&block);
5064           tmp = gfc_conv_descriptor_data_get (arg->symtree->n.sym->backend_decl);
5065           tmp = build2_loc (input_location, EQ_EXPR, boolean_type_node, tmp,
5066                             fold_convert (TREE_TYPE (tmp), null_pointer_node));
5067           return build3_v (COND_EXPR, tmp,
5068                            null_expr, non_null_expr);
5069         }
5070     }
5071
5072   return gfc_finish_block (&block);
5073 }
5074
5075
5076 /* Assign a single component of a derived type constructor.  */
5077
5078 static tree
5079 gfc_trans_subcomponent_assign (tree dest, gfc_component * cm, gfc_expr * expr)
5080 {
5081   gfc_se se;
5082   gfc_se lse;
5083   gfc_ss *rss;
5084   stmtblock_t block;
5085   tree tmp;
5086
5087   gfc_start_block (&block);
5088
5089   if (cm->attr.pointer)
5090     {
5091       gfc_init_se (&se, NULL);
5092       /* Pointer component.  */
5093       if (cm->attr.dimension)
5094         {
5095           /* Array pointer.  */
5096           if (expr->expr_type == EXPR_NULL)
5097             gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
5098           else
5099             {
5100               rss = gfc_walk_expr (expr);
5101               se.direct_byref = 1;
5102               se.expr = dest;
5103               gfc_conv_expr_descriptor (&se, expr, rss);
5104               gfc_add_block_to_block (&block, &se.pre);
5105               gfc_add_block_to_block (&block, &se.post);
5106             }
5107         }
5108       else
5109         {
5110           /* Scalar pointers.  */
5111           se.want_pointer = 1;
5112           gfc_conv_expr (&se, expr);
5113           gfc_add_block_to_block (&block, &se.pre);
5114           gfc_add_modify (&block, dest,
5115                                fold_convert (TREE_TYPE (dest), se.expr));
5116           gfc_add_block_to_block (&block, &se.post);
5117         }
5118     }
5119   else if (cm->ts.type == BT_CLASS && expr->expr_type == EXPR_NULL)
5120     {
5121       /* NULL initialization for CLASS components.  */
5122       tmp = gfc_trans_structure_assign (dest,
5123                                         gfc_class_null_initializer (&cm->ts));
5124       gfc_add_expr_to_block (&block, tmp);
5125     }
5126   else if (cm->attr.dimension && !cm->attr.proc_pointer)
5127     {
5128       if (cm->attr.allocatable && expr->expr_type == EXPR_NULL)
5129         gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
5130       else if (cm->attr.allocatable)
5131         {
5132           tmp = gfc_trans_alloc_subarray_assign (dest, cm, expr);
5133           gfc_add_expr_to_block (&block, tmp);
5134         }
5135       else
5136         {
5137           tmp = gfc_trans_subarray_assign (dest, cm, expr);
5138           gfc_add_expr_to_block (&block, tmp);
5139         }
5140     }
5141   else if (expr->ts.type == BT_DERIVED)
5142     {
5143       if (expr->expr_type != EXPR_STRUCTURE)
5144         {
5145           gfc_init_se (&se, NULL);
5146           gfc_conv_expr (&se, expr);
5147           gfc_add_block_to_block (&block, &se.pre);
5148           gfc_add_modify (&block, dest,
5149                                fold_convert (TREE_TYPE (dest), se.expr));
5150           gfc_add_block_to_block (&block, &se.post);
5151         }
5152       else
5153         {
5154           /* Nested constructors.  */
5155           tmp = gfc_trans_structure_assign (dest, expr);
5156           gfc_add_expr_to_block (&block, tmp);
5157         }
5158     }
5159   else
5160     {
5161       /* Scalar component.  */
5162       gfc_init_se (&se, NULL);
5163       gfc_init_se (&lse, NULL);
5164
5165       gfc_conv_expr (&se, expr);
5166       if (cm->ts.type == BT_CHARACTER)
5167         lse.string_length = cm->ts.u.cl->backend_decl;
5168       lse.expr = dest;
5169       tmp = gfc_trans_scalar_assign (&lse, &se, cm->ts, true, false, true);
5170       gfc_add_expr_to_block (&block, tmp);
5171     }
5172   return gfc_finish_block (&block);
5173 }
5174
5175 /* Assign a derived type constructor to a variable.  */
5176
5177 static tree
5178 gfc_trans_structure_assign (tree dest, gfc_expr * expr)
5179 {
5180   gfc_constructor *c;
5181   gfc_component *cm;
5182   stmtblock_t block;
5183   tree field;
5184   tree tmp;
5185
5186   gfc_start_block (&block);
5187   cm = expr->ts.u.derived->components;
5188
5189   if (expr->ts.u.derived->from_intmod == INTMOD_ISO_C_BINDING
5190       && (expr->ts.u.derived->intmod_sym_id == ISOCBINDING_PTR
5191           || expr->ts.u.derived->intmod_sym_id == ISOCBINDING_FUNPTR))
5192     {
5193       gfc_se se, lse;
5194
5195       gcc_assert (cm->backend_decl == NULL);
5196       gfc_init_se (&se, NULL);
5197       gfc_init_se (&lse, NULL);
5198       gfc_conv_expr (&se, gfc_constructor_first (expr->value.constructor)->expr);
5199       lse.expr = dest;
5200       gfc_add_modify (&block, lse.expr,
5201                       fold_convert (TREE_TYPE (lse.expr), se.expr));
5202
5203       return gfc_finish_block (&block);
5204     } 
5205
5206   for (c = gfc_constructor_first (expr->value.constructor);
5207        c; c = gfc_constructor_next (c), cm = cm->next)
5208     {
5209       /* Skip absent members in default initializers.  */
5210       if (!c->expr)
5211         continue;
5212
5213       field = cm->backend_decl;
5214       tmp = fold_build3_loc (input_location, COMPONENT_REF, TREE_TYPE (field),
5215                              dest, field, NULL_TREE);
5216       tmp = gfc_trans_subcomponent_assign (tmp, cm, c->expr);
5217       gfc_add_expr_to_block (&block, tmp);
5218     }
5219   return gfc_finish_block (&block);
5220 }
5221
5222 /* Build an expression for a constructor. If init is nonzero then
5223    this is part of a static variable initializer.  */
5224
5225 void
5226 gfc_conv_structure (gfc_se * se, gfc_expr * expr, int init)
5227 {
5228   gfc_constructor *c;
5229   gfc_component *cm;
5230   tree val;
5231   tree type;
5232   tree tmp;
5233   VEC(constructor_elt,gc) *v = NULL;
5234
5235   gcc_assert (se->ss == NULL);
5236   gcc_assert (expr->expr_type == EXPR_STRUCTURE);
5237   type = gfc_typenode_for_spec (&expr->ts);
5238
5239   if (!init)
5240     {
5241       /* Create a temporary variable and fill it in.  */
5242       se->expr = gfc_create_var (type, expr->ts.u.derived->name);
5243       tmp = gfc_trans_structure_assign (se->expr, expr);
5244       gfc_add_expr_to_block (&se->pre, tmp);
5245       return;
5246     }
5247
5248   cm = expr->ts.u.derived->components;
5249
5250   for (c = gfc_constructor_first (expr->value.constructor);
5251        c; c = gfc_constructor_next (c), cm = cm->next)
5252     {
5253       /* Skip absent members in default initializers and allocatable
5254          components.  Although the latter have a default initializer
5255          of EXPR_NULL,... by default, the static nullify is not needed
5256          since this is done every time we come into scope.  */
5257       if (!c->expr || (cm->attr.allocatable && cm->attr.flavor != FL_PROCEDURE))
5258         continue;
5259
5260       if (strcmp (cm->name, "_size") == 0)
5261         {
5262           val = TYPE_SIZE_UNIT (gfc_get_derived_type (cm->ts.u.derived));
5263           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, val);
5264         }
5265       else if (cm->initializer && cm->initializer->expr_type != EXPR_NULL
5266                && strcmp (cm->name, "_extends") == 0)
5267         {
5268           tree vtab;
5269           gfc_symbol *vtabs;
5270           vtabs = cm->initializer->symtree->n.sym;
5271           vtab = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtabs));
5272           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, vtab);
5273         }
5274       else
5275         {
5276           val = gfc_conv_initializer (c->expr, &cm->ts,
5277                                       TREE_TYPE (cm->backend_decl),
5278                                       cm->attr.dimension, cm->attr.pointer,
5279                                       cm->attr.proc_pointer);
5280
5281           /* Append it to the constructor list.  */
5282           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, val);
5283         }
5284     }
5285   se->expr = build_constructor (type, v);
5286   if (init) 
5287     TREE_CONSTANT (se->expr) = 1;
5288 }
5289
5290
5291 /* Translate a substring expression.  */
5292
5293 static void
5294 gfc_conv_substring_expr (gfc_se * se, gfc_expr * expr)
5295 {
5296   gfc_ref *ref;
5297
5298   ref = expr->ref;
5299
5300   gcc_assert (ref == NULL || ref->type == REF_SUBSTRING);
5301
5302   se->expr = gfc_build_wide_string_const (expr->ts.kind,
5303                                           expr->value.character.length,
5304                                           expr->value.character.string);
5305
5306   se->string_length = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (se->expr)));
5307   TYPE_STRING_FLAG (TREE_TYPE (se->expr)) = 1;
5308
5309   if (ref)
5310     gfc_conv_substring (se, ref, expr->ts.kind, NULL, &expr->where);
5311 }
5312
5313
5314 /* Entry point for expression translation.  Evaluates a scalar quantity.
5315    EXPR is the expression to be translated, and SE is the state structure if
5316    called from within the scalarized.  */
5317
5318 void
5319 gfc_conv_expr (gfc_se * se, gfc_expr * expr)
5320 {
5321   gfc_ss *ss;
5322
5323   ss = se->ss;
5324   if (ss && ss->info->expr == expr
5325       && (ss->info->type == GFC_SS_SCALAR
5326           || ss->info->type == GFC_SS_REFERENCE))
5327     {
5328       gfc_ss_info *ss_info;
5329
5330       ss_info = ss->info;
5331       /* Substitute a scalar expression evaluated outside the scalarization
5332          loop.  */
5333       se->expr = ss_info->data.scalar.value;
5334       if (ss_info->type == GFC_SS_REFERENCE)
5335         se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
5336       se->string_length = ss_info->string_length;
5337       gfc_advance_se_ss_chain (se);
5338       return;
5339     }
5340
5341   /* We need to convert the expressions for the iso_c_binding derived types.
5342      C_NULL_PTR and C_NULL_FUNPTR will be made EXPR_NULL, which evaluates to
5343      null_pointer_node.  C_PTR and C_FUNPTR are converted to match the
5344      typespec for the C_PTR and C_FUNPTR symbols, which has already been
5345      updated to be an integer with a kind equal to the size of a (void *).  */
5346   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
5347       && expr->ts.u.derived->attr.is_iso_c)
5348     {
5349       if (expr->expr_type == EXPR_VARIABLE
5350           && (expr->symtree->n.sym->intmod_sym_id == ISOCBINDING_NULL_PTR
5351               || expr->symtree->n.sym->intmod_sym_id
5352                  == ISOCBINDING_NULL_FUNPTR))
5353         {
5354           /* Set expr_type to EXPR_NULL, which will result in
5355              null_pointer_node being used below.  */
5356           expr->expr_type = EXPR_NULL;
5357         }
5358       else
5359         {
5360           /* Update the type/kind of the expression to be what the new
5361              type/kind are for the updated symbols of C_PTR/C_FUNPTR.  */
5362           expr->ts.type = expr->ts.u.derived->ts.type;
5363           expr->ts.f90_type = expr->ts.u.derived->ts.f90_type;
5364           expr->ts.kind = expr->ts.u.derived->ts.kind;
5365         }
5366     }
5367
5368   /* TODO: make this work for general class array expressions.  */
5369   if (expr->ts.type == BT_CLASS
5370         && expr->ref && expr->ref->type == REF_ARRAY)
5371     gfc_add_component_ref (expr, "_data");
5372
5373   switch (expr->expr_type)
5374     {
5375     case EXPR_OP:
5376       gfc_conv_expr_op (se, expr);
5377       break;
5378
5379     case EXPR_FUNCTION:
5380       gfc_conv_function_expr (se, expr);
5381       break;
5382
5383     case EXPR_CONSTANT:
5384       gfc_conv_constant (se, expr);
5385       break;
5386
5387     case EXPR_VARIABLE:
5388       gfc_conv_variable (se, expr);
5389       break;
5390
5391     case EXPR_NULL:
5392       se->expr = null_pointer_node;
5393       break;
5394
5395     case EXPR_SUBSTRING:
5396       gfc_conv_substring_expr (se, expr);
5397       break;
5398
5399     case EXPR_STRUCTURE:
5400       gfc_conv_structure (se, expr, 0);
5401       break;
5402
5403     case EXPR_ARRAY:
5404       gfc_conv_array_constructor_expr (se, expr);
5405       break;
5406
5407     default:
5408       gcc_unreachable ();
5409       break;
5410     }
5411 }
5412
5413 /* Like gfc_conv_expr_val, but the value is also suitable for use in the lhs
5414    of an assignment.  */
5415 void
5416 gfc_conv_expr_lhs (gfc_se * se, gfc_expr * expr)
5417 {
5418   gfc_conv_expr (se, expr);
5419   /* All numeric lvalues should have empty post chains.  If not we need to
5420      figure out a way of rewriting an lvalue so that it has no post chain.  */
5421   gcc_assert (expr->ts.type == BT_CHARACTER || !se->post.head);
5422 }
5423
5424 /* Like gfc_conv_expr, but the POST block is guaranteed to be empty for
5425    numeric expressions.  Used for scalar values where inserting cleanup code
5426    is inconvenient.  */
5427 void
5428 gfc_conv_expr_val (gfc_se * se, gfc_expr * expr)
5429 {
5430   tree val;
5431
5432   gcc_assert (expr->ts.type != BT_CHARACTER);
5433   gfc_conv_expr (se, expr);
5434   if (se->post.head)
5435     {
5436       val = gfc_create_var (TREE_TYPE (se->expr), NULL);
5437       gfc_add_modify (&se->pre, val, se->expr);
5438       se->expr = val;
5439       gfc_add_block_to_block (&se->pre, &se->post);
5440     }
5441 }
5442
5443 /* Helper to translate an expression and convert it to a particular type.  */
5444 void
5445 gfc_conv_expr_type (gfc_se * se, gfc_expr * expr, tree type)
5446 {
5447   gfc_conv_expr_val (se, expr);
5448   se->expr = convert (type, se->expr);
5449 }
5450
5451
5452 /* Converts an expression so that it can be passed by reference.  Scalar
5453    values only.  */
5454
5455 void
5456 gfc_conv_expr_reference (gfc_se * se, gfc_expr * expr)
5457 {
5458   gfc_ss *ss;
5459   tree var;
5460
5461   ss = se->ss;
5462   if (ss && ss->info->expr == expr
5463       && ss->info->type == GFC_SS_REFERENCE)
5464     {
5465       /* Returns a reference to the scalar evaluated outside the loop
5466          for this case.  */
5467       gfc_conv_expr (se, expr);
5468       return;
5469     }
5470
5471   if (expr->ts.type == BT_CHARACTER)
5472     {
5473       gfc_conv_expr (se, expr);
5474       gfc_conv_string_parameter (se);
5475       return;
5476     }
5477
5478   if (expr->expr_type == EXPR_VARIABLE)
5479     {
5480       se->want_pointer = 1;
5481       gfc_conv_expr (se, expr);
5482       if (se->post.head)
5483         {
5484           var = gfc_create_var (TREE_TYPE (se->expr), NULL);
5485           gfc_add_modify (&se->pre, var, se->expr);
5486           gfc_add_block_to_block (&se->pre, &se->post);
5487           se->expr = var;
5488         }
5489       return;
5490     }
5491
5492   if (expr->expr_type == EXPR_FUNCTION
5493       && ((expr->value.function.esym
5494            && expr->value.function.esym->result->attr.pointer
5495            && !expr->value.function.esym->result->attr.dimension)
5496           || (!expr->value.function.esym
5497               && expr->symtree->n.sym->attr.pointer
5498               && !expr->symtree->n.sym->attr.dimension)))
5499     {
5500       se->want_pointer = 1;
5501       gfc_conv_expr (se, expr);
5502       var = gfc_create_var (TREE_TYPE (se->expr), NULL);
5503       gfc_add_modify (&se->pre, var, se->expr);
5504       se->expr = var;
5505       return;
5506     }
5507
5508   gfc_conv_expr (se, expr);
5509
5510   /* Create a temporary var to hold the value.  */
5511   if (TREE_CONSTANT (se->expr))
5512     {
5513       tree tmp = se->expr;
5514       STRIP_TYPE_NOPS (tmp);
5515       var = build_decl (input_location,
5516                         CONST_DECL, NULL, TREE_TYPE (tmp));
5517       DECL_INITIAL (var) = tmp;
5518       TREE_STATIC (var) = 1;
5519       pushdecl (var);
5520     }
5521   else
5522     {
5523       var = gfc_create_var (TREE_TYPE (se->expr), NULL);
5524       gfc_add_modify (&se->pre, var, se->expr);
5525     }
5526   gfc_add_block_to_block (&se->pre, &se->post);
5527
5528   /* Take the address of that value.  */
5529   se->expr = gfc_build_addr_expr (NULL_TREE, var);
5530 }
5531
5532
5533 tree
5534 gfc_trans_pointer_assign (gfc_code * code)
5535 {
5536   return gfc_trans_pointer_assignment (code->expr1, code->expr2);
5537 }
5538
5539
5540 /* Generate code for a pointer assignment.  */
5541
5542 tree
5543 gfc_trans_pointer_assignment (gfc_expr * expr1, gfc_expr * expr2)
5544 {
5545   gfc_se lse;
5546   gfc_se rse;
5547   gfc_ss *lss;
5548   gfc_ss *rss;
5549   stmtblock_t block;
5550   tree desc;
5551   tree tmp;
5552   tree decl;
5553
5554   gfc_start_block (&block);
5555
5556   gfc_init_se (&lse, NULL);
5557
5558   lss = gfc_walk_expr (expr1);
5559   rss = gfc_walk_expr (expr2);
5560   if (lss == gfc_ss_terminator)
5561     {
5562       /* Scalar pointers.  */
5563       lse.want_pointer = 1;
5564       gfc_conv_expr (&lse, expr1);
5565       gcc_assert (rss == gfc_ss_terminator);
5566       gfc_init_se (&rse, NULL);
5567       rse.want_pointer = 1;
5568       gfc_conv_expr (&rse, expr2);
5569
5570       if (expr1->symtree->n.sym->attr.proc_pointer
5571           && expr1->symtree->n.sym->attr.dummy)
5572         lse.expr = build_fold_indirect_ref_loc (input_location,
5573                                             lse.expr);
5574
5575       if (expr2->symtree && expr2->symtree->n.sym->attr.proc_pointer
5576           && expr2->symtree->n.sym->attr.dummy)
5577         rse.expr = build_fold_indirect_ref_loc (input_location,
5578                                             rse.expr);
5579
5580       gfc_add_block_to_block (&block, &lse.pre);
5581       gfc_add_block_to_block (&block, &rse.pre);
5582
5583       /* Check character lengths if character expression.  The test is only
5584          really added if -fbounds-check is enabled.  Exclude deferred
5585          character length lefthand sides.  */
5586       if (expr1->ts.type == BT_CHARACTER && expr2->expr_type != EXPR_NULL
5587           && !(expr1->ts.deferred
5588                         && (TREE_CODE (lse.string_length) == VAR_DECL))
5589           && !expr1->symtree->n.sym->attr.proc_pointer
5590           && !gfc_is_proc_ptr_comp (expr1, NULL))
5591         {
5592           gcc_assert (expr2->ts.type == BT_CHARACTER);
5593           gcc_assert (lse.string_length && rse.string_length);
5594           gfc_trans_same_strlen_check ("pointer assignment", &expr1->where,
5595                                        lse.string_length, rse.string_length,
5596                                        &block);
5597         }
5598
5599       /* The assignment to an deferred character length sets the string
5600          length to that of the rhs.  */
5601       if (expr1->ts.deferred && (TREE_CODE (lse.string_length) == VAR_DECL))
5602         {
5603           if (expr2->expr_type != EXPR_NULL)
5604             gfc_add_modify (&block, lse.string_length, rse.string_length);
5605           else
5606             gfc_add_modify (&block, lse.string_length,
5607                             build_int_cst (gfc_charlen_type_node, 0));
5608         }
5609
5610       gfc_add_modify (&block, lse.expr,
5611                            fold_convert (TREE_TYPE (lse.expr), rse.expr));
5612
5613       gfc_add_block_to_block (&block, &rse.post);
5614       gfc_add_block_to_block (&block, &lse.post);
5615     }
5616   else
5617     {
5618       gfc_ref* remap;
5619       bool rank_remap;
5620       tree strlen_lhs;
5621       tree strlen_rhs = NULL_TREE;
5622
5623       /* Array pointer.  Find the last reference on the LHS and if it is an
5624          array section ref, we're dealing with bounds remapping.  In this case,
5625          set it to AR_FULL so that gfc_conv_expr_descriptor does
5626          not see it and process the bounds remapping afterwards explicitely.  */
5627       for (remap = expr1->ref; remap; remap = remap->next)
5628         if (!remap->next && remap->type == REF_ARRAY
5629             && remap->u.ar.type == AR_SECTION)
5630           {  
5631             remap->u.ar.type = AR_FULL;
5632             break;
5633           }
5634       rank_remap = (remap && remap->u.ar.end[0]);
5635
5636       gfc_conv_expr_descriptor (&lse, expr1, lss);
5637       strlen_lhs = lse.string_length;
5638       desc = lse.expr;
5639
5640       if (expr2->expr_type == EXPR_NULL)
5641         {
5642           /* Just set the data pointer to null.  */
5643           gfc_conv_descriptor_data_set (&lse.pre, lse.expr, null_pointer_node);
5644         }
5645       else if (rank_remap)
5646         {
5647           /* If we are rank-remapping, just get the RHS's descriptor and
5648              process this later on.  */
5649           gfc_init_se (&rse, NULL);
5650           rse.direct_byref = 1;
5651           rse.byref_noassign = 1;
5652           gfc_conv_expr_descriptor (&rse, expr2, rss);
5653           strlen_rhs = rse.string_length;
5654         }
5655       else if (expr2->expr_type == EXPR_VARIABLE)
5656         {
5657           /* Assign directly to the LHS's descriptor.  */
5658           lse.direct_byref = 1;
5659           gfc_conv_expr_descriptor (&lse, expr2, rss);
5660           strlen_rhs = lse.string_length;
5661
5662           /* If this is a subreference array pointer assignment, use the rhs
5663              descriptor element size for the lhs span.  */
5664           if (expr1->symtree->n.sym->attr.subref_array_pointer)
5665             {
5666               decl = expr1->symtree->n.sym->backend_decl;
5667               gfc_init_se (&rse, NULL);
5668               rse.descriptor_only = 1;
5669               gfc_conv_expr (&rse, expr2);
5670               tmp = gfc_get_element_type (TREE_TYPE (rse.expr));
5671               tmp = fold_convert (gfc_array_index_type, size_in_bytes (tmp));
5672               if (!INTEGER_CST_P (tmp))
5673                 gfc_add_block_to_block (&lse.post, &rse.pre);
5674               gfc_add_modify (&lse.post, GFC_DECL_SPAN(decl), tmp);
5675             }
5676         }
5677       else
5678         {
5679           /* Assign to a temporary descriptor and then copy that
5680              temporary to the pointer.  */
5681           tmp = gfc_create_var (TREE_TYPE (desc), "ptrtemp");
5682
5683           lse.expr = tmp;
5684           lse.direct_byref = 1;
5685           gfc_conv_expr_descriptor (&lse, expr2, rss);
5686           strlen_rhs = lse.string_length;
5687           gfc_add_modify (&lse.pre, desc, tmp);
5688         }
5689
5690       gfc_add_block_to_block (&block, &lse.pre);
5691       if (rank_remap)
5692         gfc_add_block_to_block (&block, &rse.pre);
5693
5694       /* If we do bounds remapping, update LHS descriptor accordingly.  */
5695       if (remap)
5696         {
5697           int dim;
5698           gcc_assert (remap->u.ar.dimen == expr1->rank);
5699
5700           if (rank_remap)
5701             {
5702               /* Do rank remapping.  We already have the RHS's descriptor
5703                  converted in rse and now have to build the correct LHS
5704                  descriptor for it.  */
5705
5706               tree dtype, data;
5707               tree offs, stride;
5708               tree lbound, ubound;
5709
5710               /* Set dtype.  */
5711               dtype = gfc_conv_descriptor_dtype (desc);
5712               tmp = gfc_get_dtype (TREE_TYPE (desc));
5713               gfc_add_modify (&block, dtype, tmp);
5714
5715               /* Copy data pointer.  */
5716               data = gfc_conv_descriptor_data_get (rse.expr);
5717               gfc_conv_descriptor_data_set (&block, desc, data);
5718
5719               /* Copy offset but adjust it such that it would correspond
5720                  to a lbound of zero.  */
5721               offs = gfc_conv_descriptor_offset_get (rse.expr);
5722               for (dim = 0; dim < expr2->rank; ++dim)
5723                 {
5724                   stride = gfc_conv_descriptor_stride_get (rse.expr,
5725                                                            gfc_rank_cst[dim]);
5726                   lbound = gfc_conv_descriptor_lbound_get (rse.expr,
5727                                                            gfc_rank_cst[dim]);
5728                   tmp = fold_build2_loc (input_location, MULT_EXPR,
5729                                          gfc_array_index_type, stride, lbound);
5730                   offs = fold_build2_loc (input_location, PLUS_EXPR,
5731                                           gfc_array_index_type, offs, tmp);
5732                 }
5733               gfc_conv_descriptor_offset_set (&block, desc, offs);
5734
5735               /* Set the bounds as declared for the LHS and calculate strides as
5736                  well as another offset update accordingly.  */
5737               stride = gfc_conv_descriptor_stride_get (rse.expr,
5738                                                        gfc_rank_cst[0]);
5739               for (dim = 0; dim < expr1->rank; ++dim)
5740                 {
5741                   gfc_se lower_se;
5742                   gfc_se upper_se;
5743
5744                   gcc_assert (remap->u.ar.start[dim] && remap->u.ar.end[dim]);
5745
5746                   /* Convert declared bounds.  */
5747                   gfc_init_se (&lower_se, NULL);
5748                   gfc_init_se (&upper_se, NULL);
5749                   gfc_conv_expr (&lower_se, remap->u.ar.start[dim]);
5750                   gfc_conv_expr (&upper_se, remap->u.ar.end[dim]);
5751
5752                   gfc_add_block_to_block (&block, &lower_se.pre);
5753                   gfc_add_block_to_block (&block, &upper_se.pre);
5754
5755                   lbound = fold_convert (gfc_array_index_type, lower_se.expr);
5756                   ubound = fold_convert (gfc_array_index_type, upper_se.expr);
5757
5758                   lbound = gfc_evaluate_now (lbound, &block);
5759                   ubound = gfc_evaluate_now (ubound, &block);
5760
5761                   gfc_add_block_to_block (&block, &lower_se.post);
5762                   gfc_add_block_to_block (&block, &upper_se.post);
5763
5764                   /* Set bounds in descriptor.  */
5765                   gfc_conv_descriptor_lbound_set (&block, desc,
5766                                                   gfc_rank_cst[dim], lbound);
5767                   gfc_conv_descriptor_ubound_set (&block, desc,
5768                                                   gfc_rank_cst[dim], ubound);
5769
5770                   /* Set stride.  */
5771                   stride = gfc_evaluate_now (stride, &block);
5772                   gfc_conv_descriptor_stride_set (&block, desc,
5773                                                   gfc_rank_cst[dim], stride);
5774
5775                   /* Update offset.  */
5776                   offs = gfc_conv_descriptor_offset_get (desc);
5777                   tmp = fold_build2_loc (input_location, MULT_EXPR,
5778                                          gfc_array_index_type, lbound, stride);
5779                   offs = fold_build2_loc (input_location, MINUS_EXPR,
5780                                           gfc_array_index_type, offs, tmp);
5781                   offs = gfc_evaluate_now (offs, &block);
5782                   gfc_conv_descriptor_offset_set (&block, desc, offs);
5783
5784                   /* Update stride.  */
5785                   tmp = gfc_conv_array_extent_dim (lbound, ubound, NULL);
5786                   stride = fold_build2_loc (input_location, MULT_EXPR,
5787                                             gfc_array_index_type, stride, tmp);
5788                 }
5789             }
5790           else
5791             {
5792               /* Bounds remapping.  Just shift the lower bounds.  */
5793
5794               gcc_assert (expr1->rank == expr2->rank);
5795
5796               for (dim = 0; dim < remap->u.ar.dimen; ++dim)
5797                 {
5798                   gfc_se lbound_se;
5799
5800                   gcc_assert (remap->u.ar.start[dim]);
5801                   gcc_assert (!remap->u.ar.end[dim]);
5802                   gfc_init_se (&lbound_se, NULL);
5803                   gfc_conv_expr (&lbound_se, remap->u.ar.start[dim]);
5804
5805                   gfc_add_block_to_block (&block, &lbound_se.pre);
5806                   gfc_conv_shift_descriptor_lbound (&block, desc,
5807                                                     dim, lbound_se.expr);
5808                   gfc_add_block_to_block (&block, &lbound_se.post);
5809                 }
5810             }
5811         }
5812
5813       /* Check string lengths if applicable.  The check is only really added
5814          to the output code if -fbounds-check is enabled.  */
5815       if (expr1->ts.type == BT_CHARACTER && expr2->expr_type != EXPR_NULL)
5816         {
5817           gcc_assert (expr2->ts.type == BT_CHARACTER);
5818           gcc_assert (strlen_lhs && strlen_rhs);
5819           gfc_trans_same_strlen_check ("pointer assignment", &expr1->where,
5820                                        strlen_lhs, strlen_rhs, &block);
5821         }
5822
5823       /* If rank remapping was done, check with -fcheck=bounds that
5824          the target is at least as large as the pointer.  */
5825       if (rank_remap && (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS))
5826         {
5827           tree lsize, rsize;
5828           tree fault;
5829           const char* msg;
5830
5831           lsize = gfc_conv_descriptor_size (lse.expr, expr1->rank);
5832           rsize = gfc_conv_descriptor_size (rse.expr, expr2->rank);
5833
5834           lsize = gfc_evaluate_now (lsize, &block);
5835           rsize = gfc_evaluate_now (rsize, &block);
5836           fault = fold_build2_loc (input_location, LT_EXPR, boolean_type_node,
5837                                    rsize, lsize);
5838
5839           msg = _("Target of rank remapping is too small (%ld < %ld)");
5840           gfc_trans_runtime_check (true, false, fault, &block, &expr2->where,
5841                                    msg, rsize, lsize);
5842         }
5843
5844       gfc_add_block_to_block (&block, &lse.post);
5845       if (rank_remap)
5846         gfc_add_block_to_block (&block, &rse.post);
5847     }
5848
5849   return gfc_finish_block (&block);
5850 }
5851
5852
5853 /* Makes sure se is suitable for passing as a function string parameter.  */
5854 /* TODO: Need to check all callers of this function.  It may be abused.  */
5855
5856 void
5857 gfc_conv_string_parameter (gfc_se * se)
5858 {
5859   tree type;
5860
5861   if (TREE_CODE (se->expr) == STRING_CST)
5862     {
5863       type = TREE_TYPE (TREE_TYPE (se->expr));
5864       se->expr = gfc_build_addr_expr (build_pointer_type (type), se->expr);
5865       return;
5866     }
5867
5868   if (TYPE_STRING_FLAG (TREE_TYPE (se->expr)))
5869     {
5870       if (TREE_CODE (se->expr) != INDIRECT_REF)
5871         {
5872           type = TREE_TYPE (se->expr);
5873           se->expr = gfc_build_addr_expr (build_pointer_type (type), se->expr);
5874         }
5875       else
5876         {
5877           type = gfc_get_character_type_len (gfc_default_character_kind,
5878                                              se->string_length);
5879           type = build_pointer_type (type);
5880           se->expr = gfc_build_addr_expr (type, se->expr);
5881         }
5882     }
5883
5884   gcc_assert (POINTER_TYPE_P (TREE_TYPE (se->expr)));
5885 }
5886
5887
5888 /* Generate code for assignment of scalar variables.  Includes character
5889    strings and derived types with allocatable components.
5890    If you know that the LHS has no allocations, set dealloc to false.  */
5891
5892 tree
5893 gfc_trans_scalar_assign (gfc_se * lse, gfc_se * rse, gfc_typespec ts,
5894                          bool l_is_temp, bool r_is_var, bool dealloc)
5895 {
5896   stmtblock_t block;
5897   tree tmp;
5898   tree cond;
5899
5900   gfc_init_block (&block);
5901
5902   if (ts.type == BT_CHARACTER)
5903     {
5904       tree rlen = NULL;
5905       tree llen = NULL;
5906
5907       if (lse->string_length != NULL_TREE)
5908         {
5909           gfc_conv_string_parameter (lse);
5910           gfc_add_block_to_block (&block, &lse->pre);
5911           llen = lse->string_length;
5912         }
5913
5914       if (rse->string_length != NULL_TREE)
5915         {
5916           gcc_assert (rse->string_length != NULL_TREE);
5917           gfc_conv_string_parameter (rse);
5918           gfc_add_block_to_block (&block, &rse->pre);
5919           rlen = rse->string_length;
5920         }
5921
5922       gfc_trans_string_copy (&block, llen, lse->expr, ts.kind, rlen,
5923                              rse->expr, ts.kind);
5924     }
5925   else if (ts.type == BT_DERIVED && ts.u.derived->attr.alloc_comp)
5926     {
5927       cond = NULL_TREE;
5928         
5929       /* Are the rhs and the lhs the same?  */
5930       if (r_is_var)
5931         {
5932           cond = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
5933                                   gfc_build_addr_expr (NULL_TREE, lse->expr),
5934                                   gfc_build_addr_expr (NULL_TREE, rse->expr));
5935           cond = gfc_evaluate_now (cond, &lse->pre);
5936         }
5937
5938       /* Deallocate the lhs allocated components as long as it is not
5939          the same as the rhs.  This must be done following the assignment
5940          to prevent deallocating data that could be used in the rhs
5941          expression.  */
5942       if (!l_is_temp && dealloc)
5943         {
5944           tmp = gfc_evaluate_now (lse->expr, &lse->pre);
5945           tmp = gfc_deallocate_alloc_comp (ts.u.derived, tmp, 0);
5946           if (r_is_var)
5947             tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
5948                             tmp);
5949           gfc_add_expr_to_block (&lse->post, tmp);
5950         }
5951
5952       gfc_add_block_to_block (&block, &rse->pre);
5953       gfc_add_block_to_block (&block, &lse->pre);
5954
5955       gfc_add_modify (&block, lse->expr,
5956                            fold_convert (TREE_TYPE (lse->expr), rse->expr));
5957
5958       /* Do a deep copy if the rhs is a variable, if it is not the
5959          same as the lhs.  */
5960       if (r_is_var)
5961         {
5962           tmp = gfc_copy_alloc_comp (ts.u.derived, rse->expr, lse->expr, 0);
5963           tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
5964                           tmp);
5965           gfc_add_expr_to_block (&block, tmp);
5966         }
5967     }
5968   else if (ts.type == BT_DERIVED || ts.type == BT_CLASS)
5969     {
5970       gfc_add_block_to_block (&block, &lse->pre);
5971       gfc_add_block_to_block (&block, &rse->pre);
5972       tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
5973                              TREE_TYPE (lse->expr), rse->expr);
5974       gfc_add_modify (&block, lse->expr, tmp);
5975     }
5976   else
5977     {
5978       gfc_add_block_to_block (&block, &lse->pre);
5979       gfc_add_block_to_block (&block, &rse->pre);
5980
5981       gfc_add_modify (&block, lse->expr,
5982                       fold_convert (TREE_TYPE (lse->expr), rse->expr));
5983     }
5984
5985   gfc_add_block_to_block (&block, &lse->post);
5986   gfc_add_block_to_block (&block, &rse->post);
5987
5988   return gfc_finish_block (&block);
5989 }
5990
5991
5992 /* There are quite a lot of restrictions on the optimisation in using an
5993    array function assign without a temporary.  */
5994
5995 static bool
5996 arrayfunc_assign_needs_temporary (gfc_expr * expr1, gfc_expr * expr2)
5997 {
5998   gfc_ref * ref;
5999   bool seen_array_ref;
6000   bool c = false;
6001   gfc_symbol *sym = expr1->symtree->n.sym;
6002
6003   /* The caller has already checked rank>0 and expr_type == EXPR_FUNCTION.  */
6004   if (expr2->value.function.isym && !gfc_is_intrinsic_libcall (expr2))
6005     return true;
6006
6007   /* Elemental functions are scalarized so that they don't need a
6008      temporary in gfc_trans_assignment_1, so return a true.  Otherwise,
6009      they would need special treatment in gfc_trans_arrayfunc_assign.  */
6010   if (expr2->value.function.esym != NULL
6011       && expr2->value.function.esym->attr.elemental)
6012     return true;
6013
6014   /* Need a temporary if rhs is not FULL or a contiguous section.  */
6015   if (expr1->ref && !(gfc_full_array_ref_p (expr1->ref, &c) || c))
6016     return true;
6017
6018   /* Need a temporary if EXPR1 can't be expressed as a descriptor.  */
6019   if (gfc_ref_needs_temporary_p (expr1->ref))
6020     return true;
6021
6022   /* Functions returning pointers or allocatables need temporaries.  */
6023   c = expr2->value.function.esym
6024       ? (expr2->value.function.esym->attr.pointer 
6025          || expr2->value.function.esym->attr.allocatable)
6026       : (expr2->symtree->n.sym->attr.pointer
6027          || expr2->symtree->n.sym->attr.allocatable);
6028   if (c)
6029     return true;
6030
6031   /* Character array functions need temporaries unless the
6032      character lengths are the same.  */
6033   if (expr2->ts.type == BT_CHARACTER && expr2->rank > 0)
6034     {
6035       if (expr1->ts.u.cl->length == NULL
6036             || expr1->ts.u.cl->length->expr_type != EXPR_CONSTANT)
6037         return true;
6038
6039       if (expr2->ts.u.cl->length == NULL
6040             || expr2->ts.u.cl->length->expr_type != EXPR_CONSTANT)
6041         return true;
6042
6043       if (mpz_cmp (expr1->ts.u.cl->length->value.integer,
6044                      expr2->ts.u.cl->length->value.integer) != 0)
6045         return true;
6046     }
6047
6048   /* Check that no LHS component references appear during an array
6049      reference. This is needed because we do not have the means to
6050      span any arbitrary stride with an array descriptor. This check
6051      is not needed for the rhs because the function result has to be
6052      a complete type.  */
6053   seen_array_ref = false;
6054   for (ref = expr1->ref; ref; ref = ref->next)
6055     {
6056       if (ref->type == REF_ARRAY)
6057         seen_array_ref= true;
6058       else if (ref->type == REF_COMPONENT && seen_array_ref)
6059         return true;
6060     }
6061
6062   /* Check for a dependency.  */
6063   if (gfc_check_fncall_dependency (expr1, INTENT_OUT,
6064                                    expr2->value.function.esym,
6065                                    expr2->value.function.actual,
6066                                    NOT_ELEMENTAL))
6067     return true;
6068
6069   /* If we have reached here with an intrinsic function, we do not
6070      need a temporary except in the particular case that reallocation
6071      on assignment is active and the lhs is allocatable and a target.  */
6072   if (expr2->value.function.isym)
6073     return (gfc_option.flag_realloc_lhs
6074               && sym->attr.allocatable
6075               && sym->attr.target);
6076
6077   /* If the LHS is a dummy, we need a temporary if it is not
6078      INTENT(OUT).  */
6079   if (sym->attr.dummy && sym->attr.intent != INTENT_OUT)
6080     return true;
6081
6082   /* If the lhs has been host_associated, is in common, a pointer or is
6083      a target and the function is not using a RESULT variable, aliasing
6084      can occur and a temporary is needed.  */
6085   if ((sym->attr.host_assoc
6086            || sym->attr.in_common
6087            || sym->attr.pointer
6088            || sym->attr.cray_pointee
6089            || sym->attr.target)
6090         && expr2->symtree != NULL
6091         && expr2->symtree->n.sym == expr2->symtree->n.sym->result)
6092     return true;
6093
6094   /* A PURE function can unconditionally be called without a temporary.  */
6095   if (expr2->value.function.esym != NULL
6096       && expr2->value.function.esym->attr.pure)
6097     return false;
6098
6099   /* Implicit_pure functions are those which could legally be declared
6100      to be PURE.  */
6101   if (expr2->value.function.esym != NULL
6102       && expr2->value.function.esym->attr.implicit_pure)
6103     return false;
6104
6105   if (!sym->attr.use_assoc
6106         && !sym->attr.in_common
6107         && !sym->attr.pointer
6108         && !sym->attr.target
6109         && !sym->attr.cray_pointee
6110         && expr2->value.function.esym)
6111     {
6112       /* A temporary is not needed if the function is not contained and
6113          the variable is local or host associated and not a pointer or
6114          a target. */
6115       if (!expr2->value.function.esym->attr.contained)
6116         return false;
6117
6118       /* A temporary is not needed if the lhs has never been host
6119          associated and the procedure is contained.  */
6120       else if (!sym->attr.host_assoc)
6121         return false;
6122
6123       /* A temporary is not needed if the variable is local and not
6124          a pointer, a target or a result.  */
6125       if (sym->ns->parent
6126             && expr2->value.function.esym->ns == sym->ns->parent)
6127         return false;
6128     }
6129
6130   /* Default to temporary use.  */
6131   return true;
6132 }
6133
6134
6135 /* Provide the loop info so that the lhs descriptor can be built for
6136    reallocatable assignments from extrinsic function calls.  */
6137
6138 static void
6139 realloc_lhs_loop_for_fcn_call (gfc_se *se, locus *where, gfc_ss **ss,
6140                                gfc_loopinfo *loop)
6141 {
6142   /* Signal that the function call should not be made by
6143      gfc_conv_loop_setup. */
6144   se->ss->is_alloc_lhs = 1;
6145   gfc_init_loopinfo (loop);
6146   gfc_add_ss_to_loop (loop, *ss);
6147   gfc_add_ss_to_loop (loop, se->ss);
6148   gfc_conv_ss_startstride (loop);
6149   gfc_conv_loop_setup (loop, where);
6150   gfc_copy_loopinfo_to_se (se, loop);
6151   gfc_add_block_to_block (&se->pre, &loop->pre);
6152   gfc_add_block_to_block (&se->pre, &loop->post);
6153   se->ss->is_alloc_lhs = 0;
6154 }
6155
6156
6157 /* For Assignment to a reallocatable lhs from intrinsic functions,
6158    replace the se.expr (ie. the result) with a temporary descriptor.
6159    Null the data field so that the library allocates space for the
6160    result. Free the data of the original descriptor after the function,
6161    in case it appears in an argument expression and transfer the
6162    result to the original descriptor.  */
6163
6164 static void
6165 fcncall_realloc_result (gfc_se *se, int rank)
6166 {
6167   tree desc;
6168   tree res_desc;
6169   tree tmp;
6170   tree offset;
6171   int n;
6172
6173   /* Use the allocation done by the library.  Substitute the lhs
6174      descriptor with a copy, whose data field is nulled.*/
6175   desc = build_fold_indirect_ref_loc (input_location, se->expr);
6176   /* Unallocated, the descriptor does not have a dtype.  */
6177   tmp = gfc_conv_descriptor_dtype (desc);
6178   gfc_add_modify (&se->pre, tmp, gfc_get_dtype (TREE_TYPE (desc)));
6179   res_desc = gfc_evaluate_now (desc, &se->pre);
6180   gfc_conv_descriptor_data_set (&se->pre, res_desc, null_pointer_node);
6181   se->expr = gfc_build_addr_expr (TREE_TYPE (se->expr), res_desc);
6182
6183   /* Free the lhs after the function call and copy the result to
6184      the lhs descriptor.  */
6185   tmp = gfc_conv_descriptor_data_get (desc);
6186   tmp = gfc_call_free (fold_convert (pvoid_type_node, tmp));
6187   gfc_add_expr_to_block (&se->post, tmp);
6188   gfc_add_modify (&se->post, desc, res_desc);
6189
6190   offset = gfc_index_zero_node;
6191   tmp = gfc_index_one_node;
6192   /* Now reset the bounds from zero based to unity based.  */
6193   for (n = 0 ; n < rank; n++)
6194     {
6195       /* Accumulate the offset.  */
6196       offset = fold_build2_loc (input_location, MINUS_EXPR,
6197                                 gfc_array_index_type,
6198                                 offset, tmp);
6199       /* Now do the bounds.  */
6200       gfc_conv_descriptor_offset_set (&se->post, desc, tmp);
6201       tmp = gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[n]);
6202       tmp = fold_build2_loc (input_location, PLUS_EXPR,
6203                              gfc_array_index_type,
6204                              tmp, gfc_index_one_node);
6205       gfc_conv_descriptor_lbound_set (&se->post, desc,
6206                                       gfc_rank_cst[n],
6207                                       gfc_index_one_node);
6208       gfc_conv_descriptor_ubound_set (&se->post, desc,
6209                                       gfc_rank_cst[n], tmp);
6210
6211       /* The extent for the next contribution to offset.  */
6212       tmp = fold_build2_loc (input_location, MINUS_EXPR,
6213                              gfc_array_index_type,
6214                              gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[n]),
6215                              gfc_conv_descriptor_lbound_get (desc, gfc_rank_cst[n]));
6216       tmp = fold_build2_loc (input_location, PLUS_EXPR,
6217                              gfc_array_index_type,
6218                              tmp, gfc_index_one_node);
6219     }
6220   gfc_conv_descriptor_offset_set (&se->post, desc, offset);
6221 }
6222
6223
6224
6225 /* Try to translate array(:) = func (...), where func is a transformational
6226    array function, without using a temporary.  Returns NULL if this isn't the
6227    case.  */
6228
6229 static tree
6230 gfc_trans_arrayfunc_assign (gfc_expr * expr1, gfc_expr * expr2)
6231 {
6232   gfc_se se;
6233   gfc_ss *ss;
6234   gfc_component *comp = NULL;
6235   gfc_loopinfo loop;
6236
6237   if (arrayfunc_assign_needs_temporary (expr1, expr2))
6238     return NULL;
6239
6240   /* The frontend doesn't seem to bother filling in expr->symtree for intrinsic
6241      functions.  */
6242   gcc_assert (expr2->value.function.isym
6243               || (gfc_is_proc_ptr_comp (expr2, &comp)
6244                   && comp && comp->attr.dimension)
6245               || (!comp && gfc_return_by_reference (expr2->value.function.esym)
6246                   && expr2->value.function.esym->result->attr.dimension));
6247
6248   ss = gfc_walk_expr (expr1);
6249   gcc_assert (ss != gfc_ss_terminator);
6250   gfc_init_se (&se, NULL);
6251   gfc_start_block (&se.pre);
6252   se.want_pointer = 1;
6253
6254   gfc_conv_array_parameter (&se, expr1, ss, false, NULL, NULL, NULL);
6255
6256   if (expr1->ts.type == BT_DERIVED
6257         && expr1->ts.u.derived->attr.alloc_comp)
6258     {
6259       tree tmp;
6260       tmp = gfc_deallocate_alloc_comp (expr1->ts.u.derived, se.expr,
6261                                        expr1->rank);
6262       gfc_add_expr_to_block (&se.pre, tmp);
6263     }
6264
6265   se.direct_byref = 1;
6266   se.ss = gfc_walk_expr (expr2);
6267   gcc_assert (se.ss != gfc_ss_terminator);
6268
6269   /* Reallocate on assignment needs the loopinfo for extrinsic functions.
6270      This is signalled to gfc_conv_procedure_call by setting is_alloc_lhs.
6271      Clearly, this cannot be done for an allocatable function result, since
6272      the shape of the result is unknown and, in any case, the function must
6273      correctly take care of the reallocation internally. For intrinsic
6274      calls, the array data is freed and the library takes care of allocation.
6275      TODO: Add logic of trans-array.c: gfc_alloc_allocatable_for_assignment
6276      to the library.  */    
6277   if (gfc_option.flag_realloc_lhs
6278         && gfc_is_reallocatable_lhs (expr1)
6279         && !gfc_expr_attr (expr1).codimension
6280         && !gfc_is_coindexed (expr1)
6281         && !(expr2->value.function.esym
6282             && expr2->value.function.esym->result->attr.allocatable))
6283     {
6284       if (!expr2->value.function.isym)
6285         {
6286           realloc_lhs_loop_for_fcn_call (&se, &expr1->where, &ss, &loop);
6287           ss->is_alloc_lhs = 1;
6288         }
6289       else
6290         fcncall_realloc_result (&se, expr1->rank);
6291     }
6292
6293   gfc_conv_function_expr (&se, expr2);
6294   gfc_add_block_to_block (&se.pre, &se.post);
6295
6296   return gfc_finish_block (&se.pre);
6297 }
6298
6299
6300 /* Try to efficiently translate array(:) = 0.  Return NULL if this
6301    can't be done.  */
6302
6303 static tree
6304 gfc_trans_zero_assign (gfc_expr * expr)
6305 {
6306   tree dest, len, type;
6307   tree tmp;
6308   gfc_symbol *sym;
6309
6310   sym = expr->symtree->n.sym;
6311   dest = gfc_get_symbol_decl (sym);
6312
6313   type = TREE_TYPE (dest);
6314   if (POINTER_TYPE_P (type))
6315     type = TREE_TYPE (type);
6316   if (!GFC_ARRAY_TYPE_P (type))
6317     return NULL_TREE;
6318
6319   /* Determine the length of the array.  */
6320   len = GFC_TYPE_ARRAY_SIZE (type);
6321   if (!len || TREE_CODE (len) != INTEGER_CST)
6322     return NULL_TREE;
6323
6324   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (type));
6325   len = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type, len,
6326                          fold_convert (gfc_array_index_type, tmp));
6327
6328   /* If we are zeroing a local array avoid taking its address by emitting
6329      a = {} instead.  */
6330   if (!POINTER_TYPE_P (TREE_TYPE (dest)))
6331     return build2_loc (input_location, MODIFY_EXPR, void_type_node,
6332                        dest, build_constructor (TREE_TYPE (dest), NULL));
6333
6334   /* Convert arguments to the correct types.  */
6335   dest = fold_convert (pvoid_type_node, dest);
6336   len = fold_convert (size_type_node, len);
6337
6338   /* Construct call to __builtin_memset.  */
6339   tmp = build_call_expr_loc (input_location,
6340                              builtin_decl_explicit (BUILT_IN_MEMSET),
6341                              3, dest, integer_zero_node, len);
6342   return fold_convert (void_type_node, tmp);
6343 }
6344
6345
6346 /* Helper for gfc_trans_array_copy and gfc_trans_array_constructor_copy
6347    that constructs the call to __builtin_memcpy.  */
6348
6349 tree
6350 gfc_build_memcpy_call (tree dst, tree src, tree len)
6351 {
6352   tree tmp;
6353
6354   /* Convert arguments to the correct types.  */
6355   if (!POINTER_TYPE_P (TREE_TYPE (dst)))
6356     dst = gfc_build_addr_expr (pvoid_type_node, dst);
6357   else
6358     dst = fold_convert (pvoid_type_node, dst);
6359
6360   if (!POINTER_TYPE_P (TREE_TYPE (src)))
6361     src = gfc_build_addr_expr (pvoid_type_node, src);
6362   else
6363     src = fold_convert (pvoid_type_node, src);
6364
6365   len = fold_convert (size_type_node, len);
6366
6367   /* Construct call to __builtin_memcpy.  */
6368   tmp = build_call_expr_loc (input_location,
6369                              builtin_decl_explicit (BUILT_IN_MEMCPY),
6370                              3, dst, src, len);
6371   return fold_convert (void_type_node, tmp);
6372 }
6373
6374
6375 /* Try to efficiently translate dst(:) = src(:).  Return NULL if this
6376    can't be done.  EXPR1 is the destination/lhs and EXPR2 is the
6377    source/rhs, both are gfc_full_array_ref_p which have been checked for
6378    dependencies.  */
6379
6380 static tree
6381 gfc_trans_array_copy (gfc_expr * expr1, gfc_expr * expr2)
6382 {
6383   tree dst, dlen, dtype;
6384   tree src, slen, stype;
6385   tree tmp;
6386
6387   dst = gfc_get_symbol_decl (expr1->symtree->n.sym);
6388   src = gfc_get_symbol_decl (expr2->symtree->n.sym);
6389
6390   dtype = TREE_TYPE (dst);
6391   if (POINTER_TYPE_P (dtype))
6392     dtype = TREE_TYPE (dtype);
6393   stype = TREE_TYPE (src);
6394   if (POINTER_TYPE_P (stype))
6395     stype = TREE_TYPE (stype);
6396
6397   if (!GFC_ARRAY_TYPE_P (dtype) || !GFC_ARRAY_TYPE_P (stype))
6398     return NULL_TREE;
6399
6400   /* Determine the lengths of the arrays.  */
6401   dlen = GFC_TYPE_ARRAY_SIZE (dtype);
6402   if (!dlen || TREE_CODE (dlen) != INTEGER_CST)
6403     return NULL_TREE;
6404   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (dtype));
6405   dlen = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
6406                           dlen, fold_convert (gfc_array_index_type, tmp));
6407
6408   slen = GFC_TYPE_ARRAY_SIZE (stype);
6409   if (!slen || TREE_CODE (slen) != INTEGER_CST)
6410     return NULL_TREE;
6411   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (stype));
6412   slen = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
6413                           slen, fold_convert (gfc_array_index_type, tmp));
6414
6415   /* Sanity check that they are the same.  This should always be
6416      the case, as we should already have checked for conformance.  */
6417   if (!tree_int_cst_equal (slen, dlen))
6418     return NULL_TREE;
6419
6420   return gfc_build_memcpy_call (dst, src, dlen);
6421 }
6422
6423
6424 /* Try to efficiently translate array(:) = (/ ... /).  Return NULL if
6425    this can't be done.  EXPR1 is the destination/lhs for which
6426    gfc_full_array_ref_p is true, and EXPR2 is the source/rhs.  */
6427
6428 static tree
6429 gfc_trans_array_constructor_copy (gfc_expr * expr1, gfc_expr * expr2)
6430 {
6431   unsigned HOST_WIDE_INT nelem;
6432   tree dst, dtype;
6433   tree src, stype;
6434   tree len;
6435   tree tmp;
6436
6437   nelem = gfc_constant_array_constructor_p (expr2->value.constructor);
6438   if (nelem == 0)
6439     return NULL_TREE;
6440
6441   dst = gfc_get_symbol_decl (expr1->symtree->n.sym);
6442   dtype = TREE_TYPE (dst);
6443   if (POINTER_TYPE_P (dtype))
6444     dtype = TREE_TYPE (dtype);
6445   if (!GFC_ARRAY_TYPE_P (dtype))
6446     return NULL_TREE;
6447
6448   /* Determine the lengths of the array.  */
6449   len = GFC_TYPE_ARRAY_SIZE (dtype);
6450   if (!len || TREE_CODE (len) != INTEGER_CST)
6451     return NULL_TREE;
6452
6453   /* Confirm that the constructor is the same size.  */
6454   if (compare_tree_int (len, nelem) != 0)
6455     return NULL_TREE;
6456
6457   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (dtype));
6458   len = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type, len,
6459                          fold_convert (gfc_array_index_type, tmp));
6460
6461   stype = gfc_typenode_for_spec (&expr2->ts);
6462   src = gfc_build_constant_array_constructor (expr2, stype);
6463
6464   stype = TREE_TYPE (src);
6465   if (POINTER_TYPE_P (stype))
6466     stype = TREE_TYPE (stype);
6467
6468   return gfc_build_memcpy_call (dst, src, len);
6469 }
6470
6471
6472 /* Tells whether the expression is to be treated as a variable reference.  */
6473
6474 static bool
6475 expr_is_variable (gfc_expr *expr)
6476 {
6477   gfc_expr *arg;
6478
6479   if (expr->expr_type == EXPR_VARIABLE)
6480     return true;
6481
6482   arg = gfc_get_noncopying_intrinsic_argument (expr);
6483   if (arg)
6484     {
6485       gcc_assert (expr->value.function.isym->id == GFC_ISYM_TRANSPOSE);
6486       return expr_is_variable (arg);
6487     }
6488
6489   return false;
6490 }
6491
6492
6493 /* Is the lhs OK for automatic reallocation?  */
6494
6495 static bool
6496 is_scalar_reallocatable_lhs (gfc_expr *expr)
6497 {
6498   gfc_ref * ref;
6499
6500   /* An allocatable variable with no reference.  */
6501   if (expr->symtree->n.sym->attr.allocatable
6502         && !expr->ref)
6503     return true;
6504
6505   /* All that can be left are allocatable components.  */
6506   if ((expr->symtree->n.sym->ts.type != BT_DERIVED
6507         && expr->symtree->n.sym->ts.type != BT_CLASS)
6508         || !expr->symtree->n.sym->ts.u.derived->attr.alloc_comp)
6509     return false;
6510
6511   /* Find an allocatable component ref last.  */
6512   for (ref = expr->ref; ref; ref = ref->next)
6513     if (ref->type == REF_COMPONENT
6514           && !ref->next
6515           && ref->u.c.component->attr.allocatable)
6516       return true;
6517
6518   return false;
6519 }
6520
6521
6522 /* Allocate or reallocate scalar lhs, as necessary.  */
6523
6524 static void
6525 alloc_scalar_allocatable_for_assignment (stmtblock_t *block,
6526                                          tree string_length,
6527                                          gfc_expr *expr1,
6528                                          gfc_expr *expr2)
6529
6530 {
6531   tree cond;
6532   tree tmp;
6533   tree size;
6534   tree size_in_bytes;
6535   tree jump_label1;
6536   tree jump_label2;
6537   gfc_se lse;
6538
6539   if (!expr1 || expr1->rank)
6540     return;
6541
6542   if (!expr2 || expr2->rank)
6543     return;
6544
6545   /* Since this is a scalar lhs, we can afford to do this.  That is,
6546      there is no risk of side effects being repeated.  */
6547   gfc_init_se (&lse, NULL);
6548   lse.want_pointer = 1;
6549   gfc_conv_expr (&lse, expr1);
6550   
6551   jump_label1 = gfc_build_label_decl (NULL_TREE);
6552   jump_label2 = gfc_build_label_decl (NULL_TREE);
6553
6554   /* Do the allocation if the lhs is NULL. Otherwise go to label 1.  */
6555   tmp = build_int_cst (TREE_TYPE (lse.expr), 0);
6556   cond = fold_build2_loc (input_location, NE_EXPR, boolean_type_node,
6557                           lse.expr, tmp);
6558   tmp = build3_v (COND_EXPR, cond,
6559                   build1_v (GOTO_EXPR, jump_label1),
6560                   build_empty_stmt (input_location));
6561   gfc_add_expr_to_block (block, tmp);
6562
6563   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
6564     {
6565       /* Use the rhs string length and the lhs element size.  */
6566       size = string_length;
6567       tmp = TREE_TYPE (gfc_typenode_for_spec (&expr1->ts));
6568       tmp = TYPE_SIZE_UNIT (tmp);
6569       size_in_bytes = fold_build2_loc (input_location, MULT_EXPR,
6570                                        TREE_TYPE (tmp), tmp,
6571                                        fold_convert (TREE_TYPE (tmp), size));
6572     }
6573   else
6574     {
6575       /* Otherwise use the length in bytes of the rhs.  */
6576       size = TYPE_SIZE_UNIT (gfc_typenode_for_spec (&expr1->ts));
6577       size_in_bytes = size;
6578     }
6579
6580   tmp = build_call_expr_loc (input_location,
6581                              builtin_decl_explicit (BUILT_IN_MALLOC),
6582                              1, size_in_bytes);
6583   tmp = fold_convert (TREE_TYPE (lse.expr), tmp);
6584   gfc_add_modify (block, lse.expr, tmp);
6585   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
6586     {
6587       /* Deferred characters need checking for lhs and rhs string
6588          length.  Other deferred parameter variables will have to
6589          come here too.  */
6590       tmp = build1_v (GOTO_EXPR, jump_label2);
6591       gfc_add_expr_to_block (block, tmp);
6592     }
6593   tmp = build1_v (LABEL_EXPR, jump_label1);
6594   gfc_add_expr_to_block (block, tmp);
6595
6596   /* For a deferred length character, reallocate if lengths of lhs and
6597      rhs are different.  */
6598   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
6599     {
6600       cond = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
6601                               expr1->ts.u.cl->backend_decl, size);
6602       /* Jump past the realloc if the lengths are the same.  */
6603       tmp = build3_v (COND_EXPR, cond,
6604                       build1_v (GOTO_EXPR, jump_label2),
6605                       build_empty_stmt (input_location));
6606       gfc_add_expr_to_block (block, tmp);
6607       tmp = build_call_expr_loc (input_location,
6608                                  builtin_decl_explicit (BUILT_IN_REALLOC),
6609                                  2, fold_convert (pvoid_type_node, lse.expr),
6610                                  size_in_bytes);
6611       tmp = fold_convert (TREE_TYPE (lse.expr), tmp);
6612       gfc_add_modify (block, lse.expr, tmp);
6613       tmp = build1_v (LABEL_EXPR, jump_label2);
6614       gfc_add_expr_to_block (block, tmp);
6615
6616       /* Update the lhs character length.  */
6617       size = string_length;
6618       gfc_add_modify (block, expr1->ts.u.cl->backend_decl, size);
6619     }
6620 }
6621
6622
6623 /* Subroutine of gfc_trans_assignment that actually scalarizes the
6624    assignment.  EXPR1 is the destination/LHS and EXPR2 is the source/RHS.
6625    init_flag indicates initialization expressions and dealloc that no
6626    deallocate prior assignment is needed (if in doubt, set true).  */
6627
6628 static tree
6629 gfc_trans_assignment_1 (gfc_expr * expr1, gfc_expr * expr2, bool init_flag,
6630                         bool dealloc)
6631 {
6632   gfc_se lse;
6633   gfc_se rse;
6634   gfc_ss *lss;
6635   gfc_ss *lss_section;
6636   gfc_ss *rss;
6637   gfc_loopinfo loop;
6638   tree tmp;
6639   stmtblock_t block;
6640   stmtblock_t body;
6641   bool l_is_temp;
6642   bool scalar_to_array;
6643   bool def_clen_func;
6644   tree string_length;
6645   int n;
6646
6647   /* Assignment of the form lhs = rhs.  */
6648   gfc_start_block (&block);
6649
6650   gfc_init_se (&lse, NULL);
6651   gfc_init_se (&rse, NULL);
6652
6653   /* Walk the lhs.  */
6654   lss = gfc_walk_expr (expr1);
6655   if (gfc_is_reallocatable_lhs (expr1)
6656         && !(expr2->expr_type == EXPR_FUNCTION
6657              && expr2->value.function.isym != NULL))
6658     lss->is_alloc_lhs = 1;
6659   rss = NULL;
6660   if (lss != gfc_ss_terminator)
6661     {
6662       /* The assignment needs scalarization.  */
6663       lss_section = lss;
6664
6665       /* Find a non-scalar SS from the lhs.  */
6666       while (lss_section != gfc_ss_terminator
6667              && lss_section->info->type != GFC_SS_SECTION)
6668         lss_section = lss_section->next;
6669
6670       gcc_assert (lss_section != gfc_ss_terminator);
6671
6672       /* Initialize the scalarizer.  */
6673       gfc_init_loopinfo (&loop);
6674
6675       /* Walk the rhs.  */
6676       rss = gfc_walk_expr (expr2);
6677       if (rss == gfc_ss_terminator)
6678         /* The rhs is scalar.  Add a ss for the expression.  */
6679         rss = gfc_get_scalar_ss (gfc_ss_terminator, expr2);
6680
6681       /* Associate the SS with the loop.  */
6682       gfc_add_ss_to_loop (&loop, lss);
6683       gfc_add_ss_to_loop (&loop, rss);
6684
6685       /* Calculate the bounds of the scalarization.  */
6686       gfc_conv_ss_startstride (&loop);
6687       /* Enable loop reversal.  */
6688       for (n = 0; n < GFC_MAX_DIMENSIONS; n++)
6689         loop.reverse[n] = GFC_ENABLE_REVERSE;
6690       /* Resolve any data dependencies in the statement.  */
6691       gfc_conv_resolve_dependencies (&loop, lss, rss);
6692       /* Setup the scalarizing loops.  */
6693       gfc_conv_loop_setup (&loop, &expr2->where);
6694
6695       /* Setup the gfc_se structures.  */
6696       gfc_copy_loopinfo_to_se (&lse, &loop);
6697       gfc_copy_loopinfo_to_se (&rse, &loop);
6698
6699       rse.ss = rss;
6700       gfc_mark_ss_chain_used (rss, 1);
6701       if (loop.temp_ss == NULL)
6702         {
6703           lse.ss = lss;
6704           gfc_mark_ss_chain_used (lss, 1);
6705         }
6706       else
6707         {
6708           lse.ss = loop.temp_ss;
6709           gfc_mark_ss_chain_used (lss, 3);
6710           gfc_mark_ss_chain_used (loop.temp_ss, 3);
6711         }
6712
6713       /* Allow the scalarizer to workshare array assignments.  */
6714       if ((ompws_flags & OMPWS_WORKSHARE_FLAG) && loop.temp_ss == NULL)
6715         ompws_flags |= OMPWS_SCALARIZER_WS;
6716
6717       /* Start the scalarized loop body.  */
6718       gfc_start_scalarized_body (&loop, &body);
6719     }
6720   else
6721     gfc_init_block (&body);
6722
6723   l_is_temp = (lss != gfc_ss_terminator && loop.temp_ss != NULL);
6724
6725   /* Translate the expression.  */
6726   gfc_conv_expr (&rse, expr2);
6727
6728   /* Stabilize a string length for temporaries.  */
6729   if (expr2->ts.type == BT_CHARACTER)
6730     string_length = gfc_evaluate_now (rse.string_length, &rse.pre);
6731   else
6732     string_length = NULL_TREE;
6733
6734   if (l_is_temp)
6735     {
6736       gfc_conv_tmp_array_ref (&lse);
6737       if (expr2->ts.type == BT_CHARACTER)
6738         lse.string_length = string_length;
6739     }
6740   else
6741     gfc_conv_expr (&lse, expr1);
6742
6743   /* Assignments of scalar derived types with allocatable components
6744      to arrays must be done with a deep copy and the rhs temporary
6745      must have its components deallocated afterwards.  */
6746   scalar_to_array = (expr2->ts.type == BT_DERIVED
6747                        && expr2->ts.u.derived->attr.alloc_comp
6748                        && !expr_is_variable (expr2)
6749                        && !gfc_is_constant_expr (expr2)
6750                        && expr1->rank && !expr2->rank);
6751   if (scalar_to_array && dealloc)
6752     {
6753       tmp = gfc_deallocate_alloc_comp (expr2->ts.u.derived, rse.expr, 0);
6754       gfc_add_expr_to_block (&loop.post, tmp);
6755     }
6756
6757   /* For a deferred character length function, the function call must
6758      happen before the (re)allocation of the lhs, otherwise the character
6759      length of the result is not known.  */
6760   def_clen_func = (((expr2->expr_type == EXPR_FUNCTION)
6761                            || (expr2->expr_type == EXPR_COMPCALL)
6762                            || (expr2->expr_type == EXPR_PPC))
6763                        && expr2->ts.deferred);
6764   if (gfc_option.flag_realloc_lhs
6765         && expr2->ts.type == BT_CHARACTER
6766         && (def_clen_func || expr2->expr_type == EXPR_OP)
6767         && expr1->ts.deferred)
6768     gfc_add_block_to_block (&block, &rse.pre);
6769
6770   tmp = gfc_trans_scalar_assign (&lse, &rse, expr1->ts,
6771                                  l_is_temp || init_flag,
6772                                  expr_is_variable (expr2) || scalar_to_array
6773                                  || expr2->expr_type == EXPR_ARRAY, dealloc);
6774   gfc_add_expr_to_block (&body, tmp);
6775
6776   if (lss == gfc_ss_terminator)
6777     {
6778       /* F2003: Add the code for reallocation on assignment.  */
6779       if (gfc_option.flag_realloc_lhs
6780             && is_scalar_reallocatable_lhs (expr1))
6781         alloc_scalar_allocatable_for_assignment (&block, rse.string_length,
6782                                                  expr1, expr2);
6783
6784       /* Use the scalar assignment as is.  */
6785       gfc_add_block_to_block (&block, &body);
6786     }
6787   else
6788     {
6789       gcc_assert (lse.ss == gfc_ss_terminator
6790                   && rse.ss == gfc_ss_terminator);
6791
6792       if (l_is_temp)
6793         {
6794           gfc_trans_scalarized_loop_boundary (&loop, &body);
6795
6796           /* We need to copy the temporary to the actual lhs.  */
6797           gfc_init_se (&lse, NULL);
6798           gfc_init_se (&rse, NULL);
6799           gfc_copy_loopinfo_to_se (&lse, &loop);
6800           gfc_copy_loopinfo_to_se (&rse, &loop);
6801
6802           rse.ss = loop.temp_ss;
6803           lse.ss = lss;
6804
6805           gfc_conv_tmp_array_ref (&rse);
6806           gfc_conv_expr (&lse, expr1);
6807
6808           gcc_assert (lse.ss == gfc_ss_terminator
6809                       && rse.ss == gfc_ss_terminator);
6810
6811           if (expr2->ts.type == BT_CHARACTER)
6812             rse.string_length = string_length;
6813
6814           tmp = gfc_trans_scalar_assign (&lse, &rse, expr1->ts,
6815                                          false, false, dealloc);
6816           gfc_add_expr_to_block (&body, tmp);
6817         }
6818
6819       /* F2003: Allocate or reallocate lhs of allocatable array.  */
6820       if (gfc_option.flag_realloc_lhs
6821             && gfc_is_reallocatable_lhs (expr1)
6822             && !gfc_expr_attr (expr1).codimension
6823             && !gfc_is_coindexed (expr1))
6824         {
6825           ompws_flags &= ~OMPWS_SCALARIZER_WS;
6826           tmp = gfc_alloc_allocatable_for_assignment (&loop, expr1, expr2);
6827           if (tmp != NULL_TREE)
6828             gfc_add_expr_to_block (&loop.code[expr1->rank - 1], tmp);
6829         }
6830
6831       /* Generate the copying loops.  */
6832       gfc_trans_scalarizing_loops (&loop, &body);
6833
6834       /* Wrap the whole thing up.  */
6835       gfc_add_block_to_block (&block, &loop.pre);
6836       gfc_add_block_to_block (&block, &loop.post);
6837
6838       gfc_cleanup_loop (&loop);
6839     }
6840
6841   return gfc_finish_block (&block);
6842 }
6843
6844
6845 /* Check whether EXPR is a copyable array.  */
6846
6847 static bool
6848 copyable_array_p (gfc_expr * expr)
6849 {
6850   if (expr->expr_type != EXPR_VARIABLE)
6851     return false;
6852
6853   /* First check it's an array.  */
6854   if (expr->rank < 1 || !expr->ref || expr->ref->next)
6855     return false;
6856
6857   if (!gfc_full_array_ref_p (expr->ref, NULL))
6858     return false;
6859
6860   /* Next check that it's of a simple enough type.  */
6861   switch (expr->ts.type)
6862     {
6863     case BT_INTEGER:
6864     case BT_REAL:
6865     case BT_COMPLEX:
6866     case BT_LOGICAL:
6867       return true;
6868
6869     case BT_CHARACTER:
6870       return false;
6871
6872     case BT_DERIVED:
6873       return !expr->ts.u.derived->attr.alloc_comp;
6874
6875     default:
6876       break;
6877     }
6878
6879   return false;
6880 }
6881
6882 /* Translate an assignment.  */
6883
6884 tree
6885 gfc_trans_assignment (gfc_expr * expr1, gfc_expr * expr2, bool init_flag,
6886                       bool dealloc)
6887 {
6888   tree tmp;
6889
6890   /* Special case a single function returning an array.  */
6891   if (expr2->expr_type == EXPR_FUNCTION && expr2->rank > 0)
6892     {
6893       tmp = gfc_trans_arrayfunc_assign (expr1, expr2);
6894       if (tmp)
6895         return tmp;
6896     }
6897
6898   /* Special case assigning an array to zero.  */
6899   if (copyable_array_p (expr1)
6900       && is_zero_initializer_p (expr2))
6901     {
6902       tmp = gfc_trans_zero_assign (expr1);
6903       if (tmp)
6904         return tmp;
6905     }
6906
6907   /* Special case copying one array to another.  */
6908   if (copyable_array_p (expr1)
6909       && copyable_array_p (expr2)
6910       && gfc_compare_types (&expr1->ts, &expr2->ts)
6911       && !gfc_check_dependency (expr1, expr2, 0))
6912     {
6913       tmp = gfc_trans_array_copy (expr1, expr2);
6914       if (tmp)
6915         return tmp;
6916     }
6917
6918   /* Special case initializing an array from a constant array constructor.  */
6919   if (copyable_array_p (expr1)
6920       && expr2->expr_type == EXPR_ARRAY
6921       && gfc_compare_types (&expr1->ts, &expr2->ts))
6922     {
6923       tmp = gfc_trans_array_constructor_copy (expr1, expr2);
6924       if (tmp)
6925         return tmp;
6926     }
6927
6928   /* Fallback to the scalarizer to generate explicit loops.  */
6929   return gfc_trans_assignment_1 (expr1, expr2, init_flag, dealloc);
6930 }
6931
6932 tree
6933 gfc_trans_init_assign (gfc_code * code)
6934 {
6935   return gfc_trans_assignment (code->expr1, code->expr2, true, false);
6936 }
6937
6938 tree
6939 gfc_trans_assign (gfc_code * code)
6940 {
6941   return gfc_trans_assignment (code->expr1, code->expr2, false, true);
6942 }