xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/fortran/trans-expr.c (revision 4724848cf0da353df257f730694b7882798e5daf)
1 /* Expression translation
2    Copyright (C) 2002-2020 Free Software Foundation, Inc.
3    Contributed by Paul Brook <paul@nowt.org>
4    and Steven Bosscher <s.bosscher@student.tudelft.nl>
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12 
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 /* trans-expr.c-- generate GENERIC trees for gfc_expr.  */
23 
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "options.h"
28 #include "tree.h"
29 #include "gfortran.h"
30 #include "trans.h"
31 #include "stringpool.h"
32 #include "diagnostic-core.h"	/* For fatal_error.  */
33 #include "fold-const.h"
34 #include "langhooks.h"
35 #include "arith.h"
36 #include "constructor.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 #include "gimplify.h"
44 
45 /* Convert a scalar to an array descriptor. To be used for assumed-rank
46    arrays.  */
47 
48 static tree
49 get_scalar_to_descriptor_type (tree scalar, symbol_attribute attr)
50 {
51   enum gfc_array_kind akind;
52 
53   if (attr.pointer)
54     akind = GFC_ARRAY_POINTER_CONT;
55   else if (attr.allocatable)
56     akind = GFC_ARRAY_ALLOCATABLE;
57   else
58     akind = GFC_ARRAY_ASSUMED_SHAPE_CONT;
59 
60   if (POINTER_TYPE_P (TREE_TYPE (scalar)))
61     scalar = TREE_TYPE (scalar);
62   return gfc_get_array_type_bounds (TREE_TYPE (scalar), 0, 0, NULL, NULL, 1,
63 				    akind, !(attr.pointer || attr.target));
64 }
65 
66 tree
67 gfc_conv_scalar_to_descriptor (gfc_se *se, tree scalar, symbol_attribute attr)
68 {
69   tree desc, type, etype;
70 
71   type = get_scalar_to_descriptor_type (scalar, attr);
72   etype = TREE_TYPE (scalar);
73   desc = gfc_create_var (type, "desc");
74   DECL_ARTIFICIAL (desc) = 1;
75 
76   if (CONSTANT_CLASS_P (scalar))
77     {
78       tree tmp;
79       tmp = gfc_create_var (TREE_TYPE (scalar), "scalar");
80       gfc_add_modify (&se->pre, tmp, scalar);
81       scalar = tmp;
82     }
83   if (!POINTER_TYPE_P (TREE_TYPE (scalar)))
84     scalar = gfc_build_addr_expr (NULL_TREE, scalar);
85   else if (TREE_TYPE (etype) && TREE_CODE (TREE_TYPE (etype)) == ARRAY_TYPE)
86     etype = TREE_TYPE (etype);
87   gfc_add_modify (&se->pre, gfc_conv_descriptor_dtype (desc),
88 		  gfc_get_dtype_rank_type (0, etype));
89   gfc_conv_descriptor_data_set (&se->pre, desc, scalar);
90 
91   /* Copy pointer address back - but only if it could have changed and
92      if the actual argument is a pointer and not, e.g., NULL().  */
93   if ((attr.pointer || attr.allocatable) && attr.intent != INTENT_IN)
94     gfc_add_modify (&se->post, scalar,
95 		    fold_convert (TREE_TYPE (scalar),
96 				  gfc_conv_descriptor_data_get (desc)));
97   return desc;
98 }
99 
100 
101 /* Get the coarray token from the ultimate array or component ref.
102    Returns a NULL_TREE, when the ref object is not allocatable or pointer.  */
103 
104 tree
105 gfc_get_ultimate_alloc_ptr_comps_caf_token (gfc_se *outerse, gfc_expr *expr)
106 {
107   gfc_symbol *sym = expr->symtree->n.sym;
108   bool is_coarray = sym->attr.codimension;
109   gfc_expr *caf_expr = gfc_copy_expr (expr);
110   gfc_ref *ref = caf_expr->ref, *last_caf_ref = NULL;
111 
112   while (ref)
113     {
114       if (ref->type == REF_COMPONENT
115 	  && (ref->u.c.component->attr.allocatable
116 	      || ref->u.c.component->attr.pointer)
117 	  && (is_coarray || ref->u.c.component->attr.codimension))
118 	  last_caf_ref = ref;
119       ref = ref->next;
120     }
121 
122   if (last_caf_ref == NULL)
123     return NULL_TREE;
124 
125   tree comp = last_caf_ref->u.c.component->caf_token, caf;
126   gfc_se se;
127   bool comp_ref = !last_caf_ref->u.c.component->attr.dimension;
128   if (comp == NULL_TREE && comp_ref)
129     return NULL_TREE;
130   gfc_init_se (&se, outerse);
131   gfc_free_ref_list (last_caf_ref->next);
132   last_caf_ref->next = NULL;
133   caf_expr->rank = comp_ref ? 0 : last_caf_ref->u.c.component->as->rank;
134   se.want_pointer = comp_ref;
135   gfc_conv_expr (&se, caf_expr);
136   gfc_add_block_to_block (&outerse->pre, &se.pre);
137 
138   if (TREE_CODE (se.expr) == COMPONENT_REF && comp_ref)
139     se.expr = TREE_OPERAND (se.expr, 0);
140   gfc_free_expr (caf_expr);
141 
142   if (comp_ref)
143     caf = fold_build3_loc (input_location, COMPONENT_REF,
144 			   TREE_TYPE (comp), se.expr, comp, NULL_TREE);
145   else
146     caf = gfc_conv_descriptor_token (se.expr);
147   return gfc_build_addr_expr (NULL_TREE, caf);
148 }
149 
150 
151 /* This is the seed for an eventual trans-class.c
152 
153    The following parameters should not be used directly since they might
154    in future implementations.  Use the corresponding APIs.  */
155 #define CLASS_DATA_FIELD 0
156 #define CLASS_VPTR_FIELD 1
157 #define CLASS_LEN_FIELD 2
158 #define VTABLE_HASH_FIELD 0
159 #define VTABLE_SIZE_FIELD 1
160 #define VTABLE_EXTENDS_FIELD 2
161 #define VTABLE_DEF_INIT_FIELD 3
162 #define VTABLE_COPY_FIELD 4
163 #define VTABLE_FINAL_FIELD 5
164 #define VTABLE_DEALLOCATE_FIELD 6
165 
166 
167 tree
168 gfc_class_set_static_fields (tree decl, tree vptr, tree data)
169 {
170   tree tmp;
171   tree field;
172   vec<constructor_elt, va_gc> *init = NULL;
173 
174   field = TYPE_FIELDS (TREE_TYPE (decl));
175   tmp = gfc_advance_chain (field, CLASS_DATA_FIELD);
176   CONSTRUCTOR_APPEND_ELT (init, tmp, data);
177 
178   tmp = gfc_advance_chain (field, CLASS_VPTR_FIELD);
179   CONSTRUCTOR_APPEND_ELT (init, tmp, vptr);
180 
181   return build_constructor (TREE_TYPE (decl), init);
182 }
183 
184 
185 tree
186 gfc_class_data_get (tree decl)
187 {
188   tree data;
189   if (POINTER_TYPE_P (TREE_TYPE (decl)))
190     decl = build_fold_indirect_ref_loc (input_location, decl);
191   data = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
192 			    CLASS_DATA_FIELD);
193   return fold_build3_loc (input_location, COMPONENT_REF,
194 			  TREE_TYPE (data), decl, data,
195 			  NULL_TREE);
196 }
197 
198 
199 tree
200 gfc_class_vptr_get (tree decl)
201 {
202   tree vptr;
203   /* For class arrays decl may be a temporary descriptor handle, the vptr is
204      then available through the saved descriptor.  */
205   if (VAR_P (decl) && DECL_LANG_SPECIFIC (decl)
206       && GFC_DECL_SAVED_DESCRIPTOR (decl))
207     decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
208   if (POINTER_TYPE_P (TREE_TYPE (decl)))
209     decl = build_fold_indirect_ref_loc (input_location, decl);
210   vptr = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
211 			    CLASS_VPTR_FIELD);
212   return fold_build3_loc (input_location, COMPONENT_REF,
213 			  TREE_TYPE (vptr), decl, vptr,
214 			  NULL_TREE);
215 }
216 
217 
218 tree
219 gfc_class_len_get (tree decl)
220 {
221   tree len;
222   /* For class arrays decl may be a temporary descriptor handle, the len is
223      then available through the saved descriptor.  */
224   if (VAR_P (decl) && DECL_LANG_SPECIFIC (decl)
225       && GFC_DECL_SAVED_DESCRIPTOR (decl))
226     decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
227   if (POINTER_TYPE_P (TREE_TYPE (decl)))
228     decl = build_fold_indirect_ref_loc (input_location, decl);
229   len = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
230 			   CLASS_LEN_FIELD);
231   return fold_build3_loc (input_location, COMPONENT_REF,
232 			  TREE_TYPE (len), decl, len,
233 			  NULL_TREE);
234 }
235 
236 
237 /* Try to get the _len component of a class.  When the class is not unlimited
238    poly, i.e. no _len field exists, then return a zero node.  */
239 
240 tree
241 gfc_class_len_or_zero_get (tree decl)
242 {
243   tree len;
244   /* For class arrays decl may be a temporary descriptor handle, the vptr is
245      then available through the saved descriptor.  */
246   if (VAR_P (decl) && DECL_LANG_SPECIFIC (decl)
247       && GFC_DECL_SAVED_DESCRIPTOR (decl))
248     decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
249   if (POINTER_TYPE_P (TREE_TYPE (decl)))
250     decl = build_fold_indirect_ref_loc (input_location, decl);
251   len = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
252 			   CLASS_LEN_FIELD);
253   return len != NULL_TREE ? fold_build3_loc (input_location, COMPONENT_REF,
254 					     TREE_TYPE (len), decl, len,
255 					     NULL_TREE)
256     : build_zero_cst (gfc_charlen_type_node);
257 }
258 
259 
260 tree
261 gfc_resize_class_size_with_len (stmtblock_t * block, tree class_expr, tree size)
262 {
263   tree tmp;
264   tree tmp2;
265   tree type;
266 
267   tmp = gfc_class_len_or_zero_get (class_expr);
268 
269   /* Include the len value in the element size if present.  */
270   if (!integer_zerop (tmp))
271     {
272       type = TREE_TYPE (size);
273       if (block)
274 	{
275 	  size = gfc_evaluate_now (size, block);
276 	  tmp = gfc_evaluate_now (fold_convert (type , tmp), block);
277 	}
278       tmp2 = fold_build2_loc (input_location, MULT_EXPR,
279 			      type, size, tmp);
280       tmp = fold_build2_loc (input_location, GT_EXPR,
281 			     logical_type_node, tmp,
282 			     build_zero_cst (type));
283       size = fold_build3_loc (input_location, COND_EXPR,
284 			      type, tmp, tmp2, size);
285     }
286   else
287     return size;
288 
289   if (block)
290     size = gfc_evaluate_now (size, block);
291 
292   return size;
293 }
294 
295 
296 /* Get the specified FIELD from the VPTR.  */
297 
298 static tree
299 vptr_field_get (tree vptr, int fieldno)
300 {
301   tree field;
302   vptr = build_fold_indirect_ref_loc (input_location, vptr);
303   field = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (vptr)),
304 			     fieldno);
305   field = fold_build3_loc (input_location, COMPONENT_REF,
306 			   TREE_TYPE (field), vptr, field,
307 			   NULL_TREE);
308   gcc_assert (field);
309   return field;
310 }
311 
312 
313 /* Get the field from the class' vptr.  */
314 
315 static tree
316 class_vtab_field_get (tree decl, int fieldno)
317 {
318   tree vptr;
319   vptr = gfc_class_vptr_get (decl);
320   return vptr_field_get (vptr, fieldno);
321 }
322 
323 
324 /* Define a macro for creating the class_vtab_* and vptr_* accessors in
325    unison.  */
326 #define VTAB_GET_FIELD_GEN(name, field) tree \
327 gfc_class_vtab_## name ##_get (tree cl) \
328 { \
329   return class_vtab_field_get (cl, field); \
330 } \
331  \
332 tree \
333 gfc_vptr_## name ##_get (tree vptr) \
334 { \
335   return vptr_field_get (vptr, field); \
336 }
337 
338 VTAB_GET_FIELD_GEN (hash, VTABLE_HASH_FIELD)
339 VTAB_GET_FIELD_GEN (extends, VTABLE_EXTENDS_FIELD)
340 VTAB_GET_FIELD_GEN (def_init, VTABLE_DEF_INIT_FIELD)
341 VTAB_GET_FIELD_GEN (copy, VTABLE_COPY_FIELD)
342 VTAB_GET_FIELD_GEN (final, VTABLE_FINAL_FIELD)
343 VTAB_GET_FIELD_GEN (deallocate, VTABLE_DEALLOCATE_FIELD)
344 
345 
346 /* The size field is returned as an array index type.  Therefore treat
347    it and only it specially.  */
348 
349 tree
350 gfc_class_vtab_size_get (tree cl)
351 {
352   tree size;
353   size = class_vtab_field_get (cl, VTABLE_SIZE_FIELD);
354   /* Always return size as an array index type.  */
355   size = fold_convert (gfc_array_index_type, size);
356   gcc_assert (size);
357   return size;
358 }
359 
360 tree
361 gfc_vptr_size_get (tree vptr)
362 {
363   tree size;
364   size = vptr_field_get (vptr, VTABLE_SIZE_FIELD);
365   /* Always return size as an array index type.  */
366   size = fold_convert (gfc_array_index_type, size);
367   gcc_assert (size);
368   return size;
369 }
370 
371 
372 #undef CLASS_DATA_FIELD
373 #undef CLASS_VPTR_FIELD
374 #undef CLASS_LEN_FIELD
375 #undef VTABLE_HASH_FIELD
376 #undef VTABLE_SIZE_FIELD
377 #undef VTABLE_EXTENDS_FIELD
378 #undef VTABLE_DEF_INIT_FIELD
379 #undef VTABLE_COPY_FIELD
380 #undef VTABLE_FINAL_FIELD
381 
382 
383 /* Search for the last _class ref in the chain of references of this
384    expression and cut the chain there.  Albeit this routine is similiar
385    to class.c::gfc_add_component_ref (), is there a significant
386    difference: gfc_add_component_ref () concentrates on an array ref to
387    be the last ref in the chain.  This routine is oblivious to the kind
388    of refs following.  */
389 
390 gfc_expr *
391 gfc_find_and_cut_at_last_class_ref (gfc_expr *e, bool is_mold)
392 {
393   gfc_expr *base_expr;
394   gfc_ref *ref, *class_ref, *tail = NULL, *array_ref;
395 
396   /* Find the last class reference.  */
397   class_ref = NULL;
398   array_ref = NULL;
399   for (ref = e->ref; ref; ref = ref->next)
400     {
401       if (ref->type == REF_ARRAY && ref->u.ar.type != AR_ELEMENT)
402 	array_ref = ref;
403 
404       if (ref->type == REF_COMPONENT
405 	  && ref->u.c.component->ts.type == BT_CLASS)
406 	{
407 	  /* Component to the right of a part reference with nonzero rank
408 	     must not have the ALLOCATABLE attribute.  If attempts are
409 	     made to reference such a component reference, an error results
410 	     followed by an ICE.  */
411 	  if (array_ref && CLASS_DATA (ref->u.c.component)->attr.allocatable)
412 	    return NULL;
413 	  class_ref = ref;
414 	}
415 
416       if (ref->next == NULL)
417 	break;
418     }
419 
420   /* Remove and store all subsequent references after the
421      CLASS reference.  */
422   if (class_ref)
423     {
424       tail = class_ref->next;
425       class_ref->next = NULL;
426     }
427   else if (e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
428     {
429       tail = e->ref;
430       e->ref = NULL;
431     }
432 
433   if (is_mold)
434     base_expr = gfc_expr_to_initialize (e);
435   else
436     base_expr = gfc_copy_expr (e);
437 
438   /* Restore the original tail expression.  */
439   if (class_ref)
440     {
441       gfc_free_ref_list (class_ref->next);
442       class_ref->next = tail;
443     }
444   else if (e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
445     {
446       gfc_free_ref_list (e->ref);
447       e->ref = tail;
448     }
449   return base_expr;
450 }
451 
452 
453 /* Reset the vptr to the declared type, e.g. after deallocation.  */
454 
455 void
456 gfc_reset_vptr (stmtblock_t *block, gfc_expr *e)
457 {
458   gfc_symbol *vtab;
459   tree vptr;
460   tree vtable;
461   gfc_se se;
462 
463   /* Evaluate the expression and obtain the vptr from it.  */
464   gfc_init_se (&se, NULL);
465   if (e->rank)
466     gfc_conv_expr_descriptor (&se, e);
467   else
468     gfc_conv_expr (&se, e);
469   gfc_add_block_to_block (block, &se.pre);
470   vptr = gfc_get_vptr_from_expr (se.expr);
471 
472   /* If a vptr is not found, we can do nothing more.  */
473   if (vptr == NULL_TREE)
474     return;
475 
476   if (UNLIMITED_POLY (e))
477     gfc_add_modify (block, vptr, build_int_cst (TREE_TYPE (vptr), 0));
478   else
479     {
480       /* Return the vptr to the address of the declared type.  */
481       vtab = gfc_find_derived_vtab (e->ts.u.derived);
482       vtable = vtab->backend_decl;
483       if (vtable == NULL_TREE)
484 	vtable = gfc_get_symbol_decl (vtab);
485       vtable = gfc_build_addr_expr (NULL, vtable);
486       vtable = fold_convert (TREE_TYPE (vptr), vtable);
487       gfc_add_modify (block, vptr, vtable);
488     }
489 }
490 
491 
492 /* Reset the len for unlimited polymorphic objects.  */
493 
494 void
495 gfc_reset_len (stmtblock_t *block, gfc_expr *expr)
496 {
497   gfc_expr *e;
498   gfc_se se_len;
499   e = gfc_find_and_cut_at_last_class_ref (expr);
500   if (e == NULL)
501     return;
502   gfc_add_len_component (e);
503   gfc_init_se (&se_len, NULL);
504   gfc_conv_expr (&se_len, e);
505   gfc_add_modify (block, se_len.expr,
506 		  fold_convert (TREE_TYPE (se_len.expr), integer_zero_node));
507   gfc_free_expr (e);
508 }
509 
510 
511 /* Obtain the last class reference in a gfc_expr. Return NULL_TREE if no class
512    reference is found. Note that it is up to the caller to avoid using this
513    for expressions other than variables.  */
514 
515 tree
516 gfc_get_class_from_gfc_expr (gfc_expr *e)
517 {
518   gfc_expr *class_expr;
519   gfc_se cse;
520   class_expr = gfc_find_and_cut_at_last_class_ref (e);
521   if (class_expr == NULL)
522     return NULL_TREE;
523   gfc_init_se (&cse, NULL);
524   gfc_conv_expr (&cse, class_expr);
525   gfc_free_expr (class_expr);
526   return cse.expr;
527 }
528 
529 
530 /* Obtain the last class reference in an expression.
531    Return NULL_TREE if no class reference is found.  */
532 
533 tree
534 gfc_get_class_from_expr (tree expr)
535 {
536   tree tmp;
537   tree type;
538 
539   for (tmp = expr; tmp; tmp = TREE_OPERAND (tmp, 0))
540     {
541       if (CONSTANT_CLASS_P (tmp))
542 	return NULL_TREE;
543 
544       type = TREE_TYPE (tmp);
545       while (type)
546 	{
547 	  if (GFC_CLASS_TYPE_P (type))
548 	    return tmp;
549 	  if (type != TYPE_CANONICAL (type))
550 	    type = TYPE_CANONICAL (type);
551 	  else
552 	    type = NULL_TREE;
553 	}
554       if (VAR_P (tmp) || TREE_CODE (tmp) == PARM_DECL)
555 	break;
556     }
557 
558   if (POINTER_TYPE_P (TREE_TYPE (tmp)))
559     tmp = build_fold_indirect_ref_loc (input_location, tmp);
560 
561   if (GFC_CLASS_TYPE_P (TREE_TYPE (tmp)))
562     return tmp;
563 
564   return NULL_TREE;
565 }
566 
567 
568 /* Obtain the vptr of the last class reference in an expression.
569    Return NULL_TREE if no class reference is found.  */
570 
571 tree
572 gfc_get_vptr_from_expr (tree expr)
573 {
574   tree tmp;
575 
576   tmp = gfc_get_class_from_expr (expr);
577 
578   if (tmp != NULL_TREE)
579     return gfc_class_vptr_get (tmp);
580 
581   return NULL_TREE;
582 }
583 
584 
585 static void
586 class_array_data_assign (stmtblock_t *block, tree lhs_desc, tree rhs_desc,
587 			 bool lhs_type)
588 {
589   tree tmp, tmp2, type;
590 
591   gfc_conv_descriptor_data_set (block, lhs_desc,
592 				gfc_conv_descriptor_data_get (rhs_desc));
593   gfc_conv_descriptor_offset_set (block, lhs_desc,
594 				  gfc_conv_descriptor_offset_get (rhs_desc));
595 
596   gfc_add_modify (block, gfc_conv_descriptor_dtype (lhs_desc),
597 		  gfc_conv_descriptor_dtype (rhs_desc));
598 
599   /* Assign the dimension as range-ref.  */
600   tmp = gfc_get_descriptor_dimension (lhs_desc);
601   tmp2 = gfc_get_descriptor_dimension (rhs_desc);
602 
603   type = lhs_type ? TREE_TYPE (tmp) : TREE_TYPE (tmp2);
604   tmp = build4_loc (input_location, ARRAY_RANGE_REF, type, tmp,
605 		    gfc_index_zero_node, NULL_TREE, NULL_TREE);
606   tmp2 = build4_loc (input_location, ARRAY_RANGE_REF, type, tmp2,
607 		     gfc_index_zero_node, NULL_TREE, NULL_TREE);
608   gfc_add_modify (block, tmp, tmp2);
609 }
610 
611 
612 /* Takes a derived type expression and returns the address of a temporary
613    class object of the 'declared' type.  If vptr is not NULL, this is
614    used for the temporary class object.
615    optional_alloc_ptr is false when the dummy is neither allocatable
616    nor a pointer; that's only relevant for the optional handling.  */
617 void
618 gfc_conv_derived_to_class (gfc_se *parmse, gfc_expr *e,
619 			   gfc_typespec class_ts, tree vptr, bool optional,
620 			   bool optional_alloc_ptr)
621 {
622   gfc_symbol *vtab;
623   tree cond_optional = NULL_TREE;
624   gfc_ss *ss;
625   tree ctree;
626   tree var;
627   tree tmp;
628   int dim;
629 
630   /* The derived type needs to be converted to a temporary
631      CLASS object.  */
632   tmp = gfc_typenode_for_spec (&class_ts);
633   var = gfc_create_var (tmp, "class");
634 
635   /* Set the vptr.  */
636   ctree =  gfc_class_vptr_get (var);
637 
638   if (vptr != NULL_TREE)
639     {
640       /* Use the dynamic vptr.  */
641       tmp = vptr;
642     }
643   else
644     {
645       /* In this case the vtab corresponds to the derived type and the
646 	 vptr must point to it.  */
647       vtab = gfc_find_derived_vtab (e->ts.u.derived);
648       gcc_assert (vtab);
649       tmp = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtab));
650     }
651   gfc_add_modify (&parmse->pre, ctree,
652 		  fold_convert (TREE_TYPE (ctree), tmp));
653 
654   /* Now set the data field.  */
655   ctree =  gfc_class_data_get (var);
656 
657   if (optional)
658     cond_optional = gfc_conv_expr_present (e->symtree->n.sym);
659 
660   if (parmse->expr && POINTER_TYPE_P (TREE_TYPE (parmse->expr)))
661     {
662       /* If there is a ready made pointer to a derived type, use it
663 	 rather than evaluating the expression again.  */
664       tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
665       gfc_add_modify (&parmse->pre, ctree, tmp);
666     }
667   else if (parmse->ss && parmse->ss->info && parmse->ss->info->useflags)
668     {
669       /* For an array reference in an elemental procedure call we need
670 	 to retain the ss to provide the scalarized array reference.  */
671       gfc_conv_expr_reference (parmse, e);
672       tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
673       if (optional)
674 	tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp),
675 			  cond_optional, tmp,
676 			  fold_convert (TREE_TYPE (tmp), null_pointer_node));
677       gfc_add_modify (&parmse->pre, ctree, tmp);
678     }
679   else
680     {
681       ss = gfc_walk_expr (e);
682       if (ss == gfc_ss_terminator)
683 	{
684 	  parmse->ss = NULL;
685 	  gfc_conv_expr_reference (parmse, e);
686 
687 	  /* Scalar to an assumed-rank array.  */
688 	  if (class_ts.u.derived->components->as)
689 	    {
690 	      tree type;
691 	      type = get_scalar_to_descriptor_type (parmse->expr,
692 						    gfc_expr_attr (e));
693 	      gfc_add_modify (&parmse->pre, gfc_conv_descriptor_dtype (ctree),
694 			      gfc_get_dtype (type));
695 	      if (optional)
696 		parmse->expr = build3_loc (input_location, COND_EXPR,
697 					   TREE_TYPE (parmse->expr),
698 					   cond_optional, parmse->expr,
699 					   fold_convert (TREE_TYPE (parmse->expr),
700 							 null_pointer_node));
701 	      gfc_conv_descriptor_data_set (&parmse->pre, ctree, parmse->expr);
702 	    }
703           else
704 	    {
705 	      tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
706 	      if (optional)
707 		tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp),
708 				  cond_optional, tmp,
709 				  fold_convert (TREE_TYPE (tmp),
710 						null_pointer_node));
711 	      gfc_add_modify (&parmse->pre, ctree, tmp);
712 	    }
713 	}
714       else
715 	{
716 	  stmtblock_t block;
717 	  gfc_init_block (&block);
718 	  gfc_ref *ref;
719 
720 	  parmse->ss = ss;
721 	  parmse->use_offset = 1;
722 	  gfc_conv_expr_descriptor (parmse, e);
723 
724 	  /* Detect any array references with vector subscripts.  */
725 	  for (ref = e->ref; ref; ref = ref->next)
726 	    if (ref->type == REF_ARRAY
727 		&& ref->u.ar.type != AR_ELEMENT
728 		&& ref->u.ar.type != AR_FULL)
729 	      {
730 		for (dim = 0; dim < ref->u.ar.dimen; dim++)
731 		  if (ref->u.ar.dimen_type[dim] == DIMEN_VECTOR)
732 		    break;
733 		if (dim < ref->u.ar.dimen)
734 		  break;
735 	      }
736 
737 	  /* Array references with vector subscripts and non-variable expressions
738 	     need be converted to a one-based descriptor.  */
739 	  if (ref || e->expr_type != EXPR_VARIABLE)
740 	    {
741 	      for (dim = 0; dim < e->rank; ++dim)
742 		gfc_conv_shift_descriptor_lbound (&block, parmse->expr, dim,
743 						  gfc_index_one_node);
744 	    }
745 
746 	  if (e->rank != class_ts.u.derived->components->as->rank)
747 	    {
748 	      gcc_assert (class_ts.u.derived->components->as->type
749 			  == AS_ASSUMED_RANK);
750 	      class_array_data_assign (&block, ctree, parmse->expr, false);
751 	    }
752 	  else
753 	    {
754 	      if (gfc_expr_attr (e).codimension)
755 		parmse->expr = fold_build1_loc (input_location,
756 						VIEW_CONVERT_EXPR,
757 						TREE_TYPE (ctree),
758 						parmse->expr);
759 	      gfc_add_modify (&block, ctree, parmse->expr);
760 	    }
761 
762 	  if (optional)
763 	    {
764 	      tmp = gfc_finish_block (&block);
765 
766 	      gfc_init_block (&block);
767 	      gfc_conv_descriptor_data_set (&block, ctree, null_pointer_node);
768 
769 	      tmp = build3_v (COND_EXPR, cond_optional, tmp,
770 			      gfc_finish_block (&block));
771 	      gfc_add_expr_to_block (&parmse->pre, tmp);
772 	    }
773 	  else
774 	    gfc_add_block_to_block (&parmse->pre, &block);
775 	}
776     }
777 
778   if (class_ts.u.derived->components->ts.type == BT_DERIVED
779       && class_ts.u.derived->components->ts.u.derived
780 		 ->attr.unlimited_polymorphic)
781     {
782       /* Take care about initializing the _len component correctly.  */
783       ctree = gfc_class_len_get (var);
784       if (UNLIMITED_POLY (e))
785 	{
786 	  gfc_expr *len;
787 	  gfc_se se;
788 
789 	  len = gfc_copy_expr (e);
790 	  gfc_add_len_component (len);
791 	  gfc_init_se (&se, NULL);
792 	  gfc_conv_expr (&se, len);
793 	  if (optional)
794 	    tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (se.expr),
795 			      cond_optional, se.expr,
796 			      fold_convert (TREE_TYPE (se.expr),
797 					    integer_zero_node));
798 	  else
799 	    tmp = se.expr;
800 	}
801       else
802 	tmp = integer_zero_node;
803       gfc_add_modify (&parmse->pre, ctree, fold_convert (TREE_TYPE (ctree),
804 							  tmp));
805     }
806   /* Pass the address of the class object.  */
807   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
808 
809   if (optional && optional_alloc_ptr)
810     parmse->expr = build3_loc (input_location, COND_EXPR,
811 			       TREE_TYPE (parmse->expr),
812 			       cond_optional, parmse->expr,
813 			       fold_convert (TREE_TYPE (parmse->expr),
814 					     null_pointer_node));
815 }
816 
817 
818 /* Create a new class container, which is required as scalar coarrays
819    have an array descriptor while normal scalars haven't. Optionally,
820    NULL pointer checks are added if the argument is OPTIONAL.  */
821 
822 static void
823 class_scalar_coarray_to_class (gfc_se *parmse, gfc_expr *e,
824 			       gfc_typespec class_ts, bool optional)
825 {
826   tree var, ctree, tmp;
827   stmtblock_t block;
828   gfc_ref *ref;
829   gfc_ref *class_ref;
830 
831   gfc_init_block (&block);
832 
833   class_ref = NULL;
834   for (ref = e->ref; ref; ref = ref->next)
835     {
836       if (ref->type == REF_COMPONENT
837 	    && ref->u.c.component->ts.type == BT_CLASS)
838 	class_ref = ref;
839     }
840 
841   if (class_ref == NULL
842 	&& e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
843     tmp = e->symtree->n.sym->backend_decl;
844   else
845     {
846       /* Remove everything after the last class reference, convert the
847 	 expression and then recover its tailend once more.  */
848       gfc_se tmpse;
849       ref = class_ref->next;
850       class_ref->next = NULL;
851       gfc_init_se (&tmpse, NULL);
852       gfc_conv_expr (&tmpse, e);
853       class_ref->next = ref;
854       tmp = tmpse.expr;
855     }
856 
857   var = gfc_typenode_for_spec (&class_ts);
858   var = gfc_create_var (var, "class");
859 
860   ctree = gfc_class_vptr_get (var);
861   gfc_add_modify (&block, ctree,
862 		  fold_convert (TREE_TYPE (ctree), gfc_class_vptr_get (tmp)));
863 
864   ctree = gfc_class_data_get (var);
865   tmp = gfc_conv_descriptor_data_get (gfc_class_data_get (tmp));
866   gfc_add_modify (&block, ctree, fold_convert (TREE_TYPE (ctree), tmp));
867 
868   /* Pass the address of the class object.  */
869   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
870 
871   if (optional)
872     {
873       tree cond = gfc_conv_expr_present (e->symtree->n.sym);
874       tree tmp2;
875 
876       tmp = gfc_finish_block (&block);
877 
878       gfc_init_block (&block);
879       tmp2 = gfc_class_data_get (var);
880       gfc_add_modify (&block, tmp2, fold_convert (TREE_TYPE (tmp2),
881 						  null_pointer_node));
882       tmp2 = gfc_finish_block (&block);
883 
884       tmp = build3_loc (input_location, COND_EXPR, void_type_node,
885 			cond, tmp, tmp2);
886       gfc_add_expr_to_block (&parmse->pre, tmp);
887     }
888   else
889     gfc_add_block_to_block (&parmse->pre, &block);
890 }
891 
892 
893 /* Takes an intrinsic type expression and returns the address of a temporary
894    class object of the 'declared' type.  */
895 void
896 gfc_conv_intrinsic_to_class (gfc_se *parmse, gfc_expr *e,
897 			     gfc_typespec class_ts)
898 {
899   gfc_symbol *vtab;
900   gfc_ss *ss;
901   tree ctree;
902   tree var;
903   tree tmp;
904   int dim;
905 
906   /* The intrinsic type needs to be converted to a temporary
907      CLASS object.  */
908   tmp = gfc_typenode_for_spec (&class_ts);
909   var = gfc_create_var (tmp, "class");
910 
911   /* Set the vptr.  */
912   ctree = gfc_class_vptr_get (var);
913 
914   vtab = gfc_find_vtab (&e->ts);
915   gcc_assert (vtab);
916   tmp = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtab));
917   gfc_add_modify (&parmse->pre, ctree,
918 		  fold_convert (TREE_TYPE (ctree), tmp));
919 
920   /* Now set the data field.  */
921   ctree = gfc_class_data_get (var);
922   if (parmse->ss && parmse->ss->info->useflags)
923     {
924       /* For an array reference in an elemental procedure call we need
925 	 to retain the ss to provide the scalarized array reference.  */
926       gfc_conv_expr_reference (parmse, e);
927       tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
928       gfc_add_modify (&parmse->pre, ctree, tmp);
929     }
930   else
931     {
932       ss = gfc_walk_expr (e);
933       if (ss == gfc_ss_terminator)
934 	{
935 	  parmse->ss = NULL;
936 	  gfc_conv_expr_reference (parmse, e);
937 	  if (class_ts.u.derived->components->as
938 	      && class_ts.u.derived->components->as->type == AS_ASSUMED_RANK)
939 	    {
940 	      tmp = gfc_conv_scalar_to_descriptor (parmse, parmse->expr,
941 						   gfc_expr_attr (e));
942 	      tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
943 				     TREE_TYPE (ctree), tmp);
944 	    }
945 	  else
946 	      tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
947 	  gfc_add_modify (&parmse->pre, ctree, tmp);
948 	}
949       else
950 	{
951 	  parmse->ss = ss;
952 	  parmse->use_offset = 1;
953 	  gfc_conv_expr_descriptor (parmse, e);
954 
955 	  /* Array references with vector subscripts and non-variable expressions
956 	     need be converted to a one-based descriptor.  */
957 	  if (e->expr_type != EXPR_VARIABLE)
958 	    {
959 	      for (dim = 0; dim < e->rank; ++dim)
960 		gfc_conv_shift_descriptor_lbound (&parmse->pre, parmse->expr,
961 						  dim, gfc_index_one_node);
962 	    }
963 
964 	  if (class_ts.u.derived->components->as->rank != e->rank)
965 	    {
966 	      tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
967 				     TREE_TYPE (ctree), parmse->expr);
968 	      gfc_add_modify (&parmse->pre, ctree, tmp);
969 	    }
970 	  else
971 	    gfc_add_modify (&parmse->pre, ctree, parmse->expr);
972 	}
973     }
974 
975   gcc_assert (class_ts.type == BT_CLASS);
976   if (class_ts.u.derived->components->ts.type == BT_DERIVED
977       && class_ts.u.derived->components->ts.u.derived
978 		 ->attr.unlimited_polymorphic)
979     {
980       ctree = gfc_class_len_get (var);
981       /* When the actual arg is a char array, then set the _len component of the
982 	 unlimited polymorphic entity to the length of the string.  */
983       if (e->ts.type == BT_CHARACTER)
984 	{
985 	  /* Start with parmse->string_length because this seems to be set to a
986 	   correct value more often.  */
987 	  if (parmse->string_length)
988 	    tmp = parmse->string_length;
989 	  /* When the string_length is not yet set, then try the backend_decl of
990 	   the cl.  */
991 	  else if (e->ts.u.cl->backend_decl)
992 	    tmp = e->ts.u.cl->backend_decl;
993 	  /* If both of the above approaches fail, then try to generate an
994 	   expression from the input, which is only feasible currently, when the
995 	   expression can be evaluated to a constant one.  */
996 	  else
997 	    {
998 	      /* Try to simplify the expression.  */
999 	      gfc_simplify_expr (e, 0);
1000 	      if (e->expr_type == EXPR_CONSTANT && !e->ts.u.cl->resolved)
1001 		{
1002 		  /* Amazingly all data is present to compute the length of a
1003 		   constant string, but the expression is not yet there.  */
1004 		  e->ts.u.cl->length = gfc_get_constant_expr (BT_INTEGER,
1005 							      gfc_charlen_int_kind,
1006 							      &e->where);
1007 		  mpz_set_ui (e->ts.u.cl->length->value.integer,
1008 			      e->value.character.length);
1009 		  gfc_conv_const_charlen (e->ts.u.cl);
1010 		  e->ts.u.cl->resolved = 1;
1011 		  tmp = e->ts.u.cl->backend_decl;
1012 		}
1013 	      else
1014 		{
1015 		  gfc_error ("Cannot compute the length of the char array "
1016 			     "at %L.", &e->where);
1017 		}
1018 	    }
1019 	}
1020       else
1021 	tmp = integer_zero_node;
1022 
1023       gfc_add_modify (&parmse->pre, ctree, fold_convert (TREE_TYPE (ctree), tmp));
1024     }
1025   else if (class_ts.type == BT_CLASS
1026 	   && class_ts.u.derived->components
1027 	   && class_ts.u.derived->components->ts.u
1028 		.derived->attr.unlimited_polymorphic)
1029     {
1030       ctree = gfc_class_len_get (var);
1031       gfc_add_modify (&parmse->pre, ctree,
1032 		      fold_convert (TREE_TYPE (ctree),
1033 				    integer_zero_node));
1034     }
1035   /* Pass the address of the class object.  */
1036   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
1037 }
1038 
1039 
1040 /* Takes a scalarized class array expression and returns the
1041    address of a temporary scalar class object of the 'declared'
1042    type.
1043    OOP-TODO: This could be improved by adding code that branched on
1044    the dynamic type being the same as the declared type. In this case
1045    the original class expression can be passed directly.
1046    optional_alloc_ptr is false when the dummy is neither allocatable
1047    nor a pointer; that's relevant for the optional handling.
1048    Set copyback to true if class container's _data and _vtab pointers
1049    might get modified.  */
1050 
1051 void
1052 gfc_conv_class_to_class (gfc_se *parmse, gfc_expr *e, gfc_typespec class_ts,
1053 			 bool elemental, bool copyback, bool optional,
1054 		         bool optional_alloc_ptr)
1055 {
1056   tree ctree;
1057   tree var;
1058   tree tmp;
1059   tree vptr;
1060   tree cond = NULL_TREE;
1061   tree slen = NULL_TREE;
1062   gfc_ref *ref;
1063   gfc_ref *class_ref;
1064   stmtblock_t block;
1065   bool full_array = false;
1066 
1067   gfc_init_block (&block);
1068 
1069   class_ref = NULL;
1070   for (ref = e->ref; ref; ref = ref->next)
1071     {
1072       if (ref->type == REF_COMPONENT
1073 	    && ref->u.c.component->ts.type == BT_CLASS)
1074 	class_ref = ref;
1075 
1076       if (ref->next == NULL)
1077 	break;
1078     }
1079 
1080   if ((ref == NULL || class_ref == ref)
1081       && !(gfc_is_class_array_function (e) && parmse->class_vptr != NULL_TREE)
1082       && (!class_ts.u.derived->components->as
1083 	  || class_ts.u.derived->components->as->rank != -1))
1084     return;
1085 
1086   /* Test for FULL_ARRAY.  */
1087   if (e->rank == 0 && gfc_expr_attr (e).codimension
1088       && gfc_expr_attr (e).dimension)
1089     full_array = true;
1090   else
1091     gfc_is_class_array_ref (e, &full_array);
1092 
1093   /* The derived type needs to be converted to a temporary
1094      CLASS object.  */
1095   tmp = gfc_typenode_for_spec (&class_ts);
1096   var = gfc_create_var (tmp, "class");
1097 
1098   /* Set the data.  */
1099   ctree = gfc_class_data_get (var);
1100   if (class_ts.u.derived->components->as
1101       && e->rank != class_ts.u.derived->components->as->rank)
1102     {
1103       if (e->rank == 0)
1104 	{
1105 	  tree type = get_scalar_to_descriptor_type (parmse->expr,
1106 						     gfc_expr_attr (e));
1107 	  gfc_add_modify (&block, gfc_conv_descriptor_dtype (ctree),
1108 			  gfc_get_dtype (type));
1109 
1110 	  tmp = gfc_class_data_get (parmse->expr);
1111 	  if (!POINTER_TYPE_P (TREE_TYPE (tmp)))
1112 	    tmp = gfc_build_addr_expr (NULL_TREE, tmp);
1113 
1114 	  gfc_conv_descriptor_data_set (&block, ctree, tmp);
1115 	}
1116       else
1117 	class_array_data_assign (&block, ctree, parmse->expr, false);
1118     }
1119   else
1120     {
1121       if (TREE_TYPE (parmse->expr) != TREE_TYPE (ctree))
1122 	parmse->expr = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
1123 					TREE_TYPE (ctree), parmse->expr);
1124       gfc_add_modify (&block, ctree, parmse->expr);
1125     }
1126 
1127   /* Return the data component, except in the case of scalarized array
1128      references, where nullification of the cannot occur and so there
1129      is no need.  */
1130   if (!elemental && full_array && copyback)
1131     {
1132       if (class_ts.u.derived->components->as
1133 	  && e->rank != class_ts.u.derived->components->as->rank)
1134 	{
1135 	  if (e->rank == 0)
1136 	    gfc_add_modify (&parmse->post, gfc_class_data_get (parmse->expr),
1137 			    gfc_conv_descriptor_data_get (ctree));
1138 	  else
1139 	    class_array_data_assign (&parmse->post, parmse->expr, ctree, true);
1140 	}
1141       else
1142 	gfc_add_modify (&parmse->post, parmse->expr, ctree);
1143     }
1144 
1145   /* Set the vptr.  */
1146   ctree = gfc_class_vptr_get (var);
1147 
1148   /* The vptr is the second field of the actual argument.
1149      First we have to find the corresponding class reference.  */
1150 
1151   tmp = NULL_TREE;
1152   if (gfc_is_class_array_function (e)
1153       && parmse->class_vptr != NULL_TREE)
1154     tmp = parmse->class_vptr;
1155   else if (class_ref == NULL
1156 	   && e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
1157     {
1158       tmp = e->symtree->n.sym->backend_decl;
1159 
1160       if (TREE_CODE (tmp) == FUNCTION_DECL)
1161 	tmp = gfc_get_fake_result_decl (e->symtree->n.sym, 0);
1162 
1163       if (DECL_LANG_SPECIFIC (tmp) && GFC_DECL_SAVED_DESCRIPTOR (tmp))
1164 	tmp = GFC_DECL_SAVED_DESCRIPTOR (tmp);
1165 
1166       slen = build_zero_cst (size_type_node);
1167     }
1168   else
1169     {
1170       /* Remove everything after the last class reference, convert the
1171 	 expression and then recover its tailend once more.  */
1172       gfc_se tmpse;
1173       ref = class_ref->next;
1174       class_ref->next = NULL;
1175       gfc_init_se (&tmpse, NULL);
1176       gfc_conv_expr (&tmpse, e);
1177       class_ref->next = ref;
1178       tmp = tmpse.expr;
1179       slen = tmpse.string_length;
1180     }
1181 
1182   gcc_assert (tmp != NULL_TREE);
1183 
1184   /* Dereference if needs be.  */
1185   if (TREE_CODE (TREE_TYPE (tmp)) == REFERENCE_TYPE)
1186     tmp = build_fold_indirect_ref_loc (input_location, tmp);
1187 
1188   if (!(gfc_is_class_array_function (e) && parmse->class_vptr))
1189     vptr = gfc_class_vptr_get (tmp);
1190   else
1191     vptr = tmp;
1192 
1193   gfc_add_modify (&block, ctree,
1194 		  fold_convert (TREE_TYPE (ctree), vptr));
1195 
1196   /* Return the vptr component, except in the case of scalarized array
1197      references, where the dynamic type cannot change.  */
1198   if (!elemental && full_array && copyback)
1199     gfc_add_modify (&parmse->post, vptr,
1200 		    fold_convert (TREE_TYPE (vptr), ctree));
1201 
1202   /* For unlimited polymorphic objects also set the _len component.  */
1203   if (class_ts.type == BT_CLASS
1204       && class_ts.u.derived->components
1205       && class_ts.u.derived->components->ts.u
1206 		      .derived->attr.unlimited_polymorphic)
1207     {
1208       ctree = gfc_class_len_get (var);
1209       if (UNLIMITED_POLY (e))
1210 	tmp = gfc_class_len_get (tmp);
1211       else if (e->ts.type == BT_CHARACTER)
1212 	{
1213 	  gcc_assert (slen != NULL_TREE);
1214 	  tmp = slen;
1215 	}
1216       else
1217 	tmp = build_zero_cst (size_type_node);
1218       gfc_add_modify (&parmse->pre, ctree,
1219 		      fold_convert (TREE_TYPE (ctree), tmp));
1220 
1221       /* Return the len component, except in the case of scalarized array
1222 	references, where the dynamic type cannot change.  */
1223       if (!elemental && full_array && copyback
1224 	  && (UNLIMITED_POLY (e) || VAR_P (tmp)))
1225 	  gfc_add_modify (&parmse->post, tmp,
1226 			  fold_convert (TREE_TYPE (tmp), ctree));
1227     }
1228 
1229   if (optional)
1230     {
1231       tree tmp2;
1232 
1233       cond = gfc_conv_expr_present (e->symtree->n.sym);
1234       /* parmse->pre may contain some preparatory instructions for the
1235  	 temporary array descriptor.  Those may only be executed when the
1236 	 optional argument is set, therefore add parmse->pre's instructions
1237 	 to block, which is later guarded by an if (optional_arg_given).  */
1238       gfc_add_block_to_block (&parmse->pre, &block);
1239       block.head = parmse->pre.head;
1240       parmse->pre.head = NULL_TREE;
1241       tmp = gfc_finish_block (&block);
1242 
1243       if (optional_alloc_ptr)
1244 	tmp2 = build_empty_stmt (input_location);
1245       else
1246 	{
1247 	  gfc_init_block (&block);
1248 
1249 	  tmp2 = gfc_conv_descriptor_data_get (gfc_class_data_get (var));
1250 	  gfc_add_modify (&block, tmp2, fold_convert (TREE_TYPE (tmp2),
1251 						      null_pointer_node));
1252 	  tmp2 = gfc_finish_block (&block);
1253 	}
1254 
1255       tmp = build3_loc (input_location, COND_EXPR, void_type_node,
1256 			cond, tmp, tmp2);
1257       gfc_add_expr_to_block (&parmse->pre, tmp);
1258     }
1259   else
1260     gfc_add_block_to_block (&parmse->pre, &block);
1261 
1262   /* Pass the address of the class object.  */
1263   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
1264 
1265   if (optional && optional_alloc_ptr)
1266     parmse->expr = build3_loc (input_location, COND_EXPR,
1267 			       TREE_TYPE (parmse->expr),
1268 			       cond, parmse->expr,
1269 			       fold_convert (TREE_TYPE (parmse->expr),
1270 					     null_pointer_node));
1271 }
1272 
1273 
1274 /* Given a class array declaration and an index, returns the address
1275    of the referenced element.  */
1276 
1277 tree
1278 gfc_get_class_array_ref (tree index, tree class_decl, tree data_comp,
1279 			 bool unlimited)
1280 {
1281   tree data, size, tmp, ctmp, offset, ptr;
1282 
1283   data = data_comp != NULL_TREE ? data_comp :
1284 				  gfc_class_data_get (class_decl);
1285   size = gfc_class_vtab_size_get (class_decl);
1286 
1287   if (unlimited)
1288     {
1289       tmp = fold_convert (gfc_array_index_type,
1290 			  gfc_class_len_get (class_decl));
1291       ctmp = fold_build2_loc (input_location, MULT_EXPR,
1292 			      gfc_array_index_type, size, tmp);
1293       tmp = fold_build2_loc (input_location, GT_EXPR,
1294 			     logical_type_node, tmp,
1295 			     build_zero_cst (TREE_TYPE (tmp)));
1296       size = fold_build3_loc (input_location, COND_EXPR,
1297 			      gfc_array_index_type, tmp, ctmp, size);
1298     }
1299 
1300   offset = fold_build2_loc (input_location, MULT_EXPR,
1301 			    gfc_array_index_type,
1302 			    index, size);
1303 
1304   data = gfc_conv_descriptor_data_get (data);
1305   ptr = fold_convert (pvoid_type_node, data);
1306   ptr = fold_build_pointer_plus_loc (input_location, ptr, offset);
1307   return fold_convert (TREE_TYPE (data), ptr);
1308 }
1309 
1310 
1311 /* Copies one class expression to another, assuming that if either
1312    'to' or 'from' are arrays they are packed.  Should 'from' be
1313    NULL_TREE, the initialization expression for 'to' is used, assuming
1314    that the _vptr is set.  */
1315 
1316 tree
1317 gfc_copy_class_to_class (tree from, tree to, tree nelems, bool unlimited)
1318 {
1319   tree fcn;
1320   tree fcn_type;
1321   tree from_data;
1322   tree from_len;
1323   tree to_data;
1324   tree to_len;
1325   tree to_ref;
1326   tree from_ref;
1327   vec<tree, va_gc> *args;
1328   tree tmp;
1329   tree stdcopy;
1330   tree extcopy;
1331   tree index;
1332   bool is_from_desc = false, is_to_class = false;
1333 
1334   args = NULL;
1335   /* To prevent warnings on uninitialized variables.  */
1336   from_len = to_len = NULL_TREE;
1337 
1338   if (from != NULL_TREE)
1339     fcn = gfc_class_vtab_copy_get (from);
1340   else
1341     fcn = gfc_class_vtab_copy_get (to);
1342 
1343   fcn_type = TREE_TYPE (TREE_TYPE (fcn));
1344 
1345   if (from != NULL_TREE)
1346     {
1347       is_from_desc = GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (from));
1348       if (is_from_desc)
1349 	{
1350 	  from_data = from;
1351 	  from = GFC_DECL_SAVED_DESCRIPTOR (from);
1352 	}
1353       else
1354 	{
1355 	  /* Check that from is a class.  When the class is part of a coarray,
1356 	     then from is a common pointer and is to be used as is.  */
1357 	  tmp = POINTER_TYPE_P (TREE_TYPE (from))
1358 	      ? build_fold_indirect_ref (from) : from;
1359 	  from_data =
1360 	      (GFC_CLASS_TYPE_P (TREE_TYPE (tmp))
1361 	       || (DECL_P (tmp) && GFC_DECL_CLASS (tmp)))
1362 	      ? gfc_class_data_get (from) : from;
1363 	  is_from_desc = GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (from_data));
1364 	}
1365      }
1366   else
1367     from_data = gfc_class_vtab_def_init_get (to);
1368 
1369   if (unlimited)
1370     {
1371       if (from != NULL_TREE && unlimited)
1372 	from_len = gfc_class_len_or_zero_get (from);
1373       else
1374 	from_len = build_zero_cst (size_type_node);
1375     }
1376 
1377   if (GFC_CLASS_TYPE_P (TREE_TYPE (to)))
1378     {
1379       is_to_class = true;
1380       to_data = gfc_class_data_get (to);
1381       if (unlimited)
1382 	to_len = gfc_class_len_get (to);
1383     }
1384   else
1385     /* When to is a BT_DERIVED and not a BT_CLASS, then to_data == to.  */
1386     to_data = to;
1387 
1388   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (to_data)))
1389     {
1390       stmtblock_t loopbody;
1391       stmtblock_t body;
1392       stmtblock_t ifbody;
1393       gfc_loopinfo loop;
1394       tree orig_nelems = nelems; /* Needed for bounds check.  */
1395 
1396       gfc_init_block (&body);
1397       tmp = fold_build2_loc (input_location, MINUS_EXPR,
1398 			     gfc_array_index_type, nelems,
1399 			     gfc_index_one_node);
1400       nelems = gfc_evaluate_now (tmp, &body);
1401       index = gfc_create_var (gfc_array_index_type, "S");
1402 
1403       if (is_from_desc)
1404 	{
1405 	  from_ref = gfc_get_class_array_ref (index, from, from_data,
1406 					      unlimited);
1407 	  vec_safe_push (args, from_ref);
1408 	}
1409       else
1410         vec_safe_push (args, from_data);
1411 
1412       if (is_to_class)
1413 	to_ref = gfc_get_class_array_ref (index, to, to_data, unlimited);
1414       else
1415 	{
1416 	  tmp = gfc_conv_array_data (to);
1417 	  tmp = build_fold_indirect_ref_loc (input_location, tmp);
1418 	  to_ref = gfc_build_addr_expr (NULL_TREE,
1419 					gfc_build_array_ref (tmp, index, to));
1420 	}
1421       vec_safe_push (args, to_ref);
1422 
1423       /* Add bounds check.  */
1424       if ((gfc_option.rtcheck & GFC_RTCHECK_BOUNDS) > 0 && is_from_desc)
1425 	{
1426 	  char *msg;
1427 	  const char *name = "<<unknown>>";
1428 	  tree from_len;
1429 
1430 	  if (DECL_P (to))
1431 	    name = (const char *)(DECL_NAME (to)->identifier.id.str);
1432 
1433 	  from_len = gfc_conv_descriptor_size (from_data, 1);
1434 	  tmp = fold_build2_loc (input_location, NE_EXPR,
1435 				  logical_type_node, from_len, orig_nelems);
1436 	  msg = xasprintf ("Array bound mismatch for dimension %d "
1437 			   "of array '%s' (%%ld/%%ld)",
1438 			   1, name);
1439 
1440 	  gfc_trans_runtime_check (true, false, tmp, &body,
1441 				   &gfc_current_locus, msg,
1442 			     fold_convert (long_integer_type_node, orig_nelems),
1443 			       fold_convert (long_integer_type_node, from_len));
1444 
1445 	  free (msg);
1446 	}
1447 
1448       tmp = build_call_vec (fcn_type, fcn, args);
1449 
1450       /* Build the body of the loop.  */
1451       gfc_init_block (&loopbody);
1452       gfc_add_expr_to_block (&loopbody, tmp);
1453 
1454       /* Build the loop and return.  */
1455       gfc_init_loopinfo (&loop);
1456       loop.dimen = 1;
1457       loop.from[0] = gfc_index_zero_node;
1458       loop.loopvar[0] = index;
1459       loop.to[0] = nelems;
1460       gfc_trans_scalarizing_loops (&loop, &loopbody);
1461       gfc_init_block (&ifbody);
1462       gfc_add_block_to_block (&ifbody, &loop.pre);
1463       stdcopy = gfc_finish_block (&ifbody);
1464       /* In initialization mode from_len is a constant zero.  */
1465       if (unlimited && !integer_zerop (from_len))
1466 	{
1467 	  vec_safe_push (args, from_len);
1468 	  vec_safe_push (args, to_len);
1469 	  tmp = build_call_vec (fcn_type, fcn, args);
1470 	  /* Build the body of the loop.  */
1471 	  gfc_init_block (&loopbody);
1472 	  gfc_add_expr_to_block (&loopbody, tmp);
1473 
1474 	  /* Build the loop and return.  */
1475 	  gfc_init_loopinfo (&loop);
1476 	  loop.dimen = 1;
1477 	  loop.from[0] = gfc_index_zero_node;
1478 	  loop.loopvar[0] = index;
1479 	  loop.to[0] = nelems;
1480 	  gfc_trans_scalarizing_loops (&loop, &loopbody);
1481 	  gfc_init_block (&ifbody);
1482 	  gfc_add_block_to_block (&ifbody, &loop.pre);
1483 	  extcopy = gfc_finish_block (&ifbody);
1484 
1485 	  tmp = fold_build2_loc (input_location, GT_EXPR,
1486 				 logical_type_node, from_len,
1487 				 build_zero_cst (TREE_TYPE (from_len)));
1488 	  tmp = fold_build3_loc (input_location, COND_EXPR,
1489 				 void_type_node, tmp, extcopy, stdcopy);
1490 	  gfc_add_expr_to_block (&body, tmp);
1491 	  tmp = gfc_finish_block (&body);
1492 	}
1493       else
1494 	{
1495 	  gfc_add_expr_to_block (&body, stdcopy);
1496 	  tmp = gfc_finish_block (&body);
1497 	}
1498       gfc_cleanup_loop (&loop);
1499     }
1500   else
1501     {
1502       gcc_assert (!is_from_desc);
1503       vec_safe_push (args, from_data);
1504       vec_safe_push (args, to_data);
1505       stdcopy = build_call_vec (fcn_type, fcn, args);
1506 
1507       /* In initialization mode from_len is a constant zero.  */
1508       if (unlimited && !integer_zerop (from_len))
1509 	{
1510 	  vec_safe_push (args, from_len);
1511 	  vec_safe_push (args, to_len);
1512 	  extcopy = build_call_vec (fcn_type, fcn, args);
1513 	  tmp = fold_build2_loc (input_location, GT_EXPR,
1514 				 logical_type_node, from_len,
1515 				 build_zero_cst (TREE_TYPE (from_len)));
1516 	  tmp = fold_build3_loc (input_location, COND_EXPR,
1517 				 void_type_node, tmp, extcopy, stdcopy);
1518 	}
1519       else
1520 	tmp = stdcopy;
1521     }
1522 
1523   /* Only copy _def_init to to_data, when it is not a NULL-pointer.  */
1524   if (from == NULL_TREE)
1525     {
1526       tree cond;
1527       cond = fold_build2_loc (input_location, NE_EXPR,
1528 			      logical_type_node,
1529 			      from_data, null_pointer_node);
1530       tmp = fold_build3_loc (input_location, COND_EXPR,
1531 			     void_type_node, cond,
1532 			     tmp, build_empty_stmt (input_location));
1533     }
1534 
1535   return tmp;
1536 }
1537 
1538 
1539 static tree
1540 gfc_trans_class_array_init_assign (gfc_expr *rhs, gfc_expr *lhs, gfc_expr *obj)
1541 {
1542   gfc_actual_arglist *actual;
1543   gfc_expr *ppc;
1544   gfc_code *ppc_code;
1545   tree res;
1546 
1547   actual = gfc_get_actual_arglist ();
1548   actual->expr = gfc_copy_expr (rhs);
1549   actual->next = gfc_get_actual_arglist ();
1550   actual->next->expr = gfc_copy_expr (lhs);
1551   ppc = gfc_copy_expr (obj);
1552   gfc_add_vptr_component (ppc);
1553   gfc_add_component_ref (ppc, "_copy");
1554   ppc_code = gfc_get_code (EXEC_CALL);
1555   ppc_code->resolved_sym = ppc->symtree->n.sym;
1556   /* Although '_copy' is set to be elemental in class.c, it is
1557      not staying that way.  Find out why, sometime....  */
1558   ppc_code->resolved_sym->attr.elemental = 1;
1559   ppc_code->ext.actual = actual;
1560   ppc_code->expr1 = ppc;
1561   /* Since '_copy' is elemental, the scalarizer will take care
1562      of arrays in gfc_trans_call.  */
1563   res = gfc_trans_call (ppc_code, false, NULL, NULL, false);
1564   gfc_free_statements (ppc_code);
1565 
1566   if (UNLIMITED_POLY(obj))
1567     {
1568       /* Check if rhs is non-NULL. */
1569       gfc_se src;
1570       gfc_init_se (&src, NULL);
1571       gfc_conv_expr (&src, rhs);
1572       src.expr = gfc_build_addr_expr (NULL_TREE, src.expr);
1573       tree cond = fold_build2_loc (input_location, NE_EXPR, logical_type_node,
1574 				   src.expr, fold_convert (TREE_TYPE (src.expr),
1575 							   null_pointer_node));
1576       res = build3_loc (input_location, COND_EXPR, TREE_TYPE (res), cond, res,
1577 			build_empty_stmt (input_location));
1578     }
1579 
1580   return res;
1581 }
1582 
1583 /* Special case for initializing a polymorphic dummy with INTENT(OUT).
1584    A MEMCPY is needed to copy the full data from the default initializer
1585    of the dynamic type.  */
1586 
1587 tree
1588 gfc_trans_class_init_assign (gfc_code *code)
1589 {
1590   stmtblock_t block;
1591   tree tmp;
1592   gfc_se dst,src,memsz;
1593   gfc_expr *lhs, *rhs, *sz;
1594 
1595   gfc_start_block (&block);
1596 
1597   lhs = gfc_copy_expr (code->expr1);
1598 
1599   rhs = gfc_copy_expr (code->expr1);
1600   gfc_add_vptr_component (rhs);
1601 
1602   /* Make sure that the component backend_decls have been built, which
1603      will not have happened if the derived types concerned have not
1604      been referenced.  */
1605   gfc_get_derived_type (rhs->ts.u.derived);
1606   gfc_add_def_init_component (rhs);
1607   /* The _def_init is always scalar.  */
1608   rhs->rank = 0;
1609 
1610   if (code->expr1->ts.type == BT_CLASS
1611       && CLASS_DATA (code->expr1)->attr.dimension)
1612     {
1613       gfc_array_spec *tmparr = gfc_get_array_spec ();
1614       *tmparr = *CLASS_DATA (code->expr1)->as;
1615       /* Adding the array ref to the class expression results in correct
1616 	 indexing to the dynamic type.  */
1617       gfc_add_full_array_ref (lhs, tmparr);
1618       tmp = gfc_trans_class_array_init_assign (rhs, lhs, code->expr1);
1619     }
1620   else
1621     {
1622       /* Scalar initialization needs the _data component.  */
1623       gfc_add_data_component (lhs);
1624       sz = gfc_copy_expr (code->expr1);
1625       gfc_add_vptr_component (sz);
1626       gfc_add_size_component (sz);
1627 
1628       gfc_init_se (&dst, NULL);
1629       gfc_init_se (&src, NULL);
1630       gfc_init_se (&memsz, NULL);
1631       gfc_conv_expr (&dst, lhs);
1632       gfc_conv_expr (&src, rhs);
1633       gfc_conv_expr (&memsz, sz);
1634       gfc_add_block_to_block (&block, &src.pre);
1635       src.expr = gfc_build_addr_expr (NULL_TREE, src.expr);
1636 
1637       tmp = gfc_build_memcpy_call (dst.expr, src.expr, memsz.expr);
1638 
1639       if (UNLIMITED_POLY(code->expr1))
1640 	{
1641 	  /* Check if _def_init is non-NULL. */
1642 	  tree cond = fold_build2_loc (input_location, NE_EXPR,
1643 				       logical_type_node, src.expr,
1644 				       fold_convert (TREE_TYPE (src.expr),
1645 						     null_pointer_node));
1646 	  tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp), cond,
1647 			    tmp, build_empty_stmt (input_location));
1648 	}
1649     }
1650 
1651   if (code->expr1->symtree->n.sym->attr.dummy
1652       && (code->expr1->symtree->n.sym->attr.optional
1653 	  || code->expr1->symtree->n.sym->ns->proc_name->attr.entry_master))
1654     {
1655       tree present = gfc_conv_expr_present (code->expr1->symtree->n.sym);
1656       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp),
1657 			present, tmp,
1658 			build_empty_stmt (input_location));
1659     }
1660 
1661   gfc_add_expr_to_block (&block, tmp);
1662 
1663   return gfc_finish_block (&block);
1664 }
1665 
1666 
1667 /* Class valued elemental function calls or class array elements arriving
1668    in gfc_trans_scalar_assign come here.  Wherever possible the vptr copy
1669    is used to ensure that the rhs dynamic type is assigned to the lhs.  */
1670 
1671 static bool
1672 trans_scalar_class_assign (stmtblock_t *block, gfc_se *lse, gfc_se *rse)
1673 {
1674   tree fcn;
1675   tree rse_expr;
1676   tree class_data;
1677   tree tmp;
1678   tree zero;
1679   tree cond;
1680   tree final_cond;
1681   stmtblock_t inner_block;
1682   bool is_descriptor;
1683   bool not_call_expr = TREE_CODE (rse->expr) != CALL_EXPR;
1684   bool not_lhs_array_type;
1685 
1686   /* Temporaries arising from depencies in assignment get cast as a
1687      character type of the dynamic size of the rhs. Use the vptr copy
1688      for this case.  */
1689   tmp = TREE_TYPE (lse->expr);
1690   not_lhs_array_type = !(tmp && TREE_CODE (tmp) == ARRAY_TYPE
1691 			 && TYPE_MAX_VALUE (TYPE_DOMAIN (tmp)) != NULL_TREE);
1692 
1693   /* Use ordinary assignment if the rhs is not a call expression or
1694      the lhs is not a class entity or an array(ie. character) type.  */
1695   if ((not_call_expr && gfc_get_class_from_expr (lse->expr) == NULL_TREE)
1696       && not_lhs_array_type)
1697     return false;
1698 
1699   /* Ordinary assignment can be used if both sides are class expressions
1700      since the dynamic type is preserved by copying the vptr.  This
1701      should only occur, where temporaries are involved.  */
1702   if (GFC_CLASS_TYPE_P (TREE_TYPE (lse->expr))
1703       && GFC_CLASS_TYPE_P (TREE_TYPE (rse->expr)))
1704     return false;
1705 
1706   /* Fix the class expression and the class data of the rhs.  */
1707   if (!GFC_CLASS_TYPE_P (TREE_TYPE (rse->expr))
1708       || not_call_expr)
1709     {
1710       tmp = gfc_get_class_from_expr (rse->expr);
1711       if (tmp == NULL_TREE)
1712 	return false;
1713       rse_expr = gfc_evaluate_now (tmp, block);
1714     }
1715   else
1716     rse_expr = gfc_evaluate_now (rse->expr, block);
1717 
1718   class_data = gfc_class_data_get (rse_expr);
1719 
1720   /* Check that the rhs data is not null.  */
1721   is_descriptor = GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (class_data));
1722   if (is_descriptor)
1723     class_data = gfc_conv_descriptor_data_get (class_data);
1724   class_data = gfc_evaluate_now (class_data, block);
1725 
1726   zero = build_int_cst (TREE_TYPE (class_data), 0);
1727   cond = fold_build2_loc (input_location, NE_EXPR,
1728 			  logical_type_node,
1729 			  class_data, zero);
1730 
1731   /* Copy the rhs to the lhs.  */
1732   fcn = gfc_vptr_copy_get (gfc_class_vptr_get (rse_expr));
1733   fcn = build_fold_indirect_ref_loc (input_location, fcn);
1734   tmp = gfc_evaluate_now (gfc_build_addr_expr (NULL, rse->expr), block);
1735   tmp = is_descriptor ? tmp : class_data;
1736   tmp = build_call_expr_loc (input_location, fcn, 2, tmp,
1737 			     gfc_build_addr_expr (NULL, lse->expr));
1738   gfc_add_expr_to_block (block, tmp);
1739 
1740   /* Only elemental function results need to be finalised and freed.  */
1741   if (not_call_expr)
1742     return true;
1743 
1744   /* Finalize the class data if needed.  */
1745   gfc_init_block (&inner_block);
1746   fcn = gfc_vptr_final_get (gfc_class_vptr_get (rse_expr));
1747   zero = build_int_cst (TREE_TYPE (fcn), 0);
1748   final_cond = fold_build2_loc (input_location, NE_EXPR,
1749 				logical_type_node, fcn, zero);
1750   fcn = build_fold_indirect_ref_loc (input_location, fcn);
1751   tmp = build_call_expr_loc (input_location, fcn, 1, class_data);
1752   tmp = build3_v (COND_EXPR, final_cond,
1753 		  tmp, build_empty_stmt (input_location));
1754   gfc_add_expr_to_block (&inner_block, tmp);
1755 
1756   /* Free the class data.  */
1757   tmp = gfc_call_free (class_data);
1758   tmp = build3_v (COND_EXPR, cond, tmp,
1759 		  build_empty_stmt (input_location));
1760   gfc_add_expr_to_block (&inner_block, tmp);
1761 
1762   /* Finish the inner block and subject it to the condition on the
1763      class data being non-zero.  */
1764   tmp = gfc_finish_block (&inner_block);
1765   tmp = build3_v (COND_EXPR, cond, tmp,
1766 		  build_empty_stmt (input_location));
1767   gfc_add_expr_to_block (block, tmp);
1768 
1769   return true;
1770 }
1771 
1772 /* End of prototype trans-class.c  */
1773 
1774 
1775 static void
1776 realloc_lhs_warning (bt type, bool array, locus *where)
1777 {
1778   if (array && type != BT_CLASS && type != BT_DERIVED && warn_realloc_lhs)
1779     gfc_warning (OPT_Wrealloc_lhs,
1780 		 "Code for reallocating the allocatable array at %L will "
1781 		 "be added", where);
1782   else if (warn_realloc_lhs_all)
1783     gfc_warning (OPT_Wrealloc_lhs_all,
1784 		 "Code for reallocating the allocatable variable at %L "
1785 		 "will be added", where);
1786 }
1787 
1788 
1789 static void gfc_apply_interface_mapping_to_expr (gfc_interface_mapping *,
1790 						 gfc_expr *);
1791 
1792 /* Copy the scalarization loop variables.  */
1793 
1794 static void
1795 gfc_copy_se_loopvars (gfc_se * dest, gfc_se * src)
1796 {
1797   dest->ss = src->ss;
1798   dest->loop = src->loop;
1799 }
1800 
1801 
1802 /* Initialize a simple expression holder.
1803 
1804    Care must be taken when multiple se are created with the same parent.
1805    The child se must be kept in sync.  The easiest way is to delay creation
1806    of a child se until after the previous se has been translated.  */
1807 
1808 void
1809 gfc_init_se (gfc_se * se, gfc_se * parent)
1810 {
1811   memset (se, 0, sizeof (gfc_se));
1812   gfc_init_block (&se->pre);
1813   gfc_init_block (&se->post);
1814 
1815   se->parent = parent;
1816 
1817   if (parent)
1818     gfc_copy_se_loopvars (se, parent);
1819 }
1820 
1821 
1822 /* Advances to the next SS in the chain.  Use this rather than setting
1823    se->ss = se->ss->next because all the parents needs to be kept in sync.
1824    See gfc_init_se.  */
1825 
1826 void
1827 gfc_advance_se_ss_chain (gfc_se * se)
1828 {
1829   gfc_se *p;
1830   gfc_ss *ss;
1831 
1832   gcc_assert (se != NULL && se->ss != NULL && se->ss != gfc_ss_terminator);
1833 
1834   p = se;
1835   /* Walk down the parent chain.  */
1836   while (p != NULL)
1837     {
1838       /* Simple consistency check.  */
1839       gcc_assert (p->parent == NULL || p->parent->ss == p->ss
1840 		  || p->parent->ss->nested_ss == p->ss);
1841 
1842       /* If we were in a nested loop, the next scalarized expression can be
1843 	 on the parent ss' next pointer.  Thus we should not take the next
1844 	 pointer blindly, but rather go up one nest level as long as next
1845 	 is the end of chain.  */
1846       ss = p->ss;
1847       while (ss->next == gfc_ss_terminator && ss->parent != NULL)
1848 	ss = ss->parent;
1849 
1850       p->ss = ss->next;
1851 
1852       p = p->parent;
1853     }
1854 }
1855 
1856 
1857 /* Ensures the result of the expression as either a temporary variable
1858    or a constant so that it can be used repeatedly.  */
1859 
1860 void
1861 gfc_make_safe_expr (gfc_se * se)
1862 {
1863   tree var;
1864 
1865   if (CONSTANT_CLASS_P (se->expr))
1866     return;
1867 
1868   /* We need a temporary for this result.  */
1869   var = gfc_create_var (TREE_TYPE (se->expr), NULL);
1870   gfc_add_modify (&se->pre, var, se->expr);
1871   se->expr = var;
1872 }
1873 
1874 
1875 /* Return an expression which determines if a dummy parameter is present.
1876    Also used for arguments to procedures with multiple entry points.  */
1877 
1878 tree
1879 gfc_conv_expr_present (gfc_symbol * sym, bool use_saved_desc)
1880 {
1881   tree decl, orig_decl, cond;
1882 
1883   gcc_assert (sym->attr.dummy);
1884   orig_decl = decl = gfc_get_symbol_decl (sym);
1885 
1886   /* Intrinsic scalars with VALUE attribute which are passed by value
1887      use a hidden argument to denote the present status.  */
1888   if (sym->attr.value && sym->ts.type != BT_CHARACTER
1889       && sym->ts.type != BT_CLASS && sym->ts.type != BT_DERIVED
1890       && !sym->attr.dimension)
1891     {
1892       char name[GFC_MAX_SYMBOL_LEN + 2];
1893       tree tree_name;
1894 
1895       gcc_assert (TREE_CODE (decl) == PARM_DECL);
1896       name[0] = '_';
1897       strcpy (&name[1], sym->name);
1898       tree_name = get_identifier (name);
1899 
1900       /* Walk function argument list to find hidden arg.  */
1901       cond = DECL_ARGUMENTS (DECL_CONTEXT (decl));
1902       for ( ; cond != NULL_TREE; cond = TREE_CHAIN (cond))
1903 	if (DECL_NAME (cond) == tree_name
1904 	    && DECL_ARTIFICIAL (cond))
1905 	  break;
1906 
1907       gcc_assert (cond);
1908       return cond;
1909     }
1910 
1911   /* Assumed-shape arrays use a local variable for the array data;
1912      the actual PARAM_DECL is in a saved decl.  As the local variable
1913      is NULL, it can be checked instead, unless use_saved_desc is
1914      requested.  */
1915 
1916   if (use_saved_desc && TREE_CODE (decl) != PARM_DECL)
1917     {
1918       gcc_assert (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (decl))
1919              || GFC_ARRAY_TYPE_P (TREE_TYPE (decl)));
1920       decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
1921     }
1922 
1923   cond = fold_build2_loc (input_location, NE_EXPR, logical_type_node, decl,
1924 			  fold_convert (TREE_TYPE (decl), null_pointer_node));
1925 
1926   /* Fortran 2008 allows to pass null pointers and non-associated pointers
1927      as actual argument to denote absent dummies. For array descriptors,
1928      we thus also need to check the array descriptor.  For BT_CLASS, it
1929      can also occur for scalars and F2003 due to type->class wrapping and
1930      class->class wrapping.  Note further that BT_CLASS always uses an
1931      array descriptor for arrays, also for explicit-shape/assumed-size.
1932      For assumed-rank arrays, no local variable is generated, hence,
1933      the following also applies with !use_saved_desc.  */
1934 
1935   if ((use_saved_desc || TREE_CODE (orig_decl) == PARM_DECL)
1936       && !sym->attr.allocatable
1937       && ((sym->ts.type != BT_CLASS && !sym->attr.pointer)
1938 	  || (sym->ts.type == BT_CLASS
1939 	      && !CLASS_DATA (sym)->attr.allocatable
1940 	      && !CLASS_DATA (sym)->attr.class_pointer))
1941       && ((gfc_option.allow_std & GFC_STD_F2008) != 0
1942 	  || sym->ts.type == BT_CLASS))
1943     {
1944       tree tmp;
1945 
1946       if ((sym->as && (sym->as->type == AS_ASSUMED_SHAPE
1947 		       || sym->as->type == AS_ASSUMED_RANK
1948 		       || sym->attr.codimension))
1949 	  || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)->as))
1950 	{
1951 	  tmp = build_fold_indirect_ref_loc (input_location, decl);
1952 	  if (sym->ts.type == BT_CLASS)
1953 	    tmp = gfc_class_data_get (tmp);
1954 	  tmp = gfc_conv_array_data (tmp);
1955 	}
1956       else if (sym->ts.type == BT_CLASS)
1957 	tmp = gfc_class_data_get (decl);
1958       else
1959 	tmp = NULL_TREE;
1960 
1961       if (tmp != NULL_TREE)
1962 	{
1963 	  tmp = fold_build2_loc (input_location, NE_EXPR, logical_type_node, tmp,
1964 				 fold_convert (TREE_TYPE (tmp), null_pointer_node));
1965 	  cond = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
1966 				  logical_type_node, cond, tmp);
1967 	}
1968     }
1969 
1970   return cond;
1971 }
1972 
1973 
1974 /* Converts a missing, dummy argument into a null or zero.  */
1975 
1976 void
1977 gfc_conv_missing_dummy (gfc_se * se, gfc_expr * arg, gfc_typespec ts, int kind)
1978 {
1979   tree present;
1980   tree tmp;
1981 
1982   present = gfc_conv_expr_present (arg->symtree->n.sym);
1983 
1984   if (kind > 0)
1985     {
1986       /* Create a temporary and convert it to the correct type.  */
1987       tmp = gfc_get_int_type (kind);
1988       tmp = fold_convert (tmp, build_fold_indirect_ref_loc (input_location,
1989 							se->expr));
1990 
1991       /* Test for a NULL value.  */
1992       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp), present,
1993 			tmp, fold_convert (TREE_TYPE (tmp), integer_one_node));
1994       tmp = gfc_evaluate_now (tmp, &se->pre);
1995       se->expr = gfc_build_addr_expr (NULL_TREE, tmp);
1996     }
1997   else
1998     {
1999       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (se->expr),
2000 			present, se->expr,
2001 			build_zero_cst (TREE_TYPE (se->expr)));
2002       tmp = gfc_evaluate_now (tmp, &se->pre);
2003       se->expr = tmp;
2004     }
2005 
2006   if (ts.type == BT_CHARACTER)
2007     {
2008       tmp = build_int_cst (gfc_charlen_type_node, 0);
2009       tmp = fold_build3_loc (input_location, COND_EXPR, gfc_charlen_type_node,
2010 			     present, se->string_length, tmp);
2011       tmp = gfc_evaluate_now (tmp, &se->pre);
2012       se->string_length = tmp;
2013     }
2014   return;
2015 }
2016 
2017 
2018 /* Get the character length of an expression, looking through gfc_refs
2019    if necessary.  */
2020 
2021 tree
2022 gfc_get_expr_charlen (gfc_expr *e)
2023 {
2024   gfc_ref *r;
2025   tree length;
2026   gfc_se se;
2027 
2028   gcc_assert (e->expr_type == EXPR_VARIABLE
2029 	      && e->ts.type == BT_CHARACTER);
2030 
2031   length = NULL; /* To silence compiler warning.  */
2032 
2033   if (is_subref_array (e) && e->ts.u.cl->length)
2034     {
2035       gfc_se tmpse;
2036       gfc_init_se (&tmpse, NULL);
2037       gfc_conv_expr_type (&tmpse, e->ts.u.cl->length, gfc_charlen_type_node);
2038       e->ts.u.cl->backend_decl = tmpse.expr;
2039       return tmpse.expr;
2040     }
2041 
2042   /* First candidate: if the variable is of type CHARACTER, the
2043      expression's length could be the length of the character
2044      variable.  */
2045   if (e->symtree->n.sym->ts.type == BT_CHARACTER)
2046     length = e->symtree->n.sym->ts.u.cl->backend_decl;
2047 
2048   /* Look through the reference chain for component references.  */
2049   for (r = e->ref; r; r = r->next)
2050     {
2051       switch (r->type)
2052 	{
2053 	case REF_COMPONENT:
2054 	  if (r->u.c.component->ts.type == BT_CHARACTER)
2055 	    length = r->u.c.component->ts.u.cl->backend_decl;
2056 	  break;
2057 
2058 	case REF_ARRAY:
2059 	  /* Do nothing.  */
2060 	  break;
2061 
2062 	case REF_SUBSTRING:
2063 	  gfc_init_se (&se, NULL);
2064 	  gfc_conv_expr_type (&se, r->u.ss.start, gfc_charlen_type_node);
2065 	  length = se.expr;
2066 	  gfc_conv_expr_type (&se, r->u.ss.end, gfc_charlen_type_node);
2067 	  length = fold_build2_loc (input_location, MINUS_EXPR,
2068 				    gfc_charlen_type_node,
2069 				    se.expr, length);
2070 	  length = fold_build2_loc (input_location, PLUS_EXPR,
2071 				    gfc_charlen_type_node, length,
2072 				    gfc_index_one_node);
2073 	  break;
2074 
2075 	default:
2076 	  gcc_unreachable ();
2077 	  break;
2078 	}
2079     }
2080 
2081   gcc_assert (length != NULL);
2082   return length;
2083 }
2084 
2085 
2086 /* Return for an expression the backend decl of the coarray.  */
2087 
2088 tree
2089 gfc_get_tree_for_caf_expr (gfc_expr *expr)
2090 {
2091   tree caf_decl;
2092   bool found = false;
2093   gfc_ref *ref;
2094 
2095   gcc_assert (expr && expr->expr_type == EXPR_VARIABLE);
2096 
2097   /* Not-implemented diagnostic.  */
2098   if (expr->symtree->n.sym->ts.type == BT_CLASS
2099       && UNLIMITED_POLY (expr->symtree->n.sym)
2100       && CLASS_DATA (expr->symtree->n.sym)->attr.codimension)
2101     gfc_error ("Sorry, coindexed access to an unlimited polymorphic object at "
2102 	       "%L is not supported", &expr->where);
2103 
2104   for (ref = expr->ref; ref; ref = ref->next)
2105     if (ref->type == REF_COMPONENT)
2106       {
2107 	if (ref->u.c.component->ts.type == BT_CLASS
2108 	    && UNLIMITED_POLY (ref->u.c.component)
2109 	    && CLASS_DATA (ref->u.c.component)->attr.codimension)
2110 	  gfc_error ("Sorry, coindexed access to an unlimited polymorphic "
2111 		     "component at %L is not supported", &expr->where);
2112       }
2113 
2114   /* Make sure the backend_decl is present before accessing it.  */
2115   caf_decl = expr->symtree->n.sym->backend_decl == NULL_TREE
2116       ? gfc_get_symbol_decl (expr->symtree->n.sym)
2117       : expr->symtree->n.sym->backend_decl;
2118 
2119   if (expr->symtree->n.sym->ts.type == BT_CLASS)
2120     {
2121       if (expr->ref && expr->ref->type == REF_ARRAY)
2122 	{
2123 	  caf_decl = gfc_class_data_get (caf_decl);
2124 	  if (CLASS_DATA (expr->symtree->n.sym)->attr.codimension)
2125 	    return caf_decl;
2126 	}
2127       for (ref = expr->ref; ref; ref = ref->next)
2128 	{
2129 	  if (ref->type == REF_COMPONENT
2130 	      && strcmp (ref->u.c.component->name, "_data") != 0)
2131 	    {
2132 	      caf_decl = gfc_class_data_get (caf_decl);
2133 	      if (CLASS_DATA (expr->symtree->n.sym)->attr.codimension)
2134 		return caf_decl;
2135 	      break;
2136 	    }
2137 	  else if (ref->type == REF_ARRAY && ref->u.ar.dimen)
2138 	    break;
2139 	}
2140     }
2141   if (expr->symtree->n.sym->attr.codimension)
2142     return caf_decl;
2143 
2144   /* The following code assumes that the coarray is a component reachable via
2145      only scalar components/variables; the Fortran standard guarantees this.  */
2146 
2147   for (ref = expr->ref; ref; ref = ref->next)
2148     if (ref->type == REF_COMPONENT)
2149       {
2150 	gfc_component *comp = ref->u.c.component;
2151 
2152 	if (POINTER_TYPE_P (TREE_TYPE (caf_decl)))
2153 	  caf_decl = build_fold_indirect_ref_loc (input_location, caf_decl);
2154 	caf_decl = fold_build3_loc (input_location, COMPONENT_REF,
2155 				    TREE_TYPE (comp->backend_decl), caf_decl,
2156 				    comp->backend_decl, NULL_TREE);
2157 	if (comp->ts.type == BT_CLASS)
2158 	  {
2159 	    caf_decl = gfc_class_data_get (caf_decl);
2160 	    if (CLASS_DATA (comp)->attr.codimension)
2161 	      {
2162 		found = true;
2163 		break;
2164 	      }
2165 	  }
2166 	if (comp->attr.codimension)
2167 	  {
2168 	    found = true;
2169 	    break;
2170 	  }
2171       }
2172   gcc_assert (found && caf_decl);
2173   return caf_decl;
2174 }
2175 
2176 
2177 /* Obtain the Coarray token - and optionally also the offset.  */
2178 
2179 void
2180 gfc_get_caf_token_offset (gfc_se *se, tree *token, tree *offset, tree caf_decl,
2181 			  tree se_expr, gfc_expr *expr)
2182 {
2183   tree tmp;
2184 
2185   /* Coarray token.  */
2186   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (caf_decl)))
2187     {
2188       gcc_assert (GFC_TYPE_ARRAY_AKIND (TREE_TYPE (caf_decl))
2189 		    == GFC_ARRAY_ALLOCATABLE
2190 		  || expr->symtree->n.sym->attr.select_type_temporary);
2191       *token = gfc_conv_descriptor_token (caf_decl);
2192     }
2193   else if (DECL_LANG_SPECIFIC (caf_decl)
2194 	   && GFC_DECL_TOKEN (caf_decl) != NULL_TREE)
2195     *token = GFC_DECL_TOKEN (caf_decl);
2196   else
2197     {
2198       gcc_assert (GFC_ARRAY_TYPE_P (TREE_TYPE (caf_decl))
2199 		  && GFC_TYPE_ARRAY_CAF_TOKEN (TREE_TYPE (caf_decl)) != NULL_TREE);
2200       *token = GFC_TYPE_ARRAY_CAF_TOKEN (TREE_TYPE (caf_decl));
2201     }
2202 
2203   if (offset == NULL)
2204     return;
2205 
2206   /* Offset between the coarray base address and the address wanted.  */
2207   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (caf_decl))
2208       && (GFC_TYPE_ARRAY_AKIND (TREE_TYPE (caf_decl)) == GFC_ARRAY_ALLOCATABLE
2209 	  || GFC_TYPE_ARRAY_AKIND (TREE_TYPE (caf_decl)) == GFC_ARRAY_POINTER))
2210     *offset = build_int_cst (gfc_array_index_type, 0);
2211   else if (DECL_LANG_SPECIFIC (caf_decl)
2212 	   && GFC_DECL_CAF_OFFSET (caf_decl) != NULL_TREE)
2213     *offset = GFC_DECL_CAF_OFFSET (caf_decl);
2214   else if (GFC_TYPE_ARRAY_CAF_OFFSET (TREE_TYPE (caf_decl)) != NULL_TREE)
2215     *offset = GFC_TYPE_ARRAY_CAF_OFFSET (TREE_TYPE (caf_decl));
2216   else
2217     *offset = build_int_cst (gfc_array_index_type, 0);
2218 
2219   if (POINTER_TYPE_P (TREE_TYPE (se_expr))
2220       && GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (TREE_TYPE (se_expr))))
2221     {
2222       tmp = build_fold_indirect_ref_loc (input_location, se_expr);
2223       tmp = gfc_conv_descriptor_data_get (tmp);
2224     }
2225   else if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (se_expr)))
2226     tmp = gfc_conv_descriptor_data_get (se_expr);
2227   else
2228     {
2229       gcc_assert (POINTER_TYPE_P (TREE_TYPE (se_expr)));
2230       tmp = se_expr;
2231     }
2232 
2233   *offset = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
2234 			     *offset, fold_convert (gfc_array_index_type, tmp));
2235 
2236   if (expr->symtree->n.sym->ts.type == BT_DERIVED
2237       && expr->symtree->n.sym->attr.codimension
2238       && expr->symtree->n.sym->ts.u.derived->attr.alloc_comp)
2239     {
2240       gfc_expr *base_expr = gfc_copy_expr (expr);
2241       gfc_ref *ref = base_expr->ref;
2242       gfc_se base_se;
2243 
2244       // Iterate through the refs until the last one.
2245       while (ref->next)
2246 	  ref = ref->next;
2247 
2248       if (ref->type == REF_ARRAY
2249 	  && ref->u.ar.type != AR_FULL)
2250 	{
2251 	  const int ranksum = ref->u.ar.dimen + ref->u.ar.codimen;
2252 	  int i;
2253 	  for (i = 0; i < ranksum; ++i)
2254 	    {
2255 	      ref->u.ar.start[i] = NULL;
2256 	      ref->u.ar.end[i] = NULL;
2257 	    }
2258 	  ref->u.ar.type = AR_FULL;
2259 	}
2260       gfc_init_se (&base_se, NULL);
2261       if (gfc_caf_attr (base_expr).dimension)
2262 	{
2263 	  gfc_conv_expr_descriptor (&base_se, base_expr);
2264 	  tmp = gfc_conv_descriptor_data_get (base_se.expr);
2265 	}
2266       else
2267 	{
2268 	  gfc_conv_expr (&base_se, base_expr);
2269 	  tmp = base_se.expr;
2270 	}
2271 
2272       gfc_free_expr (base_expr);
2273       gfc_add_block_to_block (&se->pre, &base_se.pre);
2274       gfc_add_block_to_block (&se->post, &base_se.post);
2275     }
2276   else if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (caf_decl)))
2277     tmp = gfc_conv_descriptor_data_get (caf_decl);
2278   else
2279    {
2280      gcc_assert (POINTER_TYPE_P (TREE_TYPE (caf_decl)));
2281      tmp = caf_decl;
2282    }
2283 
2284   *offset = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
2285 			    fold_convert (gfc_array_index_type, *offset),
2286 			    fold_convert (gfc_array_index_type, tmp));
2287 }
2288 
2289 
2290 /* Convert the coindex of a coarray into an image index; the result is
2291    image_num =  (idx(1)-lcobound(1)+1) + (idx(2)-lcobound(2))*extent(1)
2292               + (idx(3)-lcobound(3))*extend(1)*extent(2) + ...  */
2293 
2294 tree
2295 gfc_caf_get_image_index (stmtblock_t *block, gfc_expr *e, tree desc)
2296 {
2297   gfc_ref *ref;
2298   tree lbound, ubound, extent, tmp, img_idx;
2299   gfc_se se;
2300   int i;
2301 
2302   for (ref = e->ref; ref; ref = ref->next)
2303     if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
2304       break;
2305   gcc_assert (ref != NULL);
2306 
2307   if (ref->u.ar.dimen_type[ref->u.ar.dimen] == DIMEN_THIS_IMAGE)
2308     {
2309       return build_call_expr_loc (input_location, gfor_fndecl_caf_this_image, 1,
2310 				  integer_zero_node);
2311     }
2312 
2313   img_idx = build_zero_cst (gfc_array_index_type);
2314   extent = build_one_cst (gfc_array_index_type);
2315   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (desc)))
2316     for (i = ref->u.ar.dimen; i < ref->u.ar.dimen + ref->u.ar.codimen; i++)
2317       {
2318 	gfc_init_se (&se, NULL);
2319 	gfc_conv_expr_type (&se, ref->u.ar.start[i], gfc_array_index_type);
2320 	gfc_add_block_to_block (block, &se.pre);
2321 	lbound = gfc_conv_descriptor_lbound_get (desc, gfc_rank_cst[i]);
2322 	tmp = fold_build2_loc (input_location, MINUS_EXPR,
2323 			       TREE_TYPE (lbound), se.expr, lbound);
2324 	tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (tmp),
2325 			       extent, tmp);
2326 	img_idx = fold_build2_loc (input_location, PLUS_EXPR,
2327 				   TREE_TYPE (tmp), img_idx, tmp);
2328 	if (i < ref->u.ar.dimen + ref->u.ar.codimen - 1)
2329 	  {
2330 	    ubound = gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[i]);
2331 	    tmp = gfc_conv_array_extent_dim (lbound, ubound, NULL);
2332 	    extent = fold_build2_loc (input_location, MULT_EXPR,
2333 				      TREE_TYPE (tmp), extent, tmp);
2334 	  }
2335       }
2336   else
2337     for (i = ref->u.ar.dimen; i < ref->u.ar.dimen + ref->u.ar.codimen; i++)
2338       {
2339 	gfc_init_se (&se, NULL);
2340 	gfc_conv_expr_type (&se, ref->u.ar.start[i], gfc_array_index_type);
2341 	gfc_add_block_to_block (block, &se.pre);
2342 	lbound = GFC_TYPE_ARRAY_LBOUND (TREE_TYPE (desc), i);
2343 	tmp = fold_build2_loc (input_location, MINUS_EXPR,
2344 			       TREE_TYPE (lbound), se.expr, lbound);
2345 	tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (tmp),
2346 			       extent, tmp);
2347 	img_idx = fold_build2_loc (input_location, PLUS_EXPR, TREE_TYPE (tmp),
2348 				   img_idx, tmp);
2349 	if (i < ref->u.ar.dimen + ref->u.ar.codimen - 1)
2350 	  {
2351 	    ubound = GFC_TYPE_ARRAY_UBOUND (TREE_TYPE (desc), i);
2352 	    tmp = fold_build2_loc (input_location, MINUS_EXPR,
2353 				   TREE_TYPE (ubound), ubound, lbound);
2354 	    tmp = fold_build2_loc (input_location, PLUS_EXPR, TREE_TYPE (tmp),
2355 				   tmp, build_one_cst (TREE_TYPE (tmp)));
2356 	    extent = fold_build2_loc (input_location, MULT_EXPR,
2357 				      TREE_TYPE (tmp), extent, tmp);
2358 	  }
2359       }
2360   img_idx = fold_build2_loc (input_location, PLUS_EXPR, TREE_TYPE (img_idx),
2361 			     img_idx, build_one_cst (TREE_TYPE (img_idx)));
2362   return fold_convert (integer_type_node, img_idx);
2363 }
2364 
2365 
2366 /* For each character array constructor subexpression without a ts.u.cl->length,
2367    replace it by its first element (if there aren't any elements, the length
2368    should already be set to zero).  */
2369 
2370 static void
2371 flatten_array_ctors_without_strlen (gfc_expr* e)
2372 {
2373   gfc_actual_arglist* arg;
2374   gfc_constructor* c;
2375 
2376   if (!e)
2377     return;
2378 
2379   switch (e->expr_type)
2380     {
2381 
2382     case EXPR_OP:
2383       flatten_array_ctors_without_strlen (e->value.op.op1);
2384       flatten_array_ctors_without_strlen (e->value.op.op2);
2385       break;
2386 
2387     case EXPR_COMPCALL:
2388       /* TODO: Implement as with EXPR_FUNCTION when needed.  */
2389       gcc_unreachable ();
2390 
2391     case EXPR_FUNCTION:
2392       for (arg = e->value.function.actual; arg; arg = arg->next)
2393 	flatten_array_ctors_without_strlen (arg->expr);
2394       break;
2395 
2396     case EXPR_ARRAY:
2397 
2398       /* We've found what we're looking for.  */
2399       if (e->ts.type == BT_CHARACTER && !e->ts.u.cl->length)
2400 	{
2401 	  gfc_constructor *c;
2402 	  gfc_expr* new_expr;
2403 
2404 	  gcc_assert (e->value.constructor);
2405 
2406 	  c = gfc_constructor_first (e->value.constructor);
2407 	  new_expr = c->expr;
2408 	  c->expr = NULL;
2409 
2410 	  flatten_array_ctors_without_strlen (new_expr);
2411 	  gfc_replace_expr (e, new_expr);
2412 	  break;
2413 	}
2414 
2415       /* Otherwise, fall through to handle constructor elements.  */
2416       gcc_fallthrough ();
2417     case EXPR_STRUCTURE:
2418       for (c = gfc_constructor_first (e->value.constructor);
2419 	   c; c = gfc_constructor_next (c))
2420 	flatten_array_ctors_without_strlen (c->expr);
2421       break;
2422 
2423     default:
2424       break;
2425 
2426     }
2427 }
2428 
2429 
2430 /* Generate code to initialize a string length variable. Returns the
2431    value.  For array constructors, cl->length might be NULL and in this case,
2432    the first element of the constructor is needed.  expr is the original
2433    expression so we can access it but can be NULL if this is not needed.  */
2434 
2435 void
2436 gfc_conv_string_length (gfc_charlen * cl, gfc_expr * expr, stmtblock_t * pblock)
2437 {
2438   gfc_se se;
2439 
2440   gfc_init_se (&se, NULL);
2441 
2442   if (!cl->length && cl->backend_decl && VAR_P (cl->backend_decl))
2443     return;
2444 
2445   /* If cl->length is NULL, use gfc_conv_expr to obtain the string length but
2446      "flatten" array constructors by taking their first element; all elements
2447      should be the same length or a cl->length should be present.  */
2448   if (!cl->length)
2449     {
2450       gfc_expr* expr_flat;
2451       if (!expr)
2452 	return;
2453       expr_flat = gfc_copy_expr (expr);
2454       flatten_array_ctors_without_strlen (expr_flat);
2455       gfc_resolve_expr (expr_flat);
2456 
2457       gfc_conv_expr (&se, expr_flat);
2458       gfc_add_block_to_block (pblock, &se.pre);
2459       cl->backend_decl = convert (gfc_charlen_type_node, se.string_length);
2460 
2461       gfc_free_expr (expr_flat);
2462       return;
2463     }
2464 
2465   /* Convert cl->length.  */
2466 
2467   gcc_assert (cl->length);
2468 
2469   gfc_conv_expr_type (&se, cl->length, gfc_charlen_type_node);
2470   se.expr = fold_build2_loc (input_location, MAX_EXPR, gfc_charlen_type_node,
2471 			     se.expr, build_zero_cst (TREE_TYPE (se.expr)));
2472   gfc_add_block_to_block (pblock, &se.pre);
2473 
2474   if (cl->backend_decl && VAR_P (cl->backend_decl))
2475     gfc_add_modify (pblock, cl->backend_decl, se.expr);
2476   else
2477     cl->backend_decl = gfc_evaluate_now (se.expr, pblock);
2478 }
2479 
2480 
2481 static void
2482 gfc_conv_substring (gfc_se * se, gfc_ref * ref, int kind,
2483 		    const char *name, locus *where)
2484 {
2485   tree tmp;
2486   tree type;
2487   tree fault;
2488   gfc_se start;
2489   gfc_se end;
2490   char *msg;
2491   mpz_t length;
2492 
2493   type = gfc_get_character_type (kind, ref->u.ss.length);
2494   type = build_pointer_type (type);
2495 
2496   gfc_init_se (&start, se);
2497   gfc_conv_expr_type (&start, ref->u.ss.start, gfc_charlen_type_node);
2498   gfc_add_block_to_block (&se->pre, &start.pre);
2499 
2500   if (integer_onep (start.expr))
2501     gfc_conv_string_parameter (se);
2502   else
2503     {
2504       tmp = start.expr;
2505       STRIP_NOPS (tmp);
2506       /* Avoid multiple evaluation of substring start.  */
2507       if (!CONSTANT_CLASS_P (tmp) && !DECL_P (tmp))
2508 	start.expr = gfc_evaluate_now (start.expr, &se->pre);
2509 
2510       /* Change the start of the string.  */
2511       if ((TREE_CODE (TREE_TYPE (se->expr)) == ARRAY_TYPE
2512 	   || TREE_CODE (TREE_TYPE (se->expr)) == INTEGER_TYPE)
2513 	  && TYPE_STRING_FLAG (TREE_TYPE (se->expr)))
2514 	tmp = se->expr;
2515       else
2516 	tmp = build_fold_indirect_ref_loc (input_location,
2517 				       se->expr);
2518       /* For BIND(C), a BT_CHARACTER is not an ARRAY_TYPE.  */
2519       if (TREE_CODE (TREE_TYPE (tmp)) == ARRAY_TYPE)
2520 	{
2521 	  tmp = gfc_build_array_ref (tmp, start.expr, NULL);
2522 	  se->expr = gfc_build_addr_expr (type, tmp);
2523 	}
2524     }
2525 
2526   /* Length = end + 1 - start.  */
2527   gfc_init_se (&end, se);
2528   if (ref->u.ss.end == NULL)
2529     end.expr = se->string_length;
2530   else
2531     {
2532       gfc_conv_expr_type (&end, ref->u.ss.end, gfc_charlen_type_node);
2533       gfc_add_block_to_block (&se->pre, &end.pre);
2534     }
2535   tmp = end.expr;
2536   STRIP_NOPS (tmp);
2537   if (!CONSTANT_CLASS_P (tmp) && !DECL_P (tmp))
2538     end.expr = gfc_evaluate_now (end.expr, &se->pre);
2539 
2540   if ((gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
2541       && (ref->u.ss.start->symtree
2542 	  && !ref->u.ss.start->symtree->n.sym->attr.implied_index))
2543     {
2544       tree nonempty = fold_build2_loc (input_location, LE_EXPR,
2545 				       logical_type_node, start.expr,
2546 				       end.expr);
2547 
2548       /* Check lower bound.  */
2549       fault = fold_build2_loc (input_location, LT_EXPR, logical_type_node,
2550 			       start.expr,
2551 			       build_one_cst (TREE_TYPE (start.expr)));
2552       fault = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
2553 			       logical_type_node, nonempty, fault);
2554       if (name)
2555 	msg = xasprintf ("Substring out of bounds: lower bound (%%ld) of '%s' "
2556 			 "is less than one", name);
2557       else
2558 	msg = xasprintf ("Substring out of bounds: lower bound (%%ld) "
2559 			 "is less than one");
2560       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
2561 			       fold_convert (long_integer_type_node,
2562 					     start.expr));
2563       free (msg);
2564 
2565       /* Check upper bound.  */
2566       fault = fold_build2_loc (input_location, GT_EXPR, logical_type_node,
2567 			       end.expr, se->string_length);
2568       fault = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
2569 			       logical_type_node, nonempty, fault);
2570       if (name)
2571 	msg = xasprintf ("Substring out of bounds: upper bound (%%ld) of '%s' "
2572 			 "exceeds string length (%%ld)", name);
2573       else
2574 	msg = xasprintf ("Substring out of bounds: upper bound (%%ld) "
2575 			 "exceeds string length (%%ld)");
2576       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
2577 			       fold_convert (long_integer_type_node, end.expr),
2578 			       fold_convert (long_integer_type_node,
2579 					     se->string_length));
2580       free (msg);
2581     }
2582 
2583   /* Try to calculate the length from the start and end expressions.  */
2584   if (ref->u.ss.end
2585       && gfc_dep_difference (ref->u.ss.end, ref->u.ss.start, &length))
2586     {
2587       HOST_WIDE_INT i_len;
2588 
2589       i_len = gfc_mpz_get_hwi (length) + 1;
2590       if (i_len < 0)
2591 	i_len = 0;
2592 
2593       tmp = build_int_cst (gfc_charlen_type_node, i_len);
2594       mpz_clear (length);  /* Was initialized by gfc_dep_difference.  */
2595     }
2596   else
2597     {
2598       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_charlen_type_node,
2599 			     fold_convert (gfc_charlen_type_node, end.expr),
2600 			     fold_convert (gfc_charlen_type_node, start.expr));
2601       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_charlen_type_node,
2602 			     build_int_cst (gfc_charlen_type_node, 1), tmp);
2603       tmp = fold_build2_loc (input_location, MAX_EXPR, gfc_charlen_type_node,
2604 			     tmp, build_int_cst (gfc_charlen_type_node, 0));
2605     }
2606 
2607   se->string_length = tmp;
2608 }
2609 
2610 
2611 /* Convert a derived type component reference.  */
2612 
2613 void
2614 gfc_conv_component_ref (gfc_se * se, gfc_ref * ref)
2615 {
2616   gfc_component *c;
2617   tree tmp;
2618   tree decl;
2619   tree field;
2620   tree context;
2621 
2622   c = ref->u.c.component;
2623 
2624   if (c->backend_decl == NULL_TREE
2625       && ref->u.c.sym != NULL)
2626     gfc_get_derived_type (ref->u.c.sym);
2627 
2628   field = c->backend_decl;
2629   gcc_assert (field && TREE_CODE (field) == FIELD_DECL);
2630   decl = se->expr;
2631   context = DECL_FIELD_CONTEXT (field);
2632 
2633   /* Components can correspond to fields of different containing
2634      types, as components are created without context, whereas
2635      a concrete use of a component has the type of decl as context.
2636      So, if the type doesn't match, we search the corresponding
2637      FIELD_DECL in the parent type.  To not waste too much time
2638      we cache this result in norestrict_decl.
2639      On the other hand, if the context is a UNION or a MAP (a
2640      RECORD_TYPE within a UNION_TYPE) always use the given FIELD_DECL.  */
2641 
2642   if (context != TREE_TYPE (decl)
2643       && !(   TREE_CODE (TREE_TYPE (field)) == UNION_TYPE /* Field is union */
2644            || TREE_CODE (context) == UNION_TYPE))         /* Field is map */
2645     {
2646       tree f2 = c->norestrict_decl;
2647       if (!f2 || DECL_FIELD_CONTEXT (f2) != TREE_TYPE (decl))
2648 	for (f2 = TYPE_FIELDS (TREE_TYPE (decl)); f2; f2 = DECL_CHAIN (f2))
2649 	  if (TREE_CODE (f2) == FIELD_DECL
2650 	      && DECL_NAME (f2) == DECL_NAME (field))
2651 	    break;
2652       gcc_assert (f2);
2653       c->norestrict_decl = f2;
2654       field = f2;
2655     }
2656 
2657   if (ref->u.c.sym && ref->u.c.sym->ts.type == BT_CLASS
2658       && strcmp ("_data", c->name) == 0)
2659     {
2660       /* Found a ref to the _data component.  Store the associated ref to
2661 	 the vptr in se->class_vptr.  */
2662       se->class_vptr = gfc_class_vptr_get (decl);
2663     }
2664   else
2665     se->class_vptr = NULL_TREE;
2666 
2667   tmp = fold_build3_loc (input_location, COMPONENT_REF, TREE_TYPE (field),
2668 			 decl, field, NULL_TREE);
2669 
2670   se->expr = tmp;
2671 
2672   /* Allocatable deferred char arrays are to be handled by the gfc_deferred_
2673      strlen () conditional below.  */
2674   if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer
2675       && !c->ts.deferred
2676       && !c->attr.pdt_string)
2677     {
2678       tmp = c->ts.u.cl->backend_decl;
2679       /* Components must always be constant length.  */
2680       gcc_assert (tmp && INTEGER_CST_P (tmp));
2681       se->string_length = tmp;
2682     }
2683 
2684   if (gfc_deferred_strlen (c, &field))
2685     {
2686       tmp = fold_build3_loc (input_location, COMPONENT_REF,
2687 			     TREE_TYPE (field),
2688 			     decl, field, NULL_TREE);
2689       se->string_length = tmp;
2690     }
2691 
2692   if (((c->attr.pointer || c->attr.allocatable)
2693        && (!c->attr.dimension && !c->attr.codimension)
2694        && c->ts.type != BT_CHARACTER)
2695       || c->attr.proc_pointer)
2696     se->expr = build_fold_indirect_ref_loc (input_location,
2697 					se->expr);
2698 }
2699 
2700 
2701 /* This function deals with component references to components of the
2702    parent type for derived type extensions.  */
2703 void
2704 conv_parent_component_references (gfc_se * se, gfc_ref * ref)
2705 {
2706   gfc_component *c;
2707   gfc_component *cmp;
2708   gfc_symbol *dt;
2709   gfc_ref parent;
2710 
2711   dt = ref->u.c.sym;
2712   c = ref->u.c.component;
2713 
2714   /* Return if the component is in the parent type.  */
2715   for (cmp = dt->components; cmp; cmp = cmp->next)
2716     if (strcmp (c->name, cmp->name) == 0)
2717       return;
2718 
2719   /* Build a gfc_ref to recursively call gfc_conv_component_ref.  */
2720   parent.type = REF_COMPONENT;
2721   parent.next = NULL;
2722   parent.u.c.sym = dt;
2723   parent.u.c.component = dt->components;
2724 
2725   if (dt->backend_decl == NULL)
2726     gfc_get_derived_type (dt);
2727 
2728   /* Build the reference and call self.  */
2729   gfc_conv_component_ref (se, &parent);
2730   parent.u.c.sym = dt->components->ts.u.derived;
2731   parent.u.c.component = c;
2732   conv_parent_component_references (se, &parent);
2733 }
2734 
2735 
2736 static void
2737 conv_inquiry (gfc_se * se, gfc_ref * ref, gfc_expr *expr, gfc_typespec *ts)
2738 {
2739   tree res = se->expr;
2740 
2741   switch (ref->u.i)
2742     {
2743     case INQUIRY_RE:
2744       res = fold_build1_loc (input_location, REALPART_EXPR,
2745 			     TREE_TYPE (TREE_TYPE (res)), res);
2746       break;
2747 
2748     case INQUIRY_IM:
2749       res = fold_build1_loc (input_location, IMAGPART_EXPR,
2750 			     TREE_TYPE (TREE_TYPE (res)), res);
2751       break;
2752 
2753     case INQUIRY_KIND:
2754       res = build_int_cst (gfc_typenode_for_spec (&expr->ts),
2755 			   ts->kind);
2756       break;
2757 
2758     case INQUIRY_LEN:
2759       res = fold_convert (gfc_typenode_for_spec (&expr->ts),
2760 			  se->string_length);
2761       break;
2762 
2763     default:
2764       gcc_unreachable ();
2765     }
2766   se->expr = res;
2767 }
2768 
2769 /* Dereference VAR where needed if it is a pointer, reference, etc.
2770    according to Fortran semantics.  */
2771 
2772 tree
2773 gfc_maybe_dereference_var (gfc_symbol *sym, tree var, bool descriptor_only_p,
2774 			   bool is_classarray)
2775 {
2776   /* Characters are entirely different from other types, they are treated
2777      separately.  */
2778   if (sym->ts.type == BT_CHARACTER)
2779     {
2780       /* Dereference character pointer dummy arguments
2781 	 or results.  */
2782       if ((sym->attr.pointer || sym->attr.allocatable)
2783 	  && (sym->attr.dummy
2784 	      || sym->attr.function
2785 	      || sym->attr.result))
2786 	var = build_fold_indirect_ref_loc (input_location, var);
2787     }
2788   else if (!sym->attr.value)
2789     {
2790       /* Dereference temporaries for class array dummy arguments.  */
2791       if (sym->attr.dummy && is_classarray
2792 	  && GFC_ARRAY_TYPE_P (TREE_TYPE (var)))
2793 	{
2794 	  if (!descriptor_only_p)
2795 	    var = GFC_DECL_SAVED_DESCRIPTOR (var);
2796 
2797 	  var = build_fold_indirect_ref_loc (input_location, var);
2798 	}
2799 
2800       /* Dereference non-character scalar dummy arguments.  */
2801       if (sym->attr.dummy && !sym->attr.dimension
2802 	  && !(sym->attr.codimension && sym->attr.allocatable)
2803 	  && (sym->ts.type != BT_CLASS
2804 	      || (!CLASS_DATA (sym)->attr.dimension
2805 		  && !(CLASS_DATA (sym)->attr.codimension
2806 		       && CLASS_DATA (sym)->attr.allocatable))))
2807 	var = build_fold_indirect_ref_loc (input_location, var);
2808 
2809       /* Dereference scalar hidden result.  */
2810       if (flag_f2c && sym->ts.type == BT_COMPLEX
2811 	  && (sym->attr.function || sym->attr.result)
2812 	  && !sym->attr.dimension && !sym->attr.pointer
2813 	  && !sym->attr.always_explicit)
2814 	var = build_fold_indirect_ref_loc (input_location, var);
2815 
2816       /* Dereference non-character, non-class pointer variables.
2817 	 These must be dummies, results, or scalars.  */
2818       if (!is_classarray
2819 	  && (sym->attr.pointer || sym->attr.allocatable
2820 	      || gfc_is_associate_pointer (sym)
2821 	      || (sym->as && sym->as->type == AS_ASSUMED_RANK))
2822 	  && (sym->attr.dummy
2823 	      || sym->attr.function
2824 	      || sym->attr.result
2825 	      || (!sym->attr.dimension
2826 		  && (!sym->attr.codimension || !sym->attr.allocatable))))
2827 	var = build_fold_indirect_ref_loc (input_location, var);
2828       /* Now treat the class array pointer variables accordingly.  */
2829       else if (sym->ts.type == BT_CLASS
2830 	       && sym->attr.dummy
2831 	       && (CLASS_DATA (sym)->attr.dimension
2832 		   || CLASS_DATA (sym)->attr.codimension)
2833 	       && ((CLASS_DATA (sym)->as
2834 		    && CLASS_DATA (sym)->as->type == AS_ASSUMED_RANK)
2835 		   || CLASS_DATA (sym)->attr.allocatable
2836 		   || CLASS_DATA (sym)->attr.class_pointer))
2837 	var = build_fold_indirect_ref_loc (input_location, var);
2838       /* And the case where a non-dummy, non-result, non-function,
2839 	 non-allotable and non-pointer classarray is present.  This case was
2840 	 previously covered by the first if, but with introducing the
2841 	 condition !is_classarray there, that case has to be covered
2842 	 explicitly.  */
2843       else if (sym->ts.type == BT_CLASS
2844 	       && !sym->attr.dummy
2845 	       && !sym->attr.function
2846 	       && !sym->attr.result
2847 	       && (CLASS_DATA (sym)->attr.dimension
2848 		   || CLASS_DATA (sym)->attr.codimension)
2849 	       && (sym->assoc
2850 		   || !CLASS_DATA (sym)->attr.allocatable)
2851 	       && !CLASS_DATA (sym)->attr.class_pointer)
2852 	var = build_fold_indirect_ref_loc (input_location, var);
2853     }
2854 
2855   return var;
2856 }
2857 
2858 /* Return the contents of a variable. Also handles reference/pointer
2859    variables (all Fortran pointer references are implicit).  */
2860 
2861 static void
2862 gfc_conv_variable (gfc_se * se, gfc_expr * expr)
2863 {
2864   gfc_ss *ss;
2865   gfc_ref *ref;
2866   gfc_symbol *sym;
2867   tree parent_decl = NULL_TREE;
2868   int parent_flag;
2869   bool return_value;
2870   bool alternate_entry;
2871   bool entry_master;
2872   bool is_classarray;
2873   bool first_time = true;
2874 
2875   sym = expr->symtree->n.sym;
2876   is_classarray = IS_CLASS_ARRAY (sym);
2877   ss = se->ss;
2878   if (ss != NULL)
2879     {
2880       gfc_ss_info *ss_info = ss->info;
2881 
2882       /* Check that something hasn't gone horribly wrong.  */
2883       gcc_assert (ss != gfc_ss_terminator);
2884       gcc_assert (ss_info->expr == expr);
2885 
2886       /* A scalarized term.  We already know the descriptor.  */
2887       se->expr = ss_info->data.array.descriptor;
2888       se->string_length = ss_info->string_length;
2889       ref = ss_info->data.array.ref;
2890       if (ref)
2891 	gcc_assert (ref->type == REF_ARRAY
2892 		    && ref->u.ar.type != AR_ELEMENT);
2893       else
2894 	gfc_conv_tmp_array_ref (se);
2895     }
2896   else
2897     {
2898       tree se_expr = NULL_TREE;
2899 
2900       se->expr = gfc_get_symbol_decl (sym);
2901 
2902       /* Deal with references to a parent results or entries by storing
2903 	 the current_function_decl and moving to the parent_decl.  */
2904       return_value = sym->attr.function && sym->result == sym;
2905       alternate_entry = sym->attr.function && sym->attr.entry
2906 			&& sym->result == sym;
2907       entry_master = sym->attr.result
2908 		     && sym->ns->proc_name->attr.entry_master
2909 		     && !gfc_return_by_reference (sym->ns->proc_name);
2910       if (current_function_decl)
2911 	parent_decl = DECL_CONTEXT (current_function_decl);
2912 
2913       if ((se->expr == parent_decl && return_value)
2914 	   || (sym->ns && sym->ns->proc_name
2915 	       && parent_decl
2916 	       && sym->ns->proc_name->backend_decl == parent_decl
2917 	       && (alternate_entry || entry_master)))
2918 	parent_flag = 1;
2919       else
2920 	parent_flag = 0;
2921 
2922       /* Special case for assigning the return value of a function.
2923 	 Self recursive functions must have an explicit return value.  */
2924       if (return_value && (se->expr == current_function_decl || parent_flag))
2925 	se_expr = gfc_get_fake_result_decl (sym, parent_flag);
2926 
2927       /* Similarly for alternate entry points.  */
2928       else if (alternate_entry
2929 	       && (sym->ns->proc_name->backend_decl == current_function_decl
2930 		   || parent_flag))
2931 	{
2932 	  gfc_entry_list *el = NULL;
2933 
2934 	  for (el = sym->ns->entries; el; el = el->next)
2935 	    if (sym == el->sym)
2936 	      {
2937 		se_expr = gfc_get_fake_result_decl (sym, parent_flag);
2938 		break;
2939 	      }
2940 	}
2941 
2942       else if (entry_master
2943 	       && (sym->ns->proc_name->backend_decl == current_function_decl
2944 		   || parent_flag))
2945 	se_expr = gfc_get_fake_result_decl (sym, parent_flag);
2946 
2947       if (se_expr)
2948 	se->expr = se_expr;
2949 
2950       /* Procedure actual arguments.  Look out for temporary variables
2951 	 with the same attributes as function values.  */
2952       else if (!sym->attr.temporary
2953 	       && sym->attr.flavor == FL_PROCEDURE
2954 	       && se->expr != current_function_decl)
2955 	{
2956 	  if (!sym->attr.dummy && !sym->attr.proc_pointer)
2957 	    {
2958 	      gcc_assert (TREE_CODE (se->expr) == FUNCTION_DECL);
2959 	      se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
2960 	    }
2961 	  return;
2962 	}
2963 
2964       /* Dereference the expression, where needed.  */
2965       se->expr = gfc_maybe_dereference_var (sym, se->expr, se->descriptor_only,
2966 					    is_classarray);
2967 
2968       ref = expr->ref;
2969     }
2970 
2971   /* For character variables, also get the length.  */
2972   if (sym->ts.type == BT_CHARACTER)
2973     {
2974       /* If the character length of an entry isn't set, get the length from
2975          the master function instead.  */
2976       if (sym->attr.entry && !sym->ts.u.cl->backend_decl)
2977         se->string_length = sym->ns->proc_name->ts.u.cl->backend_decl;
2978       else
2979         se->string_length = sym->ts.u.cl->backend_decl;
2980       gcc_assert (se->string_length);
2981     }
2982 
2983   gfc_typespec *ts = &sym->ts;
2984   while (ref)
2985     {
2986       switch (ref->type)
2987 	{
2988 	case REF_ARRAY:
2989 	  /* Return the descriptor if that's what we want and this is an array
2990 	     section reference.  */
2991 	  if (se->descriptor_only && ref->u.ar.type != AR_ELEMENT)
2992 	    return;
2993 /* TODO: Pointers to single elements of array sections, eg elemental subs.  */
2994 	  /* Return the descriptor for array pointers and allocations.  */
2995 	  if (se->want_pointer
2996 	      && ref->next == NULL && (se->descriptor_only))
2997 	    return;
2998 
2999 	  gfc_conv_array_ref (se, &ref->u.ar, expr, &expr->where);
3000 	  /* Return a pointer to an element.  */
3001 	  break;
3002 
3003 	case REF_COMPONENT:
3004 	  ts = &ref->u.c.component->ts;
3005 	  if (first_time && is_classarray && sym->attr.dummy
3006 	      && se->descriptor_only
3007 	      && !CLASS_DATA (sym)->attr.allocatable
3008 	      && !CLASS_DATA (sym)->attr.class_pointer
3009 	      && CLASS_DATA (sym)->as
3010 	      && CLASS_DATA (sym)->as->type != AS_ASSUMED_RANK
3011 	      && strcmp ("_data", ref->u.c.component->name) == 0)
3012 	    /* Skip the first ref of a _data component, because for class
3013 	       arrays that one is already done by introducing a temporary
3014 	       array descriptor.  */
3015 	    break;
3016 
3017 	  if (ref->u.c.sym->attr.extension)
3018 	    conv_parent_component_references (se, ref);
3019 
3020 	  gfc_conv_component_ref (se, ref);
3021 	  if (!ref->next && ref->u.c.sym->attr.codimension
3022 	      && se->want_pointer && se->descriptor_only)
3023 	    return;
3024 
3025 	  break;
3026 
3027 	case REF_SUBSTRING:
3028 	  gfc_conv_substring (se, ref, expr->ts.kind,
3029 			      expr->symtree->name, &expr->where);
3030 	  break;
3031 
3032 	case REF_INQUIRY:
3033 	  conv_inquiry (se, ref, expr, ts);
3034 	  break;
3035 
3036 	default:
3037 	  gcc_unreachable ();
3038 	  break;
3039 	}
3040       first_time = false;
3041       ref = ref->next;
3042     }
3043   /* Pointer assignment, allocation or pass by reference.  Arrays are handled
3044      separately.  */
3045   if (se->want_pointer)
3046     {
3047       if (expr->ts.type == BT_CHARACTER && !gfc_is_proc_ptr_comp (expr))
3048 	gfc_conv_string_parameter (se);
3049       else
3050 	se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
3051     }
3052 }
3053 
3054 
3055 /* Unary ops are easy... Or they would be if ! was a valid op.  */
3056 
3057 static void
3058 gfc_conv_unary_op (enum tree_code code, gfc_se * se, gfc_expr * expr)
3059 {
3060   gfc_se operand;
3061   tree type;
3062 
3063   gcc_assert (expr->ts.type != BT_CHARACTER);
3064   /* Initialize the operand.  */
3065   gfc_init_se (&operand, se);
3066   gfc_conv_expr_val (&operand, expr->value.op.op1);
3067   gfc_add_block_to_block (&se->pre, &operand.pre);
3068 
3069   type = gfc_typenode_for_spec (&expr->ts);
3070 
3071   /* TRUTH_NOT_EXPR is not a "true" unary operator in GCC.
3072      We must convert it to a compare to 0 (e.g. EQ_EXPR (op1, 0)).
3073      All other unary operators have an equivalent GIMPLE unary operator.  */
3074   if (code == TRUTH_NOT_EXPR)
3075     se->expr = fold_build2_loc (input_location, EQ_EXPR, type, operand.expr,
3076 				build_int_cst (type, 0));
3077   else
3078     se->expr = fold_build1_loc (input_location, code, type, operand.expr);
3079 
3080 }
3081 
3082 /* Expand power operator to optimal multiplications when a value is raised
3083    to a constant integer n. See section 4.6.3, "Evaluation of Powers" of
3084    Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art of Computer
3085    Programming", 3rd Edition, 1998.  */
3086 
3087 /* This code is mostly duplicated from expand_powi in the backend.
3088    We establish the "optimal power tree" lookup table with the defined size.
3089    The items in the table are the exponents used to calculate the index
3090    exponents. Any integer n less than the value can get an "addition chain",
3091    with the first node being one.  */
3092 #define POWI_TABLE_SIZE 256
3093 
3094 /* The table is from builtins.c.  */
3095 static const unsigned char powi_table[POWI_TABLE_SIZE] =
3096   {
3097       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
3098       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
3099       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
3100      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
3101      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
3102      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
3103      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
3104      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
3105      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
3106      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
3107      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
3108      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
3109      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
3110      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
3111      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
3112      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
3113      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
3114      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
3115      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
3116      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
3117      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
3118      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
3119      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
3120      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
3121      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
3122     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
3123     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
3124     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
3125     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
3126     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
3127     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
3128     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
3129   };
3130 
3131 /* If n is larger than lookup table's max index, we use the "window
3132    method".  */
3133 #define POWI_WINDOW_SIZE 3
3134 
3135 /* Recursive function to expand the power operator. The temporary
3136    values are put in tmpvar. The function returns tmpvar[1] ** n.  */
3137 static tree
3138 gfc_conv_powi (gfc_se * se, unsigned HOST_WIDE_INT n, tree * tmpvar)
3139 {
3140   tree op0;
3141   tree op1;
3142   tree tmp;
3143   int digit;
3144 
3145   if (n < POWI_TABLE_SIZE)
3146     {
3147       if (tmpvar[n])
3148         return tmpvar[n];
3149 
3150       op0 = gfc_conv_powi (se, n - powi_table[n], tmpvar);
3151       op1 = gfc_conv_powi (se, powi_table[n], tmpvar);
3152     }
3153   else if (n & 1)
3154     {
3155       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
3156       op0 = gfc_conv_powi (se, n - digit, tmpvar);
3157       op1 = gfc_conv_powi (se, digit, tmpvar);
3158     }
3159   else
3160     {
3161       op0 = gfc_conv_powi (se, n >> 1, tmpvar);
3162       op1 = op0;
3163     }
3164 
3165   tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (op0), op0, op1);
3166   tmp = gfc_evaluate_now (tmp, &se->pre);
3167 
3168   if (n < POWI_TABLE_SIZE)
3169     tmpvar[n] = tmp;
3170 
3171   return tmp;
3172 }
3173 
3174 
3175 /* Expand lhs ** rhs. rhs is a constant integer. If it expands successfully,
3176    return 1. Else return 0 and a call to runtime library functions
3177    will have to be built.  */
3178 static int
3179 gfc_conv_cst_int_power (gfc_se * se, tree lhs, tree rhs)
3180 {
3181   tree cond;
3182   tree tmp;
3183   tree type;
3184   tree vartmp[POWI_TABLE_SIZE];
3185   HOST_WIDE_INT m;
3186   unsigned HOST_WIDE_INT n;
3187   int sgn;
3188   wi::tree_to_wide_ref wrhs = wi::to_wide (rhs);
3189 
3190   /* If exponent is too large, we won't expand it anyway, so don't bother
3191      with large integer values.  */
3192   if (!wi::fits_shwi_p (wrhs))
3193     return 0;
3194 
3195   m = wrhs.to_shwi ();
3196   /* Use the wide_int's routine to reliably get the absolute value on all
3197      platforms.  Then convert it to a HOST_WIDE_INT like above.  */
3198   n = wi::abs (wrhs).to_shwi ();
3199 
3200   type = TREE_TYPE (lhs);
3201   sgn = tree_int_cst_sgn (rhs);
3202 
3203   if (((FLOAT_TYPE_P (type) && !flag_unsafe_math_optimizations)
3204        || optimize_size) && (m > 2 || m < -1))
3205     return 0;
3206 
3207   /* rhs == 0  */
3208   if (sgn == 0)
3209     {
3210       se->expr = gfc_build_const (type, integer_one_node);
3211       return 1;
3212     }
3213 
3214   /* If rhs < 0 and lhs is an integer, the result is -1, 0 or 1.  */
3215   if ((sgn == -1) && (TREE_CODE (type) == INTEGER_TYPE))
3216     {
3217       tmp = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
3218 			     lhs, build_int_cst (TREE_TYPE (lhs), -1));
3219       cond = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
3220 			      lhs, build_int_cst (TREE_TYPE (lhs), 1));
3221 
3222       /* If rhs is even,
3223 	 result = (lhs == 1 || lhs == -1) ? 1 : 0.  */
3224       if ((n & 1) == 0)
3225         {
3226 	  tmp = fold_build2_loc (input_location, TRUTH_OR_EXPR,
3227 				 logical_type_node, tmp, cond);
3228 	  se->expr = fold_build3_loc (input_location, COND_EXPR, type,
3229 				      tmp, build_int_cst (type, 1),
3230 				      build_int_cst (type, 0));
3231 	  return 1;
3232 	}
3233       /* If rhs is odd,
3234 	 result = (lhs == 1) ? 1 : (lhs == -1) ? -1 : 0.  */
3235       tmp = fold_build3_loc (input_location, COND_EXPR, type, tmp,
3236 			     build_int_cst (type, -1),
3237 			     build_int_cst (type, 0));
3238       se->expr = fold_build3_loc (input_location, COND_EXPR, type,
3239 				  cond, build_int_cst (type, 1), tmp);
3240       return 1;
3241     }
3242 
3243   memset (vartmp, 0, sizeof (vartmp));
3244   vartmp[1] = lhs;
3245   if (sgn == -1)
3246     {
3247       tmp = gfc_build_const (type, integer_one_node);
3248       vartmp[1] = fold_build2_loc (input_location, RDIV_EXPR, type, tmp,
3249 				   vartmp[1]);
3250     }
3251 
3252   se->expr = gfc_conv_powi (se, n, vartmp);
3253 
3254   return 1;
3255 }
3256 
3257 
3258 /* Power op (**).  Constant integer exponent has special handling.  */
3259 
3260 static void
3261 gfc_conv_power_op (gfc_se * se, gfc_expr * expr)
3262 {
3263   tree gfc_int4_type_node;
3264   int kind;
3265   int ikind;
3266   int res_ikind_1, res_ikind_2;
3267   gfc_se lse;
3268   gfc_se rse;
3269   tree fndecl = NULL;
3270 
3271   gfc_init_se (&lse, se);
3272   gfc_conv_expr_val (&lse, expr->value.op.op1);
3273   lse.expr = gfc_evaluate_now (lse.expr, &lse.pre);
3274   gfc_add_block_to_block (&se->pre, &lse.pre);
3275 
3276   gfc_init_se (&rse, se);
3277   gfc_conv_expr_val (&rse, expr->value.op.op2);
3278   gfc_add_block_to_block (&se->pre, &rse.pre);
3279 
3280   if (expr->value.op.op2->ts.type == BT_INTEGER
3281       && expr->value.op.op2->expr_type == EXPR_CONSTANT)
3282     if (gfc_conv_cst_int_power (se, lse.expr, rse.expr))
3283       return;
3284 
3285   if (INTEGER_CST_P (lse.expr)
3286       && TREE_CODE (TREE_TYPE (rse.expr)) == INTEGER_TYPE)
3287     {
3288       wi::tree_to_wide_ref wlhs = wi::to_wide (lse.expr);
3289       HOST_WIDE_INT v, w;
3290       int kind, ikind, bit_size;
3291 
3292       v = wlhs.to_shwi ();
3293       w = abs (v);
3294 
3295       kind = expr->value.op.op1->ts.kind;
3296       ikind = gfc_validate_kind (BT_INTEGER, kind, false);
3297       bit_size = gfc_integer_kinds[ikind].bit_size;
3298 
3299       if (v == 1)
3300 	{
3301 	  /* 1**something is always 1.  */
3302 	  se->expr = build_int_cst (TREE_TYPE (lse.expr), 1);
3303 	  return;
3304 	}
3305       else if (v == -1)
3306 	{
3307 	  /* (-1)**n is 1 - ((n & 1) << 1) */
3308 	  tree type;
3309 	  tree tmp;
3310 
3311 	  type = TREE_TYPE (lse.expr);
3312 	  tmp = fold_build2_loc (input_location, BIT_AND_EXPR, type,
3313 				 rse.expr, build_int_cst (type, 1));
3314 	  tmp = fold_build2_loc (input_location, LSHIFT_EXPR, type,
3315 				 tmp, build_int_cst (type, 1));
3316 	  tmp = fold_build2_loc (input_location, MINUS_EXPR, type,
3317 				 build_int_cst (type, 1), tmp);
3318 	  se->expr = tmp;
3319 	  return;
3320 	}
3321       else if (w > 0 && ((w & (w-1)) == 0) && ((w >> (bit_size-1)) == 0))
3322 	{
3323 	  /* Here v is +/- 2**e.  The further simplification uses
3324 	     2**n = 1<<n, 4**n = 1<<(n+n), 8**n = 1 <<(3*n), 16**n =
3325 	     1<<(4*n), etc., but we have to make sure to return zero
3326 	     if the number of bits is too large. */
3327 	  tree lshift;
3328 	  tree type;
3329 	  tree shift;
3330 	  tree ge;
3331 	  tree cond;
3332 	  tree num_bits;
3333 	  tree cond2;
3334 	  tree tmp1;
3335 
3336 	  type = TREE_TYPE (lse.expr);
3337 
3338 	  if (w == 2)
3339 	    shift = rse.expr;
3340 	  else if (w == 4)
3341 	    shift = fold_build2_loc (input_location, PLUS_EXPR,
3342 				     TREE_TYPE (rse.expr),
3343 				       rse.expr, rse.expr);
3344 	  else
3345 	    {
3346 	      /* use popcount for fast log2(w) */
3347 	      int e = wi::popcount (w-1);
3348 	      shift = fold_build2_loc (input_location, MULT_EXPR,
3349 				       TREE_TYPE (rse.expr),
3350 				       build_int_cst (TREE_TYPE (rse.expr), e),
3351 				       rse.expr);
3352 	    }
3353 
3354 	  lshift = fold_build2_loc (input_location, LSHIFT_EXPR, type,
3355 				    build_int_cst (type, 1), shift);
3356 	  ge = fold_build2_loc (input_location, GE_EXPR, logical_type_node,
3357 				rse.expr, build_int_cst (type, 0));
3358 	  cond = fold_build3_loc (input_location, COND_EXPR, type, ge, lshift,
3359 				 build_int_cst (type, 0));
3360 	  num_bits = build_int_cst (TREE_TYPE (rse.expr), TYPE_PRECISION (type));
3361 	  cond2 = fold_build2_loc (input_location, GE_EXPR, logical_type_node,
3362 				   rse.expr, num_bits);
3363 	  tmp1 = fold_build3_loc (input_location, COND_EXPR, type, cond2,
3364 				  build_int_cst (type, 0), cond);
3365 	  if (v > 0)
3366 	    {
3367 	      se->expr = tmp1;
3368 	    }
3369 	  else
3370 	    {
3371 	      /* for v < 0, calculate v**n = |v|**n * (-1)**n */
3372 	      tree tmp2;
3373 	      tmp2 = fold_build2_loc (input_location, BIT_AND_EXPR, type,
3374 				      rse.expr, build_int_cst (type, 1));
3375 	      tmp2 = fold_build2_loc (input_location, LSHIFT_EXPR, type,
3376 				      tmp2, build_int_cst (type, 1));
3377 	      tmp2 = fold_build2_loc (input_location, MINUS_EXPR, type,
3378 				      build_int_cst (type, 1), tmp2);
3379 	      se->expr = fold_build2_loc (input_location, MULT_EXPR, type,
3380 					  tmp1, tmp2);
3381 	    }
3382 	  return;
3383 	}
3384     }
3385 
3386   gfc_int4_type_node = gfc_get_int_type (4);
3387 
3388   /* In case of integer operands with kinds 1 or 2, we call the integer kind 4
3389      library routine.  But in the end, we have to convert the result back
3390      if this case applies -- with res_ikind_K, we keep track whether operand K
3391      falls into this case.  */
3392   res_ikind_1 = -1;
3393   res_ikind_2 = -1;
3394 
3395   kind = expr->value.op.op1->ts.kind;
3396   switch (expr->value.op.op2->ts.type)
3397     {
3398     case BT_INTEGER:
3399       ikind = expr->value.op.op2->ts.kind;
3400       switch (ikind)
3401 	{
3402 	case 1:
3403 	case 2:
3404 	  rse.expr = convert (gfc_int4_type_node, rse.expr);
3405 	  res_ikind_2 = ikind;
3406 	  /* Fall through.  */
3407 
3408 	case 4:
3409 	  ikind = 0;
3410 	  break;
3411 
3412 	case 8:
3413 	  ikind = 1;
3414 	  break;
3415 
3416 	case 16:
3417 	  ikind = 2;
3418 	  break;
3419 
3420 	default:
3421 	  gcc_unreachable ();
3422 	}
3423       switch (kind)
3424 	{
3425 	case 1:
3426 	case 2:
3427 	  if (expr->value.op.op1->ts.type == BT_INTEGER)
3428 	    {
3429 	      lse.expr = convert (gfc_int4_type_node, lse.expr);
3430 	      res_ikind_1 = kind;
3431 	    }
3432 	  else
3433 	    gcc_unreachable ();
3434 	  /* Fall through.  */
3435 
3436 	case 4:
3437 	  kind = 0;
3438 	  break;
3439 
3440 	case 8:
3441 	  kind = 1;
3442 	  break;
3443 
3444 	case 10:
3445 	  kind = 2;
3446 	  break;
3447 
3448 	case 16:
3449 	  kind = 3;
3450 	  break;
3451 
3452 	default:
3453 	  gcc_unreachable ();
3454 	}
3455 
3456       switch (expr->value.op.op1->ts.type)
3457 	{
3458 	case BT_INTEGER:
3459 	  if (kind == 3) /* Case 16 was not handled properly above.  */
3460 	    kind = 2;
3461 	  fndecl = gfor_fndecl_math_powi[kind][ikind].integer;
3462 	  break;
3463 
3464 	case BT_REAL:
3465 	  /* Use builtins for real ** int4.  */
3466 	  if (ikind == 0)
3467 	    {
3468 	      switch (kind)
3469 		{
3470 		case 0:
3471 		  fndecl = builtin_decl_explicit (BUILT_IN_POWIF);
3472 		  break;
3473 
3474 		case 1:
3475 		  fndecl = builtin_decl_explicit (BUILT_IN_POWI);
3476 		  break;
3477 
3478 		case 2:
3479 		  fndecl = builtin_decl_explicit (BUILT_IN_POWIL);
3480 		  break;
3481 
3482 		case 3:
3483 		  /* Use the __builtin_powil() only if real(kind=16) is
3484 		     actually the C long double type.  */
3485 		  if (!gfc_real16_is_float128)
3486 		    fndecl = builtin_decl_explicit (BUILT_IN_POWIL);
3487 		  break;
3488 
3489 		default:
3490 		  gcc_unreachable ();
3491 		}
3492 	    }
3493 
3494 	  /* If we don't have a good builtin for this, go for the
3495 	     library function.  */
3496 	  if (!fndecl)
3497 	    fndecl = gfor_fndecl_math_powi[kind][ikind].real;
3498 	  break;
3499 
3500 	case BT_COMPLEX:
3501 	  fndecl = gfor_fndecl_math_powi[kind][ikind].cmplx;
3502 	  break;
3503 
3504 	default:
3505 	  gcc_unreachable ();
3506  	}
3507       break;
3508 
3509     case BT_REAL:
3510       fndecl = gfc_builtin_decl_for_float_kind (BUILT_IN_POW, kind);
3511       break;
3512 
3513     case BT_COMPLEX:
3514       fndecl = gfc_builtin_decl_for_float_kind (BUILT_IN_CPOW, kind);
3515       break;
3516 
3517     default:
3518       gcc_unreachable ();
3519       break;
3520     }
3521 
3522   se->expr = build_call_expr_loc (input_location,
3523 			      fndecl, 2, lse.expr, rse.expr);
3524 
3525   /* Convert the result back if it is of wrong integer kind.  */
3526   if (res_ikind_1 != -1 && res_ikind_2 != -1)
3527     {
3528       /* We want the maximum of both operand kinds as result.  */
3529       if (res_ikind_1 < res_ikind_2)
3530 	res_ikind_1 = res_ikind_2;
3531       se->expr = convert (gfc_get_int_type (res_ikind_1), se->expr);
3532     }
3533 }
3534 
3535 
3536 /* Generate code to allocate a string temporary.  */
3537 
3538 tree
3539 gfc_conv_string_tmp (gfc_se * se, tree type, tree len)
3540 {
3541   tree var;
3542   tree tmp;
3543 
3544   if (gfc_can_put_var_on_stack (len))
3545     {
3546       /* Create a temporary variable to hold the result.  */
3547       tmp = fold_build2_loc (input_location, MINUS_EXPR,
3548 			     TREE_TYPE (len), len,
3549 			     build_int_cst (TREE_TYPE (len), 1));
3550       tmp = build_range_type (gfc_charlen_type_node, size_zero_node, tmp);
3551 
3552       if (TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE)
3553 	tmp = build_array_type (TREE_TYPE (TREE_TYPE (type)), tmp);
3554       else
3555 	tmp = build_array_type (TREE_TYPE (type), tmp);
3556 
3557       var = gfc_create_var (tmp, "str");
3558       var = gfc_build_addr_expr (type, var);
3559     }
3560   else
3561     {
3562       /* Allocate a temporary to hold the result.  */
3563       var = gfc_create_var (type, "pstr");
3564       gcc_assert (POINTER_TYPE_P (type));
3565       tmp = TREE_TYPE (type);
3566       if (TREE_CODE (tmp) == ARRAY_TYPE)
3567         tmp = TREE_TYPE (tmp);
3568       tmp = TYPE_SIZE_UNIT (tmp);
3569       tmp = fold_build2_loc (input_location, MULT_EXPR, size_type_node,
3570 			    fold_convert (size_type_node, len),
3571 			    fold_convert (size_type_node, tmp));
3572       tmp = gfc_call_malloc (&se->pre, type, tmp);
3573       gfc_add_modify (&se->pre, var, tmp);
3574 
3575       /* Free the temporary afterwards.  */
3576       tmp = gfc_call_free (var);
3577       gfc_add_expr_to_block (&se->post, tmp);
3578     }
3579 
3580   return var;
3581 }
3582 
3583 
3584 /* Handle a string concatenation operation.  A temporary will be allocated to
3585    hold the result.  */
3586 
3587 static void
3588 gfc_conv_concat_op (gfc_se * se, gfc_expr * expr)
3589 {
3590   gfc_se lse, rse;
3591   tree len, type, var, tmp, fndecl;
3592 
3593   gcc_assert (expr->value.op.op1->ts.type == BT_CHARACTER
3594 	      && expr->value.op.op2->ts.type == BT_CHARACTER);
3595   gcc_assert (expr->value.op.op1->ts.kind == expr->value.op.op2->ts.kind);
3596 
3597   gfc_init_se (&lse, se);
3598   gfc_conv_expr (&lse, expr->value.op.op1);
3599   gfc_conv_string_parameter (&lse);
3600   gfc_init_se (&rse, se);
3601   gfc_conv_expr (&rse, expr->value.op.op2);
3602   gfc_conv_string_parameter (&rse);
3603 
3604   gfc_add_block_to_block (&se->pre, &lse.pre);
3605   gfc_add_block_to_block (&se->pre, &rse.pre);
3606 
3607   type = gfc_get_character_type (expr->ts.kind, expr->ts.u.cl);
3608   len = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
3609   if (len == NULL_TREE)
3610     {
3611       len = fold_build2_loc (input_location, PLUS_EXPR,
3612 			     gfc_charlen_type_node,
3613 			     fold_convert (gfc_charlen_type_node,
3614 					   lse.string_length),
3615 			     fold_convert (gfc_charlen_type_node,
3616 					   rse.string_length));
3617     }
3618 
3619   type = build_pointer_type (type);
3620 
3621   var = gfc_conv_string_tmp (se, type, len);
3622 
3623   /* Do the actual concatenation.  */
3624   if (expr->ts.kind == 1)
3625     fndecl = gfor_fndecl_concat_string;
3626   else if (expr->ts.kind == 4)
3627     fndecl = gfor_fndecl_concat_string_char4;
3628   else
3629     gcc_unreachable ();
3630 
3631   tmp = build_call_expr_loc (input_location,
3632 			 fndecl, 6, len, var, lse.string_length, lse.expr,
3633 			 rse.string_length, rse.expr);
3634   gfc_add_expr_to_block (&se->pre, tmp);
3635 
3636   /* Add the cleanup for the operands.  */
3637   gfc_add_block_to_block (&se->pre, &rse.post);
3638   gfc_add_block_to_block (&se->pre, &lse.post);
3639 
3640   se->expr = var;
3641   se->string_length = len;
3642 }
3643 
3644 /* Translates an op expression. Common (binary) cases are handled by this
3645    function, others are passed on. Recursion is used in either case.
3646    We use the fact that (op1.ts == op2.ts) (except for the power
3647    operator **).
3648    Operators need no special handling for scalarized expressions as long as
3649    they call gfc_conv_simple_val to get their operands.
3650    Character strings get special handling.  */
3651 
3652 static void
3653 gfc_conv_expr_op (gfc_se * se, gfc_expr * expr)
3654 {
3655   enum tree_code code;
3656   gfc_se lse;
3657   gfc_se rse;
3658   tree tmp, type;
3659   int lop;
3660   int checkstring;
3661 
3662   checkstring = 0;
3663   lop = 0;
3664   switch (expr->value.op.op)
3665     {
3666     case INTRINSIC_PARENTHESES:
3667       if ((expr->ts.type == BT_REAL || expr->ts.type == BT_COMPLEX)
3668 	  && flag_protect_parens)
3669 	{
3670 	  gfc_conv_unary_op (PAREN_EXPR, se, expr);
3671 	  gcc_assert (FLOAT_TYPE_P (TREE_TYPE (se->expr)));
3672 	  return;
3673 	}
3674 
3675       /* Fallthrough.  */
3676     case INTRINSIC_UPLUS:
3677       gfc_conv_expr (se, expr->value.op.op1);
3678       return;
3679 
3680     case INTRINSIC_UMINUS:
3681       gfc_conv_unary_op (NEGATE_EXPR, se, expr);
3682       return;
3683 
3684     case INTRINSIC_NOT:
3685       gfc_conv_unary_op (TRUTH_NOT_EXPR, se, expr);
3686       return;
3687 
3688     case INTRINSIC_PLUS:
3689       code = PLUS_EXPR;
3690       break;
3691 
3692     case INTRINSIC_MINUS:
3693       code = MINUS_EXPR;
3694       break;
3695 
3696     case INTRINSIC_TIMES:
3697       code = MULT_EXPR;
3698       break;
3699 
3700     case INTRINSIC_DIVIDE:
3701       /* If expr is a real or complex expr, use an RDIV_EXPR. If op1 is
3702          an integer, we must round towards zero, so we use a
3703          TRUNC_DIV_EXPR.  */
3704       if (expr->ts.type == BT_INTEGER)
3705 	code = TRUNC_DIV_EXPR;
3706       else
3707 	code = RDIV_EXPR;
3708       break;
3709 
3710     case INTRINSIC_POWER:
3711       gfc_conv_power_op (se, expr);
3712       return;
3713 
3714     case INTRINSIC_CONCAT:
3715       gfc_conv_concat_op (se, expr);
3716       return;
3717 
3718     case INTRINSIC_AND:
3719       code = flag_frontend_optimize ? TRUTH_ANDIF_EXPR : TRUTH_AND_EXPR;
3720       lop = 1;
3721       break;
3722 
3723     case INTRINSIC_OR:
3724       code = flag_frontend_optimize ? TRUTH_ORIF_EXPR : TRUTH_OR_EXPR;
3725       lop = 1;
3726       break;
3727 
3728       /* EQV and NEQV only work on logicals, but since we represent them
3729          as integers, we can use EQ_EXPR and NE_EXPR for them in GIMPLE.  */
3730     case INTRINSIC_EQ:
3731     case INTRINSIC_EQ_OS:
3732     case INTRINSIC_EQV:
3733       code = EQ_EXPR;
3734       checkstring = 1;
3735       lop = 1;
3736       break;
3737 
3738     case INTRINSIC_NE:
3739     case INTRINSIC_NE_OS:
3740     case INTRINSIC_NEQV:
3741       code = NE_EXPR;
3742       checkstring = 1;
3743       lop = 1;
3744       break;
3745 
3746     case INTRINSIC_GT:
3747     case INTRINSIC_GT_OS:
3748       code = GT_EXPR;
3749       checkstring = 1;
3750       lop = 1;
3751       break;
3752 
3753     case INTRINSIC_GE:
3754     case INTRINSIC_GE_OS:
3755       code = GE_EXPR;
3756       checkstring = 1;
3757       lop = 1;
3758       break;
3759 
3760     case INTRINSIC_LT:
3761     case INTRINSIC_LT_OS:
3762       code = LT_EXPR;
3763       checkstring = 1;
3764       lop = 1;
3765       break;
3766 
3767     case INTRINSIC_LE:
3768     case INTRINSIC_LE_OS:
3769       code = LE_EXPR;
3770       checkstring = 1;
3771       lop = 1;
3772       break;
3773 
3774     case INTRINSIC_USER:
3775     case INTRINSIC_ASSIGN:
3776       /* These should be converted into function calls by the frontend.  */
3777       gcc_unreachable ();
3778 
3779     default:
3780       fatal_error (input_location, "Unknown intrinsic op");
3781       return;
3782     }
3783 
3784   /* The only exception to this is **, which is handled separately anyway.  */
3785   gcc_assert (expr->value.op.op1->ts.type == expr->value.op.op2->ts.type);
3786 
3787   if (checkstring && expr->value.op.op1->ts.type != BT_CHARACTER)
3788     checkstring = 0;
3789 
3790   /* lhs */
3791   gfc_init_se (&lse, se);
3792   gfc_conv_expr (&lse, expr->value.op.op1);
3793   gfc_add_block_to_block (&se->pre, &lse.pre);
3794 
3795   /* rhs */
3796   gfc_init_se (&rse, se);
3797   gfc_conv_expr (&rse, expr->value.op.op2);
3798   gfc_add_block_to_block (&se->pre, &rse.pre);
3799 
3800   if (checkstring)
3801     {
3802       gfc_conv_string_parameter (&lse);
3803       gfc_conv_string_parameter (&rse);
3804 
3805       lse.expr = gfc_build_compare_string (lse.string_length, lse.expr,
3806 					   rse.string_length, rse.expr,
3807 					   expr->value.op.op1->ts.kind,
3808 					   code);
3809       rse.expr = build_int_cst (TREE_TYPE (lse.expr), 0);
3810       gfc_add_block_to_block (&lse.post, &rse.post);
3811     }
3812 
3813   type = gfc_typenode_for_spec (&expr->ts);
3814 
3815   if (lop)
3816     {
3817       /* The result of logical ops is always logical_type_node.  */
3818       tmp = fold_build2_loc (input_location, code, logical_type_node,
3819 			     lse.expr, rse.expr);
3820       se->expr = convert (type, tmp);
3821     }
3822   else
3823     se->expr = fold_build2_loc (input_location, code, type, lse.expr, rse.expr);
3824 
3825   /* Add the post blocks.  */
3826   gfc_add_block_to_block (&se->post, &rse.post);
3827   gfc_add_block_to_block (&se->post, &lse.post);
3828 }
3829 
3830 /* If a string's length is one, we convert it to a single character.  */
3831 
3832 tree
3833 gfc_string_to_single_character (tree len, tree str, int kind)
3834 {
3835 
3836   if (len == NULL
3837       || !tree_fits_uhwi_p (len)
3838       || !POINTER_TYPE_P (TREE_TYPE (str)))
3839     return NULL_TREE;
3840 
3841   if (TREE_INT_CST_LOW (len) == 1)
3842     {
3843       str = fold_convert (gfc_get_pchar_type (kind), str);
3844       return build_fold_indirect_ref_loc (input_location, str);
3845     }
3846 
3847   if (kind == 1
3848       && TREE_CODE (str) == ADDR_EXPR
3849       && TREE_CODE (TREE_OPERAND (str, 0)) == ARRAY_REF
3850       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (str, 0), 0)) == STRING_CST
3851       && array_ref_low_bound (TREE_OPERAND (str, 0))
3852 	 == TREE_OPERAND (TREE_OPERAND (str, 0), 1)
3853       && TREE_INT_CST_LOW (len) > 1
3854       && TREE_INT_CST_LOW (len)
3855 	 == (unsigned HOST_WIDE_INT)
3856 	    TREE_STRING_LENGTH (TREE_OPERAND (TREE_OPERAND (str, 0), 0)))
3857     {
3858       tree ret = fold_convert (gfc_get_pchar_type (kind), str);
3859       ret = build_fold_indirect_ref_loc (input_location, ret);
3860       if (TREE_CODE (ret) == INTEGER_CST)
3861 	{
3862 	  tree string_cst = TREE_OPERAND (TREE_OPERAND (str, 0), 0);
3863 	  int i, length = TREE_STRING_LENGTH (string_cst);
3864 	  const char *ptr = TREE_STRING_POINTER (string_cst);
3865 
3866 	  for (i = 1; i < length; i++)
3867 	    if (ptr[i] != ' ')
3868 	      return NULL_TREE;
3869 
3870 	  return ret;
3871 	}
3872     }
3873 
3874   return NULL_TREE;
3875 }
3876 
3877 
3878 void
3879 gfc_conv_scalar_char_value (gfc_symbol *sym, gfc_se *se, gfc_expr **expr)
3880 {
3881 
3882   if (sym->backend_decl)
3883     {
3884       /* This becomes the nominal_type in
3885 	 function.c:assign_parm_find_data_types.  */
3886       TREE_TYPE (sym->backend_decl) = unsigned_char_type_node;
3887       /* This becomes the passed_type in
3888 	 function.c:assign_parm_find_data_types.  C promotes char to
3889 	 integer for argument passing.  */
3890       DECL_ARG_TYPE (sym->backend_decl) = unsigned_type_node;
3891 
3892       DECL_BY_REFERENCE (sym->backend_decl) = 0;
3893     }
3894 
3895   if (expr != NULL)
3896     {
3897       /* If we have a constant character expression, make it into an
3898 	 integer.  */
3899       if ((*expr)->expr_type == EXPR_CONSTANT)
3900         {
3901 	  gfc_typespec ts;
3902           gfc_clear_ts (&ts);
3903 
3904 	  *expr = gfc_get_int_expr (gfc_default_integer_kind, NULL,
3905 				    (int)(*expr)->value.character.string[0]);
3906 	  if ((*expr)->ts.kind != gfc_c_int_kind)
3907 	    {
3908   	      /* The expr needs to be compatible with a C int.  If the
3909 		 conversion fails, then the 2 causes an ICE.  */
3910 	      ts.type = BT_INTEGER;
3911 	      ts.kind = gfc_c_int_kind;
3912 	      gfc_convert_type (*expr, &ts, 2);
3913 	    }
3914 	}
3915       else if (se != NULL && (*expr)->expr_type == EXPR_VARIABLE)
3916         {
3917 	  if ((*expr)->ref == NULL)
3918 	    {
3919 	      se->expr = gfc_string_to_single_character
3920 		(build_int_cst (integer_type_node, 1),
3921 		 gfc_build_addr_expr (gfc_get_pchar_type ((*expr)->ts.kind),
3922 				      gfc_get_symbol_decl
3923 				      ((*expr)->symtree->n.sym)),
3924 		 (*expr)->ts.kind);
3925 	    }
3926 	  else
3927 	    {
3928 	      gfc_conv_variable (se, *expr);
3929 	      se->expr = gfc_string_to_single_character
3930 		(build_int_cst (integer_type_node, 1),
3931 		 gfc_build_addr_expr (gfc_get_pchar_type ((*expr)->ts.kind),
3932 				      se->expr),
3933 		 (*expr)->ts.kind);
3934 	    }
3935 	}
3936     }
3937 }
3938 
3939 /* Helper function for gfc_build_compare_string.  Return LEN_TRIM value
3940    if STR is a string literal, otherwise return -1.  */
3941 
3942 static int
3943 gfc_optimize_len_trim (tree len, tree str, int kind)
3944 {
3945   if (kind == 1
3946       && TREE_CODE (str) == ADDR_EXPR
3947       && TREE_CODE (TREE_OPERAND (str, 0)) == ARRAY_REF
3948       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (str, 0), 0)) == STRING_CST
3949       && array_ref_low_bound (TREE_OPERAND (str, 0))
3950 	 == TREE_OPERAND (TREE_OPERAND (str, 0), 1)
3951       && tree_fits_uhwi_p (len)
3952       && tree_to_uhwi (len) >= 1
3953       && tree_to_uhwi (len)
3954 	 == (unsigned HOST_WIDE_INT)
3955 	    TREE_STRING_LENGTH (TREE_OPERAND (TREE_OPERAND (str, 0), 0)))
3956     {
3957       tree folded = fold_convert (gfc_get_pchar_type (kind), str);
3958       folded = build_fold_indirect_ref_loc (input_location, folded);
3959       if (TREE_CODE (folded) == INTEGER_CST)
3960 	{
3961 	  tree string_cst = TREE_OPERAND (TREE_OPERAND (str, 0), 0);
3962 	  int length = TREE_STRING_LENGTH (string_cst);
3963 	  const char *ptr = TREE_STRING_POINTER (string_cst);
3964 
3965 	  for (; length > 0; length--)
3966 	    if (ptr[length - 1] != ' ')
3967 	      break;
3968 
3969 	  return length;
3970 	}
3971     }
3972   return -1;
3973 }
3974 
3975 /* Helper to build a call to memcmp.  */
3976 
3977 static tree
3978 build_memcmp_call (tree s1, tree s2, tree n)
3979 {
3980   tree tmp;
3981 
3982   if (!POINTER_TYPE_P (TREE_TYPE (s1)))
3983     s1 = gfc_build_addr_expr (pvoid_type_node, s1);
3984   else
3985     s1 = fold_convert (pvoid_type_node, s1);
3986 
3987   if (!POINTER_TYPE_P (TREE_TYPE (s2)))
3988     s2 = gfc_build_addr_expr (pvoid_type_node, s2);
3989   else
3990     s2 = fold_convert (pvoid_type_node, s2);
3991 
3992   n = fold_convert (size_type_node, n);
3993 
3994   tmp = build_call_expr_loc (input_location,
3995 			     builtin_decl_explicit (BUILT_IN_MEMCMP),
3996 			     3, s1, s2, n);
3997 
3998   return fold_convert (integer_type_node, tmp);
3999 }
4000 
4001 /* Compare two strings. If they are all single characters, the result is the
4002    subtraction of them. Otherwise, we build a library call.  */
4003 
4004 tree
4005 gfc_build_compare_string (tree len1, tree str1, tree len2, tree str2, int kind,
4006 			  enum tree_code code)
4007 {
4008   tree sc1;
4009   tree sc2;
4010   tree fndecl;
4011 
4012   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str1)));
4013   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str2)));
4014 
4015   sc1 = gfc_string_to_single_character (len1, str1, kind);
4016   sc2 = gfc_string_to_single_character (len2, str2, kind);
4017 
4018   if (sc1 != NULL_TREE && sc2 != NULL_TREE)
4019     {
4020       /* Deal with single character specially.  */
4021       sc1 = fold_convert (integer_type_node, sc1);
4022       sc2 = fold_convert (integer_type_node, sc2);
4023       return fold_build2_loc (input_location, MINUS_EXPR, integer_type_node,
4024 			      sc1, sc2);
4025     }
4026 
4027   if ((code == EQ_EXPR || code == NE_EXPR)
4028       && optimize
4029       && INTEGER_CST_P (len1) && INTEGER_CST_P (len2))
4030     {
4031       /* If one string is a string literal with LEN_TRIM longer
4032 	 than the length of the second string, the strings
4033 	 compare unequal.  */
4034       int len = gfc_optimize_len_trim (len1, str1, kind);
4035       if (len > 0 && compare_tree_int (len2, len) < 0)
4036 	return integer_one_node;
4037       len = gfc_optimize_len_trim (len2, str2, kind);
4038       if (len > 0 && compare_tree_int (len1, len) < 0)
4039 	return integer_one_node;
4040     }
4041 
4042   /* We can compare via memcpy if the strings are known to be equal
4043      in length and they are
4044      - kind=1
4045      - kind=4 and the comparison is for (in)equality.  */
4046 
4047   if (INTEGER_CST_P (len1) && INTEGER_CST_P (len2)
4048       && tree_int_cst_equal (len1, len2)
4049       && (kind == 1 || code == EQ_EXPR || code == NE_EXPR))
4050     {
4051       tree tmp;
4052       tree chartype;
4053 
4054       chartype = gfc_get_char_type (kind);
4055       tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE(len1),
4056 			     fold_convert (TREE_TYPE(len1),
4057 					   TYPE_SIZE_UNIT(chartype)),
4058 			     len1);
4059       return build_memcmp_call (str1, str2, tmp);
4060     }
4061 
4062   /* Build a call for the comparison.  */
4063   if (kind == 1)
4064     fndecl = gfor_fndecl_compare_string;
4065   else if (kind == 4)
4066     fndecl = gfor_fndecl_compare_string_char4;
4067   else
4068     gcc_unreachable ();
4069 
4070   return build_call_expr_loc (input_location, fndecl, 4,
4071 			      len1, str1, len2, str2);
4072 }
4073 
4074 
4075 /* Return the backend_decl for a procedure pointer component.  */
4076 
4077 static tree
4078 get_proc_ptr_comp (gfc_expr *e)
4079 {
4080   gfc_se comp_se;
4081   gfc_expr *e2;
4082   expr_t old_type;
4083 
4084   gfc_init_se (&comp_se, NULL);
4085   e2 = gfc_copy_expr (e);
4086   /* We have to restore the expr type later so that gfc_free_expr frees
4087      the exact same thing that was allocated.
4088      TODO: This is ugly.  */
4089   old_type = e2->expr_type;
4090   e2->expr_type = EXPR_VARIABLE;
4091   gfc_conv_expr (&comp_se, e2);
4092   e2->expr_type = old_type;
4093   gfc_free_expr (e2);
4094   return build_fold_addr_expr_loc (input_location, comp_se.expr);
4095 }
4096 
4097 
4098 /* Convert a typebound function reference from a class object.  */
4099 static void
4100 conv_base_obj_fcn_val (gfc_se * se, tree base_object, gfc_expr * expr)
4101 {
4102   gfc_ref *ref;
4103   tree var;
4104 
4105   if (!VAR_P (base_object))
4106     {
4107       var = gfc_create_var (TREE_TYPE (base_object), NULL);
4108       gfc_add_modify (&se->pre, var, base_object);
4109     }
4110   se->expr = gfc_class_vptr_get (base_object);
4111   se->expr = build_fold_indirect_ref_loc (input_location, se->expr);
4112   ref = expr->ref;
4113   while (ref && ref->next)
4114     ref = ref->next;
4115   gcc_assert (ref && ref->type == REF_COMPONENT);
4116   if (ref->u.c.sym->attr.extension)
4117     conv_parent_component_references (se, ref);
4118   gfc_conv_component_ref (se, ref);
4119   se->expr = build_fold_addr_expr_loc (input_location, se->expr);
4120 }
4121 
4122 
4123 static void
4124 conv_function_val (gfc_se * se, gfc_symbol * sym, gfc_expr * expr,
4125 		   gfc_actual_arglist *actual_args)
4126 {
4127   tree tmp;
4128 
4129   if (gfc_is_proc_ptr_comp (expr))
4130     tmp = get_proc_ptr_comp (expr);
4131   else if (sym->attr.dummy)
4132     {
4133       tmp = gfc_get_symbol_decl (sym);
4134       if (sym->attr.proc_pointer)
4135         tmp = build_fold_indirect_ref_loc (input_location,
4136 				       tmp);
4137       gcc_assert (TREE_CODE (TREE_TYPE (tmp)) == POINTER_TYPE
4138 	      && TREE_CODE (TREE_TYPE (TREE_TYPE (tmp))) == FUNCTION_TYPE);
4139     }
4140   else
4141     {
4142       if (!sym->backend_decl)
4143 	sym->backend_decl = gfc_get_extern_function_decl (sym, actual_args);
4144 
4145       TREE_USED (sym->backend_decl) = 1;
4146 
4147       tmp = sym->backend_decl;
4148 
4149       if (sym->attr.cray_pointee)
4150 	{
4151 	  /* TODO - make the cray pointee a pointer to a procedure,
4152 	     assign the pointer to it and use it for the call.  This
4153 	     will do for now!  */
4154 	  tmp = convert (build_pointer_type (TREE_TYPE (tmp)),
4155 			 gfc_get_symbol_decl (sym->cp_pointer));
4156 	  tmp = gfc_evaluate_now (tmp, &se->pre);
4157 	}
4158 
4159       if (!POINTER_TYPE_P (TREE_TYPE (tmp)))
4160 	{
4161 	  gcc_assert (TREE_CODE (tmp) == FUNCTION_DECL);
4162 	  tmp = gfc_build_addr_expr (NULL_TREE, tmp);
4163 	}
4164     }
4165   se->expr = tmp;
4166 }
4167 
4168 
4169 /* Initialize MAPPING.  */
4170 
4171 void
4172 gfc_init_interface_mapping (gfc_interface_mapping * mapping)
4173 {
4174   mapping->syms = NULL;
4175   mapping->charlens = NULL;
4176 }
4177 
4178 
4179 /* Free all memory held by MAPPING (but not MAPPING itself).  */
4180 
4181 void
4182 gfc_free_interface_mapping (gfc_interface_mapping * mapping)
4183 {
4184   gfc_interface_sym_mapping *sym;
4185   gfc_interface_sym_mapping *nextsym;
4186   gfc_charlen *cl;
4187   gfc_charlen *nextcl;
4188 
4189   for (sym = mapping->syms; sym; sym = nextsym)
4190     {
4191       nextsym = sym->next;
4192       sym->new_sym->n.sym->formal = NULL;
4193       gfc_free_symbol (sym->new_sym->n.sym);
4194       gfc_free_expr (sym->expr);
4195       free (sym->new_sym);
4196       free (sym);
4197     }
4198   for (cl = mapping->charlens; cl; cl = nextcl)
4199     {
4200       nextcl = cl->next;
4201       gfc_free_expr (cl->length);
4202       free (cl);
4203     }
4204 }
4205 
4206 
4207 /* Return a copy of gfc_charlen CL.  Add the returned structure to
4208    MAPPING so that it will be freed by gfc_free_interface_mapping.  */
4209 
4210 static gfc_charlen *
4211 gfc_get_interface_mapping_charlen (gfc_interface_mapping * mapping,
4212 				   gfc_charlen * cl)
4213 {
4214   gfc_charlen *new_charlen;
4215 
4216   new_charlen = gfc_get_charlen ();
4217   new_charlen->next = mapping->charlens;
4218   new_charlen->length = gfc_copy_expr (cl->length);
4219 
4220   mapping->charlens = new_charlen;
4221   return new_charlen;
4222 }
4223 
4224 
4225 /* A subroutine of gfc_add_interface_mapping.  Return a descriptorless
4226    array variable that can be used as the actual argument for dummy
4227    argument SYM.  Add any initialization code to BLOCK.  PACKED is as
4228    for gfc_get_nodesc_array_type and DATA points to the first element
4229    in the passed array.  */
4230 
4231 static tree
4232 gfc_get_interface_mapping_array (stmtblock_t * block, gfc_symbol * sym,
4233 				 gfc_packed packed, tree data)
4234 {
4235   tree type;
4236   tree var;
4237 
4238   type = gfc_typenode_for_spec (&sym->ts);
4239   type = gfc_get_nodesc_array_type (type, sym->as, packed,
4240 				    !sym->attr.target && !sym->attr.pointer
4241 				    && !sym->attr.proc_pointer);
4242 
4243   var = gfc_create_var (type, "ifm");
4244   gfc_add_modify (block, var, fold_convert (type, data));
4245 
4246   return var;
4247 }
4248 
4249 
4250 /* A subroutine of gfc_add_interface_mapping.  Set the stride, upper bounds
4251    and offset of descriptorless array type TYPE given that it has the same
4252    size as DESC.  Add any set-up code to BLOCK.  */
4253 
4254 static void
4255 gfc_set_interface_mapping_bounds (stmtblock_t * block, tree type, tree desc)
4256 {
4257   int n;
4258   tree dim;
4259   tree offset;
4260   tree tmp;
4261 
4262   offset = gfc_index_zero_node;
4263   for (n = 0; n < GFC_TYPE_ARRAY_RANK (type); n++)
4264     {
4265       dim = gfc_rank_cst[n];
4266       GFC_TYPE_ARRAY_STRIDE (type, n) = gfc_conv_array_stride (desc, n);
4267       if (GFC_TYPE_ARRAY_LBOUND (type, n) == NULL_TREE)
4268 	{
4269 	  GFC_TYPE_ARRAY_LBOUND (type, n)
4270 		= gfc_conv_descriptor_lbound_get (desc, dim);
4271 	  GFC_TYPE_ARRAY_UBOUND (type, n)
4272 		= gfc_conv_descriptor_ubound_get (desc, dim);
4273 	}
4274       else if (GFC_TYPE_ARRAY_UBOUND (type, n) == NULL_TREE)
4275 	{
4276 	  tmp = fold_build2_loc (input_location, MINUS_EXPR,
4277 				 gfc_array_index_type,
4278 				 gfc_conv_descriptor_ubound_get (desc, dim),
4279 				 gfc_conv_descriptor_lbound_get (desc, dim));
4280 	  tmp = fold_build2_loc (input_location, PLUS_EXPR,
4281 				 gfc_array_index_type,
4282 				 GFC_TYPE_ARRAY_LBOUND (type, n), tmp);
4283 	  tmp = gfc_evaluate_now (tmp, block);
4284 	  GFC_TYPE_ARRAY_UBOUND (type, n) = tmp;
4285 	}
4286       tmp = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
4287 			     GFC_TYPE_ARRAY_LBOUND (type, n),
4288 			     GFC_TYPE_ARRAY_STRIDE (type, n));
4289       offset = fold_build2_loc (input_location, MINUS_EXPR,
4290 				gfc_array_index_type, offset, tmp);
4291     }
4292   offset = gfc_evaluate_now (offset, block);
4293   GFC_TYPE_ARRAY_OFFSET (type) = offset;
4294 }
4295 
4296 
4297 /* Extend MAPPING so that it maps dummy argument SYM to the value stored
4298    in SE.  The caller may still use se->expr and se->string_length after
4299    calling this function.  */
4300 
4301 void
4302 gfc_add_interface_mapping (gfc_interface_mapping * mapping,
4303 			   gfc_symbol * sym, gfc_se * se,
4304 			   gfc_expr *expr)
4305 {
4306   gfc_interface_sym_mapping *sm;
4307   tree desc;
4308   tree tmp;
4309   tree value;
4310   gfc_symbol *new_sym;
4311   gfc_symtree *root;
4312   gfc_symtree *new_symtree;
4313 
4314   /* Create a new symbol to represent the actual argument.  */
4315   new_sym = gfc_new_symbol (sym->name, NULL);
4316   new_sym->ts = sym->ts;
4317   new_sym->as = gfc_copy_array_spec (sym->as);
4318   new_sym->attr.referenced = 1;
4319   new_sym->attr.dimension = sym->attr.dimension;
4320   new_sym->attr.contiguous = sym->attr.contiguous;
4321   new_sym->attr.codimension = sym->attr.codimension;
4322   new_sym->attr.pointer = sym->attr.pointer;
4323   new_sym->attr.allocatable = sym->attr.allocatable;
4324   new_sym->attr.flavor = sym->attr.flavor;
4325   new_sym->attr.function = sym->attr.function;
4326 
4327   /* Ensure that the interface is available and that
4328      descriptors are passed for array actual arguments.  */
4329   if (sym->attr.flavor == FL_PROCEDURE)
4330     {
4331       new_sym->formal = expr->symtree->n.sym->formal;
4332       new_sym->attr.always_explicit
4333 	    = expr->symtree->n.sym->attr.always_explicit;
4334     }
4335 
4336   /* Create a fake symtree for it.  */
4337   root = NULL;
4338   new_symtree = gfc_new_symtree (&root, sym->name);
4339   new_symtree->n.sym = new_sym;
4340   gcc_assert (new_symtree == root);
4341 
4342   /* Create a dummy->actual mapping.  */
4343   sm = XCNEW (gfc_interface_sym_mapping);
4344   sm->next = mapping->syms;
4345   sm->old = sym;
4346   sm->new_sym = new_symtree;
4347   sm->expr = gfc_copy_expr (expr);
4348   mapping->syms = sm;
4349 
4350   /* Stabilize the argument's value.  */
4351   if (!sym->attr.function && se)
4352     se->expr = gfc_evaluate_now (se->expr, &se->pre);
4353 
4354   if (sym->ts.type == BT_CHARACTER)
4355     {
4356       /* Create a copy of the dummy argument's length.  */
4357       new_sym->ts.u.cl = gfc_get_interface_mapping_charlen (mapping, sym->ts.u.cl);
4358       sm->expr->ts.u.cl = new_sym->ts.u.cl;
4359 
4360       /* If the length is specified as "*", record the length that
4361 	 the caller is passing.  We should use the callee's length
4362 	 in all other cases.  */
4363       if (!new_sym->ts.u.cl->length && se)
4364 	{
4365 	  se->string_length = gfc_evaluate_now (se->string_length, &se->pre);
4366 	  new_sym->ts.u.cl->backend_decl = se->string_length;
4367 	}
4368     }
4369 
4370   if (!se)
4371     return;
4372 
4373   /* Use the passed value as-is if the argument is a function.  */
4374   if (sym->attr.flavor == FL_PROCEDURE)
4375     value = se->expr;
4376 
4377   /* If the argument is a pass-by-value scalar, use the value as is.  */
4378   else if (!sym->attr.dimension && sym->attr.value)
4379     value = se->expr;
4380 
4381   /* If the argument is either a string or a pointer to a string,
4382      convert it to a boundless character type.  */
4383   else if (!sym->attr.dimension && sym->ts.type == BT_CHARACTER)
4384     {
4385       tmp = gfc_get_character_type_len (sym->ts.kind, NULL);
4386       tmp = build_pointer_type (tmp);
4387       if (sym->attr.pointer)
4388         value = build_fold_indirect_ref_loc (input_location,
4389 					 se->expr);
4390       else
4391         value = se->expr;
4392       value = fold_convert (tmp, value);
4393     }
4394 
4395   /* If the argument is a scalar, a pointer to an array or an allocatable,
4396      dereference it.  */
4397   else if (!sym->attr.dimension || sym->attr.pointer || sym->attr.allocatable)
4398     value = build_fold_indirect_ref_loc (input_location,
4399 				     se->expr);
4400 
4401   /* For character(*), use the actual argument's descriptor.  */
4402   else if (sym->ts.type == BT_CHARACTER && !new_sym->ts.u.cl->length)
4403     value = build_fold_indirect_ref_loc (input_location,
4404 				     se->expr);
4405 
4406   /* If the argument is an array descriptor, use it to determine
4407      information about the actual argument's shape.  */
4408   else if (POINTER_TYPE_P (TREE_TYPE (se->expr))
4409 	   && GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (TREE_TYPE (se->expr))))
4410     {
4411       /* Get the actual argument's descriptor.  */
4412       desc = build_fold_indirect_ref_loc (input_location,
4413 				      se->expr);
4414 
4415       /* Create the replacement variable.  */
4416       tmp = gfc_conv_descriptor_data_get (desc);
4417       value = gfc_get_interface_mapping_array (&se->pre, sym,
4418 					       PACKED_NO, tmp);
4419 
4420       /* Use DESC to work out the upper bounds, strides and offset.  */
4421       gfc_set_interface_mapping_bounds (&se->pre, TREE_TYPE (value), desc);
4422     }
4423   else
4424     /* Otherwise we have a packed array.  */
4425     value = gfc_get_interface_mapping_array (&se->pre, sym,
4426 					     PACKED_FULL, se->expr);
4427 
4428   new_sym->backend_decl = value;
4429 }
4430 
4431 
4432 /* Called once all dummy argument mappings have been added to MAPPING,
4433    but before the mapping is used to evaluate expressions.  Pre-evaluate
4434    the length of each argument, adding any initialization code to PRE and
4435    any finalization code to POST.  */
4436 
4437 void
4438 gfc_finish_interface_mapping (gfc_interface_mapping * mapping,
4439 			      stmtblock_t * pre, stmtblock_t * post)
4440 {
4441   gfc_interface_sym_mapping *sym;
4442   gfc_expr *expr;
4443   gfc_se se;
4444 
4445   for (sym = mapping->syms; sym; sym = sym->next)
4446     if (sym->new_sym->n.sym->ts.type == BT_CHARACTER
4447 	&& !sym->new_sym->n.sym->ts.u.cl->backend_decl)
4448       {
4449 	expr = sym->new_sym->n.sym->ts.u.cl->length;
4450 	gfc_apply_interface_mapping_to_expr (mapping, expr);
4451 	gfc_init_se (&se, NULL);
4452 	gfc_conv_expr (&se, expr);
4453 	se.expr = fold_convert (gfc_charlen_type_node, se.expr);
4454 	se.expr = gfc_evaluate_now (se.expr, &se.pre);
4455 	gfc_add_block_to_block (pre, &se.pre);
4456 	gfc_add_block_to_block (post, &se.post);
4457 
4458 	sym->new_sym->n.sym->ts.u.cl->backend_decl = se.expr;
4459       }
4460 }
4461 
4462 
4463 /* Like gfc_apply_interface_mapping_to_expr, but applied to
4464    constructor C.  */
4465 
4466 static void
4467 gfc_apply_interface_mapping_to_cons (gfc_interface_mapping * mapping,
4468 				     gfc_constructor_base base)
4469 {
4470   gfc_constructor *c;
4471   for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
4472     {
4473       gfc_apply_interface_mapping_to_expr (mapping, c->expr);
4474       if (c->iterator)
4475 	{
4476 	  gfc_apply_interface_mapping_to_expr (mapping, c->iterator->start);
4477 	  gfc_apply_interface_mapping_to_expr (mapping, c->iterator->end);
4478 	  gfc_apply_interface_mapping_to_expr (mapping, c->iterator->step);
4479 	}
4480     }
4481 }
4482 
4483 
4484 /* Like gfc_apply_interface_mapping_to_expr, but applied to
4485    reference REF.  */
4486 
4487 static void
4488 gfc_apply_interface_mapping_to_ref (gfc_interface_mapping * mapping,
4489 				    gfc_ref * ref)
4490 {
4491   int n;
4492 
4493   for (; ref; ref = ref->next)
4494     switch (ref->type)
4495       {
4496       case REF_ARRAY:
4497 	for (n = 0; n < ref->u.ar.dimen; n++)
4498 	  {
4499 	    gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.start[n]);
4500 	    gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.end[n]);
4501 	    gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.stride[n]);
4502 	  }
4503 	break;
4504 
4505       case REF_COMPONENT:
4506       case REF_INQUIRY:
4507 	break;
4508 
4509       case REF_SUBSTRING:
4510 	gfc_apply_interface_mapping_to_expr (mapping, ref->u.ss.start);
4511 	gfc_apply_interface_mapping_to_expr (mapping, ref->u.ss.end);
4512 	break;
4513       }
4514 }
4515 
4516 
4517 /* Convert intrinsic function calls into result expressions.  */
4518 
4519 static bool
4520 gfc_map_intrinsic_function (gfc_expr *expr, gfc_interface_mapping *mapping)
4521 {
4522   gfc_symbol *sym;
4523   gfc_expr *new_expr;
4524   gfc_expr *arg1;
4525   gfc_expr *arg2;
4526   int d, dup;
4527 
4528   arg1 = expr->value.function.actual->expr;
4529   if (expr->value.function.actual->next)
4530     arg2 = expr->value.function.actual->next->expr;
4531   else
4532     arg2 = NULL;
4533 
4534   sym = arg1->symtree->n.sym;
4535 
4536   if (sym->attr.dummy)
4537     return false;
4538 
4539   new_expr = NULL;
4540 
4541   switch (expr->value.function.isym->id)
4542     {
4543     case GFC_ISYM_LEN:
4544       /* TODO figure out why this condition is necessary.  */
4545       if (sym->attr.function
4546 	  && (arg1->ts.u.cl->length == NULL
4547 	      || (arg1->ts.u.cl->length->expr_type != EXPR_CONSTANT
4548 		  && arg1->ts.u.cl->length->expr_type != EXPR_VARIABLE)))
4549 	return false;
4550 
4551       new_expr = gfc_copy_expr (arg1->ts.u.cl->length);
4552       break;
4553 
4554     case GFC_ISYM_LEN_TRIM:
4555       new_expr = gfc_copy_expr (arg1);
4556       gfc_apply_interface_mapping_to_expr (mapping, new_expr);
4557 
4558       if (!new_expr)
4559 	return false;
4560 
4561       gfc_replace_expr (arg1, new_expr);
4562       return true;
4563 
4564     case GFC_ISYM_SIZE:
4565       if (!sym->as || sym->as->rank == 0)
4566 	return false;
4567 
4568       if (arg2 && arg2->expr_type == EXPR_CONSTANT)
4569 	{
4570 	  dup = mpz_get_si (arg2->value.integer);
4571 	  d = dup - 1;
4572 	}
4573       else
4574 	{
4575 	  dup = sym->as->rank;
4576 	  d = 0;
4577 	}
4578 
4579       for (; d < dup; d++)
4580 	{
4581 	  gfc_expr *tmp;
4582 
4583 	  if (!sym->as->upper[d] || !sym->as->lower[d])
4584 	    {
4585 	      gfc_free_expr (new_expr);
4586 	      return false;
4587 	    }
4588 
4589 	  tmp = gfc_add (gfc_copy_expr (sym->as->upper[d]),
4590 					gfc_get_int_expr (gfc_default_integer_kind,
4591 							  NULL, 1));
4592 	  tmp = gfc_subtract (tmp, gfc_copy_expr (sym->as->lower[d]));
4593 	  if (new_expr)
4594 	    new_expr = gfc_multiply (new_expr, tmp);
4595 	  else
4596 	    new_expr = tmp;
4597 	}
4598       break;
4599 
4600     case GFC_ISYM_LBOUND:
4601     case GFC_ISYM_UBOUND:
4602 	/* TODO These implementations of lbound and ubound do not limit if
4603 	   the size < 0, according to F95's 13.14.53 and 13.14.113.  */
4604 
4605       if (!sym->as || sym->as->rank == 0)
4606 	return false;
4607 
4608       if (arg2 && arg2->expr_type == EXPR_CONSTANT)
4609 	d = mpz_get_si (arg2->value.integer) - 1;
4610       else
4611 	return false;
4612 
4613       if (expr->value.function.isym->id == GFC_ISYM_LBOUND)
4614 	{
4615 	  if (sym->as->lower[d])
4616 	    new_expr = gfc_copy_expr (sym->as->lower[d]);
4617 	}
4618       else
4619 	{
4620 	  if (sym->as->upper[d])
4621 	    new_expr = gfc_copy_expr (sym->as->upper[d]);
4622 	}
4623       break;
4624 
4625     default:
4626       break;
4627     }
4628 
4629   gfc_apply_interface_mapping_to_expr (mapping, new_expr);
4630   if (!new_expr)
4631     return false;
4632 
4633   gfc_replace_expr (expr, new_expr);
4634   return true;
4635 }
4636 
4637 
4638 static void
4639 gfc_map_fcn_formal_to_actual (gfc_expr *expr, gfc_expr *map_expr,
4640 			      gfc_interface_mapping * mapping)
4641 {
4642   gfc_formal_arglist *f;
4643   gfc_actual_arglist *actual;
4644 
4645   actual = expr->value.function.actual;
4646   f = gfc_sym_get_dummy_args (map_expr->symtree->n.sym);
4647 
4648   for (; f && actual; f = f->next, actual = actual->next)
4649     {
4650       if (!actual->expr)
4651 	continue;
4652 
4653       gfc_add_interface_mapping (mapping, f->sym, NULL, actual->expr);
4654     }
4655 
4656   if (map_expr->symtree->n.sym->attr.dimension)
4657     {
4658       int d;
4659       gfc_array_spec *as;
4660 
4661       as = gfc_copy_array_spec (map_expr->symtree->n.sym->as);
4662 
4663       for (d = 0; d < as->rank; d++)
4664 	{
4665 	  gfc_apply_interface_mapping_to_expr (mapping, as->lower[d]);
4666 	  gfc_apply_interface_mapping_to_expr (mapping, as->upper[d]);
4667 	}
4668 
4669       expr->value.function.esym->as = as;
4670     }
4671 
4672   if (map_expr->symtree->n.sym->ts.type == BT_CHARACTER)
4673     {
4674       expr->value.function.esym->ts.u.cl->length
4675 	= gfc_copy_expr (map_expr->symtree->n.sym->ts.u.cl->length);
4676 
4677       gfc_apply_interface_mapping_to_expr (mapping,
4678 			expr->value.function.esym->ts.u.cl->length);
4679     }
4680 }
4681 
4682 
4683 /* EXPR is a copy of an expression that appeared in the interface
4684    associated with MAPPING.  Walk it recursively looking for references to
4685    dummy arguments that MAPPING maps to actual arguments.  Replace each such
4686    reference with a reference to the associated actual argument.  */
4687 
4688 static void
4689 gfc_apply_interface_mapping_to_expr (gfc_interface_mapping * mapping,
4690 				     gfc_expr * expr)
4691 {
4692   gfc_interface_sym_mapping *sym;
4693   gfc_actual_arglist *actual;
4694 
4695   if (!expr)
4696     return;
4697 
4698   /* Copying an expression does not copy its length, so do that here.  */
4699   if (expr->ts.type == BT_CHARACTER && expr->ts.u.cl)
4700     {
4701       expr->ts.u.cl = gfc_get_interface_mapping_charlen (mapping, expr->ts.u.cl);
4702       gfc_apply_interface_mapping_to_expr (mapping, expr->ts.u.cl->length);
4703     }
4704 
4705   /* Apply the mapping to any references.  */
4706   gfc_apply_interface_mapping_to_ref (mapping, expr->ref);
4707 
4708   /* ...and to the expression's symbol, if it has one.  */
4709   /* TODO Find out why the condition on expr->symtree had to be moved into
4710      the loop rather than being outside it, as originally.  */
4711   for (sym = mapping->syms; sym; sym = sym->next)
4712     if (expr->symtree && sym->old == expr->symtree->n.sym)
4713       {
4714 	if (sym->new_sym->n.sym->backend_decl)
4715 	  expr->symtree = sym->new_sym;
4716 	else if (sym->expr)
4717 	  gfc_replace_expr (expr, gfc_copy_expr (sym->expr));
4718       }
4719 
4720       /* ...and to subexpressions in expr->value.  */
4721   switch (expr->expr_type)
4722     {
4723     case EXPR_VARIABLE:
4724     case EXPR_CONSTANT:
4725     case EXPR_NULL:
4726     case EXPR_SUBSTRING:
4727       break;
4728 
4729     case EXPR_OP:
4730       gfc_apply_interface_mapping_to_expr (mapping, expr->value.op.op1);
4731       gfc_apply_interface_mapping_to_expr (mapping, expr->value.op.op2);
4732       break;
4733 
4734     case EXPR_FUNCTION:
4735       for (actual = expr->value.function.actual; actual; actual = actual->next)
4736 	gfc_apply_interface_mapping_to_expr (mapping, actual->expr);
4737 
4738       if (expr->value.function.esym == NULL
4739 	    && expr->value.function.isym != NULL
4740 	    && expr->value.function.actual
4741 	    && expr->value.function.actual->expr
4742 	    && expr->value.function.actual->expr->symtree
4743 	    && gfc_map_intrinsic_function (expr, mapping))
4744 	break;
4745 
4746       for (sym = mapping->syms; sym; sym = sym->next)
4747 	if (sym->old == expr->value.function.esym)
4748 	  {
4749 	    expr->value.function.esym = sym->new_sym->n.sym;
4750 	    gfc_map_fcn_formal_to_actual (expr, sym->expr, mapping);
4751 	    expr->value.function.esym->result = sym->new_sym->n.sym;
4752 	  }
4753       break;
4754 
4755     case EXPR_ARRAY:
4756     case EXPR_STRUCTURE:
4757       gfc_apply_interface_mapping_to_cons (mapping, expr->value.constructor);
4758       break;
4759 
4760     case EXPR_COMPCALL:
4761     case EXPR_PPC:
4762     case EXPR_UNKNOWN:
4763       gcc_unreachable ();
4764       break;
4765     }
4766 
4767   return;
4768 }
4769 
4770 
4771 /* Evaluate interface expression EXPR using MAPPING.  Store the result
4772    in SE.  */
4773 
4774 void
4775 gfc_apply_interface_mapping (gfc_interface_mapping * mapping,
4776 			     gfc_se * se, gfc_expr * expr)
4777 {
4778   expr = gfc_copy_expr (expr);
4779   gfc_apply_interface_mapping_to_expr (mapping, expr);
4780   gfc_conv_expr (se, expr);
4781   se->expr = gfc_evaluate_now (se->expr, &se->pre);
4782   gfc_free_expr (expr);
4783 }
4784 
4785 
4786 /* Returns a reference to a temporary array into which a component of
4787    an actual argument derived type array is copied and then returned
4788    after the function call.  */
4789 void
4790 gfc_conv_subref_array_arg (gfc_se *se, gfc_expr * expr, int g77,
4791 			   sym_intent intent, bool formal_ptr,
4792 			   const gfc_symbol *fsym, const char *proc_name,
4793 			   gfc_symbol *sym, bool check_contiguous)
4794 {
4795   gfc_se lse;
4796   gfc_se rse;
4797   gfc_ss *lss;
4798   gfc_ss *rss;
4799   gfc_loopinfo loop;
4800   gfc_loopinfo loop2;
4801   gfc_array_info *info;
4802   tree offset;
4803   tree tmp_index;
4804   tree tmp;
4805   tree base_type;
4806   tree size;
4807   stmtblock_t body;
4808   int n;
4809   int dimen;
4810   gfc_se work_se;
4811   gfc_se *parmse;
4812   bool pass_optional;
4813 
4814   pass_optional = fsym && fsym->attr.optional && sym && sym->attr.optional;
4815 
4816   if (pass_optional || check_contiguous)
4817     {
4818       gfc_init_se (&work_se, NULL);
4819       parmse = &work_se;
4820     }
4821   else
4822     parmse = se;
4823 
4824   if (gfc_option.rtcheck & GFC_RTCHECK_ARRAY_TEMPS)
4825     {
4826       /* We will create a temporary array, so let us warn.  */
4827       char * msg;
4828 
4829       if (fsym && proc_name)
4830 	msg = xasprintf ("An array temporary was created for argument "
4831 			     "'%s' of procedure '%s'", fsym->name, proc_name);
4832       else
4833 	msg = xasprintf ("An array temporary was created");
4834 
4835       tmp = build_int_cst (logical_type_node, 1);
4836       gfc_trans_runtime_check (false, true, tmp, &parmse->pre,
4837 			       &expr->where, msg);
4838       free (msg);
4839     }
4840 
4841   gfc_init_se (&lse, NULL);
4842   gfc_init_se (&rse, NULL);
4843 
4844   /* Walk the argument expression.  */
4845   rss = gfc_walk_expr (expr);
4846 
4847   gcc_assert (rss != gfc_ss_terminator);
4848 
4849   /* Initialize the scalarizer.  */
4850   gfc_init_loopinfo (&loop);
4851   gfc_add_ss_to_loop (&loop, rss);
4852 
4853   /* Calculate the bounds of the scalarization.  */
4854   gfc_conv_ss_startstride (&loop);
4855 
4856   /* Build an ss for the temporary.  */
4857   if (expr->ts.type == BT_CHARACTER && !expr->ts.u.cl->backend_decl)
4858     gfc_conv_string_length (expr->ts.u.cl, expr, &parmse->pre);
4859 
4860   base_type = gfc_typenode_for_spec (&expr->ts);
4861   if (GFC_ARRAY_TYPE_P (base_type)
4862 		|| GFC_DESCRIPTOR_TYPE_P (base_type))
4863     base_type = gfc_get_element_type (base_type);
4864 
4865   if (expr->ts.type == BT_CLASS)
4866     base_type = gfc_typenode_for_spec (&CLASS_DATA (expr)->ts);
4867 
4868   loop.temp_ss = gfc_get_temp_ss (base_type, ((expr->ts.type == BT_CHARACTER)
4869 					      ? expr->ts.u.cl->backend_decl
4870 					      : NULL),
4871 				  loop.dimen);
4872 
4873   parmse->string_length = loop.temp_ss->info->string_length;
4874 
4875   /* Associate the SS with the loop.  */
4876   gfc_add_ss_to_loop (&loop, loop.temp_ss);
4877 
4878   /* Setup the scalarizing loops.  */
4879   gfc_conv_loop_setup (&loop, &expr->where);
4880 
4881   /* Pass the temporary descriptor back to the caller.  */
4882   info = &loop.temp_ss->info->data.array;
4883   parmse->expr = info->descriptor;
4884 
4885   /* Setup the gfc_se structures.  */
4886   gfc_copy_loopinfo_to_se (&lse, &loop);
4887   gfc_copy_loopinfo_to_se (&rse, &loop);
4888 
4889   rse.ss = rss;
4890   lse.ss = loop.temp_ss;
4891   gfc_mark_ss_chain_used (rss, 1);
4892   gfc_mark_ss_chain_used (loop.temp_ss, 1);
4893 
4894   /* Start the scalarized loop body.  */
4895   gfc_start_scalarized_body (&loop, &body);
4896 
4897   /* Translate the expression.  */
4898   gfc_conv_expr (&rse, expr);
4899 
4900   /* Reset the offset for the function call since the loop
4901      is zero based on the data pointer.  Note that the temp
4902      comes first in the loop chain since it is added second.  */
4903   if (gfc_is_class_array_function (expr))
4904     {
4905       tmp = loop.ss->loop_chain->info->data.array.descriptor;
4906       gfc_conv_descriptor_offset_set (&loop.pre, tmp,
4907 				      gfc_index_zero_node);
4908     }
4909 
4910   gfc_conv_tmp_array_ref (&lse);
4911 
4912   if (intent != INTENT_OUT)
4913     {
4914       tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, false, false);
4915       gfc_add_expr_to_block (&body, tmp);
4916       gcc_assert (rse.ss == gfc_ss_terminator);
4917       gfc_trans_scalarizing_loops (&loop, &body);
4918     }
4919   else
4920     {
4921       /* Make sure that the temporary declaration survives by merging
4922        all the loop declarations into the current context.  */
4923       for (n = 0; n < loop.dimen; n++)
4924 	{
4925 	  gfc_merge_block_scope (&body);
4926 	  body = loop.code[loop.order[n]];
4927 	}
4928       gfc_merge_block_scope (&body);
4929     }
4930 
4931   /* Add the post block after the second loop, so that any
4932      freeing of allocated memory is done at the right time.  */
4933   gfc_add_block_to_block (&parmse->pre, &loop.pre);
4934 
4935   /**********Copy the temporary back again.*********/
4936 
4937   gfc_init_se (&lse, NULL);
4938   gfc_init_se (&rse, NULL);
4939 
4940   /* Walk the argument expression.  */
4941   lss = gfc_walk_expr (expr);
4942   rse.ss = loop.temp_ss;
4943   lse.ss = lss;
4944 
4945   /* Initialize the scalarizer.  */
4946   gfc_init_loopinfo (&loop2);
4947   gfc_add_ss_to_loop (&loop2, lss);
4948 
4949   dimen = rse.ss->dimen;
4950 
4951   /* Skip the write-out loop for this case.  */
4952   if (gfc_is_class_array_function (expr))
4953     goto class_array_fcn;
4954 
4955   /* Calculate the bounds of the scalarization.  */
4956   gfc_conv_ss_startstride (&loop2);
4957 
4958   /* Setup the scalarizing loops.  */
4959   gfc_conv_loop_setup (&loop2, &expr->where);
4960 
4961   gfc_copy_loopinfo_to_se (&lse, &loop2);
4962   gfc_copy_loopinfo_to_se (&rse, &loop2);
4963 
4964   gfc_mark_ss_chain_used (lss, 1);
4965   gfc_mark_ss_chain_used (loop.temp_ss, 1);
4966 
4967   /* Declare the variable to hold the temporary offset and start the
4968      scalarized loop body.  */
4969   offset = gfc_create_var (gfc_array_index_type, NULL);
4970   gfc_start_scalarized_body (&loop2, &body);
4971 
4972   /* Build the offsets for the temporary from the loop variables.  The
4973      temporary array has lbounds of zero and strides of one in all
4974      dimensions, so this is very simple.  The offset is only computed
4975      outside the innermost loop, so the overall transfer could be
4976      optimized further.  */
4977   info = &rse.ss->info->data.array;
4978 
4979   tmp_index = gfc_index_zero_node;
4980   for (n = dimen - 1; n > 0; n--)
4981     {
4982       tree tmp_str;
4983       tmp = rse.loop->loopvar[n];
4984       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
4985 			     tmp, rse.loop->from[n]);
4986       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
4987 			     tmp, tmp_index);
4988 
4989       tmp_str = fold_build2_loc (input_location, MINUS_EXPR,
4990 				 gfc_array_index_type,
4991 				 rse.loop->to[n-1], rse.loop->from[n-1]);
4992       tmp_str = fold_build2_loc (input_location, PLUS_EXPR,
4993 				 gfc_array_index_type,
4994 				 tmp_str, gfc_index_one_node);
4995 
4996       tmp_index = fold_build2_loc (input_location, MULT_EXPR,
4997 				   gfc_array_index_type, tmp, tmp_str);
4998     }
4999 
5000   tmp_index = fold_build2_loc (input_location, MINUS_EXPR,
5001 			       gfc_array_index_type,
5002 			       tmp_index, rse.loop->from[0]);
5003   gfc_add_modify (&rse.loop->code[0], offset, tmp_index);
5004 
5005   tmp_index = fold_build2_loc (input_location, PLUS_EXPR,
5006 			       gfc_array_index_type,
5007 			       rse.loop->loopvar[0], offset);
5008 
5009   /* Now use the offset for the reference.  */
5010   tmp = build_fold_indirect_ref_loc (input_location,
5011 				 info->data);
5012   rse.expr = gfc_build_array_ref (tmp, tmp_index, NULL);
5013 
5014   if (expr->ts.type == BT_CHARACTER)
5015     rse.string_length = expr->ts.u.cl->backend_decl;
5016 
5017   gfc_conv_expr (&lse, expr);
5018 
5019   gcc_assert (lse.ss == gfc_ss_terminator);
5020 
5021   tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, false, true);
5022   gfc_add_expr_to_block (&body, tmp);
5023 
5024   /* Generate the copying loops.  */
5025   gfc_trans_scalarizing_loops (&loop2, &body);
5026 
5027   /* Wrap the whole thing up by adding the second loop to the post-block
5028      and following it by the post-block of the first loop.  In this way,
5029      if the temporary needs freeing, it is done after use!  */
5030   if (intent != INTENT_IN)
5031     {
5032       gfc_add_block_to_block (&parmse->post, &loop2.pre);
5033       gfc_add_block_to_block (&parmse->post, &loop2.post);
5034     }
5035 
5036 class_array_fcn:
5037 
5038   gfc_add_block_to_block (&parmse->post, &loop.post);
5039 
5040   gfc_cleanup_loop (&loop);
5041   gfc_cleanup_loop (&loop2);
5042 
5043   /* Pass the string length to the argument expression.  */
5044   if (expr->ts.type == BT_CHARACTER)
5045     parmse->string_length = expr->ts.u.cl->backend_decl;
5046 
5047   /* Determine the offset for pointer formal arguments and set the
5048      lbounds to one.  */
5049   if (formal_ptr)
5050     {
5051       size = gfc_index_one_node;
5052       offset = gfc_index_zero_node;
5053       for (n = 0; n < dimen; n++)
5054 	{
5055 	  tmp = gfc_conv_descriptor_ubound_get (parmse->expr,
5056 						gfc_rank_cst[n]);
5057 	  tmp = fold_build2_loc (input_location, PLUS_EXPR,
5058 				 gfc_array_index_type, tmp,
5059 				 gfc_index_one_node);
5060 	  gfc_conv_descriptor_ubound_set (&parmse->pre,
5061 					  parmse->expr,
5062 					  gfc_rank_cst[n],
5063 					  tmp);
5064 	  gfc_conv_descriptor_lbound_set (&parmse->pre,
5065 					  parmse->expr,
5066 					  gfc_rank_cst[n],
5067 					  gfc_index_one_node);
5068 	  size = gfc_evaluate_now (size, &parmse->pre);
5069 	  offset = fold_build2_loc (input_location, MINUS_EXPR,
5070 				    gfc_array_index_type,
5071 				    offset, size);
5072 	  offset = gfc_evaluate_now (offset, &parmse->pre);
5073 	  tmp = fold_build2_loc (input_location, MINUS_EXPR,
5074 				 gfc_array_index_type,
5075 				 rse.loop->to[n], rse.loop->from[n]);
5076 	  tmp = fold_build2_loc (input_location, PLUS_EXPR,
5077 				 gfc_array_index_type,
5078 				 tmp, gfc_index_one_node);
5079 	  size = fold_build2_loc (input_location, MULT_EXPR,
5080 				  gfc_array_index_type, size, tmp);
5081 	}
5082 
5083       gfc_conv_descriptor_offset_set (&parmse->pre, parmse->expr,
5084 				      offset);
5085     }
5086 
5087   /* We want either the address for the data or the address of the descriptor,
5088      depending on the mode of passing array arguments.  */
5089   if (g77)
5090     parmse->expr = gfc_conv_descriptor_data_get (parmse->expr);
5091   else
5092     parmse->expr = gfc_build_addr_expr (NULL_TREE, parmse->expr);
5093 
5094   /* Basically make this into
5095 
5096      if (present)
5097        {
5098 	 if (contiguous)
5099 	   {
5100 	     pointer = a;
5101 	   }
5102 	 else
5103 	   {
5104 	     parmse->pre();
5105 	     pointer = parmse->expr;
5106 	   }
5107        }
5108      else
5109        pointer = NULL;
5110 
5111      foo (pointer);
5112      if (present && !contiguous)
5113 	   se->post();
5114 
5115      */
5116 
5117   if (pass_optional || check_contiguous)
5118     {
5119       tree type;
5120       stmtblock_t else_block;
5121       tree pre_stmts, post_stmts;
5122       tree pointer;
5123       tree else_stmt;
5124       tree present_var = NULL_TREE;
5125       tree cont_var = NULL_TREE;
5126       tree post_cond;
5127 
5128       type = TREE_TYPE (parmse->expr);
5129       pointer = gfc_create_var (type, "arg_ptr");
5130 
5131       if (check_contiguous)
5132 	{
5133 	  gfc_se cont_se, array_se;
5134 	  stmtblock_t if_block, else_block;
5135 	  tree if_stmt, else_stmt;
5136 	  mpz_t size;
5137 	  bool size_set;
5138 
5139 	  cont_var = gfc_create_var (boolean_type_node, "contiguous");
5140 
5141 	  /* If the size is known to be one at compile-time, set
5142 	     cont_var to true unconditionally.  This may look
5143 	     inelegant, but we're only doing this during
5144 	     optimization, so the statements will be optimized away,
5145 	     and this saves complexity here.  */
5146 
5147 	  size_set = gfc_array_size (expr, &size);
5148 	  if (size_set && mpz_cmp_ui (size, 1) == 0)
5149 	    {
5150 	      gfc_add_modify (&se->pre, cont_var,
5151 			      build_one_cst (boolean_type_node));
5152 	    }
5153 	  else
5154 	    {
5155 	      /* cont_var = is_contiguous (expr); .  */
5156 	      gfc_init_se (&cont_se, parmse);
5157 	      gfc_conv_is_contiguous_expr (&cont_se, expr);
5158 	      gfc_add_block_to_block (&se->pre, &(&cont_se)->pre);
5159 	      gfc_add_modify (&se->pre, cont_var, cont_se.expr);
5160 	      gfc_add_block_to_block (&se->pre, &(&cont_se)->post);
5161 	    }
5162 
5163 	  if (size_set)
5164 	    mpz_clear (size);
5165 
5166 	  /* arrayse->expr = descriptor of a.  */
5167 	  gfc_init_se (&array_se, se);
5168 	  gfc_conv_expr_descriptor (&array_se, expr);
5169 	  gfc_add_block_to_block (&se->pre, &(&array_se)->pre);
5170 	  gfc_add_block_to_block (&se->pre, &(&array_se)->post);
5171 
5172 	  /* if_stmt = { pointer = &a[0]; } .  */
5173 	  gfc_init_block (&if_block);
5174 	  tmp = gfc_conv_array_data (array_se.expr);
5175 	  tmp = fold_convert (type, tmp);
5176 	  gfc_add_modify (&if_block, pointer, tmp);
5177 	  if_stmt = gfc_finish_block (&if_block);
5178 
5179 	  /* else_stmt = { parmse->pre(); pointer = parmse->expr; } .  */
5180 	  gfc_init_block (&else_block);
5181 	  gfc_add_block_to_block (&else_block, &parmse->pre);
5182 	  gfc_add_modify (&else_block, pointer, parmse->expr);
5183 	  else_stmt = gfc_finish_block (&else_block);
5184 
5185 	  /* And put the above into an if statement.  */
5186 	  pre_stmts = fold_build3_loc (input_location, COND_EXPR, void_type_node,
5187 				       gfc_likely (cont_var,
5188 						   PRED_FORTRAN_CONTIGUOUS),
5189 				       if_stmt, else_stmt);
5190 	}
5191       else
5192 	{
5193 	  /* pointer = pramse->expr;  .  */
5194 	  gfc_add_modify (&parmse->pre, pointer, parmse->expr);
5195 	  pre_stmts = gfc_finish_block (&parmse->pre);
5196 	}
5197 
5198       if (pass_optional)
5199 	{
5200 	  present_var = gfc_create_var (boolean_type_node, "present");
5201 
5202 	  /* present_var = present(sym); .  */
5203 	  tmp = gfc_conv_expr_present (sym);
5204 	  tmp = fold_convert (boolean_type_node, tmp);
5205 	  gfc_add_modify (&se->pre, present_var, tmp);
5206 
5207 	  /* else_stmt = { pointer = NULL; } .  */
5208 	  gfc_init_block (&else_block);
5209 	  gfc_add_modify (&else_block, pointer, build_int_cst (type, 0));
5210 	  else_stmt = gfc_finish_block (&else_block);
5211 
5212 	  tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node,
5213 				 gfc_likely (present_var,
5214 					     PRED_FORTRAN_ABSENT_DUMMY),
5215 				 pre_stmts, else_stmt);
5216 	  gfc_add_expr_to_block (&se->pre, tmp);
5217 	}
5218       else
5219 	gfc_add_expr_to_block (&se->pre, pre_stmts);
5220 
5221       post_stmts = gfc_finish_block (&parmse->post);
5222 
5223       /* Put together the post stuff, plus the optional
5224 	 deallocation.  */
5225       if (check_contiguous)
5226 	{
5227 	  /* !cont_var.  */
5228 	  tmp = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
5229 				 cont_var,
5230 				 build_zero_cst (boolean_type_node));
5231 	  tmp = gfc_unlikely (tmp, PRED_FORTRAN_CONTIGUOUS);
5232 
5233 	  if (pass_optional)
5234 	    {
5235 	      tree present_likely = gfc_likely (present_var,
5236 						PRED_FORTRAN_ABSENT_DUMMY);
5237 	      post_cond = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
5238 					   boolean_type_node, present_likely,
5239 					   tmp);
5240 	    }
5241 	  else
5242 	    post_cond = tmp;
5243 	}
5244       else
5245 	{
5246 	  gcc_assert (pass_optional);
5247 	  post_cond = present_var;
5248 	}
5249 
5250       tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, post_cond,
5251 			     post_stmts, build_empty_stmt (input_location));
5252       gfc_add_expr_to_block (&se->post, tmp);
5253       se->expr = pointer;
5254     }
5255 
5256   return;
5257 }
5258 
5259 
5260 /* Generate the code for argument list functions.  */
5261 
5262 static void
5263 conv_arglist_function (gfc_se *se, gfc_expr *expr, const char *name)
5264 {
5265   /* Pass by value for g77 %VAL(arg), pass the address
5266      indirectly for %LOC, else by reference.  Thus %REF
5267      is a "do-nothing" and %LOC is the same as an F95
5268      pointer.  */
5269   if (strcmp (name, "%VAL") == 0)
5270     gfc_conv_expr (se, expr);
5271   else if (strcmp (name, "%LOC") == 0)
5272     {
5273       gfc_conv_expr_reference (se, expr);
5274       se->expr = gfc_build_addr_expr (NULL, se->expr);
5275     }
5276   else if (strcmp (name, "%REF") == 0)
5277     gfc_conv_expr_reference (se, expr);
5278   else
5279     gfc_error ("Unknown argument list function at %L", &expr->where);
5280 }
5281 
5282 
5283 /* This function tells whether the middle-end representation of the expression
5284    E given as input may point to data otherwise accessible through a variable
5285    (sub-)reference.
5286    It is assumed that the only expressions that may alias are variables,
5287    and array constructors if ARRAY_MAY_ALIAS is true and some of its elements
5288    may alias.
5289    This function is used to decide whether freeing an expression's allocatable
5290    components is safe or should be avoided.
5291 
5292    If ARRAY_MAY_ALIAS is true, an array constructor may alias if some of
5293    its elements are copied from a variable.  This ARRAY_MAY_ALIAS trick
5294    is necessary because for array constructors, aliasing depends on how
5295    the array is used:
5296     - If E is an array constructor used as argument to an elemental procedure,
5297       the array, which is generated through shallow copy by the scalarizer,
5298       is used directly and can alias the expressions it was copied from.
5299     - If E is an array constructor used as argument to a non-elemental
5300       procedure,the scalarizer is used in gfc_conv_expr_descriptor to generate
5301       the array as in the previous case, but then that array is used
5302       to initialize a new descriptor through deep copy.  There is no alias
5303       possible in that case.
5304    Thus, the ARRAY_MAY_ALIAS flag is necessary to distinguish the two cases
5305    above.  */
5306 
5307 static bool
5308 expr_may_alias_variables (gfc_expr *e, bool array_may_alias)
5309 {
5310   gfc_constructor *c;
5311 
5312   if (e->expr_type == EXPR_VARIABLE)
5313     return true;
5314   else if (e->expr_type == EXPR_FUNCTION)
5315     {
5316       gfc_symbol *proc_ifc = gfc_get_proc_ifc_for_expr (e);
5317 
5318       if (proc_ifc->result != NULL
5319 	  && ((proc_ifc->result->ts.type == BT_CLASS
5320 	       && proc_ifc->result->ts.u.derived->attr.is_class
5321 	       && CLASS_DATA (proc_ifc->result)->attr.class_pointer)
5322 	      || proc_ifc->result->attr.pointer))
5323 	return true;
5324       else
5325 	return false;
5326     }
5327   else if (e->expr_type != EXPR_ARRAY || !array_may_alias)
5328     return false;
5329 
5330   for (c = gfc_constructor_first (e->value.constructor);
5331        c; c = gfc_constructor_next (c))
5332     if (c->expr
5333 	&& expr_may_alias_variables (c->expr, array_may_alias))
5334       return true;
5335 
5336   return false;
5337 }
5338 
5339 
5340 /* A helper function to set the dtype for unallocated or unassociated
5341    entities.  */
5342 
5343 static void
5344 set_dtype_for_unallocated (gfc_se *parmse, gfc_expr *e)
5345 {
5346   tree tmp;
5347   tree desc;
5348   tree cond;
5349   tree type;
5350   stmtblock_t block;
5351 
5352   /* TODO Figure out how to handle optional dummies.  */
5353   if (e && e->expr_type == EXPR_VARIABLE
5354       && e->symtree->n.sym->attr.optional)
5355     return;
5356 
5357   desc = parmse->expr;
5358   if (desc == NULL_TREE)
5359     return;
5360 
5361   if (POINTER_TYPE_P (TREE_TYPE (desc)))
5362     desc = build_fold_indirect_ref_loc (input_location, desc);
5363 
5364   if (!GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (desc)))
5365     return;
5366 
5367   gfc_init_block (&block);
5368   tmp = gfc_conv_descriptor_data_get (desc);
5369   cond = fold_build2_loc (input_location, EQ_EXPR,
5370 			  logical_type_node, tmp,
5371 			  build_int_cst (TREE_TYPE (tmp), 0));
5372   tmp = gfc_conv_descriptor_dtype (desc);
5373   type = gfc_get_element_type (TREE_TYPE (desc));
5374   tmp = fold_build2_loc (input_location, MODIFY_EXPR,
5375 			 TREE_TYPE (tmp), tmp,
5376 			 gfc_get_dtype_rank_type (e->rank, type));
5377   gfc_add_expr_to_block (&block, tmp);
5378   cond = build3_v (COND_EXPR, cond,
5379 		   gfc_finish_block (&block),
5380 		   build_empty_stmt (input_location));
5381   gfc_add_expr_to_block (&parmse->pre, cond);
5382 }
5383 
5384 
5385 
5386 /* Provide an interface between gfortran array descriptors and the F2018:18.4
5387    ISO_Fortran_binding array descriptors. */
5388 
5389 static void
5390 gfc_conv_gfc_desc_to_cfi_desc (gfc_se *parmse, gfc_expr *e, gfc_symbol *fsym)
5391 {
5392   tree tmp;
5393   tree cfi_desc_ptr;
5394   tree gfc_desc_ptr;
5395   tree type;
5396   tree cond;
5397   tree desc_attr;
5398   int attribute;
5399   int cfi_attribute;
5400   symbol_attribute attr = gfc_expr_attr (e);
5401 
5402   /* If this is a full array or a scalar, the allocatable and pointer
5403      attributes can be passed. Otherwise it is 'CFI_attribute_other'*/
5404   attribute = 2;
5405   if (!e->rank || gfc_get_full_arrayspec_from_expr (e))
5406     {
5407       if (attr.pointer)
5408 	attribute = 0;
5409       else if (attr.allocatable)
5410 	attribute = 1;
5411     }
5412 
5413   /* If the formal argument is assumed shape and neither a pointer nor
5414      allocatable, it is unconditionally CFI_attribute_other.  */
5415   if (fsym->as->type == AS_ASSUMED_SHAPE
5416       && !fsym->attr.pointer && !fsym->attr.allocatable)
5417    cfi_attribute = 2;
5418   else
5419    cfi_attribute = attribute;
5420 
5421   if (e->rank != 0)
5422     {
5423       parmse->force_no_tmp = 1;
5424       if (fsym->attr.contiguous
5425 	  && !gfc_is_simply_contiguous (e, false, true))
5426 	gfc_conv_subref_array_arg (parmse, e, false, fsym->attr.intent,
5427 				   fsym->attr.pointer);
5428       else
5429 	gfc_conv_expr_descriptor (parmse, e);
5430 
5431       if (POINTER_TYPE_P (TREE_TYPE (parmse->expr)))
5432 	parmse->expr = build_fold_indirect_ref_loc (input_location,
5433 						    parmse->expr);
5434       bool is_artificial = (INDIRECT_REF_P (parmse->expr)
5435 			    ? DECL_ARTIFICIAL (TREE_OPERAND (parmse->expr, 0))
5436 			    : DECL_ARTIFICIAL (parmse->expr));
5437 
5438       /* Unallocated allocatable arrays and unassociated pointer arrays
5439 	 need their dtype setting if they are argument associated with
5440 	 assumed rank dummies.  */
5441       if (fsym && fsym->as
5442 	  && (gfc_expr_attr (e).pointer
5443 	      || gfc_expr_attr (e).allocatable))
5444 	set_dtype_for_unallocated (parmse, e);
5445 
5446       /* All the temporary descriptors are marked as DECL_ARTIFICIAL. If
5447 	 the expression type is different from the descriptor type, then
5448 	 the offset must be found (eg. to a component ref or substring)
5449 	 and the dtype updated.  Assumed type entities are only allowed
5450 	 to be dummies in Fortran. They therefore lack the decl specific
5451 	 appendiges and so must be treated differently from other fortran
5452 	 entities passed to CFI descriptors in the interface decl.  */
5453       type = e->ts.type != BT_ASSUMED ? gfc_typenode_for_spec (&e->ts) :
5454 					NULL_TREE;
5455 
5456       if (type && is_artificial
5457 	  && type != gfc_get_element_type (TREE_TYPE (parmse->expr)))
5458 	{
5459 	  /* Obtain the offset to the data.  */
5460 	  gfc_get_dataptr_offset (&parmse->pre, parmse->expr, parmse->expr,
5461 				  gfc_index_zero_node, true, e);
5462 
5463 	  /* Update the dtype.  */
5464 	  gfc_add_modify (&parmse->pre,
5465 			  gfc_conv_descriptor_dtype (parmse->expr),
5466 			  gfc_get_dtype_rank_type (e->rank, type));
5467 	}
5468       else if (type == NULL_TREE
5469 	       || (!is_subref_array (e) && !is_artificial))
5470 	{
5471 	  /* Make sure that the span is set for expressions where it
5472 	     might not have been done already.  */
5473 	  tmp = gfc_conv_descriptor_elem_len (parmse->expr);
5474 	  tmp = fold_convert (gfc_array_index_type, tmp);
5475 	  gfc_conv_descriptor_span_set (&parmse->pre, parmse->expr, tmp);
5476 	}
5477     }
5478   else
5479     {
5480       gfc_conv_expr (parmse, e);
5481 
5482       if (POINTER_TYPE_P (TREE_TYPE (parmse->expr)))
5483 	parmse->expr = build_fold_indirect_ref_loc (input_location,
5484 						    parmse->expr);
5485 
5486       parmse->expr = gfc_conv_scalar_to_descriptor (parmse,
5487 						    parmse->expr, attr);
5488     }
5489 
5490   /* Set the CFI attribute field through a temporary value for the
5491      gfc attribute.  */
5492   desc_attr = gfc_conv_descriptor_attribute (parmse->expr);
5493   tmp = fold_build2_loc (input_location, MODIFY_EXPR,
5494 			 void_type_node, desc_attr,
5495 			 build_int_cst (TREE_TYPE (desc_attr), cfi_attribute));
5496   gfc_add_expr_to_block (&parmse->pre, tmp);
5497 
5498   /* Now pass the gfc_descriptor by reference.  */
5499   parmse->expr = gfc_build_addr_expr (NULL_TREE, parmse->expr);
5500 
5501   /* Variables to point to the gfc and CFI descriptors; cfi = NULL implies
5502      that the CFI descriptor is allocated by the gfor_fndecl_gfc_to_cfi call.  */
5503   gfc_desc_ptr = parmse->expr;
5504   cfi_desc_ptr = gfc_create_var (pvoid_type_node, "cfi");
5505   gfc_add_modify (&parmse->pre, cfi_desc_ptr, null_pointer_node);
5506 
5507   /* Allocate the CFI descriptor itself and fill the fields.  */
5508   tmp = gfc_build_addr_expr (NULL_TREE, cfi_desc_ptr);
5509   tmp = build_call_expr_loc (input_location,
5510 			     gfor_fndecl_gfc_to_cfi, 2, tmp, gfc_desc_ptr);
5511   gfc_add_expr_to_block (&parmse->pre, tmp);
5512 
5513   /* Now set the gfc descriptor attribute.  */
5514   tmp = fold_build2_loc (input_location, MODIFY_EXPR,
5515 			 void_type_node, desc_attr,
5516 			 build_int_cst (TREE_TYPE (desc_attr), attribute));
5517   gfc_add_expr_to_block (&parmse->pre, tmp);
5518 
5519   /* The CFI descriptor is passed to the bind_C procedure.  */
5520   parmse->expr = cfi_desc_ptr;
5521 
5522   /* Free the CFI descriptor.  */
5523   tmp = gfc_call_free (cfi_desc_ptr);
5524   gfc_prepend_expr_to_block (&parmse->post, tmp);
5525 
5526   /* Transfer values back to gfc descriptor.  */
5527   tmp = gfc_build_addr_expr (NULL_TREE, parmse->expr);
5528   tmp = build_call_expr_loc (input_location,
5529 			     gfor_fndecl_cfi_to_gfc, 2, gfc_desc_ptr, tmp);
5530   gfc_prepend_expr_to_block (&parmse->post, tmp);
5531 
5532   /* Deal with an optional dummy being passed to an optional formal arg
5533      by finishing the pre and post blocks and making their execution
5534      conditional on the dummy being present.  */
5535   if (fsym->attr.optional && e->expr_type == EXPR_VARIABLE
5536       && e->symtree->n.sym->attr.optional)
5537     {
5538       cond = gfc_conv_expr_present (e->symtree->n.sym);
5539       tmp = fold_build2 (MODIFY_EXPR, void_type_node,
5540 			 cfi_desc_ptr,
5541 			 build_int_cst (pvoid_type_node, 0));
5542       tmp = build3_v (COND_EXPR, cond,
5543 		      gfc_finish_block (&parmse->pre), tmp);
5544       gfc_add_expr_to_block (&parmse->pre, tmp);
5545       tmp = build3_v (COND_EXPR, cond,
5546 		      gfc_finish_block (&parmse->post),
5547 		      build_empty_stmt (input_location));
5548       gfc_add_expr_to_block (&parmse->post, tmp);
5549     }
5550 }
5551 
5552 
5553 /* Generate code for a procedure call.  Note can return se->post != NULL.
5554    If se->direct_byref is set then se->expr contains the return parameter.
5555    Return nonzero, if the call has alternate specifiers.
5556    'expr' is only needed for procedure pointer components.  */
5557 
5558 int
5559 gfc_conv_procedure_call (gfc_se * se, gfc_symbol * sym,
5560 			 gfc_actual_arglist * args, gfc_expr * expr,
5561 			 vec<tree, va_gc> *append_args)
5562 {
5563   gfc_interface_mapping mapping;
5564   vec<tree, va_gc> *arglist;
5565   vec<tree, va_gc> *retargs;
5566   tree tmp;
5567   tree fntype;
5568   gfc_se parmse;
5569   gfc_array_info *info;
5570   int byref;
5571   int parm_kind;
5572   tree type;
5573   tree var;
5574   tree len;
5575   tree base_object;
5576   vec<tree, va_gc> *stringargs;
5577   vec<tree, va_gc> *optionalargs;
5578   tree result = NULL;
5579   gfc_formal_arglist *formal;
5580   gfc_actual_arglist *arg;
5581   int has_alternate_specifier = 0;
5582   bool need_interface_mapping;
5583   bool callee_alloc;
5584   bool ulim_copy;
5585   gfc_typespec ts;
5586   gfc_charlen cl;
5587   gfc_expr *e;
5588   gfc_symbol *fsym;
5589   stmtblock_t post;
5590   enum {MISSING = 0, ELEMENTAL, SCALAR, SCALAR_POINTER, ARRAY};
5591   gfc_component *comp = NULL;
5592   int arglen;
5593   unsigned int argc;
5594 
5595   arglist = NULL;
5596   retargs = NULL;
5597   stringargs = NULL;
5598   optionalargs = NULL;
5599   var = NULL_TREE;
5600   len = NULL_TREE;
5601   gfc_clear_ts (&ts);
5602 
5603   comp = gfc_get_proc_ptr_comp (expr);
5604 
5605   bool elemental_proc = (comp
5606 			 && comp->ts.interface
5607 			 && comp->ts.interface->attr.elemental)
5608 			|| (comp && comp->attr.elemental)
5609 			|| sym->attr.elemental;
5610 
5611   if (se->ss != NULL)
5612     {
5613       if (!elemental_proc)
5614 	{
5615 	  gcc_assert (se->ss->info->type == GFC_SS_FUNCTION);
5616 	  if (se->ss->info->useflags)
5617 	    {
5618 	      gcc_assert ((!comp && gfc_return_by_reference (sym)
5619 			   && sym->result->attr.dimension)
5620 			  || (comp && comp->attr.dimension)
5621 			  || gfc_is_class_array_function (expr));
5622 	      gcc_assert (se->loop != NULL);
5623 	      /* Access the previously obtained result.  */
5624 	      gfc_conv_tmp_array_ref (se);
5625 	      return 0;
5626 	    }
5627 	}
5628       info = &se->ss->info->data.array;
5629     }
5630   else
5631     info = NULL;
5632 
5633   gfc_init_block (&post);
5634   gfc_init_interface_mapping (&mapping);
5635   if (!comp)
5636     {
5637       formal = gfc_sym_get_dummy_args (sym);
5638       need_interface_mapping = sym->attr.dimension ||
5639 			       (sym->ts.type == BT_CHARACTER
5640 				&& sym->ts.u.cl->length
5641 				&& sym->ts.u.cl->length->expr_type
5642 				   != EXPR_CONSTANT);
5643     }
5644   else
5645     {
5646       formal = comp->ts.interface ? comp->ts.interface->formal : NULL;
5647       need_interface_mapping = comp->attr.dimension ||
5648 			       (comp->ts.type == BT_CHARACTER
5649 				&& comp->ts.u.cl->length
5650 				&& comp->ts.u.cl->length->expr_type
5651 				   != EXPR_CONSTANT);
5652     }
5653 
5654   base_object = NULL_TREE;
5655   /* For _vprt->_copy () routines no formal symbol is present.  Nevertheless
5656      is the third and fourth argument to such a function call a value
5657      denoting the number of elements to copy (i.e., most of the time the
5658      length of a deferred length string).  */
5659   ulim_copy = (formal == NULL)
5660 	       && UNLIMITED_POLY (sym)
5661 	       && comp && (strcmp ("_copy", comp->name) == 0);
5662 
5663   /* Evaluate the arguments.  */
5664   for (arg = args, argc = 0; arg != NULL;
5665        arg = arg->next, formal = formal ? formal->next : NULL, ++argc)
5666     {
5667       bool finalized = false;
5668       bool non_unity_length_string = false;
5669 
5670       e = arg->expr;
5671       fsym = formal ? formal->sym : NULL;
5672       parm_kind = MISSING;
5673 
5674       if (fsym && fsym->ts.type == BT_CHARACTER && fsym->ts.u.cl
5675 	  && (!fsym->ts.u.cl->length
5676 	      || fsym->ts.u.cl->length->expr_type != EXPR_CONSTANT
5677 	      || mpz_cmp_si (fsym->ts.u.cl->length->value.integer, 1) != 0))
5678 	non_unity_length_string = true;
5679 
5680       /* If the procedure requires an explicit interface, the actual
5681 	 argument is passed according to the corresponding formal
5682 	 argument.  If the corresponding formal argument is a POINTER,
5683 	 ALLOCATABLE or assumed shape, we do not use g77's calling
5684 	 convention, and pass the address of the array descriptor
5685 	 instead.  Otherwise we use g77's calling convention, in other words
5686 	 pass the array data pointer without descriptor.  */
5687       bool nodesc_arg = fsym != NULL
5688 			&& !(fsym->attr.pointer || fsym->attr.allocatable)
5689 			&& fsym->as
5690 			&& fsym->as->type != AS_ASSUMED_SHAPE
5691 			&& fsym->as->type != AS_ASSUMED_RANK;
5692       if (comp)
5693 	nodesc_arg = nodesc_arg || !comp->attr.always_explicit;
5694       else
5695 	nodesc_arg = nodesc_arg || !sym->attr.always_explicit;
5696 
5697       /* Class array expressions are sometimes coming completely unadorned
5698 	 with either arrayspec or _data component.  Correct that here.
5699 	 OOP-TODO: Move this to the frontend.  */
5700       if (e && e->expr_type == EXPR_VARIABLE
5701 	    && !e->ref
5702 	    && e->ts.type == BT_CLASS
5703 	    && (CLASS_DATA (e)->attr.codimension
5704 		|| CLASS_DATA (e)->attr.dimension))
5705 	{
5706 	  gfc_typespec temp_ts = e->ts;
5707 	  gfc_add_class_array_ref (e);
5708 	  e->ts = temp_ts;
5709 	}
5710 
5711       if (e == NULL)
5712 	{
5713 	  if (se->ignore_optional)
5714 	    {
5715 	      /* Some intrinsics have already been resolved to the correct
5716 	         parameters.  */
5717 	      continue;
5718 	    }
5719 	  else if (arg->label)
5720 	    {
5721 	      has_alternate_specifier = 1;
5722 	      continue;
5723 	    }
5724 	  else
5725 	    {
5726 	      gfc_init_se (&parmse, NULL);
5727 
5728 	      /* For scalar arguments with VALUE attribute which are passed by
5729 		 value, pass "0" and a hidden argument gives the optional
5730 		 status.  */
5731 	      if (fsym && fsym->attr.optional && fsym->attr.value
5732 		  && !fsym->attr.dimension && fsym->ts.type != BT_CHARACTER
5733 		  && fsym->ts.type != BT_CLASS && fsym->ts.type != BT_DERIVED)
5734 		{
5735 		  parmse.expr = fold_convert (gfc_sym_type (fsym),
5736 					      integer_zero_node);
5737 		  vec_safe_push (optionalargs, boolean_false_node);
5738 		}
5739 	      else
5740 		{
5741 		  /* Pass a NULL pointer for an absent arg.  */
5742 		  parmse.expr = null_pointer_node;
5743 		  if (arg->missing_arg_type == BT_CHARACTER)
5744 		    parmse.string_length = build_int_cst (gfc_charlen_type_node,
5745 							  0);
5746 		}
5747 	    }
5748 	}
5749       else if (arg->expr->expr_type == EXPR_NULL
5750 	       && fsym && !fsym->attr.pointer
5751 	       && (fsym->ts.type != BT_CLASS
5752 		   || !CLASS_DATA (fsym)->attr.class_pointer))
5753 	{
5754 	  /* Pass a NULL pointer to denote an absent arg.  */
5755 	  gcc_assert (fsym->attr.optional && !fsym->attr.allocatable
5756 		      && (fsym->ts.type != BT_CLASS
5757 			  || !CLASS_DATA (fsym)->attr.allocatable));
5758 	  gfc_init_se (&parmse, NULL);
5759 	  parmse.expr = null_pointer_node;
5760 	  if (arg->missing_arg_type == BT_CHARACTER)
5761 	    parmse.string_length = build_int_cst (gfc_charlen_type_node, 0);
5762 	}
5763       else if (fsym && fsym->ts.type == BT_CLASS
5764 		 && e->ts.type == BT_DERIVED)
5765 	{
5766 	  /* The derived type needs to be converted to a temporary
5767 	     CLASS object.  */
5768 	  gfc_init_se (&parmse, se);
5769 	  gfc_conv_derived_to_class (&parmse, e, fsym->ts, NULL,
5770 				     fsym->attr.optional
5771 				     && e->expr_type == EXPR_VARIABLE
5772 				     && e->symtree->n.sym->attr.optional,
5773 				     CLASS_DATA (fsym)->attr.class_pointer
5774 				     || CLASS_DATA (fsym)->attr.allocatable);
5775 	}
5776       else if (UNLIMITED_POLY (fsym) && e->ts.type != BT_CLASS
5777 	       && e->ts.type != BT_PROCEDURE
5778 	       && (gfc_expr_attr (e).flavor != FL_PROCEDURE
5779 		   || gfc_expr_attr (e).proc != PROC_UNKNOWN))
5780 	{
5781 	  /* The intrinsic type needs to be converted to a temporary
5782 	     CLASS object for the unlimited polymorphic formal.  */
5783 	  gfc_find_vtab (&e->ts);
5784 	  gfc_init_se (&parmse, se);
5785 	  gfc_conv_intrinsic_to_class (&parmse, e, fsym->ts);
5786 
5787 	}
5788       else if (se->ss && se->ss->info->useflags)
5789 	{
5790 	  gfc_ss *ss;
5791 
5792 	  ss = se->ss;
5793 
5794 	  /* An elemental function inside a scalarized loop.  */
5795 	  gfc_init_se (&parmse, se);
5796 	  parm_kind = ELEMENTAL;
5797 
5798 	  /* When no fsym is present, ulim_copy is set and this is a third or
5799 	     fourth argument, use call-by-value instead of by reference to
5800 	     hand the length properties to the copy routine (i.e., most of the
5801 	     time this will be a call to a __copy_character_* routine where the
5802 	     third and fourth arguments are the lengths of a deferred length
5803 	     char array).  */
5804 	  if ((fsym && fsym->attr.value)
5805 	      || (ulim_copy && (argc == 2 || argc == 3)))
5806 	    gfc_conv_expr (&parmse, e);
5807 	  else
5808 	    gfc_conv_expr_reference (&parmse, e);
5809 
5810 	  if (e->ts.type == BT_CHARACTER && !e->rank
5811 	      && e->expr_type == EXPR_FUNCTION)
5812 	    parmse.expr = build_fold_indirect_ref_loc (input_location,
5813 						       parmse.expr);
5814 
5815 	  if (fsym && fsym->ts.type == BT_DERIVED
5816 	      && gfc_is_class_container_ref (e))
5817 	    {
5818 	      parmse.expr = gfc_class_data_get (parmse.expr);
5819 
5820 	      if (fsym->attr.optional && e->expr_type == EXPR_VARIABLE
5821 		  && e->symtree->n.sym->attr.optional)
5822 		{
5823 		  tree cond = gfc_conv_expr_present (e->symtree->n.sym);
5824 		  parmse.expr = build3_loc (input_location, COND_EXPR,
5825 					TREE_TYPE (parmse.expr),
5826 					cond, parmse.expr,
5827 					fold_convert (TREE_TYPE (parmse.expr),
5828 						      null_pointer_node));
5829 		}
5830 	    }
5831 
5832 	  /* If we are passing an absent array as optional dummy to an
5833 	     elemental procedure, make sure that we pass NULL when the data
5834 	     pointer is NULL.  We need this extra conditional because of
5835 	     scalarization which passes arrays elements to the procedure,
5836 	     ignoring the fact that the array can be absent/unallocated/...  */
5837 	  if (ss->info->can_be_null_ref && ss->info->type != GFC_SS_REFERENCE)
5838 	    {
5839 	      tree descriptor_data;
5840 
5841 	      descriptor_data = ss->info->data.array.data;
5842 	      tmp = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
5843 				     descriptor_data,
5844 				     fold_convert (TREE_TYPE (descriptor_data),
5845 						   null_pointer_node));
5846 	      parmse.expr
5847 		= fold_build3_loc (input_location, COND_EXPR,
5848 				   TREE_TYPE (parmse.expr),
5849 				   gfc_unlikely (tmp, PRED_FORTRAN_ABSENT_DUMMY),
5850 				   fold_convert (TREE_TYPE (parmse.expr),
5851 						 null_pointer_node),
5852 				   parmse.expr);
5853 	    }
5854 
5855 	  /* The scalarizer does not repackage the reference to a class
5856 	     array - instead it returns a pointer to the data element.  */
5857 	  if (fsym && fsym->ts.type == BT_CLASS && e->ts.type == BT_CLASS)
5858 	    gfc_conv_class_to_class (&parmse, e, fsym->ts, true,
5859 				     fsym->attr.intent != INTENT_IN
5860 				     && (CLASS_DATA (fsym)->attr.class_pointer
5861 					 || CLASS_DATA (fsym)->attr.allocatable),
5862 				     fsym->attr.optional
5863 				     && e->expr_type == EXPR_VARIABLE
5864 				     && e->symtree->n.sym->attr.optional,
5865 				     CLASS_DATA (fsym)->attr.class_pointer
5866 				     || CLASS_DATA (fsym)->attr.allocatable);
5867 	}
5868       else
5869 	{
5870 	  bool scalar;
5871 	  gfc_ss *argss;
5872 
5873 	  gfc_init_se (&parmse, NULL);
5874 
5875 	  /* Check whether the expression is a scalar or not; we cannot use
5876 	     e->rank as it can be nonzero for functions arguments.  */
5877 	  argss = gfc_walk_expr (e);
5878 	  scalar = argss == gfc_ss_terminator;
5879 	  if (!scalar)
5880 	    gfc_free_ss_chain (argss);
5881 
5882 	  /* Special handling for passing scalar polymorphic coarrays;
5883 	     otherwise one passes "class->_data.data" instead of "&class".  */
5884 	  if (e->rank == 0 && e->ts.type == BT_CLASS
5885 	      && fsym && fsym->ts.type == BT_CLASS
5886 	      && CLASS_DATA (fsym)->attr.codimension
5887 	      && !CLASS_DATA (fsym)->attr.dimension)
5888 	    {
5889 	      gfc_add_class_array_ref (e);
5890               parmse.want_coarray = 1;
5891 	      scalar = false;
5892 	    }
5893 
5894 	  /* A scalar or transformational function.  */
5895 	  if (scalar)
5896 	    {
5897 	      if (e->expr_type == EXPR_VARIABLE
5898 		    && e->symtree->n.sym->attr.cray_pointee
5899 		    && fsym && fsym->attr.flavor == FL_PROCEDURE)
5900 		{
5901 		    /* The Cray pointer needs to be converted to a pointer to
5902 		       a type given by the expression.  */
5903 		    gfc_conv_expr (&parmse, e);
5904 		    type = build_pointer_type (TREE_TYPE (parmse.expr));
5905 		    tmp = gfc_get_symbol_decl (e->symtree->n.sym->cp_pointer);
5906 		    parmse.expr = convert (type, tmp);
5907 		}
5908 
5909 	      else if (sym->attr.is_bind_c && e
5910 		       && (is_CFI_desc (fsym, NULL)
5911 			   || non_unity_length_string))
5912 		/* Implement F2018, C.12.6.1: paragraph (2).  */
5913 		gfc_conv_gfc_desc_to_cfi_desc (&parmse, e, fsym);
5914 
5915 	      else if (fsym && fsym->attr.value)
5916 		{
5917 		  if (fsym->ts.type == BT_CHARACTER
5918 		      && fsym->ts.is_c_interop
5919 		      && fsym->ns->proc_name != NULL
5920 		      && fsym->ns->proc_name->attr.is_bind_c)
5921 		    {
5922 		      parmse.expr = NULL;
5923 		      gfc_conv_scalar_char_value (fsym, &parmse, &e);
5924 		      if (parmse.expr == NULL)
5925 			gfc_conv_expr (&parmse, e);
5926 		    }
5927 		  else
5928 		    {
5929 		    gfc_conv_expr (&parmse, e);
5930 		    if (fsym->attr.optional
5931 			&& fsym->ts.type != BT_CLASS
5932 			&& fsym->ts.type != BT_DERIVED)
5933 		      {
5934 			if (e->expr_type != EXPR_VARIABLE
5935 			    || !e->symtree->n.sym->attr.optional
5936 			    || e->ref != NULL)
5937 			  vec_safe_push (optionalargs, boolean_true_node);
5938 			else
5939 			  {
5940 			    tmp = gfc_conv_expr_present (e->symtree->n.sym);
5941 			    if (!e->symtree->n.sym->attr.value)
5942 			      parmse.expr
5943 				= fold_build3_loc (input_location, COND_EXPR,
5944 					TREE_TYPE (parmse.expr),
5945 					tmp, parmse.expr,
5946 					fold_convert (TREE_TYPE (parmse.expr),
5947 						      integer_zero_node));
5948 
5949 			    vec_safe_push (optionalargs,
5950 					   fold_convert (boolean_type_node,
5951 							 tmp));
5952 			  }
5953 		      }
5954 		    }
5955 		}
5956 
5957 	      else if (arg->name && arg->name[0] == '%')
5958 		/* Argument list functions %VAL, %LOC and %REF are signalled
5959 		   through arg->name.  */
5960 		conv_arglist_function (&parmse, arg->expr, arg->name);
5961 	      else if ((e->expr_type == EXPR_FUNCTION)
5962 			&& ((e->value.function.esym
5963 			     && e->value.function.esym->result->attr.pointer)
5964 			    || (!e->value.function.esym
5965 				&& e->symtree->n.sym->attr.pointer))
5966 			&& fsym && fsym->attr.target)
5967 		/* Make sure the function only gets called once.  */
5968 		gfc_conv_expr_reference (&parmse, e, false);
5969 	      else if (e->expr_type == EXPR_FUNCTION
5970 		       && e->symtree->n.sym->result
5971 		       && e->symtree->n.sym->result != e->symtree->n.sym
5972 		       && e->symtree->n.sym->result->attr.proc_pointer)
5973 		{
5974 		  /* Functions returning procedure pointers.  */
5975 		  gfc_conv_expr (&parmse, e);
5976 		  if (fsym && fsym->attr.proc_pointer)
5977 		    parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
5978 		}
5979 
5980 	      else
5981 		{
5982 		  if (e->ts.type == BT_CLASS && fsym
5983 		      && fsym->ts.type == BT_CLASS
5984 		      && (!CLASS_DATA (fsym)->as
5985 			  || CLASS_DATA (fsym)->as->type != AS_ASSUMED_RANK)
5986 		      && CLASS_DATA (e)->attr.codimension)
5987 		    {
5988 		      gcc_assert (!CLASS_DATA (fsym)->attr.codimension);
5989 		      gcc_assert (!CLASS_DATA (fsym)->as);
5990 		      gfc_add_class_array_ref (e);
5991 		      parmse.want_coarray = 1;
5992 		      gfc_conv_expr_reference (&parmse, e);
5993 		      class_scalar_coarray_to_class (&parmse, e, fsym->ts,
5994 				     fsym->attr.optional
5995 				     && e->expr_type == EXPR_VARIABLE);
5996 		    }
5997 		  else if (e->ts.type == BT_CLASS && fsym
5998 			   && fsym->ts.type == BT_CLASS
5999 			   && !CLASS_DATA (fsym)->as
6000 			   && !CLASS_DATA (e)->as
6001 			   && strcmp (fsym->ts.u.derived->name,
6002 				      e->ts.u.derived->name))
6003 		    {
6004 		      type = gfc_typenode_for_spec (&fsym->ts);
6005 		      var = gfc_create_var (type, fsym->name);
6006 		      gfc_conv_expr (&parmse, e);
6007 		      if (fsym->attr.optional
6008 			  && e->expr_type == EXPR_VARIABLE
6009 			  && e->symtree->n.sym->attr.optional)
6010 			{
6011 			  stmtblock_t block;
6012 			  tree cond;
6013 			  tmp = gfc_build_addr_expr (NULL_TREE, parmse.expr);
6014 			  cond = fold_build2_loc (input_location, NE_EXPR,
6015 						  logical_type_node, tmp,
6016 						  fold_convert (TREE_TYPE (tmp),
6017 							    null_pointer_node));
6018 			  gfc_start_block (&block);
6019 			  gfc_add_modify (&block, var,
6020 					  fold_build1_loc (input_location,
6021 							   VIEW_CONVERT_EXPR,
6022 							   type, parmse.expr));
6023 			  gfc_add_expr_to_block (&parmse.pre,
6024 				 fold_build3_loc (input_location,
6025 					 COND_EXPR, void_type_node,
6026 					 cond, gfc_finish_block (&block),
6027 					 build_empty_stmt (input_location)));
6028 			  parmse.expr = gfc_build_addr_expr (NULL_TREE, var);
6029 			  parmse.expr = build3_loc (input_location, COND_EXPR,
6030 					 TREE_TYPE (parmse.expr),
6031 					 cond, parmse.expr,
6032 					 fold_convert (TREE_TYPE (parmse.expr),
6033 						       null_pointer_node));
6034 			}
6035 		      else
6036 			{
6037 			  /* Since the internal representation of unlimited
6038 			     polymorphic expressions includes an extra field
6039 			     that other class objects do not, a cast to the
6040 			     formal type does not work.  */
6041 			  if (!UNLIMITED_POLY (e) && UNLIMITED_POLY (fsym))
6042 			    {
6043 			      tree efield;
6044 
6045 			      /* Set the _data field.  */
6046 			      tmp = gfc_class_data_get (var);
6047 			      efield = fold_convert (TREE_TYPE (tmp),
6048 					gfc_class_data_get (parmse.expr));
6049 			      gfc_add_modify (&parmse.pre, tmp, efield);
6050 
6051 			      /* Set the _vptr field.  */
6052 			      tmp = gfc_class_vptr_get (var);
6053 			      efield = fold_convert (TREE_TYPE (tmp),
6054 					gfc_class_vptr_get (parmse.expr));
6055 			      gfc_add_modify (&parmse.pre, tmp, efield);
6056 
6057 			      /* Set the _len field.  */
6058 			      tmp = gfc_class_len_get (var);
6059 			      gfc_add_modify (&parmse.pre, tmp,
6060 					      build_int_cst (TREE_TYPE (tmp), 0));
6061 			    }
6062 			  else
6063 			    {
6064 			      tmp = fold_build1_loc (input_location,
6065 						     VIEW_CONVERT_EXPR,
6066 						     type, parmse.expr);
6067 			      gfc_add_modify (&parmse.pre, var, tmp);
6068 					      ;
6069 			    }
6070 			  parmse.expr = gfc_build_addr_expr (NULL_TREE, var);
6071 			}
6072 		    }
6073 		  else
6074 		    {
6075 		      bool add_clobber;
6076 		      add_clobber = fsym && fsym->attr.intent == INTENT_OUT
6077 			&& !fsym->attr.allocatable && !fsym->attr.pointer
6078 			&& e->symtree && e->symtree->n.sym
6079 			&& !e->symtree->n.sym->attr.dimension
6080 			&& !e->symtree->n.sym->attr.pointer
6081 			&& !e->symtree->n.sym->attr.allocatable
6082 			/* See PR 41453.  */
6083 			&& !e->symtree->n.sym->attr.dummy
6084 			/* FIXME - PR 87395 and PR 41453  */
6085 			&& e->symtree->n.sym->attr.save == SAVE_NONE
6086 			&& !e->symtree->n.sym->attr.associate_var
6087 			&& e->ts.type != BT_CHARACTER && e->ts.type != BT_DERIVED
6088 			&& e->ts.type != BT_CLASS && !sym->attr.elemental;
6089 
6090 		      gfc_conv_expr_reference (&parmse, e, add_clobber);
6091 		    }
6092 		  /* Catch base objects that are not variables.  */
6093 		  if (e->ts.type == BT_CLASS
6094 			&& e->expr_type != EXPR_VARIABLE
6095 			&& expr && e == expr->base_expr)
6096 		    base_object = build_fold_indirect_ref_loc (input_location,
6097 							       parmse.expr);
6098 
6099 		  /* A class array element needs converting back to be a
6100 		     class object, if the formal argument is a class object.  */
6101 		  if (fsym && fsym->ts.type == BT_CLASS
6102 			&& e->ts.type == BT_CLASS
6103 			&& ((CLASS_DATA (fsym)->as
6104 			     && CLASS_DATA (fsym)->as->type == AS_ASSUMED_RANK)
6105 			    || CLASS_DATA (e)->attr.dimension))
6106 		    gfc_conv_class_to_class (&parmse, e, fsym->ts, false,
6107 				     fsym->attr.intent != INTENT_IN
6108 				     && (CLASS_DATA (fsym)->attr.class_pointer
6109 					 || CLASS_DATA (fsym)->attr.allocatable),
6110 				     fsym->attr.optional
6111 				     && e->expr_type == EXPR_VARIABLE
6112 				     && e->symtree->n.sym->attr.optional,
6113 				     CLASS_DATA (fsym)->attr.class_pointer
6114 				     || CLASS_DATA (fsym)->attr.allocatable);
6115 
6116 		  /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is
6117 		     allocated on entry, it must be deallocated.  */
6118 		  if (fsym && fsym->attr.intent == INTENT_OUT
6119 		      && (fsym->attr.allocatable
6120 			  || (fsym->ts.type == BT_CLASS
6121 			      && CLASS_DATA (fsym)->attr.allocatable)))
6122 		    {
6123 		      stmtblock_t block;
6124 		      tree ptr;
6125 
6126 		      gfc_init_block  (&block);
6127 		      ptr = parmse.expr;
6128 		      if (e->ts.type == BT_CLASS)
6129 			ptr = gfc_class_data_get (ptr);
6130 
6131 		      tmp = gfc_deallocate_scalar_with_status (ptr, NULL_TREE,
6132 							       NULL_TREE, true,
6133 							       e, e->ts);
6134 		      gfc_add_expr_to_block (&block, tmp);
6135 		      tmp = fold_build2_loc (input_location, MODIFY_EXPR,
6136 					     void_type_node, ptr,
6137 					     null_pointer_node);
6138 		      gfc_add_expr_to_block (&block, tmp);
6139 
6140 		      if (fsym->ts.type == BT_CLASS && UNLIMITED_POLY (fsym))
6141 			{
6142 			  gfc_add_modify (&block, ptr,
6143 					  fold_convert (TREE_TYPE (ptr),
6144 							null_pointer_node));
6145 			  gfc_add_expr_to_block (&block, tmp);
6146 			}
6147 		      else if (fsym->ts.type == BT_CLASS)
6148 			{
6149 			  gfc_symbol *vtab;
6150 			  vtab = gfc_find_derived_vtab (fsym->ts.u.derived);
6151 			  tmp = gfc_get_symbol_decl (vtab);
6152 			  tmp = gfc_build_addr_expr (NULL_TREE, tmp);
6153 			  ptr = gfc_class_vptr_get (parmse.expr);
6154 			  gfc_add_modify (&block, ptr,
6155 					  fold_convert (TREE_TYPE (ptr), tmp));
6156 			  gfc_add_expr_to_block (&block, tmp);
6157 			}
6158 
6159 		      if (fsym->attr.optional
6160 			  && e->expr_type == EXPR_VARIABLE
6161 			  && e->symtree->n.sym->attr.optional)
6162 			{
6163 			  tmp = fold_build3_loc (input_location, COND_EXPR,
6164 				     void_type_node,
6165 				     gfc_conv_expr_present (e->symtree->n.sym),
6166 					    gfc_finish_block (&block),
6167 					    build_empty_stmt (input_location));
6168 			}
6169 		      else
6170 			tmp = gfc_finish_block (&block);
6171 
6172 		      gfc_add_expr_to_block (&se->pre, tmp);
6173 		    }
6174 
6175 		  if (fsym && (fsym->ts.type == BT_DERIVED
6176 			       || fsym->ts.type == BT_ASSUMED)
6177 		      && e->ts.type == BT_CLASS
6178 		      && !CLASS_DATA (e)->attr.dimension
6179 		      && !CLASS_DATA (e)->attr.codimension)
6180 		    {
6181 		      parmse.expr = gfc_class_data_get (parmse.expr);
6182 		      /* The result is a class temporary, whose _data component
6183 			 must be freed to avoid a memory leak.  */
6184 		      if (e->expr_type == EXPR_FUNCTION
6185 			  && CLASS_DATA (e)->attr.allocatable)
6186 			{
6187 			  tree zero;
6188 
6189 			  gfc_expr *var;
6190 
6191 			  /* Borrow the function symbol to make a call to
6192 			     gfc_add_finalizer_call and then restore it.  */
6193 			  tmp = e->symtree->n.sym->backend_decl;
6194 			  e->symtree->n.sym->backend_decl
6195 					= TREE_OPERAND (parmse.expr, 0);
6196 			  e->symtree->n.sym->attr.flavor = FL_VARIABLE;
6197 			  var = gfc_lval_expr_from_sym (e->symtree->n.sym);
6198 			  finalized = gfc_add_finalizer_call (&parmse.post,
6199 							      var);
6200 			  gfc_free_expr (var);
6201 			  e->symtree->n.sym->backend_decl = tmp;
6202 			  e->symtree->n.sym->attr.flavor = FL_PROCEDURE;
6203 
6204 			  /* Then free the class _data.  */
6205 			  zero = build_int_cst (TREE_TYPE (parmse.expr), 0);
6206 			  tmp = fold_build2_loc (input_location, NE_EXPR,
6207 						 logical_type_node,
6208 						 parmse.expr, zero);
6209 			  tmp = build3_v (COND_EXPR, tmp,
6210 					  gfc_call_free (parmse.expr),
6211 					  build_empty_stmt (input_location));
6212 			  gfc_add_expr_to_block (&parmse.post, tmp);
6213 			  gfc_add_modify (&parmse.post, parmse.expr, zero);
6214 			}
6215 		    }
6216 
6217 		  /* Wrap scalar variable in a descriptor. We need to convert
6218 		     the address of a pointer back to the pointer itself before,
6219 		     we can assign it to the data field.  */
6220 
6221 		  if (fsym && fsym->as && fsym->as->type == AS_ASSUMED_RANK
6222 		      && fsym->ts.type != BT_CLASS && e->expr_type != EXPR_NULL)
6223 		    {
6224 		      tmp = parmse.expr;
6225 		      if (TREE_CODE (tmp) == ADDR_EXPR)
6226 			tmp = build_fold_indirect_ref_loc (input_location, tmp);
6227 		      parmse.expr = gfc_conv_scalar_to_descriptor (&parmse, tmp,
6228 								   fsym->attr);
6229 		      parmse.expr = gfc_build_addr_expr (NULL_TREE,
6230 							 parmse.expr);
6231 		    }
6232 		  else if (fsym && e->expr_type != EXPR_NULL
6233 		      && ((fsym->attr.pointer
6234 			   && fsym->attr.flavor != FL_PROCEDURE)
6235 			  || (fsym->attr.proc_pointer
6236 			      && !(e->expr_type == EXPR_VARIABLE
6237 				   && e->symtree->n.sym->attr.dummy))
6238 			  || (fsym->attr.proc_pointer
6239 			      && e->expr_type == EXPR_VARIABLE
6240 			      && gfc_is_proc_ptr_comp (e))
6241 			  || (fsym->attr.allocatable
6242 			      && fsym->attr.flavor != FL_PROCEDURE)))
6243 		    {
6244 		      /* Scalar pointer dummy args require an extra level of
6245 			 indirection. The null pointer already contains
6246 			 this level of indirection.  */
6247 		      parm_kind = SCALAR_POINTER;
6248 		      parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
6249 		    }
6250 		}
6251 	    }
6252 	  else if (e->ts.type == BT_CLASS
6253 		    && fsym && fsym->ts.type == BT_CLASS
6254 		    && (CLASS_DATA (fsym)->attr.dimension
6255 			|| CLASS_DATA (fsym)->attr.codimension))
6256 	    {
6257 	      /* Pass a class array.  */
6258 	      parmse.use_offset = 1;
6259 	      gfc_conv_expr_descriptor (&parmse, e);
6260 
6261 	      /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is
6262 		 allocated on entry, it must be deallocated.  */
6263 	      if (fsym->attr.intent == INTENT_OUT
6264 		  && CLASS_DATA (fsym)->attr.allocatable)
6265 		{
6266 		  stmtblock_t block;
6267 		  tree ptr;
6268 
6269 		  gfc_init_block  (&block);
6270 		  ptr = parmse.expr;
6271 		  ptr = gfc_class_data_get (ptr);
6272 
6273 		  tmp = gfc_deallocate_with_status (ptr, NULL_TREE,
6274 						    NULL_TREE, NULL_TREE,
6275 						    NULL_TREE, true, e,
6276 						    GFC_CAF_COARRAY_NOCOARRAY);
6277 		  gfc_add_expr_to_block (&block, tmp);
6278 		  tmp = fold_build2_loc (input_location, MODIFY_EXPR,
6279 					 void_type_node, ptr,
6280 					 null_pointer_node);
6281 		  gfc_add_expr_to_block (&block, tmp);
6282 		  gfc_reset_vptr (&block, e);
6283 
6284 		  if (fsym->attr.optional
6285 		      && e->expr_type == EXPR_VARIABLE
6286 		      && (!e->ref
6287 			  || (e->ref->type == REF_ARRAY
6288 			      && e->ref->u.ar.type != AR_FULL))
6289 		      && e->symtree->n.sym->attr.optional)
6290 		    {
6291 		      tmp = fold_build3_loc (input_location, COND_EXPR,
6292 				    void_type_node,
6293 				    gfc_conv_expr_present (e->symtree->n.sym),
6294 				    gfc_finish_block (&block),
6295 				    build_empty_stmt (input_location));
6296 		    }
6297 		  else
6298 		    tmp = gfc_finish_block (&block);
6299 
6300 		  gfc_add_expr_to_block (&se->pre, tmp);
6301 		}
6302 
6303 	      /* The conversion does not repackage the reference to a class
6304 	         array - _data descriptor.  */
6305 	      gfc_conv_class_to_class (&parmse, e, fsym->ts, false,
6306 				     fsym->attr.intent != INTENT_IN
6307 				     && (CLASS_DATA (fsym)->attr.class_pointer
6308 					 || CLASS_DATA (fsym)->attr.allocatable),
6309 				     fsym->attr.optional
6310 				     && e->expr_type == EXPR_VARIABLE
6311 				     && e->symtree->n.sym->attr.optional,
6312 				     CLASS_DATA (fsym)->attr.class_pointer
6313 				     || CLASS_DATA (fsym)->attr.allocatable);
6314 	    }
6315 	  else
6316 	    {
6317 	      /* If the argument is a function call that may not create
6318 		 a temporary for the result, we have to check that we
6319 		 can do it, i.e. that there is no alias between this
6320 		 argument and another one.  */
6321 	      if (gfc_get_noncopying_intrinsic_argument (e) != NULL)
6322 		{
6323 		  gfc_expr *iarg;
6324 		  sym_intent intent;
6325 
6326 		  if (fsym != NULL)
6327 		    intent = fsym->attr.intent;
6328 		  else
6329 		    intent = INTENT_UNKNOWN;
6330 
6331 		  if (gfc_check_fncall_dependency (e, intent, sym, args,
6332 						   NOT_ELEMENTAL))
6333 		    parmse.force_tmp = 1;
6334 
6335 		  iarg = e->value.function.actual->expr;
6336 
6337 		  /* Temporary needed if aliasing due to host association.  */
6338 		  if (sym->attr.contained
6339 			&& !sym->attr.pure
6340 			&& !sym->attr.implicit_pure
6341 			&& !sym->attr.use_assoc
6342 			&& iarg->expr_type == EXPR_VARIABLE
6343 			&& sym->ns == iarg->symtree->n.sym->ns)
6344 		    parmse.force_tmp = 1;
6345 
6346 		  /* Ditto within module.  */
6347 		  if (sym->attr.use_assoc
6348 			&& !sym->attr.pure
6349 			&& !sym->attr.implicit_pure
6350 			&& iarg->expr_type == EXPR_VARIABLE
6351 			&& sym->module == iarg->symtree->n.sym->module)
6352 		    parmse.force_tmp = 1;
6353 		}
6354 
6355 	      if (sym->attr.is_bind_c && e
6356 		  && (is_CFI_desc (fsym, NULL) || non_unity_length_string))
6357 		/* Implement F2018, C.12.6.1: paragraph (2).  */
6358 		gfc_conv_gfc_desc_to_cfi_desc (&parmse, e, fsym);
6359 
6360 	      else if (e->expr_type == EXPR_VARIABLE
6361 		    && is_subref_array (e)
6362 		    && !(fsym && fsym->attr.pointer))
6363 		/* The actual argument is a component reference to an
6364 		   array of derived types.  In this case, the argument
6365 		   is converted to a temporary, which is passed and then
6366 		   written back after the procedure call.  */
6367 		gfc_conv_subref_array_arg (&parmse, e, nodesc_arg,
6368 				fsym ? fsym->attr.intent : INTENT_INOUT,
6369 				fsym && fsym->attr.pointer);
6370 
6371 	      else if (e->ts.type == BT_CLASS && CLASS_DATA (e)->as
6372 		       && CLASS_DATA (e)->as->type == AS_ASSUMED_SIZE
6373 		       && nodesc_arg && fsym->ts.type == BT_DERIVED)
6374 		/* An assumed size class actual argument being passed to
6375 		   a 'no descriptor' formal argument just requires the
6376 		   data pointer to be passed. For class dummy arguments
6377 		   this is stored in the symbol backend decl..  */
6378 		parmse.expr = e->symtree->n.sym->backend_decl;
6379 
6380 	      else if (gfc_is_class_array_ref (e, NULL)
6381 		       && fsym && fsym->ts.type == BT_DERIVED)
6382 		/* The actual argument is a component reference to an
6383 		   array of derived types.  In this case, the argument
6384 		   is converted to a temporary, which is passed and then
6385 		   written back after the procedure call.
6386 		   OOP-TODO: Insert code so that if the dynamic type is
6387 		   the same as the declared type, copy-in/copy-out does
6388 		   not occur.  */
6389 		gfc_conv_subref_array_arg (&parmse, e, nodesc_arg,
6390 					   fsym->attr.intent,
6391 					   fsym->attr.pointer);
6392 
6393 	      else if (gfc_is_class_array_function (e)
6394 		       && fsym && fsym->ts.type == BT_DERIVED)
6395 		/* See previous comment.  For function actual argument,
6396 		   the write out is not needed so the intent is set as
6397 		   intent in.  */
6398 		{
6399 		  e->must_finalize = 1;
6400 		  gfc_conv_subref_array_arg (&parmse, e, nodesc_arg,
6401 					     INTENT_IN, fsym->attr.pointer);
6402 		}
6403 	      else if (fsym && fsym->attr.contiguous
6404 		       && !gfc_is_simply_contiguous (e, false, true)
6405 		       && gfc_expr_is_variable (e))
6406 		{
6407 		  gfc_conv_subref_array_arg (&parmse, e, nodesc_arg,
6408 					     fsym->attr.intent,
6409 					     fsym->attr.pointer);
6410 		}
6411 	      else
6412 		gfc_conv_array_parameter (&parmse, e, nodesc_arg, fsym,
6413 					  sym->name, NULL);
6414 
6415 	      /* Unallocated allocatable arrays and unassociated pointer arrays
6416 		 need their dtype setting if they are argument associated with
6417 		 assumed rank dummies, unless already assumed rank.  */
6418 	      if (!sym->attr.is_bind_c && e && fsym && fsym->as
6419 		  && fsym->as->type == AS_ASSUMED_RANK
6420 		  && e->rank != -1)
6421 		{
6422 		  if (gfc_expr_attr (e).pointer
6423 		      || gfc_expr_attr (e).allocatable)
6424 		    set_dtype_for_unallocated (&parmse, e);
6425 		  else if (e->expr_type == EXPR_VARIABLE
6426 			   && e->symtree->n.sym->attr.dummy
6427 			   && e->symtree->n.sym->as
6428 			   && e->symtree->n.sym->as->type == AS_ASSUMED_SIZE)
6429 		    {
6430 		      tree minus_one;
6431 		      tmp = build_fold_indirect_ref_loc (input_location,
6432 							 parmse.expr);
6433 		      minus_one = build_int_cst (gfc_array_index_type, -1);
6434 		      gfc_conv_descriptor_ubound_set (&parmse.pre, tmp,
6435 						      gfc_rank_cst[e->rank - 1],
6436 						      minus_one);
6437  		    }
6438 		}
6439 
6440 	      /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is
6441 		 allocated on entry, it must be deallocated.  */
6442 	      if (fsym && fsym->attr.allocatable
6443 		  && fsym->attr.intent == INTENT_OUT)
6444 		{
6445 		  if (fsym->ts.type == BT_DERIVED
6446 		      && fsym->ts.u.derived->attr.alloc_comp)
6447 		  {
6448 		    // deallocate the components first
6449 		    tmp = gfc_deallocate_alloc_comp (fsym->ts.u.derived,
6450 						     parmse.expr, e->rank);
6451 		    /* But check whether dummy argument is optional.  */
6452 		    if (tmp != NULL_TREE
6453 			&& fsym->attr.optional
6454 			&& e->expr_type == EXPR_VARIABLE
6455 			&& e->symtree->n.sym->attr.optional)
6456 		      {
6457 			tree present;
6458 			present = gfc_conv_expr_present (e->symtree->n.sym);
6459 			tmp = build3_v (COND_EXPR, present, tmp,
6460 					build_empty_stmt (input_location));
6461 		      }
6462 		    if (tmp != NULL_TREE)
6463 		      gfc_add_expr_to_block (&se->pre, tmp);
6464 		  }
6465 
6466 		  tmp = parmse.expr;
6467 		  /* With bind(C), the actual argument is replaced by a bind-C
6468 		     descriptor; in this case, the data component arrives here,
6469 		     which shall not be dereferenced, but still freed and
6470 		     nullified.  */
6471 		  if  (TREE_TYPE(tmp) != pvoid_type_node)
6472 		    tmp = build_fold_indirect_ref_loc (input_location,
6473 						       parmse.expr);
6474 		  if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (tmp)))
6475 		    tmp = gfc_conv_descriptor_data_get (tmp);
6476 		  tmp = gfc_deallocate_with_status (tmp, NULL_TREE, NULL_TREE,
6477 						    NULL_TREE, NULL_TREE, true,
6478 						    e,
6479 						    GFC_CAF_COARRAY_NOCOARRAY);
6480 		  if (fsym->attr.optional
6481 		      && e->expr_type == EXPR_VARIABLE
6482 		      && e->symtree->n.sym->attr.optional)
6483 		    tmp = fold_build3_loc (input_location, COND_EXPR,
6484 				     void_type_node,
6485 				     gfc_conv_expr_present (e->symtree->n.sym),
6486 				       tmp, build_empty_stmt (input_location));
6487 		  gfc_add_expr_to_block (&se->pre, tmp);
6488 		}
6489 	    }
6490 	}
6491 
6492       /* The case with fsym->attr.optional is that of a user subroutine
6493 	 with an interface indicating an optional argument.  When we call
6494 	 an intrinsic subroutine, however, fsym is NULL, but we might still
6495 	 have an optional argument, so we proceed to the substitution
6496 	 just in case.  */
6497       if (e && (fsym == NULL || fsym->attr.optional))
6498 	{
6499 	  /* If an optional argument is itself an optional dummy argument,
6500 	     check its presence and substitute a null if absent.  This is
6501 	     only needed when passing an array to an elemental procedure
6502 	     as then array elements are accessed - or no NULL pointer is
6503 	     allowed and a "1" or "0" should be passed if not present.
6504 	     When passing a non-array-descriptor full array to a
6505 	     non-array-descriptor dummy, no check is needed. For
6506 	     array-descriptor actual to array-descriptor dummy, see
6507 	     PR 41911 for why a check has to be inserted.
6508 	     fsym == NULL is checked as intrinsics required the descriptor
6509 	     but do not always set fsym.
6510 	     Also, it is necessary to pass a NULL pointer to library routines
6511 	     which usually ignore optional arguments, so they can handle
6512 	     these themselves.  */
6513 	  if (e->expr_type == EXPR_VARIABLE
6514 	      && e->symtree->n.sym->attr.optional
6515 	      && (((e->rank != 0 && elemental_proc)
6516 		   || e->representation.length || e->ts.type == BT_CHARACTER
6517 		   || (e->rank != 0
6518 		       && (fsym == NULL
6519 			   || (fsym->as
6520 			       && (fsym->as->type == AS_ASSUMED_SHAPE
6521 				   || fsym->as->type == AS_ASSUMED_RANK
6522 				   || fsym->as->type == AS_DEFERRED)))))
6523 		  || se->ignore_optional))
6524 	    gfc_conv_missing_dummy (&parmse, e, fsym ? fsym->ts : e->ts,
6525 				    e->representation.length);
6526 	}
6527 
6528       if (fsym && e)
6529 	{
6530 	  /* Obtain the character length of an assumed character length
6531 	     length procedure from the typespec.  */
6532 	  if (fsym->ts.type == BT_CHARACTER
6533 	      && parmse.string_length == NULL_TREE
6534 	      && e->ts.type == BT_PROCEDURE
6535 	      && e->symtree->n.sym->ts.type == BT_CHARACTER
6536 	      && e->symtree->n.sym->ts.u.cl->length != NULL
6537 	      && e->symtree->n.sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
6538 	    {
6539 	      gfc_conv_const_charlen (e->symtree->n.sym->ts.u.cl);
6540 	      parmse.string_length = e->symtree->n.sym->ts.u.cl->backend_decl;
6541 	    }
6542 	}
6543 
6544       if (fsym && need_interface_mapping && e)
6545 	gfc_add_interface_mapping (&mapping, fsym, &parmse, e);
6546 
6547       gfc_add_block_to_block (&se->pre, &parmse.pre);
6548       gfc_add_block_to_block (&post, &parmse.post);
6549 
6550       /* Allocated allocatable components of derived types must be
6551 	 deallocated for non-variable scalars, array arguments to elemental
6552 	 procedures, and array arguments with descriptor to non-elemental
6553 	 procedures.  As bounds information for descriptorless arrays is no
6554 	 longer available here, they are dealt with in trans-array.c
6555 	 (gfc_conv_array_parameter).  */
6556       if (e && (e->ts.type == BT_DERIVED || e->ts.type == BT_CLASS)
6557 	    && e->ts.u.derived->attr.alloc_comp
6558 	    && (e->rank == 0 || elemental_proc || !nodesc_arg)
6559 	    && !expr_may_alias_variables (e, elemental_proc))
6560 	{
6561 	  int parm_rank;
6562 	  /* It is known the e returns a structure type with at least one
6563 	     allocatable component.  When e is a function, ensure that the
6564 	     function is called once only by using a temporary variable.  */
6565 	  if (!DECL_P (parmse.expr))
6566 	    parmse.expr = gfc_evaluate_now_loc (input_location,
6567 						parmse.expr, &se->pre);
6568 
6569 	  if (fsym && fsym->attr.value)
6570 	    tmp = parmse.expr;
6571 	  else
6572 	    tmp = build_fold_indirect_ref_loc (input_location,
6573 					       parmse.expr);
6574 
6575 	  parm_rank = e->rank;
6576 	  switch (parm_kind)
6577 	    {
6578 	    case (ELEMENTAL):
6579 	    case (SCALAR):
6580 	      parm_rank = 0;
6581 	      break;
6582 
6583 	    case (SCALAR_POINTER):
6584               tmp = build_fold_indirect_ref_loc (input_location,
6585 					     tmp);
6586 	      break;
6587 	    }
6588 
6589 	  if (e->ts.type == BT_DERIVED && fsym && fsym->ts.type == BT_CLASS)
6590 	    {
6591 	      /* The derived type is passed to gfc_deallocate_alloc_comp.
6592 		 Therefore, class actuals can be handled correctly but derived
6593 		 types passed to class formals need the _data component.  */
6594 	      tmp = gfc_class_data_get (tmp);
6595 	      if (!CLASS_DATA (fsym)->attr.dimension)
6596 		tmp = build_fold_indirect_ref_loc (input_location, tmp);
6597 	    }
6598 
6599 	  if (e->expr_type == EXPR_OP
6600 		&& e->value.op.op == INTRINSIC_PARENTHESES
6601 		&& e->value.op.op1->expr_type == EXPR_VARIABLE)
6602 	    {
6603 	      tree local_tmp;
6604 	      local_tmp = gfc_evaluate_now (tmp, &se->pre);
6605 	      local_tmp = gfc_copy_alloc_comp (e->ts.u.derived, local_tmp, tmp,
6606 					       parm_rank, 0);
6607 	      gfc_add_expr_to_block (&se->post, local_tmp);
6608 	    }
6609 
6610 	  if (!finalized && !e->must_finalize)
6611 	    {
6612 	      if ((e->ts.type == BT_CLASS
6613 		   && GFC_CLASS_TYPE_P (TREE_TYPE (tmp)))
6614 		  || e->ts.type == BT_DERIVED)
6615 		tmp = gfc_deallocate_alloc_comp (e->ts.u.derived, tmp,
6616 						 parm_rank);
6617 	      else if (e->ts.type == BT_CLASS)
6618 		tmp = gfc_deallocate_alloc_comp (CLASS_DATA (e)->ts.u.derived,
6619 						 tmp, parm_rank);
6620 	      gfc_prepend_expr_to_block (&post, tmp);
6621 	    }
6622         }
6623 
6624       /* Add argument checking of passing an unallocated/NULL actual to
6625          a nonallocatable/nonpointer dummy.  */
6626 
6627       if (gfc_option.rtcheck & GFC_RTCHECK_POINTER && e != NULL)
6628         {
6629 	  symbol_attribute attr;
6630 	  char *msg;
6631 	  tree cond;
6632 
6633 	  if (e->expr_type == EXPR_VARIABLE || e->expr_type == EXPR_FUNCTION)
6634 	    attr = gfc_expr_attr (e);
6635 	  else
6636 	    goto end_pointer_check;
6637 
6638 	  /*  In Fortran 2008 it's allowed to pass a NULL pointer/nonallocated
6639 	      allocatable to an optional dummy, cf. 12.5.2.12.  */
6640 	  if (fsym != NULL && fsym->attr.optional && !attr.proc_pointer
6641 	      && (gfc_option.allow_std & GFC_STD_F2008) != 0)
6642 	    goto end_pointer_check;
6643 
6644           if (attr.optional)
6645 	    {
6646               /* If the actual argument is an optional pointer/allocatable and
6647 		 the formal argument takes an nonpointer optional value,
6648 		 it is invalid to pass a non-present argument on, even
6649 		 though there is no technical reason for this in gfortran.
6650 		 See Fortran 2003, Section 12.4.1.6 item (7)+(8).  */
6651 	      tree present, null_ptr, type;
6652 
6653 	      if (attr.allocatable
6654 		  && (fsym == NULL || !fsym->attr.allocatable))
6655 		msg = xasprintf ("Allocatable actual argument '%s' is not "
6656 				 "allocated or not present",
6657 				 e->symtree->n.sym->name);
6658 	      else if (attr.pointer
6659 		       && (fsym == NULL || !fsym->attr.pointer))
6660 		msg = xasprintf ("Pointer actual argument '%s' is not "
6661 				 "associated or not present",
6662 				 e->symtree->n.sym->name);
6663 	      else if (attr.proc_pointer
6664 		       && (fsym == NULL || !fsym->attr.proc_pointer))
6665 		msg = xasprintf ("Proc-pointer actual argument '%s' is not "
6666 				 "associated or not present",
6667 				 e->symtree->n.sym->name);
6668 	      else
6669 		goto end_pointer_check;
6670 
6671 	      present = gfc_conv_expr_present (e->symtree->n.sym);
6672 	      type = TREE_TYPE (present);
6673 	      present = fold_build2_loc (input_location, EQ_EXPR,
6674 					 logical_type_node, present,
6675 					 fold_convert (type,
6676 						       null_pointer_node));
6677 	      type = TREE_TYPE (parmse.expr);
6678 	      null_ptr = fold_build2_loc (input_location, EQ_EXPR,
6679 					  logical_type_node, parmse.expr,
6680 					  fold_convert (type,
6681 							null_pointer_node));
6682 	      cond = fold_build2_loc (input_location, TRUTH_ORIF_EXPR,
6683 				      logical_type_node, present, null_ptr);
6684 	    }
6685           else
6686 	    {
6687 	      if (attr.allocatable
6688 		  && (fsym == NULL || !fsym->attr.allocatable))
6689 		msg = xasprintf ("Allocatable actual argument '%s' is not "
6690 				 "allocated", e->symtree->n.sym->name);
6691 	      else if (attr.pointer
6692 		       && (fsym == NULL || !fsym->attr.pointer))
6693 		msg = xasprintf ("Pointer actual argument '%s' is not "
6694 				 "associated", e->symtree->n.sym->name);
6695 	      else if (attr.proc_pointer
6696 		       && (fsym == NULL || !fsym->attr.proc_pointer))
6697 		msg = xasprintf ("Proc-pointer actual argument '%s' is not "
6698 				 "associated", e->symtree->n.sym->name);
6699 	      else
6700 		goto end_pointer_check;
6701 
6702 	      tmp = parmse.expr;
6703 
6704 	      /* If the argument is passed by value, we need to strip the
6705 		 INDIRECT_REF.  */
6706 	      if (!POINTER_TYPE_P (TREE_TYPE (parmse.expr)))
6707 		tmp = gfc_build_addr_expr (NULL_TREE, tmp);
6708 
6709 	      cond = fold_build2_loc (input_location, EQ_EXPR,
6710 				      logical_type_node, tmp,
6711 				      fold_convert (TREE_TYPE (tmp),
6712 						    null_pointer_node));
6713 	    }
6714 
6715 	  gfc_trans_runtime_check (true, false, cond, &se->pre, &e->where,
6716 				   msg);
6717 	  free (msg);
6718         }
6719       end_pointer_check:
6720 
6721       /* Deferred length dummies pass the character length by reference
6722 	 so that the value can be returned.  */
6723       if (parmse.string_length && fsym && fsym->ts.deferred)
6724 	{
6725 	  if (INDIRECT_REF_P (parmse.string_length))
6726 	    /* In chains of functions/procedure calls the string_length already
6727 	       is a pointer to the variable holding the length.  Therefore
6728 	       remove the deref on call.  */
6729 	    parmse.string_length = TREE_OPERAND (parmse.string_length, 0);
6730 	  else
6731 	    {
6732 	      tmp = parmse.string_length;
6733 	      if (!VAR_P (tmp) && TREE_CODE (tmp) != COMPONENT_REF)
6734 		tmp = gfc_evaluate_now (parmse.string_length, &se->pre);
6735 	      parmse.string_length = gfc_build_addr_expr (NULL_TREE, tmp);
6736 	    }
6737 	}
6738 
6739       /* Character strings are passed as two parameters, a length and a
6740 	 pointer - except for Bind(c) which only passes the pointer.
6741 	 An unlimited polymorphic formal argument likewise does not
6742 	 need the length.  */
6743       if (parmse.string_length != NULL_TREE
6744 	  && !sym->attr.is_bind_c
6745 	  && !(fsym && UNLIMITED_POLY (fsym)))
6746 	vec_safe_push (stringargs, parmse.string_length);
6747 
6748       /* When calling __copy for character expressions to unlimited
6749 	 polymorphic entities, the dst argument needs a string length.  */
6750       if (sym->name[0] == '_' && e && e->ts.type == BT_CHARACTER
6751 	  && gfc_str_startswith (sym->name, "__vtab_CHARACTER")
6752 	  && arg->next && arg->next->expr
6753 	  && (arg->next->expr->ts.type == BT_DERIVED
6754 	      || arg->next->expr->ts.type == BT_CLASS)
6755 	  && arg->next->expr->ts.u.derived->attr.unlimited_polymorphic)
6756 	vec_safe_push (stringargs, parmse.string_length);
6757 
6758       /* For descriptorless coarrays and assumed-shape coarray dummies, we
6759 	 pass the token and the offset as additional arguments.  */
6760       if (fsym && e == NULL && flag_coarray == GFC_FCOARRAY_LIB
6761 	  && ((fsym->ts.type != BT_CLASS && fsym->attr.codimension
6762 	       && !fsym->attr.allocatable)
6763 	      || (fsym->ts.type == BT_CLASS
6764 		  && CLASS_DATA (fsym)->attr.codimension
6765 		  && !CLASS_DATA (fsym)->attr.allocatable)))
6766 	{
6767 	  /* Token and offset.  */
6768 	  vec_safe_push (stringargs, null_pointer_node);
6769 	  vec_safe_push (stringargs, build_int_cst (gfc_array_index_type, 0));
6770 	  gcc_assert (fsym->attr.optional);
6771 	}
6772       else if (fsym && flag_coarray == GFC_FCOARRAY_LIB
6773 	       && ((fsym->ts.type != BT_CLASS && fsym->attr.codimension
6774 		    && !fsym->attr.allocatable)
6775 		   || (fsym->ts.type == BT_CLASS
6776 		       && CLASS_DATA (fsym)->attr.codimension
6777 		       && !CLASS_DATA (fsym)->attr.allocatable)))
6778 	{
6779 	  tree caf_decl, caf_type;
6780 	  tree offset, tmp2;
6781 
6782 	  caf_decl = gfc_get_tree_for_caf_expr (e);
6783 	  caf_type = TREE_TYPE (caf_decl);
6784 
6785 	  if (GFC_DESCRIPTOR_TYPE_P (caf_type)
6786 	      && (GFC_TYPE_ARRAY_AKIND (caf_type) == GFC_ARRAY_ALLOCATABLE
6787 		  || GFC_TYPE_ARRAY_AKIND (caf_type) == GFC_ARRAY_POINTER))
6788 	    tmp = gfc_conv_descriptor_token (caf_decl);
6789 	  else if (DECL_LANG_SPECIFIC (caf_decl)
6790 		   && GFC_DECL_TOKEN (caf_decl) != NULL_TREE)
6791 	    tmp = GFC_DECL_TOKEN (caf_decl);
6792 	  else
6793 	    {
6794 	      gcc_assert (GFC_ARRAY_TYPE_P (caf_type)
6795 			  && GFC_TYPE_ARRAY_CAF_TOKEN (caf_type) != NULL_TREE);
6796 	      tmp = GFC_TYPE_ARRAY_CAF_TOKEN (caf_type);
6797 	    }
6798 
6799 	  vec_safe_push (stringargs, tmp);
6800 
6801 	  if (GFC_DESCRIPTOR_TYPE_P (caf_type)
6802 	      && GFC_TYPE_ARRAY_AKIND (caf_type) == GFC_ARRAY_ALLOCATABLE)
6803 	    offset = build_int_cst (gfc_array_index_type, 0);
6804 	  else if (DECL_LANG_SPECIFIC (caf_decl)
6805 		   && GFC_DECL_CAF_OFFSET (caf_decl) != NULL_TREE)
6806 	    offset = GFC_DECL_CAF_OFFSET (caf_decl);
6807 	  else if (GFC_TYPE_ARRAY_CAF_OFFSET (caf_type) != NULL_TREE)
6808 	    offset = GFC_TYPE_ARRAY_CAF_OFFSET (caf_type);
6809 	  else
6810 	    offset = build_int_cst (gfc_array_index_type, 0);
6811 
6812 	  if (GFC_DESCRIPTOR_TYPE_P (caf_type))
6813 	    tmp = gfc_conv_descriptor_data_get (caf_decl);
6814 	  else
6815 	    {
6816 	      gcc_assert (POINTER_TYPE_P (caf_type));
6817 	      tmp = caf_decl;
6818 	    }
6819 
6820           tmp2 = fsym->ts.type == BT_CLASS
6821 		 ? gfc_class_data_get (parmse.expr) : parmse.expr;
6822           if ((fsym->ts.type != BT_CLASS
6823 	       && (fsym->as->type == AS_ASSUMED_SHAPE
6824 		   || fsym->as->type == AS_ASSUMED_RANK))
6825 	      || (fsym->ts.type == BT_CLASS
6826 		  && (CLASS_DATA (fsym)->as->type == AS_ASSUMED_SHAPE
6827 		      || CLASS_DATA (fsym)->as->type == AS_ASSUMED_RANK)))
6828 	    {
6829 	      if (fsym->ts.type == BT_CLASS)
6830 		gcc_assert (!POINTER_TYPE_P (TREE_TYPE (tmp2)));
6831 	      else
6832 		{
6833 		  gcc_assert (POINTER_TYPE_P (TREE_TYPE (tmp2)));
6834 		  tmp2 = build_fold_indirect_ref_loc (input_location, tmp2);
6835 		}
6836 	      gcc_assert (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (tmp2)));
6837 	      tmp2 = gfc_conv_descriptor_data_get (tmp2);
6838 	    }
6839 	  else if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (tmp2)))
6840 	    tmp2 = gfc_conv_descriptor_data_get (tmp2);
6841 	  else
6842 	    {
6843 	      gcc_assert (POINTER_TYPE_P (TREE_TYPE (tmp2)));
6844 	    }
6845 
6846 	  tmp = fold_build2_loc (input_location, MINUS_EXPR,
6847                                  gfc_array_index_type,
6848                                  fold_convert (gfc_array_index_type, tmp2),
6849                                  fold_convert (gfc_array_index_type, tmp));
6850 	  offset = fold_build2_loc (input_location, PLUS_EXPR,
6851 				    gfc_array_index_type, offset, tmp);
6852 
6853 	  vec_safe_push (stringargs, offset);
6854 	}
6855 
6856       vec_safe_push (arglist, parmse.expr);
6857     }
6858   gfc_finish_interface_mapping (&mapping, &se->pre, &se->post);
6859 
6860   if (comp)
6861     ts = comp->ts;
6862   else if (sym->ts.type == BT_CLASS)
6863     ts = CLASS_DATA (sym)->ts;
6864   else
6865     ts = sym->ts;
6866 
6867   if (ts.type == BT_CHARACTER && sym->attr.is_bind_c)
6868     se->string_length = build_int_cst (gfc_charlen_type_node, 1);
6869   else if (ts.type == BT_CHARACTER)
6870     {
6871       if (ts.u.cl->length == NULL)
6872 	{
6873 	  /* Assumed character length results are not allowed by C418 of the 2003
6874 	     standard and are trapped in resolve.c; except in the case of SPREAD
6875 	     (and other intrinsics?) and dummy functions.  In the case of SPREAD,
6876 	     we take the character length of the first argument for the result.
6877 	     For dummies, we have to look through the formal argument list for
6878 	     this function and use the character length found there.*/
6879 	  if (ts.deferred)
6880 	    cl.backend_decl = gfc_create_var (gfc_charlen_type_node, "slen");
6881 	  else if (!sym->attr.dummy)
6882 	    cl.backend_decl = (*stringargs)[0];
6883 	  else
6884 	    {
6885 	      formal = gfc_sym_get_dummy_args (sym->ns->proc_name);
6886 	      for (; formal; formal = formal->next)
6887 		if (strcmp (formal->sym->name, sym->name) == 0)
6888 		  cl.backend_decl = formal->sym->ts.u.cl->backend_decl;
6889 	    }
6890 	  len = cl.backend_decl;
6891         }
6892       else
6893         {
6894 	  tree tmp;
6895 
6896 	  /* Calculate the length of the returned string.  */
6897 	  gfc_init_se (&parmse, NULL);
6898 	  if (need_interface_mapping)
6899 	    gfc_apply_interface_mapping (&mapping, &parmse, ts.u.cl->length);
6900 	  else
6901 	    gfc_conv_expr (&parmse, ts.u.cl->length);
6902 	  gfc_add_block_to_block (&se->pre, &parmse.pre);
6903 	  gfc_add_block_to_block (&se->post, &parmse.post);
6904 	  tmp = parmse.expr;
6905 	  /* TODO: It would be better to have the charlens as
6906 	     gfc_charlen_type_node already when the interface is
6907 	     created instead of converting it here (see PR 84615).  */
6908 	  tmp = fold_build2_loc (input_location, MAX_EXPR,
6909 				 gfc_charlen_type_node,
6910 				 fold_convert (gfc_charlen_type_node, tmp),
6911 				 build_zero_cst (gfc_charlen_type_node));
6912 	  cl.backend_decl = tmp;
6913 	}
6914 
6915       /* Set up a charlen structure for it.  */
6916       cl.next = NULL;
6917       cl.length = NULL;
6918       ts.u.cl = &cl;
6919 
6920       len = cl.backend_decl;
6921     }
6922 
6923   byref = (comp && (comp->attr.dimension
6924 	   || (comp->ts.type == BT_CHARACTER && !sym->attr.is_bind_c)))
6925 	   || (!comp && gfc_return_by_reference (sym));
6926   if (byref)
6927     {
6928       if (se->direct_byref)
6929 	{
6930 	  /* Sometimes, too much indirection can be applied; e.g. for
6931 	     function_result = array_valued_recursive_function.  */
6932 	  if (TREE_TYPE (TREE_TYPE (se->expr))
6933 		&& TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr)))
6934 		&& GFC_DESCRIPTOR_TYPE_P
6935 			(TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr)))))
6936 	    se->expr = build_fold_indirect_ref_loc (input_location,
6937 						    se->expr);
6938 
6939 	  /* If the lhs of an assignment x = f(..) is allocatable and
6940 	     f2003 is allowed, we must do the automatic reallocation.
6941 	     TODO - deal with intrinsics, without using a temporary.  */
6942 	  if (flag_realloc_lhs
6943 		&& se->ss && se->ss->loop_chain
6944 		&& se->ss->loop_chain->is_alloc_lhs
6945 		&& !expr->value.function.isym
6946 		&& sym->result->as != NULL)
6947 	    {
6948 	      /* Evaluate the bounds of the result, if known.  */
6949 	      gfc_set_loop_bounds_from_array_spec (&mapping, se,
6950 						   sym->result->as);
6951 
6952 	      /* Perform the automatic reallocation.  */
6953 	      tmp = gfc_alloc_allocatable_for_assignment (se->loop,
6954 							  expr, NULL);
6955 	      gfc_add_expr_to_block (&se->pre, tmp);
6956 
6957 	      /* Pass the temporary as the first argument.  */
6958 	      result = info->descriptor;
6959 	    }
6960 	  else
6961 	    result = build_fold_indirect_ref_loc (input_location,
6962 						  se->expr);
6963 	  vec_safe_push (retargs, se->expr);
6964 	}
6965       else if (comp && comp->attr.dimension)
6966 	{
6967 	  gcc_assert (se->loop && info);
6968 
6969 	  /* Set the type of the array.  */
6970 	  tmp = gfc_typenode_for_spec (&comp->ts);
6971 	  gcc_assert (se->ss->dimen == se->loop->dimen);
6972 
6973 	  /* Evaluate the bounds of the result, if known.  */
6974 	  gfc_set_loop_bounds_from_array_spec (&mapping, se, comp->as);
6975 
6976 	  /* If the lhs of an assignment x = f(..) is allocatable and
6977 	     f2003 is allowed, we must not generate the function call
6978 	     here but should just send back the results of the mapping.
6979 	     This is signalled by the function ss being flagged.  */
6980 	  if (flag_realloc_lhs && se->ss && se->ss->is_alloc_lhs)
6981 	    {
6982 	      gfc_free_interface_mapping (&mapping);
6983 	      return has_alternate_specifier;
6984 	    }
6985 
6986 	  /* Create a temporary to store the result.  In case the function
6987 	     returns a pointer, the temporary will be a shallow copy and
6988 	     mustn't be deallocated.  */
6989 	  callee_alloc = comp->attr.allocatable || comp->attr.pointer;
6990 	  gfc_trans_create_temp_array (&se->pre, &se->post, se->ss,
6991 				       tmp, NULL_TREE, false,
6992 				       !comp->attr.pointer, callee_alloc,
6993 				       &se->ss->info->expr->where);
6994 
6995 	  /* Pass the temporary as the first argument.  */
6996 	  result = info->descriptor;
6997 	  tmp = gfc_build_addr_expr (NULL_TREE, result);
6998 	  vec_safe_push (retargs, tmp);
6999 	}
7000       else if (!comp && sym->result->attr.dimension)
7001 	{
7002 	  gcc_assert (se->loop && info);
7003 
7004 	  /* Set the type of the array.  */
7005 	  tmp = gfc_typenode_for_spec (&ts);
7006 	  gcc_assert (se->ss->dimen == se->loop->dimen);
7007 
7008 	  /* Evaluate the bounds of the result, if known.  */
7009 	  gfc_set_loop_bounds_from_array_spec (&mapping, se, sym->result->as);
7010 
7011 	  /* If the lhs of an assignment x = f(..) is allocatable and
7012 	     f2003 is allowed, we must not generate the function call
7013 	     here but should just send back the results of the mapping.
7014 	     This is signalled by the function ss being flagged.  */
7015 	  if (flag_realloc_lhs && se->ss && se->ss->is_alloc_lhs)
7016 	    {
7017 	      gfc_free_interface_mapping (&mapping);
7018 	      return has_alternate_specifier;
7019 	    }
7020 
7021 	  /* Create a temporary to store the result.  In case the function
7022 	     returns a pointer, the temporary will be a shallow copy and
7023 	     mustn't be deallocated.  */
7024 	  callee_alloc = sym->attr.allocatable || sym->attr.pointer;
7025 	  gfc_trans_create_temp_array (&se->pre, &se->post, se->ss,
7026 				       tmp, NULL_TREE, false,
7027 				       !sym->attr.pointer, callee_alloc,
7028 				       &se->ss->info->expr->where);
7029 
7030 	  /* Pass the temporary as the first argument.  */
7031 	  result = info->descriptor;
7032 	  tmp = gfc_build_addr_expr (NULL_TREE, result);
7033 	  vec_safe_push (retargs, tmp);
7034 	}
7035       else if (ts.type == BT_CHARACTER)
7036 	{
7037 	  /* Pass the string length.  */
7038 	  type = gfc_get_character_type (ts.kind, ts.u.cl);
7039 	  type = build_pointer_type (type);
7040 
7041 	  /* Emit a DECL_EXPR for the VLA type.  */
7042 	  tmp = TREE_TYPE (type);
7043 	  if (TYPE_SIZE (tmp)
7044 	      && TREE_CODE (TYPE_SIZE (tmp)) != INTEGER_CST)
7045 	    {
7046 	      tmp = build_decl (input_location, TYPE_DECL, NULL_TREE, tmp);
7047 	      DECL_ARTIFICIAL (tmp) = 1;
7048 	      DECL_IGNORED_P (tmp) = 1;
7049 	      tmp = fold_build1_loc (input_location, DECL_EXPR,
7050 				     TREE_TYPE (tmp), tmp);
7051 	      gfc_add_expr_to_block (&se->pre, tmp);
7052 	    }
7053 
7054 	  /* Return an address to a char[0:len-1]* temporary for
7055 	     character pointers.  */
7056 	  if ((!comp && (sym->attr.pointer || sym->attr.allocatable))
7057 	       || (comp && (comp->attr.pointer || comp->attr.allocatable)))
7058 	    {
7059 	      var = gfc_create_var (type, "pstr");
7060 
7061 	      if ((!comp && sym->attr.allocatable)
7062 		  || (comp && comp->attr.allocatable))
7063 		{
7064 		  gfc_add_modify (&se->pre, var,
7065 				  fold_convert (TREE_TYPE (var),
7066 						null_pointer_node));
7067 		  tmp = gfc_call_free (var);
7068 		  gfc_add_expr_to_block (&se->post, tmp);
7069 		}
7070 
7071 	      /* Provide an address expression for the function arguments.  */
7072 	      var = gfc_build_addr_expr (NULL_TREE, var);
7073 	    }
7074 	  else
7075 	    var = gfc_conv_string_tmp (se, type, len);
7076 
7077 	  vec_safe_push (retargs, var);
7078 	}
7079       else
7080 	{
7081 	  gcc_assert (flag_f2c && ts.type == BT_COMPLEX);
7082 
7083 	  type = gfc_get_complex_type (ts.kind);
7084 	  var = gfc_build_addr_expr (NULL_TREE, gfc_create_var (type, "cmplx"));
7085 	  vec_safe_push (retargs, var);
7086 	}
7087 
7088       /* Add the string length to the argument list.  */
7089       if (ts.type == BT_CHARACTER && ts.deferred)
7090 	{
7091 	  tmp = len;
7092 	  if (!VAR_P (tmp))
7093 	    tmp = gfc_evaluate_now (len, &se->pre);
7094 	  TREE_STATIC (tmp) = 1;
7095 	  gfc_add_modify (&se->pre, tmp,
7096 			  build_int_cst (TREE_TYPE (tmp), 0));
7097 	  tmp = gfc_build_addr_expr (NULL_TREE, tmp);
7098 	  vec_safe_push (retargs, tmp);
7099 	}
7100       else if (ts.type == BT_CHARACTER)
7101 	vec_safe_push (retargs, len);
7102     }
7103   gfc_free_interface_mapping (&mapping);
7104 
7105   /* We need to glom RETARGS + ARGLIST + STRINGARGS + APPEND_ARGS.  */
7106   arglen = (vec_safe_length (arglist) + vec_safe_length (optionalargs)
7107 	    + vec_safe_length (stringargs) + vec_safe_length (append_args));
7108   vec_safe_reserve (retargs, arglen);
7109 
7110   /* Add the return arguments.  */
7111   vec_safe_splice (retargs, arglist);
7112 
7113   /* Add the hidden present status for optional+value to the arguments.  */
7114   vec_safe_splice (retargs, optionalargs);
7115 
7116   /* Add the hidden string length parameters to the arguments.  */
7117   vec_safe_splice (retargs, stringargs);
7118 
7119   /* We may want to append extra arguments here.  This is used e.g. for
7120      calls to libgfortran_matmul_??, which need extra information.  */
7121   vec_safe_splice (retargs, append_args);
7122 
7123   arglist = retargs;
7124 
7125   /* Generate the actual call.  */
7126   if (base_object == NULL_TREE)
7127     conv_function_val (se, sym, expr, args);
7128   else
7129     conv_base_obj_fcn_val (se, base_object, expr);
7130 
7131   /* If there are alternate return labels, function type should be
7132      integer.  Can't modify the type in place though, since it can be shared
7133      with other functions.  For dummy arguments, the typing is done to
7134      this result, even if it has to be repeated for each call.  */
7135   if (has_alternate_specifier
7136       && TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr))) != integer_type_node)
7137     {
7138       if (!sym->attr.dummy)
7139 	{
7140 	  TREE_TYPE (sym->backend_decl)
7141 		= build_function_type (integer_type_node,
7142 		      TYPE_ARG_TYPES (TREE_TYPE (sym->backend_decl)));
7143 	  se->expr = gfc_build_addr_expr (NULL_TREE, sym->backend_decl);
7144 	}
7145       else
7146 	TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr))) = integer_type_node;
7147     }
7148 
7149   fntype = TREE_TYPE (TREE_TYPE (se->expr));
7150   se->expr = build_call_vec (TREE_TYPE (fntype), se->expr, arglist);
7151 
7152   /* Allocatable scalar function results must be freed and nullified
7153      after use. This necessitates the creation of a temporary to
7154      hold the result to prevent duplicate calls.  */
7155   if (!byref && sym->ts.type != BT_CHARACTER
7156       && ((sym->attr.allocatable && !sym->attr.dimension && !comp)
7157 	  || (comp && comp->attr.allocatable && !comp->attr.dimension)))
7158     {
7159       tmp = gfc_create_var (TREE_TYPE (se->expr), NULL);
7160       gfc_add_modify (&se->pre, tmp, se->expr);
7161       se->expr = tmp;
7162       tmp = gfc_call_free (tmp);
7163       gfc_add_expr_to_block (&post, tmp);
7164       gfc_add_modify (&post, se->expr, build_int_cst (TREE_TYPE (se->expr), 0));
7165     }
7166 
7167   /* If we have a pointer function, but we don't want a pointer, e.g.
7168      something like
7169         x = f()
7170      where f is pointer valued, we have to dereference the result.  */
7171   if (!se->want_pointer && !byref
7172       && ((!comp && (sym->attr.pointer || sym->attr.allocatable))
7173 	  || (comp && (comp->attr.pointer || comp->attr.allocatable))))
7174     se->expr = build_fold_indirect_ref_loc (input_location, se->expr);
7175 
7176   /* f2c calling conventions require a scalar default real function to
7177      return a double precision result.  Convert this back to default
7178      real.  We only care about the cases that can happen in Fortran 77.
7179   */
7180   if (flag_f2c && sym->ts.type == BT_REAL
7181       && sym->ts.kind == gfc_default_real_kind
7182       && !sym->attr.always_explicit)
7183     se->expr = fold_convert (gfc_get_real_type (sym->ts.kind), se->expr);
7184 
7185   /* A pure function may still have side-effects - it may modify its
7186      parameters.  */
7187   TREE_SIDE_EFFECTS (se->expr) = 1;
7188 #if 0
7189   if (!sym->attr.pure)
7190     TREE_SIDE_EFFECTS (se->expr) = 1;
7191 #endif
7192 
7193   if (byref)
7194     {
7195       /* Add the function call to the pre chain.  There is no expression.  */
7196       gfc_add_expr_to_block (&se->pre, se->expr);
7197       se->expr = NULL_TREE;
7198 
7199       if (!se->direct_byref)
7200 	{
7201 	  if ((sym->attr.dimension && !comp) || (comp && comp->attr.dimension))
7202 	    {
7203 	      if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
7204 		{
7205 		  /* Check the data pointer hasn't been modified.  This would
7206 		     happen in a function returning a pointer.  */
7207 		  tmp = gfc_conv_descriptor_data_get (info->descriptor);
7208 		  tmp = fold_build2_loc (input_location, NE_EXPR,
7209 					 logical_type_node,
7210 					 tmp, info->data);
7211 		  gfc_trans_runtime_check (true, false, tmp, &se->pre, NULL,
7212 					   gfc_msg_fault);
7213 		}
7214 	      se->expr = info->descriptor;
7215 	      /* Bundle in the string length.  */
7216 	      se->string_length = len;
7217 	    }
7218 	  else if (ts.type == BT_CHARACTER)
7219 	    {
7220 	      /* Dereference for character pointer results.  */
7221 	      if ((!comp && (sym->attr.pointer || sym->attr.allocatable))
7222 		  || (comp && (comp->attr.pointer || comp->attr.allocatable)))
7223 		se->expr = build_fold_indirect_ref_loc (input_location, var);
7224 	      else
7225 	        se->expr = var;
7226 
7227 	      se->string_length = len;
7228 	    }
7229 	  else
7230 	    {
7231 	      gcc_assert (ts.type == BT_COMPLEX && flag_f2c);
7232 	      se->expr = build_fold_indirect_ref_loc (input_location, var);
7233 	    }
7234 	}
7235     }
7236 
7237   /* Associate the rhs class object's meta-data with the result, when the
7238      result is a temporary.  */
7239   if (args && args->expr && args->expr->ts.type == BT_CLASS
7240       && sym->ts.type == BT_CLASS && result != NULL_TREE && DECL_P (result)
7241       && !GFC_CLASS_TYPE_P (TREE_TYPE (result)))
7242     {
7243       gfc_se parmse;
7244       gfc_expr *class_expr = gfc_find_and_cut_at_last_class_ref (args->expr);
7245 
7246       gfc_init_se (&parmse, NULL);
7247       parmse.data_not_needed = 1;
7248       gfc_conv_expr (&parmse, class_expr);
7249       if (!DECL_LANG_SPECIFIC (result))
7250 	gfc_allocate_lang_decl (result);
7251       GFC_DECL_SAVED_DESCRIPTOR (result) = parmse.expr;
7252       gfc_free_expr (class_expr);
7253       /* -fcheck= can add diagnostic code, which has to be placed before
7254 	 the call. */
7255       if (parmse.pre.head != NULL)
7256 	  gfc_add_expr_to_block (&se->pre, parmse.pre.head);
7257       gcc_assert (parmse.post.head == NULL_TREE);
7258     }
7259 
7260   /* Follow the function call with the argument post block.  */
7261   if (byref)
7262     {
7263       gfc_add_block_to_block (&se->pre, &post);
7264 
7265       /* Transformational functions of derived types with allocatable
7266 	 components must have the result allocatable components copied when the
7267 	 argument is actually given.  */
7268       arg = expr->value.function.actual;
7269       if (result && arg && expr->rank
7270 	  && expr->value.function.isym
7271 	  && expr->value.function.isym->transformational
7272 	  && arg->expr
7273 	  && arg->expr->ts.type == BT_DERIVED
7274 	  && arg->expr->ts.u.derived->attr.alloc_comp)
7275 	{
7276 	  tree tmp2;
7277 	  /* Copy the allocatable components.  We have to use a
7278 	     temporary here to prevent source allocatable components
7279 	     from being corrupted.  */
7280 	  tmp2 = gfc_evaluate_now (result, &se->pre);
7281 	  tmp = gfc_copy_alloc_comp (arg->expr->ts.u.derived,
7282 				     result, tmp2, expr->rank, 0);
7283 	  gfc_add_expr_to_block (&se->pre, tmp);
7284 	  tmp = gfc_copy_allocatable_data (result, tmp2, TREE_TYPE(tmp2),
7285 				           expr->rank);
7286 	  gfc_add_expr_to_block (&se->pre, tmp);
7287 
7288 	  /* Finally free the temporary's data field.  */
7289 	  tmp = gfc_conv_descriptor_data_get (tmp2);
7290 	  tmp = gfc_deallocate_with_status (tmp, NULL_TREE, NULL_TREE,
7291 					    NULL_TREE, NULL_TREE, true,
7292 					    NULL, GFC_CAF_COARRAY_NOCOARRAY);
7293 	  gfc_add_expr_to_block (&se->pre, tmp);
7294 	}
7295     }
7296   else
7297     {
7298       /* For a function with a class array result, save the result as
7299 	 a temporary, set the info fields needed by the scalarizer and
7300 	 call the finalization function of the temporary. Note that the
7301 	 nullification of allocatable components needed by the result
7302 	 is done in gfc_trans_assignment_1.  */
7303       if (expr && ((gfc_is_class_array_function (expr)
7304 		    && se->ss && se->ss->loop)
7305 		   || gfc_is_alloc_class_scalar_function (expr))
7306 	  && se->expr && GFC_CLASS_TYPE_P (TREE_TYPE (se->expr))
7307 	  && expr->must_finalize)
7308 	{
7309 	  tree final_fndecl;
7310 	  tree is_final;
7311 	  int n;
7312 	  if (se->ss && se->ss->loop)
7313 	    {
7314 	      gfc_add_block_to_block (&se->ss->loop->pre, &se->pre);
7315 	      se->expr = gfc_evaluate_now (se->expr, &se->ss->loop->pre);
7316 	      tmp = gfc_class_data_get (se->expr);
7317 	      info->descriptor = tmp;
7318 	      info->data = gfc_conv_descriptor_data_get (tmp);
7319 	      info->offset = gfc_conv_descriptor_offset_get (tmp);
7320 	      for (n = 0; n < se->ss->loop->dimen; n++)
7321 		{
7322 		  tree dim = gfc_rank_cst[n];
7323 		  se->ss->loop->to[n] = gfc_conv_descriptor_ubound_get (tmp, dim);
7324 		  se->ss->loop->from[n] = gfc_conv_descriptor_lbound_get (tmp, dim);
7325 		}
7326 	    }
7327 	  else
7328 	    {
7329 	      /* TODO Eliminate the doubling of temporaries. This
7330 		 one is necessary to ensure no memory leakage.  */
7331 	      se->expr = gfc_evaluate_now (se->expr, &se->pre);
7332 	      tmp = gfc_class_data_get (se->expr);
7333 	      tmp = gfc_conv_scalar_to_descriptor (se, tmp,
7334 			CLASS_DATA (expr->value.function.esym->result)->attr);
7335 	    }
7336 
7337 	  if ((gfc_is_class_array_function (expr)
7338 	       || gfc_is_alloc_class_scalar_function (expr))
7339 	      && CLASS_DATA (expr->value.function.esym->result)->attr.pointer)
7340 	    goto no_finalization;
7341 
7342 	  final_fndecl = gfc_class_vtab_final_get (se->expr);
7343 	  is_final = fold_build2_loc (input_location, NE_EXPR,
7344 				      logical_type_node,
7345 				      final_fndecl,
7346 				      fold_convert (TREE_TYPE (final_fndecl),
7347 					   	    null_pointer_node));
7348 	  final_fndecl = build_fold_indirect_ref_loc (input_location,
7349 						      final_fndecl);
7350  	  tmp = build_call_expr_loc (input_location,
7351 				     final_fndecl, 3,
7352 				     gfc_build_addr_expr (NULL, tmp),
7353 				     gfc_class_vtab_size_get (se->expr),
7354 				     boolean_false_node);
7355 	  tmp = fold_build3_loc (input_location, COND_EXPR,
7356 				 void_type_node, is_final, tmp,
7357 				 build_empty_stmt (input_location));
7358 
7359 	  if (se->ss && se->ss->loop)
7360 	    {
7361 	      gfc_prepend_expr_to_block (&se->ss->loop->post, tmp);
7362 	      tmp = fold_build2_loc (input_location, NE_EXPR,
7363 				     logical_type_node,
7364 				     info->data,
7365 				     fold_convert (TREE_TYPE (info->data),
7366 					   	    null_pointer_node));
7367 	      tmp = fold_build3_loc (input_location, COND_EXPR,
7368 				     void_type_node, tmp,
7369 				     gfc_call_free (info->data),
7370 				     build_empty_stmt (input_location));
7371 	      gfc_add_expr_to_block (&se->ss->loop->post, tmp);
7372 	    }
7373 	  else
7374 	    {
7375 	      tree classdata;
7376 	      gfc_prepend_expr_to_block (&se->post, tmp);
7377 	      classdata = gfc_class_data_get (se->expr);
7378 	      tmp = fold_build2_loc (input_location, NE_EXPR,
7379 				     logical_type_node,
7380 				     classdata,
7381 				     fold_convert (TREE_TYPE (classdata),
7382 					   	    null_pointer_node));
7383 	      tmp = fold_build3_loc (input_location, COND_EXPR,
7384 				     void_type_node, tmp,
7385 				     gfc_call_free (classdata),
7386 				     build_empty_stmt (input_location));
7387 	      gfc_add_expr_to_block (&se->post, tmp);
7388 	    }
7389 	}
7390 
7391 no_finalization:
7392       gfc_add_block_to_block (&se->post, &post);
7393     }
7394 
7395   return has_alternate_specifier;
7396 }
7397 
7398 
7399 /* Fill a character string with spaces.  */
7400 
7401 static tree
7402 fill_with_spaces (tree start, tree type, tree size)
7403 {
7404   stmtblock_t block, loop;
7405   tree i, el, exit_label, cond, tmp;
7406 
7407   /* For a simple char type, we can call memset().  */
7408   if (compare_tree_int (TYPE_SIZE_UNIT (type), 1) == 0)
7409     return build_call_expr_loc (input_location,
7410 			    builtin_decl_explicit (BUILT_IN_MEMSET),
7411 			    3, start,
7412 			    build_int_cst (gfc_get_int_type (gfc_c_int_kind),
7413 					   lang_hooks.to_target_charset (' ')),
7414 				fold_convert (size_type_node, size));
7415 
7416   /* Otherwise, we use a loop:
7417 	for (el = start, i = size; i > 0; el--, i+= TYPE_SIZE_UNIT (type))
7418 	  *el = (type) ' ';
7419    */
7420 
7421   /* Initialize variables.  */
7422   gfc_init_block (&block);
7423   i = gfc_create_var (sizetype, "i");
7424   gfc_add_modify (&block, i, fold_convert (sizetype, size));
7425   el = gfc_create_var (build_pointer_type (type), "el");
7426   gfc_add_modify (&block, el, fold_convert (TREE_TYPE (el), start));
7427   exit_label = gfc_build_label_decl (NULL_TREE);
7428   TREE_USED (exit_label) = 1;
7429 
7430 
7431   /* Loop body.  */
7432   gfc_init_block (&loop);
7433 
7434   /* Exit condition.  */
7435   cond = fold_build2_loc (input_location, LE_EXPR, logical_type_node, i,
7436 			  build_zero_cst (sizetype));
7437   tmp = build1_v (GOTO_EXPR, exit_label);
7438   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, tmp,
7439 			 build_empty_stmt (input_location));
7440   gfc_add_expr_to_block (&loop, tmp);
7441 
7442   /* Assignment.  */
7443   gfc_add_modify (&loop,
7444 		  fold_build1_loc (input_location, INDIRECT_REF, type, el),
7445 		  build_int_cst (type, lang_hooks.to_target_charset (' ')));
7446 
7447   /* Increment loop variables.  */
7448   gfc_add_modify (&loop, i,
7449 		  fold_build2_loc (input_location, MINUS_EXPR, sizetype, i,
7450 				   TYPE_SIZE_UNIT (type)));
7451   gfc_add_modify (&loop, el,
7452 		  fold_build_pointer_plus_loc (input_location,
7453 					       el, TYPE_SIZE_UNIT (type)));
7454 
7455   /* Making the loop... actually loop!  */
7456   tmp = gfc_finish_block (&loop);
7457   tmp = build1_v (LOOP_EXPR, tmp);
7458   gfc_add_expr_to_block (&block, tmp);
7459 
7460   /* The exit label.  */
7461   tmp = build1_v (LABEL_EXPR, exit_label);
7462   gfc_add_expr_to_block (&block, tmp);
7463 
7464 
7465   return gfc_finish_block (&block);
7466 }
7467 
7468 
7469 /* Generate code to copy a string.  */
7470 
7471 void
7472 gfc_trans_string_copy (stmtblock_t * block, tree dlength, tree dest,
7473 		       int dkind, tree slength, tree src, int skind)
7474 {
7475   tree tmp, dlen, slen;
7476   tree dsc;
7477   tree ssc;
7478   tree cond;
7479   tree cond2;
7480   tree tmp2;
7481   tree tmp3;
7482   tree tmp4;
7483   tree chartype;
7484   stmtblock_t tempblock;
7485 
7486   gcc_assert (dkind == skind);
7487 
7488   if (slength != NULL_TREE)
7489     {
7490       slen = gfc_evaluate_now (fold_convert (gfc_charlen_type_node, slength), block);
7491       ssc = gfc_string_to_single_character (slen, src, skind);
7492     }
7493   else
7494     {
7495       slen = build_one_cst (gfc_charlen_type_node);
7496       ssc =  src;
7497     }
7498 
7499   if (dlength != NULL_TREE)
7500     {
7501       dlen = gfc_evaluate_now (fold_convert (gfc_charlen_type_node, dlength), block);
7502       dsc = gfc_string_to_single_character (dlen, dest, dkind);
7503     }
7504   else
7505     {
7506       dlen = build_one_cst (gfc_charlen_type_node);
7507       dsc =  dest;
7508     }
7509 
7510   /* Assign directly if the types are compatible.  */
7511   if (dsc != NULL_TREE && ssc != NULL_TREE
7512       && TREE_TYPE (dsc) == TREE_TYPE (ssc))
7513     {
7514       gfc_add_modify (block, dsc, ssc);
7515       return;
7516     }
7517 
7518   /* The string copy algorithm below generates code like
7519 
7520      if (destlen > 0)
7521        {
7522          if (srclen < destlen)
7523            {
7524              memmove (dest, src, srclen);
7525              // Pad with spaces.
7526              memset (&dest[srclen], ' ', destlen - srclen);
7527            }
7528          else
7529            {
7530              // Truncate if too long.
7531              memmove (dest, src, destlen);
7532            }
7533        }
7534   */
7535 
7536   /* Do nothing if the destination length is zero.  */
7537   cond = fold_build2_loc (input_location, GT_EXPR, logical_type_node, dlen,
7538 			  build_zero_cst (TREE_TYPE (dlen)));
7539 
7540   /* For non-default character kinds, we have to multiply the string
7541      length by the base type size.  */
7542   chartype = gfc_get_char_type (dkind);
7543   slen = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (slen),
7544 			  slen,
7545 			  fold_convert (TREE_TYPE (slen),
7546 					TYPE_SIZE_UNIT (chartype)));
7547   dlen = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (dlen),
7548 			  dlen,
7549 			  fold_convert (TREE_TYPE (dlen),
7550 					TYPE_SIZE_UNIT (chartype)));
7551 
7552   if (dlength && POINTER_TYPE_P (TREE_TYPE (dest)))
7553     dest = fold_convert (pvoid_type_node, dest);
7554   else
7555     dest = gfc_build_addr_expr (pvoid_type_node, dest);
7556 
7557   if (slength && POINTER_TYPE_P (TREE_TYPE (src)))
7558     src = fold_convert (pvoid_type_node, src);
7559   else
7560     src = gfc_build_addr_expr (pvoid_type_node, src);
7561 
7562   /* Truncate string if source is too long.  */
7563   cond2 = fold_build2_loc (input_location, LT_EXPR, logical_type_node, slen,
7564 			   dlen);
7565 
7566   /* Copy and pad with spaces.  */
7567   tmp3 = build_call_expr_loc (input_location,
7568 			      builtin_decl_explicit (BUILT_IN_MEMMOVE),
7569 			      3, dest, src,
7570 			      fold_convert (size_type_node, slen));
7571 
7572   /* Wstringop-overflow appears at -O3 even though this warning is not
7573      explicitly available in fortran nor can it be switched off. If the
7574      source length is a constant, its negative appears as a very large
7575      postive number and triggers the warning in BUILTIN_MEMSET. Fixing
7576      the result of the MINUS_EXPR suppresses this spurious warning.  */
7577   tmp = fold_build2_loc (input_location, MINUS_EXPR,
7578 			 TREE_TYPE(dlen), dlen, slen);
7579   if (slength && TREE_CONSTANT (slength))
7580     tmp = gfc_evaluate_now (tmp, block);
7581 
7582   tmp4 = fold_build_pointer_plus_loc (input_location, dest, slen);
7583   tmp4 = fill_with_spaces (tmp4, chartype, tmp);
7584 
7585   gfc_init_block (&tempblock);
7586   gfc_add_expr_to_block (&tempblock, tmp3);
7587   gfc_add_expr_to_block (&tempblock, tmp4);
7588   tmp3 = gfc_finish_block (&tempblock);
7589 
7590   /* The truncated memmove if the slen >= dlen.  */
7591   tmp2 = build_call_expr_loc (input_location,
7592 			      builtin_decl_explicit (BUILT_IN_MEMMOVE),
7593 			      3, dest, src,
7594 			      fold_convert (size_type_node, dlen));
7595 
7596   /* The whole copy_string function is there.  */
7597   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond2,
7598 			 tmp3, tmp2);
7599   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, tmp,
7600 			 build_empty_stmt (input_location));
7601   gfc_add_expr_to_block (block, tmp);
7602 }
7603 
7604 
7605 /* Translate a statement function.
7606    The value of a statement function reference is obtained by evaluating the
7607    expression using the values of the actual arguments for the values of the
7608    corresponding dummy arguments.  */
7609 
7610 static void
7611 gfc_conv_statement_function (gfc_se * se, gfc_expr * expr)
7612 {
7613   gfc_symbol *sym;
7614   gfc_symbol *fsym;
7615   gfc_formal_arglist *fargs;
7616   gfc_actual_arglist *args;
7617   gfc_se lse;
7618   gfc_se rse;
7619   gfc_saved_var *saved_vars;
7620   tree *temp_vars;
7621   tree type;
7622   tree tmp;
7623   int n;
7624 
7625   sym = expr->symtree->n.sym;
7626   args = expr->value.function.actual;
7627   gfc_init_se (&lse, NULL);
7628   gfc_init_se (&rse, NULL);
7629 
7630   n = 0;
7631   for (fargs = gfc_sym_get_dummy_args (sym); fargs; fargs = fargs->next)
7632     n++;
7633   saved_vars = XCNEWVEC (gfc_saved_var, n);
7634   temp_vars = XCNEWVEC (tree, n);
7635 
7636   for (fargs = gfc_sym_get_dummy_args (sym), n = 0; fargs;
7637        fargs = fargs->next, n++)
7638     {
7639       /* Each dummy shall be specified, explicitly or implicitly, to be
7640          scalar.  */
7641       gcc_assert (fargs->sym->attr.dimension == 0);
7642       fsym = fargs->sym;
7643 
7644       if (fsym->ts.type == BT_CHARACTER)
7645         {
7646 	  /* Copy string arguments.  */
7647 	  tree arglen;
7648 
7649 	  gcc_assert (fsym->ts.u.cl && fsym->ts.u.cl->length
7650 		      && fsym->ts.u.cl->length->expr_type == EXPR_CONSTANT);
7651 
7652 	  /* Create a temporary to hold the value.  */
7653           if (fsym->ts.u.cl->backend_decl == NULL_TREE)
7654 	     fsym->ts.u.cl->backend_decl
7655 		= gfc_conv_constant_to_tree (fsym->ts.u.cl->length);
7656 
7657 	  type = gfc_get_character_type (fsym->ts.kind, fsym->ts.u.cl);
7658 	  temp_vars[n] = gfc_create_var (type, fsym->name);
7659 
7660 	  arglen = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
7661 
7662 	  gfc_conv_expr (&rse, args->expr);
7663 	  gfc_conv_string_parameter (&rse);
7664 	  gfc_add_block_to_block (&se->pre, &lse.pre);
7665 	  gfc_add_block_to_block (&se->pre, &rse.pre);
7666 
7667 	  gfc_trans_string_copy (&se->pre, arglen, temp_vars[n], fsym->ts.kind,
7668 				 rse.string_length, rse.expr, fsym->ts.kind);
7669 	  gfc_add_block_to_block (&se->pre, &lse.post);
7670 	  gfc_add_block_to_block (&se->pre, &rse.post);
7671         }
7672       else
7673         {
7674           /* For everything else, just evaluate the expression.  */
7675 
7676 	  /* Create a temporary to hold the value.  */
7677 	  type = gfc_typenode_for_spec (&fsym->ts);
7678 	  temp_vars[n] = gfc_create_var (type, fsym->name);
7679 
7680           gfc_conv_expr (&lse, args->expr);
7681 
7682           gfc_add_block_to_block (&se->pre, &lse.pre);
7683           gfc_add_modify (&se->pre, temp_vars[n], lse.expr);
7684           gfc_add_block_to_block (&se->pre, &lse.post);
7685         }
7686 
7687       args = args->next;
7688     }
7689 
7690   /* Use the temporary variables in place of the real ones.  */
7691   for (fargs = gfc_sym_get_dummy_args (sym), n = 0; fargs;
7692        fargs = fargs->next, n++)
7693     gfc_shadow_sym (fargs->sym, temp_vars[n], &saved_vars[n]);
7694 
7695   gfc_conv_expr (se, sym->value);
7696 
7697   if (sym->ts.type == BT_CHARACTER)
7698     {
7699       gfc_conv_const_charlen (sym->ts.u.cl);
7700 
7701       /* Force the expression to the correct length.  */
7702       if (!INTEGER_CST_P (se->string_length)
7703 	  || tree_int_cst_lt (se->string_length,
7704 			      sym->ts.u.cl->backend_decl))
7705 	{
7706 	  type = gfc_get_character_type (sym->ts.kind, sym->ts.u.cl);
7707 	  tmp = gfc_create_var (type, sym->name);
7708 	  tmp = gfc_build_addr_expr (build_pointer_type (type), tmp);
7709 	  gfc_trans_string_copy (&se->pre, sym->ts.u.cl->backend_decl, tmp,
7710 				 sym->ts.kind, se->string_length, se->expr,
7711 				 sym->ts.kind);
7712 	  se->expr = tmp;
7713 	}
7714       se->string_length = sym->ts.u.cl->backend_decl;
7715     }
7716 
7717   /* Restore the original variables.  */
7718   for (fargs = gfc_sym_get_dummy_args (sym), n = 0; fargs;
7719        fargs = fargs->next, n++)
7720     gfc_restore_sym (fargs->sym, &saved_vars[n]);
7721   free (temp_vars);
7722   free (saved_vars);
7723 }
7724 
7725 
7726 /* Translate a function expression.  */
7727 
7728 static void
7729 gfc_conv_function_expr (gfc_se * se, gfc_expr * expr)
7730 {
7731   gfc_symbol *sym;
7732 
7733   if (expr->value.function.isym)
7734     {
7735       gfc_conv_intrinsic_function (se, expr);
7736       return;
7737     }
7738 
7739   /* expr.value.function.esym is the resolved (specific) function symbol for
7740      most functions.  However this isn't set for dummy procedures.  */
7741   sym = expr->value.function.esym;
7742   if (!sym)
7743     sym = expr->symtree->n.sym;
7744 
7745   /* The IEEE_ARITHMETIC functions are caught here. */
7746   if (sym->from_intmod == INTMOD_IEEE_ARITHMETIC)
7747     if (gfc_conv_ieee_arithmetic_function (se, expr))
7748       return;
7749 
7750   /* We distinguish statement functions from general functions to improve
7751      runtime performance.  */
7752   if (sym->attr.proc == PROC_ST_FUNCTION)
7753     {
7754       gfc_conv_statement_function (se, expr);
7755       return;
7756     }
7757 
7758   gfc_conv_procedure_call (se, sym, expr->value.function.actual, expr,
7759 			   NULL);
7760 }
7761 
7762 
7763 /* Determine whether the given EXPR_CONSTANT is a zero initializer.  */
7764 
7765 static bool
7766 is_zero_initializer_p (gfc_expr * expr)
7767 {
7768   if (expr->expr_type != EXPR_CONSTANT)
7769     return false;
7770 
7771   /* We ignore constants with prescribed memory representations for now.  */
7772   if (expr->representation.string)
7773     return false;
7774 
7775   switch (expr->ts.type)
7776     {
7777     case BT_INTEGER:
7778       return mpz_cmp_si (expr->value.integer, 0) == 0;
7779 
7780     case BT_REAL:
7781       return mpfr_zero_p (expr->value.real)
7782 	     && MPFR_SIGN (expr->value.real) >= 0;
7783 
7784     case BT_LOGICAL:
7785       return expr->value.logical == 0;
7786 
7787     case BT_COMPLEX:
7788       return mpfr_zero_p (mpc_realref (expr->value.complex))
7789 	     && MPFR_SIGN (mpc_realref (expr->value.complex)) >= 0
7790              && mpfr_zero_p (mpc_imagref (expr->value.complex))
7791 	     && MPFR_SIGN (mpc_imagref (expr->value.complex)) >= 0;
7792 
7793     default:
7794       break;
7795     }
7796   return false;
7797 }
7798 
7799 
7800 static void
7801 gfc_conv_array_constructor_expr (gfc_se * se, gfc_expr * expr)
7802 {
7803   gfc_ss *ss;
7804 
7805   ss = se->ss;
7806   gcc_assert (ss != NULL && ss != gfc_ss_terminator);
7807   gcc_assert (ss->info->expr == expr && ss->info->type == GFC_SS_CONSTRUCTOR);
7808 
7809   gfc_conv_tmp_array_ref (se);
7810 }
7811 
7812 
7813 /* Build a static initializer.  EXPR is the expression for the initial value.
7814    The other parameters describe the variable of the component being
7815    initialized. EXPR may be null.  */
7816 
7817 tree
7818 gfc_conv_initializer (gfc_expr * expr, gfc_typespec * ts, tree type,
7819 		      bool array, bool pointer, bool procptr)
7820 {
7821   gfc_se se;
7822 
7823   if (flag_coarray != GFC_FCOARRAY_LIB && ts->type == BT_DERIVED
7824       && ts->u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
7825       && ts->u.derived->intmod_sym_id == ISOFORTRAN_EVENT_TYPE)
7826     return build_constructor (type, NULL);
7827 
7828   if (!(expr || pointer || procptr))
7829     return NULL_TREE;
7830 
7831   /* Check if we have ISOCBINDING_NULL_PTR or ISOCBINDING_NULL_FUNPTR
7832      (these are the only two iso_c_binding derived types that can be
7833      used as initialization expressions).  If so, we need to modify
7834      the 'expr' to be that for a (void *).  */
7835   if (expr != NULL && expr->ts.type == BT_DERIVED
7836       && expr->ts.is_iso_c && expr->ts.u.derived)
7837     {
7838       if (TREE_CODE (type) == ARRAY_TYPE)
7839 	return build_constructor (type, NULL);
7840       else if (POINTER_TYPE_P (type))
7841 	return build_int_cst (type, 0);
7842       else
7843 	gcc_unreachable ();
7844     }
7845 
7846   if (array && !procptr)
7847     {
7848       tree ctor;
7849       /* Arrays need special handling.  */
7850       if (pointer)
7851 	ctor = gfc_build_null_descriptor (type);
7852       /* Special case assigning an array to zero.  */
7853       else if (is_zero_initializer_p (expr))
7854         ctor = build_constructor (type, NULL);
7855       else
7856 	ctor = gfc_conv_array_initializer (type, expr);
7857       TREE_STATIC (ctor) = 1;
7858       return ctor;
7859     }
7860   else if (pointer || procptr)
7861     {
7862       if (ts->type == BT_CLASS && !procptr)
7863 	{
7864 	  gfc_init_se (&se, NULL);
7865 	  gfc_conv_structure (&se, gfc_class_initializer (ts, expr), 1);
7866 	  gcc_assert (TREE_CODE (se.expr) == CONSTRUCTOR);
7867 	  TREE_STATIC (se.expr) = 1;
7868 	  return se.expr;
7869 	}
7870       else if (!expr || expr->expr_type == EXPR_NULL)
7871 	return fold_convert (type, null_pointer_node);
7872       else
7873 	{
7874 	  gfc_init_se (&se, NULL);
7875 	  se.want_pointer = 1;
7876 	  gfc_conv_expr (&se, expr);
7877           gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
7878 	  return se.expr;
7879 	}
7880     }
7881   else
7882     {
7883       switch (ts->type)
7884 	{
7885 	case_bt_struct:
7886 	case BT_CLASS:
7887 	  gfc_init_se (&se, NULL);
7888 	  if (ts->type == BT_CLASS && expr->expr_type == EXPR_NULL)
7889 	    gfc_conv_structure (&se, gfc_class_initializer (ts, expr), 1);
7890 	  else
7891 	    gfc_conv_structure (&se, expr, 1);
7892 	  gcc_assert (TREE_CODE (se.expr) == CONSTRUCTOR);
7893 	  TREE_STATIC (se.expr) = 1;
7894 	  return se.expr;
7895 
7896 	case BT_CHARACTER:
7897 	  if (expr->expr_type == EXPR_CONSTANT)
7898 	    {
7899 	      tree ctor = gfc_conv_string_init (ts->u.cl->backend_decl, expr);
7900 	      TREE_STATIC (ctor) = 1;
7901 	      return ctor;
7902 	    }
7903 
7904 	  /* Fallthrough.  */
7905 	default:
7906 	  gfc_init_se (&se, NULL);
7907 	  gfc_conv_constant (&se, expr);
7908 	  gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
7909 	  return se.expr;
7910 	}
7911     }
7912 }
7913 
7914 static tree
7915 gfc_trans_subarray_assign (tree dest, gfc_component * cm, gfc_expr * expr)
7916 {
7917   gfc_se rse;
7918   gfc_se lse;
7919   gfc_ss *rss;
7920   gfc_ss *lss;
7921   gfc_array_info *lss_array;
7922   stmtblock_t body;
7923   stmtblock_t block;
7924   gfc_loopinfo loop;
7925   int n;
7926   tree tmp;
7927 
7928   gfc_start_block (&block);
7929 
7930   /* Initialize the scalarizer.  */
7931   gfc_init_loopinfo (&loop);
7932 
7933   gfc_init_se (&lse, NULL);
7934   gfc_init_se (&rse, NULL);
7935 
7936   /* Walk the rhs.  */
7937   rss = gfc_walk_expr (expr);
7938   if (rss == gfc_ss_terminator)
7939     /* The rhs is scalar.  Add a ss for the expression.  */
7940     rss = gfc_get_scalar_ss (gfc_ss_terminator, expr);
7941 
7942   /* Create a SS for the destination.  */
7943   lss = gfc_get_array_ss (gfc_ss_terminator, NULL, cm->as->rank,
7944 			  GFC_SS_COMPONENT);
7945   lss_array = &lss->info->data.array;
7946   lss_array->shape = gfc_get_shape (cm->as->rank);
7947   lss_array->descriptor = dest;
7948   lss_array->data = gfc_conv_array_data (dest);
7949   lss_array->offset = gfc_conv_array_offset (dest);
7950   for (n = 0; n < cm->as->rank; n++)
7951     {
7952       lss_array->start[n] = gfc_conv_array_lbound (dest, n);
7953       lss_array->stride[n] = gfc_index_one_node;
7954 
7955       mpz_init (lss_array->shape[n]);
7956       mpz_sub (lss_array->shape[n], cm->as->upper[n]->value.integer,
7957 	       cm->as->lower[n]->value.integer);
7958       mpz_add_ui (lss_array->shape[n], lss_array->shape[n], 1);
7959     }
7960 
7961   /* Associate the SS with the loop.  */
7962   gfc_add_ss_to_loop (&loop, lss);
7963   gfc_add_ss_to_loop (&loop, rss);
7964 
7965   /* Calculate the bounds of the scalarization.  */
7966   gfc_conv_ss_startstride (&loop);
7967 
7968   /* Setup the scalarizing loops.  */
7969   gfc_conv_loop_setup (&loop, &expr->where);
7970 
7971   /* Setup the gfc_se structures.  */
7972   gfc_copy_loopinfo_to_se (&lse, &loop);
7973   gfc_copy_loopinfo_to_se (&rse, &loop);
7974 
7975   rse.ss = rss;
7976   gfc_mark_ss_chain_used (rss, 1);
7977   lse.ss = lss;
7978   gfc_mark_ss_chain_used (lss, 1);
7979 
7980   /* Start the scalarized loop body.  */
7981   gfc_start_scalarized_body (&loop, &body);
7982 
7983   gfc_conv_tmp_array_ref (&lse);
7984   if (cm->ts.type == BT_CHARACTER)
7985     lse.string_length = cm->ts.u.cl->backend_decl;
7986 
7987   gfc_conv_expr (&rse, expr);
7988 
7989   tmp = gfc_trans_scalar_assign (&lse, &rse, cm->ts, true, false);
7990   gfc_add_expr_to_block (&body, tmp);
7991 
7992   gcc_assert (rse.ss == gfc_ss_terminator);
7993 
7994   /* Generate the copying loops.  */
7995   gfc_trans_scalarizing_loops (&loop, &body);
7996 
7997   /* Wrap the whole thing up.  */
7998   gfc_add_block_to_block (&block, &loop.pre);
7999   gfc_add_block_to_block (&block, &loop.post);
8000 
8001   gcc_assert (lss_array->shape != NULL);
8002   gfc_free_shape (&lss_array->shape, cm->as->rank);
8003   gfc_cleanup_loop (&loop);
8004 
8005   return gfc_finish_block (&block);
8006 }
8007 
8008 
8009 static tree
8010 gfc_trans_alloc_subarray_assign (tree dest, gfc_component * cm,
8011 				 gfc_expr * expr)
8012 {
8013   gfc_se se;
8014   stmtblock_t block;
8015   tree offset;
8016   int n;
8017   tree tmp;
8018   tree tmp2;
8019   gfc_array_spec *as;
8020   gfc_expr *arg = NULL;
8021 
8022   gfc_start_block (&block);
8023   gfc_init_se (&se, NULL);
8024 
8025   /* Get the descriptor for the expressions.  */
8026   se.want_pointer = 0;
8027   gfc_conv_expr_descriptor (&se, expr);
8028   gfc_add_block_to_block (&block, &se.pre);
8029   gfc_add_modify (&block, dest, se.expr);
8030 
8031   /* Deal with arrays of derived types with allocatable components.  */
8032   if (gfc_bt_struct (cm->ts.type)
8033 	&& cm->ts.u.derived->attr.alloc_comp)
8034     // TODO: Fix caf_mode
8035     tmp = gfc_copy_alloc_comp (cm->ts.u.derived,
8036 			       se.expr, dest,
8037 			       cm->as->rank, 0);
8038   else if (cm->ts.type == BT_CLASS && expr->ts.type == BT_DERIVED
8039 	   && CLASS_DATA(cm)->attr.allocatable)
8040     {
8041       if (cm->ts.u.derived->attr.alloc_comp)
8042 	// TODO: Fix caf_mode
8043 	tmp = gfc_copy_alloc_comp (expr->ts.u.derived,
8044 				   se.expr, dest,
8045 				   expr->rank, 0);
8046       else
8047 	{
8048 	  tmp = TREE_TYPE (dest);
8049 	  tmp = gfc_duplicate_allocatable (dest, se.expr,
8050 					   tmp, expr->rank, NULL_TREE);
8051 	}
8052     }
8053   else
8054     tmp = gfc_duplicate_allocatable (dest, se.expr,
8055 				     TREE_TYPE(cm->backend_decl),
8056 				     cm->as->rank, NULL_TREE);
8057 
8058   gfc_add_expr_to_block (&block, tmp);
8059   gfc_add_block_to_block (&block, &se.post);
8060 
8061   if (expr->expr_type != EXPR_VARIABLE)
8062     gfc_conv_descriptor_data_set (&block, se.expr,
8063 				  null_pointer_node);
8064 
8065   /* We need to know if the argument of a conversion function is a
8066      variable, so that the correct lower bound can be used.  */
8067   if (expr->expr_type == EXPR_FUNCTION
8068 	&& expr->value.function.isym
8069 	&& expr->value.function.isym->conversion
8070 	&& expr->value.function.actual->expr
8071 	&& expr->value.function.actual->expr->expr_type == EXPR_VARIABLE)
8072     arg = expr->value.function.actual->expr;
8073 
8074   /* Obtain the array spec of full array references.  */
8075   if (arg)
8076     as = gfc_get_full_arrayspec_from_expr (arg);
8077   else
8078     as = gfc_get_full_arrayspec_from_expr (expr);
8079 
8080   /* Shift the lbound and ubound of temporaries to being unity,
8081      rather than zero, based. Always calculate the offset.  */
8082   offset = gfc_conv_descriptor_offset_get (dest);
8083   gfc_add_modify (&block, offset, gfc_index_zero_node);
8084   tmp2 =gfc_create_var (gfc_array_index_type, NULL);
8085 
8086   for (n = 0; n < expr->rank; n++)
8087     {
8088       tree span;
8089       tree lbound;
8090 
8091       /* Obtain the correct lbound - ISO/IEC TR 15581:2001 page 9.
8092 	 TODO It looks as if gfc_conv_expr_descriptor should return
8093 	 the correct bounds and that the following should not be
8094 	 necessary.  This would simplify gfc_conv_intrinsic_bound
8095 	 as well.  */
8096       if (as && as->lower[n])
8097 	{
8098 	  gfc_se lbse;
8099 	  gfc_init_se (&lbse, NULL);
8100 	  gfc_conv_expr (&lbse, as->lower[n]);
8101 	  gfc_add_block_to_block (&block, &lbse.pre);
8102 	  lbound = gfc_evaluate_now (lbse.expr, &block);
8103 	}
8104       else if (as && arg)
8105 	{
8106 	  tmp = gfc_get_symbol_decl (arg->symtree->n.sym);
8107 	  lbound = gfc_conv_descriptor_lbound_get (tmp,
8108 					gfc_rank_cst[n]);
8109 	}
8110       else if (as)
8111 	lbound = gfc_conv_descriptor_lbound_get (dest,
8112 						gfc_rank_cst[n]);
8113       else
8114 	lbound = gfc_index_one_node;
8115 
8116       lbound = fold_convert (gfc_array_index_type, lbound);
8117 
8118       /* Shift the bounds and set the offset accordingly.  */
8119       tmp = gfc_conv_descriptor_ubound_get (dest, gfc_rank_cst[n]);
8120       span = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
8121 		tmp, gfc_conv_descriptor_lbound_get (dest, gfc_rank_cst[n]));
8122       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
8123 			     span, lbound);
8124       gfc_conv_descriptor_ubound_set (&block, dest,
8125 				      gfc_rank_cst[n], tmp);
8126       gfc_conv_descriptor_lbound_set (&block, dest,
8127 				      gfc_rank_cst[n], lbound);
8128 
8129       tmp = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
8130 			 gfc_conv_descriptor_lbound_get (dest,
8131 							 gfc_rank_cst[n]),
8132 			 gfc_conv_descriptor_stride_get (dest,
8133 							 gfc_rank_cst[n]));
8134       gfc_add_modify (&block, tmp2, tmp);
8135       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
8136 			     offset, tmp2);
8137       gfc_conv_descriptor_offset_set (&block, dest, tmp);
8138     }
8139 
8140   if (arg)
8141     {
8142       /* If a conversion expression has a null data pointer
8143 	 argument, nullify the allocatable component.  */
8144       tree non_null_expr;
8145       tree null_expr;
8146 
8147       if (arg->symtree->n.sym->attr.allocatable
8148 	    || arg->symtree->n.sym->attr.pointer)
8149 	{
8150 	  non_null_expr = gfc_finish_block (&block);
8151 	  gfc_start_block (&block);
8152 	  gfc_conv_descriptor_data_set (&block, dest,
8153 					null_pointer_node);
8154 	  null_expr = gfc_finish_block (&block);
8155 	  tmp = gfc_conv_descriptor_data_get (arg->symtree->n.sym->backend_decl);
8156 	  tmp = build2_loc (input_location, EQ_EXPR, logical_type_node, tmp,
8157 			    fold_convert (TREE_TYPE (tmp), null_pointer_node));
8158 	  return build3_v (COND_EXPR, tmp,
8159 			   null_expr, non_null_expr);
8160 	}
8161     }
8162 
8163   return gfc_finish_block (&block);
8164 }
8165 
8166 
8167 /* Allocate or reallocate scalar component, as necessary.  */
8168 
8169 static void
8170 alloc_scalar_allocatable_for_subcomponent_assignment (stmtblock_t *block,
8171 						      tree comp,
8172 						      gfc_component *cm,
8173 						      gfc_expr *expr2,
8174 						      gfc_symbol *sym)
8175 {
8176   tree tmp;
8177   tree ptr;
8178   tree size;
8179   tree size_in_bytes;
8180   tree lhs_cl_size = NULL_TREE;
8181 
8182   if (!comp)
8183     return;
8184 
8185   if (!expr2 || expr2->rank)
8186     return;
8187 
8188   realloc_lhs_warning (expr2->ts.type, false, &expr2->where);
8189 
8190   if (cm->ts.type == BT_CHARACTER && cm->ts.deferred)
8191     {
8192       char name[GFC_MAX_SYMBOL_LEN+9];
8193       gfc_component *strlen;
8194       /* Use the rhs string length and the lhs element size.  */
8195       gcc_assert (expr2->ts.type == BT_CHARACTER);
8196       if (!expr2->ts.u.cl->backend_decl)
8197 	{
8198 	  gfc_conv_string_length (expr2->ts.u.cl, expr2, block);
8199 	  gcc_assert (expr2->ts.u.cl->backend_decl);
8200 	}
8201 
8202       size = expr2->ts.u.cl->backend_decl;
8203 
8204       /* Ensure that cm->ts.u.cl->backend_decl is a componentref to _%s_length
8205 	 component.  */
8206       sprintf (name, "_%s_length", cm->name);
8207       strlen = gfc_find_component (sym, name, true, true, NULL);
8208       lhs_cl_size = fold_build3_loc (input_location, COMPONENT_REF,
8209 				     gfc_charlen_type_node,
8210 				     TREE_OPERAND (comp, 0),
8211 				     strlen->backend_decl, NULL_TREE);
8212 
8213       tmp = TREE_TYPE (gfc_typenode_for_spec (&cm->ts));
8214       tmp = TYPE_SIZE_UNIT (tmp);
8215       size_in_bytes = fold_build2_loc (input_location, MULT_EXPR,
8216 				       TREE_TYPE (tmp), tmp,
8217 				       fold_convert (TREE_TYPE (tmp), size));
8218     }
8219   else if (cm->ts.type == BT_CLASS)
8220     {
8221       gcc_assert (expr2->ts.type == BT_CLASS || expr2->ts.type == BT_DERIVED);
8222       if (expr2->ts.type == BT_DERIVED)
8223 	{
8224 	  tmp = gfc_get_symbol_decl (expr2->ts.u.derived);
8225 	  size = TYPE_SIZE_UNIT (tmp);
8226 	}
8227       else
8228 	{
8229 	  gfc_expr *e2vtab;
8230 	  gfc_se se;
8231 	  e2vtab = gfc_find_and_cut_at_last_class_ref (expr2);
8232 	  gfc_add_vptr_component (e2vtab);
8233 	  gfc_add_size_component (e2vtab);
8234 	  gfc_init_se (&se, NULL);
8235 	  gfc_conv_expr (&se, e2vtab);
8236 	  gfc_add_block_to_block (block, &se.pre);
8237 	  size = fold_convert (size_type_node, se.expr);
8238 	  gfc_free_expr (e2vtab);
8239 	}
8240       size_in_bytes = size;
8241     }
8242   else
8243     {
8244       /* Otherwise use the length in bytes of the rhs.  */
8245       size = TYPE_SIZE_UNIT (gfc_typenode_for_spec (&cm->ts));
8246       size_in_bytes = size;
8247     }
8248 
8249   size_in_bytes = fold_build2_loc (input_location, MAX_EXPR, size_type_node,
8250 				   size_in_bytes, size_one_node);
8251 
8252   if (cm->ts.type == BT_DERIVED && cm->ts.u.derived->attr.alloc_comp)
8253     {
8254       tmp = build_call_expr_loc (input_location,
8255 				 builtin_decl_explicit (BUILT_IN_CALLOC),
8256 				 2, build_one_cst (size_type_node),
8257 				 size_in_bytes);
8258       tmp = fold_convert (TREE_TYPE (comp), tmp);
8259       gfc_add_modify (block, comp, tmp);
8260     }
8261   else
8262     {
8263       tmp = build_call_expr_loc (input_location,
8264 				 builtin_decl_explicit (BUILT_IN_MALLOC),
8265 				 1, size_in_bytes);
8266       if (GFC_CLASS_TYPE_P (TREE_TYPE (comp)))
8267 	ptr = gfc_class_data_get (comp);
8268       else
8269 	ptr = comp;
8270       tmp = fold_convert (TREE_TYPE (ptr), tmp);
8271       gfc_add_modify (block, ptr, tmp);
8272     }
8273 
8274   if (cm->ts.type == BT_CHARACTER && cm->ts.deferred)
8275     /* Update the lhs character length.  */
8276     gfc_add_modify (block, lhs_cl_size,
8277 		    fold_convert (TREE_TYPE (lhs_cl_size), size));
8278 }
8279 
8280 
8281 /* Assign a single component of a derived type constructor.  */
8282 
8283 static tree
8284 gfc_trans_subcomponent_assign (tree dest, gfc_component * cm, gfc_expr * expr,
8285 			       gfc_symbol *sym, bool init)
8286 {
8287   gfc_se se;
8288   gfc_se lse;
8289   stmtblock_t block;
8290   tree tmp;
8291   tree vtab;
8292 
8293   gfc_start_block (&block);
8294 
8295   if (cm->attr.pointer || cm->attr.proc_pointer)
8296     {
8297       /* Only care about pointers here, not about allocatables.  */
8298       gfc_init_se (&se, NULL);
8299       /* Pointer component.  */
8300       if ((cm->attr.dimension || cm->attr.codimension)
8301 	  && !cm->attr.proc_pointer)
8302 	{
8303 	  /* Array pointer.  */
8304 	  if (expr->expr_type == EXPR_NULL)
8305 	    gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
8306 	  else
8307 	    {
8308 	      se.direct_byref = 1;
8309 	      se.expr = dest;
8310 	      gfc_conv_expr_descriptor (&se, expr);
8311 	      gfc_add_block_to_block (&block, &se.pre);
8312 	      gfc_add_block_to_block (&block, &se.post);
8313 	    }
8314 	}
8315       else
8316 	{
8317 	  /* Scalar pointers.  */
8318 	  se.want_pointer = 1;
8319 	  gfc_conv_expr (&se, expr);
8320 	  gfc_add_block_to_block (&block, &se.pre);
8321 
8322 	  if (expr->symtree && expr->symtree->n.sym->attr.proc_pointer
8323 	      && expr->symtree->n.sym->attr.dummy)
8324 	    se.expr = build_fold_indirect_ref_loc (input_location, se.expr);
8325 
8326 	  gfc_add_modify (&block, dest,
8327 			       fold_convert (TREE_TYPE (dest), se.expr));
8328 	  gfc_add_block_to_block (&block, &se.post);
8329 	}
8330     }
8331   else if (cm->ts.type == BT_CLASS && expr->expr_type == EXPR_NULL)
8332     {
8333       /* NULL initialization for CLASS components.  */
8334       tmp = gfc_trans_structure_assign (dest,
8335 					gfc_class_initializer (&cm->ts, expr),
8336 					false);
8337       gfc_add_expr_to_block (&block, tmp);
8338     }
8339   else if ((cm->attr.dimension || cm->attr.codimension)
8340 	   && !cm->attr.proc_pointer)
8341     {
8342       if (cm->attr.allocatable && expr->expr_type == EXPR_NULL)
8343  	gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
8344       else if (cm->attr.allocatable || cm->attr.pdt_array)
8345 	{
8346 	  tmp = gfc_trans_alloc_subarray_assign (dest, cm, expr);
8347 	  gfc_add_expr_to_block (&block, tmp);
8348 	}
8349       else
8350 	{
8351 	  tmp = gfc_trans_subarray_assign (dest, cm, expr);
8352 	  gfc_add_expr_to_block (&block, tmp);
8353 	}
8354     }
8355   else if (cm->ts.type == BT_CLASS
8356 	   && CLASS_DATA (cm)->attr.dimension
8357 	   && CLASS_DATA (cm)->attr.allocatable
8358 	   && expr->ts.type == BT_DERIVED)
8359     {
8360       vtab = gfc_get_symbol_decl (gfc_find_vtab (&expr->ts));
8361       vtab = gfc_build_addr_expr (NULL_TREE, vtab);
8362       tmp = gfc_class_vptr_get (dest);
8363       gfc_add_modify (&block, tmp,
8364 		      fold_convert (TREE_TYPE (tmp), vtab));
8365       tmp = gfc_class_data_get (dest);
8366       tmp = gfc_trans_alloc_subarray_assign (tmp, cm, expr);
8367       gfc_add_expr_to_block (&block, tmp);
8368     }
8369   else if (init && cm->attr.allocatable && expr->expr_type == EXPR_NULL)
8370     {
8371       /* NULL initialization for allocatable components.  */
8372       gfc_add_modify (&block, dest, fold_convert (TREE_TYPE (dest),
8373 						  null_pointer_node));
8374     }
8375   else if (init && (cm->attr.allocatable
8376 	   || (cm->ts.type == BT_CLASS && CLASS_DATA (cm)->attr.allocatable
8377 	       && expr->ts.type != BT_CLASS)))
8378     {
8379       /* Take care about non-array allocatable components here.  The alloc_*
8380 	 routine below is motivated by the alloc_scalar_allocatable_for_
8381 	 assignment() routine, but with the realloc portions removed and
8382 	 different input.  */
8383       alloc_scalar_allocatable_for_subcomponent_assignment (&block,
8384 							    dest,
8385 							    cm,
8386 							    expr,
8387 							    sym);
8388       /* The remainder of these instructions follow the if (cm->attr.pointer)
8389 	 if (!cm->attr.dimension) part above.  */
8390       gfc_init_se (&se, NULL);
8391       gfc_conv_expr (&se, expr);
8392       gfc_add_block_to_block (&block, &se.pre);
8393 
8394       if (expr->symtree && expr->symtree->n.sym->attr.proc_pointer
8395 	  && expr->symtree->n.sym->attr.dummy)
8396 	se.expr = build_fold_indirect_ref_loc (input_location, se.expr);
8397 
8398       if (cm->ts.type == BT_CLASS && expr->ts.type == BT_DERIVED)
8399 	{
8400 	  tmp = gfc_class_data_get (dest);
8401 	  tmp = build_fold_indirect_ref_loc (input_location, tmp);
8402 	  vtab = gfc_get_symbol_decl (gfc_find_vtab (&expr->ts));
8403 	  vtab = gfc_build_addr_expr (NULL_TREE, vtab);
8404 	  gfc_add_modify (&block, gfc_class_vptr_get (dest),
8405 		 fold_convert (TREE_TYPE (gfc_class_vptr_get (dest)), vtab));
8406 	}
8407       else
8408 	tmp = build_fold_indirect_ref_loc (input_location, dest);
8409 
8410       /* For deferred strings insert a memcpy.  */
8411       if (cm->ts.type == BT_CHARACTER && cm->ts.deferred)
8412 	{
8413 	  tree size;
8414 	  gcc_assert (se.string_length || expr->ts.u.cl->backend_decl);
8415 	  size = size_of_string_in_bytes (cm->ts.kind, se.string_length
8416 						? se.string_length
8417 						: expr->ts.u.cl->backend_decl);
8418 	  tmp = gfc_build_memcpy_call (tmp, se.expr, size);
8419 	  gfc_add_expr_to_block (&block, tmp);
8420 	}
8421       else
8422 	gfc_add_modify (&block, tmp,
8423 			fold_convert (TREE_TYPE (tmp), se.expr));
8424       gfc_add_block_to_block (&block, &se.post);
8425     }
8426   else if (expr->ts.type == BT_UNION)
8427     {
8428       tree tmp;
8429       gfc_constructor *c = gfc_constructor_first (expr->value.constructor);
8430       /* We mark that the entire union should be initialized with a contrived
8431          EXPR_NULL expression at the beginning.  */
8432       if (c != NULL && c->n.component == NULL
8433 	  && c->expr != NULL && c->expr->expr_type == EXPR_NULL)
8434         {
8435           tmp = build2_loc (input_location, MODIFY_EXPR, void_type_node,
8436 		            dest, build_constructor (TREE_TYPE (dest), NULL));
8437 	  gfc_add_expr_to_block (&block, tmp);
8438           c = gfc_constructor_next (c);
8439         }
8440       /* The following constructor expression, if any, represents a specific
8441          map intializer, as given by the user.  */
8442       if (c != NULL && c->expr != NULL)
8443         {
8444           gcc_assert (expr->expr_type == EXPR_STRUCTURE);
8445 	  tmp = gfc_trans_structure_assign (dest, expr, expr->symtree != NULL);
8446 	  gfc_add_expr_to_block (&block, tmp);
8447         }
8448     }
8449   else if (expr->ts.type == BT_DERIVED && expr->ts.f90_type != BT_VOID)
8450     {
8451       if (expr->expr_type != EXPR_STRUCTURE)
8452 	{
8453 	  tree dealloc = NULL_TREE;
8454 	  gfc_init_se (&se, NULL);
8455 	  gfc_conv_expr (&se, expr);
8456 	  gfc_add_block_to_block (&block, &se.pre);
8457 	  /* Prevent repeat evaluations in gfc_copy_alloc_comp by fixing the
8458 	     expression in  a temporary variable and deallocate the allocatable
8459 	     components. Then we can the copy the expression to the result.  */
8460 	  if (cm->ts.u.derived->attr.alloc_comp
8461 	      && expr->expr_type != EXPR_VARIABLE)
8462 	    {
8463 	      se.expr = gfc_evaluate_now (se.expr, &block);
8464 	      dealloc = gfc_deallocate_alloc_comp (cm->ts.u.derived, se.expr,
8465 						   expr->rank);
8466 	    }
8467 	  gfc_add_modify (&block, dest,
8468 			  fold_convert (TREE_TYPE (dest), se.expr));
8469 	  if (cm->ts.u.derived->attr.alloc_comp
8470 	      && expr->expr_type != EXPR_NULL)
8471 	    {
8472 	      // TODO: Fix caf_mode
8473 	      tmp = gfc_copy_alloc_comp (cm->ts.u.derived, se.expr,
8474 					 dest, expr->rank, 0);
8475 	      gfc_add_expr_to_block (&block, tmp);
8476 	      if (dealloc != NULL_TREE)
8477 		gfc_add_expr_to_block (&block, dealloc);
8478 	    }
8479 	  gfc_add_block_to_block (&block, &se.post);
8480 	}
8481       else
8482 	{
8483 	  /* Nested constructors.  */
8484 	  tmp = gfc_trans_structure_assign (dest, expr, expr->symtree != NULL);
8485 	  gfc_add_expr_to_block (&block, tmp);
8486 	}
8487     }
8488   else if (gfc_deferred_strlen (cm, &tmp))
8489     {
8490       tree strlen;
8491       strlen = tmp;
8492       gcc_assert (strlen);
8493       strlen = fold_build3_loc (input_location, COMPONENT_REF,
8494 				TREE_TYPE (strlen),
8495 				TREE_OPERAND (dest, 0),
8496 				strlen, NULL_TREE);
8497 
8498       if (expr->expr_type == EXPR_NULL)
8499 	{
8500 	  tmp = build_int_cst (TREE_TYPE (cm->backend_decl), 0);
8501 	  gfc_add_modify (&block, dest, tmp);
8502 	  tmp = build_int_cst (TREE_TYPE (strlen), 0);
8503 	  gfc_add_modify (&block, strlen, tmp);
8504 	}
8505       else
8506 	{
8507 	  tree size;
8508 	  gfc_init_se (&se, NULL);
8509 	  gfc_conv_expr (&se, expr);
8510 	  size = size_of_string_in_bytes (cm->ts.kind, se.string_length);
8511 	  tmp = build_call_expr_loc (input_location,
8512 				     builtin_decl_explicit (BUILT_IN_MALLOC),
8513 				     1, size);
8514 	  gfc_add_modify (&block, dest,
8515 			  fold_convert (TREE_TYPE (dest), tmp));
8516 	  gfc_add_modify (&block, strlen,
8517 			  fold_convert (TREE_TYPE (strlen), se.string_length));
8518 	  tmp = gfc_build_memcpy_call (dest, se.expr, size);
8519 	  gfc_add_expr_to_block (&block, tmp);
8520 	}
8521     }
8522   else if (!cm->attr.artificial)
8523     {
8524       /* Scalar component (excluding deferred parameters).  */
8525       gfc_init_se (&se, NULL);
8526       gfc_init_se (&lse, NULL);
8527 
8528       gfc_conv_expr (&se, expr);
8529       if (cm->ts.type == BT_CHARACTER)
8530 	lse.string_length = cm->ts.u.cl->backend_decl;
8531       lse.expr = dest;
8532       tmp = gfc_trans_scalar_assign (&lse, &se, cm->ts, false, false);
8533       gfc_add_expr_to_block (&block, tmp);
8534     }
8535   return gfc_finish_block (&block);
8536 }
8537 
8538 /* Assign a derived type constructor to a variable.  */
8539 
8540 tree
8541 gfc_trans_structure_assign (tree dest, gfc_expr * expr, bool init, bool coarray)
8542 {
8543   gfc_constructor *c;
8544   gfc_component *cm;
8545   stmtblock_t block;
8546   tree field;
8547   tree tmp;
8548   gfc_se se;
8549 
8550   gfc_start_block (&block);
8551 
8552   if (expr->ts.u.derived->from_intmod == INTMOD_ISO_C_BINDING
8553       && (expr->ts.u.derived->intmod_sym_id == ISOCBINDING_PTR
8554           || expr->ts.u.derived->intmod_sym_id == ISOCBINDING_FUNPTR))
8555     {
8556       gfc_se lse;
8557 
8558       gfc_init_se (&se, NULL);
8559       gfc_init_se (&lse, NULL);
8560       gfc_conv_expr (&se, gfc_constructor_first (expr->value.constructor)->expr);
8561       lse.expr = dest;
8562       gfc_add_modify (&block, lse.expr,
8563 		      fold_convert (TREE_TYPE (lse.expr), se.expr));
8564 
8565       return gfc_finish_block (&block);
8566     }
8567 
8568   /* Make sure that the derived type has been completely built.  */
8569   if (!expr->ts.u.derived->backend_decl
8570       || !TYPE_FIELDS (expr->ts.u.derived->backend_decl))
8571     {
8572       tmp = gfc_typenode_for_spec (&expr->ts);
8573       gcc_assert (tmp);
8574     }
8575 
8576   cm = expr->ts.u.derived->components;
8577 
8578 
8579   if (coarray)
8580     gfc_init_se (&se, NULL);
8581 
8582   for (c = gfc_constructor_first (expr->value.constructor);
8583        c; c = gfc_constructor_next (c), cm = cm->next)
8584     {
8585       /* Skip absent members in default initializers.  */
8586       if (!c->expr && !cm->attr.allocatable)
8587 	continue;
8588 
8589       /* Register the component with the caf-lib before it is initialized.
8590 	 Register only allocatable components, that are not coarray'ed
8591 	 components (%comp[*]).  Only register when the constructor is not the
8592 	 null-expression.  */
8593       if (coarray && !cm->attr.codimension
8594 	  && (cm->attr.allocatable || cm->attr.pointer)
8595 	  && (!c->expr || c->expr->expr_type == EXPR_NULL))
8596 	{
8597 	  tree token, desc, size;
8598 	  bool is_array = cm->ts.type == BT_CLASS
8599 	      ? CLASS_DATA (cm)->attr.dimension : cm->attr.dimension;
8600 
8601 	  field = cm->backend_decl;
8602 	  field = fold_build3_loc (input_location, COMPONENT_REF,
8603 				   TREE_TYPE (field), dest, field, NULL_TREE);
8604 	  if (cm->ts.type == BT_CLASS)
8605 	    field = gfc_class_data_get (field);
8606 
8607 	  token = is_array ? gfc_conv_descriptor_token (field)
8608 			   : fold_build3_loc (input_location, COMPONENT_REF,
8609 					      TREE_TYPE (cm->caf_token), dest,
8610 					      cm->caf_token, NULL_TREE);
8611 
8612 	  if (is_array)
8613 	    {
8614 	      /* The _caf_register routine looks at the rank of the array
8615 		 descriptor to decide whether the data registered is an array
8616 		 or not.  */
8617 	      int rank = cm->ts.type == BT_CLASS ? CLASS_DATA (cm)->as->rank
8618 						 : cm->as->rank;
8619 	      /* When the rank is not known just set a positive rank, which
8620 		 suffices to recognize the data as array.  */
8621 	      if (rank < 0)
8622 		rank = 1;
8623 	      size = build_zero_cst (size_type_node);
8624 	      desc = field;
8625 	      gfc_add_modify (&block, gfc_conv_descriptor_rank (desc),
8626 			      build_int_cst (signed_char_type_node, rank));
8627 	    }
8628 	  else
8629 	    {
8630 	      desc = gfc_conv_scalar_to_descriptor (&se, field,
8631 						    cm->ts.type == BT_CLASS
8632 						    ? CLASS_DATA (cm)->attr
8633 						    : cm->attr);
8634 	      size = TYPE_SIZE_UNIT (TREE_TYPE (field));
8635 	    }
8636 	  gfc_add_block_to_block (&block, &se.pre);
8637 	  tmp =  build_call_expr_loc (input_location, gfor_fndecl_caf_register,
8638 				      7, size, build_int_cst (
8639 					integer_type_node,
8640 					GFC_CAF_COARRAY_ALLOC_REGISTER_ONLY),
8641 				      gfc_build_addr_expr (pvoid_type_node,
8642 							   token),
8643 				      gfc_build_addr_expr (NULL_TREE, desc),
8644 				      null_pointer_node, null_pointer_node,
8645 				      integer_zero_node);
8646 	  gfc_add_expr_to_block (&block, tmp);
8647 	}
8648       field = cm->backend_decl;
8649       gcc_assert(field);
8650       tmp = fold_build3_loc (input_location, COMPONENT_REF, TREE_TYPE (field),
8651 			     dest, field, NULL_TREE);
8652       if (!c->expr)
8653 	{
8654 	  gfc_expr *e = gfc_get_null_expr (NULL);
8655 	  tmp = gfc_trans_subcomponent_assign (tmp, cm, e, expr->ts.u.derived,
8656 					       init);
8657 	  gfc_free_expr (e);
8658 	}
8659       else
8660         tmp = gfc_trans_subcomponent_assign (tmp, cm, c->expr,
8661                                              expr->ts.u.derived, init);
8662       gfc_add_expr_to_block (&block, tmp);
8663     }
8664   return gfc_finish_block (&block);
8665 }
8666 
8667 static void
8668 gfc_conv_union_initializer (vec<constructor_elt, va_gc> *&v,
8669                             gfc_component *un, gfc_expr *init)
8670 {
8671   gfc_constructor *ctor;
8672 
8673   if (un->ts.type != BT_UNION || un == NULL || init == NULL)
8674     return;
8675 
8676   ctor = gfc_constructor_first (init->value.constructor);
8677 
8678   if (ctor == NULL || ctor->expr == NULL)
8679     return;
8680 
8681   gcc_assert (init->expr_type == EXPR_STRUCTURE);
8682 
8683   /* If we have an 'initialize all' constructor, do it first.  */
8684   if (ctor->expr->expr_type == EXPR_NULL)
8685     {
8686       tree union_type = TREE_TYPE (un->backend_decl);
8687       tree val = build_constructor (union_type, NULL);
8688       CONSTRUCTOR_APPEND_ELT (v, un->backend_decl, val);
8689       ctor = gfc_constructor_next (ctor);
8690     }
8691 
8692   /* Add the map initializer on top.  */
8693   if (ctor != NULL && ctor->expr != NULL)
8694     {
8695       gcc_assert (ctor->expr->expr_type == EXPR_STRUCTURE);
8696       tree val = gfc_conv_initializer (ctor->expr, &un->ts,
8697                                        TREE_TYPE (un->backend_decl),
8698                                        un->attr.dimension, un->attr.pointer,
8699                                        un->attr.proc_pointer);
8700       CONSTRUCTOR_APPEND_ELT (v, un->backend_decl, val);
8701     }
8702 }
8703 
8704 /* Build an expression for a constructor. If init is nonzero then
8705    this is part of a static variable initializer.  */
8706 
8707 void
8708 gfc_conv_structure (gfc_se * se, gfc_expr * expr, int init)
8709 {
8710   gfc_constructor *c;
8711   gfc_component *cm;
8712   tree val;
8713   tree type;
8714   tree tmp;
8715   vec<constructor_elt, va_gc> *v = NULL;
8716 
8717   gcc_assert (se->ss == NULL);
8718   gcc_assert (expr->expr_type == EXPR_STRUCTURE);
8719   type = gfc_typenode_for_spec (&expr->ts);
8720 
8721   if (!init)
8722     {
8723       /* Create a temporary variable and fill it in.  */
8724       se->expr = gfc_create_var (type, expr->ts.u.derived->name);
8725       /* The symtree in expr is NULL, if the code to generate is for
8726 	 initializing the static members only.  */
8727       tmp = gfc_trans_structure_assign (se->expr, expr, expr->symtree != NULL,
8728 					se->want_coarray);
8729       gfc_add_expr_to_block (&se->pre, tmp);
8730       return;
8731     }
8732 
8733   cm = expr->ts.u.derived->components;
8734 
8735   for (c = gfc_constructor_first (expr->value.constructor);
8736        c; c = gfc_constructor_next (c), cm = cm->next)
8737     {
8738       /* Skip absent members in default initializers and allocatable
8739 	 components.  Although the latter have a default initializer
8740 	 of EXPR_NULL,... by default, the static nullify is not needed
8741 	 since this is done every time we come into scope.  */
8742       if (!c->expr || (cm->attr.allocatable && cm->attr.flavor != FL_PROCEDURE))
8743 	continue;
8744 
8745       if (cm->initializer && cm->initializer->expr_type != EXPR_NULL
8746 	  && strcmp (cm->name, "_extends") == 0
8747 	  && cm->initializer->symtree)
8748 	{
8749 	  tree vtab;
8750 	  gfc_symbol *vtabs;
8751 	  vtabs = cm->initializer->symtree->n.sym;
8752 	  vtab = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtabs));
8753 	  vtab = unshare_expr_without_location (vtab);
8754 	  CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, vtab);
8755 	}
8756       else if (cm->ts.u.derived && strcmp (cm->name, "_size") == 0)
8757 	{
8758 	  val = TYPE_SIZE_UNIT (gfc_get_derived_type (cm->ts.u.derived));
8759 	  CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl,
8760 				  fold_convert (TREE_TYPE (cm->backend_decl),
8761 						val));
8762 	}
8763       else if (cm->ts.type == BT_INTEGER && strcmp (cm->name, "_len") == 0)
8764 	CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl,
8765 				fold_convert (TREE_TYPE (cm->backend_decl),
8766 					      integer_zero_node));
8767       else if (cm->ts.type == BT_UNION)
8768         gfc_conv_union_initializer (v, cm, c->expr);
8769       else
8770 	{
8771 	  val = gfc_conv_initializer (c->expr, &cm->ts,
8772 				      TREE_TYPE (cm->backend_decl),
8773 				      cm->attr.dimension, cm->attr.pointer,
8774 				      cm->attr.proc_pointer);
8775 	  val = unshare_expr_without_location (val);
8776 
8777 	  /* Append it to the constructor list.  */
8778 	  CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, val);
8779 	}
8780     }
8781 
8782   se->expr = build_constructor (type, v);
8783   if (init)
8784     TREE_CONSTANT (se->expr) = 1;
8785 }
8786 
8787 
8788 /* Translate a substring expression.  */
8789 
8790 static void
8791 gfc_conv_substring_expr (gfc_se * se, gfc_expr * expr)
8792 {
8793   gfc_ref *ref;
8794 
8795   ref = expr->ref;
8796 
8797   gcc_assert (ref == NULL || ref->type == REF_SUBSTRING);
8798 
8799   se->expr = gfc_build_wide_string_const (expr->ts.kind,
8800 					  expr->value.character.length,
8801 					  expr->value.character.string);
8802 
8803   se->string_length = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (se->expr)));
8804   TYPE_STRING_FLAG (TREE_TYPE (se->expr)) = 1;
8805 
8806   if (ref)
8807     gfc_conv_substring (se, ref, expr->ts.kind, NULL, &expr->where);
8808 }
8809 
8810 
8811 /* Entry point for expression translation.  Evaluates a scalar quantity.
8812    EXPR is the expression to be translated, and SE is the state structure if
8813    called from within the scalarized.  */
8814 
8815 void
8816 gfc_conv_expr (gfc_se * se, gfc_expr * expr)
8817 {
8818   gfc_ss *ss;
8819 
8820   ss = se->ss;
8821   if (ss && ss->info->expr == expr
8822       && (ss->info->type == GFC_SS_SCALAR
8823 	  || ss->info->type == GFC_SS_REFERENCE))
8824     {
8825       gfc_ss_info *ss_info;
8826 
8827       ss_info = ss->info;
8828       /* Substitute a scalar expression evaluated outside the scalarization
8829 	 loop.  */
8830       se->expr = ss_info->data.scalar.value;
8831       if (gfc_scalar_elemental_arg_saved_as_reference (ss_info))
8832 	se->expr = build_fold_indirect_ref_loc (input_location, se->expr);
8833 
8834       se->string_length = ss_info->string_length;
8835       gfc_advance_se_ss_chain (se);
8836       return;
8837     }
8838 
8839   /* We need to convert the expressions for the iso_c_binding derived types.
8840      C_NULL_PTR and C_NULL_FUNPTR will be made EXPR_NULL, which evaluates to
8841      null_pointer_node.  C_PTR and C_FUNPTR are converted to match the
8842      typespec for the C_PTR and C_FUNPTR symbols, which has already been
8843      updated to be an integer with a kind equal to the size of a (void *).  */
8844   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived->ts.f90_type == BT_VOID
8845       && expr->ts.u.derived->attr.is_bind_c)
8846     {
8847       if (expr->expr_type == EXPR_VARIABLE
8848 	  && (expr->symtree->n.sym->intmod_sym_id == ISOCBINDING_NULL_PTR
8849 	      || expr->symtree->n.sym->intmod_sym_id
8850 		 == ISOCBINDING_NULL_FUNPTR))
8851         {
8852 	  /* Set expr_type to EXPR_NULL, which will result in
8853 	     null_pointer_node being used below.  */
8854           expr->expr_type = EXPR_NULL;
8855         }
8856       else
8857         {
8858           /* Update the type/kind of the expression to be what the new
8859              type/kind are for the updated symbols of C_PTR/C_FUNPTR.  */
8860           expr->ts.type = BT_INTEGER;
8861           expr->ts.f90_type = BT_VOID;
8862           expr->ts.kind = gfc_index_integer_kind;
8863         }
8864     }
8865 
8866   gfc_fix_class_refs (expr);
8867 
8868   switch (expr->expr_type)
8869     {
8870     case EXPR_OP:
8871       gfc_conv_expr_op (se, expr);
8872       break;
8873 
8874     case EXPR_FUNCTION:
8875       gfc_conv_function_expr (se, expr);
8876       break;
8877 
8878     case EXPR_CONSTANT:
8879       gfc_conv_constant (se, expr);
8880       break;
8881 
8882     case EXPR_VARIABLE:
8883       gfc_conv_variable (se, expr);
8884       break;
8885 
8886     case EXPR_NULL:
8887       se->expr = null_pointer_node;
8888       break;
8889 
8890     case EXPR_SUBSTRING:
8891       gfc_conv_substring_expr (se, expr);
8892       break;
8893 
8894     case EXPR_STRUCTURE:
8895       gfc_conv_structure (se, expr, 0);
8896       break;
8897 
8898     case EXPR_ARRAY:
8899       gfc_conv_array_constructor_expr (se, expr);
8900       break;
8901 
8902     default:
8903       gcc_unreachable ();
8904       break;
8905     }
8906 }
8907 
8908 /* Like gfc_conv_expr_val, but the value is also suitable for use in the lhs
8909    of an assignment.  */
8910 void
8911 gfc_conv_expr_lhs (gfc_se * se, gfc_expr * expr)
8912 {
8913   gfc_conv_expr (se, expr);
8914   /* All numeric lvalues should have empty post chains.  If not we need to
8915      figure out a way of rewriting an lvalue so that it has no post chain.  */
8916   gcc_assert (expr->ts.type == BT_CHARACTER || !se->post.head);
8917 }
8918 
8919 /* Like gfc_conv_expr, but the POST block is guaranteed to be empty for
8920    numeric expressions.  Used for scalar values where inserting cleanup code
8921    is inconvenient.  */
8922 void
8923 gfc_conv_expr_val (gfc_se * se, gfc_expr * expr)
8924 {
8925   tree val;
8926 
8927   gcc_assert (expr->ts.type != BT_CHARACTER);
8928   gfc_conv_expr (se, expr);
8929   if (se->post.head)
8930     {
8931       val = gfc_create_var (TREE_TYPE (se->expr), NULL);
8932       gfc_add_modify (&se->pre, val, se->expr);
8933       se->expr = val;
8934       gfc_add_block_to_block (&se->pre, &se->post);
8935     }
8936 }
8937 
8938 /* Helper to translate an expression and convert it to a particular type.  */
8939 void
8940 gfc_conv_expr_type (gfc_se * se, gfc_expr * expr, tree type)
8941 {
8942   gfc_conv_expr_val (se, expr);
8943   se->expr = convert (type, se->expr);
8944 }
8945 
8946 
8947 /* Converts an expression so that it can be passed by reference.  Scalar
8948    values only.  */
8949 
8950 void
8951 gfc_conv_expr_reference (gfc_se * se, gfc_expr * expr, bool add_clobber)
8952 {
8953   gfc_ss *ss;
8954   tree var;
8955 
8956   ss = se->ss;
8957   if (ss && ss->info->expr == expr
8958       && ss->info->type == GFC_SS_REFERENCE)
8959     {
8960       /* Returns a reference to the scalar evaluated outside the loop
8961 	 for this case.  */
8962       gfc_conv_expr (se, expr);
8963 
8964       if (expr->ts.type == BT_CHARACTER
8965 	  && expr->expr_type != EXPR_FUNCTION)
8966 	gfc_conv_string_parameter (se);
8967      else
8968 	se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
8969 
8970       return;
8971     }
8972 
8973   if (expr->ts.type == BT_CHARACTER)
8974     {
8975       gfc_conv_expr (se, expr);
8976       gfc_conv_string_parameter (se);
8977       return;
8978     }
8979 
8980   if (expr->expr_type == EXPR_VARIABLE)
8981     {
8982       se->want_pointer = 1;
8983       gfc_conv_expr (se, expr);
8984       if (se->post.head)
8985 	{
8986 	  var = gfc_create_var (TREE_TYPE (se->expr), NULL);
8987 	  gfc_add_modify (&se->pre, var, se->expr);
8988 	  gfc_add_block_to_block (&se->pre, &se->post);
8989 	  se->expr = var;
8990 	}
8991       else if (add_clobber && expr->ref == NULL)
8992 	{
8993 	  tree clobber;
8994 	  tree var;
8995 	  /* FIXME: This fails if var is passed by reference, see PR
8996 	     41453.  */
8997 	  var = expr->symtree->n.sym->backend_decl;
8998 	  clobber = build_clobber (TREE_TYPE (var));
8999 	  gfc_add_modify (&se->pre, var, clobber);
9000 	}
9001       return;
9002     }
9003 
9004   if (expr->expr_type == EXPR_FUNCTION
9005       && ((expr->value.function.esym
9006 	   && expr->value.function.esym->result
9007 	   && expr->value.function.esym->result->attr.pointer
9008 	   && !expr->value.function.esym->result->attr.dimension)
9009 	  || (!expr->value.function.esym && !expr->ref
9010 	      && expr->symtree->n.sym->attr.pointer
9011 	      && !expr->symtree->n.sym->attr.dimension)))
9012     {
9013       se->want_pointer = 1;
9014       gfc_conv_expr (se, expr);
9015       var = gfc_create_var (TREE_TYPE (se->expr), NULL);
9016       gfc_add_modify (&se->pre, var, se->expr);
9017       se->expr = var;
9018       return;
9019     }
9020 
9021   gfc_conv_expr (se, expr);
9022 
9023   /* Create a temporary var to hold the value.  */
9024   if (TREE_CONSTANT (se->expr))
9025     {
9026       tree tmp = se->expr;
9027       STRIP_TYPE_NOPS (tmp);
9028       var = build_decl (input_location,
9029 			CONST_DECL, NULL, TREE_TYPE (tmp));
9030       DECL_INITIAL (var) = tmp;
9031       TREE_STATIC (var) = 1;
9032       pushdecl (var);
9033     }
9034   else
9035     {
9036       var = gfc_create_var (TREE_TYPE (se->expr), NULL);
9037       gfc_add_modify (&se->pre, var, se->expr);
9038     }
9039 
9040   if (!expr->must_finalize)
9041     gfc_add_block_to_block (&se->pre, &se->post);
9042 
9043   /* Take the address of that value.  */
9044   se->expr = gfc_build_addr_expr (NULL_TREE, var);
9045 }
9046 
9047 
9048 /* Get the _len component for an unlimited polymorphic expression.  */
9049 
9050 static tree
9051 trans_get_upoly_len (stmtblock_t *block, gfc_expr *expr)
9052 {
9053   gfc_se se;
9054   gfc_ref *ref = expr->ref;
9055 
9056   gfc_init_se (&se, NULL);
9057   while (ref && ref->next)
9058     ref = ref->next;
9059   gfc_add_len_component (expr);
9060   gfc_conv_expr (&se, expr);
9061   gfc_add_block_to_block (block, &se.pre);
9062   gcc_assert (se.post.head == NULL_TREE);
9063   if (ref)
9064     {
9065       gfc_free_ref_list (ref->next);
9066       ref->next = NULL;
9067     }
9068   else
9069     {
9070       gfc_free_ref_list (expr->ref);
9071       expr->ref = NULL;
9072     }
9073   return se.expr;
9074 }
9075 
9076 
9077 /* Assign _vptr and _len components as appropriate.  BLOCK should be a
9078    statement-list outside of the scalarizer-loop.  When code is generated, that
9079    depends on the scalarized expression, it is added to RSE.PRE.
9080    Returns le's _vptr tree and when set the len expressions in to_lenp and
9081    from_lenp to form a le%_vptr%_copy (re, le, [from_lenp, to_lenp])
9082    expression.  */
9083 
9084 static tree
9085 trans_class_vptr_len_assignment (stmtblock_t *block, gfc_expr * le,
9086 				 gfc_expr * re, gfc_se *rse,
9087 				 tree * to_lenp, tree * from_lenp)
9088 {
9089   gfc_se se;
9090   gfc_expr * vptr_expr;
9091   tree tmp, to_len = NULL_TREE, from_len = NULL_TREE, lhs_vptr;
9092   bool set_vptr = false, temp_rhs = false;
9093   stmtblock_t *pre = block;
9094   tree class_expr = NULL_TREE;
9095 
9096   /* Create a temporary for complicated expressions.  */
9097   if (re->expr_type != EXPR_VARIABLE && re->expr_type != EXPR_NULL
9098       && rse->expr != NULL_TREE && !DECL_P (rse->expr))
9099     {
9100       if (re->ts.type == BT_CLASS && !GFC_CLASS_TYPE_P (TREE_TYPE (rse->expr)))
9101 	class_expr = gfc_get_class_from_expr (rse->expr);
9102 
9103       if (rse->loop)
9104 	pre = &rse->loop->pre;
9105       else
9106 	pre = &rse->pre;
9107 
9108       if (class_expr != NULL_TREE && UNLIMITED_POLY (re))
9109 	{
9110 	  tmp = TREE_OPERAND (rse->expr, 0);
9111 	  tmp = gfc_create_var (TREE_TYPE (tmp), "rhs");
9112 	  gfc_add_modify (&rse->pre, tmp, TREE_OPERAND (rse->expr, 0));
9113 	}
9114       else
9115 	{
9116 	  tmp = gfc_create_var (TREE_TYPE (rse->expr), "rhs");
9117 	  gfc_add_modify (&rse->pre, tmp, rse->expr);
9118 	}
9119 
9120       rse->expr = tmp;
9121       temp_rhs = true;
9122     }
9123 
9124   /* Get the _vptr for the left-hand side expression.  */
9125   gfc_init_se (&se, NULL);
9126   vptr_expr = gfc_find_and_cut_at_last_class_ref (le);
9127   if (vptr_expr != NULL && gfc_expr_attr (vptr_expr).class_ok)
9128     {
9129       /* Care about _len for unlimited polymorphic entities.  */
9130       if (UNLIMITED_POLY (vptr_expr)
9131 	  || (vptr_expr->ts.type == BT_DERIVED
9132 	      && vptr_expr->ts.u.derived->attr.unlimited_polymorphic))
9133 	to_len = trans_get_upoly_len (block, vptr_expr);
9134       gfc_add_vptr_component (vptr_expr);
9135       set_vptr = true;
9136     }
9137   else
9138     vptr_expr = gfc_lval_expr_from_sym (gfc_find_vtab (&le->ts));
9139   se.want_pointer = 1;
9140   gfc_conv_expr (&se, vptr_expr);
9141   gfc_free_expr (vptr_expr);
9142   gfc_add_block_to_block (block, &se.pre);
9143   gcc_assert (se.post.head == NULL_TREE);
9144   lhs_vptr = se.expr;
9145   STRIP_NOPS (lhs_vptr);
9146 
9147   /* Set the _vptr only when the left-hand side of the assignment is a
9148      class-object.  */
9149   if (set_vptr)
9150     {
9151       /* Get the vptr from the rhs expression only, when it is variable.
9152 	 Functions are expected to be assigned to a temporary beforehand.  */
9153       vptr_expr = (re->expr_type == EXPR_VARIABLE && re->ts.type == BT_CLASS)
9154 	  ? gfc_find_and_cut_at_last_class_ref (re)
9155 	  : NULL;
9156       if (vptr_expr != NULL && vptr_expr->ts.type == BT_CLASS)
9157 	{
9158 	  if (to_len != NULL_TREE)
9159 	    {
9160 	      /* Get the _len information from the rhs.  */
9161 	      if (UNLIMITED_POLY (vptr_expr)
9162 		  || (vptr_expr->ts.type == BT_DERIVED
9163 		      && vptr_expr->ts.u.derived->attr.unlimited_polymorphic))
9164 		from_len = trans_get_upoly_len (block, vptr_expr);
9165 	    }
9166 	  gfc_add_vptr_component (vptr_expr);
9167 	}
9168       else
9169 	{
9170 	  if (re->expr_type == EXPR_VARIABLE
9171 	      && DECL_P (re->symtree->n.sym->backend_decl)
9172 	      && DECL_LANG_SPECIFIC (re->symtree->n.sym->backend_decl)
9173 	      && GFC_DECL_SAVED_DESCRIPTOR (re->symtree->n.sym->backend_decl)
9174 	      && GFC_CLASS_TYPE_P (TREE_TYPE (GFC_DECL_SAVED_DESCRIPTOR (
9175 					   re->symtree->n.sym->backend_decl))))
9176 	    {
9177 	      vptr_expr = NULL;
9178 	      se.expr = gfc_class_vptr_get (GFC_DECL_SAVED_DESCRIPTOR (
9179 					     re->symtree->n.sym->backend_decl));
9180 	      if (to_len)
9181 		from_len = gfc_class_len_get (GFC_DECL_SAVED_DESCRIPTOR (
9182 					     re->symtree->n.sym->backend_decl));
9183 	    }
9184 	  else if (temp_rhs && re->ts.type == BT_CLASS)
9185 	    {
9186 	      vptr_expr = NULL;
9187 	      if (class_expr)
9188 		tmp = class_expr;
9189 	      else if (!GFC_CLASS_TYPE_P (TREE_TYPE (rse->expr)))
9190 		tmp = gfc_get_class_from_expr (rse->expr);
9191 	      else
9192 		tmp = rse->expr;
9193 
9194 	      se.expr = gfc_class_vptr_get (tmp);
9195 	      if (UNLIMITED_POLY (re))
9196 		from_len = gfc_class_len_get (tmp);
9197 
9198 	    }
9199 	  else if (re->expr_type != EXPR_NULL)
9200 	    /* Only when rhs is non-NULL use its declared type for vptr
9201 	       initialisation.  */
9202 	    vptr_expr = gfc_lval_expr_from_sym (gfc_find_vtab (&re->ts));
9203 	  else
9204 	    /* When the rhs is NULL use the vtab of lhs' declared type.  */
9205 	    vptr_expr = gfc_lval_expr_from_sym (gfc_find_vtab (&le->ts));
9206 	}
9207 
9208       if (vptr_expr)
9209 	{
9210 	  gfc_init_se (&se, NULL);
9211 	  se.want_pointer = 1;
9212 	  gfc_conv_expr (&se, vptr_expr);
9213 	  gfc_free_expr (vptr_expr);
9214 	  gfc_add_block_to_block (block, &se.pre);
9215 	  gcc_assert (se.post.head == NULL_TREE);
9216 	}
9217       gfc_add_modify (pre, lhs_vptr, fold_convert (TREE_TYPE (lhs_vptr),
9218 						se.expr));
9219 
9220       if (to_len != NULL_TREE)
9221 	{
9222 	  /* The _len component needs to be set.  Figure how to get the
9223 	     value of the right-hand side.  */
9224 	  if (from_len == NULL_TREE)
9225 	    {
9226 	      if (rse->string_length != NULL_TREE)
9227 		from_len = rse->string_length;
9228 	      else if (re->ts.type == BT_CHARACTER && re->ts.u.cl->length)
9229 		{
9230 		  gfc_init_se (&se, NULL);
9231 		  gfc_conv_expr (&se, re->ts.u.cl->length);
9232 		  gfc_add_block_to_block (block, &se.pre);
9233 		  gcc_assert (se.post.head == NULL_TREE);
9234 		  from_len = gfc_evaluate_now (se.expr, block);
9235 		}
9236 	      else
9237 		from_len = build_zero_cst (gfc_charlen_type_node);
9238 	    }
9239 	  gfc_add_modify (pre, to_len, fold_convert (TREE_TYPE (to_len),
9240 						     from_len));
9241 	}
9242     }
9243 
9244   /* Return the _len trees only, when requested.  */
9245   if (to_lenp)
9246     *to_lenp = to_len;
9247   if (from_lenp)
9248     *from_lenp = from_len;
9249   return lhs_vptr;
9250 }
9251 
9252 
9253 /* Assign tokens for pointer components.  */
9254 
9255 static void
9256 trans_caf_token_assign (gfc_se *lse, gfc_se *rse, gfc_expr *expr1,
9257 			gfc_expr *expr2)
9258 {
9259   symbol_attribute lhs_attr, rhs_attr;
9260   tree tmp, lhs_tok, rhs_tok;
9261   /* Flag to indicated component refs on the rhs.  */
9262   bool rhs_cr;
9263 
9264   lhs_attr = gfc_caf_attr (expr1);
9265   if (expr2->expr_type != EXPR_NULL)
9266     {
9267       rhs_attr = gfc_caf_attr (expr2, false, &rhs_cr);
9268       if (lhs_attr.codimension && rhs_attr.codimension)
9269 	{
9270 	  lhs_tok = gfc_get_ultimate_alloc_ptr_comps_caf_token (lse, expr1);
9271 	  lhs_tok = build_fold_indirect_ref (lhs_tok);
9272 
9273 	  if (rhs_cr)
9274 	    rhs_tok = gfc_get_ultimate_alloc_ptr_comps_caf_token (rse, expr2);
9275 	  else
9276 	    {
9277 	      tree caf_decl;
9278 	      caf_decl = gfc_get_tree_for_caf_expr (expr2);
9279 	      gfc_get_caf_token_offset (rse, &rhs_tok, NULL, caf_decl,
9280 					NULL_TREE, NULL);
9281 	    }
9282 	  tmp = build2_loc (input_location, MODIFY_EXPR, void_type_node,
9283 			    lhs_tok,
9284 			    fold_convert (TREE_TYPE (lhs_tok), rhs_tok));
9285 	  gfc_prepend_expr_to_block (&lse->post, tmp);
9286 	}
9287     }
9288   else if (lhs_attr.codimension)
9289     {
9290       lhs_tok = gfc_get_ultimate_alloc_ptr_comps_caf_token (lse, expr1);
9291       lhs_tok = build_fold_indirect_ref (lhs_tok);
9292       tmp = build2_loc (input_location, MODIFY_EXPR, void_type_node,
9293 			lhs_tok, null_pointer_node);
9294       gfc_prepend_expr_to_block (&lse->post, tmp);
9295     }
9296 }
9297 
9298 
9299 /* Do everything that is needed for a CLASS function expr2.  */
9300 
9301 static tree
9302 trans_class_pointer_fcn (stmtblock_t *block, gfc_se *lse, gfc_se *rse,
9303 			 gfc_expr *expr1, gfc_expr *expr2)
9304 {
9305   tree expr1_vptr = NULL_TREE;
9306   tree tmp;
9307 
9308   gfc_conv_function_expr (rse, expr2);
9309   rse->expr = gfc_evaluate_now (rse->expr, &rse->pre);
9310 
9311   if (expr1->ts.type != BT_CLASS)
9312       rse->expr = gfc_class_data_get (rse->expr);
9313   else
9314     {
9315       expr1_vptr = trans_class_vptr_len_assignment (block, expr1,
9316 						    expr2, rse,
9317 						    NULL, NULL);
9318       gfc_add_block_to_block (block, &rse->pre);
9319       tmp = gfc_create_var (TREE_TYPE (rse->expr), "ptrtemp");
9320       gfc_add_modify (&lse->pre, tmp, rse->expr);
9321 
9322       gfc_add_modify (&lse->pre, expr1_vptr,
9323 		      fold_convert (TREE_TYPE (expr1_vptr),
9324 		      gfc_class_vptr_get (tmp)));
9325       rse->expr = gfc_class_data_get (tmp);
9326     }
9327 
9328   return expr1_vptr;
9329 }
9330 
9331 
9332 tree
9333 gfc_trans_pointer_assign (gfc_code * code)
9334 {
9335   return gfc_trans_pointer_assignment (code->expr1, code->expr2);
9336 }
9337 
9338 
9339 /* Generate code for a pointer assignment.  */
9340 
9341 tree
9342 gfc_trans_pointer_assignment (gfc_expr * expr1, gfc_expr * expr2)
9343 {
9344   gfc_se lse;
9345   gfc_se rse;
9346   stmtblock_t block;
9347   tree desc;
9348   tree tmp;
9349   tree expr1_vptr = NULL_TREE;
9350   bool scalar, non_proc_ptr_assign;
9351   gfc_ss *ss;
9352 
9353   gfc_start_block (&block);
9354 
9355   gfc_init_se (&lse, NULL);
9356 
9357   /* Usually testing whether this is not a proc pointer assignment.  */
9358   non_proc_ptr_assign = !(gfc_expr_attr (expr1).proc_pointer
9359 			&& expr2->expr_type == EXPR_VARIABLE
9360 			&& expr2->symtree->n.sym->attr.flavor == FL_PROCEDURE);
9361 
9362   /* Check whether the expression is a scalar or not; we cannot use
9363      expr1->rank as it can be nonzero for proc pointers.  */
9364   ss = gfc_walk_expr (expr1);
9365   scalar = ss == gfc_ss_terminator;
9366   if (!scalar)
9367     gfc_free_ss_chain (ss);
9368 
9369   if (expr1->ts.type == BT_DERIVED && expr2->ts.type == BT_CLASS
9370       && expr2->expr_type != EXPR_FUNCTION && non_proc_ptr_assign)
9371     {
9372       gfc_add_data_component (expr2);
9373       /* The following is required as gfc_add_data_component doesn't
9374 	 update ts.type if there is a tailing REF_ARRAY.  */
9375       expr2->ts.type = BT_DERIVED;
9376     }
9377 
9378   if (scalar)
9379     {
9380       /* Scalar pointers.  */
9381       lse.want_pointer = 1;
9382       gfc_conv_expr (&lse, expr1);
9383       gfc_init_se (&rse, NULL);
9384       rse.want_pointer = 1;
9385       if (expr2->expr_type == EXPR_FUNCTION && expr2->ts.type == BT_CLASS)
9386 	trans_class_pointer_fcn (&block, &lse, &rse, expr1, expr2);
9387       else
9388 	gfc_conv_expr (&rse, expr2);
9389 
9390       if (non_proc_ptr_assign && expr1->ts.type == BT_CLASS)
9391 	{
9392 	  trans_class_vptr_len_assignment (&block, expr1, expr2, &rse, NULL,
9393 					   NULL);
9394 	  lse.expr = gfc_class_data_get (lse.expr);
9395 	}
9396 
9397       if (expr1->symtree->n.sym->attr.proc_pointer
9398 	  && expr1->symtree->n.sym->attr.dummy)
9399 	lse.expr = build_fold_indirect_ref_loc (input_location,
9400 						lse.expr);
9401 
9402       if (expr2->symtree && expr2->symtree->n.sym->attr.proc_pointer
9403 	  && expr2->symtree->n.sym->attr.dummy)
9404 	rse.expr = build_fold_indirect_ref_loc (input_location,
9405 						rse.expr);
9406 
9407       gfc_add_block_to_block (&block, &lse.pre);
9408       gfc_add_block_to_block (&block, &rse.pre);
9409 
9410       /* Check character lengths if character expression.  The test is only
9411 	 really added if -fbounds-check is enabled.  Exclude deferred
9412 	 character length lefthand sides.  */
9413       if (expr1->ts.type == BT_CHARACTER && expr2->expr_type != EXPR_NULL
9414 	  && !expr1->ts.deferred
9415 	  && !expr1->symtree->n.sym->attr.proc_pointer
9416 	  && !gfc_is_proc_ptr_comp (expr1))
9417 	{
9418 	  gcc_assert (expr2->ts.type == BT_CHARACTER);
9419 	  gcc_assert (lse.string_length && rse.string_length);
9420 	  gfc_trans_same_strlen_check ("pointer assignment", &expr1->where,
9421 				       lse.string_length, rse.string_length,
9422 				       &block);
9423 	}
9424 
9425       /* The assignment to an deferred character length sets the string
9426 	 length to that of the rhs.  */
9427       if (expr1->ts.deferred)
9428 	{
9429 	  if (expr2->expr_type != EXPR_NULL && lse.string_length != NULL)
9430 	    gfc_add_modify (&block, lse.string_length,
9431 			    fold_convert (TREE_TYPE (lse.string_length),
9432 					  rse.string_length));
9433 	  else if (lse.string_length != NULL)
9434 	    gfc_add_modify (&block, lse.string_length,
9435 			    build_zero_cst (TREE_TYPE (lse.string_length)));
9436 	}
9437 
9438       gfc_add_modify (&block, lse.expr,
9439 		      fold_convert (TREE_TYPE (lse.expr), rse.expr));
9440 
9441       /* Also set the tokens for pointer components in derived typed
9442 	 coarrays.  */
9443       if (flag_coarray == GFC_FCOARRAY_LIB)
9444 	trans_caf_token_assign (&lse, &rse, expr1, expr2);
9445 
9446       gfc_add_block_to_block (&block, &rse.post);
9447       gfc_add_block_to_block (&block, &lse.post);
9448     }
9449   else
9450     {
9451       gfc_ref* remap;
9452       bool rank_remap;
9453       tree strlen_lhs;
9454       tree strlen_rhs = NULL_TREE;
9455 
9456       /* Array pointer.  Find the last reference on the LHS and if it is an
9457 	 array section ref, we're dealing with bounds remapping.  In this case,
9458 	 set it to AR_FULL so that gfc_conv_expr_descriptor does
9459 	 not see it and process the bounds remapping afterwards explicitly.  */
9460       for (remap = expr1->ref; remap; remap = remap->next)
9461 	if (!remap->next && remap->type == REF_ARRAY
9462 	    && remap->u.ar.type == AR_SECTION)
9463 	  break;
9464       rank_remap = (remap && remap->u.ar.end[0]);
9465 
9466       if (remap && expr2->expr_type == EXPR_NULL)
9467 	{
9468 	  gfc_error ("If bounds remapping is specified at %L, "
9469 		     "the pointer target shall not be NULL", &expr1->where);
9470 	  return NULL_TREE;
9471 	}
9472 
9473       gfc_init_se (&lse, NULL);
9474       if (remap)
9475 	lse.descriptor_only = 1;
9476       gfc_conv_expr_descriptor (&lse, expr1);
9477       strlen_lhs = lse.string_length;
9478       desc = lse.expr;
9479 
9480       if (expr2->expr_type == EXPR_NULL)
9481 	{
9482 	  /* Just set the data pointer to null.  */
9483 	  gfc_conv_descriptor_data_set (&lse.pre, lse.expr, null_pointer_node);
9484 	}
9485       else if (rank_remap)
9486 	{
9487 	  /* If we are rank-remapping, just get the RHS's descriptor and
9488 	     process this later on.  */
9489 	  gfc_init_se (&rse, NULL);
9490 	  rse.direct_byref = 1;
9491 	  rse.byref_noassign = 1;
9492 
9493 	  if (expr2->expr_type == EXPR_FUNCTION && expr2->ts.type == BT_CLASS)
9494 	    expr1_vptr = trans_class_pointer_fcn (&block, &lse, &rse,
9495 						  expr1, expr2);
9496 	  else if (expr2->expr_type == EXPR_FUNCTION)
9497 	    {
9498 	      tree bound[GFC_MAX_DIMENSIONS];
9499 	      int i;
9500 
9501 	      for (i = 0; i < expr2->rank; i++)
9502 		bound[i] = NULL_TREE;
9503 	      tmp = gfc_typenode_for_spec (&expr2->ts);
9504 	      tmp = gfc_get_array_type_bounds (tmp, expr2->rank, 0,
9505 					       bound, bound, 0,
9506 					       GFC_ARRAY_POINTER_CONT, false);
9507 	      tmp = gfc_create_var (tmp, "ptrtemp");
9508 	      rse.descriptor_only = 0;
9509 	      rse.expr = tmp;
9510 	      rse.direct_byref = 1;
9511 	      gfc_conv_expr_descriptor (&rse, expr2);
9512 	      strlen_rhs = rse.string_length;
9513 	      rse.expr = tmp;
9514 	    }
9515 	  else
9516 	    {
9517 	      gfc_conv_expr_descriptor (&rse, expr2);
9518 	      strlen_rhs = rse.string_length;
9519 	      if (expr1->ts.type == BT_CLASS)
9520 		expr1_vptr = trans_class_vptr_len_assignment (&block, expr1,
9521 							      expr2, &rse,
9522 							      NULL, NULL);
9523 	    }
9524 	}
9525       else if (expr2->expr_type == EXPR_VARIABLE)
9526 	{
9527 	  /* Assign directly to the LHS's descriptor.  */
9528 	  lse.descriptor_only = 0;
9529 	  lse.direct_byref = 1;
9530 	  gfc_conv_expr_descriptor (&lse, expr2);
9531 	  strlen_rhs = lse.string_length;
9532 
9533 	  if (expr1->ts.type == BT_CLASS)
9534 	    {
9535 	      rse.expr = NULL_TREE;
9536 	      rse.string_length = NULL_TREE;
9537 	      trans_class_vptr_len_assignment (&block, expr1, expr2, &rse,
9538 					       NULL, NULL);
9539 	    }
9540 
9541 	  if (remap == NULL)
9542 	    {
9543 	      /* If the target is not a whole array, use the target array
9544 		 reference for remap.  */
9545 	      for (remap = expr2->ref; remap; remap = remap->next)
9546 		if (remap->type == REF_ARRAY
9547 		    && remap->u.ar.type == AR_FULL
9548 		    && remap->next)
9549 		  break;
9550 	    }
9551 	}
9552       else if (expr2->expr_type == EXPR_FUNCTION && expr2->ts.type == BT_CLASS)
9553 	{
9554 	  gfc_init_se (&rse, NULL);
9555 	  rse.want_pointer = 1;
9556 	  gfc_conv_function_expr (&rse, expr2);
9557 	  if (expr1->ts.type != BT_CLASS)
9558 	    {
9559 	      rse.expr = gfc_class_data_get (rse.expr);
9560 	      gfc_add_modify (&lse.pre, desc, rse.expr);
9561 	      /* Set the lhs span.  */
9562 	      tmp = TREE_TYPE (rse.expr);
9563 	      tmp = TYPE_SIZE_UNIT (gfc_get_element_type (tmp));
9564 	      tmp = fold_convert (gfc_array_index_type, tmp);
9565 	      gfc_conv_descriptor_span_set (&lse.pre, desc, tmp);
9566  	    }
9567 	  else
9568 	    {
9569 	      expr1_vptr = trans_class_vptr_len_assignment (&block, expr1,
9570 							    expr2, &rse, NULL,
9571 							    NULL);
9572 	      gfc_add_block_to_block (&block, &rse.pre);
9573 	      tmp = gfc_create_var (TREE_TYPE (rse.expr), "ptrtemp");
9574 	      gfc_add_modify (&lse.pre, tmp, rse.expr);
9575 
9576 	      gfc_add_modify (&lse.pre, expr1_vptr,
9577 			      fold_convert (TREE_TYPE (expr1_vptr),
9578 					gfc_class_vptr_get (tmp)));
9579 	      rse.expr = gfc_class_data_get (tmp);
9580 	      gfc_add_modify (&lse.pre, desc, rse.expr);
9581 	    }
9582 	}
9583       else
9584 	{
9585 	  /* Assign to a temporary descriptor and then copy that
9586 	     temporary to the pointer.  */
9587 	  tmp = gfc_create_var (TREE_TYPE (desc), "ptrtemp");
9588 	  lse.descriptor_only = 0;
9589 	  lse.expr = tmp;
9590 	  lse.direct_byref = 1;
9591 	  gfc_conv_expr_descriptor (&lse, expr2);
9592 	  strlen_rhs = lse.string_length;
9593 	  gfc_add_modify (&lse.pre, desc, tmp);
9594 	}
9595 
9596       gfc_add_block_to_block (&block, &lse.pre);
9597       if (rank_remap)
9598 	gfc_add_block_to_block (&block, &rse.pre);
9599 
9600       /* If we do bounds remapping, update LHS descriptor accordingly.  */
9601       if (remap)
9602 	{
9603 	  int dim;
9604 	  gcc_assert (remap->u.ar.dimen == expr1->rank);
9605 
9606 	  if (rank_remap)
9607 	    {
9608 	      /* Do rank remapping.  We already have the RHS's descriptor
9609 		 converted in rse and now have to build the correct LHS
9610 		 descriptor for it.  */
9611 
9612 	      tree dtype, data, span;
9613 	      tree offs, stride;
9614 	      tree lbound, ubound;
9615 
9616 	      /* Set dtype.  */
9617 	      dtype = gfc_conv_descriptor_dtype (desc);
9618 	      tmp = gfc_get_dtype (TREE_TYPE (desc));
9619 	      gfc_add_modify (&block, dtype, tmp);
9620 
9621 	      /* Copy data pointer.  */
9622 	      data = gfc_conv_descriptor_data_get (rse.expr);
9623 	      gfc_conv_descriptor_data_set (&block, desc, data);
9624 
9625 	      /* Copy the span.  */
9626 	      if (TREE_CODE (rse.expr) == VAR_DECL
9627 		  && GFC_DECL_PTR_ARRAY_P (rse.expr))
9628 		span = gfc_conv_descriptor_span_get (rse.expr);
9629 	      else
9630 		{
9631 		  tmp = TREE_TYPE (rse.expr);
9632 		  tmp = TYPE_SIZE_UNIT (gfc_get_element_type (tmp));
9633 		  span = fold_convert (gfc_array_index_type, tmp);
9634 		}
9635 	      gfc_conv_descriptor_span_set (&block, desc, span);
9636 
9637 	      /* Copy offset but adjust it such that it would correspond
9638 		 to a lbound of zero.  */
9639 	      offs = gfc_conv_descriptor_offset_get (rse.expr);
9640 	      for (dim = 0; dim < expr2->rank; ++dim)
9641 		{
9642 		  stride = gfc_conv_descriptor_stride_get (rse.expr,
9643 							   gfc_rank_cst[dim]);
9644 		  lbound = gfc_conv_descriptor_lbound_get (rse.expr,
9645 							   gfc_rank_cst[dim]);
9646 		  tmp = fold_build2_loc (input_location, MULT_EXPR,
9647 					 gfc_array_index_type, stride, lbound);
9648 		  offs = fold_build2_loc (input_location, PLUS_EXPR,
9649 					  gfc_array_index_type, offs, tmp);
9650 		}
9651 	      gfc_conv_descriptor_offset_set (&block, desc, offs);
9652 
9653 	      /* Set the bounds as declared for the LHS and calculate strides as
9654 		 well as another offset update accordingly.  */
9655 	      stride = gfc_conv_descriptor_stride_get (rse.expr,
9656 						       gfc_rank_cst[0]);
9657 	      for (dim = 0; dim < expr1->rank; ++dim)
9658 		{
9659 		  gfc_se lower_se;
9660 		  gfc_se upper_se;
9661 
9662 		  gcc_assert (remap->u.ar.start[dim] && remap->u.ar.end[dim]);
9663 
9664 		  /* Convert declared bounds.  */
9665 		  gfc_init_se (&lower_se, NULL);
9666 		  gfc_init_se (&upper_se, NULL);
9667 		  gfc_conv_expr (&lower_se, remap->u.ar.start[dim]);
9668 		  gfc_conv_expr (&upper_se, remap->u.ar.end[dim]);
9669 
9670 		  gfc_add_block_to_block (&block, &lower_se.pre);
9671 		  gfc_add_block_to_block (&block, &upper_se.pre);
9672 
9673 		  lbound = fold_convert (gfc_array_index_type, lower_se.expr);
9674 		  ubound = fold_convert (gfc_array_index_type, upper_se.expr);
9675 
9676 		  lbound = gfc_evaluate_now (lbound, &block);
9677 		  ubound = gfc_evaluate_now (ubound, &block);
9678 
9679 		  gfc_add_block_to_block (&block, &lower_se.post);
9680 		  gfc_add_block_to_block (&block, &upper_se.post);
9681 
9682 		  /* Set bounds in descriptor.  */
9683 		  gfc_conv_descriptor_lbound_set (&block, desc,
9684 						  gfc_rank_cst[dim], lbound);
9685 		  gfc_conv_descriptor_ubound_set (&block, desc,
9686 						  gfc_rank_cst[dim], ubound);
9687 
9688 		  /* Set stride.  */
9689 		  stride = gfc_evaluate_now (stride, &block);
9690 		  gfc_conv_descriptor_stride_set (&block, desc,
9691 						  gfc_rank_cst[dim], stride);
9692 
9693 		  /* Update offset.  */
9694 		  offs = gfc_conv_descriptor_offset_get (desc);
9695 		  tmp = fold_build2_loc (input_location, MULT_EXPR,
9696 					 gfc_array_index_type, lbound, stride);
9697 		  offs = fold_build2_loc (input_location, MINUS_EXPR,
9698 					  gfc_array_index_type, offs, tmp);
9699 		  offs = gfc_evaluate_now (offs, &block);
9700 		  gfc_conv_descriptor_offset_set (&block, desc, offs);
9701 
9702 		  /* Update stride.  */
9703 		  tmp = gfc_conv_array_extent_dim (lbound, ubound, NULL);
9704 		  stride = fold_build2_loc (input_location, MULT_EXPR,
9705 					    gfc_array_index_type, stride, tmp);
9706 		}
9707 	    }
9708 	  else
9709 	    {
9710 	      /* Bounds remapping.  Just shift the lower bounds.  */
9711 
9712 	      gcc_assert (expr1->rank == expr2->rank);
9713 
9714 	      for (dim = 0; dim < remap->u.ar.dimen; ++dim)
9715 		{
9716 		  gfc_se lbound_se;
9717 
9718 		  gcc_assert (!remap->u.ar.end[dim]);
9719 		  gfc_init_se (&lbound_se, NULL);
9720 		  if (remap->u.ar.start[dim])
9721 		    {
9722 		      gfc_conv_expr (&lbound_se, remap->u.ar.start[dim]);
9723 		      gfc_add_block_to_block (&block, &lbound_se.pre);
9724 		    }
9725 		  else
9726 		    /* This remap arises from a target that is not a whole
9727 		       array. The start expressions will be NULL but we need
9728 		       the lbounds to be one.  */
9729 		    lbound_se.expr = gfc_index_one_node;
9730 		  gfc_conv_shift_descriptor_lbound (&block, desc,
9731 						    dim, lbound_se.expr);
9732 		  gfc_add_block_to_block (&block, &lbound_se.post);
9733 		}
9734 	    }
9735 	}
9736 
9737       /* If rank remapping was done, check with -fcheck=bounds that
9738 	 the target is at least as large as the pointer.  */
9739       if (rank_remap && (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS))
9740 	{
9741 	  tree lsize, rsize;
9742 	  tree fault;
9743 	  const char* msg;
9744 
9745 	  lsize = gfc_conv_descriptor_size (lse.expr, expr1->rank);
9746 	  rsize = gfc_conv_descriptor_size (rse.expr, expr2->rank);
9747 
9748 	  lsize = gfc_evaluate_now (lsize, &block);
9749 	  rsize = gfc_evaluate_now (rsize, &block);
9750 	  fault = fold_build2_loc (input_location, LT_EXPR, logical_type_node,
9751 				   rsize, lsize);
9752 
9753 	  msg = _("Target of rank remapping is too small (%ld < %ld)");
9754 	  gfc_trans_runtime_check (true, false, fault, &block, &expr2->where,
9755 				   msg, rsize, lsize);
9756 	}
9757 
9758       if (expr1->ts.type == BT_CHARACTER
9759 	  && expr1->symtree->n.sym->ts.deferred
9760 	  && expr1->symtree->n.sym->ts.u.cl->backend_decl
9761 	  && VAR_P (expr1->symtree->n.sym->ts.u.cl->backend_decl))
9762 	{
9763 	  tmp = expr1->symtree->n.sym->ts.u.cl->backend_decl;
9764 	  if (expr2->expr_type != EXPR_NULL)
9765 	    gfc_add_modify (&block, tmp,
9766 			    fold_convert (TREE_TYPE (tmp), strlen_rhs));
9767 	  else
9768 	    gfc_add_modify (&block, tmp, build_zero_cst (TREE_TYPE (tmp)));
9769 	}
9770 
9771       /* Check string lengths if applicable.  The check is only really added
9772 	 to the output code if -fbounds-check is enabled.  */
9773       if (expr1->ts.type == BT_CHARACTER && expr2->expr_type != EXPR_NULL)
9774 	{
9775 	  gcc_assert (expr2->ts.type == BT_CHARACTER);
9776 	  gcc_assert (strlen_lhs && strlen_rhs);
9777 	  gfc_trans_same_strlen_check ("pointer assignment", &expr1->where,
9778 				       strlen_lhs, strlen_rhs, &block);
9779 	}
9780 
9781       gfc_add_block_to_block (&block, &lse.post);
9782       if (rank_remap)
9783 	gfc_add_block_to_block (&block, &rse.post);
9784     }
9785 
9786   return gfc_finish_block (&block);
9787 }
9788 
9789 
9790 /* Makes sure se is suitable for passing as a function string parameter.  */
9791 /* TODO: Need to check all callers of this function.  It may be abused.  */
9792 
9793 void
9794 gfc_conv_string_parameter (gfc_se * se)
9795 {
9796   tree type;
9797 
9798   if (TREE_CODE (se->expr) == STRING_CST)
9799     {
9800       type = TREE_TYPE (TREE_TYPE (se->expr));
9801       se->expr = gfc_build_addr_expr (build_pointer_type (type), se->expr);
9802       return;
9803     }
9804 
9805   if ((TREE_CODE (TREE_TYPE (se->expr)) == ARRAY_TYPE
9806        || TREE_CODE (TREE_TYPE (se->expr)) == INTEGER_TYPE)
9807       && TYPE_STRING_FLAG (TREE_TYPE (se->expr)))
9808     {
9809       if (TREE_CODE (se->expr) != INDIRECT_REF)
9810 	{
9811 	  type = TREE_TYPE (se->expr);
9812           se->expr = gfc_build_addr_expr (build_pointer_type (type), se->expr);
9813 	}
9814       else
9815 	{
9816 	  type = gfc_get_character_type_len (gfc_default_character_kind,
9817 					     se->string_length);
9818 	  type = build_pointer_type (type);
9819 	  se->expr = gfc_build_addr_expr (type, se->expr);
9820 	}
9821     }
9822 
9823   gcc_assert (POINTER_TYPE_P (TREE_TYPE (se->expr)));
9824 }
9825 
9826 
9827 /* Generate code for assignment of scalar variables.  Includes character
9828    strings and derived types with allocatable components.
9829    If you know that the LHS has no allocations, set dealloc to false.
9830 
9831    DEEP_COPY has no effect if the typespec TS is not a derived type with
9832    allocatable components.  Otherwise, if it is set, an explicit copy of each
9833    allocatable component is made.  This is necessary as a simple copy of the
9834    whole object would copy array descriptors as is, so that the lhs's
9835    allocatable components would point to the rhs's after the assignment.
9836    Typically, setting DEEP_COPY is necessary if the rhs is a variable, and not
9837    necessary if the rhs is a non-pointer function, as the allocatable components
9838    are not accessible by other means than the function's result after the
9839    function has returned.  It is even more subtle when temporaries are involved,
9840    as the two following examples show:
9841     1.  When we evaluate an array constructor, a temporary is created.  Thus
9842       there is theoretically no alias possible.  However, no deep copy is
9843       made for this temporary, so that if the constructor is made of one or
9844       more variable with allocatable components, those components still point
9845       to the variable's: DEEP_COPY should be set for the assignment from the
9846       temporary to the lhs in that case.
9847     2.  When assigning a scalar to an array, we evaluate the scalar value out
9848       of the loop, store it into a temporary variable, and assign from that.
9849       In that case, deep copying when assigning to the temporary would be a
9850       waste of resources; however deep copies should happen when assigning from
9851       the temporary to each array element: again DEEP_COPY should be set for
9852       the assignment from the temporary to the lhs.  */
9853 
9854 tree
9855 gfc_trans_scalar_assign (gfc_se * lse, gfc_se * rse, gfc_typespec ts,
9856 			 bool deep_copy, bool dealloc, bool in_coarray)
9857 {
9858   stmtblock_t block;
9859   tree tmp;
9860   tree cond;
9861 
9862   gfc_init_block (&block);
9863 
9864   if (ts.type == BT_CHARACTER)
9865     {
9866       tree rlen = NULL;
9867       tree llen = NULL;
9868 
9869       if (lse->string_length != NULL_TREE)
9870 	{
9871 	  gfc_conv_string_parameter (lse);
9872 	  gfc_add_block_to_block (&block, &lse->pre);
9873 	  llen = lse->string_length;
9874 	}
9875 
9876       if (rse->string_length != NULL_TREE)
9877 	{
9878 	  gfc_conv_string_parameter (rse);
9879 	  gfc_add_block_to_block (&block, &rse->pre);
9880 	  rlen = rse->string_length;
9881 	}
9882 
9883       gfc_trans_string_copy (&block, llen, lse->expr, ts.kind, rlen,
9884 			     rse->expr, ts.kind);
9885     }
9886   else if (gfc_bt_struct (ts.type)
9887 	   && (ts.u.derived->attr.alloc_comp
9888 		|| (deep_copy && ts.u.derived->attr.pdt_type)))
9889     {
9890       tree tmp_var = NULL_TREE;
9891       cond = NULL_TREE;
9892 
9893       /* Are the rhs and the lhs the same?  */
9894       if (deep_copy)
9895 	{
9896 	  cond = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
9897 				  gfc_build_addr_expr (NULL_TREE, lse->expr),
9898 				  gfc_build_addr_expr (NULL_TREE, rse->expr));
9899 	  cond = gfc_evaluate_now (cond, &lse->pre);
9900 	}
9901 
9902       /* Deallocate the lhs allocated components as long as it is not
9903 	 the same as the rhs.  This must be done following the assignment
9904 	 to prevent deallocating data that could be used in the rhs
9905 	 expression.  */
9906       if (dealloc)
9907 	{
9908 	  tmp_var = gfc_evaluate_now (lse->expr, &lse->pre);
9909 	  tmp = gfc_deallocate_alloc_comp_no_caf (ts.u.derived, tmp_var, 0);
9910 	  if (deep_copy)
9911 	    tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
9912 			    tmp);
9913 	  gfc_add_expr_to_block (&lse->post, tmp);
9914 	}
9915 
9916       gfc_add_block_to_block (&block, &rse->pre);
9917       gfc_add_block_to_block (&block, &lse->pre);
9918 
9919       gfc_add_modify (&block, lse->expr,
9920 			   fold_convert (TREE_TYPE (lse->expr), rse->expr));
9921 
9922       /* Restore pointer address of coarray components.  */
9923       if (ts.u.derived->attr.coarray_comp && deep_copy && tmp_var != NULL_TREE)
9924 	{
9925 	  tmp = gfc_reassign_alloc_comp_caf (ts.u.derived, tmp_var, lse->expr);
9926 	  tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
9927 			  tmp);
9928 	  gfc_add_expr_to_block (&block, tmp);
9929 	}
9930 
9931       /* Do a deep copy if the rhs is a variable, if it is not the
9932 	 same as the lhs.  */
9933       if (deep_copy)
9934 	{
9935 	  int caf_mode = in_coarray ? (GFC_STRUCTURE_CAF_MODE_ENABLE_COARRAY
9936 				       | GFC_STRUCTURE_CAF_MODE_IN_COARRAY) : 0;
9937 	  tmp = gfc_copy_alloc_comp (ts.u.derived, rse->expr, lse->expr, 0,
9938 				     caf_mode);
9939 	  tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
9940 			  tmp);
9941 	  gfc_add_expr_to_block (&block, tmp);
9942 	}
9943     }
9944   else if (gfc_bt_struct (ts.type))
9945     {
9946       gfc_add_block_to_block (&block, &lse->pre);
9947       gfc_add_block_to_block (&block, &rse->pre);
9948       tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
9949 			     TREE_TYPE (lse->expr), rse->expr);
9950       gfc_add_modify (&block, lse->expr, tmp);
9951     }
9952   /* If possible use the rhs vptr copy with trans_scalar_class_assign....  */
9953   else if (ts.type == BT_CLASS
9954 	   && !trans_scalar_class_assign (&block, lse, rse))
9955     {
9956       gfc_add_block_to_block (&block, &lse->pre);
9957       gfc_add_block_to_block (&block, &rse->pre);
9958       /* ...otherwise assignment suffices. Note the use of VIEW_CONVERT_EXPR
9959 	 for the lhs which ensures that class data rhs cast as a string assigns
9960 	 correctly.  */
9961       tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
9962 			     TREE_TYPE (rse->expr), lse->expr);
9963       gfc_add_modify (&block, tmp, rse->expr);
9964     }
9965   else if (ts.type != BT_CLASS)
9966     {
9967       gfc_add_block_to_block (&block, &lse->pre);
9968       gfc_add_block_to_block (&block, &rse->pre);
9969 
9970       gfc_add_modify (&block, lse->expr,
9971 		      fold_convert (TREE_TYPE (lse->expr), rse->expr));
9972     }
9973 
9974   gfc_add_block_to_block (&block, &lse->post);
9975   gfc_add_block_to_block (&block, &rse->post);
9976 
9977   return gfc_finish_block (&block);
9978 }
9979 
9980 
9981 /* There are quite a lot of restrictions on the optimisation in using an
9982    array function assign without a temporary.  */
9983 
9984 static bool
9985 arrayfunc_assign_needs_temporary (gfc_expr * expr1, gfc_expr * expr2)
9986 {
9987   gfc_ref * ref;
9988   bool seen_array_ref;
9989   bool c = false;
9990   gfc_symbol *sym = expr1->symtree->n.sym;
9991 
9992   /* Play it safe with class functions assigned to a derived type.  */
9993   if (gfc_is_class_array_function (expr2)
9994       && expr1->ts.type == BT_DERIVED)
9995     return true;
9996 
9997   /* The caller has already checked rank>0 and expr_type == EXPR_FUNCTION.  */
9998   if (expr2->value.function.isym && !gfc_is_intrinsic_libcall (expr2))
9999     return true;
10000 
10001   /* Elemental functions are scalarized so that they don't need a
10002      temporary in gfc_trans_assignment_1, so return a true.  Otherwise,
10003      they would need special treatment in gfc_trans_arrayfunc_assign.  */
10004   if (expr2->value.function.esym != NULL
10005       && expr2->value.function.esym->attr.elemental)
10006     return true;
10007 
10008   /* Need a temporary if rhs is not FULL or a contiguous section.  */
10009   if (expr1->ref && !(gfc_full_array_ref_p (expr1->ref, &c) || c))
10010     return true;
10011 
10012   /* Need a temporary if EXPR1 can't be expressed as a descriptor.  */
10013   if (gfc_ref_needs_temporary_p (expr1->ref))
10014     return true;
10015 
10016   /* Functions returning pointers or allocatables need temporaries.  */
10017   c = expr2->value.function.esym
10018       ? (expr2->value.function.esym->attr.pointer
10019 	 || expr2->value.function.esym->attr.allocatable)
10020       : (expr2->symtree->n.sym->attr.pointer
10021 	 || expr2->symtree->n.sym->attr.allocatable);
10022   if (c)
10023     return true;
10024 
10025   /* Character array functions need temporaries unless the
10026      character lengths are the same.  */
10027   if (expr2->ts.type == BT_CHARACTER && expr2->rank > 0)
10028     {
10029       if (expr1->ts.u.cl->length == NULL
10030 	    || expr1->ts.u.cl->length->expr_type != EXPR_CONSTANT)
10031 	return true;
10032 
10033       if (expr2->ts.u.cl->length == NULL
10034 	    || expr2->ts.u.cl->length->expr_type != EXPR_CONSTANT)
10035 	return true;
10036 
10037       if (mpz_cmp (expr1->ts.u.cl->length->value.integer,
10038 		     expr2->ts.u.cl->length->value.integer) != 0)
10039 	return true;
10040     }
10041 
10042   /* Check that no LHS component references appear during an array
10043      reference. This is needed because we do not have the means to
10044      span any arbitrary stride with an array descriptor. This check
10045      is not needed for the rhs because the function result has to be
10046      a complete type.  */
10047   seen_array_ref = false;
10048   for (ref = expr1->ref; ref; ref = ref->next)
10049     {
10050       if (ref->type == REF_ARRAY)
10051 	seen_array_ref= true;
10052       else if (ref->type == REF_COMPONENT && seen_array_ref)
10053 	return true;
10054     }
10055 
10056   /* Check for a dependency.  */
10057   if (gfc_check_fncall_dependency (expr1, INTENT_OUT,
10058 				   expr2->value.function.esym,
10059 				   expr2->value.function.actual,
10060 				   NOT_ELEMENTAL))
10061     return true;
10062 
10063   /* If we have reached here with an intrinsic function, we do not
10064      need a temporary except in the particular case that reallocation
10065      on assignment is active and the lhs is allocatable and a target,
10066      or a pointer which may be a subref pointer.  FIXME: The last
10067      condition can go away when we use span in the intrinsics
10068      directly.*/
10069   if (expr2->value.function.isym)
10070     return (flag_realloc_lhs && sym->attr.allocatable && sym->attr.target)
10071       || (sym->attr.pointer && sym->attr.subref_array_pointer);
10072 
10073   /* If the LHS is a dummy, we need a temporary if it is not
10074      INTENT(OUT).  */
10075   if (sym->attr.dummy && sym->attr.intent != INTENT_OUT)
10076     return true;
10077 
10078   /* If the lhs has been host_associated, is in common, a pointer or is
10079      a target and the function is not using a RESULT variable, aliasing
10080      can occur and a temporary is needed.  */
10081   if ((sym->attr.host_assoc
10082 	   || sym->attr.in_common
10083 	   || sym->attr.pointer
10084 	   || sym->attr.cray_pointee
10085 	   || sym->attr.target)
10086 	&& expr2->symtree != NULL
10087 	&& expr2->symtree->n.sym == expr2->symtree->n.sym->result)
10088     return true;
10089 
10090   /* A PURE function can unconditionally be called without a temporary.  */
10091   if (expr2->value.function.esym != NULL
10092       && expr2->value.function.esym->attr.pure)
10093     return false;
10094 
10095   /* Implicit_pure functions are those which could legally be declared
10096      to be PURE.  */
10097   if (expr2->value.function.esym != NULL
10098       && expr2->value.function.esym->attr.implicit_pure)
10099     return false;
10100 
10101   if (!sym->attr.use_assoc
10102 	&& !sym->attr.in_common
10103 	&& !sym->attr.pointer
10104 	&& !sym->attr.target
10105 	&& !sym->attr.cray_pointee
10106 	&& expr2->value.function.esym)
10107     {
10108       /* A temporary is not needed if the function is not contained and
10109 	 the variable is local or host associated and not a pointer or
10110 	 a target.  */
10111       if (!expr2->value.function.esym->attr.contained)
10112 	return false;
10113 
10114       /* A temporary is not needed if the lhs has never been host
10115 	 associated and the procedure is contained.  */
10116       else if (!sym->attr.host_assoc)
10117 	return false;
10118 
10119       /* A temporary is not needed if the variable is local and not
10120 	 a pointer, a target or a result.  */
10121       if (sym->ns->parent
10122 	    && expr2->value.function.esym->ns == sym->ns->parent)
10123 	return false;
10124     }
10125 
10126   /* Default to temporary use.  */
10127   return true;
10128 }
10129 
10130 
10131 /* Provide the loop info so that the lhs descriptor can be built for
10132    reallocatable assignments from extrinsic function calls.  */
10133 
10134 static void
10135 realloc_lhs_loop_for_fcn_call (gfc_se *se, locus *where, gfc_ss **ss,
10136 			       gfc_loopinfo *loop)
10137 {
10138   /* Signal that the function call should not be made by
10139      gfc_conv_loop_setup.  */
10140   se->ss->is_alloc_lhs = 1;
10141   gfc_init_loopinfo (loop);
10142   gfc_add_ss_to_loop (loop, *ss);
10143   gfc_add_ss_to_loop (loop, se->ss);
10144   gfc_conv_ss_startstride (loop);
10145   gfc_conv_loop_setup (loop, where);
10146   gfc_copy_loopinfo_to_se (se, loop);
10147   gfc_add_block_to_block (&se->pre, &loop->pre);
10148   gfc_add_block_to_block (&se->pre, &loop->post);
10149   se->ss->is_alloc_lhs = 0;
10150 }
10151 
10152 
10153 /* For assignment to a reallocatable lhs from intrinsic functions,
10154    replace the se.expr (ie. the result) with a temporary descriptor.
10155    Null the data field so that the library allocates space for the
10156    result. Free the data of the original descriptor after the function,
10157    in case it appears in an argument expression and transfer the
10158    result to the original descriptor.  */
10159 
10160 static void
10161 fcncall_realloc_result (gfc_se *se, int rank)
10162 {
10163   tree desc;
10164   tree res_desc;
10165   tree tmp;
10166   tree offset;
10167   tree zero_cond;
10168   tree not_same_shape;
10169   stmtblock_t shape_block;
10170   int n;
10171 
10172   /* Use the allocation done by the library.  Substitute the lhs
10173      descriptor with a copy, whose data field is nulled.*/
10174   desc = build_fold_indirect_ref_loc (input_location, se->expr);
10175   if (POINTER_TYPE_P (TREE_TYPE (desc)))
10176     desc = build_fold_indirect_ref_loc (input_location, desc);
10177 
10178   /* Unallocated, the descriptor does not have a dtype.  */
10179   tmp = gfc_conv_descriptor_dtype (desc);
10180   gfc_add_modify (&se->pre, tmp, gfc_get_dtype (TREE_TYPE (desc)));
10181 
10182   res_desc = gfc_evaluate_now (desc, &se->pre);
10183   gfc_conv_descriptor_data_set (&se->pre, res_desc, null_pointer_node);
10184   se->expr = gfc_build_addr_expr (NULL_TREE, res_desc);
10185 
10186   /* Free the lhs after the function call and copy the result data to
10187      the lhs descriptor.  */
10188   tmp = gfc_conv_descriptor_data_get (desc);
10189   zero_cond = fold_build2_loc (input_location, EQ_EXPR,
10190 			       logical_type_node, tmp,
10191 			       build_int_cst (TREE_TYPE (tmp), 0));
10192   zero_cond = gfc_evaluate_now (zero_cond, &se->post);
10193   tmp = gfc_call_free (tmp);
10194   gfc_add_expr_to_block (&se->post, tmp);
10195 
10196   tmp = gfc_conv_descriptor_data_get (res_desc);
10197   gfc_conv_descriptor_data_set (&se->post, desc, tmp);
10198 
10199   /* Check that the shapes are the same between lhs and expression.
10200      The evaluation of the shape is done in 'shape_block' to avoid
10201      unitialized warnings from the lhs bounds. */
10202   not_same_shape = boolean_false_node;
10203   gfc_start_block (&shape_block);
10204   for (n = 0 ; n < rank; n++)
10205     {
10206       tree tmp1;
10207       tmp = gfc_conv_descriptor_lbound_get (desc, gfc_rank_cst[n]);
10208       tmp1 = gfc_conv_descriptor_lbound_get (res_desc, gfc_rank_cst[n]);
10209       tmp = fold_build2_loc (input_location, MINUS_EXPR,
10210 			     gfc_array_index_type, tmp, tmp1);
10211       tmp1 = gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[n]);
10212       tmp = fold_build2_loc (input_location, MINUS_EXPR,
10213 			     gfc_array_index_type, tmp, tmp1);
10214       tmp1 = gfc_conv_descriptor_ubound_get (res_desc, gfc_rank_cst[n]);
10215       tmp = fold_build2_loc (input_location, PLUS_EXPR,
10216 			     gfc_array_index_type, tmp, tmp1);
10217       tmp = fold_build2_loc (input_location, NE_EXPR,
10218 			     logical_type_node, tmp,
10219 			     gfc_index_zero_node);
10220       tmp = gfc_evaluate_now (tmp, &shape_block);
10221       if (n == 0)
10222 	not_same_shape = tmp;
10223       else
10224 	not_same_shape = fold_build2_loc (input_location, TRUTH_OR_EXPR,
10225 					  logical_type_node, tmp,
10226 					  not_same_shape);
10227     }
10228 
10229   /* 'zero_cond' being true is equal to lhs not being allocated or the
10230      shapes being different.  */
10231   tmp = fold_build2_loc (input_location, TRUTH_OR_EXPR, logical_type_node,
10232 			 zero_cond, not_same_shape);
10233   gfc_add_modify (&shape_block, zero_cond, tmp);
10234   tmp = gfc_finish_block (&shape_block);
10235   tmp = build3_v (COND_EXPR, zero_cond,
10236 		  build_empty_stmt (input_location), tmp);
10237   gfc_add_expr_to_block (&se->post, tmp);
10238 
10239   /* Now reset the bounds returned from the function call to bounds based
10240      on the lhs lbounds, except where the lhs is not allocated or the shapes
10241      of 'variable and 'expr' are different. Set the offset accordingly.  */
10242   offset = gfc_index_zero_node;
10243   for (n = 0 ; n < rank; n++)
10244     {
10245       tree lbound;
10246 
10247       lbound = gfc_conv_descriptor_lbound_get (desc, gfc_rank_cst[n]);
10248       lbound = fold_build3_loc (input_location, COND_EXPR,
10249 				gfc_array_index_type, zero_cond,
10250 				gfc_index_one_node, lbound);
10251       lbound = gfc_evaluate_now (lbound, &se->post);
10252 
10253       tmp = gfc_conv_descriptor_ubound_get (res_desc, gfc_rank_cst[n]);
10254       tmp = fold_build2_loc (input_location, PLUS_EXPR,
10255 			     gfc_array_index_type, tmp, lbound);
10256       gfc_conv_descriptor_lbound_set (&se->post, desc,
10257 				      gfc_rank_cst[n], lbound);
10258       gfc_conv_descriptor_ubound_set (&se->post, desc,
10259 				      gfc_rank_cst[n], tmp);
10260 
10261       /* Set stride and accumulate the offset.  */
10262       tmp = gfc_conv_descriptor_stride_get (res_desc, gfc_rank_cst[n]);
10263       gfc_conv_descriptor_stride_set (&se->post, desc,
10264 				      gfc_rank_cst[n], tmp);
10265       tmp = fold_build2_loc (input_location, MULT_EXPR,
10266 			     gfc_array_index_type, lbound, tmp);
10267       offset = fold_build2_loc (input_location, MINUS_EXPR,
10268 				gfc_array_index_type, offset, tmp);
10269       offset = gfc_evaluate_now (offset, &se->post);
10270     }
10271 
10272   gfc_conv_descriptor_offset_set (&se->post, desc, offset);
10273 }
10274 
10275 
10276 
10277 /* Try to translate array(:) = func (...), where func is a transformational
10278    array function, without using a temporary.  Returns NULL if this isn't the
10279    case.  */
10280 
10281 static tree
10282 gfc_trans_arrayfunc_assign (gfc_expr * expr1, gfc_expr * expr2)
10283 {
10284   gfc_se se;
10285   gfc_ss *ss = NULL;
10286   gfc_component *comp = NULL;
10287   gfc_loopinfo loop;
10288 
10289   if (arrayfunc_assign_needs_temporary (expr1, expr2))
10290     return NULL;
10291 
10292   /* The frontend doesn't seem to bother filling in expr->symtree for intrinsic
10293      functions.  */
10294   comp = gfc_get_proc_ptr_comp (expr2);
10295 
10296   if (!(expr2->value.function.isym
10297 	      || (comp && comp->attr.dimension)
10298 	      || (!comp && gfc_return_by_reference (expr2->value.function.esym)
10299 		  && expr2->value.function.esym->result->attr.dimension)))
10300     return NULL;
10301 
10302   gfc_init_se (&se, NULL);
10303   gfc_start_block (&se.pre);
10304   se.want_pointer = 1;
10305 
10306   gfc_conv_array_parameter (&se, expr1, false, NULL, NULL, NULL);
10307 
10308   if (expr1->ts.type == BT_DERIVED
10309 	&& expr1->ts.u.derived->attr.alloc_comp)
10310     {
10311       tree tmp;
10312       tmp = gfc_deallocate_alloc_comp_no_caf (expr1->ts.u.derived, se.expr,
10313 					      expr1->rank);
10314       gfc_add_expr_to_block (&se.pre, tmp);
10315     }
10316 
10317   se.direct_byref = 1;
10318   se.ss = gfc_walk_expr (expr2);
10319   gcc_assert (se.ss != gfc_ss_terminator);
10320 
10321   /* Reallocate on assignment needs the loopinfo for extrinsic functions.
10322      This is signalled to gfc_conv_procedure_call by setting is_alloc_lhs.
10323      Clearly, this cannot be done for an allocatable function result, since
10324      the shape of the result is unknown and, in any case, the function must
10325      correctly take care of the reallocation internally. For intrinsic
10326      calls, the array data is freed and the library takes care of allocation.
10327      TODO: Add logic of trans-array.c: gfc_alloc_allocatable_for_assignment
10328      to the library.  */
10329   if (flag_realloc_lhs
10330 	&& gfc_is_reallocatable_lhs (expr1)
10331 	&& !gfc_expr_attr (expr1).codimension
10332 	&& !gfc_is_coindexed (expr1)
10333 	&& !(expr2->value.function.esym
10334 	    && expr2->value.function.esym->result->attr.allocatable))
10335     {
10336       realloc_lhs_warning (expr1->ts.type, true, &expr1->where);
10337 
10338       if (!expr2->value.function.isym)
10339 	{
10340 	  ss = gfc_walk_expr (expr1);
10341 	  gcc_assert (ss != gfc_ss_terminator);
10342 
10343 	  realloc_lhs_loop_for_fcn_call (&se, &expr1->where, &ss, &loop);
10344 	  ss->is_alloc_lhs = 1;
10345 	}
10346       else
10347 	fcncall_realloc_result (&se, expr1->rank);
10348     }
10349 
10350   gfc_conv_function_expr (&se, expr2);
10351   gfc_add_block_to_block (&se.pre, &se.post);
10352 
10353   if (ss)
10354     gfc_cleanup_loop (&loop);
10355   else
10356     gfc_free_ss_chain (se.ss);
10357 
10358   return gfc_finish_block (&se.pre);
10359 }
10360 
10361 
10362 /* Try to efficiently translate array(:) = 0.  Return NULL if this
10363    can't be done.  */
10364 
10365 static tree
10366 gfc_trans_zero_assign (gfc_expr * expr)
10367 {
10368   tree dest, len, type;
10369   tree tmp;
10370   gfc_symbol *sym;
10371 
10372   sym = expr->symtree->n.sym;
10373   dest = gfc_get_symbol_decl (sym);
10374 
10375   type = TREE_TYPE (dest);
10376   if (POINTER_TYPE_P (type))
10377     type = TREE_TYPE (type);
10378   if (!GFC_ARRAY_TYPE_P (type))
10379     return NULL_TREE;
10380 
10381   /* Determine the length of the array.  */
10382   len = GFC_TYPE_ARRAY_SIZE (type);
10383   if (!len || TREE_CODE (len) != INTEGER_CST)
10384     return NULL_TREE;
10385 
10386   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (type));
10387   len = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type, len,
10388 			 fold_convert (gfc_array_index_type, tmp));
10389 
10390   /* If we are zeroing a local array avoid taking its address by emitting
10391      a = {} instead.  */
10392   if (!POINTER_TYPE_P (TREE_TYPE (dest)))
10393     return build2_loc (input_location, MODIFY_EXPR, void_type_node,
10394 		       dest, build_constructor (TREE_TYPE (dest),
10395 					      NULL));
10396 
10397   /* Convert arguments to the correct types.  */
10398   dest = fold_convert (pvoid_type_node, dest);
10399   len = fold_convert (size_type_node, len);
10400 
10401   /* Construct call to __builtin_memset.  */
10402   tmp = build_call_expr_loc (input_location,
10403 			     builtin_decl_explicit (BUILT_IN_MEMSET),
10404 			     3, dest, integer_zero_node, len);
10405   return fold_convert (void_type_node, tmp);
10406 }
10407 
10408 
10409 /* Helper for gfc_trans_array_copy and gfc_trans_array_constructor_copy
10410    that constructs the call to __builtin_memcpy.  */
10411 
10412 tree
10413 gfc_build_memcpy_call (tree dst, tree src, tree len)
10414 {
10415   tree tmp;
10416 
10417   /* Convert arguments to the correct types.  */
10418   if (!POINTER_TYPE_P (TREE_TYPE (dst)))
10419     dst = gfc_build_addr_expr (pvoid_type_node, dst);
10420   else
10421     dst = fold_convert (pvoid_type_node, dst);
10422 
10423   if (!POINTER_TYPE_P (TREE_TYPE (src)))
10424     src = gfc_build_addr_expr (pvoid_type_node, src);
10425   else
10426     src = fold_convert (pvoid_type_node, src);
10427 
10428   len = fold_convert (size_type_node, len);
10429 
10430   /* Construct call to __builtin_memcpy.  */
10431   tmp = build_call_expr_loc (input_location,
10432 			     builtin_decl_explicit (BUILT_IN_MEMCPY),
10433 			     3, dst, src, len);
10434   return fold_convert (void_type_node, tmp);
10435 }
10436 
10437 
10438 /* Try to efficiently translate dst(:) = src(:).  Return NULL if this
10439    can't be done.  EXPR1 is the destination/lhs and EXPR2 is the
10440    source/rhs, both are gfc_full_array_ref_p which have been checked for
10441    dependencies.  */
10442 
10443 static tree
10444 gfc_trans_array_copy (gfc_expr * expr1, gfc_expr * expr2)
10445 {
10446   tree dst, dlen, dtype;
10447   tree src, slen, stype;
10448   tree tmp;
10449 
10450   dst = gfc_get_symbol_decl (expr1->symtree->n.sym);
10451   src = gfc_get_symbol_decl (expr2->symtree->n.sym);
10452 
10453   dtype = TREE_TYPE (dst);
10454   if (POINTER_TYPE_P (dtype))
10455     dtype = TREE_TYPE (dtype);
10456   stype = TREE_TYPE (src);
10457   if (POINTER_TYPE_P (stype))
10458     stype = TREE_TYPE (stype);
10459 
10460   if (!GFC_ARRAY_TYPE_P (dtype) || !GFC_ARRAY_TYPE_P (stype))
10461     return NULL_TREE;
10462 
10463   /* Determine the lengths of the arrays.  */
10464   dlen = GFC_TYPE_ARRAY_SIZE (dtype);
10465   if (!dlen || TREE_CODE (dlen) != INTEGER_CST)
10466     return NULL_TREE;
10467   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (dtype));
10468   dlen = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
10469 			  dlen, fold_convert (gfc_array_index_type, tmp));
10470 
10471   slen = GFC_TYPE_ARRAY_SIZE (stype);
10472   if (!slen || TREE_CODE (slen) != INTEGER_CST)
10473     return NULL_TREE;
10474   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (stype));
10475   slen = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
10476 			  slen, fold_convert (gfc_array_index_type, tmp));
10477 
10478   /* Sanity check that they are the same.  This should always be
10479      the case, as we should already have checked for conformance.  */
10480   if (!tree_int_cst_equal (slen, dlen))
10481     return NULL_TREE;
10482 
10483   return gfc_build_memcpy_call (dst, src, dlen);
10484 }
10485 
10486 
10487 /* Try to efficiently translate array(:) = (/ ... /).  Return NULL if
10488    this can't be done.  EXPR1 is the destination/lhs for which
10489    gfc_full_array_ref_p is true, and EXPR2 is the source/rhs.  */
10490 
10491 static tree
10492 gfc_trans_array_constructor_copy (gfc_expr * expr1, gfc_expr * expr2)
10493 {
10494   unsigned HOST_WIDE_INT nelem;
10495   tree dst, dtype;
10496   tree src, stype;
10497   tree len;
10498   tree tmp;
10499 
10500   nelem = gfc_constant_array_constructor_p (expr2->value.constructor);
10501   if (nelem == 0)
10502     return NULL_TREE;
10503 
10504   dst = gfc_get_symbol_decl (expr1->symtree->n.sym);
10505   dtype = TREE_TYPE (dst);
10506   if (POINTER_TYPE_P (dtype))
10507     dtype = TREE_TYPE (dtype);
10508   if (!GFC_ARRAY_TYPE_P (dtype))
10509     return NULL_TREE;
10510 
10511   /* Determine the lengths of the array.  */
10512   len = GFC_TYPE_ARRAY_SIZE (dtype);
10513   if (!len || TREE_CODE (len) != INTEGER_CST)
10514     return NULL_TREE;
10515 
10516   /* Confirm that the constructor is the same size.  */
10517   if (compare_tree_int (len, nelem) != 0)
10518     return NULL_TREE;
10519 
10520   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (dtype));
10521   len = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type, len,
10522 			 fold_convert (gfc_array_index_type, tmp));
10523 
10524   stype = gfc_typenode_for_spec (&expr2->ts);
10525   src = gfc_build_constant_array_constructor (expr2, stype);
10526 
10527   return gfc_build_memcpy_call (dst, src, len);
10528 }
10529 
10530 
10531 /* Tells whether the expression is to be treated as a variable reference.  */
10532 
10533 bool
10534 gfc_expr_is_variable (gfc_expr *expr)
10535 {
10536   gfc_expr *arg;
10537   gfc_component *comp;
10538   gfc_symbol *func_ifc;
10539 
10540   if (expr->expr_type == EXPR_VARIABLE)
10541     return true;
10542 
10543   arg = gfc_get_noncopying_intrinsic_argument (expr);
10544   if (arg)
10545     {
10546       gcc_assert (expr->value.function.isym->id == GFC_ISYM_TRANSPOSE);
10547       return gfc_expr_is_variable (arg);
10548     }
10549 
10550   /* A data-pointer-returning function should be considered as a variable
10551      too.  */
10552   if (expr->expr_type == EXPR_FUNCTION
10553       && expr->ref == NULL)
10554     {
10555       if (expr->value.function.isym != NULL)
10556 	return false;
10557 
10558       if (expr->value.function.esym != NULL)
10559 	{
10560 	  func_ifc = expr->value.function.esym;
10561 	  goto found_ifc;
10562 	}
10563       else
10564 	{
10565 	  gcc_assert (expr->symtree);
10566 	  func_ifc = expr->symtree->n.sym;
10567 	  goto found_ifc;
10568 	}
10569 
10570       gcc_unreachable ();
10571     }
10572 
10573   comp = gfc_get_proc_ptr_comp (expr);
10574   if ((expr->expr_type == EXPR_PPC || expr->expr_type == EXPR_FUNCTION)
10575       && comp)
10576     {
10577       func_ifc = comp->ts.interface;
10578       goto found_ifc;
10579     }
10580 
10581   if (expr->expr_type == EXPR_COMPCALL)
10582     {
10583       gcc_assert (!expr->value.compcall.tbp->is_generic);
10584       func_ifc = expr->value.compcall.tbp->u.specific->n.sym;
10585       goto found_ifc;
10586     }
10587 
10588   return false;
10589 
10590 found_ifc:
10591   gcc_assert (func_ifc->attr.function
10592 	      && func_ifc->result != NULL);
10593   return func_ifc->result->attr.pointer;
10594 }
10595 
10596 
10597 /* Is the lhs OK for automatic reallocation?  */
10598 
10599 static bool
10600 is_scalar_reallocatable_lhs (gfc_expr *expr)
10601 {
10602   gfc_ref * ref;
10603 
10604   /* An allocatable variable with no reference.  */
10605   if (expr->symtree->n.sym->attr.allocatable
10606 	&& !expr->ref)
10607     return true;
10608 
10609   /* All that can be left are allocatable components.  However, we do
10610      not check for allocatable components here because the expression
10611      could be an allocatable component of a pointer component.  */
10612   if (expr->symtree->n.sym->ts.type != BT_DERIVED
10613 	&& expr->symtree->n.sym->ts.type != BT_CLASS)
10614     return false;
10615 
10616   /* Find an allocatable component ref last.  */
10617   for (ref = expr->ref; ref; ref = ref->next)
10618     if (ref->type == REF_COMPONENT
10619 	  && !ref->next
10620 	  && ref->u.c.component->attr.allocatable)
10621       return true;
10622 
10623   return false;
10624 }
10625 
10626 
10627 /* Allocate or reallocate scalar lhs, as necessary.  */
10628 
10629 static void
10630 alloc_scalar_allocatable_for_assignment (stmtblock_t *block,
10631 					 tree string_length,
10632 					 gfc_expr *expr1,
10633 					 gfc_expr *expr2)
10634 
10635 {
10636   tree cond;
10637   tree tmp;
10638   tree size;
10639   tree size_in_bytes;
10640   tree jump_label1;
10641   tree jump_label2;
10642   gfc_se lse;
10643   gfc_ref *ref;
10644 
10645   if (!expr1 || expr1->rank)
10646     return;
10647 
10648   if (!expr2 || expr2->rank)
10649     return;
10650 
10651   for (ref = expr1->ref; ref; ref = ref->next)
10652     if (ref->type == REF_SUBSTRING)
10653       return;
10654 
10655   realloc_lhs_warning (expr2->ts.type, false, &expr2->where);
10656 
10657   /* Since this is a scalar lhs, we can afford to do this.  That is,
10658      there is no risk of side effects being repeated.  */
10659   gfc_init_se (&lse, NULL);
10660   lse.want_pointer = 1;
10661   gfc_conv_expr (&lse, expr1);
10662 
10663   jump_label1 = gfc_build_label_decl (NULL_TREE);
10664   jump_label2 = gfc_build_label_decl (NULL_TREE);
10665 
10666   /* Do the allocation if the lhs is NULL. Otherwise go to label 1.  */
10667   tmp = build_int_cst (TREE_TYPE (lse.expr), 0);
10668   cond = fold_build2_loc (input_location, NE_EXPR, logical_type_node,
10669 			  lse.expr, tmp);
10670   tmp = build3_v (COND_EXPR, cond,
10671 		  build1_v (GOTO_EXPR, jump_label1),
10672 		  build_empty_stmt (input_location));
10673   gfc_add_expr_to_block (block, tmp);
10674 
10675   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
10676     {
10677       /* Use the rhs string length and the lhs element size.  */
10678       size = string_length;
10679       tmp = TREE_TYPE (gfc_typenode_for_spec (&expr1->ts));
10680       tmp = TYPE_SIZE_UNIT (tmp);
10681       size_in_bytes = fold_build2_loc (input_location, MULT_EXPR,
10682 				       TREE_TYPE (tmp), tmp,
10683 				       fold_convert (TREE_TYPE (tmp), size));
10684     }
10685   else
10686     {
10687       /* Otherwise use the length in bytes of the rhs.  */
10688       size = TYPE_SIZE_UNIT (gfc_typenode_for_spec (&expr1->ts));
10689       size_in_bytes = size;
10690     }
10691 
10692   size_in_bytes = fold_build2_loc (input_location, MAX_EXPR, size_type_node,
10693 				   size_in_bytes, size_one_node);
10694 
10695   if (gfc_caf_attr (expr1).codimension && flag_coarray == GFC_FCOARRAY_LIB)
10696     {
10697       tree caf_decl, token;
10698       gfc_se caf_se;
10699       symbol_attribute attr;
10700 
10701       gfc_clear_attr (&attr);
10702       gfc_init_se (&caf_se, NULL);
10703 
10704       caf_decl = gfc_get_tree_for_caf_expr (expr1);
10705       gfc_get_caf_token_offset (&caf_se, &token, NULL, caf_decl, NULL_TREE,
10706 				NULL);
10707       gfc_add_block_to_block (block, &caf_se.pre);
10708       gfc_allocate_allocatable (block, lse.expr, size_in_bytes,
10709 				gfc_build_addr_expr (NULL_TREE, token),
10710 				NULL_TREE, NULL_TREE, NULL_TREE, jump_label1,
10711 				expr1, 1);
10712     }
10713   else if (expr1->ts.type == BT_DERIVED && expr1->ts.u.derived->attr.alloc_comp)
10714     {
10715       tmp = build_call_expr_loc (input_location,
10716 				 builtin_decl_explicit (BUILT_IN_CALLOC),
10717 				 2, build_one_cst (size_type_node),
10718 				 size_in_bytes);
10719       tmp = fold_convert (TREE_TYPE (lse.expr), tmp);
10720       gfc_add_modify (block, lse.expr, tmp);
10721     }
10722   else
10723     {
10724       tmp = build_call_expr_loc (input_location,
10725 				 builtin_decl_explicit (BUILT_IN_MALLOC),
10726 				 1, size_in_bytes);
10727       tmp = fold_convert (TREE_TYPE (lse.expr), tmp);
10728       gfc_add_modify (block, lse.expr, tmp);
10729     }
10730 
10731   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
10732     {
10733       /* Deferred characters need checking for lhs and rhs string
10734 	 length.  Other deferred parameter variables will have to
10735 	 come here too.  */
10736       tmp = build1_v (GOTO_EXPR, jump_label2);
10737       gfc_add_expr_to_block (block, tmp);
10738     }
10739   tmp = build1_v (LABEL_EXPR, jump_label1);
10740   gfc_add_expr_to_block (block, tmp);
10741 
10742   /* For a deferred length character, reallocate if lengths of lhs and
10743      rhs are different.  */
10744   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
10745     {
10746       cond = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
10747 			      lse.string_length,
10748 			      fold_convert (TREE_TYPE (lse.string_length),
10749 					    size));
10750       /* Jump past the realloc if the lengths are the same.  */
10751       tmp = build3_v (COND_EXPR, cond,
10752 		      build1_v (GOTO_EXPR, jump_label2),
10753 		      build_empty_stmt (input_location));
10754       gfc_add_expr_to_block (block, tmp);
10755       tmp = build_call_expr_loc (input_location,
10756 				 builtin_decl_explicit (BUILT_IN_REALLOC),
10757 				 2, fold_convert (pvoid_type_node, lse.expr),
10758 				 size_in_bytes);
10759       tmp = fold_convert (TREE_TYPE (lse.expr), tmp);
10760       gfc_add_modify (block, lse.expr, tmp);
10761       tmp = build1_v (LABEL_EXPR, jump_label2);
10762       gfc_add_expr_to_block (block, tmp);
10763 
10764       /* Update the lhs character length.  */
10765       size = string_length;
10766       gfc_add_modify (block, lse.string_length,
10767 		      fold_convert (TREE_TYPE (lse.string_length), size));
10768     }
10769 }
10770 
10771 /* Check for assignments of the type
10772 
10773    a = a + 4
10774 
10775    to make sure we do not check for reallocation unneccessarily.  */
10776 
10777 
10778 static bool
10779 is_runtime_conformable (gfc_expr *expr1, gfc_expr *expr2)
10780 {
10781   gfc_actual_arglist *a;
10782   gfc_expr *e1, *e2;
10783 
10784   switch (expr2->expr_type)
10785     {
10786     case EXPR_VARIABLE:
10787       return gfc_dep_compare_expr (expr1, expr2) == 0;
10788 
10789     case EXPR_FUNCTION:
10790       if (expr2->value.function.esym
10791 	  && expr2->value.function.esym->attr.elemental)
10792 	{
10793 	  for (a = expr2->value.function.actual; a != NULL; a = a->next)
10794 	    {
10795 	      e1 = a->expr;
10796 	      if (e1 && e1->rank > 0 && !is_runtime_conformable (expr1, e1))
10797 		return false;
10798 	    }
10799 	  return true;
10800 	}
10801       else if (expr2->value.function.isym
10802 	       && expr2->value.function.isym->elemental)
10803 	{
10804 	  for (a = expr2->value.function.actual; a != NULL; a = a->next)
10805 	    {
10806 	      e1 = a->expr;
10807 	      if (e1 && e1->rank > 0 && !is_runtime_conformable (expr1, e1))
10808 		return false;
10809 	    }
10810 	  return true;
10811 	}
10812 
10813       break;
10814 
10815     case EXPR_OP:
10816       switch (expr2->value.op.op)
10817 	{
10818 	case INTRINSIC_NOT:
10819 	case INTRINSIC_UPLUS:
10820 	case INTRINSIC_UMINUS:
10821 	case INTRINSIC_PARENTHESES:
10822 	  return is_runtime_conformable (expr1, expr2->value.op.op1);
10823 
10824 	case INTRINSIC_PLUS:
10825 	case INTRINSIC_MINUS:
10826 	case INTRINSIC_TIMES:
10827 	case INTRINSIC_DIVIDE:
10828 	case INTRINSIC_POWER:
10829 	case INTRINSIC_AND:
10830 	case INTRINSIC_OR:
10831 	case INTRINSIC_EQV:
10832 	case INTRINSIC_NEQV:
10833 	case INTRINSIC_EQ:
10834 	case INTRINSIC_NE:
10835 	case INTRINSIC_GT:
10836 	case INTRINSIC_GE:
10837 	case INTRINSIC_LT:
10838 	case INTRINSIC_LE:
10839 	case INTRINSIC_EQ_OS:
10840 	case INTRINSIC_NE_OS:
10841 	case INTRINSIC_GT_OS:
10842 	case INTRINSIC_GE_OS:
10843 	case INTRINSIC_LT_OS:
10844 	case INTRINSIC_LE_OS:
10845 
10846 	  e1 = expr2->value.op.op1;
10847 	  e2 = expr2->value.op.op2;
10848 
10849 	  if (e1->rank == 0 && e2->rank > 0)
10850 	    return is_runtime_conformable (expr1, e2);
10851 	  else if (e1->rank > 0 && e2->rank == 0)
10852 	    return is_runtime_conformable (expr1, e1);
10853 	  else if (e1->rank > 0 && e2->rank > 0)
10854 	    return is_runtime_conformable (expr1, e1)
10855 	      && is_runtime_conformable (expr1, e2);
10856 	  break;
10857 
10858 	default:
10859 	  break;
10860 
10861 	}
10862 
10863       break;
10864 
10865     default:
10866       break;
10867     }
10868   return false;
10869 }
10870 
10871 
10872 static tree
10873 trans_class_assignment (stmtblock_t *block, gfc_expr *lhs, gfc_expr *rhs,
10874 			gfc_se *lse, gfc_se *rse, bool use_vptr_copy,
10875 			bool class_realloc)
10876 {
10877   tree tmp, fcn, stdcopy, to_len, from_len, vptr, old_vptr;
10878   vec<tree, va_gc> *args = NULL;
10879 
10880   /* Store the old vptr so that dynamic types can be compared for
10881      reallocation to occur or not.  */
10882   if (class_realloc)
10883     {
10884       tmp = lse->expr;
10885       if (!GFC_CLASS_TYPE_P (TREE_TYPE (tmp)))
10886 	tmp = gfc_get_class_from_expr (tmp);
10887     }
10888 
10889   vptr = trans_class_vptr_len_assignment (block, lhs, rhs, rse, &to_len,
10890 					 &from_len);
10891 
10892   /* Generate (re)allocation of the lhs.  */
10893   if (class_realloc)
10894     {
10895       stmtblock_t alloc, re_alloc;
10896       tree class_han, re, size;
10897 
10898       if (tmp && GFC_CLASS_TYPE_P (TREE_TYPE (tmp)))
10899 	old_vptr = gfc_evaluate_now (gfc_class_vptr_get (tmp), block);
10900       else
10901 	old_vptr = build_int_cst (TREE_TYPE (vptr), 0);
10902 
10903       size = gfc_vptr_size_get (vptr);
10904       class_han = GFC_CLASS_TYPE_P (TREE_TYPE (lse->expr))
10905 	  ? gfc_class_data_get (lse->expr) : lse->expr;
10906 
10907       /* Allocate block.  */
10908       gfc_init_block (&alloc);
10909       gfc_allocate_using_malloc (&alloc, class_han, size, NULL_TREE);
10910 
10911       /* Reallocate if dynamic types are different. */
10912       gfc_init_block (&re_alloc);
10913       re = build_call_expr_loc (input_location,
10914 				builtin_decl_explicit (BUILT_IN_REALLOC), 2,
10915 				fold_convert (pvoid_type_node, class_han),
10916 				size);
10917       tmp = fold_build2_loc (input_location, NE_EXPR,
10918 			     logical_type_node, vptr, old_vptr);
10919       re = fold_build3_loc (input_location, COND_EXPR, void_type_node,
10920 			    tmp, re, build_empty_stmt (input_location));
10921       gfc_add_expr_to_block (&re_alloc, re);
10922 
10923       /* Allocate if _data is NULL, reallocate otherwise.  */
10924       tmp = fold_build2_loc (input_location, EQ_EXPR,
10925 			     logical_type_node, class_han,
10926 			     build_int_cst (prvoid_type_node, 0));
10927       tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node,
10928 			     gfc_unlikely (tmp,
10929 					   PRED_FORTRAN_FAIL_ALLOC),
10930 			     gfc_finish_block (&alloc),
10931 			     gfc_finish_block (&re_alloc));
10932       gfc_add_expr_to_block (&lse->pre, tmp);
10933     }
10934 
10935   fcn = gfc_vptr_copy_get (vptr);
10936 
10937   tmp = GFC_CLASS_TYPE_P (TREE_TYPE (rse->expr))
10938       ? gfc_class_data_get (rse->expr) : rse->expr;
10939   if (use_vptr_copy)
10940     {
10941       if (!POINTER_TYPE_P (TREE_TYPE (tmp))
10942 	  || INDIRECT_REF_P (tmp)
10943 	  || (rhs->ts.type == BT_DERIVED
10944 	      && rhs->ts.u.derived->attr.unlimited_polymorphic
10945 	      && !rhs->ts.u.derived->attr.pointer
10946 	      && !rhs->ts.u.derived->attr.allocatable)
10947 	  || (UNLIMITED_POLY (rhs)
10948 	      && !CLASS_DATA (rhs)->attr.pointer
10949 	      && !CLASS_DATA (rhs)->attr.allocatable))
10950 	vec_safe_push (args, gfc_build_addr_expr (NULL_TREE, tmp));
10951       else
10952 	vec_safe_push (args, tmp);
10953       tmp = GFC_CLASS_TYPE_P (TREE_TYPE (lse->expr))
10954 	  ? gfc_class_data_get (lse->expr) : lse->expr;
10955       if (!POINTER_TYPE_P (TREE_TYPE (tmp))
10956 	  || INDIRECT_REF_P (tmp)
10957 	  || (lhs->ts.type == BT_DERIVED
10958 	      && lhs->ts.u.derived->attr.unlimited_polymorphic
10959 	      && !lhs->ts.u.derived->attr.pointer
10960 	      && !lhs->ts.u.derived->attr.allocatable)
10961 	  || (UNLIMITED_POLY (lhs)
10962 	      && !CLASS_DATA (lhs)->attr.pointer
10963 	      && !CLASS_DATA (lhs)->attr.allocatable))
10964 	vec_safe_push (args, gfc_build_addr_expr (NULL_TREE, tmp));
10965       else
10966 	vec_safe_push (args, tmp);
10967 
10968       stdcopy = build_call_vec (TREE_TYPE (TREE_TYPE (fcn)), fcn, args);
10969 
10970       if (to_len != NULL_TREE && !integer_zerop (from_len))
10971 	{
10972 	  tree extcopy;
10973 	  vec_safe_push (args, from_len);
10974 	  vec_safe_push (args, to_len);
10975 	  extcopy = build_call_vec (TREE_TYPE (TREE_TYPE (fcn)), fcn, args);
10976 
10977 	  tmp = fold_build2_loc (input_location, GT_EXPR,
10978 				 logical_type_node, from_len,
10979 				 build_zero_cst (TREE_TYPE (from_len)));
10980 	  return fold_build3_loc (input_location, COND_EXPR,
10981 				  void_type_node, tmp,
10982 				  extcopy, stdcopy);
10983 	}
10984       else
10985 	return stdcopy;
10986     }
10987   else
10988     {
10989       tree rhst = GFC_CLASS_TYPE_P (TREE_TYPE (lse->expr))
10990 	  ? gfc_class_data_get (lse->expr) : lse->expr;
10991       stmtblock_t tblock;
10992       gfc_init_block (&tblock);
10993       if (!POINTER_TYPE_P (TREE_TYPE (tmp)))
10994 	tmp = gfc_build_addr_expr (NULL_TREE, tmp);
10995       if (!POINTER_TYPE_P (TREE_TYPE (rhst)))
10996 	rhst = gfc_build_addr_expr (NULL_TREE, rhst);
10997       /* When coming from a ptr_copy lhs and rhs are swapped.  */
10998       gfc_add_modify_loc (input_location, &tblock, rhst,
10999 			  fold_convert (TREE_TYPE (rhst), tmp));
11000       return gfc_finish_block (&tblock);
11001     }
11002 }
11003 
11004 /* Subroutine of gfc_trans_assignment that actually scalarizes the
11005    assignment.  EXPR1 is the destination/LHS and EXPR2 is the source/RHS.
11006    init_flag indicates initialization expressions and dealloc that no
11007    deallocate prior assignment is needed (if in doubt, set true).
11008    When PTR_COPY is set and expr1 is a class type, then use the _vptr-copy
11009    routine instead of a pointer assignment.  Alias resolution is only done,
11010    when MAY_ALIAS is set (the default).  This flag is used by ALLOCATE()
11011    where it is known, that newly allocated memory on the lhs can never be
11012    an alias of the rhs.  */
11013 
11014 static tree
11015 gfc_trans_assignment_1 (gfc_expr * expr1, gfc_expr * expr2, bool init_flag,
11016 			bool dealloc, bool use_vptr_copy, bool may_alias)
11017 {
11018   gfc_se lse;
11019   gfc_se rse;
11020   gfc_ss *lss;
11021   gfc_ss *lss_section;
11022   gfc_ss *rss;
11023   gfc_loopinfo loop;
11024   tree tmp;
11025   stmtblock_t block;
11026   stmtblock_t body;
11027   bool l_is_temp;
11028   bool scalar_to_array;
11029   tree string_length;
11030   int n;
11031   bool maybe_workshare = false, lhs_refs_comp = false, rhs_refs_comp = false;
11032   symbol_attribute lhs_caf_attr, rhs_caf_attr, lhs_attr;
11033   bool is_poly_assign;
11034   bool realloc_flag;
11035 
11036   /* Assignment of the form lhs = rhs.  */
11037   gfc_start_block (&block);
11038 
11039   gfc_init_se (&lse, NULL);
11040   gfc_init_se (&rse, NULL);
11041 
11042   /* Walk the lhs.  */
11043   lss = gfc_walk_expr (expr1);
11044   if (gfc_is_reallocatable_lhs (expr1))
11045     {
11046       lss->no_bounds_check = 1;
11047       if (!(expr2->expr_type == EXPR_FUNCTION
11048 	    && expr2->value.function.isym != NULL
11049 	    && !(expr2->value.function.isym->elemental
11050 		 || expr2->value.function.isym->conversion)))
11051 	lss->is_alloc_lhs = 1;
11052     }
11053   else
11054     lss->no_bounds_check = expr1->no_bounds_check;
11055 
11056   rss = NULL;
11057 
11058   if ((expr1->ts.type == BT_DERIVED)
11059       && (gfc_is_class_array_function (expr2)
11060 	  || gfc_is_alloc_class_scalar_function (expr2)))
11061     expr2->must_finalize = 1;
11062 
11063   /* Checking whether a class assignment is desired is quite complicated and
11064      needed at two locations, so do it once only before the information is
11065      needed.  */
11066   lhs_attr = gfc_expr_attr (expr1);
11067   is_poly_assign = (use_vptr_copy || lhs_attr.pointer
11068 		    || (lhs_attr.allocatable && !lhs_attr.dimension))
11069 		   && (expr1->ts.type == BT_CLASS
11070 		       || gfc_is_class_array_ref (expr1, NULL)
11071 		       || gfc_is_class_scalar_expr (expr1)
11072 		       || gfc_is_class_array_ref (expr2, NULL)
11073 		       || gfc_is_class_scalar_expr (expr2))
11074 		   && lhs_attr.flavor != FL_PROCEDURE;
11075 
11076   realloc_flag = flag_realloc_lhs
11077 		 && gfc_is_reallocatable_lhs (expr1)
11078 		 && expr2->rank
11079 		 && !is_runtime_conformable (expr1, expr2);
11080 
11081   /* Only analyze the expressions for coarray properties, when in coarray-lib
11082      mode.  */
11083   if (flag_coarray == GFC_FCOARRAY_LIB)
11084     {
11085       lhs_caf_attr = gfc_caf_attr (expr1, false, &lhs_refs_comp);
11086       rhs_caf_attr = gfc_caf_attr (expr2, false, &rhs_refs_comp);
11087     }
11088 
11089   if (lss != gfc_ss_terminator)
11090     {
11091       /* The assignment needs scalarization.  */
11092       lss_section = lss;
11093 
11094       /* Find a non-scalar SS from the lhs.  */
11095       while (lss_section != gfc_ss_terminator
11096 	     && lss_section->info->type != GFC_SS_SECTION)
11097 	lss_section = lss_section->next;
11098 
11099       gcc_assert (lss_section != gfc_ss_terminator);
11100 
11101       /* Initialize the scalarizer.  */
11102       gfc_init_loopinfo (&loop);
11103 
11104       /* Walk the rhs.  */
11105       rss = gfc_walk_expr (expr2);
11106       if (rss == gfc_ss_terminator)
11107 	/* The rhs is scalar.  Add a ss for the expression.  */
11108 	rss = gfc_get_scalar_ss (gfc_ss_terminator, expr2);
11109       /* When doing a class assign, then the handle to the rhs needs to be a
11110 	 pointer to allow for polymorphism.  */
11111       if (is_poly_assign && expr2->rank == 0 && !UNLIMITED_POLY (expr2))
11112 	rss->info->type = GFC_SS_REFERENCE;
11113 
11114       rss->no_bounds_check = expr2->no_bounds_check;
11115       /* Associate the SS with the loop.  */
11116       gfc_add_ss_to_loop (&loop, lss);
11117       gfc_add_ss_to_loop (&loop, rss);
11118 
11119       /* Calculate the bounds of the scalarization.  */
11120       gfc_conv_ss_startstride (&loop);
11121       /* Enable loop reversal.  */
11122       for (n = 0; n < GFC_MAX_DIMENSIONS; n++)
11123 	loop.reverse[n] = GFC_ENABLE_REVERSE;
11124       /* Resolve any data dependencies in the statement.  */
11125       if (may_alias)
11126 	gfc_conv_resolve_dependencies (&loop, lss, rss);
11127       /* Setup the scalarizing loops.  */
11128       gfc_conv_loop_setup (&loop, &expr2->where);
11129 
11130       /* Setup the gfc_se structures.  */
11131       gfc_copy_loopinfo_to_se (&lse, &loop);
11132       gfc_copy_loopinfo_to_se (&rse, &loop);
11133 
11134       rse.ss = rss;
11135       gfc_mark_ss_chain_used (rss, 1);
11136       if (loop.temp_ss == NULL)
11137 	{
11138 	  lse.ss = lss;
11139 	  gfc_mark_ss_chain_used (lss, 1);
11140 	}
11141       else
11142 	{
11143 	  lse.ss = loop.temp_ss;
11144 	  gfc_mark_ss_chain_used (lss, 3);
11145 	  gfc_mark_ss_chain_used (loop.temp_ss, 3);
11146 	}
11147 
11148       /* Allow the scalarizer to workshare array assignments.  */
11149       if ((ompws_flags & (OMPWS_WORKSHARE_FLAG | OMPWS_SCALARIZER_BODY))
11150 	  == OMPWS_WORKSHARE_FLAG
11151 	  && loop.temp_ss == NULL)
11152 	{
11153 	  maybe_workshare = true;
11154 	  ompws_flags |= OMPWS_SCALARIZER_WS | OMPWS_SCALARIZER_BODY;
11155 	}
11156 
11157       /* Start the scalarized loop body.  */
11158       gfc_start_scalarized_body (&loop, &body);
11159     }
11160   else
11161     gfc_init_block (&body);
11162 
11163   l_is_temp = (lss != gfc_ss_terminator && loop.temp_ss != NULL);
11164 
11165   /* Translate the expression.  */
11166   rse.want_coarray = flag_coarray == GFC_FCOARRAY_LIB && init_flag
11167       && lhs_caf_attr.codimension;
11168   gfc_conv_expr (&rse, expr2);
11169 
11170   /* Deal with the case of a scalar class function assigned to a derived type.  */
11171   if (gfc_is_alloc_class_scalar_function (expr2)
11172       && expr1->ts.type == BT_DERIVED)
11173     {
11174       rse.expr = gfc_class_data_get (rse.expr);
11175       rse.expr = build_fold_indirect_ref_loc (input_location, rse.expr);
11176     }
11177 
11178   /* Stabilize a string length for temporaries.  */
11179   if (expr2->ts.type == BT_CHARACTER && !expr1->ts.deferred
11180       && !(VAR_P (rse.string_length)
11181 	   || TREE_CODE (rse.string_length) == PARM_DECL
11182 	   || TREE_CODE (rse.string_length) == INDIRECT_REF))
11183     string_length = gfc_evaluate_now (rse.string_length, &rse.pre);
11184   else if (expr2->ts.type == BT_CHARACTER)
11185     {
11186       if (expr1->ts.deferred
11187 	  && gfc_expr_attr (expr1).allocatable
11188 	  && gfc_check_dependency (expr1, expr2, true))
11189 	rse.string_length =
11190 	  gfc_evaluate_now_function_scope (rse.string_length, &rse.pre);
11191       string_length = rse.string_length;
11192     }
11193   else
11194     string_length = NULL_TREE;
11195 
11196   if (l_is_temp)
11197     {
11198       gfc_conv_tmp_array_ref (&lse);
11199       if (expr2->ts.type == BT_CHARACTER)
11200 	lse.string_length = string_length;
11201     }
11202   else
11203     {
11204       gfc_conv_expr (&lse, expr1);
11205       if (gfc_option.rtcheck & GFC_RTCHECK_MEM
11206 	  && !init_flag
11207 	  && gfc_expr_attr (expr1).allocatable
11208 	  && expr1->rank
11209 	  && !expr2->rank)
11210 	{
11211 	  tree cond;
11212 	  const char* msg;
11213 
11214 	  tmp = INDIRECT_REF_P (lse.expr)
11215 	      ? gfc_build_addr_expr (NULL_TREE, lse.expr) : lse.expr;
11216 
11217 	  /* We should only get array references here.  */
11218 	  gcc_assert (TREE_CODE (tmp) == POINTER_PLUS_EXPR
11219 		      || TREE_CODE (tmp) == ARRAY_REF);
11220 
11221 	  /* 'tmp' is either the pointer to the array(POINTER_PLUS_EXPR)
11222 	     or the array itself(ARRAY_REF).  */
11223 	  tmp = TREE_OPERAND (tmp, 0);
11224 
11225 	  /* Provide the address of the array.  */
11226 	  if (TREE_CODE (lse.expr) == ARRAY_REF)
11227 	    tmp = gfc_build_addr_expr (NULL_TREE, tmp);
11228 
11229 	  cond = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
11230 				  tmp, build_int_cst (TREE_TYPE (tmp), 0));
11231 	  msg = _("Assignment of scalar to unallocated array");
11232 	  gfc_trans_runtime_check (true, false, cond, &loop.pre,
11233 				   &expr1->where, msg);
11234 	}
11235 
11236       /* Deallocate the lhs parameterized components if required.  */
11237       if (dealloc && expr2->expr_type == EXPR_FUNCTION
11238 	  && !expr1->symtree->n.sym->attr.associate_var)
11239 	{
11240 	  if (expr1->ts.type == BT_DERIVED
11241 	      && expr1->ts.u.derived
11242 	      && expr1->ts.u.derived->attr.pdt_type)
11243 	    {
11244 	      tmp = gfc_deallocate_pdt_comp (expr1->ts.u.derived, lse.expr,
11245 					     expr1->rank);
11246 	      gfc_add_expr_to_block (&lse.pre, tmp);
11247 	    }
11248 	  else if (expr1->ts.type == BT_CLASS
11249 		   && CLASS_DATA (expr1)->ts.u.derived
11250 		   && CLASS_DATA (expr1)->ts.u.derived->attr.pdt_type)
11251 	    {
11252 	      tmp = gfc_class_data_get (lse.expr);
11253 	      tmp = gfc_deallocate_pdt_comp (CLASS_DATA (expr1)->ts.u.derived,
11254 					     tmp, expr1->rank);
11255 	      gfc_add_expr_to_block (&lse.pre, tmp);
11256 	    }
11257 	}
11258     }
11259 
11260   /* Assignments of scalar derived types with allocatable components
11261      to arrays must be done with a deep copy and the rhs temporary
11262      must have its components deallocated afterwards.  */
11263   scalar_to_array = (expr2->ts.type == BT_DERIVED
11264 		       && expr2->ts.u.derived->attr.alloc_comp
11265 		       && !gfc_expr_is_variable (expr2)
11266 		       && expr1->rank && !expr2->rank);
11267   scalar_to_array |= (expr1->ts.type == BT_DERIVED
11268 				    && expr1->rank
11269 				    && expr1->ts.u.derived->attr.alloc_comp
11270 				    && gfc_is_alloc_class_scalar_function (expr2));
11271   if (scalar_to_array && dealloc)
11272     {
11273       tmp = gfc_deallocate_alloc_comp_no_caf (expr2->ts.u.derived, rse.expr, 0);
11274       gfc_prepend_expr_to_block (&loop.post, tmp);
11275     }
11276 
11277   /* When assigning a character function result to a deferred-length variable,
11278      the function call must happen before the (re)allocation of the lhs -
11279      otherwise the character length of the result is not known.
11280      NOTE 1: This relies on having the exact dependence of the length type
11281      parameter available to the caller; gfortran saves it in the .mod files.
11282      NOTE 2: Vector array references generate an index temporary that must
11283      not go outside the loop. Otherwise, variables should not generate
11284      a pre block.
11285      NOTE 3: The concatenation operation generates a temporary pointer,
11286      whose allocation must go to the innermost loop.
11287      NOTE 4: Elemental functions may generate a temporary, too.  */
11288   if (flag_realloc_lhs
11289       && expr2->ts.type == BT_CHARACTER && expr1->ts.deferred
11290       && !(lss != gfc_ss_terminator
11291 	   && rss != gfc_ss_terminator
11292 	   && ((expr2->expr_type == EXPR_VARIABLE && expr2->rank)
11293 	       || (expr2->expr_type == EXPR_FUNCTION
11294 		   && expr2->value.function.esym != NULL
11295 		   && expr2->value.function.esym->attr.elemental)
11296 	       || (expr2->expr_type == EXPR_FUNCTION
11297 		   && expr2->value.function.isym != NULL
11298 		   && expr2->value.function.isym->elemental)
11299 	       || (expr2->expr_type == EXPR_OP
11300 		   && expr2->value.op.op == INTRINSIC_CONCAT))))
11301     gfc_add_block_to_block (&block, &rse.pre);
11302 
11303   /* Nullify the allocatable components corresponding to those of the lhs
11304      derived type, so that the finalization of the function result does not
11305      affect the lhs of the assignment. Prepend is used to ensure that the
11306      nullification occurs before the call to the finalizer. In the case of
11307      a scalar to array assignment, this is done in gfc_trans_scalar_assign
11308      as part of the deep copy.  */
11309   if (!scalar_to_array && expr1->ts.type == BT_DERIVED
11310 		       && (gfc_is_class_array_function (expr2)
11311 			   || gfc_is_alloc_class_scalar_function (expr2)))
11312     {
11313       tmp = gfc_nullify_alloc_comp (expr1->ts.u.derived, rse.expr, 0);
11314       gfc_prepend_expr_to_block (&rse.post, tmp);
11315       if (lss != gfc_ss_terminator && rss == gfc_ss_terminator)
11316 	gfc_add_block_to_block (&loop.post, &rse.post);
11317     }
11318 
11319   tmp = NULL_TREE;
11320 
11321   if (is_poly_assign)
11322     {
11323       tmp = trans_class_assignment (&body, expr1, expr2, &lse, &rse,
11324 				    use_vptr_copy || (lhs_attr.allocatable
11325 						      && !lhs_attr.dimension),
11326 				    !realloc_flag && flag_realloc_lhs
11327 				    && !lhs_attr.pointer);
11328       if (expr2->expr_type == EXPR_FUNCTION
11329 	  && expr2->ts.type == BT_DERIVED
11330 	  && expr2->ts.u.derived->attr.alloc_comp)
11331 	{
11332 	  tree tmp2 = gfc_deallocate_alloc_comp (expr2->ts.u.derived,
11333 						 rse.expr, expr2->rank);
11334 	  if (lss == gfc_ss_terminator)
11335 	    gfc_add_expr_to_block (&rse.post, tmp2);
11336 	  else
11337 	    gfc_add_expr_to_block (&loop.post, tmp2);
11338 	}
11339     }
11340   else if (flag_coarray == GFC_FCOARRAY_LIB
11341 	   && lhs_caf_attr.codimension && rhs_caf_attr.codimension
11342 	   && ((lhs_caf_attr.allocatable && lhs_refs_comp)
11343 	       || (rhs_caf_attr.allocatable && rhs_refs_comp)))
11344     {
11345       /* Only detour to caf_send[get][_by_ref] () when the lhs or rhs is an
11346 	 allocatable component, because those need to be accessed via the
11347 	 caf-runtime.  No need to check for coindexes here, because resolve
11348 	 has rewritten those already.  */
11349       gfc_code code;
11350       gfc_actual_arglist a1, a2;
11351       /* Clear the structures to prevent accessing garbage.  */
11352       memset (&code, '\0', sizeof (gfc_code));
11353       memset (&a1, '\0', sizeof (gfc_actual_arglist));
11354       memset (&a2, '\0', sizeof (gfc_actual_arglist));
11355       a1.expr = expr1;
11356       a1.next = &a2;
11357       a2.expr = expr2;
11358       a2.next = NULL;
11359       code.ext.actual = &a1;
11360       code.resolved_isym = gfc_intrinsic_subroutine_by_id (GFC_ISYM_CAF_SEND);
11361       tmp = gfc_conv_intrinsic_subroutine (&code);
11362     }
11363   else if (!is_poly_assign && expr2->must_finalize
11364 	   && expr1->ts.type == BT_CLASS
11365 	   && expr2->ts.type == BT_CLASS)
11366     {
11367       /* This case comes about when the scalarizer provides array element
11368 	 references. Use the vptr copy function, since this does a deep
11369 	 copy of allocatable components, without which the finalizer call
11370 	 will deallocate the components.  */
11371       tmp = gfc_get_vptr_from_expr (rse.expr);
11372       if (tmp != NULL_TREE)
11373 	{
11374 	  tree fcn = gfc_vptr_copy_get (tmp);
11375 	  if (POINTER_TYPE_P (TREE_TYPE (fcn)))
11376 	    fcn = build_fold_indirect_ref_loc (input_location, fcn);
11377 	  tmp = build_call_expr_loc (input_location,
11378 				     fcn, 2,
11379 				     gfc_build_addr_expr (NULL, rse.expr),
11380 				     gfc_build_addr_expr (NULL, lse.expr));
11381 	}
11382     }
11383 
11384   /* If nothing else works, do it the old fashioned way!  */
11385   if (tmp == NULL_TREE)
11386     tmp = gfc_trans_scalar_assign (&lse, &rse, expr1->ts,
11387 				   gfc_expr_is_variable (expr2)
11388 				   || scalar_to_array
11389 				   || expr2->expr_type == EXPR_ARRAY,
11390 				   !(l_is_temp || init_flag) && dealloc,
11391 				   expr1->symtree->n.sym->attr.codimension);
11392 
11393   /* Add the pre blocks to the body.  */
11394   gfc_add_block_to_block (&body, &rse.pre);
11395   gfc_add_block_to_block (&body, &lse.pre);
11396   gfc_add_expr_to_block (&body, tmp);
11397   /* Add the post blocks to the body.  */
11398   gfc_add_block_to_block (&body, &rse.post);
11399   gfc_add_block_to_block (&body, &lse.post);
11400 
11401   if (lss == gfc_ss_terminator)
11402     {
11403       /* F2003: Add the code for reallocation on assignment.  */
11404       if (flag_realloc_lhs && is_scalar_reallocatable_lhs (expr1)
11405 	  && !is_poly_assign)
11406 	alloc_scalar_allocatable_for_assignment (&block, string_length,
11407 						 expr1, expr2);
11408 
11409       /* Use the scalar assignment as is.  */
11410       gfc_add_block_to_block (&block, &body);
11411     }
11412   else
11413     {
11414       gcc_assert (lse.ss == gfc_ss_terminator
11415 		  && rse.ss == gfc_ss_terminator);
11416 
11417       if (l_is_temp)
11418 	{
11419 	  gfc_trans_scalarized_loop_boundary (&loop, &body);
11420 
11421 	  /* We need to copy the temporary to the actual lhs.  */
11422 	  gfc_init_se (&lse, NULL);
11423 	  gfc_init_se (&rse, NULL);
11424 	  gfc_copy_loopinfo_to_se (&lse, &loop);
11425 	  gfc_copy_loopinfo_to_se (&rse, &loop);
11426 
11427 	  rse.ss = loop.temp_ss;
11428 	  lse.ss = lss;
11429 
11430 	  gfc_conv_tmp_array_ref (&rse);
11431 	  gfc_conv_expr (&lse, expr1);
11432 
11433 	  gcc_assert (lse.ss == gfc_ss_terminator
11434 		      && rse.ss == gfc_ss_terminator);
11435 
11436 	  if (expr2->ts.type == BT_CHARACTER)
11437 	    rse.string_length = string_length;
11438 
11439 	  tmp = gfc_trans_scalar_assign (&lse, &rse, expr1->ts,
11440 					 false, dealloc);
11441 	  gfc_add_expr_to_block (&body, tmp);
11442 	}
11443 
11444       /* F2003: Allocate or reallocate lhs of allocatable array.  */
11445       if (realloc_flag)
11446 	{
11447 	  realloc_lhs_warning (expr1->ts.type, true, &expr1->where);
11448 	  ompws_flags &= ~OMPWS_SCALARIZER_WS;
11449 	  tmp = gfc_alloc_allocatable_for_assignment (&loop, expr1, expr2);
11450 	  if (tmp != NULL_TREE)
11451 	    gfc_add_expr_to_block (&loop.code[expr1->rank - 1], tmp);
11452 	}
11453 
11454       if (maybe_workshare)
11455 	ompws_flags &= ~OMPWS_SCALARIZER_BODY;
11456 
11457       /* Generate the copying loops.  */
11458       gfc_trans_scalarizing_loops (&loop, &body);
11459 
11460       /* Wrap the whole thing up.  */
11461       gfc_add_block_to_block (&block, &loop.pre);
11462       gfc_add_block_to_block (&block, &loop.post);
11463 
11464       gfc_cleanup_loop (&loop);
11465     }
11466 
11467   return gfc_finish_block (&block);
11468 }
11469 
11470 
11471 /* Check whether EXPR is a copyable array.  */
11472 
11473 static bool
11474 copyable_array_p (gfc_expr * expr)
11475 {
11476   if (expr->expr_type != EXPR_VARIABLE)
11477     return false;
11478 
11479   /* First check it's an array.  */
11480   if (expr->rank < 1 || !expr->ref || expr->ref->next)
11481     return false;
11482 
11483   if (!gfc_full_array_ref_p (expr->ref, NULL))
11484     return false;
11485 
11486   /* Next check that it's of a simple enough type.  */
11487   switch (expr->ts.type)
11488     {
11489     case BT_INTEGER:
11490     case BT_REAL:
11491     case BT_COMPLEX:
11492     case BT_LOGICAL:
11493       return true;
11494 
11495     case BT_CHARACTER:
11496       return false;
11497 
11498     case_bt_struct:
11499       return !expr->ts.u.derived->attr.alloc_comp;
11500 
11501     default:
11502       break;
11503     }
11504 
11505   return false;
11506 }
11507 
11508 /* Translate an assignment.  */
11509 
11510 tree
11511 gfc_trans_assignment (gfc_expr * expr1, gfc_expr * expr2, bool init_flag,
11512 		      bool dealloc, bool use_vptr_copy, bool may_alias)
11513 {
11514   tree tmp;
11515 
11516   /* Special case a single function returning an array.  */
11517   if (expr2->expr_type == EXPR_FUNCTION && expr2->rank > 0)
11518     {
11519       tmp = gfc_trans_arrayfunc_assign (expr1, expr2);
11520       if (tmp)
11521 	return tmp;
11522     }
11523 
11524   /* Special case assigning an array to zero.  */
11525   if (copyable_array_p (expr1)
11526       && is_zero_initializer_p (expr2))
11527     {
11528       tmp = gfc_trans_zero_assign (expr1);
11529       if (tmp)
11530         return tmp;
11531     }
11532 
11533   /* Special case copying one array to another.  */
11534   if (copyable_array_p (expr1)
11535       && copyable_array_p (expr2)
11536       && gfc_compare_types (&expr1->ts, &expr2->ts)
11537       && !gfc_check_dependency (expr1, expr2, 0))
11538     {
11539       tmp = gfc_trans_array_copy (expr1, expr2);
11540       if (tmp)
11541         return tmp;
11542     }
11543 
11544   /* Special case initializing an array from a constant array constructor.  */
11545   if (copyable_array_p (expr1)
11546       && expr2->expr_type == EXPR_ARRAY
11547       && gfc_compare_types (&expr1->ts, &expr2->ts))
11548     {
11549       tmp = gfc_trans_array_constructor_copy (expr1, expr2);
11550       if (tmp)
11551 	return tmp;
11552     }
11553 
11554   if (UNLIMITED_POLY (expr1) && expr1->rank)
11555     use_vptr_copy = true;
11556 
11557   /* Fallback to the scalarizer to generate explicit loops.  */
11558   return gfc_trans_assignment_1 (expr1, expr2, init_flag, dealloc,
11559 				 use_vptr_copy, may_alias);
11560 }
11561 
11562 tree
11563 gfc_trans_init_assign (gfc_code * code)
11564 {
11565   return gfc_trans_assignment (code->expr1, code->expr2, true, false, true);
11566 }
11567 
11568 tree
11569 gfc_trans_assign (gfc_code * code)
11570 {
11571   return gfc_trans_assignment (code->expr1, code->expr2, false, true);
11572 }
11573